KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > util > SafeToolkit


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
42  *
43  * $Id: SafeToolkit.java 2082 2005-08-16 04:18:56Z dblevins $
44  */

45 package org.openejb.util;
46
47 import org.openejb.OpenEJBException;
48
49 import java.io.File JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.Properties JavaDoc;
52
53 public class SafeToolkit {
54
55     private String JavaDoc systemLocation;
56     public static final Messages messages = new Messages("org.openejb.util.resources");
57     public static final HashMap JavaDoc codebases = new HashMap JavaDoc();
58
59     /**
60      * Creates a new SafeToolkit dedicated to the specified system location.
61      */

62     protected SafeToolkit(String JavaDoc systemLocation) {
63         this.systemLocation = systemLocation;
64     }
65
66     /**
67      * Returns an instance of a SafeToolkit dedicated to the specified system location.
68      */

69     public static SafeToolkit getToolkit(String JavaDoc systemLocation) {
70         return new SafeToolkit(systemLocation);
71     }
72
73     /**
74      * Attempts to find and load the specified class.
75      *
76      * @param className the name of the class to be loaded.
77      * @return the specified class.
78      * @throws OpenEJBException if the class cannot be found.
79      */

80     public Class JavaDoc forName(String JavaDoc className) throws OpenEJBException {
81         Class JavaDoc clazz = null;
82         try {
83             clazz = Class.forName(className);
84         } catch (ClassNotFoundException JavaDoc cnfe) {
85             OpenEJBErrorHandler.classNotFound(systemLocation, className);
86         }
87         return clazz;
88     }
89
90     /**
91      * Attempts to find and load the specified class, using the
92      * specified codebase.
93      * If the codebase is null, the bootstrap classloader is used.
94      *
95      * @param className the name of the class to be loaded.
96      * @param codebase the codebase to load the class from.
97      * @return the specified class.
98      * @throws OpenEJBException if the class cannot be found.
99      */

100     public Class JavaDoc forName(String JavaDoc className, String JavaDoc codebase) throws OpenEJBException {
101         //ClassLoader cl = Class.class.getClassLoader();
102
ClassLoader JavaDoc cl = getContextClassLoader();
103
104         // If the codebase is present, then the classloader variable cl
105
// is replaced by a URLClassLoader that can load the class
106
// from a jar or url.
107
if (codebase != null) {
108             try {
109                 java.net.URL JavaDoc[] urlCodebase = new java.net.URL JavaDoc[1];
110                 urlCodebase[0] = new java.net.URL JavaDoc(codebase);
111                 cl = new java.net.URLClassLoader JavaDoc(urlCodebase, cl);
112             } catch (java.net.MalformedURLException JavaDoc mue) {
113                 OpenEJBErrorHandler.classCodebaseNotFound(systemLocation, className, codebase, mue);
114             } catch (SecurityException JavaDoc se) {
115                 OpenEJBErrorHandler.classCodebaseNotFound(systemLocation, className, codebase, se);
116             }
117         }
118
119         Class JavaDoc clazz = null;
120         try {
121             clazz = Class.forName(className, true, cl);
122         } catch (ClassNotFoundException JavaDoc cnfe) {
123             OpenEJBErrorHandler.classNotFound(systemLocation, className);
124         }
125         return clazz;
126     }
127
128     /**
129      * Attempts to find and load the specified class then instaniate it.
130      *
131      * @param className the name of the class to be instantiated.
132      * @return an instance of the specified class.
133      * @throws OpenEJBException if the class cannot be found or is not accessible .
134      */

135     public Object JavaDoc newInstance(String JavaDoc className) throws OpenEJBException {
136         return newInstance(forName(className));
137     }
138
139     /**
140      * Attempts to find and load the specified class then instaniate it.
141      *
142      * @param className the name of the class to be instantiated.
143      * @return an instance of the specified class.
144      * @throws OpenEJBException if the class cannot be found or is not accessible .
145      */

146     public Object JavaDoc newInstance(String JavaDoc className, String JavaDoc codebase) throws OpenEJBException {
147         return newInstance(forName(className, codebase));
148     }
149
150     /**
151      * Attempts to instaniate the specified class.
152      *
153      * @param clazz the name of the class to be instantiated.
154      * @return an instance of the specified class.
155      * @throws OpenEJBException if the class is not accessible .
156      */

157     public Object JavaDoc newInstance(Class JavaDoc clazz) throws OpenEJBException {
158         Object JavaDoc instance = null;
159         try {
160             instance = clazz.newInstance();
161         } catch (InstantiationException JavaDoc ie) {
162             OpenEJBErrorHandler.classNotIntantiateable(systemLocation, clazz.getName());
163         } catch (IllegalAccessException JavaDoc iae) {
164             OpenEJBErrorHandler.classNotAccessible(systemLocation, clazz.getName());
165         }
166                 // mjb - Exceptions thrown here can lead to some hard to find bugs, so I've added some rigorous error handling.
167
catch (Throwable JavaDoc exception) {
168             exception.printStackTrace();
169             ClassLoader JavaDoc classLoader = clazz.getClassLoader();
170             if (classLoader instanceof java.net.URLClassLoader JavaDoc) {
171                 OpenEJBErrorHandler.classNotIntantiateableFromCodebaseForUnknownReason(systemLocation, clazz.getName(), getCodebase((java.net.URLClassLoader JavaDoc) classLoader),
172                         exception.getClass().getName(), exception.getMessage());
173             } else {
174                 OpenEJBErrorHandler.classNotIntantiateableForUnknownReason(systemLocation, clazz.getName(), exception.getClass().getName(), exception.getMessage());
175             }
176         }
177         return instance;
178
179     }
180
181     /**
182      * Returns a new SafeProperties instance dedicated to this toolkit.
183      *
184      * @param props properties
185      * @return a new SafeProperties instance.
186      * @throws OpenEJBException the properties object passed in is null.
187      */

188     public SafeProperties getSafeProperties(Properties JavaDoc props) throws OpenEJBException {
189         return new SafeProperties(props, systemLocation);
190     }
191
192     /**
193      * Loads the class using the class loader for the specific
194      * codebase. If the codebase is null, the bootstrap classloader
195      * is used.
196      *
197      * @param className class name
198      * @param codebase
199      * @return class object
200      * @throws OpenEJBException
201      */

202     public static Class JavaDoc loadClass(String JavaDoc className, String JavaDoc codebase) throws OpenEJBException {
203         return loadClass(className, codebase, true);
204     }
205
206     public static Class JavaDoc loadClass(String JavaDoc className, String JavaDoc codebase, boolean cache) throws OpenEJBException {
207
208         ClassLoader JavaDoc cl = (cache) ? getCodebaseClassLoader(codebase) : getClassLoader(codebase);
209         Class JavaDoc clazz = null;
210         try {
211             clazz = cl.loadClass(className);
212         } catch (ClassNotFoundException JavaDoc cnfe) {
213             throw new OpenEJBException(messages.format("cl0007", className, codebase));
214         }
215         return clazz;
216     }
217
218     /**
219      * Ensures that a class loader for each code base used in the
220      * system is created at most one time. The default bootsrap
221      * classloader is used if codebase is null.
222      *
223      * @param codebase
224      * @return ClassLoader
225      * @throws OpenEJBException
226      */

227     public static ClassLoader JavaDoc getCodebaseClassLoader(String JavaDoc codebase) throws OpenEJBException {
228         if (codebase == null) codebase = "CLASSPATH";
229
230         ClassLoader JavaDoc cl = (ClassLoader JavaDoc) codebases.get(codebase);
231         if (cl == null) {
232             synchronized (codebases) {
233                 cl = (ClassLoader JavaDoc) codebases.get(codebase);
234                 if (cl == null) {
235                     try {
236                         java.net.URL JavaDoc[] urlCodebase = new java.net.URL JavaDoc[1];
237                         urlCodebase[0] = new java.net.URL JavaDoc("file", null, codebase);
238 // make sure everything works if we were not loaded by the system class loader
239
cl = new java.net.URLClassLoader JavaDoc(urlCodebase, SafeToolkit.class.getClassLoader());
240 //cl = SafeToolkit.class.getClassLoader();
241
codebases.put(codebase, cl);
242                     } catch (java.net.MalformedURLException JavaDoc mue) {
243                         throw new OpenEJBException(messages.format("cl0001", codebase, mue.getMessage()));
244                     } catch (SecurityException JavaDoc se) {
245                         throw new OpenEJBException(messages.format("cl0002", codebase, se.getMessage()));
246                     }
247                 }
248             }
249         }
250         return cl;
251     }
252
253     /**
254      * Ensures that a class loader for each code base used in the
255      * system is created at most one time. The default bootsrap
256      * classloader is used if codebase is null.
257      *
258      * @param codebase
259      * @return ClassLoader
260      * @throws OpenEJBException
261      */

262     public static ClassLoader JavaDoc getClassLoader(String JavaDoc codebase) throws OpenEJBException {
263         ClassLoader JavaDoc cl = null;
264         try {
265             java.net.URL JavaDoc[] urlCodebase = new java.net.URL JavaDoc[1];
266             urlCodebase[0] = new java.net.URL JavaDoc("file", null, codebase);
267             // make sure everything works if we were not loaded by the system class loader
268
cl = new java.net.URLClassLoader JavaDoc(urlCodebase, SafeToolkit.class.getClassLoader());
269         } catch (java.net.MalformedURLException JavaDoc mue) {
270             throw new OpenEJBException(messages.format("cl0001", codebase, mue.getMessage()));
271         } catch (SecurityException JavaDoc se) {
272             throw new OpenEJBException(messages.format("cl0002", codebase, se.getMessage()));
273         }
274         return cl;
275     }
276
277     /**
278      * Returns the search path used by the given URLClassLoader as a ';' delimited list of URLs.
279      */

280     private static String JavaDoc getCodebase(java.net.URLClassLoader JavaDoc urlClassLoader) {
281         StringBuffer JavaDoc codebase = new StringBuffer JavaDoc();
282         java.net.URL JavaDoc urlList[] = urlClassLoader.getURLs();
283         codebase.append(urlList[0].toString());
284         for (int i = 1; i < urlList.length; ++i) {
285             codebase.append(';');
286             codebase.append(urlList[i].toString());
287         }
288         return codebase.toString();
289     }
290
291     public static ClassLoader JavaDoc getContextClassLoader() {
292         return (ClassLoader JavaDoc) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction JavaDoc() {
293             public Object JavaDoc run() {
294                 return Thread.currentThread().getContextClassLoader();
295             }
296         });
297     }
298
299
300 }
Popular Tags