Beispiel #1
0
  /** Main method to allow PrettyPrinter to be used from the command-line. */
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println(
          "Usage: java " + PrettyPrinter.class.getName() + " [inputFilename] [outputFilename]");
      System.exit(0);
    }

    String in_filename = args[0];
    String out_filename = args[1];

    // Get instances of our handlers
    DocumentHandler prettyPrinter =
        new PrettyPrinter(new FileOutputStream(out_filename), "iso-8859-1");
    ErrorHandler errorHandler = new OntopiaErrorHandler();

    InputSource inSource = new InputSource(new FileReader(in_filename));

    // get parser instance and connect to our handlers
    Parser parser = ParserFactory.makeParser("com.jclark.xml.sax.Driver");
    parser.setDocumentHandler(prettyPrinter);
    parser.setErrorHandler(errorHandler);

    // beautify
    parser.parse(inSource);
  }
  /**
   * Parse an XML Catalog stream.
   *
   * @param catalog The catalog to which this catalog file belongs
   * @param is The input stream from which the catalog will be read
   * @throws MalformedURLException Improper fileUrl
   * @throws IOException Error reading catalog file
   * @throws CatalogException A Catalog exception
   */
  public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException {

    // Create an instance of the parser
    if (parserFactory == null && parserClass == null) {
      debug.message(1, "Cannot read SAX catalog without a parser");
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    debug = catalog.getCatalogManager().debug;
    EntityResolver bResolver = catalog.getCatalogManager().getBootstrapResolver();

    this.catalog = catalog;

    try {
      if (parserFactory != null) {
        SAXParser parser = parserFactory.newSAXParser();
        SAXParserHandler spHandler = new SAXParserHandler();
        spHandler.setContentHandler(this);
        if (bResolver != null) {
          spHandler.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is), spHandler);
      } else {
        Parser parser =
            (Parser)
                Class.forName(
                        parserClass,
                        true,
                        loader != null ? loader : this.getClass().getClassLoader())
                    .newInstance();
        parser.setDocumentHandler(this);
        if (bResolver != null) {
          parser.setEntityResolver(bResolver);
        }
        parser.parse(new InputSource(is));
      }
    } catch (ClassNotFoundException cnfe) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    } catch (SAXException se) {
      Exception e = se.getException();
      // FIXME: there must be a better way
      UnknownHostException uhe = new UnknownHostException();
      FileNotFoundException fnfe = new FileNotFoundException();
      if (e != null) {
        if (e.getClass() == uhe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        } else if (e.getClass() == fnfe.getClass()) {
          throw new CatalogException(CatalogException.PARSE_FAILED, e.toString());
        }
      }
      throw new CatalogException(se);
    }
  }
Beispiel #3
0
     /**
     * Creates Java Source code (Object model) for the given XML Schema
     * @param InputSource - the InputSource representing the XML schema.
     * @param packageName the package for the generated source files
    **/
    public void generateSource(InputSource source, String packageName) {

        //-- get default parser from Configuration
        Parser parser = null;
        try {
	    parser = Configuration.getParser();
        }
        catch(RuntimeException rte) {}
        if (parser == null) {
            System.out.println("fatal error: unable to create SAX parser.");
            return;
        }

        SchemaUnmarshaller schemaUnmarshaller = null;
        try {
           schemaUnmarshaller = new SchemaUnmarshaller();
        } catch (SAXException e) {
          // can never happen since a SAXException is thrown
          // when we are dealing with an included schema
          e.printStackTrace();
        }

        parser.setDocumentHandler(schemaUnmarshaller);
        parser.setErrorHandler(schemaUnmarshaller);

        try {
            parser.parse(source);
        }
        catch(java.io.IOException ioe) {
            System.out.println("error reading XML Schema file");
            return;
        }
        catch(org.xml.sax.SAXException sx) {

            Exception except = sx.getException();
            if (except == null) except = sx;

            if (except instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException)except;
                System.out.println("SAXParseException: " + spe);
                System.out.print(" - occured at line ");
                System.out.print(spe.getLineNumber());
                System.out.print(", column ");
                System.out.println(spe.getColumnNumber());
            }
            else except.printStackTrace();
            return;
        }

        Schema schema = schemaUnmarshaller.getSchema();
        generateSource(schema, packageName);

    } //-- generateSource
Beispiel #4
0
  /**
   * Parse the content given {@link org.xml.sax.InputSource} as XML using the specified {@link
   * org.xml.sax.HandlerBase}. <i> Use of the DefaultHandler version of this method is recommended
   * as the HandlerBase class has been deprecated in SAX 2.0</i>
   *
   * @param is The InputSource containing the content to be parsed.
   * @param hb The SAX HandlerBase to use.
   * @throws IllegalArgumentException If the <code>InputSource</code> object is <code>null</code>.
   * @throws IOException If any IO errors occur.
   * @throws SAXException If any SAX errors occur during processing.
   * @see org.xml.sax.DocumentHandler
   */
  public void parse(InputSource is, HandlerBase hb) throws SAXException, IOException {
    if (is == null) {
      throw new IllegalArgumentException("InputSource cannot be null");
    }

    Parser parser = this.getParser();
    if (hb != null) {
      parser.setDocumentHandler(hb);
      parser.setEntityResolver(hb);
      parser.setErrorHandler(hb);
      parser.setDTDHandler(hb);
    }
    parser.parse(is);
  }
Beispiel #5
0
 public void parse(InputSource paramInputSource, HandlerBase paramHandlerBase)
     throws SAXException, IOException {
   if (paramInputSource == null) {
     throw new IllegalArgumentException("InputSource cannot be null");
   }
   Parser localParser = getParser();
   if (paramHandlerBase != null) {
     localParser.setDocumentHandler(paramHandlerBase);
     localParser.setEntityResolver(paramHandlerBase);
     localParser.setErrorHandler(paramHandlerBase);
     localParser.setDTDHandler(paramHandlerBase);
   }
   localParser.parse(paramInputSource);
 }
Beispiel #6
0
  /**
   * Creates an XML Schema using the given InputSource. The InputSource must be for an XML instance
   * document. The XML Schema created will be based on the specific XML instance document.
   *
   * @param source the InputSource for the XML document
   */
  public Schema createSchema(InputSource source) throws IOException {
    XMLInstance2SchemaHandler handler = new XMLInstance2SchemaHandler();
    handler.setDefaultGroupOrder(_defaultGroup);

    try {
      Parser parser = _internalContext.getParser();
      if (parser == null) {
        throw new IOException("fatal error: unable to create SAX parser.");
      }
      parser.setDocumentHandler(handler);
      parser.setErrorHandler(handler);
      parser.parse(source);
    } catch (org.xml.sax.SAXException sx) {
      throw new NestedIOException(sx);
    }
    return handler.getSchema();
  }
  public void parse() throws IOException, SAXException, ParserConfigurationException {

    // parser stuff figured out with great ease thanks to java examples in a nutshell By David
    // Flanagan
    // http://www.oreilly.com/catalog/jenut2/chapter/ch19.html

    // Create a JAXP "parser factory" for creating SAX parsers
    SAXParserFactory spf = SAXParserFactory.newInstance();

    // Configure the parser factory for the type of parsers we require
    spf.setValidating(false); // No validation required

    // Now use the parser factory to create a SAXParser object
    // Note that SAXParser is a JAXP class, not a SAX class
    javax.xml.parsers.SAXParser sp = spf.newSAXParser();

    // Create a SAX input source for the file argument
    org.xml.sax.InputSource input = new InputSource(new FileReader(this.xmlFileLocation));

    // Give the InputSource an absolute URL for the file, so that
    // it can resolve relative URLs in a <!DOCTYPE> declaration, e.g.
    input.setSystemId("file://" + new File(this.xmlFileLocation).getAbsolutePath());

    // Finally, tell the parser to parse the input and notify the handler
    // sp.parse(input, this);

    // Instead of using the SAXParser.parse() method, which is part of the
    // JAXP API, we could also use the SAX1 API directly.  Note the
    // difference between the JAXP class javax.xml.parsers.SAXParser and
    // the SAX1 class org.xml.sax.Parser
    //
    org.xml.sax.Parser parser = sp.getParser(); // Get the SAX parser

    if (this.resolveEntities) {
      parser.setEntityResolver(this);
    } else {
      parser.setEntityResolver(new SAXFakeEntityResolver());
    }

    parser.setDocumentHandler(this); // Set main handler
    parser.setErrorHandler(errorHandler); // Set error handler
    parser.parse(input); // Parse!
  }
  public static void main(String[] args) throws IOException {
    String filename = "z.xml"; // NOT LOCALIZABLE, main

    try {
      String uri = "file:" + new File(filename).getAbsolutePath(); // NOT LOCALIZABLE, main

      //
      // turn it into an in-memory object.
      //
      Parser parser = getParser();
      parser.setDocumentHandler(new XmlParser());
      parser.setErrorHandler(new MyErrorHandler());
      parser.parse(uri);

    } catch (SAXParseException err) {
      Debug.trace(
          "** Parsing error" // NOT LOCALIZABLE, main
              + ", line "
              + err.getLineNumber() // NOT LOCALIZABLE
              + ", uri "
              + err.getSystemId()); // NOT LOCALIZABLE
      Debug.trace("   " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e;
      if (e.getException() != null) x = e.getException();
      x.printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    byte[] buf = new byte[256];
    Debug.trace("Press ENTER to exit."); // NOT LOCALIZABLE
    System.in.read(buf, 0, 256);
    System.exit(0);
  }
Beispiel #9
0
 public synchronized void parse(InputSource input) throws SAXException, IOException {
   _parser.parse(input);
 }
Beispiel #10
0
 public synchronized void parse(String input) throws SAXException, IOException {
   _parser.parse(input);
 }