Example usage for org.xml.sax XMLReader setDTDHandler

List of usage examples for org.xml.sax XMLReader setDTDHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setDTDHandler.

Prototype

public void setDTDHandler(DTDHandler handler);

Source Link

Document

Allow an application to register a DTD event handler.

Usage

From source file:TypeInfoWriter.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*from w  w  w.j  av  a 2s .  c o m*/
        System.exit(1);
    }

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // process arguments
    for (int i = 0; i < argv.length; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    // use default parser?
    if (parser == null) {
        // create parser
        try {
            parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
        } catch (Exception e) {
            System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:XMLUtilities.java

/**
 * Convenience method for parsing an XML file. This method will
 * wrap the resource in an InputSource and set the source's
 * systemId to "jedit.jar" (so the source should be able to
 * handle any external entities by itself).
 *
 * <p>SAX Errors are caught and are not propagated to the caller;
 * instead, an error message is printed to jEdit's activity
 * log. So, if you need custom error handling, <b>do not use
 * this method</b>./*from w w  w .j  ava2s  .  c  o  m*/
 *
 * <p>The given stream is closed before the method returns,
 * regardless whether there were errors or not.</p>
 *
 * @return true if any error occured during parsing, false if success.
 */
public static boolean parseXML(InputStream in, DefaultHandler handler) throws IOException {
    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InputSource isrc = new InputSource(new BufferedInputStream(in));
        isrc.setSystemId("jedit.jar");
        parser.setContentHandler(handler);
        parser.setDTDHandler(handler);
        parser.setEntityResolver(handler);
        parser.setErrorHandler(handler);
        parser.parse(isrc);
    } catch (SAXParseException se) {
        int line = se.getLineNumber();
        return true;
    } catch (SAXException e) {
        return true;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException io) {
        }
    }
    return false;
}

From source file:architecture.common.model.factory.ModelTypeFactory.java

private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*  w w w.j  a v a  2 s .  co m*/
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler();
    xmlreader.setContentHandler(handler);
    xmlreader.setDTDHandler(handler);
    xmlreader.setEntityResolver(handler);
    xmlreader.setErrorHandler(handler);
    System.out.println("Model Enum:");
    do {
        if (!enumeration.hasMoreElements())
            break;
        URL url = (URL) enumeration.nextElement();
        System.out.println(" - " + url);
        try {
            xmlreader.parse(new InputSource(url.openStream()));
            ModelList factorylist = new ModelList();
            factorylist.rank = handler.rank;
            factorylist.modelTypes.addAll(handler.getModels());
            list.add(factorylist);
        } catch (Exception exception) {
        }
    } while (true);

    return list;
}

From source file:DocumentTracer.java

/** Main. */
public static void main(String[] argv) throws Exception {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   w  w w.ja  v a 2 s  . com
        System.exit(1);
    }

    // variables
    DocumentTracer tracer = new DocumentTracer();
    PrintWriter out = new PrintWriter(System.out);
    XMLReader parser = null;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                    }
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("np")) {
                namespacePrefixes = option.equals("np");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("xd")) {
                externalDTD = option.equals("xd");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // set handlers
        parser.setDTDHandler(tracer);
        parser.setErrorHandler(tracer);
        if (parser instanceof XMLReader) {
            parser.setContentHandler(tracer);
            try {
                parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
            try {
                parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer);
            } catch (SAXException e) {
                e.printStackTrace(System.err);
            }
        } else {
            ((Parser) parser).setDocumentHandler(tracer);
        }

        // parse file
        try {
            parser.parse(arg);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            if (e instanceof SAXException) {
                Exception nested = ((SAXException) e).getException();
                if (nested != null) {
                    e = nested;
                }
            }
            e.printStackTrace(System.err);
        }
    }

}

From source file:architecture.common.util.L10NUtils.java

private void loadProps(String resource, boolean breakOnError) throws IOException {

    HashSet<URL> hashset = new HashSet<URL>();
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching ").append(resource).toString());
    }/*www .  j  ava 2 s  .  co m*/
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(resource);
    if (urls != null) {
        URL url;
        for (; urls.hasMoreElements(); hashset.add(url)) {
            url = urls.nextElement();
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Adding ").append(url).toString());
        }
    }

    for (URL url : hashset) {
        if (log.isDebugEnabled())
            log.debug((new StringBuilder()).append("Loading from ").append(url).toString());
        InputStream is = null;
        try {
            is = url.openStream();
            InputSource input = new InputSource(is);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XMLReader xmlreader = factory.newSAXParser().getXMLReader();
            I18nParsingHandler handler = new I18nParsingHandler();
            xmlreader.setContentHandler(handler);
            xmlreader.setDTDHandler(handler);
            xmlreader.setEntityResolver(handler);
            xmlreader.setErrorHandler(handler);
            xmlreader.parse(input);
            localizers.addAll(handler.localizers);
        } catch (IOException e) {
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Skipping ").append(url).toString());
            if (breakOnError)
                throw e;
        } catch (Exception e) {
            log.error(e);
        } finally {
            if (is != null)
                IOUtils.closeQuietly(is);
        }
    }

}

From source file:net.sf.joost.trax.TrAXFilter.java

/**
 * Parses the <code>InputSource</code>
 * @param input A <code>InputSource</code> object.
 * @throws SAXException//from  w w w . ja v  a  2 s.c om
 * @throws IOException
 */
public void parse(InputSource input) throws SAXException, IOException {

    Transformer transformer = null;
    if (DEBUG) {
        if (log.isDebugEnabled())
            log.debug("parsing InputSource " + input.getSystemId());
    }

    try {
        // get a new Transformer
        transformer = this.templates.newTransformer();
        if (transformer instanceof TransformerImpl) {
            this.processor = ((TransformerImpl) transformer).getStxProcessor();
        } else {
            String msg = "An error is occured, because the given transformer is "
                    + "not an instance of TransformerImpl";
            if (log != null)
                log.fatal(msg);
            else
                System.err.println("Fatal error - " + msg);

        }
        XMLReader parent = this.getParent();

        if (parent == null) {
            parent = XMLReaderFactory.createXMLReader();
            setParent(parent);
        }
        ContentHandler handler = this.getContentHandler();

        if (handler == null) {
            handler = parent.getContentHandler();
        }
        if (handler == null) {
            throw new SAXException("no ContentHandler registered");
        }
        //init StxEmitter
        StxEmitter out = null;

        //SAX specific Implementation
        out = new SAXEmitter(handler);

        if (this.processor != null) {
            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);
        } else {
            throw new SAXException("Joost-Processor is not correct configured.");
        }
        if (parent == null) {
            throw new SAXException("No parent for filter");
        }
        parent.setContentHandler(this.processor);
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this.processor);
        parent.setEntityResolver(this);
        parent.setDTDHandler(this);
        parent.setErrorHandler(this);
        parent.parse(input);

    } catch (TransformerConfigurationException tE) {
        try {
            configErrListener.fatalError(tE);
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (SAXException sE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(sE.getMessage(), sE));
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (IOException iE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(iE.getMessage(), iE));
        } catch (TransformerConfigurationException innerE) {
            throw new IOException(innerE.getMessage());
        }
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/** Return a SAX parser for reuse.
 * @param parser A SAX parser that is available for reuse
 *//*from   ww  w . j a  v  a  2 s .co  m*/
public static void releaseSAXParser(SAXParser parser) {
    if (!tryReset || !enableParserReuse)
        return;

    //Free up possible ref. held by past contenthandler.
    try {
        XMLReader xmlReader = parser.getXMLReader();
        if (null != xmlReader) {
            xmlReader.setContentHandler(doNothingContentHandler);
            xmlReader.setDTDHandler(doNothingContentHandler);
            try {
                xmlReader.setEntityResolver(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set EntityResolver on DocumentBuilder", t);
            }
            try {
                xmlReader.setErrorHandler(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set ErrorHandler on DocumentBuilder", t);
            }

            synchronized (XMLUtils.class) {
                saxParsers.push(parser);
            }
        } else {
            tryReset = false;
        }
    } catch (org.xml.sax.SAXException e) {
        tryReset = false;
    }
}

From source file:org.apache.camel.component.validator.jing.JingValidator.java

public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();//from   w w w . j  a  va 2s .  c o m
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
        Source source = ExchangeHelper.getMandatoryInBody(exchange, Source.class);
        saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
}

From source file:org.apache.fop.fotreetest.FOTreeTestCase.java

/**
 * Runs a test./*  ww w  . j a va 2  s . co  m*/
 * @throws Exception if a test or FOP itself fails
 */
@Test
public void runTest() throws Exception {
    try {
        ResultCollector collector = ResultCollector.getInstance();
        collector.reset();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Resetting values modified by processing instructions
        fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
                FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
        fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);

        FOUserAgent ua = fopFactory.newFOUserAgent();
        ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
        ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
        ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName()));

        // Used to set values in the user agent through processing instructions
        reader = new PIListener(reader, ua);

        Fop fop = fopFactory.newFop(ua);

        reader.setContentHandler(fop.getDefaultHandler());
        reader.setDTDHandler(fop.getDefaultHandler());
        reader.setErrorHandler(fop.getDefaultHandler());
        reader.setEntityResolver(fop.getDefaultHandler());
        try {
            reader.parse(testFile.toURI().toURL().toExternalForm());
        } catch (Exception e) {
            collector.notifyError(e.getLocalizedMessage());
            throw e;
        }

        List<String> results = collector.getResults();
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                System.out.println((String) results.get(i));
            }
            throw new IllegalStateException((String) results.get(0));
        }
    } catch (Exception e) {
        org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName());
        throw e;
    }
}

From source file:org.dhatim.delivery.AbstractParser.java

private void setHandlers(XMLReader reader) throws SAXException {
    if (saxDriverConfig != null) {
        List<Parameter> handlers;

        handlers = saxDriverConfig.getParameters("sax-handler");
        if (handlers != null) {
            for (Parameter handler : handlers) {
                Object handlerObj = createHandler(handler.getValue());

                if (handlerObj instanceof EntityResolver) {
                    reader.setEntityResolver((EntityResolver) handlerObj);
                }/*  www.  ja v  a2 s .  c  om*/
                if (handlerObj instanceof DTDHandler) {
                    reader.setDTDHandler((DTDHandler) handlerObj);
                }
                if (handlerObj instanceof ErrorHandler) {
                    reader.setErrorHandler((ErrorHandler) handlerObj);
                }
            }
        }
    }
}