Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/JPypeClassLoader.java

raw symbols SCIP
1 package org.jpype;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.UnsupportedEncodingException;
9 import java.net.MalformedURLException;
10 import java.net.URI;
11 import java.net.URISyntaxException;
12 import java.net.URL;
13 import java.net.URLClassLoader;
14 import java.net.URLConnection;
15 import java.nio.file.FileSystems;
16 import java.nio.file.FileVisitResult;
17 import java.nio.file.Files;
18 import java.nio.file.Path;
19 import java.nio.file.PathMatcher;
20 import java.nio.file.Paths;
21 import java.nio.file.SimpleFileVisitor;
22 import java.nio.file.attribute.BasicFileAttributes;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Enumeration;
26 import java.util.HashMap;
27 import java.util.Set;
28 import java.util.jar.JarEntry;
29 import java.util.jar.JarFile;
30 import java.net.URLDecoder;
31
32 /**
33 * Class loader for JPype.
34 *
35 * This is augmented to manage directory resources, allow for late loading, and
36 * handling of resources on non-ASCII paths.
37 */
38 public class JPypeClassLoader extends URLClassLoader
39 {
40
41 HashMap<String, ArrayList<URL>> map = new HashMap<>();
42 int code = 0;
43
44 public JPypeClassLoader(ClassLoader parent)
45 {
46 super(initial(), parent);
47 }
48
49 /**
50 * Used to keep the cache up to date.
51 *
52 * @return
53 */
54 public int getCode()
55 {
56 return code;
57 }
58
59 /**
60 * Special routine for handling non-ascii paths.
61 *
62 * If we are loaded as the system ClassLoader, then we will use
63 * "jpype.class.path" rather than "java.class.path" during the load process.
64 * We will move it into the expected place after so no one is the wiser.
65 *
66 * @return
67 */
68 private static URL[] initial()
69 {
70 // Check to see if we have a late loaded path
71 String cp = System.getProperty("jpype.class.path");
72 if (cp == null)
73 return new URL[0];
74
75 try
76 {
77 cp = URLDecoder.decode(cp, "UTF-8");
78 } catch (UnsupportedEncodingException ex)
79 {
80 // ignored
81 }
82
83 ArrayList<URL> path = new ArrayList<>();
84 int last = 0;
85 int next = 0;
86
87 while (next != -1)
88 {
89 // Find the parts
90 next = cp.indexOf(File.pathSeparator, last);
91 String element = (next == -1) ? cp.substring(last) : cp.substring(last, next);
92 if (!element.isEmpty())
93 {
94 try
95 {
96 URL url = Paths.get(element).toUri().toURL();
97 if (url != null)
98 path.add(url);
99 } catch (MalformedURLException ex)
100 {
101 System.err.println("Malformed url in classpath skipped " + element);
102 }
103 }
104 last = next + 1;
105 }
106
107 // Replace the path
108 System.clearProperty("jpype.class.path");
109 System.setProperty("java.class.path", cp);
110 return path.toArray(new URL[0]);
111 }
112
113 // This is required to add a Java agent even if it is already in the path
114 @SuppressWarnings("unused")
115 private void appendToClassPathForInstrumentation(String path) throws Throwable
116 {
117 addURL(Paths.get(path).toAbsolutePath().toUri().toURL());
118 }
119
120 /**
121 * Add a set of jars to the classpath.
122 *
123 * @param root
124 * @param glob
125 * @throws IOException
126 */
127 public void addPaths(Path root, String glob) throws IOException
128 {
129 final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
130
131 Files.walkFileTree(root, new SimpleFileVisitor<Path>()
132 {
133
134 @Override
135 public FileVisitResult visitFile(Path path,
136 BasicFileAttributes attrs) throws IOException
137 {
138 if (pathMatcher.matches(root.relativize(path)))
139 {
140 URL url = path.toUri().toURL();
141 addURL(url);
142 }
143 return FileVisitResult.CONTINUE;
144 }
145
146 @Override
147 public FileVisitResult visitFileFailed(Path file, IOException exc)
148 throws IOException
149 {
150 return FileVisitResult.CONTINUE;
151 }
152 });
153
154 }
155
156 /**
157 * Add a path to the loader after the JVM is started.
158 *
159 * @param path
160 * @throws FileNotFoundException
161 */
162 public void addPath(Path path) throws FileNotFoundException
163 {
164 try
165 {
166 if (!Files.exists(path))
167 throw new FileNotFoundException(path.toString());
168 this.addURL(path.toUri().toURL());
169 } catch (MalformedURLException ex)
170 {
171 // This should never happen
172 throw new RuntimeException(ex);
173 }
174 }
175
176 /**
177 * Loads a class from the class loader.
178 *
179 * @param name is the name of the class with java class notation (using dots).
180 * @return the class
181 * @throws ClassNotFoundException was not found by the class loader.
182 * @throws ClassFormatError if the class byte code was invalid.
183 */
184 @Override
185 public Class findClass(String name) throws ClassNotFoundException, ClassFormatError
186 {
187 String aname = name.replace('.', '/') + ".class";
188 URL url = this.getResource(aname);
189 if (url == null)
190 throw new ClassNotFoundException(name);
191
192 try
193 {
194 URLConnection connection = url.openConnection();
195 try (InputStream is = connection.getInputStream())
196 {
197 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
198 int bytes;
199 byte[] d = new byte[1024];
200 while ((bytes = is.read(d, 0, d.length)) != -1)
201 {
202 buffer.write(d, 0, bytes);
203 }
204
205 buffer.flush();
206 byte[] data = buffer.toByteArray();
207 return defineClass(null, data, 0, data.length);
208 }
209 } catch (IOException ex)
210 {
211 }
212 throw new ClassNotFoundException(name);
213 }
214
215 @Override
216 public URL findResource(String name)
217 {
218 // Check local first
219 URL url = super.findResource(name);
220 if (url != null)
221 return url;
222
223 // Both with and without / should generate the same result
224 if (name.endsWith("/"))
225 name = name.substring(0, name.length() - 1);
226 if (map.containsKey(name))
227 return map.get(name).get(0);
228
229 // We have some resource which must be sourced to a particular class loader
230 if (name.startsWith("org/jpype/"))
231 return getResource("META-INF/versions/0/" + name);
232 return null;
233 }
234
235 @Override
236 public Enumeration<URL> findResources(String name) throws IOException
237 {
238 ArrayList<URL> out = new ArrayList<>();
239 out.addAll(Collections.list(super.findResources(name)));
240 // Both with and without / should generate the same result
241 if (name.endsWith("/"))
242 name = name.substring(0, name.length() - 1);
243 if (map.containsKey(name))
244 out.addAll(map.get(name));
245 return Collections.enumeration(out);
246 }
247
248 /**
249 * Add a resource to the search.
250 *
251 * Many jar files lack directory support which is needed for the packaging
252 * import.
253 *
254 * @param name
255 * @param url
256 */
257 public void addResource(String name, URL url)
258 {
259 if (!this.map.containsKey(name))
260 this.map.put(name, new ArrayList<>());
261 this.map.get(name).add(url);
262 }
263
264 @Override
265 public void addURL(URL url)
266 {
267 // Mark our cache as dirty
268 code = code * 98745623 + url.hashCode();
269
270 // add to the search tree
271 super.addURL(url);
272
273 // See if it is a path
274 Path path;
275 try
276 {
277 path = Paths.get(url.toURI());
278 } catch (URISyntaxException ex)
279 {
280 return;
281 }
282
283 // Scan for missing resources
284 scanJar(path);
285 }
286
287 /**
288 * Recreate missing directory entries for Jars that lack indexing.
289 *
290 * Some jar files are missing the directory entries that prevents use from
291 * properly importing their contents. This procedure scans a jar file when
292 * loaded to build missing directories.
293 *
294 * @param path
295 */
296 void scanJar(Path path)
297 {
298 if (!Files.exists(path))
299 return;
300 if (Files.isDirectory(path))
301 return;
302
303 try (JarFile jf = new JarFile(path.toFile()))
304 {
305 Enumeration<JarEntry> entries = jf.entries();
306 URI abs = path.toAbsolutePath().toUri();
307 Set urls = new java.util.HashSet();
308 while (entries.hasMoreElements())
309 {
310 JarEntry next = entries.nextElement();
311 String name = next.getName();
312
313 // Skip over META-INF
314 if (name.startsWith("META-INF/"))
315 continue;
316
317 if (next.isDirectory())
318 {
319 // If we find a directory entry then the jar has directories already
320 return;
321 }
322
323 // Split on each separator in the name
324 int i = 0;
325 while (true)
326 {
327 i = name.indexOf("/", i);
328 if (i == -1)
329 break;
330 String name2 = name.substring(0, i);
331
332 i++;
333
334 // Already have an entry no problem
335 if (urls.contains(name2))
336 continue;
337
338 // Add a new entry for the missing directory
339 String jar = "jar:" + abs + "!/" + name2 + "/";
340 urls.add(name2);
341 this.addResource(name2, new URL(jar));
342 }
343 }
344 } catch (IOException ex)
345 {
346 // Anything goes wrong skip it
347 }
348 }
349
350 }