1 /***
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.xbean.classpath;
18
19 import java.io.File;
20 import java.net.URL;
21 import java.net.URLClassLoader;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24
25 public abstract class SunURLClassPath implements ClassPath {
26 public static ClassLoader getContextClassLoader() {
27 return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
28 public Object run() {
29 return Thread.currentThread().getContextClassLoader();
30 }
31 });
32 }
33
34 private java.lang.reflect.Field ucpField;
35
36 protected void addJarToPath(final URL jar, final URLClassLoader loader) throws Exception {
37 this.getURLClassPath(loader).addURL(jar);
38 }
39
40 protected void addJarsToPath(final File dir, final URLClassLoader loader) throws Exception {
41 if (dir == null || !dir.exists()) return;
42
43
44 String[] jarNames = dir.list(new java.io.FilenameFilter() {
45 public boolean accept(File dir, String name) {
46
47 return (name.endsWith(".jar") || name.endsWith(".zip"));
48 }
49 });
50
51
52 final URL[] jars = new URL[jarNames.length];
53 for (int j = 0; j < jarNames.length; j++) {
54 jars[j] = new File(dir, jarNames[j]).toURL();
55 }
56
57 sun.misc.URLClassPath path = getURLClassPath(loader);
58 for (int i = 0; i < jars.length; i++) {
59
60 path.addURL(jars[i]);
61 }
62 }
63
64 protected sun.misc.URLClassPath getURLClassPath(URLClassLoader loader) throws Exception {
65 return (sun.misc.URLClassPath) getUcpField().get(loader);
66 }
67
68 private java.lang.reflect.Field getUcpField() throws Exception {
69 if (ucpField == null) {
70
71 ucpField = (java.lang.reflect.Field) AccessController.doPrivileged(new PrivilegedAction() {
72 public Object run() {
73 java.lang.reflect.Field ucp = null;
74 try {
75 ucp = URLClassLoader.class.getDeclaredField("ucp");
76 ucp.setAccessible(true);
77 } catch (Exception e2) {
78 e2.printStackTrace();
79 }
80 return ucp;
81 }
82 });
83 }
84
85 return ucpField;
86 }
87
88 }