001: /**
002: * <copyright>
003: *
004: * Copyright 2002-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: */package org.cougaar.tools.csmart.util;
026:
027: import org.apache.xerces.parsers.DOMParser;
028: import org.cougaar.tools.csmart.ui.viewer.CSMART;
029: import org.cougaar.util.ConfigFinder;
030: import org.cougaar.util.log.Logger;
031: import org.w3c.dom.Attr;
032: import org.w3c.dom.Document;
033: import org.w3c.dom.NamedNodeMap;
034: import org.w3c.dom.Node;
035: import org.xml.sax.InputSource;
036:
037: import java.io.File;
038: import java.io.FileInputStream;
039: import java.io.FileWriter;
040: import java.io.IOException;
041: import java.io.InputStream;
042: import java.io.PrintWriter;
043: import java.io.FileNotFoundException;
044:
045: /**
046: * XMLUtils.java
047: *
048: * Basic utilities for parsing and writing XML files.
049: *
050: * Created: Wed Jun 5 10:41:48 2002
051: *
052: */
053: public class XMLUtils {
054: private static Logger log = CSMART
055: .createLogger("org.coguaar.tools.csmart.util.XMLUtils");
056:
057: public XMLUtils() {
058: }
059:
060: /**
061: * Loads and parses an XML file into a <code>Document</code>
062: *
063: * @param filename Name of file to load.
064: * @return a <code>Document</code> value, null on error or nonexistent file
065: */
066: public static Document loadXMLFile(String filename) {
067: if (filename == null || filename.equals(""))
068: return null;
069:
070: // Try to open the file in an input stream. Note it may not exist!
071: InputStream is = null;
072: try {
073: is = ConfigFinder.getInstance("csmart").open(filename);
074: } catch (IOException ioe) {
075: if (log.isWarnEnabled()) {
076: log.warn("Could not open " + filename
077: + " for reading: " + ioe);
078: }
079: return null;
080: }
081: if (is == null) {
082: if (log.isWarnEnabled()) {
083: log
084: .warn("Could not open " + filename
085: + " for reading.");
086: }
087: return null;
088: }
089:
090: return loadXMLFile(is, filename);
091: }
092:
093: /**
094: * Loads and parses and XML file into a <code>Document</code>
095: *
096: * @param file - Handle to xml file.
097: * @return a <code>Document</code> value, null on error
098: */
099: public static Document loadXMLFile(File file)
100: throws FileNotFoundException {
101: if (file == null || !file.canRead() || file.isDirectory())
102: return null;
103:
104: return loadXMLFile(new FileInputStream(file), file.getName());
105: }
106:
107: private static Document loadXMLFile(InputStream stream, String name) {
108: try {
109: DOMParser parser = new DOMParser();
110: parser.parse(new InputSource(stream));
111: return parser.getDocument();
112: } catch (org.xml.sax.SAXParseException spe) {
113: if (log.isErrorEnabled()) {
114: log.error("Parse exception Parsing file: " + name, spe);
115: }
116: } catch (org.xml.sax.SAXException se) {
117: if (log.isErrorEnabled()) {
118: log.error("SAX exception Parsing file: " + name, se);
119: }
120: } catch (Exception e) {
121: if (log.isErrorEnabled()) {
122: log.error("Exception Parsing file: " + name, e);
123: }
124: }
125:
126: return null;
127: }
128:
129: /**
130: * Writes the contents of the <code>Node</code> to the specified
131: * file, in XML format.
132: *
133: * @param configDir - Directory to write new xml file.
134: * @param node - Document Node to dump to xml file.
135: * @param name - Name of the new xml file.
136: * @see org.w3c.dom.Node
137: * @exception IOException if an error occurs
138: */
139: public static void writeXMLFile(File configDir, Node node,
140: String name) throws IOException {
141:
142: Logger log = CSMART
143: .createLogger("org.cougaar.tools.csmart.util.XMLUtils");
144:
145: if (!name.endsWith(".xml")) {
146: name = name + ".xml";
147: }
148: PrintWriter writer = new PrintWriter(new FileWriter(new File(
149: configDir, name)));
150: try {
151: writeNode(writer, node, 0);
152: } catch (Exception e) {
153: if (log.isErrorEnabled()) {
154: log.error("Error writing config file: " + e);
155: }
156: } finally {
157: writer.close();
158: }
159:
160: }
161:
162: private static void writeNode(PrintWriter writer, Node node,
163: int indent) {
164: StringBuffer ibuff = new StringBuffer();
165: for (int i = 0; i < indent; i++) {
166: ibuff.append(" ");
167: }
168: int type = node.getNodeType();
169: switch (type) {
170: case Node.DOCUMENT_NODE:
171: writer.println("<?xml version=\"1.0\" encoding=\""
172: + "UTF-8" + "\"?>");
173: indent = -2;
174: break;
175: case Node.ELEMENT_NODE:
176: writer.print(ibuff.substring(0) + '<' + node.getNodeName());
177: NamedNodeMap nnm = node.getAttributes();
178: if (nnm != null) {
179: int len = nnm.getLength();
180: Attr attr;
181: for (int i = 0; i < len; i++) {
182: attr = (Attr) nnm.item(i);
183: writer.print(' ' + attr.getNodeName() + "=\""
184: + attr.getNodeValue() + '"');
185: }
186: }
187: writer.println('>');
188: break;
189:
190: case Node.ENTITY_REFERENCE_NODE:
191: writer.print('&' + node.getNodeName() + ';');
192: break;
193: case Node.CDATA_SECTION_NODE:
194: writer.print("<![CDATA[" + node.getNodeValue() + "]]>");
195: break;
196: case Node.TEXT_NODE:
197: writer.print(ibuff.substring(0) + node.getNodeValue());
198: break;
199: case Node.PROCESSING_INSTRUCTION_NODE:
200: writer
201: .print(ibuff.substring(0) + "<?"
202: + node.getNodeName());
203: String data = node.getNodeValue();
204: if (data != null && data.length() > 0) {
205: writer.print(' ');
206: writer.print(data);
207: }
208: writer.println("?>");
209: break;
210:
211: }//end of switch
212:
213: //recurse
214: for (Node child = node.getFirstChild(); child != null; child = child
215: .getNextSibling()) {
216: writeNode(writer, child, indent + 2);
217: }
218:
219: //without this the ending tags will miss
220: if (type == Node.ELEMENT_NODE) {
221: writer.println(ibuff.substring(0) + "</"
222: + node.getNodeName() + ">");
223: }
224: }
225:
226: }// XMLUtils
|