Example usage for javax.xml.validation ValidatorHandler setErrorHandler

List of usage examples for javax.xml.validation ValidatorHandler setErrorHandler

Introduction

In this page you can find the example usage for javax.xml.validation ValidatorHandler setErrorHandler.

Prototype

public abstract void setErrorHandler(ErrorHandler errorHandler);

Source Link

Document

Sets the ErrorHandler to receive errors encountered during the validation.

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 ava  2 s .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:jeeves.utils.Xml.java

/**
 * Called by all validation methods to do the real guts of the validation job.
 * @param schema// w w w  .j  a  v a 2 s.c  om
 * @param xml
 * @param eh
 * @throws Exception
 */
private static void validateRealGuts(Schema schema, Element xml, ErrorHandler eh) throws Exception {

    Resolver resolver = ResolverWrapper.getInstance();

    ValidatorHandler vh = schema.newValidatorHandler();
    vh.setResourceResolver(resolver.getXmlResolver());
    vh.setErrorHandler(eh);

    SAXOutputter so = new SAXOutputter(vh);
    eh.setSo(so);

    so.output(xml);
}

From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl2.java

private void parseAndValidate(InputStream input, Schema schema) throws XmlParseException, IOException {
    ValidatorHandler vHandler = schema.newValidatorHandler();
    vHandler.setContentHandler(this);
    vHandler.setErrorHandler(this);

    InputSource is = new InputSource(new InputStreamReader(input, "UTF-8"));
    is.setEncoding("UTF-8");

    try {/*from w w w.  ja v a 2 s  .  c om*/
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(vHandler);
        parser.setErrorHandler(this);

        vHandler.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);

        parser.setFeature("http://apache.org/xml/features/validation/id-idref-checking", false);
        parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);
        parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
        parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        parser.parse(is);
    } catch (SAXException e) {
        throw new XmlParseException(e.getMessage(), e);
    }
}

From source file:stroom.pipeline.server.filter.SchemaFilter.java

private ValidatorHandler getValidator() throws SAXException {
    ValidatorHandler validatorHandler = null;

    if (schemaValidation && schemaPool != null) {
        // Put back the old schema if we need to.
        returnCurrentSchema();//from  w  w  w .j  a v a  2 s  . co  m

        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<xsd:schema xmlns:xsd=\"");
        sb.append(schemaLanguage);
        sb.append("\"");
        final CharBuffer namespaces = new CharBuffer(100);
        final CharBuffer locations = new CharBuffer(100);
        for (final String prefix : prefixes.keySet()) {
            final String namespace = prefixes.get(prefix);
            final String location = schemaLocations.get(namespace);
            if (location != null) {
                namespaces.append(" xmlns");
                if (prefix.length() > 0) {
                    namespaces.append(":");
                    namespaces.append(prefix);
                }
                namespaces.append("=\"");
                namespaces.append(namespace);
                namespaces.append("\"");

                locations.append("<xsd:import namespace=\"");
                locations.append(namespace);
                locations.append("\" schemaLocation=\"");
                locations.append(location);
                locations.append("\"/>\n");
            }
        }
        sb.append(namespaces.toString());
        sb.append(">\n");
        sb.append(locations.toString());
        sb.append("</xsd:schema>");

        final String data = sb.toString();
        sb.clear();

        // Get another schema.
        final SchemaKey schemaKey = new SchemaKey(schemaLanguage, data);
        poolItem = schemaPool.borrowObject(schemaKey, true);
        final StoredSchema storedSchema = poolItem.getValue();

        // Replay errors generated when creating schema.
        try {
            storedSchema.getErrorReceiver().replay(errorReceiverProxy);
        } catch (final Exception e) {
            errorHandler.fatalError(new SAXParseException(e.getMessage(), null));
        }

        // Create a validator handler.
        validatorHandler = storedSchema.getSchema().newValidatorHandler();
        validatorHandler.setDocumentLocator(locator);
        validatorHandler.setErrorHandler(errorHandler);

        validatorHandler.startDocument();
        for (final String prefix : prefixes.keySet()) {
            validatorHandler.startPrefixMapping(prefix, prefixes.get(prefix));
        }
    }

    return validatorHandler;
}