Example usage for javax.xml.validation SchemaFactory setResourceResolver

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

Introduction

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

Prototype

public abstract void setResourceResolver(LSResourceResolver resourceResolver);

Source Link

Document

Sets the LSResourceResolver to customize resource resolution when parsing schemas.

Usage

From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java

private Schema loadSchema(String theVersion, String theSchemaName) {
    String key = theVersion + "-" + theSchemaName;

    synchronized (myKeyToSchema) {
        Schema schema = myKeyToSchema.get(key);
        if (schema != null) {
            return schema;
        }//from w w  w. j a va 2  s. c  o m

        Source baseSource = loadXml(null, theSchemaName);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new MyResourceResolver());

        try {
            try {
                /*
                 * See https://github.com/jamesagnew/hapi-fhir/issues/339
                 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
                 */
                schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            } catch (SAXNotRecognizedException snex) {
                ourLog.warn("Jaxp 1.5 Support not found.", snex);
            }
            schema = schemaFactory.newSchema(new Source[] { baseSource });
        } catch (SAXException e) {
            throw new ConfigurationException("Could not load/parse schema file: " + theSchemaName, e);
        }
        myKeyToSchema.put(key, schema);
        return schema;
    }
}

From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java

public void checkIncomingDocument(byte[] document) throws Exception {

    LOG.debug("checking incoming document");
    ByteArrayInputStream documentInputStream = new ByteArrayInputStream(document);
    Document dom = this.documentBuilder.parse(documentInputStream);

    String namespace = dom.getDocumentElement().getNamespaceURI();
    if (null == namespace) {
        LOG.debug("no namespace defined");
        return;//from  w  w  w.ja v  a  2s .  c om
    }

    byte[] xsd = this.context.getXmlSchema(namespace);
    if (null == xsd) {
        LOG.debug("no XML schema available for namespace: " + namespace);
        return;
    }

    LOG.debug("validating against XML schema: " + namespace);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.context));
    StreamSource schemaSource = new StreamSource(new ByteArrayInputStream(xsd));
    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    DOMSource domSource = new DOMSource(dom);
    validator.validate(domSource);
}

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);//w w  w. j  av  a2 s.co 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:integration.AbstractTest.java

/**
 * Parses the specified file and returns the document.
 * //  ww w . j  a v a  2 s.  co  m
 * @param file The file to parse.
 * @param schemaStreamArray The schema as array of stream sources used to validate the specified file.
 * @return
 * @throws Exception Thrown if an error occurred.
 */
protected Document parseFileWithStreamArray(File file, StreamSource[] schemaStreamArray) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file to parse.");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // This must be set to avoid error : cvc-elt.1: Cannot find the declaration of element 'OME'.
    SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SchemaResolver theTestClassResolver = new SchemaResolver();
    sFactory.setResourceResolver(theTestClassResolver);

    Schema theSchema = sFactory.newSchema(schemaStreamArray);

    /*
    // Version - one step parse and validate (print error to stdErr)
    dbf.setSchema(theSchema);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    */

    // Version - two step parse then validate (throws error as exception)
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document theDoc = builder.parse(file);
    Validator validator = theSchema.newValidator();
    validator.validate(new DOMSource(theDoc));
    return theDoc;
}

From source file:csiro.pidsvc.mappingstore.Manager.java

/**************************************************************************
 *  Generic processing methods./*from ww  w.ja  v  a 2s .com*/
 */

protected void validateRequest(String inputData, String xmlSchemaResourcePath)
        throws IOException, ValidationException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new LSResourceResolver() {
            @Override
            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI);
            }
        });

        Schema schema = schemaFactory
                .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath)));
        Validator validator = schema.newValidator();
        _logger.trace("Validating XML Schema.");
        validator.validate(new StreamSource(new StringReader(inputData)));
    } catch (SAXException ex) {
        _logger.debug("Unknown format.", ex);
        throw new ValidationException("Unknown format.", ex);
    }
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Gets the <code>Schema</code> object for the provided <code>InputStream</code>.
 * //  ww  w  . java 2  s .c om
 * @param schemaStream
 *            The Stream containing the schema.
 * @return Returns the <code>Schema</code> object.
 * @throws Exception
 *             If anything fails.
 */
private static Schema getSchema(final InputStream schemaStream) throws Exception {

    if (schemaStream == null) {
        throw new Exception("No schema input stream provided");
    }

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // set resource resolver to change schema-location-host
    sf.setResourceResolver(new SchemaBaseResourceResolver());
    Schema theSchema = sf.newSchema(new SAXSource(new InputSource(schemaStream)));
    return theSchema;
}

From source file:nl.nn.adapterframework.validation.JavaxXmlValidator.java

/**
 * Returns the {@link Schema} associated with this validator. This is an XSD schema containing knowledge about the
 * schema source as returned by {@link #getSchemaSources(List)}
 *///from w  ww  . j  a v  a2 s . c  o m
protected synchronized Schema getSchemaObject(String schemasId,
        List<nl.nn.adapterframework.validation.Schema> schemas) throws ConfigurationException {
    Schema schema = javaxSchemas.get(schemasId);
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new LSResourceResolver() {
            public LSInput resolveResource(String s, String s1, String s2, String s3, String s4) {
                return null;
            }
        });
        try {
            Collection<Source> sources = getSchemaSources(schemas);
            schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
            javaxSchemas.put(schemasId, schema);
        } catch (Exception e) {
            throw new ConfigurationException("cannot read schema's [" + schemasId + "]", e);
        }
    }
    return schema;
}

From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static Schema loadXMLSecuritySchemas() throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new LSResourceResolver() {
        @Override//from   w  w  w .  j  a va  2  s  .  com
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            if ("http://www.w3.org/2001/XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("XMLSchema.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/XMLSchema.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("datatypes.dtd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils
                        .getResourceAsStream("bindings/schemas/datatypes.dtd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"
                    .equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream(
                        "bindings/schemas/xmldsig-core-schema.xsd", XMLSecurityConstants.class));
                return concreteLSInput;
            } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                ConcreteLSInput concreteLSInput = new ConcreteLSInput();
                concreteLSInput.setByteStream(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xml.xsd",
                        XMLSecurityConstants.class));
                return concreteLSInput;
            }
            return null;
        }
    });
    Schema schema = schemaFactory.newSchema(new Source[] {
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/exc-c14n.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig-core-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xenc-schema-11.xsd",
                    XMLSecurityConstants.class)),
            new StreamSource(ClassLoaderUtils.getResourceAsStream("bindings/schemas/xmldsig11-schema.xsd",
                    XMLSecurityConstants.class)), });
    return schema;
}

From source file:org.betaconceptframework.astroboa.configuration.RepositoryRegistry.java

private Schema loadXmlSchema() throws Exception {

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new W3CRelatedSchemaEntityResolver());

    //Search in classpath at root level
    URL configurationSchemaURL = this.getClass().getResource(ASTROBOA_CONFIGURATION_XSD_FILEPATH);

    if (configurationSchemaURL == null) {
        throw new Exception("Could not find " + ASTROBOA_CONFIGURATION_XSD_FILEPATH + " in classpath");
    }//from  w  w w  . j  av a  2s .c o  m

    return schemaFactory.newSchema(configurationSchemaURL);
}

From source file:org.bungeni.editor.system.ValidateConfiguration.java

public List<SAXParseException> validate(File xmlFile, ConfigInfo config) {
    final List<SAXParseException> exceptions = new LinkedList<SAXParseException>();
    try {/*from  ww  w  .  j a v a  2s .  c  om*/
        String pathToXSD = config.getXsdPath();
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new ResourceResolver());
        Schema schema = factory.newSchema(new StreamSource(config.getXsdInputStream()));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });
        StreamSource streamXML = new StreamSource(xmlFile);
        validator.validate(streamXML);
    } catch (SAXException ex) {
        log.error("Error during validation", ex);
    } catch (IOException ex) {
        log.error("Error during validation", ex);
    } finally {
    }
    return exceptions;
}