KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > xml > stream > FactoryFinder


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
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://jaxp.dev.java.net/CDDLv1.0.html.
9  * See the License for the specific language governing
10  * permissions and limitations under the License.
11  *
12  * When distributing Covered Code, include this CDDL
13  * HEADER in each file and include the License file at
14  * https://jaxp.dev.java.net/CDDLv1.0.html
15  * If applicable add the following below this CDDL HEADER
16  * with the fields enclosed by brackets "[]" replaced with
17  * your own identifying information: Portions Copyright
18  * [year] [name of copyright owner]
19  */

20
21 /*
22  * $Id: FactoryFinder.java,v 1.5.2.2 2007/01/23 06:25:57 joehw Exp $
23  * @(#)FactoryFinder.java 1.13 07/01/24
24  *
25  * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
26  */

27
28 package javax.xml.stream;
29
30 import java.io.InputStream JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.File JavaDoc;
33 import java.io.FileInputStream JavaDoc;
34
35 import java.util.Properties JavaDoc;
36 import java.io.BufferedReader JavaDoc;
37 import java.io.InputStreamReader JavaDoc;
38
39 /**
40  * <p>Implements pluggable Datatypes.</p>
41  *
42  * <p>This class is duplicated for each JAXP subpackage so keep it in
43  * sync. It is package private for secure class loading.</p>
44  *
45  * @author Santiago.PericasGeertsen@sun.com
46  */

47 class FactoryFinder {
48     
49     /**
50      * Internal debug flag.
51      */

52     private static boolean debug = false;
53     
54     /**
55      * Cache for properties in java.home/lib/jaxp.properties
56      */

57     static Properties JavaDoc cacheProps = new Properties JavaDoc();
58     
59     /**
60      * Flag indicating if properties from java.home/lib/jaxp.properties
61      * have been cached.
62      */

63     static boolean firstTime = true;
64     
65     /**
66      * Security support class use to check access control before
67      * getting certain system resources.
68      */

69     static SecuritySupport ss = new SecuritySupport();
70
71     // Define system property "jaxp.debug" to get output
72
static {
73         // Use try/catch block to support applets, which throws
74
// SecurityException out of this code.
75
try {
76             String JavaDoc val = ss.getSystemProperty("jaxp.debug");
77             // Allow simply setting the prop to turn on debug
78
debug = val != null && !"false".equals(val);
79         }
80         catch (SecurityException JavaDoc se) {
81             debug = false;
82         }
83     }
84     
85     private static void dPrint(String JavaDoc msg) {
86         if (debug) {
87             System.err.println("JAXP: " + msg);
88         }
89     }
90     
91     /**
92      * Attempt to load a class using the class loader supplied. If that fails
93      * and fall back is enabled, the current (i.e. bootstrap) class loader is
94      * tried.
95      *
96      * If the class loader supplied is <code>null</code>, first try using the
97      * context class loader followed by the current (i.e. bootstrap) class
98      * loader.
99      */

100     static private Class JavaDoc getProviderClass(String JavaDoc className, ClassLoader JavaDoc cl,
101             boolean doFallback) throws ClassNotFoundException JavaDoc
102     {
103         try {
104             if (cl == null) {
105                 cl = ss.getContextClassLoader();
106                 if (cl == null) {
107                     throw new ClassNotFoundException JavaDoc();
108                 }
109                 else {
110                     return cl.loadClass(className);
111                 }
112             }
113             else {
114                 return cl.loadClass(className);
115             }
116         }
117         catch (ClassNotFoundException JavaDoc e1) {
118             if (doFallback) {
119                 // Use current class loader - should always be bootstrap CL
120
return Class.forName(className, true, FactoryFinder.class.getClassLoader());
121             }
122             else {
123                 throw e1;
124             }
125         }
126     }
127     
128     /**
129      * Create an instance of a class. Delegates to method
130      * <code>getProviderClass()</code> in order to load the class.
131      *
132      * @param className Name of the concrete class corresponding to the
133      * service provider
134      *
135      * @param cl ClassLoader to use to load the class, null means to use
136      * the bootstrap ClassLoader
137      *
138      * @param doFallback True if the current ClassLoader should be tried as
139      * a fallback if the class is not found using cl
140      */

141     static Object JavaDoc newInstance(String JavaDoc className, ClassLoader JavaDoc cl, boolean doFallback)
142         throws ConfigurationError
143     {
144         try {
145             Class JavaDoc providerClass = getProviderClass(className, cl, doFallback);
146             Object JavaDoc instance = providerClass.newInstance();
147             if (debug) { // Extra check to avoid computing cl strings
148
dPrint("created new instance of " + providerClass +
149                        " using ClassLoader: " + cl);
150             }
151             return instance;
152         }
153         catch (ClassNotFoundException JavaDoc x) {
154             throw new ConfigurationError(
155                 "Provider " + className + " not found", x);
156         }
157         catch (Exception JavaDoc x) {
158             throw new ConfigurationError(
159                 "Provider " + className + " could not be instantiated: " + x,
160                 x);
161         }
162     }
163     
164     /**
165      * Finds the implementation Class object in the specified order. Main
166      * entry point.
167      * @return Class object of factory, never null
168      *
169      * @param factoryId Name of the factory to find, same as
170      * a property name
171      * @param fallbackClassName Implementation class name, if nothing else
172      * is found. Use null to mean no fallback.
173      *
174      * Package private so this code can be shared.
175      */

176     static Object JavaDoc find(String JavaDoc factoryId, String JavaDoc fallbackClassName)
177         throws ConfigurationError
178     {
179         dPrint("find factoryId =" + factoryId);
180         
181         // Use the system property first
182
try {
183             String JavaDoc systemProp = ss.getSystemProperty(factoryId);
184             if (systemProp != null) {
185                 dPrint("found system property, value=" + systemProp);
186                 return newInstance(systemProp, null, true);
187             }
188         }
189         catch (SecurityException JavaDoc se) {
190             if (debug) se.printStackTrace();
191         }
192
193         // Try read $java.home/lib/stax.properties followed by
194
// $java.home/lib/jaxp.properties if former not present
195
String JavaDoc configFile = null;
196         try {
197             String JavaDoc factoryClassName = null;
198             if (firstTime) {
199                 synchronized (cacheProps) {
200                     if (firstTime) {
201                         configFile = ss.getSystemProperty("java.home") + File.separator +
202                             "lib" + File.separator + "stax.properties";
203                         File JavaDoc f = new File JavaDoc(configFile);
204                         firstTime = false;
205                         if (ss.doesFileExist(f)) {
206                             dPrint("Read properties file "+f);
207                             cacheProps.load(ss.getFileInputStream(f));
208                         }
209                         else {
210                             configFile = ss.getSystemProperty("java.home") + File.separator +
211                                 "lib" + File.separator + "jaxp.properties";
212                             f = new File JavaDoc(configFile);
213                             if (ss.doesFileExist(f)) {
214                                 dPrint("Read properties file "+f);
215                                 cacheProps.load(ss.getFileInputStream(f));
216                             }
217                         }
218                     }
219                 }
220             }
221             factoryClassName = cacheProps.getProperty(factoryId);
222
223             if (factoryClassName != null) {
224                 dPrint("found in " + configFile + " value=" + factoryClassName);
225                 return newInstance(factoryClassName, null, true);
226             }
227         }
228         catch (Exception JavaDoc ex) {
229             if (debug) ex.printStackTrace();
230         }
231
232         // Try Jar Service Provider Mechanism
233
Object JavaDoc provider = findJarServiceProvider(factoryId);
234         if (provider != null) {
235             return provider;
236         }
237         if (fallbackClassName == null) {
238             throw new ConfigurationError(
239                 "Provider for " + factoryId + " cannot be found", null);
240         }
241
242         dPrint("loaded from fallback value: " + fallbackClassName);
243         return newInstance(fallbackClassName, null, true);
244     }
245     
246     /*
247      * Try to find provider using Jar Service Provider Mechanism
248      *
249      * @return instance of provider class if found or null
250      */

251     private static Object JavaDoc findJarServiceProvider(String JavaDoc factoryId)
252         throws ConfigurationError
253     {
254         String JavaDoc serviceId = "META-INF/services/" + factoryId;
255         InputStream JavaDoc is = null;
256         
257         // First try the Context ClassLoader
258
ClassLoader JavaDoc cl = ss.getContextClassLoader();
259         if (cl != null) {
260             is = ss.getResourceAsStream(cl, serviceId);
261             
262             // If no provider found then try the current ClassLoader
263
if (is == null) {
264                 cl = FactoryFinder.class.getClassLoader();
265                 is = ss.getResourceAsStream(cl, serviceId);
266             }
267         } else {
268             // No Context ClassLoader, try the current ClassLoader
269
cl = FactoryFinder.class.getClassLoader();
270             is = ss.getResourceAsStream(cl, serviceId);
271         }
272         
273         if (is == null) {
274             // No provider found
275
return null;
276         }
277         
278         if (debug) { // Extra check to avoid computing cl strings
279
dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
280         }
281         
282         BufferedReader JavaDoc rd;
283         try {
284             rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is, "UTF-8"));
285         }
286         catch (java.io.UnsupportedEncodingException JavaDoc e) {
287             rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
288         }
289         
290         String JavaDoc factoryClassName = null;
291         try {
292             // XXX Does not handle all possible input as specified by the
293
// Jar Service Provider specification
294
factoryClassName = rd.readLine();
295             rd.close();
296         } catch (IOException JavaDoc x) {
297             // No provider found
298
return null;
299         }
300         
301         if (factoryClassName != null && !"".equals(factoryClassName)) {
302             dPrint("found in resource, value=" + factoryClassName);
303             
304             // Note: here we do not want to fall back to the current
305
// ClassLoader because we want to avoid the case where the
306
// resource file was found using one ClassLoader and the
307
// provider class was instantiated using a different one.
308
return newInstance(factoryClassName, cl, false);
309         }
310         
311         // No provider found
312
return null;
313     }
314     
315     static class ConfigurationError extends Error JavaDoc {
316         private Exception JavaDoc exception;
317         
318         /**
319          * Construct a new instance with the specified detail string and
320          * exception.
321          */

322         ConfigurationError(String JavaDoc msg, Exception JavaDoc x) {
323             super(msg);
324             this.exception = x;
325         }
326         
327         Exception JavaDoc getException() {
328             return exception;
329         }
330     }
331     
332 }
333
Popular Tags