Java Code Examples for javax.xml.validation.Validator#validate()

The following examples show how to use javax.xml.validation.Validator#validate() . 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: XMLSchemaValidationHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the passed XML against the passed XSD and put all errors in the
 * passed error list.
 *
 * @param aSchema
 *        The source XSD. May not be <code>null</code>.
 * @param aXML
 *        The XML to be validated. May not be <code>null</code>.
 * @param aErrorList
 *        The error list to be filled. May not be <code>null</code>.
 * @param aLocale
 *        The locale to use for error messages. May be <code>null</code> to
 *        use the system default locale.
 * @throws IllegalArgumentException
 *         If XSD validation failed with an exception
 * @since 9.0.1
 */
public static void validate (@Nonnull final Schema aSchema,
                             @Nonnull final Source aXML,
                             @Nonnull final ErrorList aErrorList,
                             @Nullable final Locale aLocale)
{
  ValueEnforcer.notNull (aSchema, "Schema");
  ValueEnforcer.notNull (aXML, "XML");
  ValueEnforcer.notNull (aErrorList, "ErrorList");

  // Build the validator
  final Validator aValidator = aSchema.newValidator ();
  if (aLocale != null)
    EXMLParserProperty.GENERAL_LOCALE.applyTo (aValidator, aLocale);
  aValidator.setErrorHandler (new WrappedCollectingSAXErrorHandler (aErrorList));
  try
  {
    aValidator.validate (aXML, null);
  }
  catch (final Exception ex)
  {
    // Most likely the input XML document is invalid
    throw new IllegalArgumentException ("Failed to validate the XML " + aXML + " against " + aSchema, ex);
  }
}
 
Example 2
Source File: ConfigReader.java    From bt with Apache License 2.0 6 votes vote down vote up
Document readFile(Path p) {
	Document document = null;
	try {
		// parse an XML document into a DOM tree
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder parser = factory.newDocumentBuilder();
		document = parser.parse(p.toFile());



		// 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 (SAXException | IOException | ParserConfigurationException e) {
		throw new ParseException(e);
	}

	return document;
}
 
Example 3
Source File: UserSession.java    From chipster with MIT License 6 votes vote down vote up
public static boolean validateMetadataFile() throws IOException, SAXException  {

        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(UserSession.class.getResourceAsStream("/session2.xsd")));
        Validator validator = schema.newValidator();
        
        try {
        	validator.validate(new StreamSource(UserSession.class.getResourceAsStream("/session.xml")));
            System.out.println("input is valid.");
        }
        catch (SAXException ex) {
            System.out.println("input is not valid because ");
            System.out.println(ex.getMessage());
            return false;
        }  
        return true;
        
    }
 
Example 4
Source File: cfXmlData.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Validates the specified Document against a ValidatorSource. The ValidatorSource
 * could represent a DTD or xml schema document. If a validation exception arises, it
 * will be thrown. However, if the customHandler is specified and it does not throw
 * error/warning exceptions, it may be the case that this method does not throw
 * validation exceptions.
 * 
 * @param doc
 *          Document to validate
 * @param validator
 *          ValidatorSource to validate against
 * @param customHandler
 *          custom ErrorHandler, or null
 * @throws IOException
 * @throws SAXException
 */
protected static void validateXml(Node node, ValidatorSource validator, ErrorHandler customHandler) throws IOException, SAXException {
	SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	if (customHandler == null)
		customHandler = new ValidationErrorHandler();
	fact.setErrorHandler(customHandler);
	Schema schema = null;

	// Either use the specified xml schema or assume the xml document
	// itself has xml schema location hints.
	if (validator.isEmptyString())
		schema = fact.newSchema();
	else
		schema = fact.newSchema(validator.getAsSource());

	// Validate it against xml schema
	Validator v = schema.newValidator();
	v.setErrorHandler(customHandler);
	v.validate(new DOMSource(node));
}
 
Example 5
Source File: StaxBasedConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the input file against a schema
 * @param configStream
 * @throws SAXException
 * @throws IOException
 */
public void schemaValidate(InputStream configStream) throws SAXException, IOException
{
   Validator validator = schemaValidator();
   Source xmlSource = new StreamSource(configStream);
   validator.validate(xmlSource);
}
 
Example 6
Source File: Bug6457662.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    final Schema sc = factory.newSchema(writeSchema());
    final Validator validator = sc.newValidator();
    validator.validate(new StreamSource(new StringReader(xml)));
    validator.validate(new StreamSource(new StringReader(xml)));
    validator.validate(new StreamSource(new StringReader(xml)));
    validator.validate(new StreamSource(new StringReader(xml)));
}
 
Example 7
Source File: AllureLifecycleTest.java    From allure1 with Apache License 2.0 5 votes vote down vote up
public void validateTestSuite() throws SAXException, IOException {
    Validator validator = AllureModelUtils.getAllureSchemaValidator();

    for (File each : listTestSuiteFiles(resultsDirectory)) {
        validator.validate(new StreamSource(each));
    }
}
 
Example 8
Source File: ModelValidator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the given xml document using the Java XML validation framework.
 * 
 * @param source The source object for the xml document
 * @throws DdlUtilsXMLException If the document could not be validated
 */
public void validate(Source source) throws DdlUtilsXMLException
{
    try {
        SchemaFactory factory   = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema        schema    = factory.newSchema(new StreamSource(getClass().getResourceAsStream("/database.xsd")));
        Validator     validator = schema.newValidator();

        validator.validate(source);
    }
    catch (Exception ex)
    {
        throw new DdlUtilsXMLException(ex);
    }
}
 
Example 9
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 10
Source File: DmnXMLConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void validateModel(InputStreamProvider inputStreamProvider) throws Exception {
    Schema schema;
    if (isDMN12(inputStreamProvider.getInputStream())) {
        schema = createSchema(DMN_XSD);
    } else {
        schema = createSchema(DMN_11_XSD);
    }

    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(inputStreamProvider.getInputStream()));
}
 
Example 11
Source File: AllureListenerXmlValidationTest.java    From allure1 with Apache License 2.0 5 votes vote down vote up
@Test
public void validateSuiteFilesTest() throws Exception {
    Validator validator = AllureModelUtils.getAllureSchemaValidator();

    for (File each : listTestSuiteFiles(resultsDirectory)) {
        validator.validate(new StreamSource(each));
    }
}
 
Example 12
Source File: SerializationTest.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
public void testValidation() throws Exception {
    Game game = ServerTestHelper.startServerGame(getTestMap(true));

    Colony colony = getStandardColony(6);
    Player player = game.getPlayerByNationId("model.nation.dutch");

    ServerTestHelper.newTurn();
    ServerTestHelper.newTurn();

    String serialized = null;
    try {
        Validator validator = buildValidator("schema/data/data-game.xsd");
        serialized = game.serialize();
        validator.validate(new StreamSource(new StringReader(serialized)));
    } catch (SAXParseException e) {
        int col = e.getColumnNumber();
        String errMsg = e.getMessage()
            + "\nAt line=" + e.getLineNumber()
            + ", column=" + col + ":\n";
        if (serialized != null) {
            errMsg += serialized.substring(Math.max(0, col - 100),
                                           Math.min(col + 100, serialized.length()));
        }
        fail(errMsg);
    }

    ServerTestHelper.stopServerGame();
}
 
Example 13
Source File: CatalogTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "supportLSResourceResolver1")
public void supportLSResourceResolver1(URI catalogFile, Source source) throws Exception {

    CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Validator validator = factory.newSchema().newValidator();
    validator.setResourceResolver(cr);
    validator.validate(source);
}
 
Example 14
Source File: BadXmlCharacterEscapeHandlerTest.java    From allure1 with Apache License 2.0 5 votes vote down vote up
@Test
public void dataWithInvalidCharacterTest() throws Exception {
    AllureResultsUtils.writeTestSuiteResult(result, testSuiteResultFile);

    Validator validator = AllureModelUtils.getAllureSchemaValidator();
    validator.validate(new StreamSource(testSuiteResultFile));

    TestSuiteResult testSuite = JAXB.unmarshal(testSuiteResultFile, TestSuiteResult.class);
    assertThat(testSuite.getName(), is("name-and-кириллицей-also"));
    assertTrue(testSuite.getTitle().startsWith("prefix "));
    assertTrue(testSuite.getTitle().endsWith(" suffix"));
}
 
Example 15
Source File: CuentasContablesv11.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);
	Source[] schemas = new Source[XSD.length];
	for (int i = 0; i < XSD.length; i++) {
		schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
	}
	Schema schema = sf.newSchema(schemas);
	Validator validator = schema.newValidator();
	if (handler != null) {
		validator.setErrorHandler(handler);
	}
	validator.validate(new JAXBSource(context, document));
}
 
Example 16
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 17
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check validation API features. A schema which is including in Bug 4909119
 * used to be testing for the functionalities.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/userDetails.xsd">userDetails.xsd</a>
 */
@Test
public void testGetOwnerInfo() throws Exception {
    String schemaFile = XML_DIR + "userDetails.xsd";
    String xmlFile = XML_DIR + "userDetails.xml";

    try(FileInputStream fis = new FileInputStream(xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());

        Validator validator = schema.newValidator();
        MyErrorHandler eh = new MyErrorHandler();
        validator.setErrorHandler(eh);

        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        docBuilder.setErrorHandler(eh);

        Document document = docBuilder.parse(fis);
        DOMResult dResult = new DOMResult();
        DOMSource domSource = new DOMSource(document);
        validator.validate(domSource, dResult);
        assertFalse(eh.isAnyError());
    }
}
 
Example 18
Source File: ValidationWarningsTest.java    From dragonwell8_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 19
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 20
Source File: XSDAbstractUtils.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * This method allows to validate an XML against the module-default XSD schema plus custom sources.
 *
 * @param xmlSource
 *                         the {@code Source}s to validate against (custom schemas)
 * @param schema
 *                         the used {@code Schema} to validate
 * @param secureValidation
 *                         enable/disable the secure validation (protection against XXE)
 */
public void validate(final Source xmlSource, final Schema schema, boolean secureValidation) throws SAXException, IOException {
	Validator validator = schema.newValidator();
	if (secureValidation) {
		XmlDefinerUtils.getInstance().configure(validator);
	}
	validator.validate(xmlSource);
}