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.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;/*  w  w w.  ja  v a  2  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.ebayopensource.turmeric.tools.errorlibrary.util.ErrorLibraryUtils.java

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

    Document document = null;//from   ww w.  ja va 2 s  .co  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 www .  ja  v  a2s .  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 ww. j ava  2s  .c om
    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.//from ww  w .  j a v  a2s .  com
 * 
 * @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;
}

From source file:org.eclipse.smila.management.jmx.client.helpers.ConfigLoader.java

/**
 * Load.//  w  w w .  ja  va  2 s. c  om
 * 
 * @param is
 *          the is
 * 
 * @return the cmd config type
 * 
 * @throws ConfigurationLoadException
 *           the configuration load exception
 */
public static JmxClientConfigType load(final InputStream is) throws ConfigurationLoadException {
    try {
        final JAXBContext context = JAXBContext.newInstance("org.eclipse.smila.management.jmx.client.config");
        final SchemaFactory schemaFactory = SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory.newSchema(new File("schemas/jmxclient.xsd"));
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(createValidationEventHandler());
        Object result = unmarshaller.unmarshal(is);
        if (result != null) {
            if (result instanceof JAXBElement) {
                result = ((JAXBElement) result).getValue();
            }
        }
        return (JmxClientConfigType) result;
    } catch (final Throwable e) {
        throw new ConfigurationLoadException("Unable to load configuration", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (final Throwable e) {
                ;// nothing
            }
        }
    }
}

From source file:org.eclipse.smila.utils.xml.SchemaUtils.java

/**
 * Load schema./*  ww  w .j  a va  2s.c om*/
 * 
 * @param resourcePath
 *          the schema location
 * @param bundle
 *          the bundle
 * 
 * @return the schema
 * 
 * @throws SAXException
 *           the SAX exception
 */
public static Schema loadSchema(final Bundle bundle, final String resourcePath) throws SAXException {
    // TODO: remove it when DS will work ok
    final ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(SchemaUtils.class.getClassLoader());
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(bundle.getEntry(resourcePath));
    Thread.currentThread().setContextClassLoader(oldCL);
    return schema;
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.DescriptionHelper.java

/**
 * Validates <code>*.wbp-component.xml</code> against its schema.
 */// ww  w . j a va  2s.co  m
public static synchronized void validateComponentDescription(ResourceInfo resource) throws Exception {
    // validate on developers computers
    if (EnvironmentUtils.isTestingTime()) {
        // prepare Schema
        if (m_wbpComponentSchema == null) {
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            InputStream schemaStream = DesignerPlugin.getFile("schema/wbp-component.xsd");
            m_wbpComponentSchema = factory.newSchema(new StreamSource(schemaStream));
        }
        // validate
        InputStream contents = resource.getURL().openStream();
        try {
            Validator validator = m_wbpComponentSchema.newValidator();
            validator.validate(new StreamSource(contents));
        } catch (Throwable e) {
            throw new Exception("Exception during validation " + resource.getURL(), e);
        } finally {
            contents.close();
        }
    }
}

From source file:org.eurekastreams.server.action.validation.gallery.UrlXmlValidator.java

/**
 * Validates xml from given Url returning true if it passes validation, false otherwise.
 *
 * @param inActionContext//w  w  w.j  av a 2 s  . c  o  m
 *            the action context
 * @throws ValidationException
 *             on error
 */
@Override
@SuppressWarnings("unchecked")
public void validate(final ServiceActionContext inActionContext) throws ValidationException {
    InputStream schemaStream = null;
    Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
    String galleryItemUrl = (String) fields.get(URL_KEY);
    try {
        schemaStream = this.getClass().getResourceAsStream(xsdPath);
        log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));

        Validator validator = schema.newValidator();

        // TODO: stuff the input stream into the context for execute()
        InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl);

        validator.validate(new StreamSource(galleryItemInputStream));

        log.debug("Success validating xml at: " + galleryItemUrl);
    } catch (Exception e) {
        log.error("Validation for gadget definition failed.", e);
        ValidationException ve = new ValidationException();
        ve.addError(URL_KEY, "Valid url is required");
        throw ve;
    } finally {
        try {
            if (schemaStream != null) {
                schemaStream.close();
            }
        } catch (IOException ex) {
            log.error("Error closing stream, already closed.", ex);
        }
    }
}

From source file:org.evosuite.continuous.persistency.StorageManager.java

private static Project getProject(File current, InputStream stream) {
    try {/*from  w  ww . j  a v a2s.c om*/
        JAXBContext jaxbContext = JAXBContext.newInstance(Project.class);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(
                new StreamSource(StorageManager.class.getResourceAsStream("/xsd/ctg_project_report.xsd")));
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        return (Project) jaxbUnmarshaller.unmarshal(stream);
    } catch (Exception e) {
        String msg = "Error in reading " + current.getAbsolutePath() + " , " + e;
        logger.error(msg, e);
        throw new RuntimeException(msg);
    }
}