KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > diagnostics > util > XmlUtils


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 package com.sun.enterprise.diagnostics.util;
24
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileWriter JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.ArrayList JavaDoc;
31
32 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
33 import javax.xml.parsers.DocumentBuilder JavaDoc;
34 import javax.xml.parsers.ParserConfigurationException JavaDoc;
35 import javax.xml.transform.Transformer JavaDoc;
36 import javax.xml.transform.TransformerFactory JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.TransformerConfigurationException JavaDoc;
39 import javax.xml.transform.dom.DOMSource JavaDoc;
40 import javax.xml.transform.stream.StreamResult JavaDoc;
41 import java.util.logging.Level JavaDoc;
42 import java.util.logging.Logger JavaDoc;
43         
44 import org.w3c.dom.*;
45 import org.xml.sax.SAXException JavaDoc;
46 import org.xml.sax.helpers.DefaultHandler JavaDoc;
47 import org.xml.sax.InputSource JavaDoc;
48
49 import com.sun.logging.LogDomains;
50
51 /**
52  * Collection of helper methods to manipulate XML files.
53  * @author Manisha Umbarje
54  */

55 public class XmlUtils {
56
57     /**
58      * Load an XML file from disk
59      *
60      * @param srcXmlFile Absolute path of the XML file to be loaded
61      *
62      * @return XmlDocument representation of the source XML file
63      */

64     public static Document loadXML(String JavaDoc srcXmlFile, String JavaDoc dtdFileName)
65     throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc {
66     Document doc = null;
67     FileInputStream JavaDoc in = null;
68       
69     in = new FileInputStream JavaDoc(srcXmlFile);
70         DocumentBuilder JavaDoc docBuilder = DocumentBuilderFactory.newInstance().
71                 newDocumentBuilder();
72         docBuilder.setEntityResolver(new NOOPHandler(dtdFileName));
73     doc = docBuilder.parse( in );
74     if(in!=null)
75         in.close();
76     return doc;
77     }
78
79     public static void getAttributes(Node element, String JavaDoc srchStr,
80             List JavaDoc list) {
81     
82         if(element != null && srchStr != null) {
83             if(list == null)
84                 list = new ArrayList JavaDoc(5);
85             NodeList children = element.getChildNodes();
86             int noOfChildren = children.getLength();
87
88         for (int i = 0; i < noOfChildren; i++) {
89         Node child = children.item(i);
90                 String JavaDoc childName = child.getLocalName();
91         NamedNodeMap attrs = null;
92         attrs = child.getAttributes();
93         if (attrs != null) {
94             for (int j=0; j<attrs.getLength(); j++) {
95             Attr attr = (Attr)attrs.item(j);
96             if (attr.getName().toLowerCase().indexOf(srchStr) != -1) {
97                             String JavaDoc attrName =getParentNodeName(child);
98                             list.add( attrName + File.separator + attr);
99                         }
100             }//for
101
}//if
102

103         getAttributes(child,srchStr,list);
104             }
105         }
106     }
107     
108     private static String JavaDoc getParentNodeName(Node child) {
109         if(child != null) {
110             String JavaDoc name = child.getNodeName() ;
111             //String value = child.getNodeValue();
112
Node parent = child.getParentNode();
113             if(parent != null && (parent.getNodeType() == Node.ELEMENT_NODE))
114                 name = getParentNodeName(parent) + File.separator+ name ;
115             NamedNodeMap attrs = child.getAttributes();
116             if (attrs != null) {
117                 String JavaDoc nameAttribute = null;
118                 for (int j=0; j<attrs.getLength(); j++) {
119                     Attr attr = (Attr)attrs.item(j);
120                     if(attr.getName().toLowerCase().indexOf("name") != -1) {
121                         nameAttribute = attr.getValue();
122                         continue;
123                     }
124                 }
125                 if (nameAttribute != null)
126                     name = name + "=" + nameAttribute ;
127             }
128             return name;
129         }
130         return "";
131     }
132     /**
133      * Search and replace attributes within the specified XmlDocument
134      *
135      * @param doc XmlDocument in whicch to perform the search and replace.
136      * @param srchStr String within the document to be replaced.
137      * @param rplStr String to replace srchStr with.
138      *
139      */

140     public static void attrSearchReplace(Document doc, String JavaDoc srchStr,
141                     String JavaDoc rplStr){
142     Node m_root = null;
143     Node child = null;
144     m_root = doc.getDocumentElement();
145     child = m_root.getFirstChild();
146     while (child != null) {
147         NamedNodeMap attrs = null;
148         attrs = child.getAttributes();
149         if (attrs != null)
150         for (int j=0; j<attrs.getLength(); j++) {
151             Attr attr = (Attr)attrs.item(j);
152             if (attr.getName().toLowerCase().indexOf(srchStr) != -1)
153             attr.setValue(rplStr);
154         }
155         child = child.getNextSibling();
156     }
157     }
158
159      
160     /**
161      * Search and replace attributes within the specified XmlDocument
162      *
163      * @param doc XmlDocument in whicch to perform the search and replace.
164      * @param srchStr String within the document to be replaced.
165      * @param rplStr String to replace srchStr with.
166      *
167      */

168     public static void attrSearchReplace(Node element, String JavaDoc srchStr,
169                     String JavaDoc replaceString) {
170     if (element != null) {
171         NodeList children = element.getChildNodes();
172         int noOfChildren = children.getLength();
173
174         for (int i = 0; i < noOfChildren; i++) {
175         Node child = children.item(i);
176
177         NamedNodeMap attrs = null;
178         attrs = child.getAttributes();
179         if (attrs != null) {
180             for (int j=0; j<attrs.getLength(); j++) {
181             Attr attr = (Attr)attrs.item(j);
182             if (attr.getName().toLowerCase().indexOf(srchStr) != -1)
183                 attr.setValue(replaceString);
184             }//for
185
}//if
186

187         attrSearchReplace(child,srchStr,replaceString);
188         }//for
189
}//if (element != null)
190
}
191
192
193     /**
194      * Copy the specified Document to the specified file
195      *
196      * @param srcDoc The source XMLDocument
197      * @param destFile Absolute path of the destination file
198      *
199      */

200     public static void copyXMLFile(Document srcDoc, String JavaDoc destFile)
201     throws IOException JavaDoc, TransformerConfigurationException JavaDoc, TransformerException JavaDoc {
202     // Use a Transformer for output
203
TransformerFactory JavaDoc tFactory =
204         TransformerFactory.newInstance();
205     Transformer JavaDoc transformer = tFactory.newTransformer();
206
207     DOMSource JavaDoc source = new DOMSource JavaDoc(srcDoc);
208         File JavaDoc destFileObj = new File JavaDoc(destFile);
209         if(!destFileObj.getParentFile().exists())
210             destFileObj.getParentFile().mkdirs();
211     FileWriter JavaDoc destFileWriter = new FileWriter JavaDoc(destFile);
212     StreamResult JavaDoc result = new StreamResult JavaDoc(destFileWriter);
213     transformer.transform(source, result);
214     }
215 }
216
217 class NOOPHandler extends DefaultHandler JavaDoc {
218
219     static String JavaDoc _dtdFileName;
220     private static Logger JavaDoc logger =
221             LogDomains.getLogger(LogDomains.ADMIN_LOGGER);
222     NOOPHandler(String JavaDoc dtdFileName) {
223     super();
224     _dtdFileName = dtdFileName;
225         //logger.log(Level.INFO, "diagnostic-service.dtd_file_name",
226
// new Object[] {dtdFileName});
227
}
228
229     public InputSource JavaDoc resolveEntity(String JavaDoc publicId,
230      String JavaDoc systemId) throws SAXException JavaDoc
231     {
232         InputSource JavaDoc is = null;
233     try {
234             is = new InputSource JavaDoc(new FileInputStream JavaDoc(_dtdFileName));
235     } catch(Exception JavaDoc e) {
236             throw new SAXException JavaDoc("cannot resolve dtd", e);
237     }
238         return is;
239     }
240
241 }
242
243
244
Popular Tags