001: /*
002: * BEGIN_HEADER - DO NOT EDIT
003: *
004: * The contents of this file are subject to the terms
005: * of the Common Development and Distribution License
006: * (the "License"). You may not use this file except
007: * in compliance with the License.
008: *
009: * You can obtain a copy of the license at
010: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
011: * See the License for the specific language governing
012: * permissions and limitations under the License.
013: *
014: * When distributing Covered Code, include this CDDL
015: * HEADER in each file and include the License file at
016: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
017: * If applicable add the following below this CDDL HEADER,
018: * with the fields enclosed by brackets "[]" replaced with
019: * your own identifying information: Portions Copyright
020: * [year] [name of copyright owner]
021: */
022:
023: /*
024: * @(#)DOMUtil.java
025: * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
026: *
027: * END_HEADER - DO NOT EDIT
028: */
029: package com.sun.jbi.ui.common;
030:
031: import java.io.Reader;
032: import java.io.StringReader;
033: import java.io.Writer;
034: import java.util.ArrayList;
035: import javax.xml.parsers.DocumentBuilder;
036: import javax.xml.parsers.DocumentBuilderFactory;
037: import javax.xml.transform.OutputKeys;
038: import javax.xml.transform.Transformer;
039: import javax.xml.transform.TransformerConfigurationException;
040: import javax.xml.transform.TransformerException;
041: import javax.xml.transform.TransformerFactory;
042: import javax.xml.transform.dom.DOMSource;
043: import javax.xml.transform.stream.StreamResult;
044: import org.w3c.dom.Document;
045: import org.w3c.dom.Element;
046: import org.w3c.dom.Node;
047: import org.w3c.dom.NodeList;
048: import org.w3c.dom.Text;
049: import org.xml.sax.InputSource;
050: import org.xml.sax.SAXException;
051: import org.xml.sax.SAXParseException;
052: import org.xml.sax.helpers.DefaultHandler;
053:
054: /**
055: * This object provides utility methods to manipulate DOM tree
056: *
057: * @author Sun Microsystems, Inc.
058: */
059: public class DOMUtil {
060: /** static object to access the methods of this object */
061: public static final DOMUtil UTIL = new DOMUtil();
062:
063: /** Creates a new instance of DOMUtil */
064: public DOMUtil() {
065: }
066:
067: /** gets the element
068: * @return Element with tagname
069: * @param aParentDocument Document for parent node
070: * @param aTagName String for tagname
071: */
072: public Element getElement(Document aParentDocument, String aTagName) {
073: NodeList nodeList = aParentDocument
074: .getElementsByTagName(aTagName);
075: return (nodeList != null) ? (Element) nodeList.item(0) : null;
076: }
077:
078: /** get the child element
079: * @param elem parent element
080: * @param tagName element to look for
081: * @return child element of type tagName
082: */
083: public Element getElement(Element elem, String tagName) {
084: NodeList nl = elem.getElementsByTagName(tagName);
085: Element childElem = (Element) nl.item(0);
086:
087: return childElem;
088: }
089:
090: /** gets the element value
091: * @param doc document
092: * @param elemName element
093: * @return value of the element
094: */
095: public String getElementValue(Document doc, String elemName) {
096: String elemVal = null;
097:
098: Element elem = getElement(doc, elemName);
099: elemVal = getTextData(elem);
100:
101: return elemVal;
102: }
103:
104: /** use this util method to create/retrieve a Text Node in a element
105: * @param aElement Element node
106: * @return Text node for text data
107: */
108: private Text getText(Element aElement) {
109: Node node = null;
110: aElement.normalize();
111: node = aElement.getFirstChild();
112: if (node == null || !(node instanceof Text)) {
113: node = aElement.getOwnerDocument().createTextNode("");
114: aElement.appendChild(node);
115: }
116: return (Text) node;
117: }
118:
119: /** use this util method to set a Text Data in a element
120: * @param aElement Element for text node
121: * @param aData String contains text
122: */
123: public void setTextData(Element aElement, String aData) {
124: getText(aElement).setData(aData);
125: }
126:
127: /** use this util method to retrieve a Text Data in a element
128: * @param aElement Element for text node
129: * @return String contains text
130: */
131: public String getTextData(Element aElement) {
132: return getText(aElement).getData();
133: }
134:
135: /** save document to stream
136: * @return xml text
137: * @param aDocument Document
138: * @param aWriter is what the aDocument is serialized to.
139: * @throws Exception on error
140: */
141: public String DOM2String(Document aDocument, Writer aWriter)
142: throws Exception {
143: TransformerFactory transformerFactory = TransformerFactory
144: .newInstance();
145: Transformer transformer;
146: try {
147: transformer = transformerFactory.newTransformer();
148: } catch (TransformerConfigurationException e) {
149: transformer = null;
150: throw e;
151: }
152:
153: transformer.setOutputProperty(OutputKeys.METHOD, "xml");
154: transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
155: "no");
156: transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
157: transformer.setOutputProperty(
158: OutputKeys.CDATA_SECTION_ELEMENTS, "");
159: transformer.setOutputProperty(OutputKeys.INDENT, "no");
160: try {
161: transformer.transform(new DOMSource(aDocument),
162: new StreamResult(aWriter));
163: } catch (TransformerException e) {
164: throw e;
165: }
166:
167: return aWriter.toString();
168: }
169:
170: /** gets list of elements
171: * @return NodeList with tagname
172: * @param aParentElement Element for parent
173: * @param aTagName String for tagname
174: */
175: public NodeList getElements(Element aParentElement, String aTagName) {
176: return aParentElement.getElementsByTagNameNS(aParentElement
177: .getNamespaceURI(), aTagName);
178: }
179:
180: /** gets set of elements
181: * @return NodeList with tagname
182: * @param aParentDocument Document for parent node
183: * @param aTagName String for tagname
184: */
185: public NodeList getElements(Document aParentDocument,
186: String aTagName) {
187: return aParentDocument.getElementsByTagNameNS("*", aTagName);
188: }
189:
190: /** get the children of the same type element tag name
191: * @param aElement Element for parent node
192: *
193: * @param aElementTagName String for tagname
194: * @return NodeList for list of children with the tagname
195: */
196: public NodeList getChildElements(Element aElement,
197: String aElementTagName) {
198: NodeList nodeList = aElement.getChildNodes();
199: NodeListImpl list = new NodeListImpl();
200: int count = nodeList.getLength();
201: for (int i = 0; i < count; ++i) {
202: Node node = nodeList.item(i);
203: if (node instanceof Element) {
204: String tagName = getElementName((Element) node);
205: if (tagName.equals(aElementTagName)) {
206: list.add(node);
207: }
208: }
209: }
210: return list;
211: }
212:
213: /** get the child with the specified tag name
214: * @param aElement Element for parent node
215: *
216: * @param aElementTagName String for tagname
217: * @return NodeList for list of children with the tagname
218: */
219: public Element getChildElement(Element aElement,
220: String aElementTagName) {
221: NodeList list = getChildElements(aElement, aElementTagName);
222: if (list != null && list.getLength() > 0) {
223: return (Element) list.item(0);
224: } else {
225: return null;
226: }
227: }
228:
229: /**
230: * get Element Tag Name with striped prefix.
231: * @param aElement Element object
232: * @return String with stripped prefix
233: */
234: public String getElementName(Element aElement) {
235: String tagName = aElement.getTagName();
236: return getName(tagName);
237: }
238:
239: /**
240: * strips the prefix of the name if present
241: * @param aName String value of Name with prefix
242: * @return String for name after striping prefix
243: */
244: public String getName(String aName) {
245: int lastIdx = aName.lastIndexOf(':');
246: if (lastIdx >= 0) {
247: return aName.substring(lastIdx + 1);
248: }
249: return aName;
250: }
251:
252: /**
253: * return the DOM Document
254: * @param xmlText String
255: * @return dom document
256: * @throws Exception on parser exception or any other exception
257: */
258: public Document buildDOMDocument(String xmlText) throws Exception {
259: StringReader reader = new StringReader(xmlText);
260: return DOMUtil.UTIL.buildDOMDocument(reader);
261: }
262:
263: /**
264: * return the DOM Document
265: * @param xmlReader Reader
266: * @return dom document
267: * @throws Exception on parser exception or any other exception
268: */
269: public Document buildDOMDocument(Reader xmlReader) throws Exception {
270: Document xmlDoc = null;
271: DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
272: .newInstance();
273:
274: DocumentBuilder docBuilder = docBuilderFactory
275: .newDocumentBuilder();
276: docBuilder.setErrorHandler(new DefaultHandler() {
277: public void fatalError(SAXParseException e)
278: throws SAXException {
279: throw new SAXException(e.getMessage());
280: }
281: });
282:
283: InputSource is = new InputSource(xmlReader);
284: xmlDoc = docBuilder.parse(is);
285:
286: return xmlDoc;
287: }
288:
289: /**
290: * replaces the xml entity refereces with the xml escape chars
291: * @param xmlString Text with the xml xml escape chars
292: * @param Text with the xml entity refereces
293: */
294: public static String replaceXmlEscapeCharsToEntityRefereces(
295: String xmlString) {
296: if (xmlString == null) {
297: return xmlString;
298: }
299:
300: // just convert < , > and & only
301: StringBuffer sbuff = new StringBuffer(2 * xmlString.length());
302: for (int i = 0; i < xmlString.length(); ++i) {
303: switch (xmlString.charAt(i)) {
304: case '&':
305: sbuff.append("&");
306: break;
307: case '<':
308: sbuff.append("<");
309: break;
310: case '>':
311: sbuff.append(">");
312: break;
313: default:
314: sbuff.append(xmlString.charAt(i));
315: }
316: }
317: return sbuff.toString();
318: }
319:
320: /**
321: * replaces the xml entity refereces with the xml escape chars
322: * @param xmlString Text with the xml entity references
323: * @param Text with the xml escape chars
324: */
325: public static String replaceXmlEntityReferecesToEscapeChars(
326: String xmlString) {
327: if (xmlString == null) {
328: return xmlString;
329: }
330: // just look for these entity refereces only
331: String[] entities = { "<", ">", "&" };
332: char[] escapeChar = { '<', '>', '&' };
333:
334: StringBuffer sbuff = new StringBuffer(xmlString.length());
335: // sbuff.
336:
337: for (int i = 0; i < xmlString.length(); ++i) {
338: char ch = xmlString.charAt(i);
339:
340: if (ch != '&') {
341: // not found &. append the ch and continue
342: // System.out.println("Non & Char " + ch);
343: sbuff.append(ch);
344: continue;
345: }
346:
347: String what = null;
348: boolean found = false;
349: int eIdx = 0;
350: // found & char at i
351: for (; eIdx < entities.length; ++eIdx) {
352: what = entities[eIdx];
353: found = xmlString.startsWith(what, i);
354: if (found) {
355: // System.out.println("Found Entity " + what);
356: break;
357: }
358: }
359:
360: if (!found) {
361: // not found the entity
362: // System.out.println("Entity Not found");
363: continue;
364: }
365:
366: // found the entity. so replace it with escape ch
367: // System.out.println("Appending escape char " + escapeChar[eIdx]);
368: sbuff.append(escapeChar[eIdx]);
369: // System.out.println("Buff : " + sbuff.toString());
370: // now increment i to entity.length-1 as the i will be incremented +1 in the for loop
371: i += what.length() - 1;
372: }
373:
374: return sbuff.toString();
375: }
376:
377: /**
378: * NodeListImpl
379: *
380: */
381: public static class NodeListImpl extends ArrayList implements
382: NodeList {
383: /** Default Constructor
384: */
385: public NodeListImpl() {
386: super ();
387: }
388:
389: /** nodelist length
390: * @return int for number of nodes in nodelist
391: */
392: public int getLength() {
393: return this .size();
394: }
395:
396: /** return a node
397: * @param aIndex int for the index of the node
398: * @return Node at the index
399: */
400: public Node item(int aIndex) {
401: return (Node) this.get(aIndex);
402: }
403: }
404:
405: }
|