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.opennms.core.xml.JaxbUtils.java

private static Schema getValidatorFor(final Class<?> clazz) {
    LOG.trace("finding XSD for class {}", clazz);

    if (m_schemas.containsKey(clazz)) {
        return m_schemas.get(clazz);
    }//  w ww  . j  ava 2s.  com

    final List<Source> sources = new ArrayList<Source>();
    final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    for (final String schemaFileName : getSchemaFilesFor(clazz)) {
        InputStream schemaInputStream = null;
        try {
            if (schemaInputStream == null) {
                final File schemaFile = new File(
                        System.getProperty("opennms.home") + "/share/xsds/" + schemaFileName);
                if (schemaFile.exists()) {
                    LOG.trace("Found schema file {} related to {}", schemaFile, clazz);
                    schemaInputStream = new FileInputStream(schemaFile);
                }
                ;
            }
            if (schemaInputStream == null) {
                final File schemaFile = new File("target/xsds/" + schemaFileName);
                if (schemaFile.exists()) {
                    LOG.trace("Found schema file {} related to {}", schemaFile, clazz);
                    schemaInputStream = new FileInputStream(schemaFile);
                }
                ;
            }
            if (schemaInputStream == null) {
                final URL schemaResource = Thread.currentThread().getContextClassLoader()
                        .getResource("xsds/" + schemaFileName);
                if (schemaResource == null) {
                    LOG.debug("Unable to load resource xsds/{} from the classpath.", schemaFileName);
                } else {
                    LOG.trace("Found schema resource {} related to {}", schemaResource, clazz);
                    schemaInputStream = schemaResource.openStream();
                }
            }
            if (schemaInputStream == null) {
                LOG.trace("Did not find a suitable XSD.  Skipping.");
                continue;
            } else {
                sources.add(new StreamSource(schemaInputStream));
            }
        } catch (final Throwable t) {
            LOG.warn("an error occurred while attempting to load {} for validation", schemaFileName);
            continue;
        }
    }

    if (sources.size() == 0) {
        LOG.debug("No schema files found for validating {}", clazz);
        return null;
    }

    LOG.trace("Schema sources: {}", sources);

    try {
        final Schema schema = factory.newSchema(sources.toArray(EMPTY_SOURCE_LIST));
        m_schemas.put(clazz, schema);
        return schema;
    } catch (final SAXException e) {
        LOG.warn("an error occurred while attempting to load schema validation files for class {}", clazz, e);
        return null;
    }
}

From source file:org.openrepose.commons.config.parser.jaxb.UnmarshallerPoolableObjectFactory.java

@Override
public UnmarshallerValidator makeObject() {
    try {//  w  w w  .  j a  v a2s.co  m
        UnmarshallerValidator uv = new UnmarshallerValidator(context);
        //TODO: refactor this to either use two different classes that extend an Unmarshaller...
        if (xsdStreamSource != null) {
            //TODO: this might need to have a classloader
            SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
            factory.setFeature("http://apache.org/xml/features/validation/cta-full-xpath-checking", true);
            Schema schema = factory.newSchema(xsdStreamSource);
            //Setting the schema after the object creation is kind of gross
            uv.setSchema(schema);
        }
        return uv;
    } catch (ParserConfigurationException pce) {
        throw new ResourceConstructionException("Failed to configure DOM parser.", pce);
    } catch (JAXBException jaxbe) {
        throw new ResourceConstructionException("Failed to construct JAXB unmarshaller.", jaxbe);
    } catch (SAXException ex) {
        LOG.error("Error validating XML file", ex);
    }
    return null;
}

From source file:org.openrepose.filters.translation.httpx.HttpxMarshallerUtility.java

private static Schema getSchemaSource() {
    SchemaFactory factory = SchemaFactory.newInstance(XML_SCHEMA);
    InputStream inputStream = HttpxMarshaller.class.getResourceAsStream(HTTPX_SCHEMA);
    URL inputURL = HttpxMarshaller.class.getResource(HTTPX_SCHEMA);
    Source schemaSource = new StreamSource(inputStream, inputURL.toExternalForm());
    try {//from  w  w  w. j  av a  2 s .c om
        return factory.newSchema(schemaSource);
    } catch (SAXException ex) {
        throw new HttpxException("Unable to load HTTPX schema", ex);
    }
}

From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java

private void validateAgainstXSD(InputStream xml, InputStream xsd) throws ValidationException {
    try {/*from w  w w  .j a va2 s  .  c om*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));

    } catch (Exception ex) {
        throw new ValidationException("failed", "Failed against schema. Error message:" + ex.getMessage());
    }
}

From source file:org.orcid.core.cli.ManageClientGroup.java

private Validator createValidator() {
    try {/* w  w  w  .  jav a  2 s.c  o  m*/
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema = factory.newSchema(getClass().getResource("/orcid-client-group-1.3.xsd"));
        return schema.newValidator();
    } catch (SAXException e) {
        throw new RuntimeException("Error reading ORCID client group schema", e);
    }
}

From source file:org.orcid.core.manager.impl.ValidationManagerImpl.java

private void initSchema() {
    if (schema == null) {
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        try {// w w w .  j a  v a  2  s . co  m
            schema = factory
                    .newSchema(ValidateOrcidMessage.class.getResource("/orcid-message-" + version + ".xsd"));
        } catch (SAXException e) {
            handleError("Error initializing schema", e);
        }
    }
}

From source file:org.oscarehr.hospitalReportManager.HRMReportParser.java

public static HRMReport parseReport(String hrmReportFileLocation) {

    String fileData = null;/*from  w w  w .  j a  v  a2  s. c o m*/
    if (hrmReportFileLocation != null) {
        try {
            //a lot of the parsers need to refer to a file and even when they provide functions like parse(String text)
            //it will not parse the same way because it will treat the text as a URL
            //so we take the lab and store them temporarily in a random filename in /tmp/oscar-sftp/
            File tmpXMLholder = new File(hrmReportFileLocation);

            if (tmpXMLholder.exists())
                fileData = FileUtils.getStringFromFile(tmpXMLholder);
            // Parse an XML document into a DOM tree.
            DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            // Create a SchemaFactory capable of understanding WXS schemas.

            //SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");//XMLConstants.W3C_XML_SCHEMA_NS_URI);
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // Load a WXS schema, represented by a Schema instance.
            Source schemaFile = new StreamSource(
                    new File(SFTPConnector.OMD_directory + "report_manager_cds.xsd"));
            Schema schema = factory.newSchema(schemaFile);

            JAXBContext jc = JAXBContext.newInstance("org.oscarehr.hospitalReportManager.xsd");
            Unmarshaller u = jc.createUnmarshaller();
            root = (OmdCds) u.unmarshal(tmpXMLholder);

            tmpXMLholder = null;

        } catch (SAXException e) {
            logger.error("SAX ERROR PARSING XML " + e);
        } catch (ParserConfigurationException e) {
            logger.error("PARSER ERROR PARSING XML " + e);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            logger.error("error", e);
        }

        if (root != null && hrmReportFileLocation != null && fileData != null)
            return new HRMReport(root, hrmReportFileLocation, fileData);
    }

    return null;
}

From source file:org.pentaho.di.job.entries.xsdvalidator.JobEntryXSDValidator.java

public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);//  w  w  w .  j a v a2 s. c om

    String realxmlfilename = getRealxmlfilename();
    String realxsdfilename = getRealxsdfilename();

    FileObject xmlfile = null;
    FileObject xsdfile = null;

    try {

        if (xmlfilename != null && xsdfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename, this);
            xsdfile = KettleVFS.getFileObject(realxsdfilename, this);

            if (xmlfile.exists() && xsdfile.exists()) {

                SchemaFactory factorytXSDValidator_1 = SchemaFactory
                        .newInstance("http://www.w3.org/2001/XMLSchema");

                // Get XSD File
                File XSDFile = new File(KettleVFS.getFilename(xsdfile));
                Schema SchematXSD = factorytXSDValidator_1.newSchema(XSDFile);

                Validator XSDValidator = SchematXSD.newValidator();

                // Get XML File
                File xmlfiletXSDValidator_1 = new File(KettleVFS.getFilename(xmlfile));

                Source sourcetXSDValidator_1 = new StreamSource(xmlfiletXSDValidator_1);

                XSDValidator.validate(sourcetXSDValidator_1);

                // Everything is OK
                result.setResult(true);

            } else {

                if (!xmlfile.exists()) {
                    logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist1.Label")
                            + realxmlfilename
                            + BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                if (!xsdfile.exists()) {
                    logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist1.Label")
                            + realxsdfilename
                            + BaseMessages.getString(PKG, "JobEntryXSDValidator.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    } catch (SAXException ex) {
        logError("Error :" + ex.getMessage());
    } catch (Exception e) {

        logError(BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSDValidator.Label")
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXML1.Label") + realxmlfilename
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXML2.Label")
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSD1.Label") + realxsdfilename
                + BaseMessages.getString(PKG, "JobEntryXSDValidator.ErrorXSD2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null) {
                xmlfile.close();
            }

            if (xsdfile != null) {
                xsdfile.close();
            }

        } catch (IOException e) {
            // Ignore errors
        }
    }

    return result;
}

From source file:org.pentaho.di.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;//from  w w  w .  java  2 s .  com
    data = (XsdValidatorData) sdi;

    Object[] row = getRow();

    if (row == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.outputRowMeta = getInputRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);

        // Check if XML stream is given
        if (meta.getXMLStream() != null) {
            // Try to get XML Field index
            data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
            // Let's check the Field
            if (data.xmlindex < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingField") + "["
                        + meta.getXMLStream() + "]");
                throw new KettleStepException(BaseMessages.getString(PKG,
                        "XsdValidator.Exception.CouldnotFindField", meta.getXMLStream()));
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                // Result field is missing !
                logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorResultFieldMissing"));
                throw new KettleStepException(
                        BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorResultFieldMissing"));
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorXSDFileMissing"));
                    throw new KettleStepException(
                            BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorXSDFileMissing"));
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()),
                                getTransMeta());
                        if (!xsdfile.exists()) {
                            logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFileNotExists"));
                        }

                    } catch (Exception e) {
                        logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.GettingXSDFile"));
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "XsdValidator.Exception.GettingXSDFile"));
                    } finally {
                        try {
                            if (xsdfile != null) {
                                xsdfile.close();
                            }
                        } catch (IOException e) {
                            // Ignore errors
                        }
                    }
                }
            }

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(
                            BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFieldMissing"));
                } else {
                    // Let's check if the XSD field exist
                    // Try to get XML Field index
                    data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());

                    if (data.xsdindex < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingXSDField",
                                meta.getXSDDefinedField()));
                        throw new KettleStepException(BaseMessages.getString(PKG,
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField()));
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XmlStreamFieldMissing"));
            throw new KettleStepException(
                    BaseMessages.getString(PKG, "XsdValidator.Exception.XmlStreamFieldMissing"));
        }
    }

    try {

        // Get the XML field value
        String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex);

        boolean isvalid = false;

        // XSD filename
        String xsdfilename = null;

        if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
            xsdfilename = environmentSubstitute(meta.getXSDFilename());
        } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
            // Get the XSD field value
            xsdfilename = getInputRowMeta().getString(row, data.xsdindex);
        }

        // Get XSD filename
        FileObject xsdfile = null;
        String validationmsg = null;
        try {

            SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            xsdfile = KettleVFS.getFileObject(xsdfilename, getTransMeta());

            // Get XML stream
            Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));

            if (meta.getXMLSourceFile()) {

                // We deal with XML file
                // Get XML File
                File xmlfileValidator = new File(XMLFieldvalue);
                if (!xmlfileValidator.exists()) {
                    logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XMLfileMissing",
                            XMLFieldvalue));
                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "XsdValidator.Exception.XMLfileMissing", XMLFieldvalue));
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // create the schema
            Schema SchematXSD = null;
            if (xsdfile instanceof LocalFile) {
                SchematXSD = factoryXSDValidator.newSchema(new File(KettleVFS.getFilename(xsdfile)));
            } else if (xsdfile instanceof HttpFileObject) {
                SchematXSD = factoryXSDValidator.newSchema(new URL(KettleVFS.getFilename(xsdfile)));
            } else {
                // we should not get here as anything entered in that does not look like
                // a url should be made a FileObject.
                throw new KettleStepException(BaseMessages.getString(PKG,
                        "XsdValidator.Exception.CannotCreateSchema", xsdfile.getClass().getName()));
            }

            if (meta.getXSDSource().equals(meta.NO_NEED)) {
                // ---Some documents specify the schema they expect to be validated against,
                // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
                // ---Schema SchematXSD = factoryXSDValidator.newSchema();
                SchematXSD = factoryXSDValidator.newSchema();
            }

            // Create XSDValidator
            Validator XSDValidator = SchematXSD.newValidator();
            // Validate XML / XSD
            XSDValidator.validate(sourceXML);

            isvalid = true;

        } catch (SAXException ex) {
            validationmsg = ex.getMessage();
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
        } finally {
            try {
                if (xsdfile != null) {
                    xsdfile.close();
                }
            } catch (IOException e) {
                // Ignore errors
            }
        }

        Object[] outputRowData = null;
        Object[] outputRowData2 = null;

        if (meta.getOutputStringField()) {
            // Output type=String
            if (isvalid) {
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlValid()));
            } else {
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlInvalid()));
            }
        } else {
            outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid);
        }

        if (meta.useAddValidationMessage()) {
            outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1,
                    validationmsg);
        } else {
            outputRowData2 = outputRowData;
        }

        if (log.isRowLevel()) {
            logRowlevel(BaseMessages.getString(PKG, "XsdValidator.Log.ReadRow") + " "
                    + getInputRowMeta().getString(row));
        }

        // add new values to the row.
        putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
    } catch (KettleException e) {
        boolean sendToErrorRow = false;
        String errorMessage = null;

        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        }

        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
        } else {
            logError(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}

From source file:org.perfclipse.core.scenario.ScenarioManager.java

/**
 * Creates {@link ScenarioModel} object representation of the scenario
 * specified in XML file at scenarioURL parameter.
 * @param scenarioURL - URL to scenario XML definition
 * @return {@link ScenarioModel} of given XML definition
 * @throws ScenarioException//w w w . java 2  s . c om
 */
public ScenarioModel createModel(URL scenarioURL) throws ScenarioException {

    org.perfcake.model.Scenario model;

    if (scenarioURL == null) {
        log.error("URL to scenario is null");
        throw new IllegalArgumentException("URL to scenario is null.");
    }

    try {

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = SchemaScanner.getSchema();
        Schema schema = schemaFactory.newSchema(schemaUrl);

        JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        model = (org.perfcake.model.Scenario) unmarshaller.unmarshal(scenarioURL);
        return new ScenarioModel(model);
    } catch (JAXBException e) {
        throw new ScenarioException(e);
    } catch (IOException e) {
        throw new ScenarioException(e);
    } catch (SAXException e) {
        throw new ScenarioException(e);
    }

}