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.ojbc.util.xml.XmlUtils.java

/**
  * Validate a document against an IEPD. Note that this does not require the xsi namespace location attributes to be set in the instance.
  * /*from   w  w w  .  j  av a  2 s  .co m*/
  * @param schemaPathList
  *            the paths to all schemas necessary to validate the instance; this is the equivalent of specifying these schemas in an xsi:schemaLocation attribute in the instance
  *                       
  * @param Never_Used_TODO_Remove 
  * 
  *            
  * @param rootSchemaFileName
  *            the name of the document/exchange schema
  * @param d
  *            the document to validate
  * @param iepdResourceResolver
  *            the resource resolver to use
  * @return the document that was validated
  * @throws Exception
  *             if the document is not valid
  */
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver,
        List<String> schemaPathList) throws SAXException, Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(iepdResourceResolver);

    List<Source> sourceList = new ArrayList<Source>();

    for (String schemaPath : schemaPathList) {

        InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath);

        StreamSource schemaStreamSource = new StreamSource(schemaInStream);

        sourceList.add(schemaStreamSource);
    }

    Source[] schemaSourcesArray = sourceList.toArray(new Source[] {});

    try {
        Schema schema = schemaFactory.newSchema(schemaSourcesArray);

        Validator validator = schema.newValidator();

        validator.validate(new DOMSource(d));

    } catch (Exception e) {
        try {
            e.printStackTrace();
            System.err.println("Input document:");
            XmlUtils.printNode(d);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        throw e;
    }
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

public ProcessFileStore(File rootDirectory) {
    this.processDir = rootDirectory;
    if (!rootDirectory.exists() && !rootDirectory.mkdirs()) {
        throw new RuntimeException("Could not make directory " + rootDirectory.getAbsolutePath());
    } else if (!rootDirectory.isDirectory()) {
        throw new IllegalArgumentException("Root directory '" + rootDirectory + "' is not a directory.");
    }//from  w w w.  j  av a  2  s  .c  o m
    try {
        jaxbContext = JAXBContext.newInstance(WorkflowLog.class);
        xmlif = XMLInputFactory.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    try {
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new URL("http://is.tm.tue.nl/research/processmining/WorkflowLog.xsd"));
    } catch (Exception e) {
        LOGGER.warn("Error during creating of Mxml schema. Continue without schema validation.", e);
    }
}

From source file:org.openhab.tools.analysis.checkstyle.EshInfXmlValidationCheck.java

@Override
public void beginProcessing(String charset) {
    ContentReceviedCallback<Schema> callback = new ContentReceviedCallback<Schema>() {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        @Override/*from   w w w .ja  v a  2s .  c  o m*/
        public Schema transform(byte[] content) {
            try {
                InputStream is = new ByteArrayInputStream(content);
                return schemaFactory.newSchema(new StreamSource(is));
            } catch (SAXException e) {
                logger.error("Unable to parse schema ", e);
                return null;
            }
        }
    };

    CachingHttpClient<Schema> cachingClient = new CachingHttpClient<>(callback);

    bindingSchemaFile = getXSD(bindingSchema, cachingClient);
    thingSchemaFile = getXSD(thingSchema, cachingClient);
    configSchemaFile = getXSD(configSchema, cachingClient);

    super.beginProcessing(charset);
}

From source file:org.openmainframe.ade.main.AdeUtilMain.java

protected void validateGood(File file) throws IOException, SAXException, AdeException {
    System.out.println("Starting");

    String fileName_Flowlayout_xsd = Ade.getAde().getConfigProperties().getXsltDir()
            + FLOW_LAYOUT_XSD_File_Name;
    Source schemaFile = new StreamSource(fileName_Flowlayout_xsd);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema mSchema = sf.newSchema(schemaFile);

    System.out.println("Validating " + file.getPath());
    Validator val = mSchema.newValidator();
    FileInputStream fis = new FileInputStream(file);
    StreamSource streamSource = new StreamSource(fis);

    try {/*from w  w w .  j av  a  2 s.  c  om*/
        val.validate(streamSource);
    } catch (SAXParseException e) {
        System.out.println(e);
        throw e;
    }
    System.out.println("SUCCESS!");
}

From source file:org.openmrs.module.radiology.report.template.XsdMrrtReportTemplateValidator.java

/**
 * @see MrrtReportTemplateValidator#validate(String)
 *//*  www.j  a  v  a 2 s.  c om*/
@Override
public void validate(String mrrtTemplate) throws IOException {

    final Document document = Jsoup.parse(mrrtTemplate, "");
    final Elements metatags = document.getElementsByTag("meta");
    ValidationResult validationResult = metaTagsValidationEngine.run(metatags);

    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    final Validator validator;
    try (InputStream in = IOUtils.toInputStream(mrrtTemplate)) {
        schema = factory.newSchema(getSchemaFile());
        validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                log.debug(exception.getMessage(), exception);
                validationResult.addError(exception.getMessage(), "");
            }
        });
        validator.validate(new StreamSource(in));
        validationResult.assertOk();
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
        throw new APIException("radiology.report.template.validation.error", null, e);
    }
}

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

private void validateAgainstXSD(InputStream xml, InputStream xsd) throws ValidationException {
    try {//from w ww.j  a  v  a  2s . c o  m
        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.oscarehr.hospitalReportManager.HRMReportParser.java

public static HRMReport parseReport(String hrmReportFileLocation) {

    String fileData = null;//from   w  w  w  .j a  v a  2 s .  co 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.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;/*from  w  ww. j  a v a 2  s  .  c om*/
    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//ww  w  . j  a  va  2s . com
 */
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);
    }

}

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

/**
 * The createXML method converts scenario model into XML representation 
 * according to PerfCake XML Schema and writes output to output stream out
 * @param model model to be converted//from  w w  w . ja  v  a 2  s .  co m
 * @param out OutputStream to which xml will be written
 * @throws ScenarioException
 */
public void createXML(org.perfcake.model.Scenario model, OutputStream out) throws ScenarioException {
    try {
        JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        //obtain url to schema definition, which is located somewhere in PerfCakeBundle
        URL schemaUrl = SchemaScanner.getSchema();
        Schema schema = schemaFactory.newSchema(schemaUrl);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(schema);

        //add line breaks and indentation into output
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(model, out);
    } catch (JAXBException e) {
        log.error("JAXB error", e);
        throw new ScenarioException("JAXB error", e);
    } catch (MalformedURLException e) {
        log.error("Malformed url", e);
        throw new ScenarioException("Malformed url", e);
    } catch (SAXException e) {
        log.error("Cannot obtain schema definition", e);
        throw new ScenarioException("Cannot obtain schema definition", e);
    } catch (IOException e) {
        log.error("Cannot obtain XML schema file", e);
        throw new ScenarioException("Cannot obtain XML schema file", e);
    }
}