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:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

private static Object validate(final Unmarshaller unmarshaller,
        final ValidationEventHandler validationEventHandler, final Reader reader,
        final boolean includeMetaDataSchema) throws JAXBException, SAXException, IOException {

    Object jaxbObject = null;/*from   w  w w .  j  a  v  a  2s .co m*/
    try {
        // Set the schema for the unmarshaller
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(getSchemaSources(includeMetaDataSchema).toArray(new Source[] {}));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(validationEventHandler);

        // Unmarshal and validate
        jaxbObject = unmarshaller.unmarshal(reader);
    } catch (UnmarshalException ue) {
        // Swallow the exception. The ValidationEventHandler attached to the unmarshaller will
        // contain the validation events
        logger.info(ue);
    }

    return jaxbObject;
}

From source file:eu.planets_project.pp.plato.evaluation.evaluators.ExperimentEvaluator.java

private String evaluateLogging(String logOutput) {
    if ((logOutput == null) || "".equals(logOutput)) {
        return "none";
    } else {/*from  ww w  . j  a v a  2 s .com*/
        String result = "text";

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = factory.newSchema();
            Validator validator = schema.newValidator();

            validator.validate(new StreamSource(new StringReader(logOutput)));

            // ok, the log is well-formed XML
            result = "XML";
        } catch (SAXException e) {
            // no xml - this is ok
        } catch (IOException e) {
            log.error("logoutput-evaluator is not properly configured: ", e);
        }

        return result;
    }
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the export study response./*from w w w . ja  v a2 s .  c o  m*/
 *
 * @param study the study
 * @return the sOAP message
 * @throws SOAPException the sOAP exception
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private SOAPMessage createExportStudyResponse(Study study)
        throws SOAPException, XMLUtilityException, ParserConfigurationException, SAXException, IOException {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage response = mf.createMessage();
    SOAPBody body = response.getSOAPBody();
    SOAPElement exportStudyResponse = body.addChildElement(new QName(SERVICE_NS, "ExportStudyResponse"));
    String xml = marshaller.toXML(study);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(XmlMarshaller.class.getResource(C3PR_DOMAIN_XSD_URL)));
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml));
    Element studyEl = (Element) doc.getFirstChild();
    exportStudyResponse.appendChild(body.getOwnerDocument().importNode(studyEl, true));
    response.saveChanges();
    return response;
}

From source file:csiro.pidsvc.mappingstore.Manager.java

/**************************************************************************
 *  Generic processing methods.//from  ww w. ja  v a2s .  c  o  m
 */

protected void validateRequest(String inputData, String xmlSchemaResourcePath)
        throws IOException, ValidationException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setResourceResolver(new LSResourceResolver() {
            @Override
            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                return new XsdSchemaResolver(type, namespaceURI, publicId, systemId, baseURI);
            }
        });

        Schema schema = schemaFactory
                .newSchema(new StreamSource(getClass().getResourceAsStream(xmlSchemaResourcePath)));
        Validator validator = schema.newValidator();
        _logger.trace("Validating XML Schema.");
        validator.validate(new StreamSource(new StringReader(inputData)));
    } catch (SAXException ex) {
        _logger.debug("Unknown format.", ex);
        throw new ValidationException("Unknown format.", ex);
    }
}

From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public Schema loadSchema(String name) {
    Schema schema = null;//w ww. j a  v a  2 s  .  c o  m
    try {
        String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        SchemaFactory factory = SchemaFactory.newInstance(language);
        schema = factory.newSchema(new File(name));
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return schema;
}

From source file:io.fabric8.camel.tooling.util.CamelNamespaces.java

private static void loadSchemas(SchemaFinder loader) throws SAXException, IOException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    XsdDetails[] xsds = new XsdDetails[] {
            new XsdDetails("camel-spring.xsd", "http://camel.apache.org/schema/spring/camel-spring.xsd",
                    CamelEndpointFactoryBean.class),
            new XsdDetails("camel-blueprint.xsd",
                    "http://camel.apache.org/schema/blueprint/camel-blueprint.xsd",
                    org.apache.camel.blueprint.CamelEndpointFactoryBean.class) };

    List<Source> sources = new ArrayList<Source>(xsds.length);

    for (XsdDetails xsdd : xsds) {
        URL url = loader.findSchema(xsdd);
        if (url != null) {
            sources.add(new StreamSource(url.openStream(), xsdd.getUri()));
        } else {//from  w  ww.j a  v a 2s  . c  o m
            System.out.println("Warning could not find local resource " + xsdd.getPath() + " on classpath");
            sources.add(new StreamSource(xsdd.getUri()));
        }
    }

    _schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
}

From source file:org.psikeds.knowledgebase.xml.impl.XSDValidator.java

/**
 * Validate XML against specified XSD schmema.<br>
 * <b>Note:</b> The XML source/stream will not be closed. This must be
 * invoked by the caller afterwards!<br>
 * //  w  ww .  j  a va2 s.  c om
 * @param xsd
 *          Source for XSD-schema that will be used to validate the XML
 * @param xml
 *          Source for XML
 * @throws SAXException
 *           if XML is not valid against XSD
 * @throws IOException
 */
public static void validate(final Source xsd, final Source xml) throws SAXException, IOException {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(xsd);
    final Validator validator = schema.newValidator();
    validator.validate(xml);
}

From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;/*w w  w  .j  a v  a 2  s.  co  m*/
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}

From source file:com.threeglav.sh.bauk.main.StreamHorizonEngine.java

private static final BaukConfiguration findConfiguration() {
    LOG.info(//from  ww  w.  j  a v a2 s . c o  m
            "Trying to find configuration file. First if specified as {} system property and then as {} in classpath",
            CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
    final String configFile = System.getProperty(CONFIG_FILE_PROP_NAME);
    InputStream is = null;
    if (StringUtil.isEmpty(configFile)) {
        LOG.info(
                "Was not able to find system property {}. Trying to find default configuration {} in classpath",
                CONFIG_FILE_PROP_NAME, DEFAULT_CONFIG_FILE_NAME);
        is = StreamHorizonEngine.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG_FILE_NAME);
        if (is == null) {
            LOG.error("Was not able to find file {} in the classpath. Unable to start application",
                    DEFAULT_CONFIG_FILE_NAME);
            return null;
        }
        LOG.info("Found configuration file {} in classpath", DEFAULT_CONFIG_FILE_NAME);
    } else {
        LOG.info("Found system property {}={}. Will try to load it as configuration...", CONFIG_FILE_PROP_NAME,
                configFile);
        final File cFile = new File(configFile);
        try {
            if (cFile.exists() && cFile.isFile()) {
                LOG.debug("Loading config file [{}] from file system", configFile);
                is = new FileInputStream(configFile);
            } else {
                LOG.debug("Loading config file [{}] from classpath", configFile);
                is = StreamHorizonEngine.class.getClass().getResourceAsStream(configFile);
            }
            LOG.info("Successfully found configuration [{}] on file system", configFile);
        } catch (final FileNotFoundException fnfe) {
            LOG.error("Was not able to find file {}. Use full, absolute path.", configFile);
            return null;
        }
    }
    if (is == null) {
        return null;
    }
    try {
        LOG.debug("Trying to load configuration from xml file");
        final JAXBContext jaxbContext = JAXBContext.newInstance(BaukConfiguration.class);
        final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory
                .newSchema(StreamHorizonEngine.class.getResource("/bauk_config.xsd"));
        jaxbUnmarshaller.setSchema(schema);
        final BaukConfiguration config = (BaukConfiguration) jaxbUnmarshaller.unmarshal(is);
        LOG.info("Successfully loaded configuration");
        return config;
    } catch (final Exception exc) {
        LOG.error("Exception while loading configuration", exc);
        exc.printStackTrace();
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.denimgroup.threadfix.importer.impl.upload.SSVLChannelImporter.java

@Nonnull
@Override//  w w w  .ja va 2  s .co m
public ScanCheckResultBean checkFile() {

    boolean valid = false;
    String[] schemaList = new String[] { "ssvl.xsd", "ssvl_v0.3.xsd" };

    for (String schemaFilePath : schemaList) {

        try {
            URL schemaFile = ResourceUtils.getResourceAsUrl(schemaFilePath);

            if (schemaFile == null) {
                throw new IllegalStateException("ssvl.xsd file not available from ClassLoader. Fix that.");
            }

            if (inputFileName == null) {
                throw new IllegalStateException("inputFileName was null, unable to load scan file.");
            }

            Source xmlFile = new StreamSource(new File(inputFileName));
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);

            valid = true;
            log.info(xmlFile.getSystemId() + " is valid");
            break;

        } catch (MalformedURLException e) {
            log.error("Code contained an incorrect path to the XSD file.", e);
        } catch (SAXException e) {
            log.warn("SAX Exception encountered, ", e);
        } catch (IOException e) {
            log.warn("IOException encountered, ", e);
        }
    }

    if (valid) {
        return testSAXInput(new SSVLChannelSAXValidator());
    } else {
        return new ScanCheckResultBean(ScanImportStatus.FAILED_XSD);
    }
}