KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ws > jaxme > impl > JAXBContextImpl


1 /*
2  * Copyright 2003, 2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15
16  */

17 package org.apache.ws.jaxme.impl;
18
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25
26 import javax.xml.bind.DatatypeConverter;
27 import javax.xml.bind.JAXBContext;
28 import javax.xml.bind.JAXBException;
29 import javax.xml.bind.MarshalException;
30 import javax.xml.bind.Marshaller;
31 import javax.xml.bind.UnmarshalException;
32 import javax.xml.bind.Unmarshaller;
33 import javax.xml.bind.ValidationException;
34 import javax.xml.bind.Validator;
35 import javax.xml.namespace.QName JavaDoc;
36 import javax.xml.parsers.ParserConfigurationException JavaDoc;
37 import javax.xml.parsers.SAXParser JavaDoc;
38 import javax.xml.parsers.SAXParserFactory JavaDoc;
39
40 import org.apache.ws.jaxme.JMManager;
41 import org.apache.ws.jaxme.JMMarshaller;
42 import org.apache.ws.jaxme.JMUnmarshaller;
43 import org.apache.ws.jaxme.JMValidator;
44 import org.apache.ws.jaxme.PM;
45 import org.apache.ws.jaxme.PMException;
46 import org.apache.ws.jaxme.util.Configurator;
47 import org.xml.sax.Attributes JavaDoc;
48 import org.xml.sax.InputSource JavaDoc;
49 import org.xml.sax.SAXException JavaDoc;
50 import org.xml.sax.SAXParseException JavaDoc;
51 import org.xml.sax.XMLReader JavaDoc;
52
53
54 /** <p>JaxMe's implementation of a JAXBContext.</p>
55  *
56  * @author <a HREF="mailto:joe@ispsoft.de">Jochen Wiedmann</a>
57  * @version $Id: JAXBContextImpl.java,v 1.9 2005/03/10 10:14:03 jochen Exp $
58  */

59 public class JAXBContextImpl extends JAXBContext {
60     /** The namespace of JaxMe's configuration files.
61      */

62     public static final String JavaDoc CONFIGURATION_URI = "http://ws.apache.org/jaxme/namespaces/jaxme2/configuration";
63     private static final SAXParserFactory JavaDoc spf;
64     private static final DatatypeConverterImpl datatypeConverter = new DatatypeConverterImpl();
65     private ClassLoader JavaDoc cl;
66     private String JavaDoc packageNames;
67     private Map JavaDoc managersByQName = new HashMap JavaDoc();
68     private Map JavaDoc managersByInterface = new HashMap JavaDoc();
69     private Class JavaDoc jmMarshallerClass;
70     private Class JavaDoc jmUnmarshallerClass;
71     private Class JavaDoc jmValidatorClass;
72
73     static {
74         spf = SAXParserFactory.newInstance();
75         spf.setValidating(false);
76         spf.setNamespaceAware(true);
77         DatatypeConverter.setDatatypeConverter(datatypeConverter);
78     }
79
80     protected JAXBContextImpl() {}
81
82     /** <p>Sets the ClassLoader to use.</p>
83      */

84     protected void setClassLoader(ClassLoader JavaDoc pClassLoader) {
85         cl = pClassLoader;
86     }
87
88     /** <p>Returns the ClassLoader to use.</p>
89      */

90     public ClassLoader JavaDoc getClassLoader() {
91         return cl;
92     }
93
94     /** <p>Sets the package names managed by this context.</p>
95      */

96     protected void setPackageNames(String JavaDoc pPackageNames) {
97         packageNames = pPackageNames;
98     }
99
100     /** <p>Returns the package names managed by this context.</p>
101      */

102     public String JavaDoc getPackageNames() {
103         return packageNames;
104     }
105
106     /** <p>Sets the JMMarshaller class to use.</p>
107      */

108     protected void setJMMarshallerClass(Class JavaDoc pClass) {
109         jmMarshallerClass = pClass;
110     }
111
112     /** <p>Returns the JMMarshaller class to use.</p>
113      */

114     public Class JavaDoc getJMMarshallerClass() {
115         return jmMarshallerClass;
116     }
117
118     /** <p>Sets the JMUnmarshaller class to use.</p>
119      */

120     protected void setJMUnmarshallerClass(Class JavaDoc pClass) {
121         jmUnmarshallerClass = pClass;
122     }
123
124     /** <p>Sets the JMUnmarshaller class to use.</p>
125      */

126     public Class JavaDoc getJMUnmarshallerClass() {
127         return jmUnmarshallerClass;
128     }
129
130     /** <p>Sets the JMValidator class to use.</p>
131      */

132     protected void setJMValidatorClass(Class JavaDoc pClass) {
133         jmValidatorClass = pClass;
134     }
135
136     /** <p>Returns the JMValidator class to use.</p>
137      */

138     public Class JavaDoc getJMValidatorClass() {
139         return jmValidatorClass;
140     }
141
142     public Marshaller createMarshaller() throws JAXBException {
143         Class JavaDoc c = getJMMarshallerClass();
144         try {
145             JMMarshaller marshaller = (JMMarshaller) c.newInstance();
146             marshaller.setJAXBContextImpl(this);
147             return marshaller;
148         } catch (InstantiationException JavaDoc e) {
149             throw new JAXBException("Failed to instantiate class " + c.getName(), e);
150         } catch (IllegalAccessException JavaDoc e) {
151             throw new JAXBException("Illegal access to class " + c.getName(), e);
152         } catch (ClassCastException JavaDoc e) {
153             throw new JAXBException("Class " + c.getName() +
154                     " is not implementing " +
155                     JMMarshaller.class.getName());
156         }
157     }
158
159     public Unmarshaller createUnmarshaller() throws JAXBException {
160         Class JavaDoc c = getJMUnmarshallerClass();
161         try {
162             JMUnmarshaller unmarshaller = (JMUnmarshaller) c.newInstance();
163             unmarshaller.setJAXBContextImpl(this);
164             return unmarshaller;
165         } catch (InstantiationException JavaDoc e) {
166             throw new JAXBException("Failed to instantiate class " + c.getName(), e);
167         } catch (IllegalAccessException JavaDoc e) {
168             throw new JAXBException("Illegal access to class " + c.getName(), e);
169         } catch (ClassCastException JavaDoc e) {
170             throw new JAXBException("Class " + c.getName() +
171                     " is not implementing " +
172                     JMUnmarshaller.class.getName());
173         }
174     }
175
176     public Validator createValidator() throws JAXBException {
177         Class JavaDoc c = getJMValidatorClass();
178         try {
179             JMValidator validator = (JMValidator) c.newInstance();
180             validator.setJAXBContextImpl(this);
181             return validator;
182         } catch (InstantiationException JavaDoc e) {
183             throw new JAXBException("Failed to instantiate class " + c.getName(), e);
184         } catch (IllegalAccessException JavaDoc e) {
185             throw new JAXBException("Illegal access to class " + c.getName(), e);
186         } catch (ClassCastException JavaDoc e) {
187             throw new JAXBException("Class " + c.getName() +
188                     " is not implementing " +
189                     JMValidator.class.getName());
190         }
191     }
192
193     protected JMManager getManagerByQName(QName JavaDoc pQName) {
194         return (JMManager) managersByQName.get(pQName);
195     }
196
197     protected JMManager getManagerByInterface(Class JavaDoc pElementInterface) {
198         return (JMManager) managersByInterface.get(pElementInterface);
199     }
200
201     /** Returns a Manager for the given QName.
202      *
203      * @throws JAXBException No Manager is registered for the
204      * given QName.
205      */

206     public JMManager getManager(QName JavaDoc pQName) throws JAXBException {
207         JMManager manager = getManagerByQName(pQName);
208         if (manager == null) {
209             throw new JAXBException("A Manager for " + pQName + " is not declared.");
210         }
211         return manager;
212     }
213
214     /** Returns a Manager for the given element interface.
215      * Same method than {@link #getManager(Class)}, except that it
216      * throws a {@link JAXBException}.
217      * @throws JAXBException No Manager is registered for the
218      * given QName.
219      * @see #getManagerS(Class)
220      */

221     public JMManager getManager(Class JavaDoc pElementInterface) throws JAXBException {
222         JMManager manager = getManagerByInterface(pElementInterface);
223         if (manager == null) {
224             throw new JAXBException("A Manager for " + pElementInterface.getName() +
225             " is not declared.");
226         }
227         return manager;
228     }
229
230     /** Returns a Manager for the given element interface.
231      * Same method than {@link #getManager(Class)}, except that it
232      * throws a {@link SAXException}.
233      * @throws SAXException No Manager is registered for the
234      * given QName.
235      * @see #getManager(Class)
236      */

237     public JMManager getManagerS(Class JavaDoc pElementInterface) throws SAXException JavaDoc {
238         JMManager manager = getManagerByInterface(pElementInterface);
239         if (manager == null) {
240             throw new SAXException JavaDoc("A Manager for " + pElementInterface.getName() +
241                                    " is not declared.");
242         }
243         return manager;
244     }
245
246   /** <p>Returns a new JMMarshaller.</p>
247    */

248   public JMMarshaller getJMMarshaller() throws MarshalException {
249     Class JavaDoc c = getJMMarshallerClass();
250     if (c == null) {
251       throw new MarshalException("A JMMarshaller class is not set.");
252     }
253     try {
254       return (JMMarshaller) c.newInstance();
255     } catch (Exception JavaDoc e) {
256       throw new MarshalException("Failed to instantiate JMMarshaller class " + c, e);
257     }
258   }
259
260   /** <p>Returns a new JMUnmarshaller.</p>
261    */

262   public JMUnmarshaller getJMUnmarshaller() throws UnmarshalException {
263     Class JavaDoc c = getJMUnmarshallerClass();
264     if (c == null) {
265       throw new UnmarshalException("A JMUnmarshaller class is not set.");
266     }
267     try {
268       return (JMUnmarshaller) c.newInstance();
269     } catch (Exception JavaDoc e) {
270       throw new UnmarshalException("Failed to instantiate JMUnmarshaller class " + c, e);
271     }
272   }
273
274   /** <p>Returns a new JMValidator.</p>
275    */

276   public JMValidator getJMValidator() throws ValidationException {
277     Class JavaDoc c = getJMValidatorClass();
278     if (c == null) {
279       throw new ValidationException("A JMValidator class is not set.");
280     }
281     try {
282       return (JMValidator) c.newInstance();
283     } catch (Exception JavaDoc e) {
284       throw new ValidationException("Failed to instantiate JMValidator class " + c, e);
285     }
286   }
287
288   /** <p>Returns a new instance of JMPM.</p>
289    */

290   public PM getJMPM(Class JavaDoc pElementInterface) throws PMException {
291     JMManager manager = getManagerByInterface(pElementInterface);
292     Class JavaDoc c = manager.getPmClass();
293     if (c == null) {
294       throw new PMException("No persistency class configured for " +
295                              pElementInterface.getName());
296     }
297     try {
298       PM pm = (PM) c.newInstance();
299       pm.init(manager);
300       return pm;
301     } catch (Exception JavaDoc e) {
302       e.printStackTrace(System.err);
303       throw new PMException("Could not instantiate persistence manager class " +
304                              c.getName(), e);
305     }
306   }
307
308   /** <p>Returns a new instance of JMPM.</p>
309    */

310   public PM getJMPM(QName JavaDoc pQName) throws PMException {
311     JMManager manager = getManagerByQName(pQName);
312     Class JavaDoc c = manager.getPmClass();
313     if (c == null) {
314       throw new PMException("No persistency class configured for " + pQName);
315     }
316     try {
317       PM pm = (PM) c.newInstance();
318       pm.init(manager);
319       return pm;
320     } catch (Exception JavaDoc e) {
321       throw new PMException("Could not instantiate persistence manager class " +
322                              c.getName(), e);
323     }
324   }
325
326   /** <p>Initializes the context by loading the configuration
327    * or the configurations from the given classpath.</p>
328    */

329   protected void init() throws JAXBException {
330     if (packageNames == null || packageNames.length() == 0) {
331       packageNames = JAXBContextImpl.class.getName();
332       packageNames = packageNames.substring(0, packageNames.lastIndexOf('.'));
333     }
334     boolean first = true;
335     for (StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(packageNames, ":");
336          st.hasMoreTokens(); ) {
337       String JavaDoc packageName = st.nextToken();
338       String JavaDoc configFileName =
339         ((packageName.length() > 0) ?
340           (packageName.replace('.', '/') + '/') : "") + "Configuration.xml";
341       URL JavaDoc url = getClassLoader().getResource(configFileName);
342       if (url != null) {
343         InputStream JavaDoc istream = null;
344         try {
345           Configuration c = new Configuration(this);
346           Configurator configurator = new Configurator();
347           configurator.setNamespace(CONFIGURATION_URI);
348           configurator.setRootObject(c);
349           SAXParser JavaDoc sp = spf.newSAXParser();
350           XMLReader JavaDoc xr = sp.getXMLReader();
351           xr.setContentHandler(configurator);
352           istream = url.openStream();
353           InputSource JavaDoc isource = new InputSource JavaDoc(istream);
354           isource.setSystemId(url.toString());
355           xr.parse(isource);
356           istream.close();
357           istream = null;
358
359           if (first) {
360             first = false;
361             setJMMarshallerClass(c.getJMMarshallerClass());
362             setJMUnmarshallerClass(c.getJMUnmarshallerClass());
363             setJMValidatorClass(c.getJMValidatorClass());
364           }
365         } catch (IOException JavaDoc e) {
366           throw new JAXBException("Failed to load config file " + url, e);
367         } catch (SAXParseException JavaDoc e) {
368           Exception JavaDoc f = e.getException() == null ? e : e.getException();
369           throw new JAXBException("Failed to parse config file " + url +
370                                    " at line " + e.getLineNumber() +
371                                    ", column " + e.getColumnNumber() +
372                                    ": " + f.getMessage(), f);
373         } catch (SAXException JavaDoc e) {
374           Exception JavaDoc f = e.getException() == null ? e : e.getException();
375           String JavaDoc msg = "Failed to parse config file " + url +": " + f.getMessage();
376           throw new JAXBException(msg, f);
377         } catch (ParserConfigurationException JavaDoc e) {
378           throw new JAXBException("Failed to create a SAX Parser: " + e.getMessage(), e);
379         } finally {
380           if (istream != null) { try { istream.close(); } catch (Throwable JavaDoc ignore) {} }
381         }
382       }
383     }
384     if (first) {
385       throw new JAXBException("Unable to locate configuration file Configuration.xml in " + packageNames);
386     }
387   }
388
389   /** Creates a new instance of {@link javax.xml.bind.JAXBContext}.
390    * Invoked implicitly by
391    * {@link javax.xml.bind.JAXBContext#newInstance(java.lang.String)}.
392    */

393   public static JAXBContextImpl createContext() throws JAXBException {
394     return createContext(null, JAXBContextImpl.class.getClassLoader());
395   }
396
397   /** Invoked from the SAX handler when loading the config file.
398    */

399   public Configuration createConfiguration(Attributes JavaDoc pAttributes) throws JAXBException {
400     String JavaDoc className = pAttributes.getValue("", "className");
401     if (className == null || className.length() == 0) {
402       return new Configuration(this);
403     } else {
404       try {
405         return (Configuration) cl.loadClass(className).newInstance();
406       } catch (Exception JavaDoc e) {
407         throw new JAXBException("Failed to instantiate Configuration class " + className, e);
408       }
409     }
410   }
411
412   private static boolean verbose = true;
413   private static void showException(Exception JavaDoc e) {
414     if (!verbose) { return; }
415     System.err.println("Exception catched in " + JAXBContextImpl.class.getName() +
416                        ".createContext().");
417     System.err.println("Set " + JAXBContextImpl.class.getName() +
418                        ".verbose = false to suppress this message.");
419     e.printStackTrace(System.err);
420   }
421
422   /** Creates a new instance of {@link javax.xml.bind.JAXBContext}.
423    * Invoked implicitly by
424    * {@link javax.xml.bind.JAXBContext#newInstance(String, ClassLoader)}
425    */

426   public static JAXBContextImpl createContext(String JavaDoc pPackageNames,
427                                               ClassLoader JavaDoc pClassLoader)
428       throws JAXBException {
429     try {
430        JAXBContextImpl result = new JAXBContextImpl();
431        result.setClassLoader(pClassLoader);
432        result.setPackageNames(pPackageNames);
433        result.init();
434        return result;
435     } catch (RuntimeException JavaDoc e) {
436       showException(e);
437       throw e;
438     } catch (JAXBException e) {
439       showException(e);
440       throw e;
441     }
442   }
443
444   /** Invoked from the SAX handler when reading the config file
445    * for adding another instance of JMManager.
446    */

447   public void addManager(JMManager pManager) throws JAXBException {
448     Class JavaDoc elementInterface = pManager.getElementInterface();
449     if (elementInterface == null) {
450       throw new JAXBException("The Manager must have its elementInterface set.");
451     }
452     if (managersByInterface.containsKey(elementInterface)) {
453       throw new JAXBException("A Manager for interface " +
454                                elementInterface.getName() +
455                                " is already set.");
456     }
457
458     if (pManager.getDriverClass() == null) {
459         throw new IllegalStateException JavaDoc("Missing driver class for " + pManager.getQName());
460     }
461     if (pManager.getHandlerClass() == null) {
462         throw new IllegalStateException JavaDoc("Missing driver class for " + pManager.getQName());
463     }
464     
465     QName JavaDoc qName = pManager.getQName();
466     if (qName != null && managersByQName.containsKey(qName)) {
467       throw new JAXBException("A Manager for document type " + qName +
468                                " is already set.");
469     }
470
471     managersByInterface.put(elementInterface, pManager);
472     if (qName != null) {
473       managersByQName.put(qName, pManager);
474     }
475   }
476 }
477
Popular Tags