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:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Validates an xml object graph against its schema. Therefore it reads the
 * version from the root tag and tries to load the related xsd file from the
 * classpath./*w  w w .  j  a  va2s .c o  m*/
 * 
 * @param xmlRootNode
 *            root xml node of the document to validate
 * @throws InvalidConfigurationException
 *             if the validation could not be performed or the xml graph is
 *             invalid against the schema
 */
private static void validateDocumentAgainstSchema(final Document xmlRootNode)
        throws InvalidConfigurationException {
    final Element rootElement = xmlRootNode.getDocumentElement();
    final String version = rootElement.getAttribute("version");
    String schemaFileName = "persistence_" + version.replace(".", "_") + ".xsd";

    try {
        final List validationErrors = new ArrayList();
        final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName));
        final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource);

        final Validator schemaValidator = schemaDefinition.newValidator();
        schemaValidator.setErrorHandler(new ErrorLogger("XML InputStream", validationErrors));
        schemaValidator.validate(new DOMSource(xmlRootNode));

        if (!validationErrors.isEmpty()) {
            final String exceptionText = "persistence.xml is not conform against the supported schema definitions.";
            throw new InvalidConfigurationException(exceptionText);
        }
    } catch (SAXException e) {
        final String exceptionText = "Error validating persistence.xml against schema defintion, caused by: ";
        throw new InvalidConfigurationException(exceptionText, e);
    } catch (IOException e) {
        final String exceptionText = "Error opening xsd schema file. The given persistence.xml descriptor version "
                + version + " might not be supported yet.";
        throw new InvalidConfigurationException(exceptionText, e);
    }
}

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

public static <T> ValidationResult validate(InputStream xmlStream, Class<T> targetClass) {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Unmarshaller unmarshaller;/*from w  w w .j a v  a  2s.  co m*/
    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(xmlStream);
    } 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:eu.delving.x3ml.X3MLEngine.java

private static SchemaFactory schemaFactory() {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {// w w  w .j  a  v a  2 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.rest4j.ApiFactory.java

/**
 * Create the API instance. The XML describing the API is read, preprocessed, analyzed for errors,
 * and the internal structures for Java object marshalling and unmarshalling are created, as
 * well as endpoint mappings./*from  w w  w . j  ava 2  s. com*/
 *
 * @return The API instance
 * @throws ConfigurationException When there is a problem with your XML description.
 */
public API createAPI() throws ConfigurationException {
    try {
        JAXBContext context;
        if (extObjectFactory == null)
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class);
        else
            context = JAXBContext.newInstance(com.rest4j.impl.model.ObjectFactory.class, extObjectFactory);
        Document xml = getDocument();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source apiXsdSource = new StreamSource(getClass().getResourceAsStream("api.xsd"));
        List<Source> xsds = new ArrayList<Source>();
        xsds.add(apiXsdSource);
        Schema schema;
        if (!StringUtils.isEmpty(extSchema)) {
            xsds.add(new StreamSource(getClass().getClassLoader().getResourceAsStream(extSchema)));
        }
        xsds.add(new StreamSource(getClass().getResourceAsStream("html.xsd")));
        schema = schemaFactory.newSchema(xsds.toArray(new Source[xsds.size()]));

        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        JAXBElement<com.rest4j.impl.model.API> element = (JAXBElement<com.rest4j.impl.model.API>) unmarshaller
                .unmarshal(xml);
        com.rest4j.impl.model.API root = element.getValue();
        APIImpl api;
        api = new APIImpl(root, pathPrefix, serviceProvider,
                factories.toArray(new ObjectFactory[factories.size()]),
                fieldFilters.toArray(new FieldFilter[fieldFilters.size()]), permissionChecker);
        return api;
    } catch (javax.xml.bind.UnmarshalException e) {
        if (e.getLinkedException() instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e.getLinkedException();
            throw new ConfigurationException("Cannot parse " + apiDescriptionXml, spe);
        }
        throw new AssertionError(e);
    } catch (ConfigurationException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java

private Validator createValidator(StreamSource[] sources) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setFeature("http://apache.org/xml/features/xinclude", true);
    Schema schema = sf.newSchema(sources);
    return schema.newValidator();
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Validate the configuration against XML Schema.
 *
 * @throws ConfigException if not valid//  w ww. j  a v  a2  s.c  o  m
 */
private void validateXMLConfiguration(InputStream xmlConfigurationStream) throws IOException, ConfigException {
    assert xmlConfigurationStream != null;
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        final Schema schema = sf
                .newSchema(MathMLCanonicalizer.class.getResource(Settings.getProperty("configSchema")));

        final Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlConfigurationStream));
    } catch (SAXException ex) {
        throw new ConfigException("configuration not valid\n" + ex.getMessage(), ex);
    }
}

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

@Override
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]));
    }// www. java2s.  com
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
}

From source file:ddf.test.itests.platform.TestSingleSignOn.java

private void validateSaml(String xml, SamlSchema schema) throws IOException {

    // Prepare the schema and xml
    String schemaFileName = "saml-schema-" + schema.toString().toLowerCase() + "-2.0.xsd";
    URL schemaURL = getClass().getClassLoader().getResource(schemaFileName);
    StreamSource streamSource = new StreamSource(new StringReader(xml));

    // If we fail to create a validator we don't want to stop the show, so we just log a warning
    Validator validator = null;/*w  ww.j a  va  2 s .com*/
    try {
        validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL)
                .newValidator();
    } catch (SAXException e) {
        LOGGER.warn("Exception creating validator. ", e);
    }

    // If the xml is invalid, then we want to fail completely
    if (validator != null) {
        try {
            validator.validate(streamSource);
        } catch (SAXException e) {
            fail("Failed to validate SAML " + e.getMessage());
        }
    }
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * @param useProxy if a debugging proxy should be used
 *
 * @throws IllegalStateException if DOM parser could not be created
 *///from   w w  w .  ja  v  a 2 s . co  m
public WineryRepositoryClient(boolean useProxy) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getClasses().add(JacksonJsonProvider.class);
    if (useProxy) {
        URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
        this.client = new Client(ch, clientConfig);
    } else {
        this.client = Client.create(clientConfig);
    }

    this.entityTypeDataCache = new HashMap<>();
    this.nameCache = new HashMap<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    if (WineryRepositoryClient.VALIDATING) {
        factory.setValidating(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema;
        URL resource = this.getClass().getResource("/TOSCA-v1.0.xsd");
        try {
            schema = schemaFactory.newSchema(resource);
        } catch (SAXException e) {
            throw new IllegalStateException("Schema could not be initalized", e);
        }
        factory.setSchema(schema);
    }
    try {
        this.toscaDocumentBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("document builder could not be initalized", e);
    }
    /*
     TODO: include this somehow - in the case of VALIDATING
            
     Does not work with TTopolgoyTemplate as this is not allowed in the root of an XML document
    this.toscaDocumentBuilder.setErrorHandler(new ErrorHandler() {
            
       @Override
       public void warning(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void fatalError(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void error(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
    });
    */
}

From source file:org.ff4j.console.conf.XmlConfigurationParser.java

/**
 * Mthode permettant de crer le Unmarshaller pour le parsing du XML.
 * @param modelPackage/*from  ww  w . j a  va2  s.co m*/
 *            nom du package qui contient les beans utilises pour le parsing du fichier.
 * @param schemafile
 *            le fichier XSD pour la validation du XML.
 * @return Unmarshaller
 * @throws JAXBException
 * @throws SAXException
 */
public Unmarshaller getUnmarshaller(String modelPackage, File schemafile) throws JAXBException, SAXException {
    JAXBContext jc = JAXBContext.newInstance(modelPackage);
    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemafile);
    Unmarshaller u = jc.createUnmarshaller();
    u.setSchema(schema);
    u.setEventHandler(new XmlConfigurationErrorHandler());
    return u;
}