001: /*
002: * <copyright>
003: *
004: * Copyright 2003-2004 BBNT Solutions, LLC
005: * under sponsorship of the Defense Advanced Research Projects
006: * Agency (DARPA).
007: *
008: * You can redistribute this software and/or modify it under the
009: * terms of the Cougaar Open Source License as published on the
010: * Cougaar Open Source Website (www.cougaar.org).
011: *
012: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
013: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
014: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
015: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
016: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
017: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
018: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
019: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
020: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
021: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
022: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
023: *
024: * </copyright>
025: */
026: package org.cougaar.lib.aggagent.util;
027:
028: import java.io.BufferedReader;
029: import java.io.IOException;
030: import java.io.InputStream;
031: import java.io.InputStreamReader;
032: import java.io.OutputStream;
033: import java.io.PrintStream;
034: import java.io.StringReader;
035: import java.net.HttpURLConnection;
036: import java.net.MalformedURLException;
037: import java.net.URL;
038: import java.net.URLConnection;
039:
040: import org.apache.xerces.parsers.DOMParser;
041: import org.w3c.dom.Element;
042: import org.w3c.dom.Node;
043: import org.w3c.dom.NodeList;
044: import org.xml.sax.InputSource;
045: import org.xml.sax.SAXException;
046:
047: /**
048: * The XmlUtils class is the home of a suite of static convenience methods for
049: * handling XML documents. Support for parsing, traversing, and generating
050: * these documents may be found here.
051: */
052: public class XmlUtils {
053: /**
054: * when debug is set to true, all XML is printed to standard out before it
055: * is parsed.
056: */
057: public static boolean debug = false;
058:
059: /**
060: * This convenience method searches for a child Element and attempts to
061: * parse its content text as an integer. An Exception will be raised if
062: * no such Element exists, or else one exists, but its contents cannot be
063: * intrepreted as an integer. If the Element has more than one child with
064: * the given name, then the first one is used (even if the contents are
065: * invalid).
066: */
067: public static int getChildInt(Element elt, String tag)
068: throws NumberFormatException {
069: return Integer.parseInt(getChildText(elt, tag));
070: }
071:
072: /**
073: * Search for an Element of the given name that is a child of the specified
074: * Element. If any such Elements exist, the first is returned; otherwise,
075: * the method returns null. Note: the search will return only direct
076: * children, as opposed to higher-order descendants (e.g., grandchildren).
077: */
078: public static Element getChildElement(Element elt, String tag) {
079: NodeList nl = elt.getChildNodes();
080: for (int i = 0; i < nl.getLength(); i++) {
081: Node n = nl.item(i);
082: if (n.getNodeType() == Node.ELEMENT_NODE
083: && n.getNodeName().equals(tag))
084: return (Element) n;
085: }
086: return null;
087: }
088:
089: /**
090: * This convenience method extracts the text content of a child Element
091: * whose name is specified by the caller. Assuming such an Element exists,
092: * its contents are handled as in getElementText (q.v.). If there are many
093: * child Elements matching the description, the first one is used. If there
094: * are no such Elements, then this method returns null.
095: */
096: public static String getChildText(Element elt, String tag) {
097: return getElementText(getChildElement(elt, tag));
098: }
099:
100: /**
101: * This convenience method extracts the text content of an XML element
102: * (including white spaces). If the Element has child Elements, they are
103: * ignored, and the intervening Text nodes are concatenated into the result.
104: * This method will return null if and only if it is passed a null Element.
105: */
106: public static String getElementText(Element elt) {
107: if (elt == null)
108: return null;
109:
110: StringBuffer buf = new StringBuffer();
111: NodeList nl = elt.getChildNodes();
112: for (int i = 0; i < nl.getLength(); i++) {
113: Node n = nl.item(i);
114: if (n.getNodeType() == Node.TEXT_NODE)
115: buf.append(n.getNodeValue());
116: }
117: return buf.toString();
118: }
119:
120: /**
121: * Parse an XML document and return the "document element", which is the
122: * root of the XML structure as specified in the text of the document. For
123: * this method, the text must come from a String.
124: */
125: public static Element parse(String s) throws IOException,
126: SAXException {
127: if (debug) {
128: System.out
129: .println("------------------ XML to parse ------------------");
130: System.out.println(s);
131: System.out
132: .println("--------------------------------------------------");
133: }
134: InputSource in = new InputSource(new StringReader(s));
135: return parse(in);
136: }
137:
138: /**
139: * Parse an XML document and return the "document element", which is the
140: * root of the XML structure as specified in the text of the document. For
141: * this method, the text must come from an InputStream.
142: */
143: public static Element parse(InputStream s) throws IOException,
144: SAXException {
145: if (debug) {
146: // redirect to string based reader for debug
147: String in = readToString(s);
148: return parse(in);
149: }
150: InputSource in = new InputSource(s);
151: return parse(in);
152: }
153:
154: /**
155: * Parse an XML document and return the "document element", which is the
156: * root of the XML structure as specified in the text of the document. By
157: * and large, this method will be called by other parse methods after
158: * converting the source of the XML text into an InputSource.
159: */
160: public static Element parse(InputSource in) throws IOException,
161: SAXException {
162: // We believe that all the XML will be well-formed, so this method should
163: // always succeed.
164: DOMParser p = new DOMParser();
165: p.parse(in);
166: return p.getDocument().getDocumentElement();
167: }
168:
169: /**
170: * Post request to URL represented by passed string. Return parsed XML
171: * response. Currently just catches exceptions and prints message to
172: * standard out (returning null).
173: */
174: public static Element requestXML(String urlString, String request) {
175: Element parsedResponse = null;
176: InputStream is = null;
177:
178: try {
179: is = sendRequest(urlString, request);
180: parsedResponse = parse(is);
181: } catch (MalformedURLException mfe) {
182: System.out.println("Failed to send request: bad URL<br>");
183: System.out.println("\"" + urlString + "\"");
184: } catch (IOException ioe) {
185: System.out.println("Failed to send request: io Exception");
186: } catch (SAXException se) {
187: System.out
188: .println("Failed to parse response: sax Exception");
189: se.printStackTrace();
190: }
191:
192: return parsedResponse;
193: }
194:
195: /**
196: * Post request to URL represented by passed string. Return response as
197: * string. Currently just catches exceptions and prints message to
198: * standard out (returning null).
199: */
200: public static String requestString(String urlString, String request) {
201: String response = null;
202:
203: try {
204: if (debug) {
205: System.out.println("requestString:");
206: System.out.println(" url: " + urlString);
207: System.out.println(" request: " + request);
208: }
209: InputStream is = sendRequest(urlString, request);
210: response = readToString(is);
211: if (debug) {
212: System.out.println(" response: " + response);
213: }
214: } catch (MalformedURLException mfe) {
215: System.out.println("Failed to send request: bad URL<br>");
216: System.out.println("\"" + urlString + "\"");
217: } catch (IOException ioe) {
218: System.out.println("Failed to send request: io Exception");
219: }
220:
221: return response;
222: }
223:
224: /**
225: * Post request to URL represented by passed string. Return response as
226: * input stream.
227: */
228: public static InputStream sendRequest(String urlString,
229: String request) throws MalformedURLException, IOException {
230: // open connection
231: URL url = new URL(urlString);
232: URLConnection uc = url.openConnection();
233: ((HttpURLConnection) uc).setRequestMethod("PUT");
234: uc.setDoInput(true);
235: uc.setDoOutput(true);
236: OutputStream os = uc.getOutputStream();
237: PrintStream servicePrint = new PrintStream(os);
238:
239: // send request
240: if (request != null)
241: servicePrint.println(request);
242:
243: return uc.getInputStream();
244: }
245:
246: public static String readToString(InputStream is)
247: throws IOException {
248: StringBuffer buf = new StringBuffer();
249: BufferedReader bufr = new BufferedReader(new InputStreamReader(
250: is));
251: String line = null;
252: while ((line = bufr.readLine()) != null) {
253: buf.append(line);
254: buf.append("\n");
255: }
256: return buf.toString();
257: }
258: }
|