Example usage for org.xml.sax XMLReader setFeature

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

Introduction

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

Prototype

public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Set the value of a feature flag.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    String parserClass = "org.apache.xerces.parsers.SAXParser";
    String validationFeature = "http://xml.org/sax/features/validation";
    String schemaFeature = "http://apache.org/xml/features/validation/schema";
    String x = args[0];//from  w w  w  .j  av  a2s. co  m
    XMLReader r = XMLReaderFactory.createXMLReader(parserClass);
    r.setFeature(validationFeature, true);
    r.setFeature(schemaFeature, true);
    r.setErrorHandler(new MyErrorHandler());
    r.parse(x);
}

From source file:DocumentTracer.java

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

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();// ww w .  j  av a 2s  .  co  m
        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:Writer.java

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

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();/*w ww.j a va 2s .  com*/
        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:Counter.java

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

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

    // variables
    Counter counter = new Counter();
    PrintWriter out = new PrintWriter(System.out);
    XMLReader parser = null;
    int repetition = DEFAULT_REPETITION;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
    boolean validation = DEFAULT_VALIDATION;
    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;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;
    boolean tagginess = DEFAULT_TAGGINESS;

    // 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.");
                    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 + ")");
                    }
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                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("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.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equalsIgnoreCase("t")) {
                tagginess = option.equals("t");
                continue;
            }
            if (option.equals("-rem")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -# option.");
                    continue;
                }
                System.out.print("# ");
                System.out.println(argv[i]);
                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 + ")");
                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(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 + ")");
        }

        // parse file
        parser.setContentHandler(counter);
        parser.setErrorHandler(counter);
        try {
            long timeBefore = System.currentTimeMillis();
            long memoryBefore = Runtime.getRuntime().freeMemory();
            for (int j = 0; j < repetition; j++) {
                parser.parse(arg);
            }
            long memoryAfter = Runtime.getRuntime().freeMemory();
            long timeAfter = System.currentTimeMillis();

            long time = timeAfter - timeBefore;
            long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE;
            counter.printResults(out, arg, time, memory, tagginess, repetition);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);

        }
    }

}

From source file:Main.java

/**
 * Get an instance of an XML reader from the XMLReaderFactory.
 *
 * @return the XMLReader.//  w  w w . j  a va2s.  co m
 */
public static XMLReader getXmlReader() {
    try {
        final XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        return reader;
    } catch (final Exception e) {
        throw new RuntimeException("Unable to create XMLReader", e);
    }
}

From source file:Util.java

/**
 * Creates an XMLReader with default feature set. Note that all Cayenne internal XML
 * parsers should probably use XMLReader obtained via this method for consistency
 * sake, and can customize feature sets as needed.
 *//*from   w w  w  .  java  2s. c  o  m*/
public static XMLReader createXmlReader() throws SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();

    // Create a JAXP SAXParser
    SAXParser saxParser = spf.newSAXParser();

    // Get the encapsulated SAX XMLReader
    XMLReader reader = saxParser.getXMLReader();

    // set default features
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    return reader;
}

From source file:io.milton.http.LockInfoSaxHandler.java

public static LockInfo parseLockInfo(Request request) throws IOException, FileNotFoundException, SAXException {
    InputStream in = request.getInputStream();

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

    LockInfoSaxHandler handler = new LockInfoSaxHandler();
    reader.setContentHandler(handler);//  ww w .  j  a v a 2  s .c o m
    if (log.isDebugEnabled()) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        IOUtils.copy(in, bout);
        byte[] bytes = bout.toByteArray();
        in = new ByteArrayInputStream(bytes);
        log.debug("LockInfo: " + bout.toString());
    }
    reader.parse(new InputSource(in));
    LockInfo info = handler.getInfo();
    info.depth = LockDepth.INFINITY; // todo
    if (info.lockedByUser == null) {
        if (request.getAuthorization() != null) {
            if (request.getAuthorization().getUser() != null) {
                info.lockedByUser = request.getAuthorization().getUser();
            } else {
                Object user = request.getAuthorization().getTag();
                if (user instanceof DiscretePrincipal) {
                    DiscretePrincipal dp = (DiscretePrincipal) user;
                    info.lockedByUser = dp.getPrincipalURL();
                }
            }

        }
    }
    if (info.lockedByUser == null) {
        log.warn("resource is being locked with a null user. This won't really be locked at all...");
    }
    return info;
}

From source file:com.mirth.connect.plugins.datatypes.ncpdp.test.NCPDPTest.java

private static long runTest(String testMessage) throws MessageSerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    //      Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    //        properties.put("useStrictParser", "true");
    //        properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource",SchemaUrl);
    stopwatch.start();/*from   w  w w . j  ava  2 s  .c  o m*/
    NCPDPSerializer serializer = new NCPDPSerializer(null);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.serialize(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

private static long runTest(String testMessage) throws SerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    properties.put("useStrictParser", "true");
    properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl);
    stopwatch.start();/*from www. j  a  v a2s.c  o m*/
    NCPDPSerializer serializer = new NCPDPSerializer(properties);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.toXML(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:com.googlecode.jgenhtml.JGenHtmlTestUtils.java

/**
 * Get an HTML page as a DOM object//from   w  w  w.ja  va  2 s  .c o  m
 * @param location The path to the HTML file.
 */
public static Node parse(String location) {
    try {
        XMLReader reader = new Parser();
        reader.setFeature(Parser.namespacesFeature, false);
        reader.setFeature(Parser.namespacePrefixesFeature, false);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(new SAXSource(reader, new InputSource(new FileReader(new File(location)))),
                result);
        return result.getNode();
    } catch (TransformerConfigurationException ex) {
        TestCase.fail(ex.getLocalizedMessage());
    } catch (SAXNotRecognizedException ex) {
        TestCase.fail(ex.getLocalizedMessage());
    } catch (SAXNotSupportedException ex) {
        TestCase.fail(ex.getLocalizedMessage());
    } catch (TransformerException ex) {
        TestCase.fail(ex.getLocalizedMessage());
    } catch (IOException ex) {
        TestCase.fail(ex.getLocalizedMessage());
    }
    return null;
}