KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > guiframework > view > ViewXMLReader


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 package com.sun.enterprise.tools.guiframework.view;
25
26 // JAXP packages
27
import javax.xml.parsers.*;
28 import org.xml.sax.*;
29 import org.xml.sax.helpers.*;
30 import org.w3c.dom.*;
31 import javax.xml.transform.*;
32 import javax.xml.transform.dom.DOMSource JavaDoc;
33 import javax.xml.transform.stream.StreamResult JavaDoc;
34 import org.xml.sax.SAXException JavaDoc;
35 import org.w3c.dom.Document JavaDoc;
36
37 import java.io.*;
38 import java.util.HashMap JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.lang.reflect.Constructor JavaDoc;
41 import java.lang.reflect.Array JavaDoc;
42 import java.util.ArrayList JavaDoc;
43 import java.util.StringTokenizer JavaDoc;
44
45 import com.sun.enterprise.tools.guiframework.FrameworkDescriptor;
46 import com.sun.enterprise.tools.guiframework.event.descriptors.EventDescriptor;
47 import com.sun.enterprise.tools.guiframework.event.descriptors.HandlerDescriptor;
48 import com.sun.enterprise.tools.guiframework.event.descriptors.IODescriptor;
49 import com.sun.enterprise.tools.guiframework.event.descriptors.UseHandlerDescriptor;
50 import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
51 import com.sun.enterprise.tools.guiframework.view.descriptors.ViewDescriptor;
52 import com.sun.enterprise.tools.guiframework.util.Util;
53
54
55 /**
56  *
57  */

58 public class ViewXMLReader {
59
60     public ViewXMLReader(String JavaDoc fileName, String JavaDoc dtdURLBase) throws Exception JavaDoc {
61     this(fileName, dtdURLBase, null);
62     }
63     
64     public ViewXMLReader(String JavaDoc fileName, String JavaDoc dtdURLBase, String JavaDoc jspRoot) throws Exception JavaDoc {
65     this(new FileInputStream(new File(fileName)), dtdURLBase, jspRoot);
66     }
67
68     public ViewXMLReader(InputStream is, String JavaDoc dtdURLBase) throws Exception JavaDoc {
69     // Invoke w/ the default "/jsp/" jsp root
70
this(is, dtdURLBase, null);
71     }
72
73     public ViewXMLReader(InputStream is, String JavaDoc dtdURLBase, String JavaDoc jspRoot) throws Exception JavaDoc {
74         // Invoke w/ the entityresolver
75
this(is, dtdURLBase, jspRoot, null);
76     }
77     
78     public ViewXMLReader(InputStream is, String JavaDoc dtdURLBase, String JavaDoc jspRoot,
79         EntityResolver entityResolver) throws Exception JavaDoc {
80     setJSPRoot(jspRoot);
81     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
82     dbf.setNamespaceAware(true);
83     dbf.setValidating(false);
84     dbf.setIgnoringComments(false);
85     dbf.setIgnoringElementContentWhitespace(false);
86     dbf.setCoalescing(false);
87     // The opposite of creating entity ref nodes is expanding them inline
88
dbf.setExpandEntityReferences(true);
89     
90     DocumentBuilder db = dbf.newDocumentBuilder();
91         if (entityResolver != null) {
92             db.setEntityResolver(entityResolver);
93         }
94     OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, OUTPUT_ENCODING);
95     db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
96     doc = db.parse(is, dtdURLBase);
97     preProcess();
98     }
99
100
101     private void preProcess() throws Exception JavaDoc {
102     // get all display item types
103
NodeList nodeList = doc.getElementsByTagName(DISPLAY_ITEM_TYPE);
104     for (int i = 0; i < nodeList.getLength(); i++) {
105         Element elem = (Element)nodeList.item(i);
106         typeMap.put(elem.getAttribute(NAME), elem);
107     }
108     }
109
110
111     /**
112      *
113      */

114     private ViewDescriptor getDescriptor(String JavaDoc name, String JavaDoc type) throws Exception JavaDoc {
115     // I need to create a DisplayFieldDescriptor. The name of the class is known.
116
Element typeNode = (Element)typeMap.get(type);
117     if (typeNode == null) {
118         return new ViewDescriptor(name); // default type
119
}
120
121     // Get the ViewDescriptor Class
122
Class JavaDoc descriptorClass =
123         Class.forName(typeNode.getAttribute(DESCRIPTOR_CLASS));
124
125     // Get the constructor for the ViewDescriptor
126
Constructor JavaDoc constructor =
127         descriptorClass.getConstructor(new Class JavaDoc[] {String JavaDoc.class});
128
129     // Create a new instance
130
return (ViewDescriptor)constructor.newInstance(new Object JavaDoc[] {name});
131     }
132
133
134     /**
135      *
136      */

137     private void processEvent(Element node, ViewDescriptor vd) throws Exception JavaDoc {
138     String JavaDoc type = node.getAttribute(TYPE);
139     EventDescriptor eventDesc = new EventDescriptor(vd, type);
140
141     UseHandlerDescriptor useDesc;
142     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
143         if (child.getNodeName().compareToIgnoreCase(CALL) == 0) {
144         useDesc = getUseHandler(eventDesc, (Element)child);
145         eventDesc.addEventHandler(useDesc);
146         }
147     }
148     vd.setEventDescriptor(eventDesc);
149     }
150
151
152     /**
153      *
154      */

155     private UseHandlerDescriptor getUseHandler(FrameworkDescriptor parent, Element node) {
156     // Get the Handler Node
157
Element handlerNode = getHandlerNode(node.getAttribute(NAME), doc);
158     if (handlerNode == null) {
159         throw new IllegalArgumentException JavaDoc("'"+CALL+
160         "' referred to a handler that was not found: '"+
161         node.getAttribute(NAME)+"'");
162     }
163
164     // Create the UseHandlerDescriptor
165
HandlerDescriptor handlerDesc = getHandler(handlerNode);
166     UseHandlerDescriptor useDesc =
167         new UseHandlerDescriptor(parent, handlerDesc);
168
169     // Get the 'if' value
170
String JavaDoc ifValue = node.getAttribute(IF);
171     if (Util.hasValue(ifValue)) {
172         useDesc.setIfCheck(ifValue);
173     }
174
175     // Get the input parameters
176
Element elt;
177     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
178         String JavaDoc childName = child.getNodeName();
179         if (childName.compareToIgnoreCase(INPUT)==0) {
180         elt = (Element)child;
181         // Make sure 'name' is valid...
182
String JavaDoc name = elt.getAttribute(NAME);
183         if (handlerDesc.getInputDescriptor(name) == null) {
184             throw new FrameworkException(CALL+" '"+
185             handlerDesc.getName()+"' defined "+INPUT+": '"+name+
186             "', however, '"+name+"' is not a valid "+INPUT+"!");
187         }
188         useDesc.setInputValue(name, getParameterValue(elt));
189         } else if (childName.compareToIgnoreCase(OUTPUT)==0) {
190         elt = (Element)child;
191         // Make sure 'name' is valid...
192
String JavaDoc name = elt.getAttribute(NAME);
193         if (handlerDesc.getOutputDescriptor(name) == null) {
194             throw new FrameworkException(CALL+" '"+
195             handlerDesc.getName()+"' defined "+OUTPUT+": '"+name+
196             "', however, '"+name+"' is not a valid "+OUTPUT+"!");
197         }
198         useDesc.setOutputMapping(
199             name, elt.getAttribute(TARGET_KEY), elt.getAttribute(TARGET_TYPE));
200         }
201     }
202
203     // Return the UseHandlerDescriptor
204
return useDesc;
205     }
206
207
208     /**
209      *
210      */

211     private HandlerDescriptor getHandler(Element node) {
212     // Make sure we haven't already created this handler
213
String JavaDoc name = node.getAttribute(NAME);
214     HandlerDescriptor handler = (HandlerDescriptor)handlerMap.get(name);
215     if (handler != null) {
216         return handler;
217     }
218
219     // Create Handler
220
handler = new HandlerDescriptor(name);
221
222     // Set the description (hold this for future tool support)
223
handler.setDescription(node.getAttribute(DESCRIPTION));
224
225     // Set method
226
String JavaDoc className = node.getAttribute(FUNCTION_CLASS);
227     String JavaDoc methodName = node.getAttribute(FUNCTION_METHOD);
228     if (Util.hasValue(className) && Util.hasValue(methodName)) {
229         handler.setHandlerMethod(className, methodName);
230     }
231
232     // Set If Check
233
String JavaDoc ifValue = node.getAttribute(IF);
234     if (Util.hasValue(ifValue)) {
235         handler.setIfCheck(ifValue);
236     }
237
238     // Iterate through the kids...
239
String JavaDoc nodeName;
240     UseHandlerDescriptor useDesc;
241     IODescriptor ioDesc;
242     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
243         nodeName = child.getNodeName();
244         if (nodeName.compareToIgnoreCase(CALL) == 0) {
245         useDesc = getUseHandler(handler, (Element)child);
246         handler.addChildHandlerDescriptor(useDesc);
247         } else if (nodeName.compareToIgnoreCase(INPUT_DEF) == 0) {
248         ioDesc = getIODescriptor((Element)child);
249         String JavaDoc defValue = ((Element)child).getAttribute(DEFAULT);
250         if (Util.hasValue(defValue)) {
251             ioDesc.setDefault(defValue);
252         }
253         handler.addInputDescriptor(ioDesc);
254         } else if (nodeName.compareToIgnoreCase(OUTPUT_DEF) == 0) {
255         ioDesc = getIODescriptor((Element)child);
256         handler.addOutputDescriptor(ioDesc);
257         }
258     }
259
260     // Return the handler
261
handlerMap.put(name, handler);
262     return handler;
263     }
264
265
266     /**
267      *
268      */

269     private IODescriptor getIODescriptor(Element node) {
270     IODescriptor desc = new IODescriptor(
271         node.getAttribute(NAME), node.getAttribute(TYPE));
272     desc.setDescription(node.getAttribute(DESCRIPTION));
273     return desc;
274     }
275
276
277     private void processParameter(Element node, ViewDescriptor vd) {
278     vd.addParameter(node.getAttribute(NAME), getParameterValue(node));
279     }
280
281
282     private void processInclude(Element node, ViewDescriptor vd) throws Exception JavaDoc{
283     /* look for the displayItem in the xml and just add it to the vd */
284     Node descriptorNode = getViewDescriptorNode(node.getAttribute("item"), doc);
285     if (descriptorNode == null) {
286         throw new Exception JavaDoc ("Invalid include :" + node.getAttribute("item"));
287     }
288
289     // Process Child DisplayItem
290
vd.addChildDescriptor(process((Element)descriptorNode));
291     }
292
293     private Object JavaDoc getInputValue(Element node) {
294     return getParameterValue(node);
295     }
296
297     private Object JavaDoc getParameterValue(Element node) {
298     if (Util.hasValue(node.getAttribute(VALUE))) {
299         /* removed support for $(top) parsing at xml parsing time
300             return Util.replace(node.getAttribute(VALUE), RESERVED_WORD_TOP, topLevelDescriptorName);
301              */

302             return node.getAttribute(VALUE);
303     }
304
305     ArrayList JavaDoc values = new ArrayList JavaDoc();
306     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
307         if (child.getNodeName().equalsIgnoreCase(VALUES)) {
308         /* removed support for $(top) parsing at xml parsing time
309         String str = Util.replace(((Element)child).getAttribute(VALUE), RESERVED_WORD_TOP, topLevelDescriptorName);
310              */

311         String JavaDoc str = ((Element)child).getAttribute(VALUE);
312         values.add(str);
313         }
314     }
315
316     // Make sure they specified one or the other.
317
if (values.size() == 0) {
318         return null;
319     }
320     return values;
321     }
322
323
324     private String JavaDoc getDisplayItem(Node node) {
325     Node parentNode = node;
326     while (true) {
327         parentNode = parentNode.getParentNode();
328         if (parentNode == null || parentNode.getNodeName().compareToIgnoreCase(DISPLAY_ITEM)==0) {
329         break;
330         }
331     }
332     if (parentNode == null) {
333         return null;
334     }
335     NamedNodeMap attrs = parentNode.getAttributes();
336     if (attrs == null) {
337         return null;
338     }
339     return attrs.getNamedItem(NAME).getNodeValue();
340     }
341
342
343     private ViewDescriptor process(Element node) throws Exception JavaDoc {
344     String JavaDoc name = node.getAttribute(NAME);
345     String JavaDoc description = node.getAttribute(DESCRIPTION);
346     String JavaDoc type = node.getAttribute(TYPE);
347     String JavaDoc extendsFrom = node.getAttribute("extends");
348     String JavaDoc displayURL = node.getAttribute("displayURL");
349
350     // Perform "extends" functionality
351
Node extendsViewDescriptor = null;
352     if (Util.hasValue(extendsFrom)) {
353         extendsViewDescriptor = getViewDescriptorNode(extendsFrom, doc);
354         if (extendsViewDescriptor == null) {
355         throw new Exception JavaDoc("Cannot find " + extendsFrom);
356         }
357             // leaving this for backward compatibility - type should better
358
// be specified in the view descriptor itself..
359
if (type == null || type.length() == 0) {
360         type = ((Element)extendsViewDescriptor).getAttribute(TYPE);
361         }
362     }
363
364     ViewDescriptor vd = getDescriptor(name, type);
365     vd.setDescription(description);
366
367     // The following line sets a reasonable default display URL
368
if ((displayURL == null) || (displayURL.equals(""))) {
369         vd.setDisplayURL(getJSPName(name));
370     } else {
371         vd.setDisplayURL(displayURL);
372     }
373
374     // Perform "extends" functionality
375
if (extendsViewDescriptor != null) {
376             processExtends((Element)extendsViewDescriptor, vd);
377         }
378 // processDisplayItemChildren((Element)extendsViewDescriptor, vd);
379
// }
380

381     processDisplayItemChildren(node ,vd);
382     return vd;
383     }
384
385     protected void processExtends(Element extendsViewDescriptor,
386                 ViewDescriptor vd) throws Exception JavaDoc {
387     String JavaDoc extendsFrom = extendsViewDescriptor.getAttribute("extends");
388         if (Util.hasValue(extendsFrom)) {
389         Element extendsParentViewDescriptor = getViewDescriptorNode(extendsFrom, doc);
390         if (extendsViewDescriptor == null) {
391         throw new Exception JavaDoc("Cannot find " + extendsFrom);
392         }
393             processExtends(extendsParentViewDescriptor, vd);
394         }
395         processDisplayItemChildren((Element)extendsViewDescriptor, vd);
396     }
397
398     protected String JavaDoc getJSPName(String JavaDoc name) {
399     return getJSPRoot() + name + ".jsp";
400     }
401
402
403     protected String JavaDoc getJSPRoot() {
404     return _jspRoot;
405     }
406
407
408     protected void setJSPRoot(String JavaDoc root) {
409     if (root == null) {
410         return;
411     }
412     _jspRoot = root;
413     }
414
415
416     private void processDisplayItemChildren(Node node, ViewDescriptor vd) throws Exception JavaDoc {
417     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
418         String JavaDoc childName = child.getNodeName();
419         if (childName.compareToIgnoreCase(PARAMETER)==0) {
420         processParameter((Element)child, vd);
421         }
422         else if (childName.compareToIgnoreCase(EVENTS)==0) {
423         processEvent((Element)child, vd);
424         }
425         else if (childName.compareToIgnoreCase(DISPLAY_ITEM)==0) {
426         // Process Child DisplayItem
427
vd.addChildDescriptor(process((Element)child));
428         }
429         else if (childName.compareToIgnoreCase(INCLUDE)==0) {
430         processInclude((Element)child, vd);
431         }
432
433     }
434     }
435
436
437     /**
438      *
439      */

440     private Element getHandlerNode(String JavaDoc key, Node node) {
441     if (node == null) {
442         return null;
443     }
444     for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
445         String JavaDoc nodeName = child.getNodeName();
446         if (nodeName.compareToIgnoreCase(FUNCTION)==0) {
447         if (((Element)child).getAttribute(NAME).equals(key)) {
448             return (Element)child;
449         }
450         } else {
451         Element handlerNode = getHandlerNode(key, child);
452         if (handlerNode != null) {
453             return handlerNode;
454         }
455         }
456     }
457     return null;
458     }
459
460
461     private Element getViewDescriptorNode(String JavaDoc key, Node node) throws Exception JavaDoc {
462     if (node == null) {
463         return null;
464     }
465
466     // First try to find a Top-Level displayItem...
467
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
468         String JavaDoc nodeName = child.getNodeName();
469         if (nodeName.compareToIgnoreCase(DISPLAY_ITEM)==0) {
470         NamedNodeMap attrs = child.getAttributes();
471         if (attrs == null) {
472             throw new Exception JavaDoc("No attrs!!!");
473         }
474         Node name = attrs.getNamedItem(NAME);
475         if (name == null) {
476             throw new Exception JavaDoc("Name cannot be null!!!");
477         }
478         if (name.getNodeValue().equals(key)) {
479             return (Element)child;
480         }
481         }
482         else {
483         Element vdNode = getViewDescriptorNode(key, child);
484         if (vdNode != null) {
485             return vdNode;
486         }
487         }
488     }
489
490     // The above loop should have found it... unless we should be looking
491
// for a deep ViewDescriptor...
492
if (key.indexOf(".") >= 0) {
493         /*key could be a.b.c etc., which depicts a hierarchy of viewdescriptors
494          *in xml terms, this means
495          *<displayItem name = "a">
496          * <displayItem name = "b">
497          * <displayItem name = "c"/>
498          * </displayItem>
499          *</displayItem> */

500         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(key, ".");
501         Node childNode = node;
502         while (tokenizer.hasMoreElements()) {
503         key = tokenizer.nextToken();
504         childNode = getViewDescriptorNode(key, childNode);
505         }
506         return (Element)childNode;
507     }
508
509     return null;
510     }
511
512
513     /**
514      *
515      */

516     public ViewDescriptor getViewDescriptor(String JavaDoc key) throws Exception JavaDoc {
517     Element node = getViewDescriptorNode(key, doc);
518     if (node == null) {
519         return null;
520 // throw new FrameworkException("Key not found in XML file: "+key);
521
}
522     //topLevelDescriptorName = key;
523
return process(node);
524     }
525
526
527     // Error handler to report errors and warnings
528
private static class MyErrorHandler implements ErrorHandler {
529     /** Error handler output goes here */
530     private PrintWriter out;
531
532     MyErrorHandler(PrintWriter out) {
533         this.out = out;
534     }
535
536     /**
537      * Returns a string describing parse exception details
538      */

539     private String JavaDoc getParseExceptionInfo(SAXParseException spe) {
540         String JavaDoc systemId = spe.getSystemId();
541         if (systemId == null) {
542         systemId = "null";
543         }
544         String JavaDoc info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage();
545         return info;
546     }
547
548     // The following methods are standard SAX ErrorHandler methods.
549
// See SAX documentation for more info.
550

551     public void warning(SAXParseException spe) throws SAXException JavaDoc {
552         out.println("Warning: " + getParseExceptionInfo(spe));
553     }
554
555     public void error(SAXParseException spe) throws SAXException JavaDoc {
556         String JavaDoc message = "Error: " + getParseExceptionInfo(spe);
557         throw new SAXException JavaDoc(message);
558     }
559
560     public void fatalError(SAXParseException spe) throws SAXException JavaDoc {
561         String JavaDoc message = "Fatal Error: " + getParseExceptionInfo(spe);
562         throw new SAXException JavaDoc(message);
563     }
564     }
565
566
567     // returns all 'top level' view descriptors
568
public HashMap JavaDoc getAllViewDescriptors() throws Exception JavaDoc {
569     NodeList nodeList = doc.getElementsByTagName(DISPLAY_ITEM);
570         HashMap JavaDoc descriptors = new HashMap JavaDoc();
571     for (int i = 0; i < nodeList.getLength(); i++) {
572         Element displayItem = (Element)nodeList.item(i);
573             Node parent = displayItem.getParentNode();
574             // if it has a parent, it is not a top level view descriptor.
575
if (parent != null && parent.getNodeName().equals(DISPLAY_ITEM))
576                 continue;
577             String JavaDoc topLevelDescriptorName = displayItem.getAttribute(NAME);
578             if (descriptors.get(topLevelDescriptorName) != null) {
579                 throw new Exception JavaDoc("DisplayItem " + topLevelDescriptorName + " defined more than once");
580             }
581             descriptors.put(topLevelDescriptorName, process(displayItem));
582         }
583         return descriptors;
584     }
585     
586     public static void main(String JavaDoc args[]) {
587     try {
588         if (Array.getLength(args) < 2) {
589         System.out.println("Usage ViewXMLReader <XMLFileName> <ViewName>");
590         return;
591         }
592         ViewXMLReader xmlReader = new ViewXMLReader(args[0], "file://./");
593         xmlReader.getViewDescriptor(args[1]);
594     } catch (Exception JavaDoc ex) {
595         ex.printStackTrace();
596     }
597     }
598
599
600     private String JavaDoc _jspRoot = "/jsp/";
601     //private String topLevelDescriptorName;
602

603
604     private Document JavaDoc doc;
605     private Map JavaDoc typeMap = new HashMap JavaDoc();
606     private Map JavaDoc handlerMap = new HashMap JavaDoc();
607
608     private static final String JavaDoc OUTPUT_ENCODING = "UTF-8";
609
610     private static final String JavaDoc DESCRIPTOR_CLASS = "descriptorClass";
611     private static final String JavaDoc DISPLAY_ITEM = "displayItem";
612     private static final String JavaDoc DISPLAY_ITEM_TYPE = "displayItemType";
613     private static final String JavaDoc EVENTS = "events";
614     private static final String JavaDoc FUNCTION = "function";
615     private static final String JavaDoc FUNCTION_CLASS = "className";
616     private static final String JavaDoc FUNCTION_METHOD = "methodName";
617     private static final String JavaDoc INPUT_DEF = "inputDef";
618     private static final String JavaDoc OUTPUT_DEF = "outputDef";
619     private static final String JavaDoc CALL = "call";
620     private static final String JavaDoc INPUT = "input";
621     private static final String JavaDoc OUTPUT = "output";
622     private static final String JavaDoc TARGET_KEY = "key";
623     private static final String JavaDoc TARGET_TYPE = "target";
624     private static final String JavaDoc IF = "if";
625     private static final String JavaDoc PARAMETER = "parameter";
626     private static final String JavaDoc INCLUDE = "include";
627     private static final String JavaDoc VALUE = "value";
628     private static final String JavaDoc VALUES = "values";
629     private static final String JavaDoc NAME = "name";
630     private static final String JavaDoc TYPE = "type";
631     private static final String JavaDoc DEFAULT = "default";
632     private static final String JavaDoc DESCRIPTION = "description";
633 }
634
Popular Tags