KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > util > XMLConfigFile


1  /*
2   * Enhydra Java Application Server Project
3   *
4   * The contents of this file are subject to the Enhydra Public License
5   * Version 1.1 (the "License"); you may not use this file except in
6   * compliance with the License. You may obtain a copy of the License on
7   * the Enhydra web site ( http://www.enhydra.org/ ).
8   *
9   * Software distributed under the License is distributed on an "AS IS"
10   * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11   * the License for the specific terms governing rights and limitations
12   * under the License.
13   *
14   * The Initial Developer of the Enhydra Application Server is Lutris
15   * Technologies, Inc. The Enhydra Application Server and portions created
16   * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17   * All Rights Reserved.
18   *
19   * Contributor(s):
20   *
21   * $Id: XMLConfigFile.java,v 1.1 2005/07/13 11:09:06 slobodan Exp $
22   */

23 package org.enhydra.util;
24
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.util.Vector JavaDoc;
32
33 import javax.xml.parsers.DocumentBuilder JavaDoc;
34 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
35
36 import org.apache.xml.serialize.OutputFormat;
37 import org.apache.xml.serialize.XMLSerializer;
38 import org.w3c.dom.Document JavaDoc;
39 import org.w3c.dom.Node JavaDoc;
40 import org.w3c.dom.NodeList JavaDoc;
41 import org.xml.sax.EntityResolver JavaDoc;
42 import org.xml.sax.InputSource JavaDoc;
43
44 import com.lutris.util.Config;
45 import com.lutris.util.ConfigException;
46 import com.lutris.util.KeywordValueException;
47 import com.lutris.util.KeywordValueTable;
48 import com.lutris.util.ParseException;
49
50    /**
51     * XMLConfigFile is used to manipulate application's web.xml file to read its
52     * configuration parameters.
53     *
54     * @see Config, ConfigFileInterface, AbsConfigFile
55     * @author Tanja Jovanovic
56     * @version 1.0
57     */

58
59 public class XMLConfigFile extends AbsConfigFile{
60
61   /**
62    * Document in which is xml document parsed.
63    */

64   private Document JavaDoc doc = null;
65
66   /**
67    * Root element (tag <web-app>) of document doc.
68    */

69   private Node JavaDoc xmlDoc = null;
70
71   /**
72    * Version of xml declaration of this xml file.
73    */

74   private String JavaDoc version;
75
76   /**
77    * Encoding of xml declaration of this xml file.
78    */

79   private String JavaDoc encoding;
80
81  /**
82   * Default constructor for an empty config file.
83   */

84   public XMLConfigFile () {
85     super();
86     version = "";
87     encoding = "";
88   }
89
90 /**
91  * Constructor from an InputStream.
92  * @param inputStream The input stream from which to parse the config file.
93  * @exception ConfigException
94  */

95 /*
96   public XMLConfigFile (InputStream inputStream) throws ConfigException {
97   }
98 */

99
100 /**
101  * Constructor from a File. Allows to later write back the configuration to the
102  * same file.
103  * @param file The local file to parse.
104  * @exception IOException
105  * @exception ConfigException
106  */

107   public XMLConfigFile (File JavaDoc file) throws ConfigException, IOException JavaDoc {
108     super(file);
109     version = "";
110     encoding = "";
111    // read version and endocing from xml declaration, if it exists
112
this.readXmlDeclaration();
113    String JavaDoc name = file.getName();
114    // handle public id from xml declaration
115
// instead search on the Internet, the local dtd file is used
116
EntityResolver JavaDoc er = new PublicIdResolver();
117       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
118      factory.setValidating(false);
119       factory.setIgnoringElementContentWhitespace(false);
120       try {
121         DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
122         builder.setEntityResolver(er);
123         doc = builder.parse(file);
124       }
125       catch (Exception JavaDoc ex){
126         //ex.printStackTrace();
127
throw new ConfigException("Error in reading configuration parameters from file.");
128
129       }
130
131       NodeList JavaDoc nl = doc.getChildNodes();
132       boolean found = false;
133       int i = 0;
134
135 // find root element of the Document (tag <web-app>)
136
while (i<nl.getLength() && !found){
137          xmlDoc = nl.item(i);
138          if (xmlDoc.getNodeName().equalsIgnoreCase("web-app") && xmlDoc.getNodeType() == Document.ELEMENT_NODE)
139             found = true;
140          i++;
141       }
142 // tj 08.02.2004 needed for JNDI with <context-param> tag
143
// tj 06.05.2004 needed for JNDI with <env-entry> tag
144
// tj 24.05.2004 put under comment: there is JNDI SPI for parsing unpacked web.xml file
145
/*
146    try {
147       this.parseTree();
148     }
149     catch (Exception e) {
150       throw new ConfigException(ConfigException.SYNTAX, e.getMessage());
151     }
152 */

153   }
154
155 /**
156  * Constructor from a KeywordValueTable.
157  * @param kvt A KeywordValueTable from which to populate the xml file.
158  * @exception ConfigException
159  */

160   public XMLConfigFile (KeywordValueTable kvt) throws ConfigException {
161     super(kvt);
162     version = "";
163     encoding = "";
164   }
165
166 /**
167  * Reads application configuration parameters by using JNDI Context.
168  */

169  protected void readJndi() throws ConfigException {
170     try {
171        if (jndiAdapt == null){
172           try {
173              jndiAdapt = new JNDIAdapter(this.file.getAbsolutePath(), "org.enhydra.spi.webxml.WebXmlInitialContextFactory");
174           }
175           catch(Exception JavaDoc e){
176              jndiAdapt = new JNDIAdapter();
177           }
178        }
179        String JavaDoc[] leafKeys = jndiAdapt.leafKeys();
180        if (leafKeys != null) {
181           int leafKeysLength = leafKeys.length;
182           String JavaDoc newKey = null;
183           String JavaDoc stringValue;
184           String JavaDoc[] stringValues;
185           for (int i=0; i<leafKeysLength; i++){
186              String JavaDoc leafKey = leafKeys[i];
187              if (leafKey != null) {
188                 if (jndiAdapt.isArray(leafKey)){
189                    newKey = jndiAdapt.removeArrayMark(leafKey);
190                    if (newKey !=null) {
191                       stringValues = jndiAdapt.getStrings(newKey);
192                       newKey = jndiAdapt.makeConfigString(newKey);
193                       config.set(newKey, stringValues);
194                       if (!order.contains(newKey))
195                          order.addElement(newKey);
196                       comments.put(newKey, "");
197                    }
198                 } // if (jndiAdapt.isArray(leafKey))
199
else {
200                    Object JavaDoc ovalue = jndiAdapt.get(leafKey);
201                    newKey = jndiAdapt.makeConfigString(leafKey);
202
203 // stringValue = (String)jndiAdapt.get(leafKey);
204
if (ovalue instanceof java.lang.String JavaDoc){
205                       stringValue = (String JavaDoc)ovalue;
206                       if (stringValue.startsWith("jndi:")){
207                          stringValue = stringValue.substring(5);
208                          Object JavaDoc resource = jndiAdapt.getResource(stringValue);
209              
210                          if (resource != null) {
211                             config.set(newKey, resource);
212                             jndiParameterNames.put(newKey,stringValue);
213                          }
214                          else {
215                             config.set(newKey, "jndi:"+stringValue);
216                          }
217                       } // if (stringValue.startsWith("jndi:"))
218
else {
219                          config.set(newKey, stringValue);
220                       }
221                       if (!order.contains(newKey))
222                          order.addElement(newKey);
223                       comments.put(newKey, "");
224                    } // if (ovalue instanceof java.lang.String)
225
else {
226                    }
227                 } // else from if (jndiAdapt.isArray(leafKey))
228
} // if (leafKey != null)
229
} // for
230
} // if (leafKeys != null)
231
} // try
232
catch (Exception JavaDoc e){
233         //System.err.println("Error readJndi");
234
//e.printStackTrace();
235
throw new ConfigException("Error in reading JNDI configuration parameters.");
236     }
237   }
238
239   /**
240    * Reads version and encoding from xml declaration from xml file.
241    * If there is no declaration defined, the default values are used in writting
242    * into the xml file.
243    * Default values are: version = "1.0" and encoding = "UTF-8".
244    * @throws IOException
245    */

246   private void readXmlDeclaration() throws IOException JavaDoc {
247       String JavaDoc xmlHeader = "";
248       int length;
249       FileInputStream JavaDoc fi = new FileInputStream JavaDoc(file);
250       byte[] bChar = new byte[1];
251       int ok = fi.read(bChar);
252       String JavaDoc tempString = "";
253       if (ok != -1) {
254         String JavaDoc ch = new String JavaDoc(bChar);
255         if (ch.equalsIgnoreCase("<")) {
256           tempString = tempString + ch;
257           ok = fi.read(bChar);
258           while (ok != -1 && !new String JavaDoc(bChar).equalsIgnoreCase(">")) {
259             tempString = tempString + new String JavaDoc(bChar);
260             ok = fi.read(bChar);
261           }
262           if (ok != -1){
263             tempString = tempString + new String JavaDoc(bChar);
264             if (tempString.length() >= 5) {
265               if (tempString.substring(0, 5).equalsIgnoreCase("<?xml")) {
266                 xmlHeader = tempString;
267               }
268             }
269           }
270         }
271       }
272       if (xmlHeader != null){
273         int index, startQuote, endQuote;
274         index = xmlHeader.indexOf("version");
275         if (index != -1){
276           startQuote = xmlHeader.indexOf("\"",(index+7));
277           if (startQuote != -1) {
278             endQuote = xmlHeader.indexOf("\"", startQuote + 1);
279             if ((endQuote != -1) && (startQuote+1 < endQuote)) {
280               version = xmlHeader.substring(startQuote + 1, endQuote);
281             }
282           }
283         }
284         index = xmlHeader.indexOf("encoding");
285         if (index != -1){
286           startQuote = xmlHeader.indexOf("\"",(index+8));
287           if (startQuote != -1) {
288             endQuote = xmlHeader.indexOf("\"", startQuote + 1);
289             if ((endQuote != -1) && (startQuote+1 < endQuote)) {
290               encoding = xmlHeader.substring(startQuote + 1, endQuote);
291             }
292           }
293         }
294       }
295       fi.close();
296   }
297
298 // tj 08.02.2004 needed for JNDI with <context-param> tag
299
/**
300    * Parses the Document doc, got by transformation of the xml file.
301    * All configuration parameters (names, values and comments) are put in
302    * the Config object's HashTable.
303    * @throws ParseException
304    * @throws KeywordValueException
305    */

306 /*
307   private void parseTree() throws ParseException, KeywordValueException {
308      Node web = xmlDoc;
309      Node contextParam = null;
310      Node param = null;
311      Node paramValue = null;
312      Node deleteNode = null;
313
314      if ((web != null) && (web.getNodeName().equals("web-app"))) {
315        contextParam = web.getFirstChild();
316        while (contextParam != null) {
317          if (contextParam.getNodeName().equals("context-param")){
318            param = contextParam.getFirstChild();
319            String paramNameString = null;
320            String paramValueString = null;
321            String commentString = null;
322            while (param != null) {
323              if (param.getNodeName().equals("param-name")){
324                paramValue = param.getFirstChild();
325                try {
326                  paramNameString = paramValue.getNodeValue();
327                }
328                catch (Exception ex ){
329                  throw new KeywordValueException("Error in parsing <param-name> tag.");
330                }
331              }
332              else {
333                if (param.getNodeName().equals("param-value")){
334                  paramValue = param.getFirstChild();
335                  if (paramValue == null){
336                     paramValueString = new String("");
337                     param.appendChild(doc.createTextNode(paramValueString));
338                     paramValue = param.getFirstChild();
339                  }
340
341                  else {
342                     try {
343                        paramValueString = paramValue.getNodeValue();
344                     }
345                     catch (Exception ex) {
346                        throw new KeywordValueException(
347                              "Error in parsing <param-value> tag.");
348                     }
349                  }
350                }
351                else{
352                  if (param.getNodeName().equals("description")){
353                    paramValue = param.getFirstChild();
354                    if (paramValue != null) {
355                        commentString = paramValue.getNodeValue();
356                    }
357                      else{
358                        deleteNode=param;
359                         commentString = "";
360                      }
361                  }
362                }
363              }
364
365              param = param.getNextSibling();
366              if (deleteNode != null){
367                 contextParam.removeChild((Node)(deleteNode));
368                 deleteNode = null;
369              }
370            } // while (param != null)
371            if ((paramNameString == null) || (paramValueString == null)) {
372              throw new KeywordValueException(
373                  "Error in parsing configuration parameters.");
374            }
375            if (commentString == null)
376              commentString = "";
377            paramNameString = paramNameString.trim();
378
379            int len = paramNameString.length();
380            if ((len>2) && (paramNameString.substring(len-2).equals("[]"))){
381                paramNameString = paramNameString.substring(0, len-2);
382                StringTokenizer tok = new StringTokenizer(paramValueString,
383                    new String(","));
384                String[] stringArray = new String[tok.countTokens()];
385                int i = 0;
386                while (tok.hasMoreTokens()) {
387                  stringArray[i] = tok.nextToken().trim();
388                  i++;
389                }
390                addEntry(jndiAdapt.makeConfigString(paramNameString), stringArray, commentString);
391                if (jndiAdapt != null) {
392                   String jndiName = JNDIAdapter.makeContextString(paramNameString);
393                   try {
394                     jndiAdapt.set(jndiName+"[]", paramValueString);
395                   }
396                   catch(Exception ex){}
397                }
398            }
399            else {
400              addEntry(jndiAdapt.makeConfigString(paramNameString), paramValueString, commentString);
401              if (jndiAdapt != null) {
402                 String jndiName = JNDIAdapter.makeContextString(paramNameString);
403                 try {
404                     jndiAdapt.set(paramNameString, paramValueString);
405                 }
406                 catch(Exception ex){}
407
408              }
409            }
410         } // if (contextParam.getNodeName().equals("context-param"))
411        contextParam = contextParam.getNextSibling();
412        } // while (contextParam != null)
413      } // if
414 */

415
416 // tj 06.05.2004 needed for JNDI with <env-entry> tag
417
/**
418    * Parses the Document doc, got by transformation of the xml file.
419    * All configuration parameters (names, values and comments) are put in
420    * the Config object's HashTable.
421    * @throws ParseException
422    * @throws KeywordValueException
423    */

424
425   private void parseTree() throws ParseException, KeywordValueException {
426      Node JavaDoc web = xmlDoc;
427      Node JavaDoc envParam = null;
428      Node JavaDoc param = null;
429      Node JavaDoc paramValue = null;
430      Node JavaDoc deleteNode = null;
431
432      if ((web != null) && (web.getNodeName().equals("web-app"))) {
433        envParam = web.getFirstChild();
434        while (envParam != null) {
435          if (envParam.getNodeName().equals("env-entry")){
436            param = envParam.getFirstChild();
437            String JavaDoc paramNameString = null;
438            String JavaDoc paramValueString = null;
439            String JavaDoc paramTypeString = null;
440            String JavaDoc commentString = null;
441
442            while (param != null) {
443              if (param.getNodeName().equals("env-entry-name")){
444                paramValue = param.getFirstChild();
445                try {
446                  paramNameString = paramValue.getNodeValue();
447                }
448                catch (Exception JavaDoc ex ){
449                  throw new KeywordValueException("Error in parsing <env-entry-name> tag.");
450                }
451              }
452              else {
453                if (param.getNodeName().equals("env-entry-value")){
454                  paramValue = param.getFirstChild();
455                  if (paramValue == null){
456                     paramValueString = new String JavaDoc("");
457                     param.appendChild(doc.createTextNode(paramValueString));
458                     paramValue = param.getFirstChild();
459                  }
460
461                  else {
462                     try {
463                        paramValueString = paramValue.getNodeValue();
464                     }
465                     catch (Exception JavaDoc ex) {
466                        throw new KeywordValueException(
467                              "Error in parsing <env-entry-value> tag.");
468                     }
469                  }
470                }
471                else{
472                  if (param.getNodeName().equals("env-entry-type")){
473                    paramValue = param.getFirstChild();
474                    if (paramValue != null) {
475                        paramTypeString = paramValue.getNodeValue();
476                    }
477 // else{
478
// deleteNode=param;
479
// paramTypeString = "";
480
// }
481
}
482                }
483              }
484
485              param = param.getNextSibling();
486              if (deleteNode != null){
487                 envParam.removeChild((Node JavaDoc)(deleteNode));
488                 deleteNode = null;
489              }
490            } // while (param != null)
491
if ((paramNameString == null) || (paramValueString == null) || (paramTypeString == null)) {
492              throw new KeywordValueException(
493                  "Error in parsing configuration parameters.");
494            }
495 // if (commentString == null)
496
commentString = "";
497            paramNameString = paramNameString.trim();
498
499            int len = paramNameString.length();
500            if ((len>2) && (paramNameString.substring(len-2).equals("[]"))){
501                paramNameString = paramNameString.substring(0, len-2);
502                StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(paramValueString,
503                    new String JavaDoc(","));
504                String JavaDoc[] stringArray = new String JavaDoc[tok.countTokens()];
505                int i = 0;
506                while (tok.hasMoreTokens()) {
507                  stringArray[i] = tok.nextToken().trim();
508                  i++;
509                }
510                addEntry(JNDIAdapter.makeConfigString(paramNameString), stringArray, commentString);
511                if (jndiAdapt != null) {
512                   String JavaDoc jndiName = JNDIAdapter.makeContextString(paramNameString);
513                   try {
514                     jndiAdapt.set(jndiName+"[]", paramValueString);
515                   }
516                   catch(Exception JavaDoc ex){}
517                }
518            }
519            else {
520              addEntry(JNDIAdapter.makeConfigString(paramNameString), paramValueString, commentString);
521              if (jndiAdapt != null) {
522                 String JavaDoc jndiName = JNDIAdapter.makeContextString(paramNameString);
523                 try {
524                     jndiAdapt.set(paramNameString, paramValueString);
525                 }
526                 catch(Exception JavaDoc ex){}
527
528              }
529            }
530         } // if (envParam.getNodeName().equals("env-entry"))
531
envParam = envParam.getNextSibling();
532        } // while (envParam != null)
533
} // if
534
}
535
536
537 /**
538  * Writes out a xml file to the OutputStream specified. Note that Objects
539  * other than String or String[] will be converted into a String.
540  * @param outputStream The output stream on which to write the config file.
541  */

542 public void write(OutputStream JavaDoc outputStream) {
543   try {
544 // tj 08.02.2004 needed for JNDI with <context-param> tag
545
// this.updateTree();
546

547     this.updateEnvEntryTagInTree();// tj 08.02.2004 JNDI with <env-entry> tag
548

549   }
550   catch (Exception JavaDoc ex){
551     System.out.println("Error in writting file.");
552     //ex.printStackTrace();
553
}
554   try {
555       FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(file);
556       OutputFormat of = new OutputFormat();
557       of.setIndenting(true);
558       of.setIndent(2);
559 // of.setMethod(Method.XML);
560
// of.setPreserveSpace(false);
561
of.setLineWidth(79);
562       if (!version.equals("")) {
563         of.setVersion(version);
564       }
565       if (!encoding.equals("")) {
566         of.setEncoding(encoding);
567       }
568       XMLSerializer out = new XMLSerializer(os, of);
569       out.serialize(doc);
570       os.close();
571     }
572     catch (Exception JavaDoc ex){
573       System.out.println("Error in writing file.");
574       //ex.printStackTrace();
575
}
576 }
577
578 // tj 08.02.2004 needed for JNDI with <context-param> tag
579
/**
580  * Updates the document doc with changes (added, apdated and removed entries).
581  * @throws KeywordValueException
582  */

583 /*
584   private void updateTree() throws KeywordValueException {
585       Node web = xmlDoc;
586       Node contextParam = null;
587       Node placeToAdd = null;
588       Node param = null;
589       Node paramValue = null;
590       Vector allParams = (Vector)order.clone();
591       Node deleteNode = null;
592
593       if ((web != null) && (web.getNodeName().equals("web-app"))) {
594         contextParam = web.getFirstChild();
595         while (contextParam != null) {
596           if (contextParam.getNodeName().equals("context-param")){
597  // placeToAdd = contextParam;
598             param = contextParam.getFirstChild();
599             String paramNameString = null;
600             String commentString = null;
601             Node paramValueNode = null;
602             Node commentNode = null;
603             Node descriptionNode = null;
604             String arrayIndicator = "";
605             int paramLength =0;
606             while (param != null) {
607               if (param.getNodeName().equals("param-name")){
608                 paramValue = param.getFirstChild();
609                 paramNameString = paramValue.getNodeValue();
610                 paramLength = paramNameString.length();
611                 if ((paramLength>2)&&(paramNameString.substring(paramLength-2).equals("[]"))){
612                   paramNameString = paramNameString.substring(0, paramLength-2);
613                   arrayIndicator = "[]";
614                 }
615               }
616               else {
617                 if (param.getNodeName().equals("param-value")){
618                   paramValueNode = param;
619                   paramValue = param.getFirstChild();
620                   paramValueNode = paramValue;
621                 }
622                 else{
623                   if (param.getNodeName().equals("description")){
624 // commentNode = param;
625                     descriptionNode = param;
626                     paramValue = param.getFirstChild();
627                     commentNode = paramValue;
628                     if (paramValue != null){
629                       commentString = paramValue.getNodeValue();
630                     }
631                     else {
632                        commentString = "";
633                     }
634                   }
635                 }
636               }
637               param = param.getNextSibling();
638             } // while (param != null)
639             if (allParams.contains(paramNameString)){
640               boolean doComment = true;
641               Object newValue;
642                String newValueString;
643                String newComment;
644                newValue = config.get(paramNameString);
645                newComment = (String)comments.get(paramNameString);
646                if (arrayIndicator.equals("")) { // node isn't array
647                  if (!newValue.getClass().isArray()){ // conf param is not array
648                    newValueString = newValue.toString();
649                    paramValueNode.setNodeValue(newValueString);
650 // paramValueNode.setNodeValue("hello");
651                    allParams.remove(paramNameString);
652                  }
653                  else { // node isn't array but the config param is
654                    deleteNode = contextParam;
655                    doComment = false;
656                  }
657                }
658                else { // node is array
659                  if (!newValue.getClass().isArray()){ // conf param is not array
660                    deleteNode = contextParam;
661                    doComment = false;
662                  }
663                  else { // node is array and the config param is also
664                    String[] s = (String[]) newValue;
665                    int len = s.length;
666                    if (len > 0) {
667                       newValueString = s[0].trim();
668                       if (s.length > 1){
669                          for (int i = 1; i < s.length; i++) {
670                             newValueString = newValueString.concat(", ");
671                             newValueString = newValueString.concat(s[i].trim());
672                          }
673                       }
674                    }
675                    else
676                       newValueString = new String("");
677                    paramValueNode.setNodeValue(newValueString);
678                    allParams.remove(paramNameString);
679                  }
680                }
681 // paramValueNode.setNodeValue(newValue);
682                if (doComment) {
683                  if (commentNode != null) {
684                    if (!newComment.equals(""))
685                      commentNode.setNodeValue(newComment);
686                    else
687                      contextParam.removeChild(descriptionNode);
688                  }
689                  else {
690                    if ( (newComment != null) && (!newComment.equals(""))) {
691                      if (descriptionNode != null) {
692                        descriptionNode.appendChild(doc.createTextNode( (String)
693                            newComment));
694                      }
695                      else {
696                        descriptionNode = doc.createElement("description");
697                        descriptionNode.appendChild(doc.createTextNode( ( (String)
698                            newComment)));
699                        contextParam.appendChild(descriptionNode);
700                      }
701                    }
702                  }
703                }
704 // allParams.remove(paramNameString);
705              }
706              else {
707                 deleteNode = contextParam;
708              }
709
710
711           } // if (contextParam.getNodeName().equals("context-param"))
712         contextParam = contextParam.getNextSibling();
713         if (deleteNode != null){
714            web.removeChild((Node)deleteNode);
715            deleteNode = null;
716         }
717         } // while (contextParam != null)
718       } // if
719 // if (placeToAdd != null) {
720 // System.out.println("placeToAdd != null");
721 // placeToAdd = placeToAdd.getNextSibling();
722 // }
723 // else {
724 // System.out.println("placeToAdd == null");
725          placeToAdd = findPlaceInTree();
726  // }
727        Node newNode;
728        for (int i=0; i<allParams.size(); i++) {
729          newNode = createNewContextParam((String)allParams.elementAt(i));
730 // placeToAdd = web.insertBefore(newNode, placeToAdd);
731          web.insertBefore(newNode, placeToAdd);
732       }
733   } // end of updateTree() method
734 */

735
736
737 /**
738  * Updates the document doc with changes (added, apdated and removed entries).
739  * @throws KeywordValueException
740  */

741   private void updateEnvEntryTagInTree() throws KeywordValueException {
742   // tj 08.02.2004 for JNDI with <env-entry> tag
743
Node JavaDoc web = xmlDoc;
744       Node JavaDoc envEntryParam = null;
745       Node JavaDoc placeToAdd = null;
746       Node JavaDoc param = null;
747       Node JavaDoc paramValue = null;
748       Vector JavaDoc allParams = (Vector JavaDoc)order.clone();
749       Node JavaDoc deleteNode = null;
750       if ((web != null) && (web.getNodeName().equals("web-app"))) {
751         envEntryParam = web.getFirstChild();
752         while (envEntryParam != null) {
753           if (envEntryParam.getNodeName().equals("env-entry")){
754  // placeToAdd = envEntryParam;
755
param = envEntryParam.getFirstChild();
756             String JavaDoc paramNameString = null;
757             String JavaDoc paramType = null;
758             String JavaDoc commentString = null;
759             Node JavaDoc paramValueNode = null;
760             Node JavaDoc paramNodeForNullValue = null;
761             Node JavaDoc commentNode = null;
762             Node JavaDoc descriptionNode = null;
763             String JavaDoc arrayIndicator = "";
764             int paramLength =0;
765             while (param != null) {
766               if (param.getNodeName().equals("env-entry-name")){
767                 paramValue = param.getFirstChild();
768                 paramNameString = paramValue.getNodeValue();
769                 paramLength = paramNameString.length();
770                 if ((paramLength>2)&&(paramNameString.substring(paramLength-2).equals("[]"))){
771                   paramNameString = paramNameString.substring(0, paramLength-2);
772                   arrayIndicator = "[]";
773                 }
774               }
775               else {
776                 if (param.getNodeName().equals("env-entry-value")){
777                   paramNodeForNullValue = param;
778                   paramValue = param.getFirstChild();
779                   paramValueNode = paramValue;
780                 }
781                 else{
782                   if (param.getNodeName().equals("env-entry-type")){
783                     paramValue = param.getFirstChild();
784                     paramType = paramValue.getNodeValue();
785                   }
786                   else {
787                     if (param.getNodeName().equals("description")){
788   // commentNode = param;
789
descriptionNode = param;
790                       paramValue = param.getFirstChild();
791                       commentNode = paramValue;
792                       if (paramValue != null){
793                         commentString = paramValue.getNodeValue();
794                       }
795                       else {
796                          commentString = "";
797                       }
798                     }
799                   }
800                 }
801               }
802               param = param.getNextSibling();
803             } // while (param != null)
804
if (allParams.contains(JNDIAdapter.makeConfigString(paramNameString))){
805               boolean doComment = true;
806               Object JavaDoc newValue;
807               String JavaDoc newValueString;
808               String JavaDoc newComment;
809                newValue = config.get(JNDIAdapter.makeConfigString(paramNameString));
810                newComment = (String JavaDoc)comments.get(JNDIAdapter.makeConfigString(paramNameString));
811                if (arrayIndicator.equals("")) { // node isn't array
812
if ((!newValue.getClass().isArray()) && (paramType.trim().equals("java.lang.String"))) {
813                    // env-entry param is not array
814
//Enumeration e = jndiParameterNames.keys();
815
//while (e.hasMoreElements()) {
816
//System.out.println("elem: " + (String)e.nextElement());
817
//}
818
if (jndiParameterNames.containsKey(JNDIAdapter.makeConfigString(paramNameString))){
819                       newValueString = "jndi:" + (String JavaDoc)jndiParameterNames.get(JNDIAdapter.makeConfigString(paramNameString));
820 // jndiParameterNames.remove(JNDIAdapter.makeConfigString(paramNameString));
821
}
822                    else {
823                     newValueString = newValue.toString();
824                    }
825
826                    if (paramValueNode == null) {
827                       paramNodeForNullValue.appendChild(doc.createTextNode(newValueString));
828                    }
829                    else
830                      paramValueNode.setNodeValue(newValueString);
831                    allParams.remove(jndiAdapt.makeConfigString(paramNameString));
832                  }
833                  else { // node isn't array but the config param is
834
deleteNode = envEntryParam;
835                    doComment = false;
836                  }
837                }
838                else { // node is array
839
if (!newValue.getClass().isArray()){ // env-entry param is not array
840
deleteNode = envEntryParam;
841                    doComment = false;
842                  }
843                  else {
844                    if (paramType.trim().equals("java.lang.String")) { // env-entry is array and the config param is also
845
String JavaDoc[] s = (String JavaDoc[]) newValue;
846                      int len = s.length;
847                      if (len > 0) {
848                         newValueString = s[0].trim();
849                         if (s.length > 1){
850                            for (int i = 1; i < s.length; i++) {
851                               newValueString = newValueString.concat(", ");
852                               newValueString = newValueString.concat(s[i].trim());
853                            }
854                         }
855                      }
856                      else
857                         newValueString = new String JavaDoc("");
858                      paramValueNode.setNodeValue(newValueString);
859                      allParams.remove(JNDIAdapter.makeConfigString(paramNameString));
860                     }
861                     else {
862                       deleteNode = envEntryParam;
863                       doComment = false;
864                     }
865                  }
866                }
867 // paramValueNode.setNodeValue(newValue);
868
if (doComment) {
869                  if (commentNode != null) {
870                    if (!newComment.equals(""))
871                      commentNode.setNodeValue(newComment);
872                    else
873                      envEntryParam.removeChild(descriptionNode);
874                  }
875                  else {
876                    if ( (newComment != null) && (!newComment.equals(""))) {
877                      if (descriptionNode != null) {
878                        descriptionNode.appendChild(doc.createTextNode( (String JavaDoc)
879                            newComment));
880                      }
881                      else {
882                        descriptionNode = doc.createElement("description");
883                        descriptionNode.appendChild(doc.createTextNode( ( (String JavaDoc)
884                            newComment)));
885                        envEntryParam.appendChild(descriptionNode);
886                      }
887                    }
888                  }
889                }
890 // allParams.remove(paramNameString);
891
}
892              else {
893                 deleteNode = envEntryParam;
894              }
895
896           } // if (envEntryParam.getNodeName().equals("context-param"))
897
envEntryParam = envEntryParam.getNextSibling();
898         if (deleteNode != null){
899            web.removeChild((Node JavaDoc)deleteNode);
900            deleteNode = null;
901         }
902         } // while (envEntryParam != null)
903
} // if
904

905 // tj 08.02.2004 needed for JNDI with <context-param> tag
906
// placeToAdd = findPlaceInTree();
907
// tj 08.02.2004 needed for JNDI with <env-entry> tag
908
// placeToAdd = findEnvEntryPlaceInTree();
909
// placeToAdd = findPlaceInTree();
910
Node JavaDoc newNode;
911       for (int i=0; i<allParams.size(); i++) {
912 // tj 08.02.2004 needed for JNDI with <context-param> tag
913
// newNode = createNewContextParam((String)allParams.elementAt(i));
914
// tj 08.02.2004 needed for JNDI with <env-entry> tag
915
newNode = createNewEnvEntry((String JavaDoc)allParams.elementAt(i));// config form of key
916

917 // placeToAdd = web.insertBefore(newNode, placeToAdd);
918
web.insertBefore(newNode, placeToAdd);
919       }
920   } // end of updateEnvEntryTagInTree() method
921

922
923 // tj 08.02.2004 needed for JNDI with <context-param> tag
924
/**
925    * Creates new <context-param> node with all necessary sub-nodes for new entry.
926    * @param key Name of the parameter for which is new node created.
927    * @return Created <context-param> node with its sub-nodes.
928    * @throws KeywordValueException
929    */

930 /*
931   private Node createNewContextParam (String key) throws KeywordValueException {
932    Node newNodeContext = null;
933    Node newNode = null;
934    Object value = null;
935    String valStr = null;
936    String[] strings = null;
937    try {
938       newNodeContext = doc.createElement("context-param");
939
940       newNode = doc.createElement("param-name");
941       value = config.get(key);
942       if (value.getClass().isArray())
943         valStr = key.concat("[]");
944       else
945         valStr = key;
946       newNode.appendChild(doc.createTextNode(valStr));
947       newNodeContext.appendChild(newNode);
948       valStr = null;
949       newNode = doc.createElement("param-value");
950       if (value.getClass().isArray()) {
951         strings = (String[])value;
952         valStr = strings[0];
953         int i = 1;
954         while (i < strings.length){
955           valStr = valStr.concat(", ");
956           valStr = valStr.concat(strings[i]);
957           i++;
958         }
959         newNode.appendChild(doc.createTextNode(valStr));
960       }
961       else {
962         newNode.appendChild(doc.createTextNode(value.toString()));
963       }
964       newNodeContext.appendChild(newNode);
965    if (!comments.get(key).equals("")) {
966          newNode = doc.createElement("description");
967          newNode.appendChild(doc.createTextNode((String)comments.get(key)));
968          newNodeContext.appendChild(newNode);
969       }
970    }
971    catch (Exception ex){
972       System.out.println("error in createNewContextParam method");
973    }
974    return newNodeContext;
975   }
976 */

977
978   /**
979    * Creates new <env-entry> node with all necessary sub-nodes for new entry.
980    * @param key Name of the parameter for which is new node created.
981    * @return Created <env-entry> node with its sub-nodes.
982    * @throws KeywordValueException
983    */

984   private Node JavaDoc createNewEnvEntry(String JavaDoc key) throws KeywordValueException {
985    // tj 08.02.2004 needed for JNDI with <env-entry> tag
986
String JavaDoc contextKeyForm = JNDIAdapter.makeContextString(key);
987    Node JavaDoc newEnvEntry = null;
988    Node JavaDoc newNode = null;
989    Object JavaDoc value = null;
990    String JavaDoc valStr = null;
991    String JavaDoc[] strings = null;
992    try {
993       newEnvEntry = doc.createElement("env-entry");
994
995       if (!comments.get(key).equals("")) {
996          newNode = doc.createElement("description");
997          newNode.appendChild(doc.createTextNode((String JavaDoc)comments.get(key)));
998          newEnvEntry.appendChild(newNode);
999       }
1000
1001      newNode = doc.createElement("env-entry-name");
1002      value = config.get(key);
1003      if (value.getClass().isArray()) {
1004// valStr = key.concat("[]");
1005
valStr = contextKeyForm.concat("[]");
1006      }
1007      else {
1008// valStr = key;
1009
valStr = contextKeyForm;
1010      }
1011      newNode.appendChild(doc.createTextNode(valStr));
1012      newEnvEntry.appendChild(newNode);
1013
1014      valStr = null;
1015      newNode = doc.createElement("env-entry-value");
1016      if (value.getClass().isArray()) {
1017        strings = (String JavaDoc[])value;
1018        valStr = strings[0];
1019        int i = 1;
1020        while (i < strings.length){
1021          valStr = valStr.concat(", ");
1022          valStr = valStr.concat(strings[i]);
1023          i++;
1024        }
1025        newNode.appendChild(doc.createTextNode(valStr));
1026      }
1027      else {
1028        newNode.appendChild(doc.createTextNode(value.toString()));
1029      }
1030      newEnvEntry.appendChild(newNode);
1031
1032      newNode = doc.createElement("env-entry-type");
1033      newNode.appendChild(doc.createTextNode("java.lang.String"));
1034      newEnvEntry.appendChild(newNode);
1035   }
1036   catch (Exception JavaDoc ex){
1037      System.out.println("error in createNewEnvEntry method");
1038   }
1039   return newEnvEntry;
1040  }
1041
1042
1043// tj 08.02.2004 needed for JNDI with <context-param> tag
1044
/**
1045   * Finds the node before which will be <context-param> nodes added. This is
1046   * used only if there had not been any after parsing the document doc.
1047   * @return Node before which will new parameters added or null, if the new
1048   * parameters will be added at the end.
1049   * @throws KeywordValueException
1050   */

1051/*
1052  private Node findPlaceInTree () throws KeywordValueException {
1053     Node web = xmlDoc;
1054    Node child = null;
1055
1056    if ((web != null) && (web.getNodeName().equals("web-app"))) {
1057      child = web.getFirstChild();
1058      while ( (child != null) && ! (child.getNodeName().equals("filter") ||
1059               child.getNodeName().equals("filter-mapping") ||
1060               child.getNodeName().equals("listener") ||
1061               child.getNodeName().equals("servlet") ||
1062               child.getNodeName().equals("servlet-mapping") ||
1063               child.getNodeName().equals("session-config") ||
1064               child.getNodeName().equals("mime-mapping") ||
1065               child.getNodeName().equals("welcome-file-list") ||
1066               child.getNodeName().equals("error-page") ||
1067               child.getNodeName().equals("taglib") ||
1068               child.getNodeName().equals("resourceenv-ref") ||
1069               child.getNodeName().equals("resource-ref") ||
1070               child.getNodeName().equals("security-constraint") ||
1071               child.getNodeName().equals("login-config") ||
1072               child.getNodeName().equals("security-role") ||
1073               child.getNodeName().equals("env-entry") ||
1074               child.getNodeName().equals("ejb-ref") ||
1075               child.getNodeName().equals("ejb-local-ref"))) {
1076        child = child.getNextSibling();
1077      } // while
1078      if (child != null) {
1079        Node prev = child.getPreviousSibling();
1080        while ( (prev != null) && (prev.getNodeType() != Node.ELEMENT_NODE)) {
1081          child = prev;
1082          prev = prev.getPreviousSibling();
1083        }
1084      }
1085    }
1086    return child;
1087  }
1088*/

1089
1090
1091  /**
1092   * Finds the node before which will be <env-entry> nodes added.
1093   * @return Node before which will new parameters added or null, if the new
1094   * parameters will be added at the end.
1095   * @throws KeywordValueException
1096   */

1097
1098  private Node JavaDoc findPlaceInTree () throws KeywordValueException {
1099    // tj 08.02.2004 needed for JNDI with <env-entry> tag
1100
Node JavaDoc web = xmlDoc;
1101    Node JavaDoc child = null;
1102
1103    if ((web != null) && (web.getNodeName().equals("web-app"))) {
1104      child = web.getFirstChild();
1105      while ( (child != null) && !(child.getNodeName().equals("ejb-ref") || child.getNodeName().equals("ejb-local-ref"))) {
1106        child = child.getNextSibling();
1107      } // while
1108
if (child != null) {
1109        Node JavaDoc prev = child.getPreviousSibling();
1110        while ( (prev != null) && (prev.getNodeType() != Node.ELEMENT_NODE)) {
1111          child = prev;
1112          prev = prev.getPreviousSibling();
1113        }
1114      }
1115    }
1116    return child;
1117  }
1118
1119  public class PublicIdResolver implements EntityResolver JavaDoc {
1120   public PublicIdResolver () {
1121        super();
1122   }
1123
1124   public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) {
1125     String JavaDoc Resource23 = "/org/enhydra/util/dtd/webXml2_3.dtd";
1126     String JavaDoc Resource24 = "/org/enhydra/util/dtd/webXml2_4.dtd";
1127      try {
1128        if (publicId != null) {
1129          // return a special input source
1130
if (publicId.equals("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN")) {
1131             return new InputSource JavaDoc(this.getClass().getResource(Resource23).toString());
1132          }
1133          else {
1134             if (publicId.equals("-//Sun Microsystems, Inc.//DTD Web Application 2.4//EN")) {
1135                return new InputSource JavaDoc(this.getClass().getResource(Resource24).toString());
1136             }
1137             else {
1138                return new InputSource JavaDoc(this.getClass().getResource(Resource23).toString());
1139             }
1140
1141          }
1142        }
1143      }
1144      catch (Exception JavaDoc e){
1145        System.out.println("Resolver Entity Error.");
1146        //e.printStackTrace();
1147
}
1148      // use the default behaviour
1149
return null;
1150    }
1151  }
1152
1153
1154}
Popular Tags