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

The following examples show how to use javax.xml.validation.Validator#setErrorHandler() . 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: SchemaHandler.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Validates the given XML document against the compiled schema.
 * @param xml instance document to be validated.
 * @return true if the xml is a valid instance of the schema
 * @throws IllegalStateException if schema has not been compiled successfully
 */
public boolean validate(String xml) {
    if (! compiled) {
        throw new IllegalStateException("Schema must first have been successfully " +
                "compiled before validation can be performed.");
    }

    errorHandler.reset();
    exceptionMessage = null;

    try {
        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(stringToSource(xml));
        return errorHandler.isValid();
    }
    catch (Exception e) {
        exceptionMessage = "Validation failed with exception: " + e.getMessage();
        return false;
    }
}
 
Example 2
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 3
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 4
Source File: NdkMetadataHandler.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setMetadataAsXml(DescriptionMetadata<String> xmlData, String message, String typeRecord) throws DigitalObjectException {
    ModsDefinition mods;
    String modelId = handler.getModel().getPid();
    if (xmlData.getData() != null) {
        ValidationErrorHandler errHandler = new ValidationErrorHandler();
        try {
            String data = xmlData.getData();
            xmlData.setData(data);

            Validator validator = ModsUtils.getSchema().newValidator();
            validator.setErrorHandler(errHandler);
            validator.validate(new StreamSource(new StringReader(xmlData.getData())));
            checkValidation(errHandler, xmlData);
            mods = ModsUtils.unmarshalModsType(new StreamSource(new StringReader(xmlData.getData())));
        } catch (DataBindingException | SAXException | IOException ex) {
            checkValidation(errHandler, xmlData);
            throw new DigitalObjectValidationException(xmlData.getPid(),
                        xmlData.getBatchId(), ModsStreamEditor.DATASTREAM_ID, null, ex)
                    .addValidation("mods", ex.getMessage());
        }
    } else {
        mods = createDefault(modelId);
    }
    write(modelId, mods, xmlData, message, typeRecord);
}
 
Example 5
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 6
Source File: SourceGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Application readWadl() {
    Element wadlElement = readDocument(wadlPath);
    if (validateWadl) {
        final WadlValidationErrorHandler errorHandler = new WadlValidationErrorHandler();
        try {
            Schema s = SchemaHandler.createSchema(
                    Arrays.asList("classpath:/schemas/wsdl/xml.xsd", "classpath:/schemas/wadl/wadl.xsd"), null,
                    bus);
            Validator v = s.newValidator();
            v.setErrorHandler(errorHandler);
            v.validate(new DOMSource(wadlElement));
        } catch (Exception ex) {
            throw new ValidationException("WADL document can not be validated", ex);
        }
        if (errorHandler.isValidationFailed()) {
            throw new ValidationException("WADL document is not valid.");
        }
    }
    return new Application(wadlElement, wadlPath);
}
 
Example 7
Source File: SchemaValidationAction.java    From validator with Apache License 2.0 6 votes vote down vote up
private Result<Boolean, XMLSyntaxError> validate(final Bag results, final Scenario scenario) {
    log.debug("Validating document using scenario {}", scenario.getConfiguration().getName());
    final CollectingErrorEventHandler errorHandler = new CollectingErrorEventHandler();
    try ( final SourceProvider validateInput = resolveSource(results) ) {

        final Validator validator = this.factory.createValidator(scenario.getSchema());
        validator.setErrorHandler(errorHandler);
        validator.validate(validateInput.getSource());
        return new Result<>(!errorHandler.hasErrors(), errorHandler.getErrors());
    } catch (final SAXException | SaxonApiException | IOException e) {
        final String msg = String.format("Error processing schema validation for scenario %s", scenario.getConfiguration().getName());
        log.error(msg, e);
        results.addProcessingError(msg);
        return new Result<>(Boolean.FALSE);
    }
}
 
Example 8
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
@Override
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 9
Source File: SoapParser.java    From teamengine with Apache License 2.0 5 votes vote down vote up
/**
 * A method to validate the SOAP message received. The message is validated
 * against the propoer SOAP Schema (1.1 or 1.2 depending on the namespace of
 * the incoming message)
 * 
 * @param soapMessage
 *            the SOAP message to validate.
 * @param eh
 *            the error handler.
 * 
 * @author Simone Gianfranceschi
 */
private void validateSoapMessage(Document soapMessage, ErrorHandler eh)
        throws Exception {
    String namespace = soapMessage.getDocumentElement().getNamespaceURI();

    if (namespace == null) {
        throw new Exception(
                "Error: SOAP message cannot be validated. The returned response may be an HTML response: "
                        + DomUtils.serializeNode(soapMessage));
    }

    // Create SOAP validator
    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema soap_schema = null;
    if (namespace.equals(SOAP_12_NAMESPACE)) {
        soap_schema = sf.newSchema(Misc
                .getResourceAsFile("com/occamlab/te/schemas/soap12.xsd"));
    } else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{
        soap_schema = sf.newSchema(Misc
                .getResourceAsFile("com/occamlab/te/schemas/soap11.xsd"));
    }

    Validator soap_validator = soap_schema.newValidator();
    soap_validator.setErrorHandler(eh);
    soap_validator.validate(new DOMSource(soapMessage));
}
 
Example 10
Source File: PerDiemXmlInputFileType.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.kfs.sys.batch.XmlBatchInputFileTypeBase#validateContentsAgainstSchema(java.lang.String, java.io.InputStream)
 */
@Override
protected void validateContentsAgainstSchema(String schemaLocation, InputStream fileContents) throws ParseException {

    try {
        // get schemaFile
        UrlResource schemaResource = new UrlResource(schemaLocation);

        // load a WXS schema, represented by a Schema instance
        Source schemaSource = new StreamSource(schemaResource.getInputStream());

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(schemaSource);

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

        Source source = this.transform(fileContents);
        validator.validate(source);
    }
    catch (MalformedURLException e2) {
        LOG.error("error getting schema url: " + e2.getMessage());
        throw new RuntimeException("error getting schema url:  " + e2.getMessage(), e2);
    }
    catch (SAXException e) {
        LOG.error("error encountered while parsing xml " + e.getMessage());
        throw new ParseException("Schema validation error occured while processing file: " + e.getMessage(), e);
    }
    catch (IOException e1) {
        LOG.error("error occured while validating file contents: " + e1.getMessage());
        throw new RuntimeException("error occurred while validating file contents: " + e1.getMessage(), e1);
    }
}
 
Example 11
Source File: Bug4966254.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Validator getValidator() throws SAXException {
    Schema s = getSchema();
    Validator v = s.newValidator();
    Assert.assertNotNull(v);
    v.setErrorHandler(new DraconianErrorHandler());
    return v;
}
 
Example 12
Source File: PolizasPeriodov11.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 13
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 14
Source File: BalanzaComprobacionv11.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 15
Source File: RuleToXmlConverterTest.java    From yare with MIT License 5 votes vote down vote up
@Test
void shouldCheckValidRuleAgainstSchema() throws Exception {
    // given
    RuleSer ruleObject = TestRuleFactory.constructValidRuleWithBuildInObjectTypes();

    JAXBContext jc = JAXBContext.newInstance(RuleSer.class, TestRuleFactory.Isbn.class);
    JAXBSource source = new JAXBSource(jc, objectFactory.createRule(ruleObject));
    Validator validator = getSchema().newValidator();
    validator.setErrorHandler(new ThrowingErrorHandler());

    // when / then
    validator.validate(source);
}
 
Example 16
Source File: SchemaCache.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to get the validator for a given schema using the error
 * handler provided in the constructor.
 *
 * @param aSchema
 *        The schema for which the validator is to be retrieved. May not be
 *        <code>null</code>.
 * @return The validator and never <code>null</code>.
 */
@Nonnull
public final Validator getValidatorFromSchema (@Nonnull final Schema aSchema)
{
  ValueEnforcer.notNull (aSchema, "Schema");

  final Validator aValidator = aSchema.newValidator ();
  aValidator.setErrorHandler (m_aSchemaFactory.getErrorHandler ());
  return aValidator;
}
 
Example 17
Source File: XmlParser.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public static void parse(XMLEventReader reader, Resource schemaResource, ObjectReadyNotifier notifier) throws SAXException, IOException, XMLStreamException {
    XmlParser parser = new XmlParser(reader, notifier);

    SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = SCHEMA_FACTORY.newSchema(schemaResource.getURL());
    Validator validator = schema.newValidator();
    validator.setErrorHandler(parser);
    validator.validate(new StAXSource(parser));
}
 
Example 18
Source File: CFDv3.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
@Override
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 19
Source File: RuleToXmlConverterTest.java    From yare with MIT License 5 votes vote down vote up
@Test
void shouldCheckInvalidRuleAgainstSchema() throws Exception {
    // given
    Rule ruleObject = TestRuleFactory.constructInvalidRule();

    JAXBContext jc = JAXBContext.newInstance(Rule.class);
    JAXBSource source = new JAXBSource(jc, objectFactory.createRule(toXmlConverter.map(ruleObject)));
    Validator validator = getSchema().newValidator();
    validator.setErrorHandler(new ThrowingErrorHandler());

    // when
    assertThatThrownBy(() -> validator.validate(source))
            // then
            .isInstanceOf(SAXParseException.class);
}
 
Example 20
Source File: XMLValidatingParser.java    From teamengine with Apache License 2.0 4 votes vote down vote up
/**
 * Validates an XML resource against a list of XML Schemas. Validation
 * errors are reported to the given handler.
 * 
 * @param doc
 *            The input Document node.
 * @param xsdList
 *            A list of XML schema references. Must be non-null, but if
 *            empty, validation will be performed by using location hints
 *            found in the input document.
 * @param errHandler
 *            An ErrorHandler that collects validation errors.
 * @throws SAXException
 *             If a schema cannot be read for some reason.
 * @throws IOException
 *             If an I/O error occurs.
 */
void validateAgainstXMLSchemaList(Document doc, List<SchemaSupplier> xsdList,
		ErrorHandler errHandler) throws SAXException, IOException {
	jlogger.fine("Validating XML resource from " + doc.getDocumentURI()
		+ " with these specified schemas: " + xsdList);
	Schema schema;
	if (!xsdList.isEmpty()) {
		schema = schemaLoader.loadSchema(ImmutableList.copyOf(xsdList));
	} else {
		schema = schemaLoader.defaultSchema();
	}
	Validator validator = schema.newValidator();
	validator.setErrorHandler(errHandler);
	DOMSource source = new DOMSource(doc, doc.getBaseURI());
	validator.validate(source);
}