Example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

List of usage examples for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Prototype

String W3C_XML_SCHEMA_NS_URI

To view the source code for javax.xml XMLConstants W3C_XML_SCHEMA_NS_URI.

Click Source Link

Document

W3C XML Schema Namespace URI.

Usage

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 {//from  www  .j  a  v a2 s . c om
        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;

        {/*from ww  w  .  j  a  va  2  s . co 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;//  w w w  . 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()) {/* ww  w.  jav a  2  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.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)));
}

From source file:org.dataconservancy.model.builder.DcsModelBuilderTest.java

/**
 * Sets options on XMLUnit, locates the schema used to validate the DCP xml, validates the schema document itself,
 * and ensures we have an implementation to test.
 */// www. ja  v  a  2  s  .  com
@Before
public void setUp() throws IOException {

    // Set XMLUnit options
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);

    // Locate the schema
    final String schemaResourcePath = "classpath:/schema/dcp.xsd";
    dcpSchema = resourceLoader.getResource(schemaResourcePath);
    assertNotNull("Could not find the schema " + schemaResourcePath, dcpSchema);
    assertTrue("Schema does not exist at " + schemaResourcePath, dcpSchema.exists());

    // Validate the schema itself
    try {
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(dcpSchema.getInputStream()));
    } catch (SAXException e) {
        fail("Schema document '" + dcpSchema.getURI().toString() + "' is invalid: " + e.getMessage());
    }

    // Ensure we have an implementation to test!
    assertNotNull("Builder instance under test must not be null!", this.underTest = getUnderTest());
}

From source file:org.dataconservancy.model.builder.DcsModelBuilderTest.java

private ErrorHandlerCollector isValid(TestCase tc, String xml) throws IOException, SAXException {
    assertNotNull(tc);//from   w  ww. j a v  a  2s.c om
    assertNotNull(xml);
    assertFalse(xml.trim().length() == 0);

    final TestResult result;

    final Schema s = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(new StreamSource(dcpSchema.getInputStream()));

    final ErrorHandlerCollector errors = new ErrorHandlerCollector();

    final Validator v = s.newValidator();
    v.setErrorHandler(errors);
    try {
        v.validate(new StreamSource(IOUtils.toInputStream(xml)));
    } catch (SAXException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }

    return errors;
}

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  w ww .  j a v  a 2s . c o  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);
        }
    }
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

public ProfileServiceImpl(ProfileDAO profileDAO, String docBuilderFactory, IDMappingDAO idMappingDAO,
        TypeMappingService typeMappingService) {

    this.profileDAO = profileDAO;
    this.idMappingDAO = idMappingDAO;
    this.typeMappingService = typeMappingService;
    if (docBuilderFactory != null)
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", docBuilderFactory);
    dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from   w  w w  . ja v a 2 s.c  o  m*/
    sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    if (logger.isDebugEnabled()) {
        logger.debug("DocumentBuilderFactory: " + dbf.getClass().getName());
        ClassLoader cl = Thread.currentThread().getContextClassLoader().getSystemClassLoader();
        URL url = cl.getResource("org/apache/xerces/jaxp/DocumentBuilderFactoryImpl.class");
        logger.debug("Parser loaded from: " + url);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (Exception e) {
        logger.warn("An error occurred!", e);
    }
}