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.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.
 */// w w w .j a  v a 2  s.  c  om
@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 w  w .j av a2s. com
    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/>/* w  w w.j a va 2s .  c om*/
 * <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.deegree.protocol.csw.client.getrecords.TestGetRecordsXMLEncoderTest.java

private void validateGetRecordsXml(ByteArrayOutputStream os) throws SAXException, IOException {
    InputStream getRecordsRequest = new ByteArrayInputStream(os.toByteArray());
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Validator validator = null;//from ww w .  j a va2  s .c o m
    Source source = null;
    try {
        URL schemaLocation = new URL("http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd");
        Schema schema = factory.newSchema(schemaLocation);
        validator = schema.newValidator();
        source = new StreamSource(getRecordsRequest);
    } catch (Exception e) {
        Assume.assumeNoException(e);
        return;
    }
    validator.validate(source);
}

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);/*  w ww .  ja  v  a  2  s  . co 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);
    }
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public ProfileServiceImpl(TypedProfileDAO profileDAO, ProfiledItemTypeDAO profiledItemTypeDAO,
        String docBuilderFactory) {

    this.typedProfileDAO = profileDAO;
    this.profiledItemTypeDAO = profiledItemTypeDAO;
    if (docBuilderFactory != null)
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", docBuilderFactory);
    dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from   w w  w.j av a  2  s  . c om
    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);
    }
    validationParsers = new HashMap<Integer, Map<String, DocumentBuilder>>();

    loadSchemas();
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (Exception e) {

    }
}

From source file:org.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

public static boolean validateAgainstSchema(String xmlLocation, String xsdLocation)
        throws PreProcessFailedException {
    boolean isValidate = false;

    Document document = null;/*ww w.  j a  va2s . c o  m*/
    Schema schema = null;
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder parser = domFactory.newDocumentBuilder();
        document = parser.parse(new File(xmlLocation));

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = Thread.currentThread().getContextClassLoader().getResource(xsdLocation);
        if (schemaUrl == null) {
            throw new PreProcessFailedException("Unable to find schema resource: " + xsdLocation);
        }

        InputStream stream = null;
        try {
            stream = schemaUrl.openStream();
            Source schemaFile = new StreamSource(stream);
            schema = factory.newSchema(schemaFile);
        } finally {
            IOUtils.closeQuietly(stream);
        }

    } catch (ParserConfigurationException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);

    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "XML parsing failed because of IOException : " + exception.getMessage(), exception);
    } catch (Exception exception) {
        throw new PreProcessFailedException("XML parsing failed : " + exception.getMessage(), exception);
    }

    Validator validator = schema.newValidator();

    try {
        validator.validate(new DOMSource(document));
        isValidate = true;
    } catch (SAXException exception) {
        throw new PreProcessFailedException("XML validation against XSD failed : " + exception.getMessage(),
                exception);
    } catch (IOException exception) {
        throw new PreProcessFailedException(
                "Schema validation failed because of IOException : " + exception.getMessage(), exception);
    }

    return isValidate;
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static void validate(IPath tmpFileInWorkspaceDir)
        throws IOException, ParserConfigurationException, SAXException, URISyntaxException {

    // TODO delete commented out code which was used for debugging (debug code needs to stay at least two releases after 2.5.9)
    // Get the XSD file
    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");
    // Path ditaSchemadirPath = new Path("DITA-OT/schema/technicalContent/xsd/topic.xsd");
    // URL ditaXSD = FileLocator.toFileURL(FileLocator.find(bundle, ditaSchemadirPath, null));
    Path ditaFolderPath = new Path("DITA-OT");
    URL ditaFolder = FileLocator.toFileURL(FileLocator.find(bundle, ditaFolderPath, null));
    // System.out.println(ditaFolder);

    // Create DBF and ignore DTD
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from   w  w  w. j  a  v a  2  s. co  m
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document document = parser.parse(tmpFileInWorkspaceDir.toFile());

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Use catalog
    // Path ditaCatalogPath = new Path("DITA-OT/schema/catalog.xml");
    // URL ditaCatalog = FileLocator.toFileURL(FileLocator.find(bundle, ditaCatalogPath, null));
    File ditaCatalogFile = new File(ditaFolder.getFile(), "schema/catalog.xml");
    // System.out.println(ditaCatalogFile);
    // System.out.println(ditaCatalogFile.exists());
    XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { ditaCatalogFile.getAbsolutePath() });
    schemaFactory.setResourceResolver(resolver);

    // load a WXS schema, represented by a Schema instance
    File ditaSchemaFile = new File(ditaFolder.getFile(), "schema/technicalContent/xsd/topic.xsd");

    // System.out.println(ditaSchemaFile);
    // System.out.println(ditaSchemaFile.exists());
    Source schemaFile = new StreamSource(ditaSchemaFile);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    DOMSource dom = new DOMSource(document);
    validator.validate(dom);
}

From source file:org.eclipse.om2m.commons.utils.XmlValidator.java

/** Constructor */
private XmlValidator() {
    schemas = new HashMap<String, Schema>();
    factory = SAXParserFactory.newInstance();
    factory.setValidating(false);//from   w w w . ja v a  2s .c o m
    factory.setNamespaceAware(true);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    // Create all required schemas based on xsd files when starting and add them to the schemas map to enhance response time performance.
    try {
        schemas.put("sclBase.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/sclBase.xsd")));
        schemas.put("accessRights.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/accessRights.xsd")));
        schemas.put("accessRight.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/accessRight.xsd")));
        schemas.put("accessRightAnnc.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/accessRightAnnc.xsd")));
        schemas.put("scls.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/scls.xsd")));
        schemas.put("scl.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/scl.xsd")));
        schemas.put("applications.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/applications.xsd")));
        schemas.put("application.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/application.xsd")));
        schemas.put("applicationAnnc.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/applicationAnnc.xsd")));
        schemas.put("containers.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/containers.xsd")));
        schemas.put("container.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/container.xsd")));
        schemas.put("containerAnnc.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/containerAnnc.xsd")));
        schemas.put("contentInstance.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/contentInstance.xsd")));
        schemas.put("subscription.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/subscription.xsd")));
        schemas.put("groups.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/groups.xsd")));
        schemas.put("group.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/group.xsd")));
        schemas.put("groupAnnc.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/groupAnnc.xsd")));
        schemas.put("attachedDevices.xsd", schemaFactory.newSchema(
                FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/attachedDevices.xsd")));
        schemas.put("mgmtObjs.xsd", schemaFactory
                .newSchema(FrameworkUtil.getBundle(XmlValidator.class).getResource(xsdPath + "/mgmtObjs.xsd")));
    } catch (SAXException e) {
        LOGGER.error("Error reading XSD shemas", e);

    }
}

From source file:org.eclipse.smila.connectivity.framework.schema.internal.JaxbPluginContext.java

/**
 * Creates the validating unmarshaller.//  ww w. ja va2  s .c  o m
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 * @throws SchemaNotFoundException
 *           the index order schema not found exception
 */
public Unmarshaller createValidatingUnmarshaller() throws JAXBException, SchemaNotFoundException {
    initilize();
    assertNotNull(_context);
    final Unmarshaller unmarshaller = _context.createUnmarshaller();
    final SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    try {
        sf.setResourceResolver(new XSDContextURIResolver(sf.getResourceResolver()));
        final javax.xml.validation.Schema schema = sf
                .newSchema(Platform.getBundle(_id).getEntry(_plugIn.getSchemaLocation()));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(final ValidationEvent ve) {
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    final ValidationEventLocator vel = ve.getLocator();
                    _log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                    return false;
                }
                return true;
            }
        });
    } catch (final org.xml.sax.SAXException se) {
        throw new SchemaRuntimeException("Unable to validate due to following error.", se);
    }
    return unmarshaller;
}