001: package com.salmonllc.xml;
002:
003: /////////////////////////
004: //$Archive: /SOFIA/SourceCode/com/salmonllc/xml/XMLTreeParser.java $
005: //$Author: Dan $
006: //$Revision: 10 $
007: //$Modtime: 6/11/03 4:53p $
008: /////////////////////////
009: /**
010: * The XML Tree paser is used to parse any XML file specified as Tree.dtd file.
011: */
012:
013: import java.io.*;
014:
015: import org.w3c.dom.*;
016:
017: public class XMLTreeParser {
018:
019: /** Default parser name. */
020: private static final String DEFAULT_PARSER_NAME = "com.salmonllc.xml.DOMParser";
021:
022: private static String URIpath = "";
023:
024: private static Tree fieldTree = null;
025:
026: /** Default Encoding */
027: private static String PRINTWRITER_ENCODING = "UTF8";
028:
029: private static String MIME2JAVA_ENCODINGS[] = { "Default", "UTF-8",
030: "US-ASCII", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3",
031: "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
032: "ISO-8859-8", "ISO-8859-9", "ISO-2022-JP", "SHIFT_JIS",
033: "EUC-JP", "GB2312", "BIG5", "EUC-KR", "ISO-2022-KR",
034: "KOI8-R", "EBCDIC-CP-US", "EBCDIC-CP-CA", "EBCDIC-CP-NL",
035: "EBCDIC-CP-DK", "EBCDIC-CP-NO", "EBCDIC-CP-FI",
036: "EBCDIC-CP-SE", "EBCDIC-CP-IT", "EBCDIC-CP-ES",
037: "EBCDIC-CP-GB", "EBCDIC-CP-FR", "EBCDIC-CP-AR1",
038: "EBCDIC-CP-HE", "EBCDIC-CP-CH", "EBCDIC-CP-ROECE",
039: "EBCDIC-CP-YU", "EBCDIC-CP-IS", "EBCDIC-CP-AR2", "UTF-16" };
040:
041: /** Print writer. */
042: protected PrintWriter out;
043:
044: /** Canonical output. */
045: protected boolean canonical;
046:
047: public XMLTreeParser(String encoding, boolean canonical)
048: throws UnsupportedEncodingException {
049: out = new PrintWriter(new OutputStreamWriter(System.out,
050: encoding));
051: this .canonical = canonical;
052: fieldTree = new Tree();
053: } // <init>(String,boolean)
054:
055: //
056: // Constructors
057: //
058:
059: /** Default constructor. */
060: public XMLTreeParser(boolean canonical)
061: throws UnsupportedEncodingException {
062: this (getWriterEncoding(), canonical);
063: }
064:
065: /**
066: * Creation date: (7/20/01 2:03:28 PM)
067: * @return java.lang.String
068: * @param node org.w3c.dom.Node
069: * @param columnName java.lang.String
070: */
071: private boolean getNodeBooleanValue(Node node, String columnName) {
072:
073: Node temp = node.getAttributes().getNamedItem(columnName);
074: if (temp != null)
075: return temp.getNodeValue().equals("true");
076:
077: return false;
078: }
079:
080: /**
081: * Creation date: (7/20/01 2:03:28 PM)
082: * @return java.lang.String
083: * @param node org.w3c.dom.Node
084: * @param columnName java.lang.String
085: */
086: private String getNodeValue(Node node, String columnName) {
087:
088: Node temp = node.getAttributes().getNamedItem(columnName);
089: if (temp != null)
090: return temp.getNodeValue();
091:
092: return null;
093: }
094:
095: /**
096: * Gets the Tree detailed in XML file
097: * Creation date: (8/21/01 5:12:27 PM)
098: * @return com.salmonllc.xml.Tree
099: */
100: public static Tree getTree() {
101: return fieldTree;
102: }
103:
104: private static String getWriterEncoding() {
105: return (PRINTWRITER_ENCODING);
106: }// getWriterEncoding
107:
108: private static boolean isValidJavaEncoding(String encoding) {
109: for (int i = 0; i < MIME2JAVA_ENCODINGS.length; i++)
110: if (encoding.equals(MIME2JAVA_ENCODINGS[i]))
111: return (true);
112:
113: return (false);
114: }// isValidJavaEncoding
115:
116: //
117: // Main
118: //
119:
120: /** Main program entry point. */
121: public static void main(String argv[]) {
122:
123: // is there anything to do?
124: if (argv.length == 0) {
125: printUsage();
126: System.exit(1);
127: }
128:
129: // vars
130:
131: String encoding = "UTF8"; // default encoding
132:
133: // check parameters
134: for (int i = 0; i < argv.length; i++) {
135: String arg = argv[i];
136:
137: // options
138: if (arg.startsWith("-")) {
139: if (arg.equals("-p")) {
140: if (i == argv.length - 1) {
141: System.err
142: .println("error: missing parser name");
143: System.exit(1);
144: }
145: continue;
146: }
147:
148: if (arg.equals("-c")) {
149: continue;
150: }
151:
152: if (arg.equals("-h")) {
153: printUsage();
154: System.exit(1);
155: }
156:
157: if (arg.equals("-e")) {
158: if (i == argv.length - 1) {
159: System.err
160: .println("error: missing encoding name");
161: printValidJavaEncoding();
162: System.exit(1);
163: } else {
164: encoding = argv[++i];
165: if (isValidJavaEncoding(encoding))
166: setWriterEncoding(encoding);
167: else {
168: printValidJavaEncoding();
169: System.exit(1);
170: }
171: }
172: continue;
173: }
174:
175: }
176:
177: // print uri
178: System.err.println(arg + ':');
179: //parseFile(parserName, arg, canonical );
180: System.err.println();
181: }
182:
183: } // main(String[])
184:
185: /** Normalizes the given string. */
186: protected String normalize(String s) {
187: StringBuffer str = new StringBuffer();
188:
189: int len = (s != null) ? s.length() : 0;
190: for (int i = 0; i < len; i++) {
191: char ch = s.charAt(i);
192: switch (ch) {
193: case '<': {
194: str.append("<");
195: break;
196: }
197: case '>': {
198: str.append(">");
199: break;
200: }
201: case '&': {
202: str.append("&");
203: break;
204: }
205: case '"': {
206: str.append(""");
207: break;
208: }
209: case '\r':
210: case '\n': {
211: if (canonical) {
212: str.append("&#");
213: str.append(Integer.toString(ch));
214: str.append(';');
215: break;
216: }
217: // else, default append char
218: }
219: default: {
220: str.append(ch);
221: }
222: }
223: }
224:
225: return (str.toString());
226:
227: } // normalize(String):String
228:
229: /**
230: * This method is used to create the Tree object out of the XML file. XML file name
231: * is passed as uri. Method getTree is used after this method to get the Tree object.
232: *
233: */
234: public static void parseFile(String uri) throws Exception {
235: parseFile(DEFAULT_PARSER_NAME, uri, false);
236:
237: } // print(String,String,boolean)
238:
239: /** Prints the resulting document tree. */
240: private static void parseFile(String parserWrapperName, String uri,
241: boolean canonical) throws Exception {
242: int nUriLastSlashIndex = uri.lastIndexOf("\\");
243: boolean anypath = true;
244: if (nUriLastSlashIndex == -1) {
245: anypath = false;
246: nUriLastSlashIndex = uri.lastIndexOf("/");
247: if (nUriLastSlashIndex != -1) {
248: anypath = true;
249: }
250: }
251:
252: if (anypath)
253: URIpath = uri.substring(0, nUriLastSlashIndex);
254:
255: DOMParserWrapper parser = (DOMParserWrapper) Class.forName(
256: parserWrapperName).newInstance();
257: Document document = parser.parse(uri);
258: XMLTreeParser writer = new XMLTreeParser(canonical);
259: writer.parseNode(document);
260: System.out.println("Done" + getTree());
261: } // print(String,String,boolean)
262:
263: /** Prints the specified node, recursively. */
264: private void parseNode(Node node) {
265:
266: // is there anything to do?
267: if (node == null) {
268: return;
269: }
270:
271: int type = node.getNodeType();
272: switch (type) {
273: // print document
274: case Node.DOCUMENT_NODE:
275: parseNode(((Document) node).getDocumentElement());
276: break;
277: // print element with attributes
278: case Node.ELEMENT_NODE:
279:
280: if (node.getNodeName().equalsIgnoreCase("Tree")) {
281: NodeList children = node.getChildNodes();
282: if (children != null) {
283: if (getTree() == null)
284: setTree(new Tree());
285:
286: getTree().setName(getNodeValue(node, "name"));
287: getTree().setExpandImage(
288: getNodeValue(node, "expandImage"));
289: getTree().setContractImage(
290: getNodeValue(node, "contractImage"));
291: getTree().setNullImage(
292: getNodeValue(node, "nullImage"));
293: getTree().setSelectMode(
294: getNodeValue(node, "selectMode"));
295: getTree().setTreeMode(
296: getNodeValue(node, "treeMode"));
297: getTree().setShowRoot(
298: getNodeBooleanValue(node, "showRoot"));
299: getTree().setTarget(getNodeValue(node, "target"));
300:
301: int len = children.getLength();
302: for (int i = 0; i < len; i++) {
303: Node nodeChild = children.item(i);
304: if (nodeChild.getNodeName().equalsIgnoreCase(
305: "TreeItem")) {
306: parseNode(nodeChild, getTree());
307: }
308: }
309: }
310: }
311:
312: break;
313:
314: }
315: }
316:
317: /** Prints the specified node, recursively. */
318: private Tree parseNode(Node node, Tree tree) {
319: int type = node.getNodeType();
320: switch (type) {
321: // print document
322: case Node.DOCUMENT_NODE:
323: parseNode(((Document) node).getDocumentElement());
324: break;
325: // print element with attributes
326: case Node.ELEMENT_NODE:
327:
328: if (node.getNodeName().equalsIgnoreCase("TreeItem")) {
329: NodeList children = node.getChildNodes();
330: if (children != null) {
331: TreeItem item = new TreeItem();
332: item.setText(getNodeValue(node, "text"));
333: item.setHref(getNodeValue(node, "href"));
334: item.setImgSource(getNodeValue(node, "imgsource"));
335: item.setImgExpSource(getNodeValue(node,
336: "imgexpsource"));
337: item.setImgHref(getNodeValue(node, "imghref"));
338:
339: if (tree.getChilds() == null)
340: tree.setChilds(new java.util.Vector());
341: else
342: tree.getChilds().add(item);
343:
344: int len = children.getLength();
345: for (int i = 0; i < len; i++) {
346: Node nodeChild = children.item(i);
347: if (nodeChild.getNodeName().equalsIgnoreCase(
348: "TreeItem"))
349: parseNode(nodeChild, item);
350: if (nodeChild.getNodeName().equalsIgnoreCase(
351: "TreeItemAddImage")) {
352: if (item.getAddImages() == null) {
353: item
354: .setAddImages(new java.util.Vector());
355: }
356: // Create a Add image Object
357: TreeItemAddImage addImage = new TreeItemAddImage();
358: addImage.setHref(getNodeValue(nodeChild,
359: "href"));
360: addImage.setName(getNodeValue(nodeChild,
361: "name"));
362: addImage.setSrc(getNodeValue(nodeChild,
363: "src"));
364: addImage.setText(getNodeValue(nodeChild,
365: "text"));
366: // add it to a Tree Item - Node
367: item.getAddImages().add(addImage);
368:
369: }
370: }
371: }
372: }
373:
374: break;
375: }
376:
377: return tree;
378: }
379:
380: /** Prints the usage. */
381: private static void printUsage() {
382:
383: System.err
384: .println("usage: java dom.DOMWriter (options) uri ...");
385: System.err.println();
386: System.err.println("options:");
387: System.err
388: .println(" -p name Specify DOM parser wrapper by name.");
389: System.err.println(" Default parser: "
390: + DEFAULT_PARSER_NAME);
391: System.err.println(" -c Canonical XML output.");
392: System.err.println(" -h This help screen.");
393: System.err.println(" -e Output Java Encoding.");
394: System.err.println(" Default encoding: UTF-8");
395:
396: } // printUsage()
397:
398: private static void printValidJavaEncoding() {
399: System.err.println(" ENCODINGS:");
400: System.err.print(" ");
401: for (int i = 0; i < MIME2JAVA_ENCODINGS.length; i++) {
402: System.err.print(MIME2JAVA_ENCODINGS[i] + " ");
403: if ((i % 7) == 0) {
404: System.err.println();
405: System.err.print(" ");
406: }
407: }
408:
409: } // printJavaEncoding()
410:
411: /**
412: * Creation date: (8/21/01 5:12:27 PM)
413: * @param newTree com.salmonllc.xml.Tree
414: */
415: private static void setTree(Tree newTree) {
416: fieldTree = newTree;
417: }
418:
419: private static void setWriterEncoding(String encoding) {
420: if (encoding.equalsIgnoreCase("DEFAULT"))
421: PRINTWRITER_ENCODING = "UTF8";
422: else if (encoding.equalsIgnoreCase("UTF-16"))
423: PRINTWRITER_ENCODING = "Unicode";
424: //else
425: // PRINTWRITER_ENCODING = MIME2Java.convert( encoding );
426: }// setWriterEncoding
427:
428: /** Returns a sorted list of attributes. */
429: protected Attr[] sortAttributes(NamedNodeMap attrs) {
430:
431: int len = (attrs != null) ? attrs.getLength() : 0;
432: Attr array[] = new Attr[len];
433: for (int i = 0; i < len; i++) {
434: array[i] = (Attr) attrs.item(i);
435: }
436: for (int i = 0; i < len - 1; i++) {
437: String name = array[i].getNodeName();
438: int index = i;
439: for (int j = i + 1; j < len; j++) {
440: String curName = array[j].getNodeName();
441: if (curName.compareTo(name) < 0) {
442: name = curName;
443: index = j;
444: }
445: }
446: if (index != i) {
447: Attr temp = array[i];
448: array[i] = array[index];
449: array[index] = temp;
450: }
451: }
452:
453: return (array);
454:
455: } // sortAttributes(NamedNodeMap):Attr[]
456: }
|