Example usage for org.xml.sax XMLReader setProperty

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

Introduction

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

Prototype

public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Set the value of a property.

Usage

From source file:net.sf.joost.stx.Processor.java

/**
 * Assigns a parent to this filter instance. Attempts to register itself
 * as a lexical handler on this parent.//from   w  ww.  java2  s .  c  o m
 */
public void setParent(XMLReader parent) {
    super.setParent(parent);
    parent.setContentHandler(this); // necessary??

    try {
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this);
    } catch (SAXException ex) {
        if (log != null)
            log.warn("Accessing " + parent + ": " + ex);
        else
            System.err.println("Warning - Accessing " + parent + ": " + ex);
    }
}

From source file:Writer.java

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

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

    // variables
    Writer writer = null;
    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 generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;
    boolean canonical = DEFAULT_CANONICAL;

    // 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 + ")");
                        e.printStackTrace(System.err);
                    }
                }
                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("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                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.equalsIgnoreCase("c")) {
                canonical = option.equals("c");
                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 + ")");
                e.printStackTrace(System.err);
                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(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_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 + ")");
        }

        // setup writer
        if (writer == null) {
            writer = new Writer();
            try {
                writer.setOutput(System.out, "UTF8");
            } catch (UnsupportedEncodingException e) {
                System.err.println("error: Unable to set output. Exiting.");
                System.exit(1);
            }
        }

        // set parser
        parser.setContentHandler(writer);
        parser.setErrorHandler(writer);
        try {
            parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer);
        } catch (SAXException e) {
            // ignore
        }

        // parse file
        writer.setCanonical(canonical);
        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:net.sf.joost.stx.Processor.java

/**
 * Create an <code>XMLReader</code> object (a SAX Parser)
 * @throws SAXException if a SAX Parser couldn't be created
 *///from www .ja  va  2  s .c  o m
public static XMLReader createXMLReader() throws SAXException {
    // Using pure SAX2, not JAXP
    XMLReader reader = null;
    try {
        // try default parser implementation
        reader = XMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        String prop = System.getProperty("org.xml.sax.driver");
        if (prop != null) {
            // property set, but still failed
            throw new SAXException("Can't create XMLReader for class " + prop);
            // leave the method here
        }
        // try another SAX implementation
        String PARSER_IMPLS[] = { "org.apache.xerces.parsers.SAXParser", // Xerces
                "org.apache.crimson.parser.XMLReaderImpl", // Crimson
                "gnu.xml.aelfred2.SAXDriver" // Aelfred nonvalidating
        };
        for (int i = 0; i < PARSER_IMPLS.length; i++) {
            try {
                reader = XMLReaderFactory.createXMLReader(PARSER_IMPLS[i]);
                break; // for (...)
            } catch (SAXException e1) {
            } // continuing
        }
        if (reader == null) {
            throw new SAXException("Can't find SAX parser implementation.\n"
                    + "Please specify a parser class via the system property " + "'org.xml.sax.driver'");
        }
    }

    // set features and properties that have been put
    // into the system properties (e.g. via command line)
    Properties sysProps = System.getProperties();
    for (Enumeration e = sysProps.propertyNames(); e.hasMoreElements();) {
        String propKey = (String) e.nextElement();
        if (propKey.startsWith(EXTERN_SAX_FEATURE_PREFIX)) {
            reader.setFeature(propKey.substring(EXTERN_SAX_FEATURE_PREFIX.length()),
                    Boolean.parseBoolean(sysProps.getProperty(propKey)));
            continue;
        }
        if (propKey.startsWith(EXTERN_SAX_PROPERTY_PREFIX)) {
            reader.setProperty(propKey.substring(EXTERN_SAX_PROPERTY_PREFIX.length()),
                    sysProps.getProperty(propKey));
            continue;
        }
    }

    if (DEBUG)
        log.debug("Using " + reader.getClass().getName());
    return reader;
}

From source file:org.apache.camel.dataformat.tagsoup.TidyMarkupDataFormat.java

/**
 * Create the tagSoup Parser/*from w ww.j  av a 2  s . c o  m*/
 * 
 * @return
 * @throws CamelException
 */
protected XMLReader createTagSoupParser() throws CamelException {
    XMLReader reader = new Parser();
    try {
        reader.setFeature(Parser.namespacesFeature, false);
        reader.setFeature(Parser.namespacePrefixesFeature, false);

        /*
         * set each parser feature that the user may have supplied.
         * http://www.saxproject.org/apidoc/org/xml/sax/package-summary.html
         * http://home.ccil.org/~cowan/XML/tagsoup/#properties
         */

        if (getParserFeatures() != null) {
            for (Entry<String, Boolean> e : getParserFeatures().entrySet()) {
                reader.setFeature(e.getKey(), e.getValue());
            }
        }

        /*
         * set each parser feature that the user may have supplied. {@link
         * http://home.ccil.org/~cowan/XML/tagsoup/#properties}
         */

        if (getParserPropeties() != null) {
            for (Entry<String, Object> e : getParserPropeties().entrySet()) {
                reader.setProperty(e.getKey(), e.getValue());
            }
        }

        /*
         * default the schema to HTML
         */
        if (this.getParsingSchema() != null) {
            reader.setProperty(Parser.schemaProperty, getParsingSchema());
        }

    } catch (Exception e) {
        throw new IllegalArgumentException("Problem configuring the parser", e);
    }
    return reader;
}

From source file:org.apache.vxquery.xtest.util.DiskPerformance.java

public Pair<XMLReader, SAXContentHandler> getNewParser() {
    XMLReader parser;
    SAXContentHandler handler;/*w  w  w .j a v a2 s .c  o m*/

    try {
        parser = XMLReaderFactory.createXMLReader();
        List<SequenceType> childSeq = new ArrayList<SequenceType>();
        NameTest nt = new NameTest(createUTF8String(""), createUTF8String("data"));
        childSeq.add(SequenceType.create(new ElementType(nt, AnyType.INSTANCE, false), Quantifier.QUANT_ONE));
        handler = new SAXContentHandler(false, new TreeNodeIdProvider((short) 0), null, null, childSeq);
        parser.setContentHandler(handler);
        parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
        return new Pair<XMLReader, SAXContentHandler>(parser, handler);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.deegree.tools.metadata.ISO19139Validator.java

/**
 * @param srcOpt//from  w w  w.j  a v  a  2 s .  com
 * @param schemaOpt
 * @param resultOpt
 * @throws IOException
 * @throws SAXException
 */
public void run(String srcOpt, String schemaOpt, String resultOpt) throws IOException, SAXException {
    File src = new File(srcOpt);
    if (!src.exists()) {
        throw new IllegalArgumentException("src does not exist: " + srcOpt + ". Check parameter " + OPT_SRC);
    }
    File result;
    if (resultOpt != null && resultOpt.length() > 0) {
        result = new File(resultOpt);
        if (!result.exists()) {
            result.createNewFile();
        }
    } else {
        result = File.createTempFile(DEFAULT_FILENAME, ".txt");
    }

    SCHEMAVERSION schemaVersion = SCHEMAVERSION.V2007;
    if (schemaOpt != null) {
        try {
            schemaVersion = SCHEMAVERSION.valueOf(schemaOpt);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid argument for " + OPT_SCHEMA_VERSION + ": " + schemaOpt);
        }
    }

    String schema = "/META-INF/SCHEMAS_OPENGIS_NET/iso/19139/20070417/gmd/metadataEntity.xsd";
    if (SCHEMAVERSION.V2006.equals(schemaVersion)) {
        schema = "/META-INF/SCHEMAS_OPENGIS_NET/iso/19139/20060504/gmd/metadataEntity.xsd";
    }
    URL u = ISO19139Validator.class.getResource(schema);
    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setFeature("http://xml.org/sax/features/validation", true);
    parser.setFeature("http://apache.org/xml/features/validation/schema", true);
    parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            "http://www.isotc211.org/2005/gmd " + u.toExternalForm());

    final FileWriter fw = new FileWriter(result);

    File[] filesToValidate;
    if (src.isDirectory()) {
        filesToValidate = src.listFiles();
        fw.write("validate " + filesToValidate.length + " files from directory " + src);
        fw.write("\n");
    } else {
        filesToValidate = new File[] { src };
    }
    System.out.println("Start validation");
    int noOfValidRecords = 0;
    for (int i = 0; i < filesToValidate.length; i++) {
        FileErrorHandler feh = new FileErrorHandler(fw);
        parser.setErrorHandler(feh);
        if (filesToValidate.length > 1) {
            fw.write("validate record " + i + " of " + filesToValidate.length);
            fw.write("\n");
        }
        File fileToValidate = filesToValidate[i];
        System.out.println(fileToValidate);
        fw.write("validate file " + fileToValidate.getAbsolutePath());
        fw.write("\n");
        try {
            parser.parse(new InputSource(new FileInputStream(fileToValidate)));
        } catch (Exception e) {
            String msg = "Could not validate current occured: " + e.getMessage()
                    + ". Continue with next record";
            System.err.println(msg);
            fw.write(msg);
            fw.write("\n");
            continue;
        }
        fw.flush();
        if (feh.isValid())
            noOfValidRecords++;
    }
    fw.write(noOfValidRecords + " of " + filesToValidate.length + " records are valid.");
    fw.close();
    System.out.println("Validation finished, result file: " + result.getAbsolutePath());
}

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

protected void configureReader(XMLReader reader, DefaultHandler2 handler, ExecutionContext execContext,
        Source source) throws SAXException {
    if (reader instanceof SmooksXMLReader) {
        ((SmooksXMLReader) reader).setExecutionContext(execContext);
    }/*from  www  .j a v  a2  s .  c  o m*/

    if (reader instanceof JavaXMLReader) {
        if (!(source instanceof JavaSource)) {
            throw new SAXException("A " + JavaSource.class.getName() + " source must be supplied for "
                    + JavaXMLReader.class.getName() + " implementations.");
        }
        ((JavaXMLReader) reader).setSourceObjects(((JavaSource) source).getSourceObjects());
    }

    reader.setContentHandler(handler);

    try {
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
    } catch (SAXNotRecognizedException e) {
        logger.debug(
                "XMLReader property 'http://xml.org/sax/properties/lexical-handler' not recognized by XMLReader '"
                        + reader.getClass().getName() + "'.");
    }
}

From source file:org.dita.dost.module.reader.AbstractReaderModule.java

/**
 * Read a file and process it for list information.
 *
 * @param ref system path of the file to process
 * @param parseFile file to parse, may be {@code null}
 * @throws DITAOTException if processing failed
 *///from   www  .  ja v  a  2 s.  c  o m
void readFile(final Reference ref, final URI parseFile) throws DITAOTException {
    currentFile = ref.filename;
    assert currentFile.isAbsolute();
    final URI src = parseFile != null ? parseFile : currentFile;
    assert src.isAbsolute();
    final URI rel = tempFileNameScheme.generateTempFileName(currentFile);
    outputFile = new File(job.tempDirURI.resolve(rel));
    final File outputDir = outputFile.getParentFile();
    if (!outputDir.exists() && !outputDir.mkdirs()) {
        logger.error("Failed to create output directory " + outputDir.getAbsolutePath());
        return;
    }
    validateMap = Collections.emptyMap();
    defaultValueMap = Collections.emptyMap();
    logger.info("Processing " + currentFile + " to " + outputFile.toURI());
    final String[] params = { currentFile.toString() };

    // Verify stub for current file is in Job
    final FileInfo fi = job.getFileInfo(currentFile);
    if (fi == null) {
        final FileInfo stub = new FileInfo.Builder().src(currentFile).uri(rel).result(currentFile)
                .isInput(currentFile.equals(rootFile)).build();
        job.add(stub);
    }

    //        InputSource in = null;
    Result out = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final SAXTransformerFactory stf = (SAXTransformerFactory) tf;
        final TransformerHandler serializer = stf.newTransformerHandler();

        XMLReader parser = getXmlReader(ref.format);
        XMLReader xmlSource = parser;
        for (final XMLFilter f : getProcessingPipe(currentFile)) {
            f.setParent(xmlSource);
            f.setEntityResolver(CatalogUtils.getCatalogResolver());
            xmlSource = f;
        }

        try {
            final LexicalHandler lexicalHandler = new DTDForwardHandler(xmlSource);
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", lexicalHandler);
            parser.setFeature("http://xml.org/sax/features/lexical-handler", true);
        } catch (final SAXNotRecognizedException e) {
        }

        //            in = new InputSource(src.toString());
        out = new StreamResult(new FileOutputStream(outputFile));
        serializer.setResult(out);
        xmlSource.setContentHandler(serializer);
        xmlSource.parse(src.toString());

        if (listFilter.isValidInput()) {
            processParseResult(currentFile);
            categorizeCurrentFile(ref);
        } else if (!currentFile.equals(rootFile)) {
            logger.warn(MessageUtils.getMessage("DOTJ021W", params).toString());
            failureList.add(currentFile);
        }
    } catch (final RuntimeException e) {
        throw e;
    } catch (final SAXParseException sax) {
        final Exception inner = sax.getException();
        if (inner != null && inner instanceof DITAOTException) {
            throw (DITAOTException) inner;
        }
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + sax.getMessage(), sax);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + sax.getMessage(), sax);
        }
        failureList.add(currentFile);
    } catch (final FileNotFoundException e) {
        if (!exists(currentFile)) {
            if (currentFile.equals(rootFile)) {
                throw new DITAOTException(MessageUtils.getMessage("DOTA069F", params).toString(), e);
            } else if (processingMode == Mode.STRICT) {
                throw new DITAOTException(MessageUtils.getMessage("DOTX008E", params).toString(), e);
            } else {
                logger.error(MessageUtils.getMessage("DOTX008E", params).toString());
            }
        } else if (currentFile.equals(rootFile)) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ078F", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(MessageUtils.getMessage("DOTJ079E", params).toString()
                    + " Cannot load file: " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ079E", params).toString() + " Cannot load file: "
                    + e.getMessage());
        }
        failureList.add(currentFile);
    } catch (final Exception e) {
        if (currentFile.equals(rootFile)) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ012F", params).toString() + ": " + e.getMessage(), e);
        } else if (processingMode == Mode.STRICT) {
            throw new DITAOTException(
                    MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        } else {
            logger.error(MessageUtils.getMessage("DOTJ013E", params).toString() + ": " + e.getMessage(), e);
        }
        failureList.add(currentFile);
    } finally {
        if (out != null) {
            try {
                close(out);
            } catch (final IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        if (failureList.contains(currentFile)) {
            FileUtils.deleteQuietly(outputFile);
        }
    }

    if (!listFilter.isValidInput() && currentFile.equals(rootFile)) {
        if (validate) {
            // stop the build if all content in the input file was filtered out.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ022F", params).toString());
        } else {
            // stop the build if the content of the file is not valid.
            throw new DITAOTException(MessageUtils.getMessage("DOTJ034F", params).toString());
        }
    }

    doneList.add(currentFile);
    listFilter.reset();
    keydefFilter.reset();

}

From source file:org.eclipse.rdf4j.rio.rdfxml.RDFXMLParser.java

private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException {
    clear();//from   www.ja  va  2  s .  co  m

    try {
        documentURI = inputSource.getSystemId();

        saxFilter.setParseStandAloneDocuments(
                getParserConfig().get(XMLParserSettings.PARSE_STANDALONE_DOCUMENTS));

        // saxFilter.clear();
        saxFilter.setDocumentURI(documentURI);

        XMLReader xmlReader;

        if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) {
            xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER);
        } else {
            xmlReader = XMLReaderFactory.createXMLReader();
        }

        xmlReader.setContentHandler(saxFilter);
        xmlReader.setErrorHandler(this);

        // Set all compulsory feature settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<Boolean> aSetting : getCompulsoryXmlFeatureSettings()) {
            try {
                xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Set all compulsory property settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<?> aSetting : getCompulsoryXmlPropertySettings()) {
            try {
                xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        // Check for any optional feature settings that are explicitly set in
        // the parser config
        for (RioSetting<Boolean> aSetting : getOptionalXmlFeatureSettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Check for any optional property settings that are explicitly set in
        // the parser config
        for (RioSetting<?> aSetting : getOptionalXmlPropertySettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        xmlReader.parse(inputSource);
    } catch (SAXParseException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e, e.getLineNumber(), e.getColumnNumber());
        } else {
            reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber());
        }
    } catch (SAXException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e);
        } else if (wrappedExc instanceof RDFParseException) {
            throw (RDFParseException) wrappedExc;
        } else if (wrappedExc instanceof RDFHandlerException) {
            throw (RDFHandlerException) wrappedExc;
        } else {
            reportFatalError(wrappedExc);
        }
    } finally {
        // Clean up
        saxFilter.clear();
        xmlLang = null;
        elementStack.clear();
        usedIDs.clear();
        clear();
    }
}

From source file:org.exist.mongodb.xquery.gridfs.Get.java

/**
 * Parse an byte-array containing (compressed) XML data into an eXist-db
 * document./*from  w  w  w  . j  a v  a2 s  .  c om*/
 *
 * @param data Byte array containing the XML data.
 * @return Sequence containing the XML as DocumentImpl
 *
 * @throws XPathException Something bad happened.
 */
private Sequence processXML(XQueryContext xqueryContext, InputStream is) throws XPathException {

    Sequence content = null;
    try {
        final ValidationReport validationReport = new ValidationReport();
        final SAXAdapter adapter = new SAXAdapter(xqueryContext);
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        final InputSource src = new InputSource(is);
        final SAXParser parser = factory.newSAXParser();
        XMLReader xr = parser.getXMLReader();

        xr.setErrorHandler(validationReport);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);

        xr.parse(src);

        // Cleanup
        IOUtils.closeQuietly(is);

        if (validationReport.isValid()) {
            content = (DocumentImpl) adapter.getDocument();
        } else {
            String txt = String.format("Received document is not valid: %s", validationReport.toString());
            LOG.debug(txt);
            throw new XPathException(txt);
        }

    } catch (SAXException | ParserConfigurationException | IOException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(ex.getMessage());

    }

    return content;
}