javax.xml.validation.Validator Java Examples

The following examples show how to use javax.xml.validation.Validator. 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: 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 #2
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 #3
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 #4
Source File: AddonsListFetcher.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 SdkAddonsListConstants#getXsdStream(int)}
 */
private Validator getValidator(int version) throws SAXException {
    InputStream xsdStream = SdkAddonsListConstants.getXsdStream(version);
    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;
}
 
Example #5
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 #6
Source File: WriteTestSuiteResultTest.java    From allure1 with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidCharacterTest() throws Exception {
    TestSuiteResult testSuiteResult = new TestSuiteResult()
            .withName("somename");

    String titleWithInvalidXmlCharacter = String.valueOf(Character.toChars(0x0));
    testSuiteResult.setTitle(titleWithInvalidXmlCharacter);

    AllureResultsUtils.writeTestSuiteResult(testSuiteResult);

    Validator validator = AllureModelUtils.getAllureSchemaValidator();

    for (File each : listTestSuiteFiles(resultsDirectory)) {
        validator.validate(new StreamSource(each));
    }
}
 
Example #7
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 #8
Source File: Bug6941169Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testValidation_SAX_withServiceMech() {
    System.out.println("Validation using SAX Source. Using service mechnism (by default) to find SAX Impl:");
    InputSource is = new InputSource(Bug6941169Test.class.getResourceAsStream("Bug6941169.xml"));
    SAXSource ss = new SAXSource(is);
    setSystemProperty(SAX_FACTORY_ID, "MySAXFactoryImpl");
    long start = System.currentTimeMillis();
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(_xsd));
        Validator validator = schema.newValidator();
        validator.validate(ss, null);
        Assert.fail("User impl MySAXFactoryImpl should be used.");
    } catch (Exception e) {
        String error = e.getMessage();
        if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
            // expected
        }
        // System.out.println(e.getMessage());

    }
    long end = System.currentTimeMillis();
    double elapsedTime = ((end - start));
    System.out.println("Time elapsed: " + elapsedTime);
    clearSystemProperty(SAX_FACTORY_ID);
}
 
Example #9
Source File: DynFormValidator.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean validateAgainstSchema(DynFormField input, String value) {
    try {
        _errorHandler.reset();
        Schema schema = _factory.newSchema(getInputSchema(input));
        if (_errorHandler.isValid()) {
            Validator validator = schema.newValidator();
            validator.setErrorHandler(_errorHandler);
            validator.validate(getInputValueAsXML(input, value));
            if (! _errorHandler.isValid()) addErrorMessage(input, value);
            return _errorHandler.isValid();
        }
    }
    catch (SAXException se) {
        if (_msgPanel != null) _msgPanel.error(se.getMessage());
        se.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example #10
Source File: EReportingHeaderEncoderTest.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private void xmlValidation(ByteArrayOutputStream baos)
        throws XMLStreamException, OwsExceptionReport, IOException,
               SAXException, MalformedURLException {
    ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
    URL schemaFile = new URL(AqdConstants.NS_AQD_SCHEMA);
    Source xmlFile = new StreamSource(in);
    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) {
        Assertions.fail(e.getLocalizedMessage());
    }
}
 
Example #11
Source File: AbstractXMLConfigFactory.java    From Octopus with MIT License 6 votes vote down vote up
protected void validateXML(Source source, String schemaUri) throws Exception {
    is.reset();
    SchemaFactory schemaFactory = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    if (StringUtils.isEmpty(schemaUri)) {
        //default use xsd in this jar
        schema = schemaFactory.newSchema(new StreamSource(this.getClass().getClassLoader().getResourceAsStream("octopus.xsd")));
    } else {
        if (schemaUri.startsWith("http:") || schemaUri.startsWith("https:")) {
            schema = schemaFactory.newSchema(new URL(schemaUri));
        } else if (schemaUri.startsWith("file:")) {
            schema = schemaFactory.newSchema(new File(schemaUri));
        } else {
            schema = schemaFactory.newSchema(new StreamSource(this.getClass().getClassLoader().getResourceAsStream(schemaUri)));
        }
    }
    Validator validator = schema.newValidator();
    validator.validate(source);
    is.reset();
}
 
Example #12
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 #13
Source File: XmlCharDataGenerator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
protected void validate(Document doc) throws DataGeneratorException {
  try {
    Validator validator = getSchema().newValidator();
    validator.validate(new DOMSource(doc));
  } catch (Exception ex) {
    throw new DataGeneratorException(Errors.XML_GENERATOR_02, ex);
  }
}
 
Example #14
Source File: BrokerShareResultAssemblerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void serialize() throws Exception {
    // given
    BrokerRevenueShareResult result = brokerShareAssembler.build(
            BROKER_KEY, PERIOD_START_TIME, PERIOD_END_TIME);
    result.calculateAllShares();

    // when
    JAXBContext jc = JAXBContext
            .newInstance(BrokerRevenueShareResult.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshaller.marshal(result, bos);
    assertNotNull(bos.toByteArray());
    printXml(bos);

    final List<String> fragments = new ArrayList<String>();
    fragments.add(new String(bos.toByteArray(), "UTF-8"));

    byte[] xmlBytes = XMLConverter.combine("RevenueSharesResults",
            fragments, BrokerRevenueShareResult.SCHEMA);
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    bos1.write(xmlBytes);
    System.out.println(new String(bos1.toByteArray()));

    SchemaFactory schemaFactory = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = BillingServiceBean.class.getResource("/"
            + "BrokerRevenueShareResult.xsd");
    Schema schema = schemaFactory.newSchema(schemaUrl);

    Source xmlFile = new StreamSource(new ByteArrayInputStream(xmlBytes));
    Validator validator = schema.newValidator();
    validator.validate(xmlFile);

}
 
Example #15
Source File: XsdCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String validateAgainstXSD(InputStream xml, InputStream xsd, String checkUrl, String xsdFile) {
	try {
		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema = factory.newSchema(new StreamSource(xsd));
		Validator validator = schema.newValidator();
		validator.validate(new StreamSource(xml));
		return null;
	} catch (Exception ex) {
		return checkUrl + " doesn't match this XSD: " + xsdFile + ", error message: " + ex.getMessage();
	}
}
 
Example #16
Source File: ResellerShareResultAssemblerTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void serialize() throws Exception {
    // given
    ResellerRevenueShareResult result = resellerShareAssembler.build(
            RESELLER_KEY, PERIOD_START_TIME, PERIOD_END_TIME);
    result.calculateAllShares();

    // when
    JAXBContext jc = JAXBContext
            .newInstance(ResellerRevenueShareResult.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshaller.marshal(result, bos);
    assertNotNull(bos.toByteArray());
    printXml(bos);

    final List<String> fragments = new ArrayList<String>();
    fragments.add(new String(bos.toByteArray(), "UTF-8"));

    byte[] xmlBytes = XMLConverter.combine("RevenueSharesResults",
            fragments, ResellerRevenueShareResult.SCHEMA);
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    bos1.write(xmlBytes);
    System.out.println(new String(bos1.toByteArray()));

    SchemaFactory schemaFactory = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = BillingServiceBean.class.getResource("/"
            + "ResellerRevenueShareResult.xsd");
    Schema schema = schemaFactory.newSchema(schemaUrl);

    Source xmlFile = new StreamSource(new ByteArrayInputStream(xmlBytes));
    Validator validator = schema.newValidator();
    validator.validate(xmlFile);

}
 
Example #17
Source File: SerializationTest.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
private void validateMap(String name) throws Exception {
    try {
        Validator mapValidator = buildValidator("schema/data/data-savedGame.xsd");

        FreeColSavegameFile mapFile = new FreeColSavegameFile(new File(name));

        mapValidator.validate(new StreamSource(mapFile.getSavegameInputStream()));
    } catch (SAXParseException e) {
        String errMsg = e.getMessage()
            + " at line=" + e.getLineNumber()
            + " column=" + e.getColumnNumber();
        fail(errMsg);
    }
}
 
Example #18
Source File: StaxParserUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void validate(InputStream doc, InputStream sch) throws ParsingException {
    try {
        XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(doc);
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(sch));
        Validator validator = schema.newValidator();
        StAXSource stAXSource = new StAXSource(xmlEventReader);
        validator.validate(stAXSource);
    } catch (Exception e) {
        throw logger.parserException(e);
    }

}
 
Example #19
Source File: IoTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static void validateXmlAgainstGraphMLXsd(final File file) throws Exception {
    final Source xmlFile = new StreamSource(file);
    final SchemaFactory schemaFactory = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(new StreamSource(getResourceAsStream(GraphMLResourceAccess.class, "graphml-1.1.xsd")));
    final Validator validator = schema.newValidator();
    validator.validate(xmlFile);
}
 
Example #20
Source File: StrictRelativeResolvingStrategy.java    From validator with Apache License 2.0 5 votes vote down vote up
@Override
public Validator createValidator(final Schema schema) {
    if (schema == null) {
        throw new IllegalArgumentException("No schema supplied. Can not create validator");
    }
    forceOpenJdkXmlImplementation();
    final Validator validator = schema.newValidator();
    disableExternalEntities(validator);
    allowExternalSchema(validator, "file" /* allow nothing external */);
    return validator;

}
 
Example #21
Source File: GpxUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static Validator getSchemaValidator(final URL schemaUrl) {
  final SchemaFactory schemaFactory =
      SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema;
  try {
    schema = schemaFactory.newSchema(schemaUrl);

    return schema.newValidator();
  } catch (final SAXException e) {
    LOGGER.warn("Unable to read schema '" + schemaUrl.toString() + "'", e);
  }
  return null;
}
 
Example #22
Source File: ValidatorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class)
public void testGetNullFeature() throws SAXNotRecognizedException, SAXNotSupportedException {
    Validator validator = getValidator();
    assertNotNull(validator);
    validator.getFeature(null);

}
 
Example #23
Source File: ValidationWarningsTest.java    From hottub 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 #24
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 #25
Source File: ValidationWarningsTest.java    From openjdk-jdk8u 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 #26
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 #27
Source File: CR6708840Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * refer to http://forums.java.net/jive/thread.jspa?threadID=41626&tstart=0
 */
@Test
public final void testStAX() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        schemaValidator.validate(staxSrc);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (NullPointerException ne) {
        Assert.fail("NullPointerException when result is not specified.");
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #28
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 #29
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 #30
Source File: CR6708840Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * workaround before the fix: provide a result
 */
@Test
public final void testStAXWResult() {
    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();

        // XMLStreamReader staxReader =
        // xmlif.createXMLStreamReader((Source)new
        // StreamSource(getClass().getResource("Forum31576.xml").getFile()));
        XMLStreamReader staxReader = xmlif.createXMLStreamReader(this.getClass().getResourceAsStream("gMonths.xml"));

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schemaGrammar = schemaFactory.newSchema(new File(getClass().getResource("gMonths.xsd").getFile()));

        Validator schemaValidator = schemaGrammar.newValidator();

        Source staxSrc = new StAXSource(staxReader);
        File resultFile = new File(USER_DIR + "gMonths.result.xml");
        if (resultFile.exists()) {
            resultFile.delete();
        }

        Result xmlResult = new javax.xml.transform.stax.StAXResult(XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter(resultFile)));
        schemaValidator.validate(staxSrc, xmlResult);

        while (staxReader.hasNext()) {
            int eventType = staxReader.next();
            System.out.println("Event of type: " + eventType);
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }
}