KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > tools > ultradev > ctlx > TLDParser


1 /*
2  * Copyright 1999,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.taglibs.tools.ultradev.ctlx;
18
19 import javax.xml.parsers.DocumentBuilder JavaDoc;
20 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
21 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
22 import javax.xml.parsers.ParserConfigurationException JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.servlet.http.HttpServlet JavaDoc;
26 import javax.servlet.ServletConfig JavaDoc;
27 import javax.servlet.ServletException JavaDoc;
28 import org.xml.sax.SAXException JavaDoc;
29 import org.xml.sax.SAXParseException JavaDoc;
30 import org.xml.sax.InputSource JavaDoc;
31 import org.w3c.dom.Document JavaDoc;
32 import org.w3c.dom.Element JavaDoc;
33 import org.w3c.dom.Node JavaDoc;
34 import org.w3c.dom.Text JavaDoc;
35 import org.w3c.dom.DOMException JavaDoc;
36 import java.io.File JavaDoc;
37 import java.io.PrintWriter JavaDoc;
38 import java.io.IOException JavaDoc;
39 import java.util.Arrays JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.Hashtable JavaDoc;
42 import java.net.URL JavaDoc;
43
44
45 /* file: TLDParser.java
46  * author : Dan Mandell [dmandell@stanford.edu]
47  * contributors : Julien Carnelos [juliencarnelos@netcourrier.com]
48  * : David Miller [dmiller_va@hotmail.com]
49  * -------------------------------------------
50  * Takes the URL of a TLD file as an argument and produces a text
51  * file containing JavaScript declarations of associative
52  * arrays representing all tags and their attributes in the supplied
53  * TLD. Requires the xerces XML parser available from xml.apache.org
54  *
55  */

56
57
58 public class TLDParser extends HttpServlet JavaDoc {
59
60     /* Output Modes */
61     public final int ULTRADEV = 1;
62     public final int OTHER = 2;
63     public final int TLD_LIST = 3;
64     
65     /* Result Flags */
66     public final int FAILURE = 0;
67     public final int SUCCESS = 1;
68     
69     /* Private Constants/Defaults */
70     private final String JavaDoc URL_SEP = "/";
71     private final String JavaDoc PATH_TO_TLDS = URL_SEP + "tlds";
72     private final String JavaDoc TLD_SUFFIX = ".tld";
73     private final String JavaDoc UNDEFINED = "UNDEFINED";
74     private final String JavaDoc DEFAULT_OUTPUT_FILE = "tagLibData.js";
75     private final int DEFAULT_OUTPUT_MODE = ULTRADEV;
76     
77     /* Private Variables */
78     private int result = FAILURE; // internal flag. Set to SUCCESS if parsing is successful
79
private int mode; // defines format of the output
80
private String JavaDoc outputFilePrefix; // for naming output files (ie: prefix.js, prefix.html)
81
private PrintWriter JavaDoc out;
82     private Hashtable JavaDoc tags;
83
84     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc
85     {
86         super.init(config);
87     }
88
89     public void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
90                     throws ServletException JavaDoc, IOException JavaDoc
91     {
92         tags = new Hashtable JavaDoc();
93         out = new PrintWriter JavaDoc(res.getOutputStream());
94         String JavaDoc userMode;
95         URL JavaDoc tld = null;
96         
97         userMode = req.getParameter("mode").toLowerCase();
98         outputFilePrefix = req.getParameter("prefix");
99         String JavaDoc tldPath = PATH_TO_TLDS + URL_SEP + outputFilePrefix + TLD_SUFFIX;
100
101         /* updated the separator to make it compatible with Windows based servers */
102         tld = getServletConfig().getServletContext().getResource(tldPath);
103
104             System.out.println( "tld = " + tld );
105                 
106         if (userMode.equals("ultradev")) mode = ULTRADEV;
107         else if (userMode.equals("other")) mode = OTHER;
108         else if (userMode.equals("tldlist")) mode = TLD_LIST;
109         
110         if (mode == TLD_LIST) outputTLDList(req);
111         else parseTLD(tld);
112
113         out.close();
114     }
115         
116
117
118 /* funtion: parseTLD()
119  * -------------------
120  * Use the Xerces XML parser to create a DOM of the supplied TLD.
121  * Passes the root element of the DOM to the createAttTable method
122  * to create the attribute table.
123  */

124  
125     private void parseTLD(URL JavaDoc TLD) {
126         System.out.println("You entered " + TLD);
127         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
128         factory.setValidating(true);
129         factory.setNamespaceAware(true);
130             
131         try {
132             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
133             Document JavaDoc doc = builder.parse(new InputSource JavaDoc(TLD.openStream()));
134             Element JavaDoc root = doc.getDocumentElement();
135             System.out.println("Creating attributes table");
136             createAttTable(root);
137             writeOutput();
138             result = SUCCESS;
139         }
140         
141         catch (org.xml.sax.SAXException JavaDoc e) {
142             e.printStackTrace();
143         }
144
145         catch (javax.xml.parsers.ParserConfigurationException JavaDoc e) {
146             e.printStackTrace();
147         }
148
149         catch (java.io.IOException JavaDoc e) {
150             e.printStackTrace();
151         }
152     }
153     
154     
155 /* method: createAttTable()
156  * ------------------------
157  * Takes the root element in a DOM and enters the tags
158  * into the tags table as an arraylist
159  *
160  */

161     private void createAttTable (Element JavaDoc root) {
162         Node JavaDoc curTag = root.getFirstChild();
163                 
164         curTag = getNextTag(curTag, "tag");//start with first <tag> node
165
Tag thetag;
166         
167         while (curTag != null) {
168             System.out.println("Current tag name is: " + getTagName(curTag));
169             if (curTag.getNodeName().toLowerCase().equals("tag")) {
170                 thetag = analyzeAtts(curTag);
171                 tags.put(getTagName(curTag), thetag);
172             }
173             curTag = getNextTag(curTag, "tag");
174         }
175     }
176     
177     
178  /* method: analyzeAtts()
179   * ---------------------
180   * Analyzes each child of the supplied tag. If the child is an attribute,
181   * the child Node is passed to checkFields to check if the attribute
182   * should be written.
183   */

184     
185     private Tag analyzeAtts(Node JavaDoc tagNode) {
186         Node JavaDoc bodyContentNode;
187         Node JavaDoc curAtt = getNextTag(tagNode.getFirstChild(), "attribute"); // go to first attribute
188
Node JavaDoc curField; // the current attribute field, ie. name,required, etc...
189
Node JavaDoc curFieldContent; // whatever content is inside the current field
190
String JavaDoc curFieldText; // the text data of the curFieldContent
191
String JavaDoc curFieldName; // the name of the current field Node
192
String JavaDoc attName = UNDEFINED; // the value of the attribute's "name" field
193
String JavaDoc attReq = UNDEFINED; // the value of the attribute's "required" field
194
Tag thetag = new Tag();
195
196         bodyContentNode = getNextTag(tagNode.getFirstChild(), "bodycontent"); // node containing value of bodycontent
197
if (bodyContentNode == null)
198              bodyContentNode = getNextTag(tagNode.getFirstChild(), "body-content"); // support for JSP 1.2 naming
199
if (bodyContentNode != null) { //set bodyContent based on text contained in body content node
200
String JavaDoc bodyContentText = ((Text JavaDoc)bodyContentNode.getFirstChild()).getData();
201             thetag.setBodyContent(bodyContentText.toLowerCase().equals("empty") ? false : true);
202         }
203
204         System.out.println("Analyzing attributes...");
205
206         while (curAtt != null) {
207             curField = curAtt.getFirstChild();
208             
209             while (curField != null) { // store relevent attribute fields
210
if (curField.hasChildNodes()) {
211                     curFieldContent = curField.getFirstChild();
212                     curFieldName = curField.getNodeName().toLowerCase();
213                     curFieldText = ((Text JavaDoc)curFieldContent).getData();
214                 
215                     if (curFieldName != null && curFieldName.equals("name")) {
216                         attName = curFieldText;
217                     }
218                 
219                     else if (curFieldName != null && curFieldName.equals("required")) {
220                         attReq = curFieldText;
221                     }
222                 }
223                 curField = curField.getNextSibling();
224             }
225             if (attName == null | attReq == null) {
226                 //tag is malformed; either <name> or <required> does not exist
227

228                 System.err.println("Warning - Malformed tag: " + getTagName(tagNode));
229                 System.err.println("<name> and <required> are required fields in TLD");
230                 attName = attReq = UNDEFINED;
231             }
232             else if (attName != UNDEFINED && attReq != UNDEFINED){
233                 // add attName to the tag's atts list
234
thetag.addAtt(attName);
235                 // if att is required, also add it to the reqAtts list
236
if (attReq.toLowerCase().equals("true")) {
237                     thetag.reqAtts.add(attName);
238                 }
239                 System.out.println("Attribute = " + attName);
240                 System.out.println("Required = " + attReq);
241                 attName = attReq = UNDEFINED;
242             }
243             curAtt = curAtt.getNextSibling();
244         }
245         return thetag;
246     }
247
248
249 /* method: getNextTag()
250  * ----------------------
251  * Takes a Node object and returns the subsequent node that the getNodeName()
252  * method returns a string equal (case insensitive) to the supplied tagName.
253  *
254  */

255  
256     private Node JavaDoc getNextTag(Node JavaDoc curField, String JavaDoc tagName) {
257         Node JavaDoc nextTag = curField.getNextSibling();
258         
259         //continue through DOM until next tag matching tagName is found
260
while (nextTag != null &&
261             !(nextTag.getNodeName().toLowerCase().equals(tagName.toLowerCase())))
262         {
263             nextTag = nextTag.getNextSibling();
264         }
265
266         return nextTag;
267     }
268
269
270 /* method: getTagName()
271  * ----------------------
272  * Takes a tag in a TLD DOM and returns a string version of the text data
273  * in the tag's <name> field.
274  *
275  */

276
277     private String JavaDoc getTagName(Node JavaDoc tag) {
278         Node JavaDoc nameTag = getNextTag(tag.getFirstChild(), "name").getFirstChild();
279         return ((Text JavaDoc)nameTag).getData();
280     }
281     
282
283 /* method: writeOutput()
284  * ---------------------
285  * Writes the out file(s) based on the file output mode.
286  * Currently a placeholder for future output formats.
287  */

288  
289     private void writeOutput() {
290         switch(mode) {
291             case ULTRADEV:
292                 outputForUltraDev();
293                 break;
294             default:
295                 outputForUltraDev();
296                 break;
297         }
298     }
299
300 /* method: outputForUltraDev()
301  * ---------------------------
302  * Writes the JavaScript (.js) and HTML (.html) files necessary to
303  * represent the floater to the current directory.
304  */

305  
306     private void outputForUltraDev() {
307         outputTaglibData();
308     }
309
310     
311 /* method: outputTaglibData()
312  * --------------------------
313  * Outputs the taglib's TLD data, as a series of JavaScript
314  * associative array declarations, to the HTTP response object.
315  *
316  */

317
318     private void outputTaglibData() {
319         Object JavaDoc[] tagNames = (tags.keySet().toArray());
320         Arrays.sort(tagNames);
321         String JavaDoc curName;
322         Object JavaDoc[] attributes, reqAttributes;
323         Tag curTag;
324         
325         out.println("taglibs[\"" + outputFilePrefix + "\"]=[");
326         for (int i = 0; i < tagNames.length; i++) {
327             curName = (String JavaDoc)tagNames[i];
328             curTag = ((Tag)tags.get(curName));
329             out.print("\t[\"" + curName + "\", " + curTag.hasBodyContent() + ", [");
330
331             reqAttributes = ((ArrayList JavaDoc)(curTag.getReqAtts())).toArray();
332             for (int j = 0; j < reqAttributes.length; j++) {
333                 out.print("\"" + reqAttributes[j] + "\"");
334                 if (j < reqAttributes.length - 1) out.print(", ");
335             }
336             out.print("], [");
337             
338             attributes = ((ArrayList JavaDoc)(curTag.getAtts())).toArray();
339             for (int k = 0; k < attributes.length; k++) {
340                 out.print("\"" + attributes[k] + "\"");
341                 if (k < attributes.length - 1) out.print(", ");
342             }
343
344             out.print("]");
345
346             /* easy to add any new information... */
347
348             if ( i >= tagNames.length - 1 ) out.println( "]];");
349             else
350                 out.println("],");
351         }
352     }
353     
354     
355 /* method: outputTLDList()
356  * -----------------------
357  * Sends a tab-delimited list of TLDs in the servlet's TLDs directory
358  * to the http response out stream.
359  *
360  */

361  
362     private void outputTLDList(HttpServletRequest JavaDoc req) {
363                 String JavaDoc tldpath = getServletConfig().getServletContext().getRealPath(PATH_TO_TLDS);
364         File JavaDoc dir = new File JavaDoc(tldpath);
365         String JavaDoc[] files = dir.list();
366         
367         for (int i = 0; i < files.length; i++) {
368             out.print(files[i].substring(0,files[i].indexOf(".")));
369             if (i < files.length - 1) out.print("\t");
370         }
371     }
372     
373     
374  
375 /** Public Accessors **/
376
377
378
379 /* method: setOutputPrefix()
380  * -----------------------
381  * Sets the name of the file to be written.
382  *
383  */

384
385     public void setOutputPrefix(String JavaDoc prefix) {
386         outputFilePrefix = prefix.toLowerCase();
387     }
388     
389
390 /* method: setOutputMode()
391  * -------------------------
392  * Sets the output mode of the parser. Available options listed at top
393  * under "Output Modes". Modify this method as output modes are added.
394  *
395  */

396
397     public void setOutputMode(int outputMode) {
398         if (outputMode != ULTRADEV &&
399             outputMode != OTHER) {
400                 System.err.println("Invalid output mode.");
401         }
402         
403         else {
404             mode = outputMode;
405         }
406     }
407
408
409 /* method: getOutputMode()
410  * -----------------------
411  * Returns the parser's output mode.
412  *
413  */

414
415     public int getOutputMode() {
416         return mode;
417     }
418     
419
420 /* method: getResult()
421  * -------------------
422  * Returns the value of the result flag. True if all operations completed
423  * successfully.
424  */

425  
426     public int getResult() {
427         return result;
428     }
429     
430
431
432 /* Private classes */
433     
434
435
436 /* class: Tag
437  * ----------
438  * Private wrapper class. Stores an ArrayList of attributes, an ArrayList
439  * of required attributes (kept seperate for performance purposes) and a
440  * bodyContent boolean, set to true if the tag allows any body content.
441  */

442
443     private class Tag {
444         private ArrayList JavaDoc atts = new ArrayList JavaDoc();
445         private ArrayList JavaDoc reqAtts = new ArrayList JavaDoc();
446         private boolean bodyContent;
447         
448         public void addAtt (String JavaDoc att) {
449             if (att != null) {
450                 System.out.println("Adding attribute: " + att);
451                 atts.add(att);
452             }
453         }
454         
455         public void addReqAtt (String JavaDoc att) {
456             if (att != null ) {
457                 reqAtts.add(att);
458             }
459         }
460         
461         public void setBodyContent(boolean bc) {
462             if (bc == true || bc == false) {
463                 bodyContent = bc;
464             }
465         }
466
467         public ArrayList JavaDoc getAtts () {
468             return atts;
469         }
470         
471         public ArrayList JavaDoc getReqAtts () {
472             return reqAtts;
473         }
474         
475         public boolean hasBodyContent() {
476             return bodyContent;
477         }
478     }
479 }
480
Popular Tags