Example usage for javax.xml.validation Validator setResourceResolver

List of usage examples for javax.xml.validation Validator setResourceResolver

Introduction

In this page you can find the example usage for javax.xml.validation Validator setResourceResolver.

Prototype

public abstract void setResourceResolver(LSResourceResolver resourceResolver);

Source Link

Document

Sets the LSResourceResolver to customize resource resolution while in a validation episode.

Usage

From source file:com.predic8.membrane.core.interceptor.schemavalidation.XMLSchemaValidator.java

@Override
protected List<Validator> createValidators() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(resourceResolver.toLSResourceResolver());
    List<Validator> validators = new ArrayList<Validator>();
    log.debug("Creating validator for schema: " + location);
    StreamSource ss = new StreamSource(resourceResolver.resolve(location));
    ss.setSystemId(location);/*  w  ww .  ja v a 2s .  c  o m*/
    Validator validator = sf.newSchema(ss).newValidator();
    validator.setResourceResolver(resourceResolver.toLSResourceResolver());
    validator.setErrorHandler(new SchemaValidatorErrorHandler());
    validators.add(validator);
    return validators;
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.AbstractXMLSchemaValidator.java

protected List<Validator> createValidators() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getSchemas()) {
        log.debug("Creating validator for schema: " + schema);
        StreamSource ss = new StreamSource(new StringReader(schema.getAsString()));
        ss.setSystemId(location);/*from w w w .  j  a va2s. c  o  m*/
        sf.setResourceResolver(resourceResolver.toLSResourceResolver());
        Validator validator = sf.newSchema(ss).newValidator();
        validator.setResourceResolver(resourceResolver.toLSResourceResolver());
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

From source file:at.tfr.securefs.module.validation.SchemaValidationModule.java

@Override
public ModuleResult apply(InputStream input, ModuleConfiguration moduleConfiguration)
        throws ModuleException, IOException {
    SchemaResolver errorHandler = null;//from ww  w .  ja v  a  2s. com
    moduleStatistics.getCalls().incrementAndGet();

    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setCoalescing(true);
        dbf.setCoalescing(true);

        if (schema == null) {
            loadSchema(moduleConfiguration);
        }

        DOMImplementationLS domImpl = (DOMImplementationLS) dbf.newDocumentBuilder().getDOMImplementation();
        errorHandler = new SchemaResolver(configuration.getSchemaPath(), domImpl);

        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.setResourceResolver(errorHandler);

        validator.validate(new StreamSource(input));

    } catch (SAXParseException e) {
        moduleStatistics.getFailures().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.debug(message, e);
        log.info(message);
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    } catch (Exception e) {
        moduleStatistics.getErrors().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.info(message, e);
        log.warn(message);
        if (moduleConfiguration.isMandatory()) {
            throw new IOException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    }

    if (errorHandler != null && errorHandler.getErrors().size() > 0) {

        moduleStatistics.getFailures().incrementAndGet();

        String message = "Validation errors for File: " + getCurrent() + " errors: " + errorHandler.getErrors();
        if (log.isDebugEnabled()) {
            log.debug(message);
            if (log.isTraceEnabled()) {
                log.trace("Validation warnings for File: " + getCurrent() + " errors: "
                        + errorHandler.getWarnings());
            }
        }
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message);
        } else {
            log.info("accepted errors - " + message);
        }
        return new ModuleResult(false, errorHandler.getErrors().get(0));
    }

    moduleStatistics.getSuccesses().incrementAndGet();
    return new ModuleResult(true);
}

From source file:org.apache.shindig.social.opensocial.util.XSDValidator.java

/**
 * Validate a xml input stream against a supplied schema.
 *
 * @param xml//from  w w  w .  j  a v a  2  s .  c  om
 *          a stream containing the xml
 * @param schema
 *          a stream containing the schema
 * @return a list of errors or warnings, a 0 lenght string if none.
 */
public static String validate(InputStream xml, InputStream schema) {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    final StringBuilder errors = new StringBuilder();
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        Schema s = schemaFactory.newSchema(new StreamSource(schema));

        Validator validator = s.newValidator();
        final LSResourceResolver lsr = validator.getResourceResolver();
        validator.setResourceResolver(new LSResourceResolver() {

            public LSInput resolveResource(String arg0, String arg1, String arg2, String arg3, String arg4) {
                log.info("resolveResource(" + arg0 + ',' + arg1 + ',' + arg2 + ',' + arg3 + ',' + arg4 + ')');
                return lsr.resolveResource(arg0, arg1, arg2, arg3, arg4);
            }

        });

        validator.validate(new StreamSource(xml));
    } catch (IOException e) {
    } catch (SAXException e) {
        errors.append(e.getMessage()).append('\n');
    }

    return errors.toString();
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and URL. Loads only the
 * given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //w ww.j a v  a2s  . co m
 * @param url
 *            the Schema URL
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(URL url, JAXBContext context, Handler handler, Resolver resolver)
        throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    // adds a custom object factory
    // u.setProperty("com.sun.xml.bind.ObjectFactory",new
    // ObjectFactoryEx());
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(url);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.modeldriven.fuml.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //from   www  . j a  va  2s. co  m
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream stream, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schemaGrammar = schemaFactory.newSchema(new StreamSource(stream));
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.plasma.common.bind.ValidatingUnmarshaler.java

/**
 * Creates an unmarshaler using the given factories and sream. Loads only
 * the given (subclass) schema as this is the "root" schema and it should
 * include any other schema resources it needs, and so on. Note all included
 * schemas MUST be found at the same class level as the root schema.
 * //from   w  ww.  j a v a2s.com
 * @param stream
 *            the Schema stream
 * @param context
 *            the SAXB context
 * @param handler
 *            the SAX handler
 * @param resolver
 *            the SAX resolver
 * @return the unmarshaler
 * @throws JAXBException
 * @throws SAXException
 */
private Unmarshaller createUnmarshaler(InputStream[] streams, JAXBContext context, Handler handler,
        Resolver resolver) throws JAXBException, SAXException {
    Unmarshaller u = context.createUnmarshaller();
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    StreamSource[] sources = new StreamSource[streams.length];
    for (int i = 0; i < streams.length; i++) {
        sources[i] = new StreamSource(streams[i]);
        //FIXME: will not resolve relative URI's (included schemas) without this
        //sources[i].setSystemId(systemId)
    }
    Schema schemaGrammar = schemaFactory.newSchema(sources);
    u.setSchema(schemaGrammar);
    Validator schemaValidator = schemaGrammar.newValidator();
    schemaValidator.setResourceResolver(resolver);
    schemaValidator.setErrorHandler(handler);

    return u;
}

From source file:org.sonar.plugins.xml.checks.XmlSchemaCheck.java

private void validate(String[] schemaList) {

    // Create a new validator
    Validator validator = createSchema(schemaList).newValidator();
    setFeature(validator, Constants.XERCES_FEATURE_PREFIX + "continue-after-fatal-error", true);
    validator.setErrorHandler(new MessageHandler());
    validator.setResourceResolver(new SchemaResolver());

    // Validate and catch the exceptions. MessageHandler will receive the errors and warnings.
    try {/*from  ww w.ja v a 2  s  .  c  om*/
        LOG.info("Validate " + getWebSourceCode() + " with schema " + StringUtils.join(schemaList, ","));
        validator.validate(new StreamSource(getWebSourceCode().createInputStream()));
    } catch (SAXException e) {
        if (!containsMessage(e)) {
            createViolation(0, e.getMessage());
        }
    } catch (IOException e) {
        throw new SonarException(e);
    } catch (UnrecoverableParseError e) {
        // ignore, message already reported.
    }
}