1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.jdo.impl.enhancer.util;
19
20 import java.util.List;
21 import java.util.ArrayList;
22 import java.util.Enumeration;
23 import java.util.StringTokenizer;
24
25 import java.io.IOException;
26 import java.io.FileNotFoundException;
27 import java.io.PrintWriter;
28 import java.io.File;
29 import java.io.InputStream;
30
31 import java.net.URL;
32 import java.net.URLClassLoader;
33
34 /***
35 * Searches resources within a path.
36 */
37 public class PathResourceLocator
38 extends ResourceLocatorBase
39 implements ResourceLocator
40 {
41 /***
42 * The class loader for loading jdo resources.
43 */
44 final private URLClassLoader classLoader;
45
46 /***
47 * Returns a classloader initialized on the path provided to constructor.
48 */
49 public URLClassLoader getClassLoader() {
50 return classLoader;
51 }
52
53 /***
54 * Creates an instance.
55 */
56 public PathResourceLocator(PrintWriter out,
57 boolean verbose,
58 String path)
59 throws IOException
60 {
61 super(out, verbose);
62 affirm(path != null);
63
64
65 final List urls = new ArrayList();
66 for (Enumeration e = new StringTokenizer(path, File.pathSeparator);
67 e.hasMoreElements();) {
68 final String s = (String)e.nextElement();
69
70
71 final File file = new File(s).getCanonicalFile();
72 final URL url = file.toURL();
73 final String canonicalName = url.toString();
74 affirm(canonicalName != null);
75
76
77 if (!file.canRead()) {
78 final String msg
79 = getI18N("enhancer.cannot_read_resource",
80 file.toString());
81 throw new IOException(msg);
82 }
83
84
85 final String l = s.toLowerCase();
86 if (!(file.isDirectory()
87 || (file.isFile()
88 && (l.endsWith(".jar") || l.endsWith(".zip"))))) {
89 final String msg
90 = getI18N("enhancer.illegal_path_element",
91 file.toString());
92 throw new IOException(msg);
93 }
94
95 urls.add(url);
96 printMessage(getI18N("enhancer.using_path_element",
97 canonicalName));
98 }
99
100
101 final URL[] urlArray = (URL[])urls.toArray(new URL[urls.size()]);
102 classLoader = new URLClassLoader(urlArray, null);
103 affirm(classLoader != null);
104 }
105
106 /***
107 * Finds a resource with a given name.
108 */
109 public InputStream getInputStreamForResource(String resourceName)
110 {
111
112
113 affirm(resourceName != null);
114
115
116 final URL url = classLoader.findResource(resourceName);
117 if (url == null) {
118 printMessage(getI18N("enhancer.not_found_resource", resourceName));
119 return null;
120 }
121
122
123 final InputStream stream;
124 try {
125 stream = url.openStream();
126 } catch (IOException ex) {
127
128
129 final String msg
130 = getI18N("enhancer.io_error_while_reading_resource",
131 url.toString(), ex.getMessage());
132 throw new RuntimeException(msg);
133 }
134 affirm(stream != null);
135 printMessage(getI18N("enhancer.found_resource", resourceName));
136 return stream;
137 }
138 }