Example usage for javax.xml.validation SchemaFactory newInstance

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

Introduction

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

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }// ww  w. j av a 2 s .co m
    validator.validate(new JAXBSource(context, document));
}

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

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {//  w w  w  .j  a  va2s  .co m
        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:de.iteratec.iteraplan.businesslogic.service.SavedQueryXmlHelper.java

private static Schema getSchema(String schemaName) throws SAXException {
    SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL inStream = SavedQueryServiceImpl.class.getResource(schemaName);
    if (inStream == null) {
        throw new IteraplanTechnicalException(IteraplanErrorMessages.FILE_NOT_FOUND_EXCEPTION);
    }//from   w  w w .jav  a 2s. co m

    return sf.newSchema(inStream);
}

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  ww  . j  a  v a 2s  .com
    }

    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:io.aino.agents.core.config.InputStreamConfigBuilder.java

/**
 * Validates the config file against XSD schema.
 *
 * @param stream InputStream to config file.
 *///from   w w w.j  a  va  2  s .c  o  m
private void validateSchema(InputStream stream) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        InputStream xsdStream = this.getClass().getClassLoader().getResourceAsStream(LOGGER_SCHEMA);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(stream));
    } catch (SAXException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    } catch (IOException e) {
        throw new InvalidAgentConfigException("Failed to validate logger config.", e);
    }
}

From source file:mx.bigdata.sat.cfdi.CFDv3.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[] { new StreamSource(getClass().getResourceAsStream(XSD)),
            new StreamSource(getClass().getResourceAsStream(XSD_TFD)) };
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }//from  w  w w .  java 2 s . c  o  m
    validator.validate(new JAXBSource(context, document));
}

From source file:info.raack.appliancelabeler.service.OAuthRequestProcessor.java

@PostConstruct
public void init() {
    try {//from  ww w  .  j a v  a  2 s. c  o m
        JAXBContext jc = JAXBContext.newInstance("edu.cmu.hcii.stepgreen.data.teds");
        u1 = jc.createUnmarshaller();
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = this.getClass().getClassLoader().getResource("teds.xsd");
        Schema schema = sf.newSchema(url);
        u1.setSchema(schema);

        jc = JAXBContext.newInstance("edu.cmu.hcii.stepgreen.data.base");
        u2 = jc.createUnmarshaller();
        sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        url = this.getClass().getClassLoader().getResource("stepgreen.xsd");
        schema = sf.newSchema(url);
        u2.setSchema(schema);

    } catch (Exception e) {
        throw new RuntimeException("Could not create JAXB unmarshaller", e);
    }
}

From source file:org.mitre.stix.STIXSchema.java

/**
 * Private constructor to permit a single STIXSchema to exists.
 *//*  ww w .j av a2 s . c o m*/
private STIXSchema() {

    this.version = ((Version) this.getClass().getPackage().getAnnotation(Version.class)).schema();

    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(
            this.getClass().getClassLoader());
    Resource[] schemaResources;

    try {
        schemaResources = patternResolver.getResources("classpath:schemas/v" + version + "/**/*.xsd");

        prefixSchemaBindings = new HashMap<String, String>();

        String url, prefix, targetNamespace;
        Document schemaDocument;
        NamedNodeMap attributes;
        Node attribute;

        for (Resource resource : schemaResources) {

            url = resource.getURL().toString();

            schemaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(resource.getInputStream());

            schemaDocument.getDocumentElement().normalize();

            attributes = schemaDocument.getDocumentElement().getAttributes();

            for (int i = 0; i < attributes.getLength(); i++) {

                attribute = attributes.item(i);

                targetNamespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");

                if (attribute.getNodeName().startsWith("xmlns:")
                        && attribute.getNodeValue().equals(targetNamespace)) {

                    prefix = attributes.item(i).getNodeName().split(":")[1];

                    if ((prefixSchemaBindings.containsKey(prefix))
                            && (prefixSchemaBindings.get(prefix).split("schemas/v" + version + "/")[1]
                                    .startsWith("external"))) {

                        continue;

                    }

                    LOGGER.fine("     adding: " + prefix + " :: " + url);

                    prefixSchemaBindings.put(prefix, url);
                }
            }
        }

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Source[] schemas = new Source[prefixSchemaBindings.values().size()];

        int i = 0;
        for (String schemaLocation : prefixSchemaBindings.values()) {
            schemas[i++] = new StreamSource(schemaLocation);
        }

        schema = factory.newSchema(schemas);

        validator = schema.newValidator();
        validator.setErrorHandler(new ValidationErrorHandler());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.polimi.modaclouds.qos_models.util.XMLHelper.java

public static <T> ValidationResult validate(FileInputStream xmlPath, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;//w ww . j av a  2 s  .  com
    ValidationResult result;
    try {
        Schema schema = schemaFactory.newSchema();
        unmarshaller = JAXBContext.newInstance(targetClass).createUnmarshaller();
        unmarshaller.setSchema(schema);
    } catch (SAXException | JAXBException e) {
        result = new ValidationResult(false);
        result.addMessage("Error occured in creating the schema");
        result.addMessage(e.getLocalizedMessage());
        return result;
    }
    try {
        unmarshaller.unmarshal(xmlPath);
    } catch (JAXBException e) {
        result = new ValidationResult(false);
        if (e.getMessage() != null)
            result.addMessage(e.getLocalizedMessage());
        if (e.getLinkedException() != null && e.getLinkedException().getLocalizedMessage() != null)
            result.addMessage(e.getLinkedException().getLocalizedMessage());
        return result;
    }
    return new ValidationResult(true);

}

From source file:mx.bigdata.sat.cfd.CFDv22.java

public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
        schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }/* ww  w .  ja  v a  2  s  .co m*/
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
}