KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > loader > ClassLoaderUtils


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * @(#) ClassLoaderUtils.java
26  *
27  * Copyright 2001-2002 by iPlanet/Sun Microsystems, Inc.,
28  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
29  * All rights reserved.
30  *
31  * This software is the confidential and proprietary information
32  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
33  * You shall not disclose such Confidential Information and shall
34  * use it only in accordance with the terms of the license
35  * agreement you entered into with iPlanet/Sun Microsystems.
36  */

37 package com.sun.enterprise.loader;
38
39 import java.io.File JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.ArrayList JavaDoc;
42 import java.net.URL JavaDoc;
43 import java.net.URLClassLoader JavaDoc;
44 import java.util.StringTokenizer JavaDoc;
45
46 import com.sun.enterprise.util.io.FileUtils;
47
48 import java.io.IOException JavaDoc;
49
50 import java.util.logging.Level JavaDoc;
51 import java.util.logging.Logger JavaDoc;
52 import com.sun.logging.LogDomains;
53
54
55 /**
56  * Contains utility methods to create class loaders.
57  *
58  * @author Nazrul Islam
59  * @since JDK1.4
60  */

61 public class ClassLoaderUtils {
62
63     /** logger for this class */
64     private static Logger JavaDoc _logger =
65         LogDomains.getLogger(LogDomains.LOADER_LOGGER);
66
67     /**
68      * Returns a new class loader based on the given directory paths and
69      * the jar files & zip files found under jar directory.
70      *
71      * @param dirs array of directory path names
72      * @param jarDirs array of path name to directories that contains
73      * JAR & ZIP files.
74      * @param parent parent class loader for the new class loader
75      *
76      * @return a new class loader based on the urls from the given params
77      *
78      * @throws IOException if an i/o error while constructing the urls
79      */

80     public static ClassLoader JavaDoc getClassLoader(File JavaDoc[] dirs, File JavaDoc[] jarDirs,
81             ClassLoader JavaDoc parent) throws IOException JavaDoc {
82
83         URLClassLoader JavaDoc loader = null;
84         URL JavaDoc[] urls = getUrls(dirs, jarDirs);
85
86         if (urls != null) {
87             if (parent != null) {
88                 loader = new URLClassLoader JavaDoc(urls, parent);
89             } else {
90                 loader = new URLClassLoader JavaDoc(urls);
91             }
92         }
93
94         return loader;
95     }
96
97     /**
98      * Returns an array of urls that contains ..
99      * <pre>
100      * i. all the valid directories from the given directory (dirs) array
101      * ii. all jar files from the given directory (jarDirs) array
102      * iii. all zip files from the given directory (jarDirs) array
103      * </pre>
104      *
105      * @param dirs array of directory path names
106      * @param jarDirs array of path name to directories that contains
107      * JAR & ZIP files.
108      * @return an array of urls that contains all the valid dirs,
109      * *.jar & *.zip
110      *
111      * @throws IOException if an i/o error while constructing the urls
112      */

113     public static URL JavaDoc[] getUrls(File JavaDoc[] dirs, File JavaDoc[] jarDirs)
114             throws IOException JavaDoc {
115
116         URL JavaDoc[] urls = null;
117         List JavaDoc list = new ArrayList JavaDoc();
118
119         // adds all directories
120
if (dirs != null) {
121             for (int i=0; i<dirs.length; i++) {
122                 File JavaDoc dir = dirs[i];
123                 if (dir.isDirectory() || dir.canRead()) {
124                     URL JavaDoc url = dir.toURI().toURL();
125                     list.add(url);
126
127                     if (_logger.isLoggable(Level.FINE)) {
128                         _logger.log(Level.FINE,
129                             "Adding directory to class path:" + url.toString());
130                     }
131                 }
132             }
133         }
134
135         // adds all the jars
136
if (jarDirs != null) {
137             for (int i=0; i<jarDirs.length; i++) {
138                 File JavaDoc jarDir = jarDirs[i];
139
140                 if (jarDir.isDirectory() || jarDir.canRead()) {
141                     File JavaDoc[] files = jarDir.listFiles();
142
143                     for (int j=0; j<files.length; j++) {
144                         File JavaDoc jar = files[j];
145
146                         if ( FileUtils.isJar(jar) || FileUtils.isZip(jar) ) {
147                             list.add(jar.toURI().toURL());
148
149                             if (_logger.isLoggable(Level.FINE)) {
150                                 _logger.log(Level.FINE,
151                                     "Adding jar to class path:" + jar.toURL());
152                             }
153                         }
154                     }
155                 }
156             }
157         }
158
159         // converts the list to an array
160
if (list.size() > 0) {
161             urls = new URL JavaDoc[list.size()];
162             urls = (URL JavaDoc[]) list.toArray(urls);
163         }
164
165         return urls;
166     }
167
168     /**
169      * Returns a list of urls that contains ..
170      * <pre>
171      * i. all the valid directories from the given directory (dirs) array
172      * ii. all jar files from the given directory (jarDirs) array
173      * iii. all zip files from the given directory (jarDirs) array
174      * </pre>
175      *
176      * This is similar to getUrls(File[], File[])
177      *
178      * @param dirs array of directory path names
179      * @param jarDirs array of path name to directories that contains
180      * JAR & ZIP files.
181      * @return a list of urls that contains all the valid dirs,
182      * *.jar & *.zip; the obj representing the paths are
183      * of type java.lang.String. It returns an empty list
184      * if no valid dir, jar or zip present.
185      *
186      * @throws IOException if an i/o error while constructing the urls
187      *
188      * @see #getUrls(File[], File[]);
189      */

190     public static List JavaDoc getUrlList(File JavaDoc[] dirs, File JavaDoc[] jarDirs)
191         throws IOException JavaDoc {
192         return getUrlList(dirs, jarDirs, false);
193     }
194
195     /**
196      * Returns a list of urls that contains ..
197      * <pre>
198      * i. all the valid directories from the given directory (dirs)
199      * array
200      * ii. all jar files from the given directory (jarDirs) array
201      * iii. all zip files from the given directory (jarDirs) array if
202      * not ignoring zip file (ignoreZip is false).
203      *
204      * </pre>
205      *
206      * @param dirs array of directory path names
207      * @param jarDirs array of path name to directories that contains
208      * JAR & ZIP files.
209      * @return a list of urls that contains all the valid dirs,
210      * *.jar & *.zip if not ignoring zip file, the obj
211      * representing the paths are of type java.lang.String.
212      * It returns an empty list if no valid dir, jar or zip
213      * present.
214      *
215      * @throws IOException if an i/o error while constructing the urls
216      *
217      */

218     public static List JavaDoc getUrlList(File JavaDoc[] dirs, File JavaDoc[] jarDirs,
219         boolean ignoreZip) throws IOException JavaDoc {
220
221         List JavaDoc list = new ArrayList JavaDoc();
222
223         // adds all directories
224
if (dirs != null) {
225             for (int i=0; i<dirs.length; i++) {
226                 File JavaDoc dir = dirs[i];
227                 if (dir.isDirectory() || dir.canRead()) {
228                     list.add( dir.getCanonicalPath() );
229
230                     if (_logger.isLoggable(Level.FINE)) {
231                         _logger.log(Level.FINE,
232                             "Adding directory to class path:"
233                             + dir.getCanonicalPath());
234                     }
235                 }
236             }
237         }
238
239         // adds all the jars
240
if (jarDirs != null) {
241             for (int i=0; i<jarDirs.length; i++) {
242                 File JavaDoc jarDir = jarDirs[i];
243
244                 if (jarDir.isDirectory() || jarDir.canRead()) {
245                     File JavaDoc[] files = jarDir.listFiles();
246
247                     for (int j=0; j<files.length; j++) {
248                         File JavaDoc jar = files[j];
249
250                         if ( FileUtils.isJar(jar) ||
251                             (!ignoreZip && FileUtils.isZip(jar)) ) {
252                             list.add( jar.getCanonicalPath() );
253
254                             if (_logger.isLoggable(Level.FINE)) {
255                                 _logger.log(Level.FINE,
256                                     "Adding jar to class path:"
257                                     + jar.getCanonicalPath());
258                             }
259                         }
260                     }
261                 }
262             }
263         }
264
265         return list;
266     }
267
268     /**
269      * get URL[] from classpath
270      * catches exception for wrong files
271      */

272     public static URL JavaDoc[] getUrlsFromClasspath(String JavaDoc classpath) {
273
274         List JavaDoc urls = new ArrayList JavaDoc();
275         
276         if (classpath == null) return (URL JavaDoc[]) urls.toArray(); //return empty arr
277

278         // tokenize classpath
279
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(classpath, File.pathSeparator);
280         while (st.hasMoreTokens()) {
281             try {
282                 File JavaDoc f = new File JavaDoc(st.nextToken());
283                 urls.add(f.toURI().toURL());
284             } catch(Exception JavaDoc e) {
285                   _logger.log(Level.WARNING,
286                             "loader.unexpected_error_while_creating_urls",e);
287             }
288         }
289          
290         // converts the list to an array
291
URL JavaDoc[] ret;
292         if (urls.size() > 0) {
293             ret = new URL JavaDoc[urls.size()];
294             ret = (URL JavaDoc[]) urls.toArray(ret);
295         } else {
296             ret = new URL JavaDoc[0];
297         }
298
299         return ret;
300      }
301
302     /**
303      * Unit test code.
304      */

305     public static void main(String JavaDoc[] args) {
306
307         try {
308             URL JavaDoc[] urls = getUrls(new File JavaDoc[] {new File JavaDoc(args[0])},
309                      new File JavaDoc[] {new File JavaDoc(args[1])});
310             for (int i=0; i<urls.length; i++) {
311                 System.out.println(urls[i]);
312             }
313
314             URLClassLoader JavaDoc loader = (URLClassLoader JavaDoc)
315                     getClassLoader(new File JavaDoc[] {new File JavaDoc(args[0])},
316                         new File JavaDoc[] {new File JavaDoc(args[1])}, null);
317
318             //Class c = Class.forName(args[2], true, loader);
319
Class JavaDoc c = loader.loadClass(args[2]);
320             System.out.println("Loaded: " + c.getName());
321             System.out.println("Loaded class has the following methods...");
322             java.lang.reflect.Method JavaDoc[] m = c.getDeclaredMethods();
323             for (int i=0; i<m.length; i++) {
324                 System.out.println(m[i]);
325             }
326         } catch (Exception JavaDoc e) {
327             e.printStackTrace();
328         }
329     }
330 }
331
Popular Tags