home *** CD-ROM | disk | FTP | other *** search
/ Dynamic HTML in Action / Dynamicke-HTML-v-akci-covermount.bin / XML / PARSER / XMLINST.EXE / msxml.java < prev    next >
Encoding:
Java Source  |  1997-12-01  |  16.3 KB  |  523 lines

  1.  
  2. import com.ms.xml.parser.*;
  3. import com.ms.xml.om.Document;
  4. import com.ms.xml.om.Element;
  5. import com.ms.xml.util.XMLOutputStream;
  6. import com.ms.xml.util.Name;
  7. import com.ms.xml.om.ElementEnumeration;
  8. import com.ms.xml.om.ElementImpl;
  9.  
  10. import java.util.Enumeration;
  11. import java.io.*;
  12. import java.io.PrintStream;
  13. import java.net.*;
  14.  
  15.  
  16. import com.ms.xml.util.Name;
  17. import com.ms.xml.om.ElementFactory;
  18.  
  19. //-------------------------------------------------------------------
  20. class NullElementFactory implements ElementFactory
  21. {
  22.     public NullElementFactory()
  23.     {
  24.     }
  25.  
  26.     public Element createElement(Element parent, int type, Name tag, String text)
  27.     {
  28.         return null;
  29.     }
  30.  
  31.     public void parsed(Element elem) 
  32.     {
  33.     }
  34.  
  35.     public void parsedAttribute(Element e, Name name, Object value)
  36.     {
  37.     }
  38. }    
  39.  
  40.  
  41. //-------------------------------------------------------------------
  42. class msxml
  43. {
  44.  
  45.     public static void main(String args[])
  46.     {        
  47.         parseArgs(args);
  48.         if (fileName == null && omtest == false) 
  49.         {
  50.             printUsage(System.out);
  51.         } 
  52.         else 
  53.         {
  54.             if (omtest) omTest();
  55.             if (fileName == null) return;
  56.  
  57.             URL url = createURL(fileName);    
  58.  
  59.             Document d = null;
  60.             try 
  61.             {
  62.                 for (long i = 0; i < loops; i++) 
  63.                 {
  64.                     if (fast)
  65.                         d = new Document(new NullElementFactory()); 
  66.                     else
  67.                         d = new Document(); 
  68.                     Start();
  69.                     InputStream instream = null;
  70.                     d.setCaseInsensitive(caseInsensitive);
  71.                     d.setLoadExternal(loadexternal);
  72.                     if (stream) 
  73.                     {
  74.                         try 
  75.                         {
  76.                             instream = url.openStream();
  77.                         } 
  78.                         catch (IOException e) 
  79.                         {
  80.                             System.out.println("Error opening input stream for \"" + 
  81.                                 url.toString() + "\": " + e.toString());
  82.                             System.exit(0);
  83.                         }
  84.                         d.load(instream);
  85.                     } 
  86.                     else 
  87.                     {
  88.                         d.load(url);
  89.                     }
  90.                     Stop();
  91.                     if (i < loops - 1)
  92.                     {
  93.                         // Force garbage collection now.
  94.                         d = null;
  95.                         System.gc();
  96.                     }
  97.                 }
  98. //                if (timeit) reportTimes(System.out);
  99.  
  100.             } 
  101.             catch (ParseException e) 
  102.             {
  103.                 d.reportError(e, System.out);
  104.                 d = null; // don't dump tree then.
  105.             }
  106.  
  107.             if (d != null) 
  108.             {
  109.                 if (tree) 
  110.                 {
  111.                     try 
  112.                     {
  113.                         dumpTree(d,new PrintStream(out),"");
  114.                     } 
  115.                     catch( IOException e ) 
  116.                     {
  117.                         System.out.println( "Error saving output stream." );
  118.                     }
  119.                 } 
  120.                 else if (schema)
  121.                 {
  122.                     try 
  123.                     {
  124.                         dumpSchema(d,d.createOutputStream(out));
  125.                     } 
  126.                     catch( IOException e ) 
  127.                     {
  128.                         System.out.println( "Error saving output stream." );
  129.                     }
  130.                 }
  131.                 else if (output ) 
  132.                 {
  133.                     if( outputEncoding != null )                    
  134.                         d.setEncoding( outputEncoding );
  135.                     d.setOutputStyle(style);
  136.                     try 
  137.                     {             
  138.                         XMLOutputStream xout = d.createOutputStream(out);
  139.                         d.save(xout);
  140.                     } 
  141.                     catch( IOException e ) 
  142.                     {
  143.                         System.out.println( "Error saving output stream." );
  144.                     }
  145.                 }
  146.  
  147. //                System.out.println(d.getText());
  148.             }
  149.         }   
  150.         System.exit(0);
  151.     } 
  152.  
  153.     static void printUsage(PrintStream o)
  154.     {
  155.         o.println("Usage:  jview msxml [-d|-d1|-d2|-f] [-t num] [-e encoding] [-o filename] [-c|-p] [-i] [-m] [-s] filename");
  156.         o.println(); 
  157.         o.println("Version: 1.0.8");
  158.         o.println(); 
  159.         o.println("This program parses the given XML file and optionally dumps");
  160.         o.println("the resulting data structures to standard output.\n");
  161.         o.println("Arguments:");
  162.         o.println("-d\tWrite parsed XML in original XML format.");
  163.         o.println("-d1\tWrite parsed XML in a tree format.");
  164.         o.println("-d2\tWrite schema representation of DTD.");
  165.         o.println("-f\tFast parsing that bypasses tree building.");
  166.         o.println("-t\tSpecifies how many iterations to time the parser.");
  167.         o.println("-o\tProvides a filename for dumping output.");
  168.         o.println("\t(This is needed if data is in Unicode.)");
  169.         o.println("-e\tCharacter encoding for output other than that of the input.");
  170.         o.println("-c\tOutput in compact mode (no newlines or tabs).");
  171.         o.println("-p\tOutput in pretty mode (inserts newlines & tabs).");
  172.         o.println("-i\tSwitch to case insensitive.");
  173.         o.println("-m\tPerform object model test, which creates test file 'test.xml'.");
  174.         o.println("-s\tStandalone - do not load external DTD's or entities.\n");
  175.     }
  176.     
  177.     static void parseArgs(String args[])
  178.     {
  179.         for (int i = 0; i < args.length; i++)
  180.         {
  181.             if (args[i].equals("-d")) 
  182.             {
  183.                 output = true;
  184.             } 
  185.             else if (args[i].equals("-d1")) 
  186.             {
  187.                 tree = true;
  188.                 output = true;
  189.             } 
  190.             else if (args[i].equals("-d2")) 
  191.             {
  192.                 schema = true;
  193.                 output = true;
  194.             } 
  195.             else if (args[i].equals("-t")) 
  196.             {
  197.                 i++;
  198.                 Integer value = new Integer(args[i]);
  199.                 loops = value.intValue();
  200.                 timeit = true;
  201.             } 
  202.             else if (args[i].equals("-i")) 
  203.             {
  204.                 caseInsensitive = true;
  205.             } 
  206.             else if (args[i].equals("-f")) 
  207.             {
  208.                 fast = true;
  209.             } 
  210.             else if (args[i].equals("-o")) 
  211.             {
  212.                 i++;
  213.                 try 
  214.                 {
  215.                     out = new FileOutputStream( args[i] );
  216.                 } 
  217.                 catch( IOException e ) 
  218.                 {
  219.                     out = System.out;
  220.                 }
  221.             } 
  222.             else if (args[i].equals("-e")) 
  223.             {
  224.                 i++;
  225.                 outputEncoding = args[i];
  226.             } 
  227.             else if (args[i].equals("-c")) 
  228.             {
  229.                 style = XMLOutputStream.COMPACT;
  230.             } 
  231.             else if (args[i].equals("-p")) 
  232.             {
  233.                 style = XMLOutputStream.PRETTY;
  234.             } 
  235.             else if (args[i].equals("-m")) 
  236.             {
  237.                 omtest = true;
  238.             } 
  239.             else if (args[i].equals("-s")) 
  240.             {
  241.                 loadexternal = false;
  242.             } 
  243.             else 
  244.             {
  245.                 fileName = args[i];
  246.             }
  247.         }        
  248.     }
  249.     
  250.     static void Start() 
  251.     { 
  252.         start = System.currentTimeMillis(); 
  253.     }
  254.  
  255.     static void Stop() 
  256.     { 
  257.         long end = System.currentTimeMillis(); 
  258.         long time = end-start;
  259.         if (timeit)
  260.             System.out.println("time=" + time); //  + " created=" + Name.created + " reused=" + Name.reused);
  261. //        Name.created = 0;
  262. //        Name.reused = 0;
  263.         if (min == 0 || time < min) min = time;
  264.         if (max == 0 || time > max) max = time;
  265.         sum += (end-start);
  266.         count++;
  267.     }
  268.  
  269.     static void reportTimes(PrintStream o) 
  270.     {
  271.         o.println("Parsed " + count + " times:");
  272.         o.println("\tMin="+ min + " milliseconds.");
  273.         o.println("\tMax="+ max + " milliseconds.");
  274.         o.println("\tAverage="+ (sum/count) + " milliseconds.");
  275.     }
  276.  
  277.     static URL createURL(String fileName) 
  278.     {
  279.         URL url = null;
  280.         try 
  281.         {
  282.             url = new URL(fileName);
  283.         } 
  284.         catch (MalformedURLException ex) 
  285.         {
  286.             File f = new File(fileName);
  287.             try 
  288.             {
  289.                 String path = f.getAbsolutePath();
  290.                 // This is a bunch of weird code that is required to
  291.                 // make a valid URL on the Windows platform, due
  292.                 // to inconsistencies in what getAbsolutePath returns.
  293.                 String fs = System.getProperty("file.separator");
  294.                 if (fs.length() == 1) 
  295.                 {
  296.                     char sep = fs.charAt(0);
  297.                     if (sep != '/')
  298.                         path = path.replace(sep, '/');
  299.                     if (path.charAt(0) != '/')
  300.                         path = '/' + path;
  301.                 }
  302.                 path = "file://" + path;
  303.                 url = new URL(path);
  304.             } 
  305.             catch (MalformedURLException e) 
  306.             {
  307.                 System.out.println("Cannot create url for: " + fileName);
  308.                 System.exit(0);
  309.             }
  310.         }
  311.         return url;
  312.     }
  313.  
  314.     // dumpTree dumps a tree out in the following format:
  315.     // 
  316.     // root
  317.     // |---node
  318.     // |---node2
  319.     // |   |---foo
  320.     // |   +---bar.
  321.     // +---lastnode
  322.     //     |---apple
  323.     //     +---orange.
  324.     //
  325.  
  326.     static void dumpTree(Element e, PrintStream o, String indent) throws IOException
  327.     {
  328.         if (indent.length() > 0)
  329.         {
  330.             o.print(indent + "---");
  331.         }
  332.         // Once we've printed the '+', from then on we are
  333.         // to print a blank space, since the '+' means we've
  334.         // reached the end of that branch.
  335.         String lines = indent.replace('+',' ');
  336.         boolean dumpText = false;
  337.         boolean dumpTagName = true;
  338.         boolean dumpAttributes = false;
  339.  
  340.         switch (e.getType()) {
  341.         case Element.CDATA:
  342.             o.print("CDATA");
  343.             dumpText = true;
  344.             break;
  345.         case Element.COMMENT:
  346.             o.print("COMMENT");
  347.             break;
  348.         case Element.DOCUMENT:
  349.             o.print("DOCUMENT");
  350.             break;
  351.         case Element.DTD:
  352.             o.print("DOCTYPE");
  353.             dumpAttributes = true;
  354.             dumpTagName = false;            
  355.             break;
  356.         case Element.ELEMENT:
  357.             o.print("ELEMENT");
  358.             break;
  359.         case Element.ENTITY:
  360.             o.print(e.getTagName().getName());
  361.             dumpTagName = false;
  362.             if (e.numElements() == 0) dumpText = true;
  363.             break;
  364.         case Element.ENTITYREF:
  365.             o.print("ENTITYREF");
  366.             dumpText = true;
  367.             break;
  368.         case Element.NOTATION:
  369.             o.print("NOTATION");
  370.             dumpText = true;
  371.             break;
  372.         case Element.ELEMENTDECL:
  373.             o.print("ELEMENTDECL");
  374.             break;
  375.         case Element.PCDATA:
  376.             o.print("PCDATA");
  377.             dumpText = true;
  378.             break;
  379.         case Element.PI:
  380.             if (e.getTagName().getName().toString().equals("XML"))
  381.             {
  382.                 o.print("XMLDECL");
  383.                 dumpAttributes = true;
  384.                 dumpTagName = false;
  385.             } else {
  386.                 o.print("PI");
  387.                 dumpText = true;
  388.             }
  389.             break;
  390.         case Element.NAMESPACE:
  391.             o.print("NAMESPACE");
  392.             dumpAttributes = true;
  393.             dumpTagName = false;
  394.             break;
  395.         case Element.WHITESPACE:
  396.             {
  397.                 o.print("WHITESPACE");
  398.                 String text = e.getText();
  399.                 int len = text.length();
  400.                 for (int i = 0; i < len; i++) 
  401.                 {
  402.                     int c = text.charAt(i);
  403.                     o.print(" 0x" + Integer.toHexString(c));
  404.                 }
  405.                 dumpAttributes = false;
  406.                 dumpTagName = false;
  407.             }
  408.             break;
  409.         }
  410.             
  411.         if (dumpTagName) {
  412.             Name n = e.getTagName();
  413.             if (n != null) 
  414.             {
  415.                 o.print(" " + n.toString());
  416.             }
  417.         }
  418.         if (e.getType() == Element.ENTITY) 
  419.         {
  420.             Entity en = (Entity)e;
  421.             o.print(" " + en.getName());
  422.         } 
  423.         else if (e.getType() == Element.ELEMENTDECL)
  424.         {
  425.             ElementDecl ed = (ElementDecl)e;
  426.             o.print(" ");
  427.             XMLOutputStream out = new XMLOutputStream(o);
  428.             ed.getContent().save(null, out);
  429.             out.flush();
  430.         }
  431.         if (dumpAttributes)
  432.         {
  433.             o.print(" ");
  434.             XMLOutputStream s = new XMLOutputStream(o);
  435.             ((ElementImpl)e).saveAttributes(e.getTagName().getNameSpace(), s);
  436.             s.flush();
  437.         }
  438.  
  439.         if (dumpText && e.getText() != null) 
  440.         {
  441.             o.print(" \"" + e.getText() + "\"");
  442.         }
  443.         o.println("");
  444.  
  445.         String newLines = "";
  446.         if (lines.length() > 0) 
  447.         {
  448.             newLines = lines + "   |";
  449.         } 
  450.         else 
  451.         {
  452.             newLines = "|";
  453.         }
  454.         for (ElementEnumeration en = new ElementEnumeration(e); en.hasMoreElements(); ) 
  455.         {
  456.             Element child = (Element)en.nextElement();
  457.             if (! en.hasMoreElements()) 
  458.             {
  459.                 if (lines.length() > 0) 
  460.                 {
  461.                     newLines = lines + "   +";
  462.                 } 
  463.                 else 
  464.                 {
  465.                     newLines = "+";
  466.                 }
  467.             }
  468.             dumpTree(child,o,newLines);
  469.         }
  470.     }
  471.  
  472.     static void dumpSchema(Document d, XMLOutputStream s) throws IOException
  473.     {
  474.         Element schema = d.getDTD().getSchema();
  475.         s.setOutputStyle(XMLOutputStream.PRETTY);
  476.         schema.save(s);
  477.     }
  478.  
  479.     static void omTest()
  480.     {
  481.         try {
  482.             Document d = new Document();
  483.             d.setStandalone("yes");
  484.             d.createElement(d,Element.WHITESPACE,null,"\r\n");
  485.             Element root = d.createElement(d,Element.ELEMENT,Name.create("ROOT"),null);
  486.             d.createElement(root,Element.WHITESPACE,null,"\r\n");
  487.             Element child = d.createElement(root,Element.ELEMENT,Name.create("CHILD"),null);
  488.             d.createElement(child,Element.PCDATA,null,"This is a test");
  489.             d.createElement(child,Element.WHITESPACE,null,"\r\n");
  490.             d.createElement(child,Element.COMMENT,null,"comment goes here");
  491.             d.createElement(child,Element.WHITESPACE,null,"\r\n");
  492.             d.createElement(child,Element.PI,Name.create("PI"),"processing instruction");
  493.             d.createElement(child,Element.WHITESPACE,null,"\r\n");
  494.  
  495.             FileOutputStream out = new FileOutputStream("test.xml");
  496.             d.save(d.createOutputStream(out));
  497.         } catch (Exception e)
  498.         {
  499.             System.out.println("Exception writing text.xml: " + e.toString());
  500.         }
  501.     }
  502.  
  503.     static String fileName;    
  504.     static boolean output = false;
  505.     static boolean tree = false;
  506.     static boolean schema = false;
  507.     static int loops = 1;
  508.     static boolean timeit = false;
  509.     static boolean caseInsensitive = false;
  510.     static boolean stream = false;
  511.     static long start = 0;
  512.     static long min =0;
  513.     static long max = 0;
  514.     static long count = 0;
  515.     static long sum = 0;
  516.     static int style = 0;
  517.     static OutputStream out = System.out;
  518.     static String outputEncoding = null;
  519.     static boolean fast = false;
  520.     static boolean omtest = false;
  521.     static boolean loadexternal = true;
  522. }    
  523.