Java Code Examples for javax.xml.validation.SchemaFactory#newInstance()

The following examples show how to use javax.xml.validation.SchemaFactory#newInstance() . 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: XMLTools.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Validator getValidator(URI schemaURI) throws XMLException {
	if (schemaURI == null) {
		throw new NullPointerException("SchemaURL is null!");
	}
	synchronized (VALIDATORS) {
		if (VALIDATORS.containsKey(schemaURI)) {
			return VALIDATORS.get(schemaURI);
		} else {
			SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			Validator validator;
			try {
				validator = factory.newSchema(schemaURI.toURL()).newValidator();
			} catch (SAXException | MalformedURLException e) {
				throw new XMLException("Cannot parse XML schema: " + e.getMessage(), e);
			}
			VALIDATORS.put(schemaURI, validator);
			return validator;
		}
	}
}
 
Example 2
Source File: BillingDataRetrievalServiceBean.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
public Schema loadSchemaFiles() {
    try (InputStream brStream = ResourceLoader.getResourceAsStream(
            BillingDataRetrievalServiceBean.class, "BillingResult.xsd");
            InputStream localeStream = ResourceLoader.getResourceAsStream(
                    BillingDataRetrievalServiceBean.class, "Locale.xsd")) {

        URL billingResultUri = ResourceLoader.getResource(
                BillingDataRetrievalServiceBean.class, "BillingResult.xsd");
        URL localeUri = ResourceLoader.getResource(
                BillingDataRetrievalServiceBean.class, "Locale.xsd");
        SchemaFactory schemaFactory = SchemaFactory
                .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        StreamSource[] sourceDocuments = new StreamSource[] {
                new StreamSource(localeStream, localeUri.getPath()),
                new StreamSource(brStream, billingResultUri.getPath()) };
        return schemaFactory.newSchema(sourceDocuments);
    } catch (SAXException | IOException e) {
        throw new BillingRunFailed("Schema files couldn't be loaded", e);
    }
}
 
Example 3
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 4
Source File: MetsUtils.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}
 
Example 5
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 6
Source File: XmlConfigurationStrategy.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initializeSchemaValidation(DocumentBuilderFactory factory) throws SAXException {
    if (Boolean.getBoolean(Sejda.PERFORM_SCHEMA_VALIDATION_PROPERTY_NAME)) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(
                Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_SEJDA_CONFIG)) }));

        factory.setNamespaceAware(true);
    }
}
 
Example 7
Source File: ValidateXml.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void parseSchema(final ProcessContext context) throws IOException, SAXException {
    try {
        final File file = new File(context.getProperty(SCHEMA_FILE).getValue());
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(SCHEMA_LANGUAGE);
        final Schema schema = schemaFactory.newSchema(file);
        this.schemaRef.set(schema);
    } catch (final SAXException e) {
        throw e;
    }
}
 
Example 8
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 9
Source File: SoapTransportCommandProcessor.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void onCougarStart() {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (ServiceBindingDescriptor sd : getServiceBindingDescriptors()) {
        SoapServiceBindingDescriptor soapServiceDesc = (SoapServiceBindingDescriptor) sd;
        try {
            // we'll load the schema content and create a Schema object once, as this is threadsafe and so can be reused
            // this should cut down on some memory usage and remove schema parsing from the critical path when validating
            try (InputStream is = soapServiceDesc.getClass().getClassLoader().getResourceAsStream(soapServiceDesc.getSchemaPath())) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                StreamUtils.copy(is, baos);
                String schemaContent = baos.toString();
                Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(schemaContent)));
                String uriVersionStripped = stripMinorVersionFromUri(soapServiceDesc.getServiceContextPath() + soapServiceDesc.getServiceVersion());
                for (OperationBindingDescriptor desc : soapServiceDesc.getOperationBindings()) {
                    SoapOperationBindingDescriptor soapOpDesc = (SoapOperationBindingDescriptor) desc;
                    OperationDefinition opDef = getOperationDefinition(soapOpDesc.getOperationKey());
                    String operationName = uriVersionStripped + "/" + soapOpDesc.getRequestName().toLowerCase();
                    bindings.put(operationName,
                            new SoapOperationBinding(opDef, soapOpDesc,
                                    soapServiceDesc, schema));
                }
            }
        }
        catch (IOException | SAXException e) {
            throw new CougarFrameworkException("Error loading schema", e);
        }
    }
}
 
Example 10
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 11
Source File: XMLValidation.java    From journaldev with MIT License 5 votes vote down vote up
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
    
    try {
        SchemaFactory factory = 
                SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new File(xsdPath));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new File(xmlPath)));
    } catch (IOException | SAXException e) {
        System.out.println("Exception: "+e.getMessage());
        return false;
    }
    return true;
}
 
Example 12
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 13
Source File: DeviceSchema.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that returns a validator for a specific version of the XSD.
 *
 * @param version Between 1 and {@link #NS_LATEST_VERSION}, included.
 * @return A {@link Schema} validator or null.
 */
@Nullable
public static Schema getSchema(int version) throws SAXException {
    InputStream xsdStream = getXsdStream(version);
    if (xsdStream == null) {
        return null;
    }
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new StreamSource(xsdStream));
    return schema;
}
 
Example 14
Source File: DeviceManagementConfigTests.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@BeforeClass
private void initSchema() {
    File deviceManagementSchemaConfig = new File(DeviceManagementConfigTests.TEST_CONFIG_SCHEMA_LOCATION);
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        schema = factory.newSchema(deviceManagementSchemaConfig);
    } catch (SAXException e) {
        Assert.fail("Invalid schema found", e);
    }
}
 
Example 15
Source File: XmlUtils.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
public static Schema getSchema(String schemaString) {
	Schema schema = null;
	try {
		if (schemaString != null) {
			SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			StreamSource ss = new StreamSource();
			ss.setReader(new StringReader(schemaString));
			schema = sf.newSchema(ss);
		}
	} catch (Exception e) {
		throw new RuntimeException("Failed to create schema from string: " + schemaString, e);
	}
	return schema;
}
 
Example 16
Source File: XmlAligner.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected static ValidatorHandler getValidatorHandler(URL schemaURL) throws SAXException {
	SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	Schema schema = sf.newSchema(schemaURL); 
	return schema.newValidatorHandler();
}
 
Example 17
Source File: BpmnParser.java    From camunda-bpmn-model with Apache License 2.0 4 votes vote down vote up
public BpmnParser() {
  this.schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
  addSchema(BPMN20_NS, createSchema(BPMN_20_SCHEMA_LOCATION, BpmnParser.class.getClassLoader()));
}
 
Example 18
Source File: MagicalGoConfigXmlWriterTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldBeAValidXSD() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    factory.newSchema(new StreamSource(getClass().getResourceAsStream("/cruise-config.xsd")));
}
 
Example 19
Source File: HQMFProvider.java    From cqf-ruler with Apache License 2.0 4 votes vote down vote up
private Schema loadHQMFSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL hqmfSchema = ClassLoader.getSystemClassLoader().getResource("hqmf/schemas/EMeasure_N1.xsd");
    return factory.newSchema(hqmfSchema);
}
 
Example 20
Source File: EdfiRecordParserImpl2.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
        RecordVisitor visitor) throws SAXException, IOException, XmlParseException {

    EdfiRecordParserImpl2 parser = new EdfiRecordParserImpl2();

    parser.addVisitor(visitor);
    parser.typeProvider = typeProvider;

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Schema schema = schemaFactory.newSchema(schemaResource.getURL());

    parser.parseAndValidate(input, schema);
}