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: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  ava2  s  .c o m

    return schemaFactory.newSchema(configurationSchemaURL);
}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

protected JAXBRenderer(final UrlRenderer urlRenderer) {
    final RestProperties properties = RestProperties.getInstance();
    this.urlRenderer = urlRenderer;

    try {//from www .j av a  2 s  .  com
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (final DatatypeConfigurationException ex) {
        throw new RuntimeException("Could not instantiate data type factory.", ex);
    }

    this.validateXMLInput = "true".equals(properties.get(VALIDATE_XML_INPUT));
    this.validateXMLOutput = "true".equals(properties.get(VALIDATE_XML_OUTPUT));
    ModelFactory.getInstance().setModelValidator(properties.getModelValidator());

    // we only need to load the XML schema if we validate input or output
    if (this.validateXMLInput || this.validateXMLOutput) {
        try {
            schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                    .newSchema(this.getClass().getClassLoader().getResource("xschema.xsd"));
        } catch (final Exception e) {
            log.error("Failed to load XML schema", e);
            schema = null;
        }
    } else {
        schema = null;
    }
}

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;
    }/*from www  .  j ava 2s  .  co m*/
    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.  j av a  2  s  . c  o m
    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 {//www.ja  v  a  2 s  .c  o  m
        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 w w  w .j a  v 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.  j  a  v a 2  s  . c o m*/
            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.commonvox.hbase_column_manager.TestRepositoryAdmin.java

private void validateXmlAgainstXsd(File xmlFile) throws IOException {
    Document hsaDocument = null;//from   w ww  . j  av  a 2  s.c o  m
    Schema hsaSchema = null;
    try {
        hsaDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    } catch (ParserConfigurationException pce) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " parser config exception thrown: " + pce.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading test document: "
                + se.getMessage());
    }
    try {
        hsaSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(Paths
                        .get(ClassLoader.getSystemResource(XmlSchemaGenerator.DEFAULT_OUTPUT_FILE_NAME).toURI())
                        .toFile());
    } catch (URISyntaxException ue) {
        fail(TEST_ENVIRONMENT_SETUP_PROBLEM + " URI syntax exception thrown: " + ue.getMessage());
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " SAX exception thrown while loading XML-schema: " + se.getMessage());
    }
    // validate against XSD
    try {
        hsaSchema.newValidator().validate(new DOMSource(hsaDocument));
    } catch (SAXException se) {
        fail(REPOSITORY_ADMIN_FAILURE + " exported HSA file is invalid with respect to " + "XML schema: "
                + se.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  ww w  . ja v a 2 s.com*/
            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.dcs.archive.impl.elm.DcsEntityStreamTest.java

@BeforeClass
public static void getSchema() throws Exception {
    schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new StreamSource(
            DcsEntityStreamTest.class.getResourceAsStream(DcsEntityStreamTest.DCP_SCHEMA_LOC)));
}