import java.io.*;
import java.net.*;
import oracle.xml.parser.v2.*;
import oracle.xml.classgen.*;
import org.w3c.dom.Element;

/**
 * Sample Class to uses XML Class Generator
 */
public class SampleMain
{

   public SampleMain()
   {
   }

   public static void main (String args[]) 
   {
       // validate arguments
      if (args.length < 1) 
      {
         System.out.println("Usage: java SampleMain "+
                            "[-root <rootName>] <fileName>");
         System.out.println("fileName\t   Input file, XML document or " +
                            "external DTD file");
         System.out.println("-root <rootName>   Name of the root Element " +
                            "(required if the input file is an external DTD)");
         return ;
      }
      try // to open the XML File/ External DTD File
      { 
         // instantiate the parser
         DOMParser   parser = new DOMParser();
         XMLDocument doc    = null;
         DTD         dtd    = null;

         if (args.length == 3)
         {
            parser.parseDTD(fileToURL(args[2]), args[1]);            
            dtd = (DTD)parser.getDoctype();
         }
         else
         {
            parser.setValidationMode(true);
            parser.parse(fileToURL(args[0]));            
            doc = parser.getDocument();
            dtd = (DTD)doc.getDoctype();
         }

         String doctype_name = null;

         if (args.length == 3)
         {
            doctype_name = args[1];
         }
         else
         {
            /* get the Root Element name from the XMLDocument*/
            doctype_name = doc.getDocumentElement().getTagName();
         }

         // generate the Java files...
         ClassGenerator generator = new ClassGenerator();

         // set generate comments to true
         generator.setGenerateComments(true);
         // set output directory 
         generator.setOutputDirectory(".");
         // set validating mode to true
         generator.setValidationMode(true);

         // generate java src
         generator.generate(dtd, doctype_name);

      }
      catch (Exception e) 
      {
         System.out.println ("XML Class Generator: Error " + e.toString());
         e.printStackTrace();
      }
   }

   static public URL fileToURL(String sfile) 
   {
      File file = new File(sfile);
      String path = file.getAbsolutePath();
      String fSep = System.getProperty("file.separator");
      if (fSep != null && fSep.length() == 1)
         path = path.replace(fSep.charAt(0), '/');
      if (path.length() > 0 && path.charAt(0) != '/')
         path = '/' + path;
      try 
      {
         return new URL("file", null, path);
      }
      catch (java.net.MalformedURLException e) 
      {
         /* According to the spec this could only happen if the file
            protocol were not recognized. */
         throw new Error("unexpected MalformedURLException");
      }
   }
}
