1 package javax.jdo;
2
3 import org.apache.tools.ant.AntClassLoader;
4
5 import java.net.URL;
6 import java.net.URLClassLoader;
7 import java.net.MalformedURLException;
8 import java.util.StringTokenizer;
9 import java.util.List;
10 import java.util.ArrayList;
11 import java.util.Iterator;
12
13 /***
14 * A class loader used to ensure that classpath URLs added in JUnit tests
15 * aren't included in subsequent JUnit tests.
16 */
17 public class JDOConfigTestClassLoader extends URLClassLoader {
18
19 public JDOConfigTestClassLoader(
20 String partialPathToIgnore,
21 ClassLoader unparent
22 ) {
23 this(new String[]{partialPathToIgnore}, unparent);
24 }
25
26 public JDOConfigTestClassLoader(
27 String[] partialPathsToIgnore,
28 ClassLoader unparent
29 ) {
30 super(new URL[]{}, null);
31
32 if (unparent instanceof URLClassLoader) {
33 addNonTestURLs(
34 partialPathsToIgnore == null
35 ? new String[]{}
36 : partialPathsToIgnore,
37 (URLClassLoader) unparent);
38 }
39 else if (unparent instanceof AntClassLoader) {
40 addNonTestURLs(
41 partialPathsToIgnore == null
42 ? new String[]{}
43 : partialPathsToIgnore,
44 (AntClassLoader) unparent);
45 }
46 else {
47 throw new RuntimeException(
48 "unknown ClassLoader type: "
49 + unparent.getClass().getName());
50 }
51 }
52
53
54 protected void addNonTestURLs(
55 String[] partialPathsToIgnore,
56 URLClassLoader unparent
57 ) {
58 URL[] urls = unparent.getURLs();
59 for (int i = 0; i < urls.length; i++) {
60 URL url = urls[i];
61 String urlString = url.toString();
62 for (int j = 0; j < partialPathsToIgnore.length; j++) {
63 if (urlString.indexOf(partialPathsToIgnore[j]) == -1) {
64 addURL(url);
65 }
66 }
67 }
68 }
69
70 protected void addNonTestURLs(
71 String[] partialPathsToIgnore,
72 AntClassLoader unparent
73 ) {
74 List elements = new ArrayList();
75 String classpath = unparent.getClasspath();
76 StringTokenizer st = new StringTokenizer(
77 classpath, System.getProperty("path.separator"));
78 while (st.hasMoreTokens()) {
79 elements.add("file://" + st.nextToken());
80 }
81 Iterator i = elements.iterator();
82 while (i.hasNext()) {
83 String element = (String) i.next();
84 for (int j = 0; j < partialPathsToIgnore.length; j++) {
85 if (element.indexOf(partialPathsToIgnore[j]) == -1) {
86 try {
87 addURL(new URL(element));
88 }
89 catch (MalformedURLException e) {
90 throw new RuntimeException(e);
91 }
92 }
93 }
94 }
95 }
96 }