?? tldparser.java
字號:
/*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.taglibs.tools.ultradev.ctlx;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.DOMException;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Hashtable;
import java.net.URL;
/* file: TLDParser.java
* author : Dan Mandell [dmandell@stanford.edu]
* contributors : Julien Carnelos [juliencarnelos@netcourrier.com]
* : David Miller [dmiller_va@hotmail.com]
* -------------------------------------------
* Takes the URL of a TLD file as an argument and produces a text
* file containing JavaScript declarations of associative
* arrays representing all tags and their attributes in the supplied
* TLD. Requires the xerces XML parser available from xml.apache.org
*
*/
public class TLDParser extends HttpServlet {
/* Output Modes */
public final int ULTRADEV = 1;
public final int OTHER = 2;
public final int TLD_LIST = 3;
/* Result Flags */
public final int FAILURE = 0;
public final int SUCCESS = 1;
/* Private Constants/Defaults */
private final String URL_SEP = "/";
private final String PATH_TO_TLDS = URL_SEP + "tlds";
private final String TLD_SUFFIX = ".tld";
private final String UNDEFINED = "UNDEFINED";
private final String DEFAULT_OUTPUT_FILE = "tagLibData.js";
private final int DEFAULT_OUTPUT_MODE = ULTRADEV;
/* Private Variables */
private int result = FAILURE; // internal flag. Set to SUCCESS if parsing is successful
private int mode; // defines format of the output
private String outputFilePrefix; // for naming output files (ie: prefix.js, prefix.html)
private PrintWriter out;
private Hashtable tags;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
tags = new Hashtable();
out = new PrintWriter(res.getOutputStream());
String userMode;
URL tld = null;
userMode = req.getParameter("mode").toLowerCase();
outputFilePrefix = req.getParameter("prefix");
String tldPath = PATH_TO_TLDS + URL_SEP + outputFilePrefix + TLD_SUFFIX;
/* updated the separator to make it compatible with Windows based servers */
tld = getServletConfig().getServletContext().getResource(tldPath);
System.out.println( "tld = " + tld );
if (userMode.equals("ultradev")) mode = ULTRADEV;
else if (userMode.equals("other")) mode = OTHER;
else if (userMode.equals("tldlist")) mode = TLD_LIST;
if (mode == TLD_LIST) outputTLDList(req);
else parseTLD(tld);
out.close();
}
/* funtion: parseTLD()
* -------------------
* Use the Xerces XML parser to create a DOM of the supplied TLD.
* Passes the root element of the DOM to the createAttTable method
* to create the attribute table.
*/
private void parseTLD(URL TLD) {
System.out.println("You entered " + TLD);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(TLD.openStream()));
Element root = doc.getDocumentElement();
System.out.println("Creating attributes table");
createAttTable(root);
writeOutput();
result = SUCCESS;
}
catch (org.xml.sax.SAXException e) {
e.printStackTrace();
}
catch (javax.xml.parsers.ParserConfigurationException e) {
e.printStackTrace();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
/* method: createAttTable()
* ------------------------
* Takes the root element in a DOM and enters the tags
* into the tags table as an arraylist
*
*/
private void createAttTable (Element root) {
Node curTag = root.getFirstChild();
curTag = getNextTag(curTag, "tag");//start with first <tag> node
Tag thetag;
while (curTag != null) {
System.out.println("Current tag name is: " + getTagName(curTag));
if (curTag.getNodeName().toLowerCase().equals("tag")) {
thetag = analyzeAtts(curTag);
tags.put(getTagName(curTag), thetag);
}
curTag = getNextTag(curTag, "tag");
}
}
/* method: analyzeAtts()
* ---------------------
* Analyzes each child of the supplied tag. If the child is an attribute,
* the child Node is passed to checkFields to check if the attribute
* should be written.
*/
private Tag analyzeAtts(Node tagNode) {
Node bodyContentNode;
Node curAtt = getNextTag(tagNode.getFirstChild(), "attribute"); // go to first attribute
Node curField; // the current attribute field, ie. name,required, etc...
Node curFieldContent; // whatever content is inside the current field
String curFieldText; // the text data of the curFieldContent
String curFieldName; // the name of the current field Node
String attName = UNDEFINED; // the value of the attribute's "name" field
String attReq = UNDEFINED; // the value of the attribute's "required" field
Tag thetag = new Tag();
bodyContentNode = getNextTag(tagNode.getFirstChild(), "bodycontent"); // node containing value of bodycontent
if (bodyContentNode == null)
bodyContentNode = getNextTag(tagNode.getFirstChild(), "body-content"); // support for JSP 1.2 naming
if (bodyContentNode != null) { //set bodyContent based on text contained in body content node
String bodyContentText = ((Text)bodyContentNode.getFirstChild()).getData();
thetag.setBodyContent(bodyContentText.toLowerCase().equals("empty") ? false : true);
}
System.out.println("Analyzing attributes...");
while (curAtt != null) {
curField = curAtt.getFirstChild();
while (curField != null) { // store relevent attribute fields
if (curField.hasChildNodes()) {
curFieldContent = curField.getFirstChild();
curFieldName = curField.getNodeName().toLowerCase();
curFieldText = ((Text)curFieldContent).getData();
if (curFieldName != null && curFieldName.equals("name")) {
attName = curFieldText;
}
else if (curFieldName != null && curFieldName.equals("required")) {
attReq = curFieldText;
}
}
curField = curField.getNextSibling();
}
if (attName == null | attReq == null) {
//tag is malformed; either <name> or <required> does not exist
System.err.println("Warning - Malformed tag: " + getTagName(tagNode));
System.err.println("<name> and <required> are required fields in TLD");
attName = attReq = UNDEFINED;
}
else if (attName != UNDEFINED && attReq != UNDEFINED){
// add attName to the tag's atts list
thetag.addAtt(attName);
// if att is required, also add it to the reqAtts list
if (attReq.toLowerCase().equals("true")) {
thetag.reqAtts.add(attName);
}
System.out.println("Attribute = " + attName);
System.out.println("Required = " + attReq);
attName = attReq = UNDEFINED;
}
curAtt = curAtt.getNextSibling();
}
return thetag;
}
/* method: getNextTag()
* ----------------------
* Takes a Node object and returns the subsequent node that the getNodeName()
* method returns a string equal (case insensitive) to the supplied tagName.
*
*/
private Node getNextTag(Node curField, String tagName) {
Node nextTag = curField.getNextSibling();
//continue through DOM until next tag matching tagName is found
while (nextTag != null &&
!(nextTag.getNodeName().toLowerCase().equals(tagName.toLowerCase())))
{
nextTag = nextTag.getNextSibling();
}
return nextTag;
}
/* method: getTagName()
* ----------------------
* Takes a tag in a TLD DOM and returns a string version of the text data
* in the tag's <name> field.
*
*/
private String getTagName(Node tag) {
Node nameTag = getNextTag(tag.getFirstChild(), "name").getFirstChild();
return ((Text)nameTag).getData();
}
/* method: writeOutput()
* ---------------------
* Writes the out file(s) based on the file output mode.
* Currently a placeholder for future output formats.
*/
private void writeOutput() {
switch(mode) {
case ULTRADEV:
outputForUltraDev();
break;
default:
outputForUltraDev();
break;
}
}
/* method: outputForUltraDev()
* ---------------------------
* Writes the JavaScript (.js) and HTML (.html) files necessary to
* represent the floater to the current directory.
*/
private void outputForUltraDev() {
outputTaglibData();
}
/* method: outputTaglibData()
* --------------------------
* Outputs the taglib's TLD data, as a series of JavaScript
* associative array declarations, to the HTTP response object.
*
*/
private void outputTaglibData() {
Object[] tagNames = (tags.keySet().toArray());
Arrays.sort(tagNames);
String curName;
Object[] attributes, reqAttributes;
Tag curTag;
out.println("taglibs[\"" + outputFilePrefix + "\"]=[");
for (int i = 0; i < tagNames.length; i++) {
curName = (String)tagNames[i];
curTag = ((Tag)tags.get(curName));
out.print("\t[\"" + curName + "\", " + curTag.hasBodyContent() + ", [");
reqAttributes = ((ArrayList)(curTag.getReqAtts())).toArray();
for (int j = 0; j < reqAttributes.length; j++) {
out.print("\"" + reqAttributes[j] + "\"");
if (j < reqAttributes.length - 1) out.print(", ");
}
out.print("], [");
attributes = ((ArrayList)(curTag.getAtts())).toArray();
for (int k = 0; k < attributes.length; k++) {
out.print("\"" + attributes[k] + "\"");
if (k < attributes.length - 1) out.print(", ");
}
out.print("]");
/* easy to add any new information... */
if ( i >= tagNames.length - 1 ) out.println( "]];");
else
out.println("],");
}
}
/* method: outputTLDList()
* -----------------------
* Sends a tab-delimited list of TLDs in the servlet's TLDs directory
* to the http response out stream.
*
*/
private void outputTLDList(HttpServletRequest req) {
String tldpath = getServletConfig().getServletContext().getRealPath(PATH_TO_TLDS);
File dir = new File(tldpath);
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
out.print(files[i].substring(0,files[i].indexOf(".")));
if (i < files.length - 1) out.print("\t");
}
}
/** Public Accessors **/
/* method: setOutputPrefix()
* -----------------------
* Sets the name of the file to be written.
*
*/
public void setOutputPrefix(String prefix) {
outputFilePrefix = prefix.toLowerCase();
}
/* method: setOutputMode()
* -------------------------
* Sets the output mode of the parser. Available options listed at top
* under "Output Modes". Modify this method as output modes are added.
*
*/
public void setOutputMode(int outputMode) {
if (outputMode != ULTRADEV &&
outputMode != OTHER) {
System.err.println("Invalid output mode.");
}
else {
mode = outputMode;
}
}
/* method: getOutputMode()
* -----------------------
* Returns the parser's output mode.
*
*/
public int getOutputMode() {
return mode;
}
/* method: getResult()
* -------------------
* Returns the value of the result flag. True if all operations completed
* successfully.
*/
public int getResult() {
return result;
}
/* Private classes */
/* class: Tag
* ----------
* Private wrapper class. Stores an ArrayList of attributes, an ArrayList
* of required attributes (kept seperate for performance purposes) and a
* bodyContent boolean, set to true if the tag allows any body content.
*/
private class Tag {
private ArrayList atts = new ArrayList();
private ArrayList reqAtts = new ArrayList();
private boolean bodyContent;
public void addAtt (String att) {
if (att != null) {
System.out.println("Adding attribute: " + att);
atts.add(att);
}
}
public void addReqAtt (String att) {
if (att != null ) {
reqAtts.add(att);
}
}
public void setBodyContent(boolean bc) {
if (bc == true || bc == false) {
bodyContent = bc;
}
}
public ArrayList getAtts () {
return atts;
}
public ArrayList getReqAtts () {
return reqAtts;
}
public boolean hasBodyContent() {
return bodyContent;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -