javax.xml.validation.Schema Java Examples

The following examples show how to use javax.xml.validation.Schema. 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: SchemaXsdBasedValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
  protected void validate(Model model, Schema schema, XsdBasedValidator.Handler handler) {
      try {
          SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
          CatalogModel cm = (CatalogModel) model.getModelSource().getLookup()
.lookup(CatalogModel.class);
   if (cm != null) {
              sf.setResourceResolver(cm);
          }
          sf.setErrorHandler(handler);
          Source saxSource = getSource(model, handler);
          if (saxSource == null) {
              return;
          }
          sf.newSchema(saxSource);
      } catch(SAXException sax) {
          //already processed by handler
      } catch(Exception ex) {
          handler.logValidationErrors(Validator.ResultType.ERROR, ex.getMessage());
      }
  }
 
Example #2
Source File: ConversionService.java    From validator with Apache License 2.0 6 votes vote down vote up
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) {
    if (model == null) {
        throw new ConversionExeption("Can not serialize null");
    }
    try ( final StringWriter w = new StringWriter() ) {
        final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector();
        final Marshaller marshaller = getJaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setSchema(schema);
        marshaller.setEventHandler(handler);
        final XMLOutputFactory xof = XMLOutputFactory.newFactory();
        final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
        if (null == introspector.getElementName(model)) {
            final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
            marshaller.marshal(jaxbElement, xmlStreamWriter);
        } else {
            marshaller.marshal(model, xmlStreamWriter);
        }
        xmlStreamWriter.flush();
        return w.toString();
    } catch (final JAXBException | IOException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e);
    }
}
 
Example #3
Source File: XmlResultValidator.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
private void validateAgainstXsdSchema(AbbyyInput abbyyInput, String xml) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream xsdStream = getClass().getResourceAsStream(xsdSchemaPath);
    Schema schema = factory.newSchema(new StreamSource(xsdStream));
    Validator xmlValidator = schema.newValidator();

    xml = EncodingUtils.toUTF8(xml, abbyyInput.getResponseCharacterSet())
            .trim().replaceFirst("^([\\W]+)<", "<")
            .replaceFirst("(\\uFFFD)+$", ">")
            .replace("xmlns:xsi=\"@link\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");

    try {
        StringReader xmlReader = new StringReader(xml);
        xmlValidator.validate(new StreamSource(xmlReader));
    } catch (SAXException ex) {
        throw new ValidationException(ExceptionMsgs.RESPONSE_VALIDATION_ERROR + ex.getMessage());
    }
}
 
Example #4
Source File: SchemaXsdBasedValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected Schema getSchema(Model model) {
    if (! (model instanceof SchemaModel)) {
        return null;
    }
    
    // This will not be used as validate(.....) method is being overridden here.
    // So just return a schema returned by newSchema().
    if(schema == null) {
        try {
            schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema();
        } catch(SAXException ex) {
            assert false: "Error while creating compiled schema for"; //NOI18N
        }
    }
    return schema;
}
 
Example #5
Source File: IdentityProviderFactory.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();

    // load the users from the specified file
    if (loginIdentityProvidersConfigurationFile.exists()) {
        try {
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

            // attempt to unmarshal
            XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(loginIdentityProvidersConfigurationFile));
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<IdentityProviders> element = unmarshaller.unmarshal(xsr, IdentityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the login identity provider configuration file at: " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the login identity provider configuration file at " + loginIdentityProvidersConfigurationFile.getAbsolutePath());
    }
}
 
Example #6
Source File: ValidationExample.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Unmarshaller createUnmarshaller() throws JAXBException {
	Unmarshaller unmarshaller = super.createUnmarshaller();

	Schema schema;

	try {
		schema = JAXBUtil.getSchema();
	} catch(Exception e){
		throw new RuntimeException(e);
	}

	unmarshaller.setSchema(schema);
	unmarshaller.setEventHandler(new SimpleValidationEventHandler());

	return unmarshaller;
}
 
Example #7
Source File: GenericJAXBMarshaller.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * @param aClassLoader
 *        The class loader to be used for XML schema resolving. May be
 *        <code>null</code>.
 * @return The JAXB unmarshaller to use. Never <code>null</code>.
 * @throws JAXBException
 *         In case the creation fails.
 */
@Nonnull
private Unmarshaller _createUnmarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException
{
  final JAXBContext aJAXBContext = getJAXBContext (aClassLoader);

  // create an Unmarshaller
  final Unmarshaller aUnmarshaller = aJAXBContext.createUnmarshaller ();
  if (m_aVEHFactory != null)
  {
    // Create and set a new event handler
    final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aUnmarshaller.getEventHandler ());
    if (aEvHdl != null)
      aUnmarshaller.setEventHandler (aEvHdl);
  }

  // Set XSD (if any)
  final Schema aValidationSchema = createValidationSchema ();
  if (aValidationSchema != null)
    aUnmarshaller.setSchema (aValidationSchema);

  return aUnmarshaller;
}
 
Example #8
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 #9
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}
 
Example #10
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Unmarshaller createUnmarshaller(Class<?> cls, Type genericType, boolean isCollection)
    throws JAXBException {
    JAXBContext context = isCollection ? getCollectionContext(cls)
                                       : getJAXBContext(cls, genericType);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (validateInputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            unmarshaller.setSchema(theSchema);
        }
    }
    if (eventHandler != null) {
        unmarshaller.setEventHandler(eventHandler);
    }
    if (unmarshallerListener != null) {
        unmarshaller.setListener(unmarshallerListener);
    }
    if (uProperties != null) {
        for (Map.Entry<String, Object> entry : uProperties.entrySet()) {
            unmarshaller.setProperty(entry.getKey(), entry.getValue());
        }
    }
    return unmarshaller;
}
 
Example #11
Source File: XMLEncUtilsTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test() throws JAXBException, SAXException {
	JAXBContext jaxbContext = xmlEncUtils.getJAXBContext();
	assertNotNull(jaxbContext);

	Schema schema = xmlEncUtils.getSchema();
	assertNotNull(schema);
}
 
Example #12
Source File: Bug6964720Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(Bug6964720Test.class.getResourceAsStream("Bug6964720.xsd")));
        Assert.fail("should produce an error message");
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    }
}
 
Example #13
Source File: Bug7014246Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(Bug7014246Test.class.getResourceAsStream("Bug7014246.xsd")));
        Assert.fail("STATUS:Failed.The negative testcase unexpectedly passed.");
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
 
Example #14
Source File: AnyURITest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src", "."), XSDFILE));
        throw new RuntimeException("Illegal URI // should be rejected.");
    } catch (SAXException e) {
        //expected:
        //Enumeration value '//' is not in the value space of the base type, anyURI.
    }


}
 
Example #15
Source File: Bug4969732.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    StringReader reader = new StringReader(xsd);
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
 
Example #16
Source File: Bug4970402.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private ValidatorHandler createValidatorHandler(String xsd) throws SAXException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    StringReader reader = new StringReader(xsd);
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
 
Example #17
Source File: ChangeLogDeserializer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void validate(XMLStreamReader reader) throws XMLStreamException {
   try {
      Source source = new StreamSource(getClass().getClassLoader().getResourceAsStream(SCHEMA_LOCATION));
      Schema schema = schemaFactory.newSchema(source);
      Validator validator = schema.newValidator();
      validator.validate(new StAXSource(reader));
   } catch(Exception e) {
      throw new XMLStreamException(e);
   }
}
 
Example #18
Source File: XPathWhiteSpaceTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src", "."), XSDFILE));
    } catch (SAXException e) {
        throw new RuntimeException(e.getMessage());
    }


}
 
Example #19
Source File: AnyURITest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try{
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src", "."), XSDFILE));
        throw new RuntimeException("Illegal URI // should be rejected.");
    } catch (SAXException e) {
        //expected:
        //Enumeration value '//' is not in the value space of the base type, anyURI.
    }


}
 
Example #20
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 #21
Source File: WalkerData.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public void writeXml(int worldId) {
	Schema schema = null;
	SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

	try {
		schema = sf.newSchema(new File("./data/static_data/npc_walker/npc_walker.xsd"));
	}
	catch (SAXException e1) {
		log.error("Error while saving data: " + e1.getMessage(), e1.getCause());
		return;
	}

	File xml = new File("./data/static_data/npc_walker/walker_" + worldId + "_" + World.getInstance().getWorldMap(worldId).getName() + ".xml");
	JAXBContext jc;
	Marshaller marshaller;
	try {
		jc = JAXBContext.newInstance(WalkerData.class);
		marshaller = jc.createMarshaller();
		marshaller.setSchema(schema);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(this, xml);
	}
	catch (JAXBException e) {
		log.error("Error while saving data: " + e.getMessage(), e.getCause());
		return;
	}
}
 
Example #22
Source File: LargeMaxOccursTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testmgJ014() {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        String xsdFile = "mgJ014.xsd";
        Schema schema = sf.newSchema(new File(getClass().getResource(xsdFile).toURI()));
        Validator validator = schema.newValidator();
    } catch (Exception ex) {
        return; // expected
    }
    Assert.fail("Parser configuration error expected since maxOccurs > 5000 " + "and constant-space optimization does not apply");
}
 
Example #23
Source File: SchemaBuilderTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringLocation() {
    final SchemaBuilder builder = schema("myname").schemaLocation("simple.xsd");
    final Result<Pair<ValidateWithXmlSchema, Schema>, String> result = builder.build(Simple.createContentRepository());
    assertThat(result).isNotNull();
    assertThat(result.isValid()).isTrue();
}
 
Example #24
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 #25
Source File: XSDResourceTypeIdentifier.java    From cxf with Apache License 2.0 5 votes vote down vote up
public XSDResourceTypeIdentifier(Source xsd, ResourceTransformer resourceTransformer) {
    try {
        this.resourceTransformer = resourceTransformer;
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(xsd);
        this.validator = schema.newValidator();
    } catch (SAXException ex) {
        LOG.severe(ex.getLocalizedMessage());
        throw new SoapFault("Internal error", getSoapVersion().getReceiver());
    }
}
 
Example #26
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 #27
Source File: SchemaBuilder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the policy schema map. There are three schemas.
 *
 * @param configHolder holder EntitlementConfigHolder
 * @throws SAXException if fails
 */
public void buildPolicySchema() throws SAXException {

    if (!"true".equalsIgnoreCase((String) configHolder.getEngineProperties().get(
            EntitlementExtensionBuilder.PDP_SCHEMA_VALIDATION))) {
        log.warn("PDP schema validation disabled.");
        return;
    }

    String[] schemaNSs = new String[]{PDPConstants.XACML_1_POLICY_XMLNS,
            PDPConstants.XACML_2_POLICY_XMLNS,
            PDPConstants.XACML_3_POLICY_XMLNS};

    for (String schemaNS : schemaNSs) {

        String schemaFile;

        if (PDPConstants.XACML_1_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_1_POLICY_SCHEMA_FILE;
        } else if (PDPConstants.XACML_2_POLICY_XMLNS.equals(schemaNS)) {
            schemaFile = PDPConstants.XACML_2_POLICY_SCHEMA_FILE;
        } else {
            schemaFile = PDPConstants.XACML_3_POLICY_SCHEMA_FILE;
        }

        InputStream schemaFileStream = EntitlementExtensionBuilder.class.getResourceAsStream("/" + schemaFile);
        try{
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(new StreamSource(schemaFileStream));
            configHolder.getPolicySchemaMap().put(schemaNS, schema);
        } finally {
            IdentityIOStreamUtils.closeInputStream(schemaFileStream);
        }
    }
}
 
Example #28
Source File: Bug6941169Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testValidation_SAX_withoutServiceMech() {
    System.out.println("Validation using SAX Source;  Service mechnism is turned off;  SAX Impl should be the default:");
    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);
        factory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, false);
        Schema schema = factory.newSchema(new StreamSource(_xsd));
        Validator validator = schema.newValidator();
        validator.validate(ss, null);
    } catch (Exception e) {
        // e.printStackTrace();
        String error = e.getMessage();
        if (error.indexOf("javax.xml.parsers.FactoryConfigurationError: Provider MySAXFactoryImpl not found") > 0) {
            Assert.fail(e.getMessage());
        } else {
            System.out.println("Default impl is used");
        }

        // System.out.println(e.getMessage());

    }
    long end = System.currentTimeMillis();
    double elapsedTime = ((end - start));
    System.out.println("Time elapsed: " + elapsedTime);
    clearSystemProperty(SAX_FACTORY_ID);
}
 
Example #29
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validateObjectIfNeeded(Marshaller marshaller, Class<?> cls, Object obj)
    throws JAXBException {
    if (validateOutputIfPossible) {
        Schema theSchema = getSchema(cls);
        if (theSchema != null) {
            marshaller.setEventHandler(eventHandler);
            marshaller.setSchema(theSchema);
            if (validateBeforeWrite) {
                marshaller.marshal(obj, new DefaultHandler());
                marshaller.setSchema(null);
            }
        }
    }
}
 
Example #30
Source File: ScenarioBuilder.java    From validator with Apache License 2.0 5 votes vote down vote up
private void buildSchema(final ContentRepository repository, final List<String> errors, final Scenario scenario) {
    if (this.schemaBuilder == null) {
        errors.add("Must supply schema for validation");
    } else {
        final Result<Pair<ValidateWithXmlSchema, Schema>, String> result = this.schemaBuilder.build(repository);
        if (result.isValid()) {
            scenario.setSchema(result.getObject().getRight());
            scenario.getConfiguration().setValidateWithXmlSchema(result.getObject().getLeft());
        } else {
            errors.addAll(result.getErrors());
        }
    }
}