001: /**
002: * Licensed to the Apache Software Foundation (ASF) under one
003: * or more contributor license agreements. See the NOTICE file
004: * distributed with this work for additional information
005: * regarding copyright ownership. The ASF licenses this file
006: * to you under the Apache License, Version 2.0 (the
007: * "License"); you may not use this file except in compliance
008: * with the License. You may obtain a copy of the License at
009: *
010: * http://www.apache.org/licenses/LICENSE-2.0
011: *
012: * Unless required by applicable law or agreed to in writing,
013: * software distributed under the License is distributed on an
014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015: * KIND, either express or implied. See the License for the
016: * specific language governing permissions and limitations
017: * under the License.
018: */package org.apache.cxf.helpers;
019:
020: import java.io.ByteArrayInputStream;
021: import java.io.ByteArrayOutputStream;
022: import java.io.File;
023: import java.io.IOException;
024: import java.io.InputStream;
025: import java.io.OutputStream;
026: import java.io.Writer;
027: import java.util.Map;
028: import java.util.Properties;
029: import java.util.StringTokenizer;
030: import java.util.logging.Level;
031: import java.util.logging.Logger;
032: import javax.wsdl.Definition;
033: import javax.xml.namespace.QName;
034: import javax.xml.parsers.DocumentBuilder;
035: import javax.xml.parsers.DocumentBuilderFactory;
036: import javax.xml.parsers.ParserConfigurationException;
037: import javax.xml.transform.OutputKeys;
038: import javax.xml.transform.Source;
039: import javax.xml.transform.Transformer;
040: import javax.xml.transform.TransformerConfigurationException;
041: import javax.xml.transform.TransformerException;
042: import javax.xml.transform.TransformerFactory;
043: import javax.xml.transform.dom.DOMResult;
044: import javax.xml.transform.dom.DOMSource;
045: import javax.xml.transform.stream.StreamResult;
046:
047: import org.w3c.dom.Attr;
048: import org.w3c.dom.DOMImplementation;
049: import org.w3c.dom.Document;
050: import org.w3c.dom.Element;
051: import org.w3c.dom.NamedNodeMap;
052: import org.w3c.dom.Node;
053: import org.w3c.dom.NodeList;
054: import org.w3c.dom.Text;
055: import org.w3c.dom.bootstrap.DOMImplementationRegistry;
056: import org.w3c.dom.ls.DOMImplementationLS;
057: import org.w3c.dom.ls.LSOutput;
058: import org.w3c.dom.ls.LSSerializer;
059: import org.xml.sax.InputSource;
060: import org.xml.sax.SAXException;
061:
062: import org.apache.cxf.common.logging.LogUtils;
063:
064: public final class XMLUtils {
065:
066: private static final Logger LOG = LogUtils
067: .getL7dLogger(XMLUtils.class);
068: private static DocumentBuilderFactory parserFactory;
069: private static TransformerFactory transformerFactory;
070: private static String omitXmlDecl = "no";
071: private static String charset = "utf-8";
072: private static int indent = -1;
073:
074: static {
075: parserFactory = DocumentBuilderFactory.newInstance();
076: parserFactory.setNamespaceAware(true);
077:
078: transformerFactory = TransformerFactory.newInstance();
079: }
080:
081: private XMLUtils() {
082:
083: }
084:
085: public static Transformer newTransformer()
086: throws TransformerConfigurationException {
087: return transformerFactory.newTransformer();
088: }
089:
090: public static DocumentBuilder getParser()
091: throws ParserConfigurationException {
092: return parserFactory.newDocumentBuilder();
093: }
094:
095: public static Document parse(InputSource is)
096: throws ParserConfigurationException, SAXException,
097: IOException {
098: return getParser().parse(is.getSystemId());
099: }
100:
101: public static Document parse(File is)
102: throws ParserConfigurationException, SAXException,
103: IOException {
104: return getParser().parse(is);
105: }
106:
107: public static Document parse(InputStream in)
108: throws ParserConfigurationException, SAXException,
109: IOException {
110: if (in == null && LOG.isLoggable(Level.FINE)) {
111: LOG.fine("XMLUtils trying to parse a null inputstream");
112: }
113: return getParser().parse(in);
114: }
115:
116: public static Document parse(String in)
117: throws ParserConfigurationException, SAXException,
118: IOException {
119: return parse(in.getBytes());
120: }
121:
122: public static Document parse(byte[] in)
123: throws ParserConfigurationException, SAXException,
124: IOException {
125: if (in == null && LOG.isLoggable(Level.FINE)) {
126: LOG.fine("XMLUtils trying to parse a null bytes");
127: }
128: return getParser().parse(new ByteArrayInputStream(in));
129: }
130:
131: public static Document newDocument()
132: throws ParserConfigurationException {
133: return getParser().newDocument();
134: }
135:
136: public static void setOmitXmlDecl(String value) {
137: omitXmlDecl = value;
138: }
139:
140: public static void setCharsetEncoding(String value) {
141: charset = value;
142: }
143:
144: public static void setIndention(int i) {
145: indent = i;
146: }
147:
148: private static boolean indent() {
149: return indent != -1;
150: }
151:
152: public static void writeTo(Node node, OutputStream os) {
153: writeTo(new DOMSource(node), os);
154: }
155:
156: public static void writeTo(Source src, OutputStream os) {
157: Transformer it;
158: try {
159: it = newTransformer();
160: it.setOutputProperty(OutputKeys.METHOD, "xml");
161: if (indent()) {
162: it.setOutputProperty(OutputKeys.INDENT, "yes");
163: it.setOutputProperty(
164: "{http://xml.apache.org/xslt}indent-amount",
165: Integer.toString(indent));
166: }
167: it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
168: omitXmlDecl);
169: it.setOutputProperty(OutputKeys.ENCODING, charset);
170: it.transform(src, new StreamResult(os));
171: } catch (TransformerException e) {
172: // TODO Auto-generated catch block
173: e.printStackTrace();
174: }
175:
176: }
177:
178: public static String toString(Source source)
179: throws TransformerException, IOException {
180: return toString(source, null);
181: }
182:
183: public static String toString(Source source, Properties props)
184: throws TransformerException, IOException {
185: ByteArrayOutputStream bos = new ByteArrayOutputStream();
186: StreamResult sr = new StreamResult(bos);
187: Transformer trans = newTransformer();
188: if (props == null) {
189: props = new Properties();
190: props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
191: }
192: trans.setOutputProperties(props);
193: trans.transform(source, sr);
194: bos.close();
195: return bos.toString();
196: }
197:
198: public static String toString(Node node) {
199: ByteArrayOutputStream out = new ByteArrayOutputStream();
200: writeTo(node, out);
201: return out.toString();
202: }
203:
204: public static void printDOM(Node node) {
205: printDOM("", node);
206: }
207:
208: public static void printDOM(String words, Node node) {
209: System.out.println(words);
210: System.out.println(toString(node));
211: }
212:
213: public static Attr getAttribute(Element el, String attrName) {
214: return el.getAttributeNode(attrName);
215: }
216:
217: public static void replaceAttribute(Element element, String attr,
218: String value) {
219: if (element.hasAttribute(attr)) {
220: element.removeAttribute(attr);
221: }
222: element.setAttribute(attr, value);
223: }
224:
225: public static boolean hasAttribute(Element element, String value) {
226: NamedNodeMap attributes = element.getAttributes();
227: for (int i = 0; i < attributes.getLength(); i++) {
228: Node node = attributes.item(i);
229: if (value.equals(node.getNodeValue())) {
230: return true;
231: }
232: }
233: return false;
234: }
235:
236: public static void printAttributes(Element element) {
237: NamedNodeMap attributes = element.getAttributes();
238: for (int i = 0; i < attributes.getLength(); i++) {
239: Node node = attributes.item(i);
240: System.err.println("## prefix=" + node.getPrefix()
241: + " localname:" + node.getLocalName() + " value="
242: + node.getNodeValue());
243: }
244: }
245:
246: public static QName getNamespace(Map<String, String> namespaces,
247: String str, String defaultNamespace) {
248: String prefix = null;
249: String localName = null;
250:
251: StringTokenizer tokenizer = new StringTokenizer(str, ":");
252: if (tokenizer.countTokens() == 2) {
253: prefix = tokenizer.nextToken();
254: localName = tokenizer.nextToken();
255: } else if (tokenizer.countTokens() == 1) {
256: localName = tokenizer.nextToken();
257: }
258:
259: String namespceURI = defaultNamespace;
260: if (prefix != null) {
261: namespceURI = (String) namespaces.get(prefix);
262: }
263: return new QName(namespceURI, localName);
264: }
265:
266: public static void generateXMLFile(Element element, Writer writer) {
267: try {
268: Transformer it = newTransformer();
269:
270: it.setOutputProperty(OutputKeys.METHOD, "xml");
271: it.setOutputProperty(OutputKeys.INDENT, "yes");
272: it.setOutputProperty(
273: "{http://xml.apache.org/xslt}indent-amount", "2");
274: it.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
275: it.transform(new DOMSource(element), new StreamResult(
276: writer));
277: } catch (Exception e) {
278: e.printStackTrace();
279: }
280: }
281:
282: public static Element createElementNS(Node node, QName name) {
283: return createElementNS(node.getOwnerDocument(), name
284: .getNamespaceURI(), name.getLocalPart());
285: }
286:
287: public static Element createElementNS(Document root, QName name) {
288: return createElementNS(root, name.getNamespaceURI(), name
289: .getLocalPart());
290: }
291:
292: public static Element createElementNS(Document root,
293: String namespaceURI, String qualifiedName) {
294: return root.createElementNS(namespaceURI, qualifiedName);
295: }
296:
297: public static Text createTextNode(Document root, String data) {
298: return root.createTextNode(data);
299: }
300:
301: public static Text createTextNode(Node node, String data) {
302: return createTextNode(node.getOwnerDocument(), data);
303: }
304:
305: public static void removeContents(Node node) {
306: NodeList list = node.getChildNodes();
307: for (int i = 0; i < list.getLength(); i++) {
308: Node entry = list.item(i);
309: node.removeChild(entry);
310: }
311: }
312:
313: public static String writeQName(Definition def, QName qname) {
314: return def.getPrefix(qname.getNamespaceURI()) + ":"
315: + qname.getLocalPart();
316: }
317:
318: public static InputStream getInputStream(Document doc)
319: throws Exception {
320: DOMImplementationLS impl = null;
321: DOMImplementation docImpl = doc.getImplementation();
322: // Try to get the DOMImplementation from doc first before
323: // defaulting to the sun implementation.
324: if (docImpl != null && docImpl.hasFeature("LS", "3.0")) {
325: impl = (DOMImplementationLS) docImpl
326: .getFeature("LS", "3.0");
327: } else {
328: DOMImplementationRegistry registry = DOMImplementationRegistry
329: .newInstance();
330: impl = (DOMImplementationLS) registry
331: .getDOMImplementation("LS");
332: if (impl == null) {
333: System
334: .setProperty(
335: DOMImplementationRegistry.PROPERTY,
336: "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
337: registry = DOMImplementationRegistry.newInstance();
338: impl = (DOMImplementationLS) registry
339: .getDOMImplementation("LS");
340: }
341: }
342: LSOutput output = impl.createLSOutput();
343: ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
344: output.setByteStream(byteArrayOutputStream);
345: LSSerializer writer = impl.createLSSerializer();
346: writer.write(doc, output);
347: byte[] buf = byteArrayOutputStream.toByteArray();
348: return new ByteArrayInputStream(buf);
349: }
350:
351: public static Element fetchElementByNameAttribute(Element parent,
352: String targetName, String nameValue) {
353: Element ret = null;
354: NodeList nodeList = parent.getElementsByTagName(targetName);
355: Node node = null;
356: for (int i = 0; i < nodeList.getLength(); i++) {
357: node = nodeList.item(i);
358: if (node instanceof Element
359: && ((Element) node).getAttribute("name").equals(
360: nameValue)) {
361: ret = (Element) node;
362: break;
363: }
364: }
365: return ret;
366: }
367:
368: public static QName getQName(String value, Node node) {
369: if (value == null) {
370: return null;
371: }
372:
373: int index = value.indexOf(":");
374:
375: if (index == -1) {
376: return new QName(value);
377: }
378:
379: String prefix = value.substring(0, index);
380: String localName = value.substring(index + 1);
381: String ns = node.lookupNamespaceURI(prefix);
382:
383: if (ns == null || localName == null) {
384: throw new RuntimeException("Invalid QName in mapping: "
385: + value);
386: }
387:
388: return new QName(ns, localName, prefix);
389: }
390:
391: public static Node fromSource(Source src) throws Exception {
392:
393: Transformer trans = TransformerFactory.newInstance()
394: .newTransformer();
395: DOMResult res = new DOMResult();
396: trans.transform(src, res);
397: return res.getNode();
398: }
399: }
|