View Javadoc

1   /*
2    * Copyright 2001-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  package org.apache.juddi.util.xml;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.OutputStream;
20  import java.net.URL;
21  import java.util.Vector;
22  
23  import javax.xml.parsers.DocumentBuilder;
24  import javax.xml.parsers.DocumentBuilderFactory;
25  import javax.xml.parsers.ParserConfigurationException;
26  import javax.xml.transform.Result;
27  import javax.xml.transform.Transformer;
28  import javax.xml.transform.TransformerFactory;
29  import javax.xml.transform.dom.DOMSource;
30  import javax.xml.transform.stream.StreamResult;
31  
32  import org.apache.juddi.util.Loader;
33  import org.w3c.dom.Document;
34  import org.w3c.dom.Element;
35  import org.w3c.dom.Node;
36  import org.w3c.dom.NodeList;
37  import org.xml.sax.SAXException;
38  import org.xml.sax.SAXParseException;
39  import org.xml.sax.helpers.DefaultHandler;
40  
41  /***
42   * @author Steve Viens (sviens@apache.org)
43   */
44  public class XMLUtils
45  {
46    // jUDDI XML document builder
47    private static DocumentBuilder docBuilder = null;
48  
49    /***
50     *
51     * @param element
52     * @return String
53     */
54    public static String getText(Element element)
55    {
56      StringBuffer textBuffer = new StringBuffer();
57  
58      NodeList nodeList = element.getChildNodes();
59      for (int i=0; i<nodeList.getLength(); i++)
60      {
61        if (nodeList.item(i).getNodeType() == Element.TEXT_NODE)
62          textBuffer.append(nodeList.item(i).getNodeValue());
63      }
64  
65      return textBuffer.toString().trim();
66    }
67  
68    /***
69     *
70     * @param element
71     * @param tagName
72     * @return Vector
73     */
74    public static Vector getChildElementsByTagName(Element element,String tagName)
75    {
76      Vector result = new Vector();
77  
78      NodeList children = element.getChildNodes();
79      for (int i=0; i<children.getLength(); i++)
80      {
81        //System.out.println("node name:       "+node.getNodeName());
82        //System.out.println("node local name: "+node.getLocalName());
83          
84        Node node = children.item(i);      
85        String nodeName = node.getNodeName();
86        String localName = node.getLocalName();
87        
88        if ((localName == null) && (nodeName != null))
89            localName = nodeName;
90              
91        if (node.getNodeType() == Node.ELEMENT_NODE && localName.equals(tagName))
92          result.addElement(node); // matching element
93      }
94  
95      return result;
96    }
97  
98    /***
99     * create a new empty xml element
100    * @return a new org.w3c.Element named "root"
101    */
102   public static Element newRootElement()
103   {
104     Element element = null;
105 
106     try
107     {
108       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
109       DocumentBuilder builder = factory.newDocumentBuilder();
110       Document document = builder.newDocument();
111       Element holder = document.createElement("root");
112       document.appendChild(holder);
113       element = document.getDocumentElement();
114     }
115     catch(Exception ex) { ex.printStackTrace(); }
116 
117     return element;
118   }
119 
120   public static Document createDocument()
121   {
122     if (docBuilder == null)
123       docBuilder = createDocumentBuilder();
124 
125     return docBuilder.newDocument();
126   }
127 
128   private static DocumentBuilder createDocumentBuilder()
129   {
130     if (docBuilder != null)
131       return docBuilder;
132 
133     try {
134      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
135      docBuilder = factory.newDocumentBuilder();
136     }
137     catch(ParserConfigurationException pcex) {
138       pcex.printStackTrace();
139     }
140 
141     return docBuilder;
142   }
143 
144   public static void writeXML(Element element,OutputStream stream)
145   {
146     try {
147       TransformerFactory xformerFactory = TransformerFactory.newInstance();
148       Transformer xformer = xformerFactory.newTransformer();
149       Result output = new StreamResult(stream);
150       DOMSource source = new DOMSource(element);
151       
152       // print the xml to the specified OutputStream
153       xformer.transform(source,output);
154     }
155     catch(Exception ex) {
156       ex.printStackTrace();
157     }
158   }
159     
160   public static String toString(Element element)
161   {
162       ByteArrayOutputStream stream = new ByteArrayOutputStream();      
163       writeXML(element,stream);
164       
165       return stream.toString();      
166   }
167   
168   public static void validate(URL xmlDocUrl) 
169   {    
170     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
171     factory.setValidating(true);    
172     factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema");
173     factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",Loader.getResource("uddi_v2.xsd"));
174 
175     try
176     {
177         DocumentBuilder builder = factory.newDocumentBuilder();
178         Validator handler = new Validator();
179         builder.setErrorHandler(handler); 
180         //builder.parse(xmlDocUrl);
181     
182         if ((handler.error) || (handler.warning))
183             System.out.println(handler.toString());
184     }
185     catch(ParserConfigurationException pcex) {
186         pcex.printStackTrace();
187     }
188   }
189 }
190 
191 class Validator extends DefaultHandler
192 {
193   public boolean warning = false;
194   public boolean error = false;  
195   public SAXParseException exception = null;
196     
197   public void warning(SAXParseException spex) 
198       throws SAXException
199   {
200     warning = true;
201     exception = spex;        
202   }
203   
204   public void error(SAXParseException spex) 
205       throws SAXException
206   {
207     error = true;
208     exception = spex;        
209   }
210   
211   public void fatalError(SAXParseException spex) 
212       throws SAXException
213   {
214     error = true;
215     exception = spex;        
216   }
217   
218   public String toString()
219   {
220     StringBuffer buffer = new StringBuffer();
221     
222     if (exception != null)
223     {
224       buffer.append("Public ID: " + exception.getPublicId());
225       buffer.append("\n");
226       buffer.append("System ID: " + exception.getSystemId());
227       buffer.append("\n");
228       buffer.append("Line number: " + exception.getLineNumber());
229       buffer.append("\n");
230       buffer.append("Column number: " + exception.getColumnNumber());
231       buffer.append("\n");
232       buffer.append("Message: " + exception.getMessage());
233     }
234     
235     return buffer.toString();
236   }
237 }