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:de.fhg.iais.model.aip.util.XmlUtilsTest.java

private static Document parseAndValidate(String xml, URL xsd) {
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;//from  w w  w .j  av  a2  s  .c  om
    try {
        schema = factory.newSchema(xsd);
    } catch (final SAXException e) {
        throw new DbcException(e);
    }

    //        final Document xmlDocument = XmlUtils.parse(xml);
    final Document xmlDocument = XmlProcessor.buildDocumentFrom(xml);
    final Validator validator = schema.newValidator();
    try {
        validator.validate(new JDOMSource(xmlDocument));
        return xmlDocument;
    } catch (final SAXException e) {
        throw new DbcException(e);
    } catch (final IOException e) {
        throw new DbcException(e);
    }
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml// www. j  ava  2s .c o m
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:main.java.refinement_class.Useful.java

public static Object unmashal2(String schema_file, String xml_file, Class c) {
    Object obj = null;/* w  w  w . ja va  2 s. com*/
    try {

        // create a JAXBContext capable of handling classes generated into
        // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

        JAXBContext jc = JAXBContext.newInstance(c);

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file));

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error(se.toString());
        }

        obj = u.unmarshal(new File(xml_file));

        // even though document was determined to be invalid unmarshalling,
        // marshal out result.
        //           System.out.println("");
        //         System.out.println("Still able to marshal invalid document");
        //       javax.xml.bind.Marshaller m = jc.createMarshaller();
        // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
        //     m.marshal(poe, System.out);
    } catch (UnmarshalException ue) {
        // The JAXB specification does not mandate how the JAXB provider
        // must behave when attempting to unmarshal invalid XML data.
        // those cases, the JAXB provider is allowed to terminate the
        // call to unmarshal with an UnmarshalException.
        System.out.println("Caught UnmarshalException");
    } catch (JAXBException je) {
        je.printStackTrace();
        LOG.error(je.toString());
    }

    return obj;
}

From source file:org.n52.sos.service.it.SosITBase.java

/**
 * Returns a javax.xml.validation Validator that validates xml documents
 * against their internally defined schemas. Constructs the validator if
 * necessary.//from ww  w.jav a  2  s  .  c om
 * 
 * @return xmlValidator
 * @throws SAXException
 */
protected Validator getXmlValidator() throws SAXException {
    if (xmlValidator == null) {
        xmlValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema().newValidator();
    }
    return xmlValidator;
}

From source file:com.azaptree.services.spring.application.config.SpringApplicationServiceConfig.java

private SpringApplicationService parse(final InputStream xml) throws JAXBException {
    Assert.notNull(xml);//from  ww  w.j a  v a  2  s .  c o  m
    final JAXBContext jc = JAXBContext.newInstance(SpringApplicationService.class);
    final Unmarshaller u = jc.createUnmarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
    generateSchema(bos);
    try {
        final SpringApplicationService springApplicationService = (SpringApplicationService) u.unmarshal(xml);
        final Schema schema = schemaFactory
                .newSchema(new StreamSource(new ByteArrayInputStream(bos.toByteArray())));
        final Validator validator = schema.newValidator();
        validator.validate(new JAXBSource(jc, springApplicationService));
        return springApplicationService;
    } catch (SAXException | IOException e) {
        throw new IllegalArgumentException(
                "Failed to parse XML. The XML must conform to the following schema:\n" + bos, e);
    }
}

From source file:InlineSchemaValidator.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();// ww  w.j a  v  a 2s .  c om
        System.exit(1);
    }

    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;

    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: xpath expressions for schemas
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: xpath expressions for instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-nm")) {
                String prefix;
                String uri;
                while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
                        && !(uri = argv[i + 2]).startsWith("-")) {
                    if (prefixMappings == null) {
                        prefixMappings = new HashMap();
                        uriMappings = new HashMap();
                    }
                    prefixMappings.put(prefix, uri);
                    HashSet prefixes = (HashSet) uriMappings.get(uri);
                    if (prefixes == null) {
                        prefixes = new HashSet();
                        uriMappings.put(uri, prefixes);
                    }
                    prefixes.add(prefix);
                    i += 2;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    try {
        // Create new instance of inline schema validator.
        InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings);

        // Parse document containing schemas and validation roots
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(inlineSchemaValidator);
        Document doc = db.parse(docURI);

        // Create XPath factory for selecting schema and validation roots
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setNamespaceContext(inlineSchemaValidator);

        // Select schema roots from the DOM
        NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
        for (int i = 0; i < schemaNodes.length; ++i) {
            XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i));
            schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
        }

        // Select validation roots from the DOM
        NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
        for (int i = 0; i < instanceNodes.length; ++i) {
            XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i));
            instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
        }

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(inlineSchemaValidator);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        {
            DOMSource[] sources;
            int size = 0;
            for (int i = 0; i < schemaNodes.length; ++i) {
                size += schemaNodes[i].getLength();
            }
            sources = new DOMSource[size];
            if (size == 0) {
                schema = factory.newSchema();
            } else {
                int count = 0;
                for (int i = 0; i < schemaNodes.length; ++i) {
                    NodeList nodeList = schemaNodes[i];
                    int nodeListLength = nodeList.getLength();
                    for (int j = 0; j < nodeListLength; ++j) {
                        sources[count++] = new DOMSource(nodeList.item(j));
                    }
                }
                schema = factory.newSchema(sources);
            }
        }

        // Setup validator and input source.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(inlineSchemaValidator);

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents
        for (int i = 0; i < instanceNodes.length; ++i) {
            NodeList nodeList = instanceNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
                DOMSource source = new DOMSource(nodeList.item(j));
                source.setSystemId(docURI);
                inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:com.jtstand.swing.Main.java

public Main(String[] args) {
    //BasicConfigurator.configure();

    options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("version", false, "print the version information and exit");
    options.addOption("s", true, "station host name");
    options.addOption("t", true, "title text");
    options.addOption("r", true, "revision number");
    options.addOption("v", true, "version");
    options.addOption("x", true, "schema file location");

    CommandLineParser parser = new PosixParser();
    try {//from   w  w  w  . j  a v  a  2  s  . c  o m
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jtstand", options);
            System.exit(0);
        } else if (cmd.hasOption("version")) {
            printVersion();
            System.exit(0);
        } else {
            if (cmd.getArgs() != null && cmd.getArgs().length > 0) {
                if (cmd.getArgs().length == 1) {
                    projectLocation = cmd.getArgs()[0];
                } else {
                    log.error("Only one argument is expected; the project location!");
                    log.error("Received arguments:");
                    for (int i = 0; i < cmd.getArgs().length; i++) {
                        log.error(cmd.getArgs()[i]);
                    }
                }
            }
            if (cmd.hasOption("s")) {
                station = cmd.getOptionValue("s");
            }
            if (cmd.hasOption("r")) {
                revision = Integer.parseInt(cmd.getOptionValue("r"));
            }
            if (cmd.hasOption("v")) {
                version = cmd.getOptionValue("v");
            }
            if (cmd.hasOption("t")) {
                title = cmd.getOptionValue("t");
            }
            if (cmd.hasOption("x")) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                String schemaLocation = cmd.getOptionValue("x");
                File schemaFile = new File(schemaLocation);
                if (schemaFile.isFile()) {
                    try {
                        TestProject.setSchema(schemaFactory.newSchema(schemaFile));
                    } catch (SAXException ex) {
                        log.fatal("Exception", ex);
                        javax.swing.JOptionPane.showMessageDialog(null,
                                "Schema file is invalid!\nPress OK to exit.", "Error",
                                javax.swing.JOptionPane.ERROR_MESSAGE);
                        System.exit(-1);
                    }
                } else {
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Schema file cannot be opened!\nPress OK to continue.", "Warning",
                            javax.swing.JOptionPane.WARNING_MESSAGE);
                }
            }
            startProject();
        }
    } catch (ParseException e) {
        log.fatal("Parsing failed" + e);
        System.exit(-1);
    }
}

From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;//w  w  w  .  j  ava  2 s .c  o  m
    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);

        // 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(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$
                        + "]");
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                //   Result field is missing !
                logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()));
                        if (!xsdfile.exists()) {
                            logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    Messages.getString("XsdValidator.Exception.XSDFileNotExists"));
                        }

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

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(Messages.getString("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(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$
                                meta.getXSDDefinedField())); //$NON-NLS-2$
                        throw new KettleStepException(Messages.getString(
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    boolean sendToErrorRow = false;
    String errorMessage = null;

    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);
            File XSDFile = new File(KettleVFS.getFilename(xsdfile));

            //   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(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // Create XSD schema
            Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile);

            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();
            logError("SAX Exception : " + ex);
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } finally {
            try {
                if (xsdfile != null)
                    xsdfile.close();

            } catch (IOException e) {
            }
        }

        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(
                    Messages.getString("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) {
        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(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}

From source file:eu.planets_project.tb.gui.backing.exp.utils.ExpTypeWeeUtils.java

private void checkValidXMLConfig(InputStream xmlWFConfig) throws Exception {
    InputStream bis = getClass().getClassLoader().getResourceAsStream("planets_wdt.xsd");
    try {/*from   w w  w .j  av a  2s. co  m*/
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(bis));
        Validator validator = schema.newValidator();
        // Validate file against schema
        XMLOutputter outputter = new XMLOutputter();
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(xmlWFConfig);
        validator.validate(new StreamSource(new StringReader(outputter.outputString(doc.getRootElement()))));
    } catch (Exception e) {
        String err = "The provided xmlWFConfig is not valid against the currently used planets_wdt_xsd schema";
        log.debug(err, e);
        throw new Exception(err, e);
    } finally {
        bis.close();
    }
}