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:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {// ww w .ja  v  a 2 s  .c  om
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from   w  w w. j a v a 2 s  .  c  om*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:eu.delving.x3ml.X3MLEngine.java

private static SchemaFactory schemaFactory() {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {/* w w w  . ja  v a2  s  .  c o  m*/
        //            schemaFactory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.CTA_FULL_XPATH_CHECKING_FEATURE, true);
        schemaFactory.setResourceResolver(new ResourceResolver());
    } catch (Exception e) {
        throw new RuntimeException("Configuring schema factory", e);
    }
    return schemaFactory;
}

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);//from w w w. j a  v a 2  s  .com
    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.SOAPMessageValidatorInterceptor.java

private List<Validator> getValidators() throws Exception {
    log.info("Get validators for WSDL: " + wsdl);
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(wsdl);//from  ww w.  j ava  2s .  c  o m
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(new SOAModelResourceResolver(wsdl));
    List<Validator> validators = new ArrayList<Validator>();
    for (Schema schema : getEmbeddedSchemas(ctx)) {
        log.info("Adding embedded schema: " + schema);
        Validator validator = sf
                .newSchema(new StreamSource(new ByteArrayInputStream(schema.getAsString().getBytes())))
                .newValidator();
        validator.setErrorHandler(new SchemaValidatorErrorHandler());
        validators.add(validator);
    }
    return validators;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file//from w  w w . j  a v a 2 s . c  o m
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document//from   w w  w  .  j  a  va 2s  . co  m
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}

From source file:io.onedecision.engine.decisions.model.dmn.validators.SchemaValidator.java

public void validate(InputStream obj, Errors errors) {
    InputStream is = (InputStream) obj;

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

    try {//from ww w  .java  2  s .  c  o m
        schemaFactory.newSchema(new StreamSource(getResourceAsStreamWrapper("schema/dmn.xsd")));
    } catch (SAXException e1) {
        errors.reject("Cannot find / read schema", "Exception: " + e1.getMessage());
    }

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    // parserFactory.setValidating(true);
    parserFactory.setNamespaceAware(true);
    // parserFactory.setSchema(schema);

    SAXParser parser = null;
    try {
        parser = parserFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(this);

        try {
            parser.parse(new InputSource(is), (DefaultHandler) null);
        } catch (Exception e) {
            String msg = "Schema validation failed";
            LOGGER.error(msg, e);
            errors.reject(msg, "Exception: " + e.getMessage());
        }
        if (this.errors.size() > 0) {
            errors.reject("Schema validation failed", this.errors.toString());
        }
    } catch (ParserConfigurationException e1) {
        errors.reject("Cannot create parser", "Exception: " + e1.getMessage());
    } catch (SAXException e1) {
        errors.reject("Parser cannot be created", "Exception: " + e1.getMessage());
    }
}

From source file:be.fedict.eid.dss.model.bean.XmlSchemaManagerBean.java

public void add(String revision, InputStream xsdInputStream)
        throws InvalidXmlSchemaException, ExistingXmlSchemaException {
    byte[] xsd;// w  w  w  . j  a  va2s .co  m
    try {
        xsd = IOUtils.toByteArray(xsdInputStream);
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(xsd);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.entityManager));
    StreamSource schemaSource = new StreamSource(schemaInputStream);
    try {
        schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("SAX error: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException("SAX error: " + e.getMessage(), e);
    } catch (RuntimeException e) {
        LOG.error("Runtime exception: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException(e.getMessage(), e);
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    schemaInputStream = new ByteArrayInputStream(xsd);
    Document schemaDocument;
    try {
        schemaDocument = documentBuilder.parse(schemaInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    String namespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");
    LOG.debug("namespace: " + namespace);

    XmlSchemaEntity existingXmlSchemaEntity = this.entityManager.find(XmlSchemaEntity.class, namespace);
    if (null != existingXmlSchemaEntity) {
        throw new ExistingXmlSchemaException();
    }

    XmlSchemaEntity xmlSchemaEntity = new XmlSchemaEntity(namespace, revision, xsd);
    this.entityManager.persist(xmlSchemaEntity);
}

From source file:eu.delving.test.TestMappingEngine.java

private Validator validator(SchemaVersion schemaVersion) {
    try {/*  ww w  .  j  a v a 2s . c om*/
        SchemaFactory factory = XMLToolFactory.schemaFactory(schemaVersion.getPrefix());
        factory.setResourceResolver(new CachedResourceResolver());
        String validationXsd = schemaRepo.getSchema(schemaVersion, SchemaType.VALIDATION_SCHEMA)
                .getSchemaText();
        if (validationXsd == null)
            throw new RuntimeException("Unable to find validation schema " + schemaVersion);
        Schema schema = factory.newSchema(new StreamSource(new StringReader(validationXsd)));
        return schema.newValidator();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}