KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas_lib > genbase > utils > XMLUtils


1 /**
2  * JOnAS : Java(TM) OpenSource Application Server
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17  * USA
18  *
19  * Initial Developer : Guillaume Sauthier
20  * --------------------------------------------------------------------------
21  * $Id: XMLUtils.java,v 1.3 2005/07/18 23:47:08 mwringe Exp $
22  * --------------------------------------------------------------------------
23  */

24
25 package org.objectweb.jonas_lib.genbase.utils;
26
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29
30 import javax.xml.parsers.DocumentBuilder JavaDoc;
31 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
32 import javax.xml.parsers.ParserConfigurationException JavaDoc;
33
34 import org.w3c.dom.Attr JavaDoc;
35 import org.w3c.dom.Document JavaDoc;
36 import org.w3c.dom.Element JavaDoc;
37 import org.w3c.dom.NodeList JavaDoc;
38 import org.w3c.dom.Text JavaDoc;
39 import org.xml.sax.SAXException JavaDoc;
40
41 import org.objectweb.jonas_client.deployment.lib.JonasAppClientDTDs;
42 import org.objectweb.jonas_client.deployment.lib.JonasAppClientSchemas;
43
44 import org.objectweb.jonas_ear.deployment.lib.EarDTDs;
45 import org.objectweb.jonas_ear.deployment.lib.EarSchemas;
46
47 import org.objectweb.jonas_ejb.deployment.lib.JonasEjbjarDTDs;
48 import org.objectweb.jonas_ejb.deployment.lib.JonasEjbjarSchemas;
49
50 import org.objectweb.jonas_lib.deployment.digester.JEntityResolver;
51 import org.objectweb.jonas_lib.genbase.archive.Archive;
52
53 import org.objectweb.jonas_web.deployment.lib.JonasWebAppDTDs;
54 import org.objectweb.jonas_web.deployment.lib.JonasWebAppSchemas;
55 import org.objectweb.jonas_web.deployment.lib.WebAppDTDs;
56 import org.objectweb.jonas_web.deployment.lib.WebAppSchemas;
57
58 import org.objectweb.jonas_ws.deployment.lib.JonasWsSchemas;
59 import org.objectweb.jonas_ws.deployment.lib.WsSchemas;
60 import org.objectweb.jonas_ws.wsgen.NoJ2EEWebservicesException;
61
62 /**
63  * XML Utils Class. Holds methods for easier DOM parsing, XML modifications, ...
64  * @author Guillaume Sauthier
65  */

66 public class XMLUtils {
67
68     /** DOM factory */
69     private static DocumentBuilderFactory JavaDoc factory = null;
70
71     /**
72      * J2EE namespace
73      */

74     private static final String JavaDoc J2EE_NS = "http://java.sun.com/xml/ns/j2ee";
75
76     /**
77      * JONAS namespace
78      */

79     private static final String JavaDoc JONAS_NS = "http://www.objectweb.org/jonas/ns";
80
81     /**
82      * XML NS namespace
83      */

84     private static final String JavaDoc XMLNS_NS = "http://www.w3.org/2000/xmlns/";
85
86     /**
87      * XML Schema instance namespace
88      */

89     private static final String JavaDoc XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
90
91     /**
92      * jonas-session tag name
93      */

94     private static final String JavaDoc SESSION_BEAN = "jonas-session";
95
96     /**
97      * jonas-entity tag name
98      */

99     private static final String JavaDoc ENTITY_BEAN = "jonas-entity";
100
101     /**
102      * jonas-message-driven tag name
103      */

104     private static final String JavaDoc MESSAGE_BEAN = "jonas-message-driven";
105
106     /**
107      * ejb-name tag name
108      */

109     private static final String JavaDoc EJB_NAME = "ejb-name";
110
111     /**
112      * servlet tag name
113      */

114     private static final String JavaDoc SERVLET = "servlet";
115
116     /**
117      * servlet-name tag name
118      */

119     private static final String JavaDoc SERVLET_NAME = "servlet-name";
120
121     /**
122      * jonas-service-ref tag name
123      */

124     private static final String JavaDoc JONAS_SERVICE_REF = "jonas-service-ref";
125
126     /**
127      * service-ref-name tag name
128      */

129     private static final String JavaDoc SR_NAME = "service-ref-name";
130
131     /**
132      * Empty private constructor for Utility Class
133      */

134     private XMLUtils() {
135     }
136
137     /**
138      * Returns a new DocumentBuilderFactory.
139      * @param validating set the parser validating or not
140      * @return a new DocumentBuilderFactory.
141      */

142     private static DocumentBuilderFactory JavaDoc newFactory(boolean validating) {
143         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
144         factory.setNamespaceAware(true);
145         factory.setValidating(validating);
146         setFactoryValidation (factory, validating);
147
148         return factory;
149     }
150
151     /**
152      * Sets the validation for the factory
153      *
154      * @param factory the factory
155      * @param validating to turn on or off validation
156      */

157     private static void setFactoryValidation (DocumentBuilderFactory JavaDoc factory, boolean validating) {
158         factory.setValidating(validating);
159         // ignore white space can only be set if parser is validating
160
factory.setIgnoringElementContentWhitespace(validating);
161         factory.setAttribute("http://apache.org/xml/features/validation/schema", new Boolean JavaDoc(validating));
162     }
163
164
165     /**
166      * Creates a new Document from a given InputStream. Validate the file.
167      *
168      * @param is the InputStream to be parsed
169      * @param name filename
170      * @param isDTDsAllowed if false, throw exception on DTD Doctype
171      *
172      * @return the Document instance.
173      *
174      * @throws ParserConfigurationException ParserConfigurationException
175      * @throws SAXException SAXException
176      * @throws IOException IOException
177      * @throws NoJ2EEWebservicesException NoJ2EEWebservicesException
178      */

179     public static Document JavaDoc newDocument(InputStream JavaDoc is, String JavaDoc name, boolean isDTDsAllowed) throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc, NoJ2EEWebservicesException {
180
181         return newDocument (is, name, isDTDsAllowed, true);
182     }
183
184     /**
185      * Creates a new Document from a given InputStream.
186      *
187      * @param is the InputStream to be parsed
188      * @param name filename
189      * @param isDTDsAllowed if false, throw exception on DTD Doctype
190      * @param validate if the file is to be validated
191      *
192      * @return the Document instance.
193      *
194      * @throws ParserConfigurationException ParserConfigurationException
195      * @throws SAXException SAXException
196      * @throws IOException IOException
197      * @throws NoJ2EEWebservicesException NoJ2EEWebservicesException
198      */

199     public static Document JavaDoc newDocument(InputStream JavaDoc is, String JavaDoc name, boolean isDTDsAllowed, boolean validate)
200             throws NoJ2EEWebservicesException, ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
201
202         if (factory == null) {
203             factory = newFactory(validate);
204         }
205
206         if (factory.isValidating() != validate) {
207             setFactoryValidation(factory, validate);
208         }
209
210         DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
211
212         // add entity resolver
213
if (factory.isValidating()) {
214             JEntityResolver jer = new JEntityResolver();
215             // add Schemas
216
jer.addSchemas(new WebAppSchemas());
217             jer.addSchemas(new JonasWebAppSchemas());
218             jer.addSchemas(new JonasEjbjarSchemas());
219             jer.addSchemas(new JonasAppClientSchemas());
220             jer.addSchemas(new EarSchemas());
221             jer.addSchemas(new WsSchemas());
222             jer.addSchemas(new JonasWsSchemas());
223
224             // add DTDs
225
jer.addDtds(new WebAppDTDs());
226             jer.addDtds(new JonasWebAppDTDs());
227             jer.addDtds(new JonasEjbjarDTDs());
228             jer.addDtds(new JonasAppClientDTDs());
229             jer.addDtds(new EarDTDs());
230
231             builder.setEntityResolver(jer);
232         }
233         Document JavaDoc doc = builder.parse(is);
234         // close InputStream when finished parsing
235
is.close();
236         if (doc.getDoctype() != null && !isDTDsAllowed) {
237             // DTD case
238
// -> Throw Exception
239
throw new NoJ2EEWebservicesException(name + " use a DTD. Only XML Schema are accepted for J2EE 1.4 webservices");
240         }
241         return doc;
242     }
243
244
245     /**
246      * Returns the <code>session</code>/<code>entity</code>/
247      * <code>message-driven</code> XML Element with given name.
248      * @param base <code>jonas-ejb-jar</code> Element.
249      * @param bName the bean name to be found.
250      * @return the <code>session</code>/<code>entity</code>/
251      * <code>message-driven</code> XML Element.
252      */

253     public static Element JavaDoc getBeanElement(Element JavaDoc base, String JavaDoc bName) {
254         Element JavaDoc found = null;
255
256         // try Session Bean
257
NodeList JavaDoc sessions = base.getElementsByTagNameNS(JONAS_NS, SESSION_BEAN);
258
259         for (int i = 0; (i < sessions.getLength()) && (found == null); i++) {
260             Element JavaDoc session = (Element JavaDoc) sessions.item(i);
261             NodeList JavaDoc names = session.getElementsByTagNameNS(JONAS_NS, EJB_NAME);
262
263             // ejb-name mandatory and unique
264
Element JavaDoc name = (Element JavaDoc) names.item(0);
265
266             if (name.getFirstChild().getNodeValue().equals(bName)) {
267                 found = session;
268             }
269         }
270
271         // try Entity Bean
272
NodeList JavaDoc entities = base.getElementsByTagNameNS(JONAS_NS, ENTITY_BEAN);
273
274         for (int i = 0; (i < entities.getLength()) && (found == null); i++) {
275             Element JavaDoc entity = (Element JavaDoc) entities.item(i);
276             NodeList JavaDoc names = entity.getElementsByTagNameNS(JONAS_NS, EJB_NAME);
277
278             // ejb-name mandatory and unique
279
Element JavaDoc name = (Element JavaDoc) names.item(0);
280
281             if (name.getFirstChild().getNodeValue().equals(bName)) {
282                 found = entity;
283             }
284         }
285
286         // try Message Driven Bean
287
NodeList JavaDoc messages = base.getElementsByTagNameNS(JONAS_NS, MESSAGE_BEAN);
288
289         for (int i = 0; (i < messages.getLength()) && (found == null); i++) {
290             Element JavaDoc message = (Element JavaDoc) messages.item(i);
291             NodeList JavaDoc names = message.getElementsByTagNameNS(JONAS_NS, EJB_NAME);
292
293             // ejb-name mandatory and unique
294
Element JavaDoc name = (Element JavaDoc) names.item(0);
295
296             if (name.getFirstChild().getNodeValue().equals(bName)) {
297                 found = message;
298             }
299         }
300
301         return found;
302     }
303
304     /**
305      * Returns the matching <code>servlet</code> XML Element with given name.
306      * @param base <code>web-app</code> Element.
307      * @param sName the servlet name to be found.
308      * @return the matching <code>servlet</code> XML Element.
309      */

310     public static Element JavaDoc getServletElement(Element JavaDoc base, String JavaDoc sName) {
311         Element JavaDoc found = null;
312
313         // Search servlet List
314
NodeList JavaDoc servlets = base.getElementsByTagNameNS(J2EE_NS, SERVLET);
315
316         for (int i = 0; (i < servlets.getLength()) && (found == null); i++) {
317             Element JavaDoc servlet = (Element JavaDoc) servlets.item(i);
318             NodeList JavaDoc names = servlet.getElementsByTagNameNS(J2EE_NS, SERVLET_NAME);
319
320             // servlet-name mandatory and unique
321
Element JavaDoc name = (Element JavaDoc) names.item(0);
322
323             if (name.getFirstChild().getNodeValue().equals(sName)) {
324                 found = servlet;
325             }
326         }
327
328         return found;
329     }
330
331     /**
332      * Returns the <code>jonas-service-ref</code> XML Element with given name.
333      * @param base <code>web-app</code>/ bean Element containing
334      * <code>jonas-service-ref</code> Element(s).
335      * @param srName the service-ref name to be found.
336      * @return the <code>jonas-service-ref</code> XML Element.
337      */

338     public static Element JavaDoc getJonasServiceRef(Element JavaDoc base, String JavaDoc srName) {
339         Element JavaDoc found = null;
340
341         // Search jonas-service-ref list
342
if (base != null) {
343             NodeList JavaDoc jsrs = base.getElementsByTagNameNS(JONAS_NS, JONAS_SERVICE_REF);
344
345             for (int i = 0; (i < jsrs.getLength()) && (found == null); i++) {
346                 Element JavaDoc jsr = (Element JavaDoc) jsrs.item(i);
347                 NodeList JavaDoc names = jsr.getElementsByTagNameNS(JONAS_NS, SR_NAME);
348
349                 // service-ref-name mandatory and unique
350
Element JavaDoc name = (Element JavaDoc) names.item(0);
351
352                 if (name.getFirstChild().getNodeValue().equals(srName)) {
353                     found = jsr;
354                 }
355             }
356         }
357
358         return found;
359     }
360
361     /**
362      * default application.xml contains a fake ejb module needed to be parsed
363      * without error but not needed for a normal application. Than we remove it.
364      * @param doc application.xml document
365      */

366     public static void cleanDummyApplication(Document JavaDoc doc) {
367         Element JavaDoc root = doc.getDocumentElement();
368         NodeList JavaDoc nl = root.getElementsByTagNameNS(J2EE_NS, "module");
369         root.removeChild(nl.item(0));
370     }
371
372     /**
373      * Add an ejb module in an application Document
374      * @param app application.xml Document
375      * @param ejbjar EJBJar archive
376      */

377     public static void addEjb(Document JavaDoc app, Archive ejbjar) {
378         Element JavaDoc module = app.createElementNS(J2EE_NS, "module");
379         Element JavaDoc ejb = app.createElementNS(J2EE_NS, "ejb");
380         Text JavaDoc ejbText = app.createTextNode(ejbjar.getRootFile().getName());
381         ejb.appendChild(ejbText);
382         module.appendChild(ejb);
383
384         insertModule(app, module);
385     }
386
387     /**
388      * Add a client module in an application Document
389      * @param app application.xml Document
390      * @param client Client archive
391      */

392     public static void addClient(Document JavaDoc app, Archive client) {
393         Element JavaDoc module = app.createElementNS(J2EE_NS, "module");
394         Element JavaDoc clt = app.createElementNS(J2EE_NS, "java");
395         Text JavaDoc cltText = app.createTextNode(client.getRootFile().getName());
396         clt.appendChild(cltText);
397         module.appendChild(clt);
398
399         insertModule(app, module);
400     }
401
402     /**
403      * Add an web module in an application Document
404      * @param app application.xml Document
405      * @param webapp WebApp archive
406      * @param ctx context-root
407      */

408     public static void addWebApp(Document JavaDoc app, Archive webapp, String JavaDoc ctx) {
409         Element JavaDoc module = app.createElementNS(J2EE_NS, "module");
410         Element JavaDoc web = app.createElementNS(J2EE_NS, "web");
411         Element JavaDoc webUri = app.createElementNS(J2EE_NS, "web-uri");
412         Element JavaDoc context = app.createElementNS(J2EE_NS, "context-root");
413
414         Text JavaDoc webText = app.createTextNode(webapp.getName());
415         Text JavaDoc ctxText = app.createTextNode(ctx);
416         webUri.appendChild(webText);
417         context.appendChild(ctxText);
418
419         web.appendChild(webUri);
420         web.appendChild(context);
421
422         module.appendChild(web);
423
424         insertModule(app, module);
425     }
426
427     /**
428      * Insert a module in application Document
429      * @param app application.xml Document
430      * @param module module Element
431      */

432     private static void insertModule(Document JavaDoc app, Element JavaDoc module) {
433         Element JavaDoc application = app.getDocumentElement();
434         Element JavaDoc first = findFirstSecurityRole(application);
435         application.insertBefore(module, first);
436     }
437
438     /**
439      * return the first found security-role Element (or null if not found)
440      * @param app application.xml Document
441      * @return the first found security-role Element (or null if not found)
442      */

443     private static Element JavaDoc findFirstSecurityRole(Element JavaDoc app) {
444         NodeList JavaDoc nl = app.getElementsByTagNameNS(J2EE_NS, "security-role");
445
446         if (nl.getLength() == 0) {
447             return null;
448         } else {
449             return (Element JavaDoc) nl.item(0);
450         }
451     }
452
453     /**
454      * Creates a new XML Document for an empty jonas-client.xml.
455      * @return Returns a new XML Document for an empty jonas-client.xml.
456      */

457     public static Document JavaDoc newJonasClient() {
458
459        Document JavaDoc root = createDocument();
460
461        // jonas-client
462
Element JavaDoc jonasClient = root.createElementNS(JONAS_NS, "jonas-client");
463
464        // Automatically retrieve latest schema name
465
int index = JonasAppClientSchemas.JONAS_APPCLIENT_SCHEMAS.length - 1;
466        String JavaDoc schema = JonasAppClientSchemas.JONAS_APPCLIENT_SCHEMAS[index];
467        addNamespaces(jonasClient, schema);
468        root.appendChild(jonasClient);
469
470        return root;
471    }
472
473     /**
474      * @return Returns an empty jonas-web-app Document
475      */

476     public static Document JavaDoc newJonasWeb() {
477
478         Document JavaDoc root = createDocument();
479
480         // jonas-web-app
481
Element JavaDoc jonasWebApp = root.createElementNS(JONAS_NS, "jonas-web-app");
482
483         // Automatically retrieve latest schema name
484
int index = JonasWebAppSchemas.JONAS_WEBAPP_SCHEMAS.length - 1;
485         String JavaDoc schema = JonasWebAppSchemas.JONAS_WEBAPP_SCHEMAS[index];
486         addNamespaces(jonasWebApp, schema);
487         root.appendChild(jonasWebApp);
488
489         return root;
490     }
491
492     /**
493      * @return Returns an empty Document.
494      */

495     private static Document JavaDoc createDocument() {
496         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
497         factory.setNamespaceAware(true);
498         DocumentBuilder JavaDoc builder;
499         try {
500             builder = factory.newDocumentBuilder();
501         } catch (ParserConfigurationException JavaDoc e) {
502             throw new RuntimeException JavaDoc(e);
503         }
504         return builder.newDocument();
505     }
506
507     /**
508      * Add common namespaces to the given element and add schemaLocation
509      * @param e the Element to be updated
510      * @param schema the schema location value
511      */

512     private static void addNamespaces(Element JavaDoc e, String JavaDoc schema) {
513         Document JavaDoc root = e.getOwnerDocument();
514         // create xmlns="http://www.w3.org/XML/1998/namespace"
515
Attr JavaDoc xmlns = root.createAttributeNS(XMLNS_NS, "xmlns");
516         xmlns.setValue(JONAS_NS);
517
518         // create xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
519
Attr JavaDoc xsi = root.createAttributeNS(XMLNS_NS, "xmlns:xsi");
520         xsi.setValue(XSI_NS);
521
522         // create xsi:schemaLocation="http://www.objectweb.org/jonas/ns
523
// http://www.objectweb.org/jonas/ns/<schema>"
524
Attr JavaDoc schemaLocation = root.createAttributeNS(XSI_NS, "xsi:schemaLocation");
525         schemaLocation.setValue(JONAS_NS + " " + JONAS_NS + "/" + schema);
526
527         e.setAttributeNodeNS(xmlns);
528         e.setAttributeNodeNS(xsi);
529         e.setAttributeNodeNS(schemaLocation);
530
531     }
532
533 }
Popular Tags