Java Examples for javax.xml.validation.Validator

The following java examples will help you to understand the usage of javax.xml.validation.Validator. These source code samples are taken from different open source projects.

Example 1
Project: metadata-editor-master  File: SchemaValidator.java View source code
@Override
public void validate(Source source) throws ValidatorException, IOException {
    javax.xml.validation.Validator schemaValidator = schema.newValidator();
    schemaValidator.setErrorHandler(new DefaultHandler() {

        @Override
        public void error(SAXParseException ex) throws SAXException {
            throw ex;
        }

        @Override
        public void fatalError(SAXParseException ex) throws SAXException {
            throw ex;
        }

        @Override
        public void warning(SAXParseException ex) throws SAXException {
            return;
        }
    });
    try {
        schemaValidator.validate(source);
    } catch (SAXException ex) {
        throw new ValidatorException(ex);
    }
}
Example 2
Project: voxels-master  File: XmlTools.java View source code
public static boolean validateAgainstXSD(String xml, StreamSource xsd, ErrorHandlerInterface errorHandler) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(xsd);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        return true;
    } catch (Exception ex) {
        errorHandler.handle(ex);
        return false;
    }
}
Example 3
Project: java-aws-mturk-model-master  File: SchemaHelper.java View source code
public static void validate(String schemaName, InputStream input) throws SAXException, IOException {
    InputStream schemaStream = SchemaHelper.class.getResourceAsStream(schemaName);
    StreamSource schemaSource = new StreamSource(schemaStream);
    Schema schema = schemaFactory.newSchema(schemaSource);
    Validator validator = schema.newValidator();
    StreamSource inputSource = new StreamSource(input);
    validator.validate(inputSource);
}
Example 4
Project: jentrata-msh-master  File: SchemaValidator.java View source code
/* (non-Javadoc)
     * @see org.jentrata.validation.Validator#validate(javax.xml.soap.AttachmentPart, java.lang.String)
     */
public void validate(AttachmentPart payload) throws ValidationException {
    Validator validator = xsdScheme.newValidator();
    Source source;
    try {
        source = new StreamSource(payload.getRawContent());
        validator.validate(source);
    } catch (SOAPException e) {
        ValidationProcessor.core.log.error("unable to schema validate payload " + e);
        ValidationProcessor.core.log.debug("", e);
    } catch (SAXException e) {
        throw new ValidationException(e.getMessage(), e);
    } catch (IOException e) {
        ValidationProcessor.core.log.error("unable to schema validate payload " + e);
        ValidationProcessor.core.log.debug("", e);
    }
}
Example 5
Project: junit5-master  File: XmlReportAssertions.java View source code
private static Validator getSchemaValidator() throws SAXException {
    if (schemaValidator == null) {
        URL schemaFile = XmlReportsWritingListener.class.getResource("/jenkins-junit.xsd");
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaValidator = schemaFactory.newSchema(schemaFile).newValidator();
    }
    return schemaValidator;
}
Example 6
Project: xmlunit-master  File: JAXPValidator.java View source code
@Override
public ValidationResult validateInstance(Source s) {
    Schema schema;
    try {
        schema = getSchema();
    } catch (SAXException e) {
        throw new XMLUnitException("The schema is invalid", e);
    }
    ValidationHandler v = new ValidationHandler();
    javax.xml.validation.Validator val = schema.newValidator();
    val.setErrorHandler(v);
    try {
        val.validate(s);
    } catch (SAXParseException e) {
        v.error((SAXParseException) e);
    } catch (SAXException e) {
        throw new XMLUnitException(e);
    } catch (java.io.IOException e) {
        throw new XMLUnitException(e);
    }
    return v.getResult();
}
Example 7
Project: allure1-master  File: AllureModelUtils.java View source code
public static Validator getAllureSchemaValidator() throws SAXException {
    String schemaFileName = AllureConfig.newInstance().getSchemaFileName();
    InputStream schemaFile = ClassLoader.getSystemResourceAsStream(schemaFileName);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new StreamSource(schemaFile));
    return schema.newValidator();
}
Example 8
Project: axis2-java-master  File: ServicePluginUtils.java View source code
/**
	 * Validates the given xml file against the axis2 services schema. 
	 * @return return true if the xml is valid
	 */
public static boolean isServicesXMLValid(String servicesXmlPath) {
    SchemaFactory factory = SchemaFactory.newInstance(ServiceConstants.XML_SCHEMA);
    try {
        String resourcePath = addAnotherNodeToPath(ServiceConstants.RESOURCE_FOLDER, ServiceConstants.SERVICES_XSD_SCHEMA_NAME);
        Schema schema = factory.newSchema(ServiceArchiver.getDefault().getBundle().getEntry(resourcePath));
        Validator validator = schema.newValidator();
        Source source = new StreamSource(new File(servicesXmlPath));
        validator.validate(source);
        return true;
    } catch (SAXException e) {
        logger.debug("Schema addition failed", e);
        return false;
    } catch (IOException e) {
        logger.debug("Schema validation failed", e);
        return false;
    }
}
Example 9
Project: betsy-master  File: PEBLWriterMain.java View source code
public static void validateXml(Path workingDirectory) throws JAXBException, IOException, SAXException {
    Path xsd = Paths.get("pebl/src/main/resources/pebl/pebl.xsd");
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source schemaFile = new StreamSource(xsd.toFile());
    Schema schema = factory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(workingDirectory.resolve("pebl.xml").toFile()));
}
Example 10
Project: Collabinate-master  File: DatabaseResourceTest.java View source code
public static boolean isValidGraphml(String graphMl) {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;
    try {
        schema = factory.newSchema(DatabaseResourceTest.class.getClassLoader().getResource(GRAPHML_SCHEMA_FILE));
    } catch (Exception e) {
        e.printStackTrace();
        return true;
    }
    Validator validator = schema.newValidator();
    // create a source from a string
    Source source = new StreamSource(new StringReader(graphMl));
    // check input
    boolean isValid = true;
    try {
        validator.validate(source);
    } catch (Exception e) {
        e.printStackTrace();
        isValid = false;
    }
    return isValid;
}
Example 11
Project: common-biorepository-model-master  File: CbmDataExtractionTests.java View source code
private static void validateXml(String fileName) throws Exception {
    File schemaFile = new File("CBM.xsd");
    Source xmlFile = new StreamSource(new File(fileName));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {
        validator.validate(xmlFile);
    } catch (SAXException e) {
        String failMsg = "The file downloaded from the CBM node ";
        failMsg += xmlFile.getSystemId() + " is NOT valid";
        failMsg += "Reason: " + e.getLocalizedMessage();
        fail(failMsg);
    }
}
Example 12
Project: dataverse-master  File: XmlValidator.java View source code
public static boolean validateXml(String fileToValidate, String schemaToValidateAgainst) throws IOException, SAXException {
    System.out.print(" before get schema file " + schemaToValidateAgainst);
    StreamSource schemaFile = new StreamSource(new File(schemaToValidateAgainst));
    // StreamSource schemaFile = new StreamSource(new URL(schemaToValidateAgainst).openStream());
    System.out.print(" after get schema file ");
    Source xmlFile = new StreamSource(new File(fileToValidate));
    System.out.print(" after get file to validate ");
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    System.out.print(" after get schema factory ");
    Schema schema = schemaFactory.newSchema(schemaFile);
    System.out.print(" after instantiate Schema ");
    Validator validator = schema.newValidator();
    System.out.print(" after instantiate Validator ");
    try {
        validator.validate(xmlFile);
        logger.info(xmlFile.getSystemId() + " is valid");
        return true;
    } catch (SAXException ex) {
        System.out.print(ex.getMessage());
        System.out.print(ex.getLocalizedMessage());
        logger.info(xmlFile.getSystemId() + " is not valid: " + ex.getLocalizedMessage());
        return false;
    }
}
Example 13
Project: dbmigrate-master  File: XmlValidator.java View source code
private static boolean validateSchema(Source source, String xsdPath) throws ParseException {
    try {
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File(xsdPath);
        Schema schema;
        schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
        validator.validate(source);
        return true;
    } catch (IOException e) {
        LoggerFactory.getLogger().log(e.getMessage(), Level.Error);
        throw new ParseException();
    } catch (SAXException e) {
        LoggerFactory.getLogger().log(e.getMessage(), Level.Error);
        throw new ParseException();
    }
}
Example 14
Project: droolsjbpm-knowledge-master  File: KModuleXSDTest.java View source code
@Test
public void loadAndValidate() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    URL url = getClass().getClassLoader().getResource("org/kie/api/kmodule.xsd");
    assertNotNull(url);
    Schema schema = null;
    try {
        schema = factory.newSchema(url);
    } catch (SAXParseException ex) {
        fail("Unable to load XSD: " + ex.getMessage() + ":" + ex.getLineNumber() + ":" + ex.getColumnNumber());
    }
    assertNotNull(schema);
    Validator validator = schema.newValidator();
    Source source = new StreamSource(KModuleXSDTest.class.getResource("kmod1.xml").openStream());
    assertNotNull(source);
    try {
        validator.validate(source);
    } catch (SAXException ex) {
        fail("XML should be valid: " + ex.getMessage());
    }
}
Example 15
Project: eclipse.platform.ua-master  File: SchemaValidator.java View source code
public static String testXMLSchema(String uri, String schemaFile) {
    //$NON-NLS-1$
    String msg = "";
    try {
        //$NON-NLS-1$
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema = null;
        if (schemaFile.startsWith("http") || schemaFile.startsWith("ftp"))
            schema = factory.newSchema(new URL(schemaFile));
        else
            schema = factory.newSchema(new File(schemaFile));
        Validator validator = schema.newValidator();
        Source source = new StreamSource(uri);
        try {
            validator.validate(source);
            //$NON-NLS-1$
            msg = "valid";
        } catch (SAXException ex) {
            msg = "not valid. Details: " + ex.getMessage();
        }
    } catch (Exception e) {
        msg = "Exception e: " + e;
    }
    return msg;
}
Example 16
Project: geogebra-master  File: XmlTest.java View source code
public static void testCurrentXML(AppDNoGui app) {
    String xml = "";
    try {
        URL schemaFile = new URL("http://static.geogebra.org/ggb.xsd");
        xml = app.getXML();
        Source xmlFile = new StreamSource(new StringReader(xml));
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
    } catch (SAXParseException se) {
        int l = se.getLineNumber();
        for (int i = l - 2; i < l + 3; i++) {
            System.out.println(xml.split("\\n")[i]);
        }
        Assert.assertNull(se.getLocalizedMessage(), se);
    } catch (Exception e) {
        Assert.assertNull(e.getLocalizedMessage(), e);
    }
}
Example 17
Project: lilyproject-master  File: SchemaTest.java View source code
@Test
public void test() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL url = getClass().getClassLoader().getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd");
    Schema schema = factory.newSchema(url);
    Validator validator = schema.newValidator();
    InputStream is = getClass().getClassLoader().getResourceAsStream("org/lilyproject/indexer/engine/test/indexerconf1.xml");
    validator.validate(new StreamSource(is));
}
Example 18
Project: oas-master  File: AccessControlSchemaXmlValidationTest.java View source code
/**
   * Tests if the access-control-schema.xml is valid.
   *
   * @throws ParserConfigurationException If a DocumentBuilder cannot be created which satisfies the configuration
   *         requested.
   * @throws IOException If any IO errors occur.
   * @throws SAXException If an error occurs during the validation.
   */
@Test
public void validateAccessControllSchema() throws ParserConfigurationException, SAXException, IOException {
    // parse an XML document into a DOM tree
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    String xmlPath = getClass().getResource("/config/app/security/access-control-schema.xml").getPath();
    Document document = parser.parse(new File(xmlPath));
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // load a WXS schema, represented by a Schema instance
    URL schemaPath = getClass().getResource("/io/oasp/module/security/access-control-schema.xsd");
    Schema schema = factory.newSchema(schemaPath);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    validator.validate(new DOMSource(document));
}
Example 19
Project: oasp4j-master  File: AccessControlSchemaXmlValidationTest.java View source code
/**
   * Tests if the access-control-schema.xml is valid.
   *
   * @throws ParserConfigurationException If a DocumentBuilder cannot be created which satisfies the configuration
   *         requested.
   * @throws IOException If any IO errors occur.
   * @throws SAXException If an error occurs during the validation.
   */
@Test
public void validateAccessControllSchema() throws ParserConfigurationException, SAXException, IOException {
    // parse an XML document into a DOM tree
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    String xmlPath = getClass().getResource("/config/app/security/access-control-schema.xml").getPath();
    Document document = parser.parse(new File(xmlPath));
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // load a WXS schema, represented by a Schema instance
    URL schemaPath = getClass().getResource("/io/oasp/module/security/access-control-schema.xsd");
    Schema schema = factory.newSchema(schemaPath);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    validator.validate(new DOMSource(document));
}
Example 20
Project: ORCID-Source-master  File: ValidateOrcidMessage.java View source code
private static boolean validAgainstSchema(File fileToValidate) {
    Validator validator = createValidator();
    Source source = new StreamSource(fileToValidate);
    try {
        validator.validate(source);
        System.out.println(fileToValidate + " is valid");
        return true;
    } catch (SAXException e) {
        System.out.println(fileToValidate + " is invalid");
        System.out.println(e);
    } catch (IOException e) {
        System.out.println("Unable to read file " + fileToValidate);
    }
    return false;
}
Example 21
Project: ringmud-master  File: DocumentValidator.java View source code
public boolean validate(File file) throws IOException {
    FileInputStream input = new FileInputStream(file);
    StreamSource src = new StreamSource(input);
    errorHandler = new DocumentErrorHandler();
    Validator validator = SCHEMA.newValidator();
    validator.setErrorHandler(errorHandler);
    try {
        validator.validate(src);
        return true;
    } catch (SAXException e) {
        return false;
    }
}
Example 22
Project: StaticPages-master  File: TestXSD.java View source code
public static void main(String[] args) {
    File pageXSD = new File("/home/joseph/NetBeansProjects/StaticPages/src/page.xsd");
    File xml = new File("/home/joseph/NetBeansProjects/StaticPages/src/index.xml");
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schemaFile;
    try {
        schemaFile = schemaFactory.newSchema(pageXSD);
        Validator validator = schemaFile.newValidator();
        validator.validate(new StreamSource(xml));
    } catch (SAXException ex) {
        System.out.println(ex.getLocalizedMessage());
        System.out.println(ex.getMessage());
    } catch (IOException ex) {
        System.out.println("Couldn't read xml file.");
    }
}
Example 23
Project: zendserver-sdk-java-master  File: XmlValidator.java View source code
/**
	 * Validates an xml using a schema xsd file
	 * 
	 * {@link http
	 * ://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi/index.html}
	 * 
	 * @param xsd
	 *            stream
	 * @param xml
	 *            stream
	 * @return true if xml is valid
	 * @throws SAXException
	 * @throws IOException
	 */
public static boolean validateXsd(InputStream xsd, InputStream xml) throws SAXException, IOException {
    // 1. Lookup a factory for the W3C XML Schema language
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    // 2. Compile the schema.
    StreamSource source = new StreamSource(xsd);
    Schema schema = factory.newSchema(source);
    // 3. Get a validator from the schema.
    Validator validator = schema.newValidator();
    // 4. Parse the document you want to check.
    Source source1 = new StreamSource(xml);
    // 5. Check the document
    validator.validate(source1);
    return true;
}
Example 24
Project: acs-master  File: XMLValidator.java View source code
public void run(String[] args) {
    try {
        if (args.length != 2) {
            System.out.println("Incorrect arguments. You need to provide the XML and XSD files.");
            System.exit(3);
        }
        XMLValidator.error = false;
        // define the type of schema - we use W3C:
        String schemaLang = "http://www.w3.org/2001/XMLSchema";
        // get validation driver:
        SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
        // create schema by reading it from an XSD file:
        Schema schema = factory.newSchema(new StreamSource(args[1]));
        Validator validator = schema.newValidator();
        ErrorHandler eh = new XMLErrorHandler(args[0]);
        validator.setErrorHandler(eh);
        // at last perform validation:
        XMLInputFactory xFact = XMLInputFactory.newInstance();
        XMLStreamReader xRead = xFact.createXMLStreamReader(new FileReader(args[0]));
        if (xRead.getVersion() == null) {
            System.err.println(args[0] + ": There is no XML Definition.");
            XMLValidator.error = true;
        } else if (xRead.getCharacterEncodingScheme() == null) {
            System.err.println(args[0] + ": The encoding attribute is not defined in the XML Definition.");
            XMLValidator.error = true;
        } else if (xRead.getCharacterEncodingScheme().compareTo("ISO-8859-1") != 0) {
            System.err.println(args[0] + ": Incorrect encoding type in the XML Definition.");
            XMLValidator.error = true;
        }
        validator.validate(new StreamSource(args[0]));
    } catch (SAXException ex) {
        System.err.println("Fatal Error");
        System.err.println(args[0] + ": " + ex.getMessage());
        XMLValidator.error = true;
    } catch (Exception ex) {
        ex.printStackTrace();
        XMLValidator.error = true;
    }
    if (XMLValidator.error) {
        //System.exit(1); //Error
        //Warning
        System.exit(//Warning
        0);
    } else {
        System.exit(0);
    }
}
Example 25
Project: apifest-master  File: MappingConfigValidator.java View source code
public static boolean validate(File mappingFile) {
    boolean ok = false;
    try {
        if (schema == null) {
            loadSchema();
        }
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(mappingFile));
        ok = true;
    } catch (SAXException ex) {
        log.error("mapping file NOT valid: {}", ex.getMessage());
    } catch (IOException e) {
        log.error("schema file not loaded: {}", e.getMessage());
    }
    return ok;
}
Example 26
Project: AsciidocFX-master  File: DocbookValidator.java View source code
public boolean validateDocbook(String rendered) {
    final boolean validateDocbook = editorConfigBean.getValidateDocbook();
    if (!validateDocbook) {
        return true;
    }
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Path xsdPath = controller.getConfigPath().resolve("docbook-config/xsd/docbook.xsd");
        Schema sch = schemaFactory.newSchema(new StreamSource(xsdPath.toFile()));
        Validator validator = sch.newValidator();
        validator.validate(new StreamSource(new ByteArrayInputStream(rendered.getBytes(Charset.forName("UTF-8")))));
        logger.debug("Docbook successfully validated");
        return true;
    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException pe = (SAXParseException) e;
            int columnNumber = pe.getColumnNumber();
            int lineNumber = pe.getLineNumber();
            Path currentDir = current.currentPath().map(Path::getParent).get();
            Path xmlPath = IOHelper.createTempFile(currentDir, ".xml");
            IOHelper.writeToFile(xmlPath, rendered);
            Platform.runLater(() -> {
                tabService.addTab(xmlPath, () -> {
                    current.currentEditor().call("addAnnotation", (lineNumber - 1), columnNumber, pe.getMessage(), "error");
                });
            });
            logger.error("Please fix Docbook validation error. LineNumber: {}, Column: {}", lineNumber, columnNumber, pe);
        } else {
            logger.error("Problem occured while validating Docbook content", e);
        }
        indikatorService.stopProgressBar();
        return false;
    }
}
Example 27
Project: carbon-platform-integration-master  File: ConfigurationXSDValidatorTest.java View source code
@Test(groups = "context.unit.test", description = "Upload aar service and verify deployment")
public void validateAutomationXml() throws IOException, SAXException {
    boolean validated = false;
    URL schemaFile = validateXsdFile.toURI().toURL();
    Source xmlFile = new StreamSource(configXmlFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    try {
        validator.validate(xmlFile);
        validated = true;
    } catch (SAXException e) {
        log.error(e.getStackTrace());
        throw new SAXException(e);
    }
    Assert.assertTrue(validated);
}
Example 28
Project: dwca-io-master  File: MetaValidator.java View source code
public static Validator getValidator() throws IOException, SAXException {
    if (VALIDATOR == null) {
        // define the type of schema - we use W3C:
        // resolve validation driver:
        SchemaFactory factory = SchemaFactory.newInstance(SCHEMA_LANG);
        // create schema by reading it from gbif online resources:
        Schema schema = factory.newSchema(new StreamSource(XSD_SCHEMA));
        VALIDATOR = schema.newValidator();
    }
    return VALIDATOR;
}
Example 29
Project: elexis-3-base-master  File: UtilXml.java View source code
public static List<String> validateSchema(String schemaUrl, String xmlDocumentUrl) {
    MyErrorHandler errorHandler = new MyErrorHandler();
    try {
        // 1. Lookup a factory for the W3C XML Schema language
        SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
        // 2. Compile the schema.
        // Here the schema is loaded from a java.io.File, but you could use
        // a java.net.URL or a javax.xml.transform.Source instead.
        Schema schema = factory.newSchema();
        if (schemaUrl != null) {
            File schemaLocation = new File(schemaUrl);
            schema = factory.newSchema(schemaLocation);
        }
        // 3. Get a validator from the schema.
        Validator validator = schema.newValidator();
        // 4. Parse the document you want to check.
        Source source = new StreamSource(xmlDocumentUrl);
        // 5. Check the document
        validator.setErrorHandler(errorHandler);
        validator.validate(source);
    } catch (Exception ex) {
        errorHandler.exception(ex);
    }
    return errorHandler.getMessageList();
}
Example 30
Project: enzymeportal-master  File: EnzymePortalXmlValidator.java View source code
/**
     * Validate provided XML against the provided XSD schema files.
     *
     * @param xmlFile XML file to be validated; should not be null or empty.
     * @param xsdFiles XSDs against which to validate the XML should not be null
     * or empty.
     * @return true if validated otherwise false
     */
public static boolean validateXml(final String xmlFile, final String[] xsdFiles) {
    Preconditions.checkArgument(xmlFile == null || xmlFile.isEmpty(), "XML file to be validated cannot be null.");
    Preconditions.checkArgument(xsdFiles == null || xsdFiles.length < 1, "At least an XSD File must be provided for XML validation to proceed.");
    File file = new File(xmlFile);
    Preconditions.checkArgument(file.exists() == false, "XML file does not exist.");
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final StreamSource[] streamSources = streamSourcesFromXsdFiles(xsdFiles);
    try {
        final Schema schema = schemaFactory.newSchema(streamSources);
        final Validator validator = schema.newValidator();
        String info = "Started validating " + xmlFile + " against XSDs " + Arrays.toString(xsdFiles) + "...";
        logger.info(info);
        validator.validate(new StreamSource(new File(xmlFile)));
        logger.warn("The validation of the XML file in this dir [" + xmlFile + "] seems successful.");
    } catch (IOExceptionSAXException |  exception) {
        String errorMsg = ("ERROR: Unable to validate " + xmlFile + " against XSDs " + Arrays.toString(xsdFiles) + " - " + exception);
        logger.error(errorMsg);
        return false;
    }
    logger.info("XML Validation process is now completed.Please check the logs for more info.");
    return true;
}
Example 31
Project: fcrepo-before33-master  File: DOValidatorXMLSchemaTest.java View source code
@Test
public void testAtomValidation() throws Exception {
    InputStream in = new FileInputStream(getDemoFile("atom/local-server-demos/simple-image-demo/obj_demo_5.xml"));
    DOValidatorXMLSchema dov = new DOValidatorXMLSchema(RESOURCES + "xsd/atom.xsd");
    dov.validate(in);
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XML_XSD.uri);
    Schema schema = sf.newSchema(new File(RESOURCES + "xsd/atom.xsd"));
    Validator validator = schema.newValidator();
//validator.validate(new StreamSource(in));
}
Example 32
Project: geoserver-master  File: XMLValidator.java View source code
/**
     * Validates a User/Group DOM against the XMLSchema.
     * The schema is determined by the version of the 
     * User/Group DOM 
     * 
     * @param doc
     * @throws IOException
     */
public void validateUserGroupRegistry(Document doc) throws IOException {
    if (versionMapUR == null)
        initializeSchemataUR();
    XPathExpression expr = XMLXpathFactory.Singleton.getVersionExpressionUR();
    String versionString = null;
    try {
        versionString = expr.evaluate(doc);
    } catch (XPathExpressionException e) {
        throw new IOException(e);
    }
    Schema schema = versionMapUR.get(versionString);
    Validator val = schema.newValidator();
    try {
        val.validate(new DOMSource(doc));
    } catch (SAXException e) {
        throw new IOException(e);
    }
}
Example 33
Project: gexf4j-core-master  File: GraphWriterTest.java View source code
@Test
public void writeToStream() throws SAXException, IOException {
    Gexf gexf = builder.buildGexf();
    GexfWriter gw = newGraphWriter();
    String fileName = "target/" + getFileNamePrefix() + "_" + builder.getSuffix() + ".gexf";
    File f = new File(fileName);
    FileOutputStream fos = new FileOutputStream(f);
    gw.writeToStream(gexf, fos);
    URL schemaFile = new URL(builder.getSchemaUrl());
    Source xmlFile = new StreamSource(f);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}
Example 34
Project: jAPS2-master  File: AbstractAttributeSupportObjectDOM.java View source code
protected void validate(String xmlText, String definitionPath) throws ApsSystemException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream schemaIs = null;
    InputStream xmlIs = null;
    try {
        schemaIs = this.getClass().getResourceAsStream(this.getSchemaFileName());
        Source schemaSource = new StreamSource(schemaIs);
        Schema schema = factory.newSchema(schemaSource);
        Validator validator = schema.newValidator();
        xmlIs = new ByteArrayInputStream(xmlText.getBytes("UTF-8"));
        Source source = new StreamSource(xmlIs);
        validator.validate(source);
        ApsSystemUtils.getLogger().info("Valid definition : " + definitionPath);
    } catch (Throwable t) {
        String message = "Error validating definition : " + definitionPath;
        ApsSystemUtils.logThrowable(t, this, "this", message);
        throw new ApsSystemException(message, t);
    } finally {
        try {
            if (null != schemaIs)
                schemaIs.close();
            if (null != xmlIs)
                xmlIs.close();
        } catch (IOException e) {
            ApsSystemUtils.logThrowable(e, this, "this");
        }
    }
}
Example 35
Project: jboss-as-quickstart-master  File: XMLParser.java View source code
public List<Book> parse(InputStream is) throws Exception {
    /*
         * Validate against schema before it triggers implementation.
         */
    StringBuffer xmlFile = new StringBuffer();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        xmlFile.append(line);
    }
    String xml = xmlFile.toString();
    // validate against schema.
    try {
        URL schema = Resources.getResource("/catalog.xsd");
        Validator validator = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(schema).newValidator();
        Source source = new StreamSource(new CharArrayReader(xml.toCharArray()));
        validator.validate(source);
    } catch (Exception e) {
        this.errorHolder.addErrorMessage("Validation Error", e);
        return null;
    }
    // parse file into catalog
    ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
    // ask extending class to parse
    return parseInternal(bais);
}
Example 36
Project: jcloudscale-master  File: SaxParser.java View source code
private void validateConfiguration(InputStream xmlStream) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream schemaStream = classLoader.getResourceAsStream("META-INF/datastores.xsd");
    Source schemaSource = new StreamSource(schemaStream);
    Source xmlSource = new StreamSource(xmlStream);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    try {
        schema = schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        throw new DatastoreException("Error validating XML configuration: " + e.getMessage());
    }
    Validator validator = schema.newValidator();
    try {
        validator.validate(xmlSource);
        schemaStream.close();
        xmlStream.close();
    } catch (SAXException e) {
        throw new DatastoreException("Invalid XML configuration: " + e.getMessage());
    } catch (IOException e) {
        throw new DatastoreException("Error reading XML configuration: " + e.getMessage());
    }
}
Example 37
Project: jentrata-master  File: XmlSchemaValidator.java View source code
@Override
public void process(Exchange exchange) throws Exception {
    try {
        Validator validator = schema.newValidator();
        StreamSource source = new StreamSource(exchange.getIn().getBody(InputStream.class));
        final List<String> errors = new ArrayList<>();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                LOG.debug("Validation warning:" + exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                LOG.warn("Validation error:" + exception);
                errors.add(exception.getMessage());
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                LOG.warn("Validation error:" + exception);
                errors.add(exception.getMessage());
            }
        });
        validator.validate(source);
        if (errors.isEmpty()) {
            exchange.getIn().setHeader(SCHEMA_VALID, true);
        } else {
            exchange.getIn().setHeader(SCHEMA_VALID, false);
            StringBuilder error = new StringBuilder();
            for (String err : errors) {
                error.append(err + "\n");
            }
            exchange.getIn().setHeader(SCHEMA_ERRORS, error.toString());
            throw new ValidationException("Failed Schema Validation:" + error.toString(), exchange, null);
        }
    } catch (SAXParseException ex) {
        throw new ValidationException("Failed Schema Validation:" + ex.getMessage(), exchange, ex);
    }
}
Example 38
Project: Lizard-fastDB-master  File: XMLValidator.java View source code
/**
	 * 根� schema 语法定义文件验� xml文件内容是�规范
	 * 
	 * @param schemaLocation schema 文件
	 * @param xml xml 文件内容
	 * @return 最终的验�信�
	 */
public static boolean validate(String schemaLocation, String xml) {
    // 获�Schema工厂类,
    // 这里的XMLConstants.W3C_XML_SCHEMA_NS_URI的值就是:http://www.w3.org/2001/XMLSchema
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    boolean res = false;
    InputStream is = null;
    try {
        // 读� schema 定义文件
        is = XMLValidator.class.getClassLoader().getResourceAsStream(schemaLocation);
        StreamSource ss = new StreamSource(is);
        // 创建 schema
        Schema schema = factory.newSchema(ss);
        // 从 schema 中获� validator
        Validator validator = schema.newValidator();
        // 解��检测的 xml 文件内容
        ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Source source = new StreamSource(bis);
        // 验� xml 文件内容格�是�符�schema语法定义规范
        validator.validate(source);
        res = true;
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            is = null;
        }
    }
    return res;
}
Example 39
Project: MTBT-master  File: XmlParser.java View source code
private static boolean isValid(byte[] workPlanData) throws Exception {
    InputStream schemaInStr = XmlParser.class.getResourceAsStream("/workPlan.xsd");
    Source schemaSrc = new StreamSource(schemaInStr);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(schemaSrc);
    Validator val = schema.newValidator();
    InputStream inStr = new ByteArrayInputStream(workPlanData);
    Source src = new StreamSource(inStr);
    boolean rtn;
    try {
        val.validate(src);
        rtn = true;
    } catch (Exception e) {
        _LOG.error("Cannot validate xml file", e);
        rtn = false;
    }
    return rtn;
}
Example 40
Project: mymom-master  File: SaveGameValidator.java View source code
public static void main(String[] args) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    File schemaLocation = new File("schema/data/data-savedGame.xsd");
    Schema schema = factory.newSchema(schemaLocation);
    Validator saveGameValidator = schema.newValidator();
    List<File> allFiles = new ArrayList<File>();
    for (String name : args) {
        File file = new File(name);
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File fsg : file.listFiles(fsgFilter)) {
                    allFiles.add(fsg);
                }
            } else if (fsgFilter.accept(file)) {
                allFiles.add(file);
            }
        }
    }
    for (File file : allFiles) {
        System.out.println("Processing file " + file.getPath());
        try {
            FreeColSavegameFile mapFile = new FreeColSavegameFile(file);
            saveGameValidator.validate(new StreamSource(mapFile.getSavegameInputStream()));
            System.out.println("Successfully validated " + file.getName());
        } catch (SAXParseException e) {
            System.out.println(e.getMessage() + " at line=" + e.getLineNumber() + " column=" + e.getColumnNumber());
        } catch (Exception e) {
            System.out.println("Failed to read " + file.getName());
        }
    }
}
Example 41
Project: open2jam-master  File: SkinChecker.java View source code
public boolean validate(String xmlFile) throws SAXException, IOException {
    InputStream input_stream = null;
    URL url = SkinChecker.class.getResource(xmlFile);
    if (url == null) {
        File file = new File(xmlFile);
        if (!file.exists()) {
            Logger.global.log(Level.SEVERE, "There is no xml file {0}", xmlFile);
            return false;
        }
        input_stream = new FileInputStream(file);
    } else {
        input_stream = url.openStream();
    }
    if (input_stream == null)
        Logger.global.log(Level.SEVERE, "There is no xml file {0}", xmlFile);
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    URL schema_file = SkinChecker.class.getResource(schemaLocation);
    Schema schema = factory.newSchema(schema_file);
    Validator validator = schema.newValidator();
    Source source = new StreamSource(input_stream);
    ErrorHandler error_handler = new SimpleErrorHandler();
    validator.setErrorHandler(error_handler);
    try {
        validator.validate(source);
        //it's valid.
        return true;
    } catch (SAXException ex) {
        return false;
    }
}
Example 42
Project: openjdk-master  File: RegexWord.java View source code
/*
    The original reZ003v.xml contains a full list of word characters that \w should accept.
    However, U+2308..U+230B were changed from Sm to either Ps or Pe in Unicode 7.0.
    They are therefore excluded from the test.

    The test throws an Exception (and fails) if it fails to recognize any of characters.
    */
@Test
public void test() throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new StreamSource(RegexWord.class.getResourceAsStream("reZ003.xsd")));
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(RegexWord.class.getResourceAsStream("reZ003vExc23082309.xml")));
}
Example 43
Project: OpenSAML-master  File: SchemaValidationFilter.java View source code
/** {@inheritDoc} */
public void doFilter(XMLObject metadata) throws FilterException {
    Validator schemaValidator = null;
    try {
        schemaValidator = SAMLSchemaBuilder.getSAML11Schema().newValidator();
    } catch (SAXException e) {
        log.error("Unable to build metadata validation schema", e);
        throw new FilterException("Unable to build metadata validation schema", e);
    }
    try {
        schemaValidator.validate(new DOMSource(metadata.getDOM()));
    } catch (Exception e) {
        log.error("Incoming metadata was not schema valid.", e);
        throw new FilterException("Incoming metadata was not schema valid.", e);
    }
}
Example 44
Project: quickstart-master  File: XMLParser.java View source code
public List<Book> parse(InputStream is) throws Exception {
    /*
         * Validate against schema before it triggers implementation.
         */
    StringBuilder xmlFile = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        xmlFile.append(line);
    }
    String xml = xmlFile.toString();
    // validate against schema.
    try {
        URL schema = Resources.getResource("/catalog.xsd");
        Validator validator = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(schema).newValidator();
        Source source = new StreamSource(new CharArrayReader(xml.toCharArray()));
        validator.validate(source);
    } catch (Exception e) {
        this.errorHolder.addErrorMessage("Validation Error", e);
        return null;
    }
    // parse file into catalog
    ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
    // ask extending class to parse
    return parseInternal(bais);
}
Example 45
Project: spring-ws-master  File: Jaxp13ValidatorFactory.java View source code
@Override
public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler) throws IOException {
    if (errorHandler == null) {
        errorHandler = new DefaultValidationErrorHandler();
    }
    Validator validator = schema.newValidator();
    validator.setErrorHandler(errorHandler);
    try {
        validator.validate(source);
        return errorHandler.getErrors();
    } catch (SAXException ex) {
        throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
    }
}
Example 46
Project: xmltool-master  File: Utils.java View source code
static ValidationResult validate(Document doc, Source... schemas) throws IOException, SAXException {
    XMLErrorHandler errorHandler = new XMLErrorHandler();
    Validator validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemas).newValidator();
    try {
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(doc));
        return errorHandler;
    } finally {
        validator.reset();
    }
}
Example 47
Project: GeoprocessingAppstore-master  File: XsdValidator.java View source code
/**
 * Creates a new javax.xml.validation.Validator for a schema.
 * <p/>
 * A validator will only be created if an XSD has been configured for
 * the schema - schema.getXsdLocation().
 * <p/>
 * The XSD is cached for subsequent use.
 * @param schema the subject schema
 * @return the validator (null if an XSD has not been configured for the schema)
 * @throws ValidationException if the schema's XSD cannot be accessed
 */
private javax.xml.validation.Validator newValidator(Schema schema) throws ValidationException {
    String xsdLocation = Val.chkStr(_xsdLocation);
    if (xsdLocation.length() == 0) {
        xsdLocation = Val.chkStr(schema.getXsdLocation());
    }
    if (xsdLocation.length() > 0) {
        String sMsg;
        ValidationError error;
        // find a cached XSD reference,
        // if none was found, create the reference and cache
        javax.xml.validation.Schema xsd = XSDS.get(xsdLocation);
        if (xsd == null) {
            javax.xml.validation.SchemaFactory factory = javax.xml.validation.SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            try {
                String[] xsdLocations = Val.tokenize(xsdLocation, ",");
                if (xsdLocations != null && xsdLocations.length > 1) {
                    ArrayList<StreamSource> streamSources = new ArrayList<StreamSource>();
                    for (String systemId : xsdLocations) {
                        streamSources.add(new StreamSource(systemId));
                    }
                    xsd = factory.newSchema(streamSources.toArray(new StreamSource[streamSources.size()]));
                    XSDS.put(xsdLocation, xsd);
                } else {
                    URL url = new URL(xsdLocation);
                    xsd = factory.newSchema(url);
                    XSDS.put(xsdLocation, xsd);
                }
            } catch (MalformedURLException e) {
                sMsg = "Malformed XSD URL, schema=" + schema.getKey() + " xsdLocation=" + xsdLocation;
                LogUtil.getLogger().log(Level.SEVERE, sMsg, e);
                error = new ValidationError();
                error.setMessage(sMsg);
                error.setReasonCode(ValidationError.REASONCODE_XSD_ISINVALID);
                getValidationErrors().add(error);
                throw new ValidationException(schema.getKey(), sMsg, getValidationErrors());
            } catch (SAXException e) {
                sMsg = "Error parsing XSD, schema=" + schema.getKey() + " xsdLocation=" + xsdLocation;
                LogUtil.getLogger().log(Level.SEVERE, sMsg, e);
                error = new ValidationError();
                error.setMessage(sMsg);
                error.setReasonCode(ValidationError.REASONCODE_XSD_ISINVALID);
                getValidationErrors().add(error);
                throw new ValidationException(schema.getKey(), sMsg, getValidationErrors());
            }
        }
        return xsd.newValidator();
    }
    return null;
}
Example 48
Project: 101simplejava-master  File: Serialization.java View source code
/**
	 * return true if document is a valid company
	 * 
	 */
public static boolean isValidXml(String xmlFile, String xsdFile) {
    Schema schema = null;
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    // Create a factory for validation
    String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(language);
    try {
        // Create schema from xsd file
        schema = schemaFactory.newSchema(new File(xsdFile));
        // Create validator
        Validator validator = schema.newValidator();
        // Create DocumentBuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // Create document from xml file
        Document doc = builder.parse(new File(xmlFile));
        // validate xml file with xsd schema
        validator.validate(new DOMSource(doc));
        return true;
    } catch (SAXException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } catch (ParserConfigurationException e) {
        System.err.println(e);
    }
    return false;
}
Example 49
Project: ambari-master  File: ServicePropertiesTest.java View source code
/**
   * This unit test checks that all config xmls for all services pass validation.
   * They should match xsd schema configuration-schema.xsd.
   * Test checks real (production) configs like hdfs-site.xml. The reason why
   * this test exists is to make sure that anybody who adds new properties to stack
   * configs, explicitly defines whether they should be added/modified/deleted
   * during ambari upgrade and/or stack upgrade.
   *
   * @throws SAXException
   * @throws IOException
   */
@Test
public void validatePropertySchemaOfServiceXMLs() throws SAXException, IOException, URISyntaxException {
    Validator validator = StackManager.getPropertySchemaValidator();
    // TODO: make sure that test does not depend on mvn/junit working directory
    StackManager.validateAllPropertyXmlsInFolderRecursively(getDirectoryFromMainResources("common-services"), validator);
    StackManager.validateAllPropertyXmlsInFolderRecursively(getDirectoryFromMainResources("stacks"), validator);
}
Example 50
Project: android-gradle-plugin-master  File: ValidateSysImgXmlTest.java View source code
/** Validate a valid sample using namespace version 1 using an InputStream */
public void testValidateLocalSysImgFile1() throws Exception {
    InputStream xmlStream = this.getClass().getResourceAsStream("/com/android/sdklib/testdata/sys_img_sample_1.xml");
    Source source = new StreamSource(xmlStream);
    CaptureErrorHandler handler = new CaptureErrorHandler();
    Validator validator = getValidator(1, handler);
    validator.validate(source);
    handler.verify();
}
Example 51
Project: android-maven-plugin-master  File: AndroidTestRunListenerTest.java View source code
public boolean validateXMLSchema(String xsdResource, File xmlFile) {
    try {
        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = factory.newSchema(new StreamSource(getClass().getClassLoader().getResourceAsStream(xsdResource)));
        final Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlFile));
    } catch (IOExceptionSAXException |  e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
Example 52
Project: android-platform-tools-base-master  File: ValidateSysImgXmlTest.java View source code
/** Validate a valid sample using namespace version 1 using an InputStream */
public void testValidateLocalSysImgFile1() throws Exception {
    InputStream xmlStream = this.getClass().getResourceAsStream("/com/android/sdklib/testdata/sys_img_sample_1.xml");
    Source source = new StreamSource(xmlStream);
    CaptureErrorHandler handler = new CaptureErrorHandler();
    Validator validator = getValidator(1, handler);
    validator.validate(source);
    handler.verify();
}
Example 53
Project: BPMNspector-master  File: WsdlValidator.java View source code
private void validateUsingStreamSource(StreamSource src, Resource resource, ValidationResult validationResult) throws IOException, SAXException, ValidationException {
    List<SAXParseException> xsdErrorList = new ArrayList<>();
    Validator validator = schema.newValidator();
    validator.setErrorHandler(new XsdValidationErrorHandler(xsdErrorList));
    try {
        validator.validate(src);
        for (SAXParseException saxParseException : xsdErrorList) {
            Location location = createLocation(resource, saxParseException.getLineNumber(), saxParseException.getColumnNumber());
            Violation violation = new Violation(location, saxParseException.getMessage(), "WSDL-XSD-Check");
            validationResult.addViolation(violation);
            LOGGER.info("WSDL xsd violation found in {} at line {}.", resource.getResourceName(), saxParseException.getLineNumber());
        }
    } catch (SAXParseException e) {
        Location location = createLocation(resource, e.getLineNumber(), e.getLineNumber());
        Violation violation = new Violation(location, e.getMessage(), "XSD-Check");
        validationResult.addViolation(violation);
        String msg = String.format("File %s is not well-formed at line %d: %s", resource.getResourceName(), e.getLineNumber(), e.getMessage());
        LOGGER.info(msg);
        throw new ValidationException("Cancel Validation as checked File is not well-formed.");
    }
}
Example 54
Project: carbon-governance-master  File: Util.java View source code
//    The methods have been duplicated in several places because there is no common bundle to place them.
//    We have to keep this inside different bundles so that users will not run in to problems if they uninstall some features
public static boolean validateOMContent(OMElement omContent, Validator validator) {
    try {
        InputStream is = new ByteArrayInputStream(omContent.toString().getBytes("utf-8"));
        Source xmlFile = new StreamSource(is);
        if (validator != null) {
            validator.validate(xmlFile);
        }
    } catch (SAXException e) {
        log.error("Unable to validate the given xml configuration ", e);
        return false;
    } catch (UnsupportedEncodingException e) {
        log.error("Unsupported content");
        return false;
    } catch (IOException e) {
        log.error("Unable to validate the given file");
        return false;
    }
    return true;
}
Example 55
Project: carbon-registry-master  File: SchemaValidator.java View source code
/**
     * This will validate the given schema against the w3c.XMLSchema.
     *
     * @param xsdContent : Input stream representing XSD content
     *
     * @throws org.wso2.carbon.registry.core.exceptions.RegistryException
     *          : If there is a problem in the XSD then that will throw as the exception
     */
public void validate(InputStream xsdContent, Resource resource) throws RegistryException {
    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(XMLSCHEMA_XSD_LOCATION);
        Source scoure = new SAXSource(reader, new InputSource(in));
        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(xsdContent);
        Schema schema = factory.newSchema(schemaFile);
        // create a Validator instance, which can be used to validate an instance document
        Validator validator = schema.newValidator();
        // validate the DOM tree
        validator.validate(scoure);
        resource.setProperty(XSD_STATUS, XSD_VALID);
    } catch (Exception e) {
        resource.setProperty(XSD_STATUS, XSD_IN_VALID);
        resource.addProperty(XSD_VALIDATION_ERROR, e.getMessage());
        throw new RegistryException(e.getMessage());
    }
}
Example 56
Project: citygml4j-master  File: JAXBValidator.java View source code
public void validate(Object object, ModuleContext moduleContext) throws CityGMLValidateException {
    try {
        Schema schema = validationSchemaHandler.getSchema();
        if (object instanceof ADEComponent)
            object = ((ADEComponent) object).getContent();
        if (object instanceof Element) {
            javax.xml.validation.Validator validator = schema.newValidator();
            if (validationEventHandler != null)
                validator.setErrorHandler(new ErrorHandler2ValidationEventHandler());
            try {
                validator.validate(new DOMSource((Element) object));
            } catch (IOException e) {
                throw new CityGMLValidateException("Caused by: ", e);
            }
        } else {
            JAXBMarshaller marshaller = builder.createJAXBMarshaller(moduleContext);
            Object jaxb = marshaller.marshalJAXBElement(object);
            if (jaxb != null) {
                try {
                    Marshaller m = builder.getJAXBContext().createMarshaller();
                    m.setSchema(schema);
                    if (validationEventHandler != null)
                        m.setEventHandler(validationEventHandler);
                    m.marshal(jaxb, new DefaultHandler());
                } catch (JAXBException e) {
                    throw new CityGMLValidateException("Caused by: ", e);
                }
            } else
                throw new CityGMLValidateException("failed to marshal citygml4j object to JAXB - validation aborted.");
        }
    } catch (SAXException e) {
        throw new CityGMLValidateException("Caused by: ", e);
    }
}
Example 57
Project: cmestemp22-master  File: UrlXmlValidator.java View source code
/**
     * Validates xml from given Url returning true if it passes validation, false otherwise.
     *
     * @param inActionContext
     *            the action context
     * @throws ValidationException
     *             on error
     */
@Override
@SuppressWarnings("unchecked")
public void validate(final ServiceActionContext inActionContext) throws ValidationException {
    InputStream schemaStream = null;
    Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
    String galleryItemUrl = (String) fields.get(URL_KEY);
    try {
        schemaStream = this.getClass().getResourceAsStream(xsdPath);
        log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
        Validator validator = schema.newValidator();
        // TODO: stuff the input stream into the context for execute()
        InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl);
        validator.validate(new StreamSource(galleryItemInputStream));
        log.debug("Success validating xml at: " + galleryItemUrl);
    } catch (Exception e) {
        log.error("Validation for gadget definition failed.", e);
        ValidationException ve = new ValidationException();
        ve.addError(URL_KEY, "Valid url is required");
        throw ve;
    } finally {
        try {
            if (schemaStream != null) {
                schemaStream.close();
            }
        } catch (IOException ex) {
            log.error("Error closing stream, already closed.", ex);
        }
    }
}
Example 58
Project: cougar-master  File: XmlValidator.java View source code
private void doValidate(Document doc) throws Exception {
    // preparsed schema seems to be the only way to get xi:include working,
    // see http://www.xml.com/lpt/a/1597
    DOMSource source = new DOMSource(doc);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema();
    javax.xml.validation.Validator validator = schema.newValidator();
    // see notes in javadoc above
    validator.setResourceResolver(resolver);
    validator.validate(source);
}
Example 59
Project: csv2xml-master  File: SchemaValidator.java View source code
/**
     * validate xml file in xmlDir folder.
     * @param xmlDir
     * @return
     * @throws Exception
     */
public static String check(String xmlDir) throws Exception {
    Map<String, String> schemaMap = new HashMap<String, String>();
    for (String schema : SCHEMAS) {
        String schemaBase = schema.replace("Interchange", "").replace("-", "").replace("_", "").replace(".xsd", "");
        schemaMap.put(schemaBase, SCHEMA_DIR + schema);
    }
    for (File file : new File(xmlDir).listFiles()) {
        if (file.isFile()) {
            String fname = file.getName();
            String baseName = "";
            for (String key : schemaMap.keySet()) {
                if (fname.contains(key) && fname.contains("xml")) {
                    baseName = key;
                }
            }
            if (schemaMap.get(baseName) != null) {
                String schemaFile = schemaMap.get(baseName);
                SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
                File schemaLocation = new File(schemaFile);
                Schema schema = factory.newSchema(schemaLocation);
                Validator validator = schema.newValidator();
                Source source = new StreamSource(file);
                try {
                    validator.validate(source);
                    System.out.println(file.getCanonicalPath() + " is valid. [" + schemaFile + "]");
                    System.out.println("");
                } catch (SAXException ex) {
                    System.out.println("** ERROR **" + file.getCanonicalPath() + " is not valid. [" + schemaFile + "]");
                    System.out.println(ex.getMessage());
                    System.out.println("");
                }
            }
        }
    }
    return null;
}
Example 60
Project: Eclipse-JDE-master  File: BBSchemaValidator.java View source code
private BBDiagnostic validateBBSchema(IFile modelFile, URL schemaLocation) {
    BBDiagnostic diag = AbstractDiagnosticFactory.createChainedDiagnostic();
    // 1. Lookup a factory for the W3C XML Schema language
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {
        // 2. Compile the schema.
        // Here the schema is loaded from a java.io.File, but you could use
        // a java.net.URL or a javax.xml.transform.Source instead.
        Schema schema = factory.newSchema(schemaLocation);
        // 3. Get a validator from the schema.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler(diag));
        // 4. Parse the document you want to check.
        Source source = new StreamSource(modelFile.getContents());
        // 5. Check the document
        validator.validate(source);
    } catch (Exception e) {
        _logger.error(e);
        diag.add(DiagnosticFactory.createDiagnostic(BBDiagnostic.ERROR, 0, e.getMessage()));
    }
    return diag;
}
Example 61
Project: eclipselink.runtime-master  File: SchemaGenTestCases.java View source code
/**
     * Validates a given instance doc against the generated schema.
     *
     * @param src
     * @param schemaIndex index in output resolver's list of generated schemas
     * @param outputResolver contains one or more schemas to validate against
     */
protected String validateAgainstSchema(String src, int schemaIndex, MySchemaOutputResolver outputResolver) {
    SchemaFactory sFact = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema theSchema;
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(src);
    try {
        theSchema = sFact.newSchema(outputResolver.schemaFiles.get(schemaIndex));
        Validator validator = theSchema.newValidator();
        StreamSource ss = new StreamSource(is);
        validator.validate(ss);
    } catch (Exception e) {
        return e.getMessage();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Example 62
Project: entando-core-master  File: ComponentDefDOM.java View source code
private void validate(String xmlText, String configPath) throws ApsSystemException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream schemaIs = null;
    InputStream xmlIs = null;
    try {
        schemaIs = this.getClass().getResourceAsStream("componentDef-4.2.xsd");
        Source schemaSource = new StreamSource(schemaIs);
        Schema schema = factory.newSchema(schemaSource);
        Validator validator = schema.newValidator();
        xmlIs = new ByteArrayInputStream(xmlText.getBytes(StandardCharsets.UTF_8));
        Source source = new StreamSource(xmlIs);
        validator.validate(source);
        _logger.debug("Valid Component definition : {}", configPath);
    } catch (Throwable t) {
        _logger.error("Error validating Component definition : {}", configPath, t);
        String message = "Error validating Component definition : " + configPath;
        throw new ApsSystemException(message, t);
    } finally {
        try {
            if (null != schemaIs) {
                schemaIs.close();
            }
            if (null != xmlIs) {
                xmlIs.close();
            }
        } catch (IOException e) {
            _logger.error("error in validate", e);
        }
    }
}
Example 63
Project: epcis-master  File: CaptureUtil.java View source code
public static boolean validate(InputStream is, String xsdPath) {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File xsdFile = new File(xsdPath);
        Schema schema = schemaFactory.newSchema(xsdFile);
        Validator validator = schema.newValidator();
        StreamSource xmlSource = new StreamSource(is);
        validator.validate(xmlSource);
        return true;
    } catch (SAXException e) {
        Configuration.logger.log(Level.ERROR, e.toString());
        return false;
    } catch (IOException e) {
        Configuration.logger.log(Level.ERROR, e.toString());
        return false;
    }
}
Example 64
Project: eurekastreams-master  File: UrlXmlValidator.java View source code
/**
     * Validates xml from given Url returning true if it passes validation, false otherwise.
     *
     * @param inActionContext
     *            the action context
     * @throws ValidationException
     *             on error
     */
@Override
@SuppressWarnings("unchecked")
public void validate(final ServiceActionContext inActionContext) throws ValidationException {
    InputStream schemaStream = null;
    Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
    String galleryItemUrl = (String) fields.get(URL_KEY);
    try {
        schemaStream = this.getClass().getResourceAsStream(xsdPath);
        log.debug("Attempt to validate xml at: " + galleryItemUrl + "with xsd at: " + xsdPath);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaString);
        Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
        Validator validator = schema.newValidator();
        // TODO: stuff the input stream into the context for execute()
        InputStream galleryItemInputStream = xmlFetcher.getInputStream(galleryItemUrl);
        validator.validate(new StreamSource(galleryItemInputStream));
        log.debug("Success validating xml at: " + galleryItemUrl);
    } catch (Exception e) {
        log.error("Validation for gadget definition failed.", e);
        ValidationException ve = new ValidationException();
        ve.addError(URL_KEY, "Valid url is required");
        throw ve;
    } finally {
        try {
            if (schemaStream != null) {
                schemaStream.close();
            }
        } catch (IOException ex) {
            log.error("Error closing stream, already closed.", ex);
        }
    }
}
Example 65
Project: fcrepo-master  File: ValidatorHelper.java View source code
/**
     * Validate XML document supplied as a string.
     * <p>
     * Validates against the local copy of the XML schema specified as
     * schemaLocation in document
     *</p>
     *
     * @param xml
     * @throws Exception
     */
public void offlineValidate(String url, String xml, List<File> schemas) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    LOGGER.info(sf.getClass().getName());
    ArrayList<Source> schemata = new ArrayList<Source>();
    for (File schemaFile : schemas) {
        schemata.add(new StreamSource(schemaFile));
    }
    Schema schema;
    try {
        schema = sf.newSchema(schemata.toArray(new Source[0]));
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse schema " + schemas.toString(), e);
    }
    Validator v = schema.newValidator();
    StringBuilder errors = new StringBuilder();
    v.setErrorHandler(new ValidatorErrorHandler(errors));
    v.validate(new StreamSource(new StringReader(xml)));
    assertTrue("Offline validation failed for " + url + ". Errors: " + errors.toString() + "\n xml:\n" + xml, 0 == errors.length());
}
Example 66
Project: hale-master  File: Validate.java View source code
/**
	 * @see Validator#validate(InputStream)
	 */
public void validate(InputStream xml) {
    javax.xml.validation.Schema validateSchema;
    try {
        URI mainUri = null;
        Source[] sources = new Source[schemaLocations.length];
        for (int i = 0; i < this.schemaLocations.length; i++) {
            URI schemaLocation = this.schemaLocations[i];
            if (// use first schema location for main URI
            mainUri == null) {
                mainUri = schemaLocation;
            }
            // load a WXS schema, represented by a Schema instance
            sources[i] = new StreamSource(schemaLocation.toURL().openStream());
        }
        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new SchemaResolver(mainUri));
        validateSchema = factory.newSchema(sources);
    } catch (Exception e) {
        throw new IllegalStateException("Error parsing schema for XML validation", e);
    }
    final AtomicInteger warnings = new AtomicInteger(0);
    final AtomicInteger errors = new AtomicInteger(0);
    // create a Validator instance, which can be used to validate an
    // instance document
    javax.xml.validation.Validator validator = validateSchema.newValidator();
    validator.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            System.out.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            warnings.incrementAndGet();
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            errors.incrementAndGet();
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
            errors.incrementAndGet();
        }
    });
    // validate the XML document
    try {
        validator.validate(new StreamSource(xml));
    } catch (Exception e) {
        throw new IllegalStateException("Error validating XML file", e);
    }
    System.out.println("Validation completed.");
    System.out.println(warnings.get() + " warnings");
    System.out.println(errors.get() + " errors");
}
Example 67
Project: ithaka-digraph-master  File: GraphMLExporterTest.java View source code
@Test
public void test() throws XMLStreamException {
    Digraph<String, Integer> digraph = new MapDigraph<String, Integer>();
    digraph.put("a", "b", 1);
    digraph.put("b", "a", 2);
    digraph.put("a", "c", 3);
    digraph.add("d");
    SimpleGraphMLProvider<String, Integer, Digraph<? extends String, ? extends Integer>> provider = new SimpleGraphMLProvider<String, Integer, Digraph<? extends String, ? extends Integer>>();
    provider.addGraphProperty(foo);
    provider.addNodeProperty(name);
    provider.addEdgeProperty(weight);
    StringWriter result = new StringWriter();
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(result);
    new GraphMLExporter().export(provider, digraph, null, writer);
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(getClass().getResource("graphml-foo.xsd"));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(result.toString())));
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Example 68
Project: knox-master  File: TopologyValidator.java View source code
public boolean validateTopology() {
    errors = new LinkedList<String>();
    try {
        SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL schemaUrl = getClass().getResource("/conf/topology-v1.xsd");
        Schema s = fact.newSchema(schemaUrl);
        Validator validator = s.newValidator();
        final List<SAXParseException> exceptions = new LinkedList<>();
        validator.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                exceptions.add(exception);
            }
        });
        File xml = new File(filePath);
        validator.validate(new StreamSource(xml));
        if (exceptions.size() > 0) {
            for (SAXParseException e : exceptions) {
                errors.add("Line: " + e.getLineNumber() + " -- " + e.getMessage());
            }
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        errors.add("Error reading topology file");
        errors.add(e.getMessage());
        return false;
    } catch (SAXException e) {
        errors.add("There was a fatal error in parsing the xml file.");
        errors.add(e.getMessage());
        return false;
    } catch (NullPointerException n) {
        errors.add("Error retrieving schema from ClassLoader");
        return false;
    }
}
Example 69
Project: logging-log4j2-master  File: XmlCompactFileAsyncAppenderValidationTest.java View source code
private void validateXmlSchema(final File file) throws SAXException, IOException {
    final URL schemaFile = this.getClass().getClassLoader().getResource("Log4j-events.xsd");
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(schemaFile);
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}
Example 70
Project: midpoint-master  File: TestDomParser.java View source code
private void validateSchemaCompliance(String xmlString, PrismContext prismContext) throws SAXException, IOException {
//		Document xmlDocument = DOMUtil.parseDocument(xmlString);
//		Schema javaxSchema = prismContext.getSchemaRegistry().getJavaxSchema();
//		Validator validator = javaxSchema.newValidator();
//		validator.setResourceResolver(prismContext.getEntityResolver());
//		validator.validate(new DOMSource(xmlDocument));
}
Example 71
Project: modello-master  File: FeaturesXsdGeneratorTest.java View source code
public void testXsdGenerator() throws Throwable {
    ModelloCore modello = (ModelloCore) lookup(ModelloCore.ROLE);
    Model model = modello.loadModel(getXmlResourceReader("/features.mdo"));
    Properties parameters = getModelloParameters("1.0.0");
    modello.generate(model, "xsd", parameters);
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new StreamSource(new File(getOutputDirectory(), "features-1.0.0.xsd")));
    Validator validator = schema.newValidator();
    try {
        validator.validate(new StreamSource(getClass().getResourceAsStream("/features.xml")));
    } catch (SAXParseException e) {
        throw new ModelloException("line " + e.getLineNumber() + " column " + e.getColumnNumber(), e);
    }
    try {
        validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid.xml")));
        fail("parsing of features-invalid.xml should have failed");
    } catch (SAXParseException e) {
        assertTrue(String.valueOf(e.getMessage()).contains("invalidElement"));
    }
    try {
        validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid-transient.xml")));
        fail("XSD did not prohibit appearance of transient fields");
    } catch (SAXParseException e) {
        assertTrue(String.valueOf(e.getMessage()).contains("transientString"));
    }
}
Example 72
Project: nextprot-api-master  File: XSDValidationTest.java View source code
@Test
public void shouldValidateXMLFilewithXSD() {
    Schema schema;
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = factory.newSchema(new StreamSource(new File("src/main/webapp/nextprot-export-v2.xsd")));
        File f = new File("tmp.xml");
        StreamSource xmlFile = new StreamSource(f);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EntryStreamWriter<?> writer = new EntryXMLStreamWriter(baos, "entry");
        exportService.streamResults(writer, "entry", Arrays.asList(new String[] { "NX_Q15858" }));
        //exportService.streamResults(writer, "entry", Arrays.asList(new String[] { "NX_Q6PIU2" })); 
        XMLPrettyPrinter prettyPrinter = new XMLPrettyPrinter();
        //System.err.println(baos.toString());
        String prettyXml = prettyPrinter.prettify(baos.toString());
        PrintWriter out = new PrintWriter(f);
        out.print(prettyXml);
        out.close();
        // instance document
        Validator validator = schema.newValidator();
        // validate the DOM tree
        validator.validate(xmlFile);
        f.delete();
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}
Example 73
Project: olca-modules-master  File: SchemaValidator.java View source code
public boolean isValid(Path path, DataSetType type) {
    if (path == null)
        return false;
    Validator val = makeValidator(type);
    if (val == null)
        return false;
    try (BufferedInputStream is = new BufferedInputStream(Files.newInputStream(path))) {
        val.validate(new StreamSource(is));
        return true;
    } catch (Exception e) {
        log.error("validation of {} failed: {}", path, e.getMessage());
        return false;
    }
}
Example 74
Project: oliot-epcis-master  File: CaptureUtil.java View source code
public static boolean validate(InputStream is, String xsdPath) {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File xsdFile = new File(xsdPath);
        Schema schema = schemaFactory.newSchema(xsdFile);
        Validator validator = schema.newValidator();
        StreamSource xmlSource = new StreamSource(is);
        validator.validate(xmlSource);
        return true;
    } catch (SAXException e) {
        Configuration.logger.log(Level.ERROR, e.toString());
        return false;
    } catch (IOException e) {
        Configuration.logger.log(Level.ERROR, e.toString());
        return false;
    }
}
Example 75
Project: orb-object-migration-master  File: XmlTest.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String xml_file = "account.xml";
    BufferedReader infile = null;
    StringBuffer xml = new StringBuffer();
    try {
        System.out.println("Lendo o arquivo " + xml_file);
        infile = new BufferedReader(new FileReader(xml_file));
        String str;
        while ((str = infile.readLine()) != null) {
            xml.append(str + "\n");
        }
        infile.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            infile.close();
        } catch (IOException e) {
        }
        System.out.println("leitura finalizada");
    }
    System.out.println("xml lido: \n" + xml.toString());
    System.out.println("");
    /*
		 * Teste de Validacao do xml
		 */
    // parse an XML document into a DOM tree
    DocumentBuilder parser = null;
    try {
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e2) {
        e2.printStackTrace();
    }
    //Document
    Document document = null;
    try {
        document = parser.parse(new File(xml_file));
    } catch (SAXException e2) {
        e2.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    // create a SchemaFactory capable of understanding WXS schemas
    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("/Users/gustavosoares/workspace/morb_modificado/protocol.xsd"));
    Schema schema = null;
    try {
        schema = factory.newSchema(schemaFile);
    } catch (SAXException e1) {
        e1.printStackTrace();
    }
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {
        System.out.println("validating xml " + xml_file);
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        System.out.println("DOCUMENTO INVALIDO");
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("");
    String field = "object";
    String patternStr = "<" + field + ">(.*?)</" + field + ">";
    System.out.println("pattern: " + patternStr);
    // Compile and use regular expression
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(xml.toString());
    boolean matchFound = matcher.find();
    if (matchFound) {
        // Get all groups for this match
        String field_value = matcher.group(matcher.groupCount());
        System.out.println("field value: " + field_value);
    } else {
        System.out.println("object tag not found!");
    }
}
Example 76
Project: ParlamentoElettronicoOnlineTools-master  File: XmlUtils.java View source code
public boolean isDocValid(String xml) {
    boolean ret = true;
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    File schemaLocation = new File(Constants.XSD_PATH);
    if (schemaLocation.exists()) {
        Schema schema = null;
        try {
            schema = factory.newSchema(schemaLocation);
        } catch (SAXException e) {
            ret = false;
            e.printStackTrace();
        }
        Validator validator = schema.newValidator();
        Source source = new StreamSource(new StringReader(xml));
        try {
            validator.validate(source);
        } catch (SAXException e) {
            ret = false;
            e.printStackTrace();
        } catch (IOException e) {
            ret = false;
            e.printStackTrace();
        }
    } else {
        ret = false;
    }
    return ret;
}
Example 77
Project: phoenix.webui.framework-master  File: Validation.java View source code
/**
	 * 利用xsd验�xml
	 * @param xsdFile
	 * @param xmlInput
	 * @throws SAXException 
	 * @throws IOException 
	 */
public static void validation(String xsdFile, InputStream xmlInput) throws SAXException, IOException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL xsdURL = Validation.class.getClassLoader().getResource(xsdFile);
    if (xsdURL != null) {
        Schema schema = factory.newSchema(xsdURL);
        Validator validator = schema.newValidator();
        //			validator.setErrorHandler(new AutoErrorHandler());
        Source source = new StreamSource(xmlInput);
        try (OutputStream resultOut = new FileOutputStream(new File(PathUtil.getRootDir(), xsdFile + ".xml"))) {
            Result result = new StreamResult(resultOut);
            validator.validate(source, result);
        }
    } else {
        throw new FileNotFoundException(String.format("can not found xsd file [%s] from classpath.", xsdFile));
    }
}
Example 78
Project: platform_sdk-master  File: ValidateSysImgXmlTest.java View source code
// --- Helpers ------------
/**
     * Helper method that returns a validator for our Repository XSD
     *
     * @param version The version number, in range {@code 1..NS_LATEST_VERSION}
     * @param handler A {@link CaptureErrorHandler}. If null the default will be used,
     *   which will most likely print errors to stderr.
     */
private Validator getValidator(int version, @Nullable CaptureErrorHandler handler) throws SAXException {
    Validator validator = null;
    InputStream xsdStream = SdkSysImgConstants.getXsdStream(version);
    if (xsdStream != null) {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        validator = schema.newValidator();
        if (handler != null) {
            validator.setErrorHandler(handler);
        }
    }
    return validator;
}
Example 79
Project: proarc-master  File: ResolverXmlUtils.java View source code
public static void validate(Import imp, ErrorHandler status) throws SAXException {
    try {
        if (REGISTRATION_SCHEMA == null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            REGISTRATION_SCHEMA = schemaFactory.newSchema(ResolverXmlUtils.class.getResource("registration/digDocRegistration.xsd"));
        }
        Validator validator = REGISTRATION_SCHEMA.newValidator();
        validator.setErrorHandler(status);
        validator.validate(new JAXBSource(defaultRegistrationContext(), imp));
    } catch (IOException ex) {
        throw new SAXException(ex);
    } catch (JAXBException ex) {
        throw new SAXException(ex);
    }
}
Example 80
Project: radiology-master  File: XsdMrrtReportTemplateValidator.java View source code
/**
     * @see MrrtReportTemplateValidator#validate(String)
     */
@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);
    }
}
Example 81
Project: raml-tester-master  File: JavaXmlSchemaValidator.java View source code
@Override
public void validate(Reader content, Reader schema, RamlViolations violations, Message message) {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        schemaFactory.setResourceResolver(new LoaderLSResourceResolver(loader));
        final Schema s = schemaFactory.newSchema(new StreamSource(schema));
        final Validator validator = s.newValidator();
        final ViolationsWritingErrorHandler errorHandler = new ViolationsWritingErrorHandler();
        validator.setErrorHandler(errorHandler);
        validator.validate(new StreamSource(content));
        if (!errorHandler.getExceptions().isEmpty()) {
            String msg = "";
            for (final SAXParseException ex : errorHandler.getExceptions()) {
                msg += new Message("javaXmlSchemaValidator.message", ex.getLineNumber(), ex.getColumnNumber(), ex.getMessage());
            }
            violations.add(message.withParam(msg), new XmlSchemaViolationCause(errorHandler.getExceptions()));
        }
    } catch (SAXException e) {
        violations.add(message.withParam(new Message("schema.invalid", e.getMessage())), new XmlSchemaViolationCause(e));
    } catch (IOException e) {
        violations.add(message.withParam(new Message("schema.invalid", e.getMessage())));
    }
}
Example 82
Project: service-proxy-master  File: XMLSchemaValidator.java View source code
@Override
protected List<Validator> createValidators() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(Constants.XSD_NS);
    sf.setResourceResolver(resourceResolver.toLSResourceResolver());
    List<Validator> validators = new ArrayList<Validator>();
    log.debug("Creating validator for schema: " + location);
    StreamSource ss = new StreamSource(resourceResolver.resolve(location));
    ss.setSystemId(location);
    Validator validator = sf.newSchema(ss).newValidator();
    validator.setResourceResolver(resourceResolver.toLSResourceResolver());
    validator.setErrorHandler(new SchemaValidatorErrorHandler());
    validators.add(validator);
    return validators;
}
Example 83
Project: siu-master  File: Support.java View source code
private List<String> validateBySchema(final Document document, URL schemaUrl) {
    final long startMs = System.currentTimeMillis();
    final List<String> errors = new ArrayList<String>();
    try {
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory.newSchema(schemaUrl);
        final Validator validator = schema.newValidator();
        validator.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                errors.add(exception.getMessage());
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                errors.add(exception.getMessage());
            }
        });
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        errors.add(e.getMessage());
    } catch (IOException e) {
        errors.add(e.getMessage());
    } finally {
        System.out.println("VALIDATE: " + (System.currentTimeMillis() - startMs));
    }
    return errors;
}
Example 84
Project: smooks-master  File: XsdValidator.java View source code
/**
     * Validate the supplied source against the namespaces referenced in it.
     * @throws org.xml.sax.SAXException Validation error.
     * @throws java.io.IOException Error reading the XSD Sources.
     */
public void validate(Source source) throws SAXException, IOException {
    AssertArgument.isNotNull(source, "source");
    if (schema == null) {
        throw new IllegalStateException("Invalid call to validate.  XSD sources not set.");
    }
    // Create the merged Schema instance and from that, create the Validator instance...
    Validator validator = schema.newValidator();
    if (schemaSourceResolver != null) {
        validator.setResourceResolver(schemaSourceResolver);
    }
    if (errorHandler != null) {
        validator.setErrorHandler(errorHandler);
    }
    // Validate the source...
    validator.validate(source);
}
Example 85
Project: wildfly-core-master  File: ModuleConfigTestCase.java View source code
private void validateXmlSchema(final URL schemaUrl, final InputStream data) throws IOException, SAXException {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(ERROR_HANDLER);
    final Schema schema = schemaFactory.newSchema(schemaUrl);
    final Validator validator = schema.newValidator();
    validator.validate(new StreamSource(data));
}
Example 86
Project: wildfly-master  File: XSDValidationUnitTestCase.java View source code
private void validateXsd(final File xsdFile) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(xsdFile);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(new ErrorHandlerImpl());
    schemaFactory.setResourceResolver(new XMLResourceResolver());
    Schema schema = schemaFactory.newSchema(resource("schema/XMLSchema.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));
}
Example 87
Project: xml-matchers-master  File: ConformsToSchema.java View source code
@Override
protected boolean matchesSafely(Source source, Description mismatchDescription) {
    boolean isValid = true;
    DOMSource domSource = convert(source);
    Validator validator = schema.newValidator();
    ValidationErrorHandler errorCollector = new ValidationErrorHandler();
    validator.setErrorHandler(errorCollector);
    try {
        validator.validate(domSource);
    } catch (SAXException e) {
        isValid = false;
    } catch (IOException e) {
        isValid = false;
    }
    if (errorCollector.hasErrors()) {
        errorCollector.updateDiscription(mismatchDescription);
        isValid = false;
    }
    return isValid;
}
Example 88
Project: eXist-1.4.x-master  File: Jaxv.java View source code
/**
     * @throws org.exist.xquery.XPathException 
     * @see BasicFunction#eval(Sequence[], Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2) {
        return Sequence.EMPTY_SEQUENCE;
    }
    ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource grammars[] = null;
    try {
        report.start();
        // Get inputstream for instance document
        instance = Shared.getStreamSource(args[0].itemAt(0), context);
        // Validate using resource speciefied in second parameter
        grammars = Shared.getStreamSource(args[1], context);
        for (StreamSource grammar : grammars) {
            String grammarUrl = grammar.getSystemId();
            if (grammarUrl != null && !grammarUrl.endsWith(".xsd")) {
                throw new XPathException("Only XML schemas (.xsd) are supported.");
            }
        }
        // Prepare
        String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
        SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
        // Create grammar
        Schema schema = factory.newSchema(grammars);
        // Setup validator
        Validator validator = schema.newValidator();
        validator.setErrorHandler(report);
        // Perform validation
        validator.validate(instance);
    } catch (MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (ExistIOException ex) {
        LOG.error(ex.getCause());
        report.setException(ex);
    } catch (Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeStreamSource(instance);
        Shared.closeStreamSources(grammars);
    }
    // Create response
    if (isCalledAs("jaxv")) {
        Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxv-report") */
    {
        MemTreeBuilder builder = context.getDocumentBuilder();
        NodeImpl result = Shared.writeReport(report, builder);
        return result;
    }
}
Example 89
Project: exist-master  File: Jaxv.java View source code
/**
     * @throws org.exist.xquery.XPathException 
     * @see BasicFunction#eval(Sequence[], Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2 && args.length != 3) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource grammars[] = null;
    String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    try {
        report.start();
        // Get inputstream for instance document
        instance = Shared.getStreamSource(args[0].itemAt(0), context);
        // Validate using resource speciefied in second parameter
        grammars = Shared.getStreamSource(args[1], context);
        // Check input
        for (final StreamSource grammar : grammars) {
            final String grammarUrl = grammar.getSystemId();
            if (grammarUrl != null && !grammarUrl.endsWith(".xsd") && !grammarUrl.endsWith(".rng")) {
                throw new XPathException("Only XML schemas (.xsd) and RELAXNG grammars (.rng) are supported" + ", depending on the used XML parser.");
            }
        }
        // Fetch third argument if available, and override defailt value
        if (args.length == 3) {
            schemaLang = args[2].getStringValue();
        }
        // Get language specific factory
        SchemaFactory factory = null;
        try {
            factory = SchemaFactory.newInstance(schemaLang);
        } catch (final IllegalArgumentException ex) {
            final String msg = "Schema language '" + schemaLang + "' is not supported. " + ex.getMessage();
            LOG.error(msg);
            throw new XPathException(msg);
        }
        // Create grammar
        final Schema schema = factory.newSchema(grammars);
        // Setup validator
        final Validator validator = schema.newValidator();
        validator.setErrorHandler(report);
        // Perform validation
        validator.validate(instance);
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeStreamSource(instance);
        Shared.closeStreamSources(grammars);
    }
    // Create response
    if (isCalledAs("jaxv")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxv-report") */
    {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final NodeImpl result = Shared.writeReport(report, builder);
        return result;
    }
}
Example 90
Project: XSLT-master  File: Jaxv.java View source code
/**
     * @throws org.exist.xquery.XPathException 
     * @see BasicFunction#eval(Sequence[], Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2 && args.length != 3) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource grammars[] = null;
    String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    try {
        report.start();
        // Get inputstream for instance document
        instance = Shared.getStreamSource(args[0].itemAt(0), context);
        // Validate using resource speciefied in second parameter
        grammars = Shared.getStreamSource(args[1], context);
        // Check input
        for (final StreamSource grammar : grammars) {
            final String grammarUrl = grammar.getSystemId();
            if (grammarUrl != null && !grammarUrl.endsWith(".xsd") && !grammarUrl.endsWith(".rng")) {
                throw new XPathException("Only XML schemas (.xsd) and RELAXNG grammars (.rng) are supported" + ", depending on the used XML parser.");
            }
        }
        // Fetch third argument if available, and override defailt value
        if (args.length == 3) {
            schemaLang = args[2].getStringValue();
        }
        // Get language specific factory
        SchemaFactory factory = null;
        try {
            factory = SchemaFactory.newInstance(schemaLang);
        } catch (final IllegalArgumentException ex) {
            final String msg = "Schema language '" + schemaLang + "' is not supported. " + ex.getMessage();
            LOG.error(msg);
            throw new XPathException(msg);
        }
        // Create grammar
        final Schema schema = factory.newSchema(grammars);
        // Setup validator
        final Validator validator = schema.newValidator();
        validator.setErrorHandler(report);
        // Perform validation
        validator.validate(instance);
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeStreamSource(instance);
        Shared.closeStreamSources(grammars);
    }
    // Create response
    if (isCalledAs("jaxv")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxv-report") */
    {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final NodeImpl result = Shared.writeReport(report, builder);
        return result;
    }
}
Example 91
Project: amalia-model-master  File: XmlModelDeserializer.java View source code
public void validate() throws ModelException {
    try {
        Source schemaFile = new StreamSource(getClass().getResourceAsStream(AmaliaConstants.getXMLSchema()));
        Source xmlFile;
        if (isReaderUsed()) {
            xmlFile = new StreamSource(getReader());
        } else if (isStreamUsed()) {
            xmlFile = new StreamSource(getStream());
        } else {
            throw new ModelException("No XML source is set");
        }
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
    } catch (SAXException e) {
        throw new ModelException(e);
    } catch (IOException e) {
        throw new ModelException(e);
    }
}
Example 92
Project: android-platform_sdk-master  File: LayoutDevicesXsd.java View source code
/** Helper method that returns a {@link Validator} for our XSD */
public static Validator getValidator(ErrorHandler handler) throws SAXException {
    InputStream xsdStream = getXsdStream();
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new StreamSource(xsdStream));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    return validator;
}
Example 93
Project: Carolina-Digital-Repository-master  File: AbstractMETS2N3BagJob.java View source code
protected void validateMETS() {
    if (!getMETSFile().exists()) {
        failJob("Cannot find a METS file", "A METS was not found in the expected locations: mets.xml, METS.xml, METS.XML.");
    }
    Validator metsValidator = getMetsSipSchema().newValidator();
    METSParseException handler = new METSParseException("There was a problem parsing METS XML.");
    metsValidator.setErrorHandler(handler);
    try {
        metsValidator.validate(new StreamSource(getMETSFile()));
    } catch (SAXException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        failJob(handler, "METS is not valid with respect to schemas.");
    } catch (IOException e) {
        failJob(e, "Cannot parse METS file.");
    }
    recordDepositEvent(Type.VALIDATION, "METS schema(s) validated");
}
Example 94
Project: ccr-importer-master  File: CCRValidator.java View source code
//    private Document parseStreamSource(StreamSource source, boolean validating) {
//        try {
//            // Create a builder factory
//            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            factory.setValidating(validating);
//            // need to be namespace aware for JAXB to be able to unmarshal DOM
//            factory.setNamespaceAware(true);
//            // Create the builder and parse the file
//            Document doc = factory.newDocumentBuilder().parse(new InputSource(source.getReader()));
//            return doc;
//        } catch (ParserConfigurationException ex) {
//            Logger.getLogger(Evaluator.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (SAXException ex) {
//            Logger.getLogger(Evaluator.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(Evaluator.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        return null;
//    }
private void setupValidator() {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL xsdURL = this.getClass().getClassLoader().getResource(config.getCcrXSDLocation());
        File xsdFile = null;
        xsdFile = new File(xsdURL.toURI());
        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(xsdFile);
        Schema schema = sf.newSchema(schemaFile);
        // create a Validator instance, which can be used to validate an instance document
        validator = schema.newValidator();
        eHandler = new ValidatonErrorHandler();
        validator.setErrorHandler(eHandler);
    } catch (SAXException ex) {
        Logger.getLogger(Evaluator.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(Evaluator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Example 95
Project: cdi-tck-master  File: EjbJarDescriptorBuilderTest.java View source code
@Test
public void testDescriptorIsValid() throws ParserConfigurationException, SAXException, DescriptorExportException, IOException {
    EjbJarDescriptor ejbJarDescriptor = new EjbJarDescriptorBuilder().messageDrivenBeans(newMessageDriven("TestQueue", QueueMessageDrivenBean.class.getName()).addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge").addActivationConfigProperty("destinationType", "javax.jms.Queue").addActivationConfigProperty("destinationLookup", "test_queue"), newMessageDriven("TestTopic", TopicMessageDrivenBean.class.getName()).addActivationConfigProperty("acknowledgeMode", "Auto-acknowledge").addActivationConfigProperty("destinationType", "javax.jms.Topic").addActivationConfigProperty("destinationLookup", "test_topic")).build();
    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) {
            try {
                if (systemId.startsWith("http")) {
                    // Ugly workaround for xml.xsd
                    systemId = StringUtils.substringAfterLast(systemId, "/");
                }
                return new Input(publicId, systemId, new FileInputStream(new File("src/test/resources/xsd", systemId)));
            } catch (FileNotFoundException e) {
                throw new IllegalStateException();
            }
        }
    });
    schemaFactory.setErrorHandler(new ErrorHandler() {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    Source schemaFile = new StreamSource(new FileInputStream(new File("src/test/resources/xsd", "ejb-jar_3_1.xsd")));
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(new ByteArrayInputStream(ejbJarDescriptor.exportAsString().getBytes())));
}
Example 96
Project: droolsjbpm-master  File: XsdDOMValidator.java View source code
/**
     * Validate the document against the namespaces referenced in it.
     * @throws SAXException Validation error.
     * @throws IOException Error reading the XSD Sources.
     */
public void validate() throws SAXException, IOException {
    // Using the namespace URI list, create the XSD Source array used to
    // create the merged Schema instance...
    Source[] xsdSources = new Source[namespaces.size()];
    for (int i = 0; i < namespaces.size(); i++) {
        xsdSources[i] = getNamespaceSource(namespaces.get(i));
    }
    // Create the merged Schema instance and from that, create the Validator instance...
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(xsdSources);
    Validator validator = schema.newValidator();
    // Validate the document...
    validator.validate(new DOMSource(document));
}
Example 97
Project: effektif-master  File: Bpmn.java View source code
/**
   * Performs XML schema validation on the given XML using the BPMN 2.0 schema.
   *
   * @throws BpmnSchemaValidationError if the document is not valid BPMN 2.0
   */
public static void validateSchema(String bpmnDocument) {
    InputStream schemaStream = Bpmn.class.getResourceAsStream("/xsd/BPMN20.xsd");
    Source schemaSource = new StreamSource(new BufferedReader(new InputStreamReader(schemaStream)));
    Source xml = new StreamSource(new StringReader(bpmnDocument));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(new ClasspathResourceResolver("xsd/"));
    Schema schema = null;
    try {
        schema = schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        log.error("Error parsing schema:\n" + schemaSource.toString(), e);
        throw new RuntimeException("Error parsing schema: " + e.getMessage());
    }
    try {
        Validator validator = schema.newValidator();
        validator.validate(xml);
    } catch (SAXException e) {
        throw new BpmnSchemaValidationError(e);
    } catch (IOException e) {
        throw new RuntimeException("IOException during BPMN XML validation: " + e.getMessage());
    }
}
Example 98
Project: etm-api-master  File: XmlValidator.java View source code
/**
     * Creates schema factory, opens schema file and initializes schema rulesConfigValidator.
     *
     * @param schemaFileName XSD schema file name.
     * @return validator object.
     * @throws org.xml.sax.SAXException when parser error occurs.
     * @throws java.io.IOException when IO error occurs.
     */
private Validator initValidator(String schemaFileName) throws SAXException, IOException {
    InputStream is = null;
    try {
        SchemaFactory factory = SchemaFactory.newInstance(W3_ORG_XMLSCHEMA);
        is = getClass().getResourceAsStream(schemaFileName);
        Source source = new StreamSource(is);
        Schema schema = factory.newSchema(source);
        return schema.newValidator();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
Example 99
Project: federation-master  File: JAXPValidationUtil.java View source code
public static Validator validator() throws SAXException, IOException {
    SystemPropertiesUtil.ensure();
    if (validator == null) {
        Schema schema = getSchema();
        if (schema == null)
            throw logger.nullValueError("schema");
        validator = schema.newValidator();
        validator.setErrorHandler(new CustomErrorHandler());
    }
    return validator;
}
Example 100
Project: fop-master  File: AbstractIFTest.java View source code
@Override
protected void validate(Document doc) throws SAXException, IOException {
    if (IF_SCHEMA == null) {
        //skip validation;
        return;
    }
    Validator validator = IF_SCHEMA.newValidator();
    validator.setErrorHandler(new ErrorHandler() {

        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

        public void warning(SAXParseException exception) throws SAXException {
        //ignore
        }
    });
    validator.validate(new DOMSource(doc));
}
Example 101
Project: hazelcast-archive-master  File: XMLConfigBuilderTest.java View source code
private void testXSDConfigXML(String xmlResource) throws SAXException, IOException {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    URL schemaUrl = XMLConfigBuilderTest.class.getClassLoader().getResource("hazelcast-config-2.0.xsd");
    URL xmlURL = XMLConfigBuilderTest.class.getClassLoader().getResource(xmlResource);
    File schemaFile = new File(schemaUrl.getFile());
    File defaultXML = new File(xmlURL.getFile());
    Schema schema = factory.newSchema(schemaFile);
    Validator validator = schema.newValidator();
    Source source = new StreamSource(defaultXML);
    try {
        validator.validate(source);
    } catch (SAXException ex) {
        fail(defaultXML + " is not valid because: " + ex.getMessage());
        ex.printStackTrace();
    }
}