KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > spi > webxml > util > WebXmlUtil


1 package org.enhydra.spi.webxml.util;
2
3 import java.io.*;
4 import java.util.*;
5 import org.w3c.dom.*;
6 import org.xml.sax.EntityResolver JavaDoc;
7 import javax.xml.parsers.*;
8 import javax.naming.*;
9 import org.xml.sax.InputSource JavaDoc;
10
11 /**
12  * <p>Title: </p>
13  * <p>Description: </p>
14  * <p>Copyright: Copyright (c) 2004</p>
15  * <p>Company: </p>
16  * @author Tanja Jovanovic
17  * @version 1.0
18  */

19
20 public class WebXmlUtil {
21
22  /**
23   * The associated file (if any).
24   */

25  protected File file = null;
26
27  /**
28   * Application's java:comp/env/ context.
29   */

30  private Context elements = null;
31
32   /**
33   * Document in which is xml document parsed.
34   */

35  private Document doc = null;
36
37  /**
38   * Root element (tag <web-app>) of document doc.
39   */

40  private Node xmlDoc = null;
41
42  /**
43   * Version of xml declaration of this xml file.
44   */

45  private String JavaDoc version;
46
47  /**
48   * Encoding of xml declaration of this xml file.
49   */

50  private String JavaDoc encoding;
51
52 /**
53  * Default constructor for an empty config file.
54  */

55  public WebXmlUtil () {
56    version = "";
57    encoding = "";
58  }
59
60 /**
61 * Constructor from a File. Allows to later write back the configuration to the
62 * same file.
63 * @param file The local file to parse.
64 * @exception IOException
65 * @exception XmlParseException
66 */

67  public WebXmlUtil(File file) throws XmlParseException, IOException {
68    this.file = file;
69    version = "";
70    encoding = "";
71 // read version and endocing from xml declaration, if it exists
72
this.readXmlDeclaration();
73    String JavaDoc name = file.getName();
74 // handle public id from xml declaration
75
// instead search on the Internet, the local dtd file is used
76
EntityResolver JavaDoc er = new PublicIdResolver();
77    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
78    factory.setValidating(false);
79    factory.setIgnoringElementContentWhitespace(false);
80    try {
81      DocumentBuilder builder = factory.newDocumentBuilder();
82      builder.setEntityResolver(er);
83      doc = builder.parse(file);
84    }
85    catch (Exception JavaDoc ex) {
86      ex.printStackTrace();
87      throw new XmlParseException (
88          "Error in reading configuration parameters from file.");
89    }
90    NodeList nl = doc.getChildNodes();
91    boolean found = false;
92    int i = 0;
93 // find root element of the Document (tag <web-app>)
94
while (i < nl.getLength() && !found) {
95      xmlDoc = nl.item(i);
96      if (xmlDoc.getNodeName().equalsIgnoreCase("web-app") &&
97          xmlDoc.getNodeType() == Document.ELEMENT_NODE)
98        found = true;
99      i++;
100    }
101  }
102
103  /**
104   * Reads version and encoding from xml declaration from xml file.
105   * If there is no declaration defined, the default values are used in writting
106   * into the xml file.
107   * Default values are: version = "1.0" and encoding = "UTF-8".
108   * @throws IOException
109   */

110  private void readXmlDeclaration() throws IOException {
111      String JavaDoc xmlHeader = "";
112      int length;
113      FileInputStream fi = new FileInputStream(file);
114      byte[] bChar = new byte[1];
115      int ok = fi.read(bChar);
116      String JavaDoc tempString = "";
117      if (ok != -1) {
118        String JavaDoc ch = new String JavaDoc(bChar);
119        if (ch.equalsIgnoreCase("<")) {
120          tempString = tempString + ch;
121          ok = fi.read(bChar);
122          while (ok != -1 && !new String JavaDoc(bChar).equalsIgnoreCase(">")) {
123            tempString = tempString + new String JavaDoc(bChar);
124            ok = fi.read(bChar);
125          }
126          if (ok != -1){
127            tempString = tempString + new String JavaDoc(bChar);
128            if (tempString.length() >= 5) {
129              if (tempString.substring(0, 5).equalsIgnoreCase("<?xml")) {
130                xmlHeader = tempString;
131              }
132            }
133          }
134        }
135      }
136      if (xmlHeader != null){
137        int index, startQuote, endQuote;
138        index = xmlHeader.indexOf("version");
139        if (index != -1){
140          startQuote = xmlHeader.indexOf("\"",(index+7));
141          if (startQuote != -1) {
142            endQuote = xmlHeader.indexOf("\"", startQuote + 1);
143            if ((endQuote != -1) && (startQuote+1 < endQuote)) {
144              version = xmlHeader.substring(startQuote + 1, endQuote);
145            }
146          }
147        }
148        index = xmlHeader.indexOf("encoding");
149        if (index != -1){
150          startQuote = xmlHeader.indexOf("\"",(index+8));
151          if (startQuote != -1) {
152            endQuote = xmlHeader.indexOf("\"", startQuote + 1);
153            if ((endQuote != -1) && (startQuote+1 < endQuote)) {
154              encoding = xmlHeader.substring(startQuote + 1, endQuote);
155            }
156          }
157        }
158      }
159      fi.close();
160  }
161
162 // tj 06.05.2004 needed for JNDI with <env-entry> tag
163
/**
164   * Parses the Document doc, got by transformation of the xml file.
165   * All configuration parameters (names, values and comments) are put in
166   * the Config object's HashTable.
167   * @param con Application's java:comp/env/ context.
168   * @throws ParseException
169   * @throws XmlParseException
170   */

171
172  public void parseTree(Context con) throws XmlParseException {
173     this.elements = con;
174     Node web = xmlDoc;
175     Node envParam = null;
176     Node param = null;
177     Node paramValue = null;
178 // Node deleteNode = null;
179

180     if ((web != null) && (web.getNodeName().equals("web-app"))) {
181       envParam = web.getFirstChild();
182       while (envParam != null) {
183         if (envParam.getNodeName().equals("env-entry")){
184           param = envParam.getFirstChild();
185           String JavaDoc paramNameString = null;
186           String JavaDoc paramValueString = null;
187           String JavaDoc paramTypeString = null;
188           String JavaDoc commentString = null;
189
190           while (param != null) {
191             if (param.getNodeName().equals("env-entry-name")){
192               paramValue = param.getFirstChild();
193               try {
194                 paramNameString = paramValue.getNodeValue();
195               }
196               catch (Exception JavaDoc ex ){
197                 throw new XmlParseException("Error in parsing <env-entry-name> tag.");
198               }
199             }
200             else {
201               if (param.getNodeName().equals("env-entry-value")){
202                 paramValue = param.getFirstChild();
203                 if (paramValue == null){
204                    paramValueString = new String JavaDoc("");
205                    param.appendChild(doc.createTextNode(paramValueString));
206                    paramValue = param.getFirstChild();
207                 }
208
209                 else {
210                    try {
211                       paramValueString = paramValue.getNodeValue();
212                    }
213                    catch (Exception JavaDoc ex) {
214                       throw new XmlParseException(
215                             "Error in parsing <env-entry-value> tag.");
216                    }
217                 }
218               }
219               else{
220                 if (param.getNodeName().equals("env-entry-type")){
221                   paramValue = param.getFirstChild();
222                   if (paramValue != null) {
223                       paramTypeString = paramValue.getNodeValue();
224                   }
225 // else{
226
// deleteNode=param;
227
// paramTypeString = "";
228
// }
229
}
230               }
231             }
232
233             param = param.getNextSibling();
234 /*
235             if (deleteNode != null){
236                envParam.removeChild((Node)(deleteNode));
237                deleteNode = null;
238             }
239 */

240           } // while (param != null)
241
if ((paramNameString == null) || (paramValueString == null) || (paramTypeString == null)) {
242             throw new XmlParseException(
243                 "Error in parsing configuration parameters.");
244           }
245 // if (commentString == null)
246
commentString = "";
247           paramNameString = paramNameString.trim();
248
249           int len = paramNameString.length();
250           if ((len>2) && (paramNameString.substring(len-2).equals("[]"))){
251 // paramNameString = paramNameString.substring(0, len-2);
252
StringTokenizer tok = new StringTokenizer(paramValueString,
253                   new String JavaDoc(","));
254               String JavaDoc[] stringArray = new String JavaDoc[tok.countTokens()];
255               int i = 0;
256               while (tok.hasMoreTokens()) {
257                 stringArray[i] = tok.nextToken().trim();
258                 i++;
259               }
260               try {
261                 elements.rebind(paramNameString, stringArray);
262               }
263               catch (Exception JavaDoc e){
264                 throw new XmlParseException(
265                 "Error in rebinding configuration array parameters.");
266               }
267           }
268           else {
269             try {
270                 elements.rebind(paramNameString, paramValueString);
271               }
272               catch (Exception JavaDoc e){
273                 throw new XmlParseException(
274                 "Error in rebinding configuration parameters.");
275               }
276          }
277        } // if (envParam.getNodeName().equals("env-entry"))
278
envParam = envParam.getNextSibling();
279       } // while (envParam != null)
280
} // if
281
}
282
283  public class PublicIdResolver implements EntityResolver JavaDoc {
284   public PublicIdResolver () {
285        super();
286   }
287
288   public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) {
289     String JavaDoc Resource23 = "/org/enhydra/util/dtd/webXml2_3.dtd";
290     String JavaDoc Resource24 = "/org/enhydra/util/dtd/webXml2_4.dtd";
291      try {
292        if (publicId != null) {
293          // return a special input source
294
if (publicId.equals("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN")) {
295             return new InputSource JavaDoc(this.getClass().getResource(Resource23).toString());
296          }
297          else {
298             if (publicId.equals("-//Sun Microsystems, Inc.//DTD Web Application 2.4//EN")) {
299                return new InputSource JavaDoc(this.getClass().getResource(Resource24).toString());
300             }
301             else {
302                return new InputSource JavaDoc(this.getClass().getResource(Resource23).toString());
303             }
304
305          }
306        }
307      }
308      catch (Exception JavaDoc e){
309        System.out.println("Resolver Entity Error.");
310        e.printStackTrace();
311      }
312      // use the default behaviour
313
return null;
314    }
315  }
316
317 }
Popular Tags