001: /* CVS ID: $Id: XMLCommon.java,v 1.1.1.1 2002/10/02 18:42:54 wastl Exp $ */
002: package net.wastl.webmail.xml;
003:
004: import org.w3c.dom.*;
005:
006: import java.io.*;
007: import java.util.*;
008:
009: /*
010: * XMLCommon.java
011: *
012: * Created: Sat Mar 11 15:59:22 2000
013: *
014: * Copyright (C) 2000 Sebastian Schaffert
015: *
016: * This program is free software; you can redistribute it and/or
017: * modify it under the terms of the GNU General Public License
018: * as published by the Free Software Foundation; either version 2
019: * of the License, or (at your option) any later version.
020: *
021: * This program is distributed in the hope that it will be useful,
022: * but WITHOUT ANY WARRANTY; without even the implied warranty of
023: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
024: * GNU General Public License for more details.
025: *
026: * You should have received a copy of the GNU General Public License
027: * along with this program; if not, write to the Free Software
028: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
029: */
030: /**
031: * This class contains some static methods that are used commonly in other WebMail parts.
032: *
033: *
034: * @author Sebastian Schaffert
035: * @version
036: */
037:
038: public final class XMLCommon {
039:
040: public static Element getElementByAttribute(Element root,
041: String tagname, String attribute, String att_value) {
042: NodeList nl = root.getElementsByTagName(tagname);
043: for (int i = 0; i < nl.getLength(); i++) {
044: Element elem = (Element) nl.item(i);
045: if (elem.getAttribute(attribute).equals(att_value)) {
046: return elem;
047: }
048: }
049: return null;
050: }
051:
052: public static String getElementTextValue(Element e) {
053: e.normalize();
054: NodeList nl = e.getChildNodes();
055: if (nl.getLength() <= 0) {
056: System.err.println("Elements: " + nl.getLength());
057: return "";
058: } else {
059: String s = "";
060: for (int i = 0; i < nl.getLength(); i++) {
061: if (nl.item(i) instanceof CharacterData) {
062: s += nl.item(i).getNodeValue();
063: }
064: }
065: return s.trim();
066: }
067: }
068:
069: public static void setElementTextValue(Element e, String text) {
070: setElementTextValue(e, text, false);
071: }
072:
073: public static void setElementTextValue(Element e,String text, boolean cdata) {
074: Document root=e.getOwnerDocument();
075: e.normalize();
076: if(e.hasChildNodes()) {
077: NodeList nl=e.getChildNodes();
078:
079: /* This suxx: NodeList Object is changed when removing children !!!
080: I will store all nodes that should be deleted in a Vector and delete them afterwards */
081: int length=nl.getLength();
082:
083: Vector v=new Vector(nl.getLength());
084: for(int i=0;i<length;i++) {
085: if(nl.item(i) instanceof CharacterData) {
086: v.addElement(nl.item(i));
087: }
088: }
089: Enumeration enum=v.elements();
090: while(enum.hasMoreElements()) {
091: Node n=(Node)enum.nextElement();
092: e.removeChild(n);
093: }
094: }
095:
096: if(cdata) {
097: e.appendChild(root.createCDATASection(text));
098: } else {
099: e.appendChild(root.createTextNode(text));
100: }
101: }
102:
103: public static String getTagValue(Element e, String tagname) {
104: NodeList namel = e.getElementsByTagName(tagname);
105: if (namel.getLength() > 0) {
106: return getElementTextValue((Element) namel.item(0));
107: } else {
108: return null;
109: }
110: }
111:
112: /**
113: * Set the value of the first tag below e with name tagname to text.
114: */
115: public static void setTagValue(Element e, String tagname,
116: String text) {
117: setTagValue(e, tagname, text, false);
118: }
119:
120: public static void setTagValue(Element e, String tagname,
121: String text, boolean cdata) {
122: try {
123: setTagValue(e, tagname, text, false, "", cdata);
124: } catch (Exception ex) {
125: }
126: }
127:
128: public static void setTagValue(Element e, String tagname,
129: String text, boolean unique, String errormsg)
130: throws Exception {
131: setTagValue(e, tagname, text, unique, errormsg, false);
132: }
133:
134: public static void setTagValue(Element e, String tagname,
135: String text, boolean unique, String errormsg, boolean cdata)
136: throws Exception {
137:
138: if (text == null || tagname == null)
139: throw new NullPointerException(
140: "Text or Tagname may not be null!");
141:
142: Document root = e.getOwnerDocument();
143:
144: if (unique) {
145: // Check for double entries!
146: NodeList nl = ((Element) e.getParentNode())
147: .getElementsByTagName(tagname);
148: for (int i = 0; i < nl.getLength(); i++) {
149: if (getElementTextValue((Element) nl.item(0)).equals(
150: text)) {
151: throw new Exception(errormsg);
152: }
153: }
154: }
155: NodeList namel = e.getElementsByTagName(tagname);
156: Element elem;
157: if (namel.getLength() <= 0) {
158: System.err.println("Creating Element " + tagname
159: + "; will set to " + text);
160: elem = root.createElement(tagname);
161: e.appendChild(elem);
162: } else {
163: elem = (Element) namel.item(0);
164: }
165: //debugXML(root);
166: setElementTextValue(elem, text, cdata);
167: }
168:
169: public static void genericRemoveAll(Element parent, String tagname) {
170: NodeList nl=parent.getChildNodes();
171: Vector parts=new Vector();
172: for(int i=0;i<nl.getLength();i++) {
173: if(nl.item(i) instanceof Element) {
174: Element elem=(Element)nl.item(i);
175: if(elem.getTagName().equals(tagname)) {
176: parts.addElement(elem);
177: }
178: }
179: }
180: Enumeration enum=parts.elements();
181: while(enum.hasMoreElements()) {
182: parent.removeChild((Node)enum.nextElement());
183: }
184: }
185:
186: public static void writeXML(Document d, OutputStream os,
187: String sysID) throws IOException {
188: // Modified by exce, start
189: /**
190: * To support i18n, we have to specify the encoding of
191: * output writer to UTF-8 when we writing the XML.
192: */
193: // PrintWriter out=new PrintWriter(os);
194: PrintWriter out = new PrintWriter(new OutputStreamWriter(os,
195: "UTF-8"));
196: // Modified by exce, end
197:
198: out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
199: out.println();
200: out.println("<!DOCTYPE " + d.getDoctype().getName()
201: + " SYSTEM \"" + sysID + "\">");
202: out.println();
203: //d.getDocumentElement().normalize();
204: writeXMLwalkTree(d.getDocumentElement(), 0, out);
205: out.flush();
206: }
207:
208: protected static void writeXMLwalkTree(Node node, int indent,
209: PrintWriter out) {
210: if (node == null) {
211: System.err.println("??? Node was null ???");
212: return;
213: }
214: if (node.hasChildNodes()) {
215: if (node instanceof Element) {
216: Element elem = (Element) node;
217: //elem.normalize();
218: out.print("\n");
219: for (int j = 0; j < indent; j++) {
220: out.print(" ");
221: }
222: out.print("<" + elem.getTagName());
223: NamedNodeMap attrs = elem.getAttributes();
224: for (int i = 0; i < attrs.getLength(); i++) {
225: Attr a = (Attr) attrs.item(i);
226: out.print(" " + a.getName() + "=\"" + a.getValue()
227: + "\"");
228: }
229: out.print(">");
230: NodeList nl = node.getChildNodes();
231: for (int i = 0; i < nl.getLength(); i++) {
232: writeXMLwalkTree(nl.item(i), indent + 2, out);
233: }
234: // for(int j=0;j<indent;j++) {
235: // out.print(" ");
236: // }
237: out.println("</" + elem.getTagName() + ">");
238: }
239: } else {
240: if (node instanceof Element) {
241: Element elem = (Element) node;
242: out.print("\n");
243: for (int j = 0; j < indent; j++) {
244: out.print(" ");
245: }
246: out.print("<" + elem.getTagName());
247: NamedNodeMap attrs = elem.getAttributes();
248: for (int i = 0; i < attrs.getLength(); i++) {
249: Attr a = (Attr) attrs.item(i);
250: out.print(" " + a.getName() + "=\"" + a.getValue()
251: + "\"");
252: }
253: out.println("/>");
254: } else if (node instanceof CDATASection) {
255: CDATASection cdata = (CDATASection) node;
256: // for(int j=0;j<indent;j++) {
257: // out.print(" ");
258: // }
259: out.print("<![CDATA[" + cdata.getData() + "]]>");
260: } else if (node instanceof Text) {
261: Text text = (Text) node;
262: StringBuffer buf = new StringBuffer(text.getData()
263: .length());
264: for (int i = 0; i < text.getData().length(); i++) {
265: if (text.getData().charAt(i) == '\n'
266: || text.getData().charAt(i) == '\r'
267: || text.getData().charAt(i) == ' '
268: || text.getData().charAt(i) == '\t') {
269: if (buf.length() > 0
270: && buf.charAt(buf.length() - 1) != ' ') {
271: buf.append(' ');
272: }
273: } else {
274: buf.append(text.getData().charAt(i));
275: }
276: }
277: if (buf.length() > 0 && !buf.toString().equals(" ")) {
278: StringBuffer buf2 = new StringBuffer(buf.length()
279: + indent);
280: // for(int j=0;j<indent;j++) {
281: // buf2.append(' ');
282: // }
283: buf2.append(buf.toString());
284: out.print(buf2);
285: }
286: }
287: }
288: }
289:
290: /**
291: * This is a helper function to deal with problems that occur when importing Nodes from
292: * JTidy Documents to Xerces Documents.
293: */
294: public static Node importNode(Document d, Node n, boolean deep) {
295: Node r = cloneNode(d, n);
296: if (deep) {
297: NodeList nl = n.getChildNodes();
298: for (int i = 0; i < nl.getLength(); i++) {
299: Node n1 = importNode(d, nl.item(i), deep);
300: r.appendChild(n1);
301: }
302: }
303: return r;
304: }
305:
306: public static Node cloneNode(Document d, Node n) {
307: Node r = null;
308: switch (n.getNodeType()) {
309: case Node.TEXT_NODE:
310: r = d.createTextNode(((Text) n).getData());
311: break;
312: case Node.CDATA_SECTION_NODE:
313: r = d.createCDATASection(((CDATASection) n).getData());
314: break;
315: case Node.ELEMENT_NODE:
316: r = d.createElement(((Element) n).getTagName());
317: NamedNodeMap map = n.getAttributes();
318: for (int i = 0; i < map.getLength(); i++) {
319: ((Element) r).setAttribute(((Attr) map.item(i))
320: .getName(), ((Attr) map.item(i)).getValue());
321: }
322: break;
323: }
324: return r;
325: }
326:
327: public static synchronized void debugXML(Document d) {
328: try {
329: FileOutputStream fout = new FileOutputStream(
330: "/tmp/webmail.xml." + System.currentTimeMillis());
331: PrintWriter out = new PrintWriter(fout);
332: out.println("Debugging XML:");
333: out
334: .println("==============================================================");
335:
336: writeXML(d, fout, "test");
337: // OutputFormat of=new OutputFormat(Method.XML,"ISO-8859-1",true);
338: // of.setIndenting(true);
339: // of.setIndent(2);
340: // of.setDoctype(null,d.getDoctype().getName());
341: // of.setStandalone(false);
342: // System.err.println("Doctype system:"+of.getDoctypeSystem());
343: // XMLSerializer ser=new XMLSerializer(System.out,of);
344: // ser.serialize(d.getDocumentElement());
345: out
346: .println("==============================================================");
347: fout.flush();
348: fout.close();
349: } catch (Exception ex) {
350: ex.printStackTrace();
351: }
352: }
353: } // XMLCommon
|