Java Code Examples for javax.xml.validation.Schema#newValidator()

The following examples show how to use javax.xml.validation.Schema#newValidator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AdeUtilMain.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
protected void validateGood(File file) throws IOException, SAXException,
		AdeException {
	System.out.println("Starting");

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

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

	try {
		val.validate(streamSource);
	} catch (SAXParseException e) {
		System.out.println(e);
		throw e;
	}
	System.out.println("SUCCESS!");
}
 
Example 2
Source File: ValidatorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));

        // Get a Validator which can be used to validate instance document
        // against this grammar.
        Validator validator = schema.newValidator();
        ErrorHandler eh = new ErrorHandlerImpl();
        validator.setErrorHandler(eh);

        // Validate this instance document against the
        // Instance document supplied
        validator.validate(src, result);
    } catch (Exception ex) {
        throw ex;
    }
}
 
Example 3
Source File: SdkStats.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Helper method that returns a validator for our XSD, or null if the current Java
 * implementation can't process XSD schemas.
 *
 * @param version The version of the XML Schema.
 *        See {@link SdkStatsConstants#getXsdStream(int)}
 */
private Validator getValidator(int version) throws SAXException {
    InputStream xsdStream = SdkStatsConstants.getXsdStream(version);
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        if (factory == null) {
            return null;
        }

        // This may throw a SAX Exception if the schema itself is not a valid XSD
        Schema schema = factory.newSchema(new StreamSource(xsdStream));

        Validator validator = schema == null ? null : schema.newValidator();

        return validator;
    } finally {
        if (xsdStream != null) {
            try {
                xsdStream.close();
            } catch (IOException ignore) {}
        }
    }
}
 
Example 4
Source File: Configuration.java    From claw-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Validate the configuration file with the XSD schema.
 *
 * @param document XML Document.
 * @param xsd      File representing the XSD schema.
 * @throws SAXException If configuration file is not valid.
 * @throws IOException  If schema is not found.
 */
private void validate(Document document, File xsd)
    throws SAXException, IOException
{
  SchemaFactory factory =
      SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Source schemaFile = new StreamSource(xsd);
  Schema schema = factory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(new DOMSource(document));
}
 
Example 5
Source File: GraphMlTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void validate() throws Exception {
  GraphMl graphMl = creategraphml();
  JAXBContext jc = new GraphMlContext().getJaxbContext();
  JAXBSource source = new JAXBSource(jc, graphMl);

  SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema = sf.newSchema(new URL("http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"));

  Validator validator = schema.newValidator();
  validator.setErrorHandler(new GraphErrorHandler());
  validator.validate(source);
}
 
Example 6
Source File: CaptureOperationsModule.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Validates the given document against the given schema.
 */
private void validateDocument(Document document, Schema schema) throws SAXException, IOException {
    if (schema != null) {
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
        LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
    } else {
        LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
    }
}
 
Example 7
Source File: XMLUtils.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Validator getValidator() throws IOException, SAXException {
	if (validator == null) {
		SchemaFactory xmlSchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		File schemafile = new File(schemaFilePathName);
		int idx = schemaFilePathName.lastIndexOf(schemafile.getName());
		String path = schemaFilePathName.substring(0, idx);
		xmlSchemaFactory.setResourceResolver(new XMLUtils().new ResourceResolver(path));
		Reader reader = new StringReader(convertSchemaToString(schemaFilePathName));
		Schema schema = xmlSchemaFactory.newSchema(new StreamSource(reader));
		validator = schema.newValidator();
	}
	return validator;
}
 
Example 8
Source File: TFDv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(getClass().getResource(XSD));
    Validator validator = schema.newValidator();
    if (handler != null) {
        validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(CONTEXT, tfd));
}
 
Example 9
Source File: ModuleConfigTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 10
Source File: HQMFProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
private boolean validateXML(Schema schema, String xml){    
    try {
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(xml)));
    } catch (IOException | SAXException e) {
        System.out.println("Exception: " + e.getMessage());
        return false;
    }
    return true;
}
 
Example 11
Source File: JAXPValidationUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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 12
Source File: ValidationWarningsTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
void doOneTestIteration() throws Exception {
    Source src = new StreamSource(new StringReader(xml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXSource xsdSource = new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes())));
    Schema schema = schemaFactory.newSchema(xsdSource);
    Validator v = schema.newValidator();
    v.validate(src);
}
 
Example 13
Source File: XmlCompactFileAsyncAppenderValidationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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 14
Source File: RepositoryValidator.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
private Document validateSchema(ErrorListener errorHandler)
    throws ParserConfigurationException, SAXException, IOException {
  // parse an XML document into a DOM tree
  final DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
  parserFactory.setNamespaceAware(true);
  parserFactory.setXIncludeAware(true);
  final DocumentBuilder parser = parserFactory.newDocumentBuilder();
  final Document document = parser.parse(inputStream);

  // create a SchemaFactory capable of understanding WXS schemas
  final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  final ResourceResolver resourceResolver = new ResourceResolver();
  factory.setResourceResolver(resourceResolver);

  // load a WXS schema, represented by a Schema instance
  final URL resourceUrl = this.getClass().getClassLoader().getResource("xsd/repository.xsd");
  final String path = resourceUrl.getPath();
  final String parentPath = path.substring(0, path.lastIndexOf('/'));
  final URL baseUrl = new URL(resourceUrl.getProtocol(), null, parentPath);
  resourceResolver.setBaseUrl(baseUrl);

  final Source schemaFile = new StreamSource(resourceUrl.openStream());
  final Schema schema = factory.newSchema(schemaFile);

  // create a Validator instance, which can be used to validate an instance document
  final Validator validator = schema.newValidator();

  validator.setErrorHandler(errorHandler);

  // validate the DOM tree
  validator.validate(new DOMSource(document));
  return document;
}
 
Example 15
Source File: ValidationWarningsTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void doOneTestIteration() throws Exception {
    Source src = new StreamSource(new StringReader(xml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXSource xsdSource = new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes())));
    Schema schema = schemaFactory.newSchema(xsdSource);
    Validator v = schema.newValidator();
    v.validate(src);
}
 
Example 16
Source File: ValueModelTest.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 * Test of validateXML method, of class ValueModel.
 */
@Test
public void test_ValidateXML() {
    //Test to see if the XML DOM tree is validated
    System.out.println("Testing ValueModel's validateXML(String xmlURI)");
    String xmlURI= System.getProperty("user.dir");
    xmlURI=xmlURI.concat(File.separator);
    xmlURI=xmlURI.concat("test_ValidateXML");
    ValueModel instance = new ValueModel();
    boolean expResult = false;
    boolean result = instance.validateXML(xmlURI);
    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setNamespaceAware(true);
        DocumentBuilder parser = dbFactory.newDocumentBuilder();
        Document document = parser.parse(xmlURI);
        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory =
                SchemaFactory.newInstance(
                XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(
                new URL(instance.getValueModelXMLSchemaURL()).openStream());
        Schema schema = schemaFactory.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(new DOMSource(document));
       }
        catch (ParserConfigurationException | SAXException | IOException ex) {
        result = ex instanceof UnknownHostException;
                                                                             }               
    assertEquals(expResult, result);
}
 
Example 17
Source File: XmlDataImporter.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void validate(InputStream inputStream) throws Exception {
   XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
   SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
   Schema schema = factory.newSchema(XmlDataImporter.findResource("schema/artemis-import-export.xsd"));

   Validator validator = schema.newValidator();
   validator.validate(new StAXSource(reader));
   reader.close();
}
 
Example 18
Source File: Utils.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static boolean validate(URL schemaURL, Source input)  {
	try {
		Schema schema = getSchemaFromResource(schemaURL);
		Validator validator = schema.newValidator();
		validator.setErrorHandler(getValidationErrorHandler("sax "));
		validator.validate(input);
		return true;
	} catch (Exception e) {
		//System.out.println("("+e.getClass().getName()+"): "+e.getMessage());
		return false;
	}
}
 
Example 19
Source File: SchemaValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
public boolean validate(InputSource wsdlsource, String[] schemas) throws ToolException {
    boolean isValid = false;
    Schema schema;
    try {
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        saxFactory.setFeature("http://xml.org/sax/features/namespaces", true);
        saxFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        saxParser = saxFactory.newSAXParser();

        if (defaultSchemas != null) {
            schemas = addSchemas(defaultSchemas, schemas);
            schema = createSchema(schemas);
        } else {
            schema = createSchema(schemaFromJar, schemas);
        }


        Validator validator = schema.newValidator();

        NewStackTraceErrorHandler errHandler = new NewStackTraceErrorHandler();
        validator.setErrorHandler(errHandler);
        SAXSource saxSource = new SAXSource(saxParser.getXMLReader(), wsdlsource);
        validator.validate(saxSource);


        if (!errHandler.isValid()) {
            throw new ToolException(errHandler.getErrorMessages());
        }

        isValid = true;

    } catch (IOException ioe) {
        throw new ToolException("Cannot get the wsdl " + wsdlsource.getSystemId(), ioe);
    } catch (SAXException saxEx) {
        throw new ToolException(saxEx);
    } catch (ParserConfigurationException e) {
        throw new ToolException(e);
    }
    return isValid;
}
 
Example 20
Source File: XSDValidator.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private XSDValidator(Schema schema) {
   this.validator = schema.newValidator();
   this.validator.setErrorHandler(new XSDErrorHandler());
}