Example usage for javax.xml.validation SchemaFactory newSchema

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

Introduction

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

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:org.artifactory.jaxb.JaxbHelper.java

@SuppressWarnings({ "unchecked" })
public T read(InputStream stream, Class clazz, URL schemaUrl) {
    T o = null;//from   ww w.jav  a  2 s. c  o  m
    try {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        if (schemaUrl != null) {
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(schemaUrl);
            unmarshaller.setSchema(schema);
        }
        o = (T) unmarshaller.unmarshal(stream);
    } catch (Throwable t) {
        // The following code resolves the errors from JAXB result.
        // Just throwing new RuntimeException doesn't shows the root cause of the failure and it is almost impossible
        // to conclude it without this log.
        if (t instanceof IllegalAnnotationsException) {
            List<IllegalAnnotationException> errors = ((IllegalAnnotationsException) t).getErrors();
            if (errors != null) {
                for (IllegalAnnotationException error : errors) {
                    log.error("Failed to read object from stream, error:", error);
                }
            }
        }
        throw new RuntimeException("Failed to read object from stream.", t);
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return o;
}

From source file:org.artifactory.version.ConfigXmlConversionTest.java

private CentralConfigDescriptor getConfigValid(String configXml) throws Exception {
    JAXBContext context = JAXBContext.newInstance(CentralConfigDescriptorImpl.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL xsdUrl = getClass().getResource("/artifactory.xsd");
    Schema schema = sf.newSchema(xsdUrl);
    unmarshaller.setSchema(schema);//from w ww  .  ja v a  2 s .co  m
    return (CentralConfigDescriptor) unmarshaller.unmarshal(new StringReader(configXml));
}

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 .  ja  v  a  2 s. c o  m

    return schemaFactory.newSchema(configurationSchemaURL);
}

From source file:org.bonitasoft.engine.io.IOUtil.java

public static byte[] marshallObjectToXML(final Object jaxbModel, final URL schemaURL)
        throws JAXBException, IOException, SAXException {
    if (jaxbModel == null) {
        return null;
    }/*  www  . j a va2  s  .  c om*/
    if (schemaURL == null) {
        throw new IllegalArgumentException("schemaURL is null");
    }
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(schemaURL);
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        final JAXBContext contextObj = JAXBContext.newInstance(jaxbModel.getClass());
        final Marshaller m = contextObj.createMarshaller();
        m.setSchema(schema);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(jaxbModel, baos);
        return baos.toByteArray();
    }
}

From source file:org.bonitasoft.engine.io.IOUtil.java

public static <T> T unmarshallXMLtoObject(final byte[] xmlObject, final Class<T> objectClass,
        final URL schemaURL) throws JAXBException, IOException, SAXException {
    if (xmlObject == null) {
        return null;
    }//from  w  w w  .ja va2s  .  c om
    if (schemaURL == null) {
        throw new IllegalArgumentException("schemaURL is null");
    }
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(schemaURL);
    final JAXBContext contextObj = JAXBContext.newInstance(objectClass);
    final Unmarshaller um = contextObj.createUnmarshaller();
    um.setSchema(schema);
    try (ByteArrayInputStream bais = new ByteArrayInputStream(xmlObject)) {
        final StreamSource ss = new StreamSource(bais);
        final JAXBElement<T> jaxbElement = um.unmarshal(ss, objectClass);
        return jaxbElement.getValue();
    }
}

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 {/*  w w  w .  ja v a 2 s .com*/
        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;
}

From source file:org.cerberus.crud.service.impl.ImportFileService.java

@Override
public AnswerItem importAndValidateXMLFromInputStream(InputStream filecontent, InputStream schemaContent,
        XMLHandlerEnumType handlerType) {
    AnswerItem answer = new AnswerItem();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    msg.setDescription(//from ww w.j  av a  2s.  c  o  m
            msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Import"));
    if (schemaContent != null) {
        try {

            //InputStream data = new BufferedInputStream(filecontent);

            String textContent = IOUtils.toString(filecontent);

            Source source = new StreamSource(IOUtils.toInputStream(textContent));
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            Source sourceschema = new StreamSource(schemaContent);

            Schema schema = factory.newSchema(sourceschema);
            Validator validator = schema.newValidator();
            //is valid
            validator.validate(source);
            //document is valid, then proceed to load the data

            answer.setItem(parseXMLFile(IOUtils.toInputStream(textContent), handlerType));

        } catch (SAXException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_IMPORT_ERROR_FORMAT);
            msg.setDescription(
                    msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%FORMAT%", "XML"));

        } catch (ParserConfigurationException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to parse the XML document. Please try again later."));
        } catch (IOException ex) {
            MyLogger.log(ImportFileService.class.getName(), Level.ERROR,
                    "Unable to parse XML: " + ex.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                    "Unable to verify if the XML document is valid. Please try again later."));
        }

    }
    answer.setResultMessage(msg);
    return answer;
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.endpoint.writer.TestFeatureCollectionMessageBodyWriter.java

@Test
public void testWriteToGeneratesGMLConformantXml() throws IOException, WebApplicationException, SAXException {

    FeatureCollectionMessageBodyWriter wtr = new FeatureCollectionMessageBodyWriter();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    wtr.writeTo(getWfsFeatureCollection(), null, null, null, null, null, stream);
    String actual = stream.toString();

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

        private Map<String, String> schemaLocations;

        private Map<String, LSInput> inputs;

        {/* ww w.  ja v a2s. c  om*/
            inputs = new HashMap<String, LSInput>();

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

            schemaLocations.put("xml.xsd", "/w3/1999/xml.xsd");
            schemaLocations.put("xlink.xsd", "/w3/1999/xlink.xsd");
            schemaLocations.put("geometry.xsd", "/gml/2.1.2/geometry.xsd");
            schemaLocations.put("feature.xsd", "/gml/2.1.2/feature.xsd");
            schemaLocations.put("gml.xsd", "/gml/2.1.2/gml.xsd");
            schemaLocations.put("expr.xsd", "/filter/1.0.0/expr.xsd");
            schemaLocations.put("filter.xsd", "/filter/1.0.0/filter.xsd");
            schemaLocations.put("filterCapabilities.xsd", "/filter/1.0.0/filterCapabilties.xsd");
            schemaLocations.put("WFS-capabilities.xsd", "/wfs/1.0.0/WFS-capabilities.xsd");
            schemaLocations.put("OGC-exception.xsd", "/wfs/1.0.0/OGC-exception.xsd");
            schemaLocations.put("WFS-basic.xsd", "/wfs/1.0.0/WFS-basic.xsd");
            schemaLocations.put("WFS-transaction.xsd", "/wfs/1.0.0/WFS-transaction.xsd");
            schemaLocations.put("wfs.xsd", "/wfs/1.0.0/wfs.xsd");
        }

        @Override
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            String fileName = new java.io.File(systemId).getName();
            if (inputs.containsKey(fileName)) {
                return inputs.get(fileName);
            }

            LSInput input = new DOMInputImpl();
            InputStream is = getClass().getResourceAsStream(schemaLocations.get(fileName));
            input.setByteStream(is);
            input.setBaseURI(baseURI);
            input.setSystemId(systemId);
            inputs.put(fileName, input);
            return input;
        }
    });

    Source wfsSchemaSource = new StreamSource(getClass().getResourceAsStream("/wfs/1.0.0/wfs.xsd"));
    Source testSchemaSource = new StreamSource(getClass().getResourceAsStream("/schema.xsd"));

    Schema schema = schemaFactory.newSchema(new Source[] { wfsSchemaSource, testSchemaSource });

    try {
        schema.newValidator().validate(new StreamSource(new StringReader(actual)));
    } catch (Exception e) {
        fail("Generated GML Response does not conform to WFS Schema" + e.getMessage());
    }
}

From source file:org.dataconservancy.dcs.access.server.TransformerServiceImpl.java

@Override
public SchemaType.Name validateXML(String inputXml, String schemaURI) {

    if (schemaURI == null)
        return null;
    for (SchemaType.Name schemaName : SchemaType.Name.values()) {
        if (Pattern.compile(Pattern.quote(schemaName.nameValue()), Pattern.CASE_INSENSITIVE).matcher(schemaURI)
                .find()) {//from w  ww . ja  v  a2  s .c  o  m
            DocumentBuilder parser;
            Document document;
            try {

                parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();

                document = parser.parse(new StringBufferInputStream(inputXml));

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

                Source schemaFile = new StreamSource(
                        new File(getServletContext().getContextPath() + "xml/" + schemaName.name() + ".xsd"));
                Schema schema = factory.newSchema(schemaFile);

                Validator validator = schema.newValidator();
                validator.validate(new DOMSource(document));
                return schemaName;
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
    }
    return null;

}

From source file:org.dataconservancy.ui.model.builder.xstream.XstreamBusinessObjectBuilder.java

/**
 * Constructs a builder that will perform validation when de-serializing XML streams if <code>isValidating</code>
 * is <code>true</code>.  The schema used for validation is the BOP 1.0 schema.
 * <p/>/*from   ww w .  j a  v  a2  s.  co m*/
 * <strong><em>N.B.</em></strong>: currently this class will only validate incoming DC BOPs (it will <em>not</em>
 * validate entities).  At a later time this implementation may be updated to validate entities as well.
 *
 * @param isValidating flag indicating whether or not validation should be enabled
 * @throws IllegalStateException if the BOP schema cannot be resolved or parsed
 */
public XstreamBusinessObjectBuilder(XStream xStream, boolean isValidating) {
    x = xStream;
    validating = isValidating;

    if (validating) {
        try {
            // Create a namespace-aware parser that will parse XML into a DOM tree.
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            parser = dbf.newDocumentBuilder();

            // Create a SchemaFactory
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // Load the schema
            final URL businessObjectSchema = this.getClass().getResource(BOP_SCHEMA_RESOURCE);
            Source schemaFile = new StreamSource(businessObjectSchema.openStream());
            Schema schema = factory.newSchema(schemaFile);

            // Create a Validator instance, which can be used to validate an instance document
            validator = schema.newValidator();
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException("Unable to initialize " + this.getClass().getName()
                    + ": error configuring parser: " + e.getMessage(), e);
        } catch (SAXException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": error retrieving "
                            + " or parsing class path resource " + BOP_SCHEMA_RESOURCE + ": " + e.getMessage(),
                    e);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to initialize " + this.getClass().getName() + ": IO error: " + e.getMessage(), e);
        }
    }
}