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

The following examples show how to use javax.xml.validation.SchemaFactory#newSchema() . 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: ConverterImpl.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 7 votes vote down vote up
@Override
public String toXML(T obj) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);

        Marshaller m = context.createMarshaller();
        if(schemaLocation != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
            Schema schema = schemaFactory.newSchema(source);
            m.setSchema(schema);
        }

        StringWriter writer = new StringWriter();

        m.marshal(obj, writer);
        String xml = writer.toString();

        return xml;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
 
Example 2
Source File: DOMForest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks the correctness of the XML Schema documents and return true
 * if it's OK.
 *
 * <p>
 * This method performs a weaker version of the tests where error messages
 * are provided without line number information. So whenever possible
 * use {@link SchemaConstraintChecker}.
 *
 * @see SchemaConstraintChecker
 */
public boolean checkSchemaCorrectness(ErrorReceiver errorHandler) {
    try {
        boolean disableXmlSecurity = false;
        if (options != null) {
            disableXmlSecurity = options.disableXmlSecurity;
        }
        SchemaFactory sf = XmlFactory.createSchemaFactory(W3C_XML_SCHEMA_NS_URI, disableXmlSecurity);
        ErrorReceiverFilter filter = new ErrorReceiverFilter(errorHandler);
        sf.setErrorHandler(filter);
        Set<String> roots = getRootDocuments();
        Source[] sources = new Source[roots.size()];
        int i=0;
        for (String root : roots) {
            sources[i++] = new DOMSource(get(root),root);
        }
        sf.newSchema(sources);
        return !filter.hadError();
    } catch (SAXException e) {
        // the errors should have been reported
        return false;
    }
}
 
Example 3
Source File: DmnXMLConverter.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(DMN_XSD));
    }

    if (schema == null) {
        schema = factory.newSchema(DmnXMLConverter.class.getClassLoader().getResource(DMN_XSD));
    }

    if (schema == null) {
        throw new DmnXMLException("DMN XSD could not be found");
    }
    return schema;
}
 
Example 4
Source File: LoginIdentityProviderFactoryBean.java    From nifi with Apache License 2.0 6 votes vote down vote up
private LoginIdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getLoginIdentityProviderConfigurationFile();

    // 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(LoginIdentityProviders.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<LoginIdentityProviders> element = unmarshaller.unmarshal(xsr, LoginIdentityProviders.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 5
Source File: RdfResultsWriterFactoryTest.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private void validateXml(String xml) throws SAXException, IOException {

        String schemaFile = "/org/aksw/rdfunit/io/writer/junit-4.xsd";
        InputStream xsd = RdfResultsWriterFactoryTest.class.getResourceAsStream(schemaFile);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(xml)));
    }
 
Example 6
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 7
Source File: XSDResourceValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public XSDResourceValidator(Source xsd, ResourceTransformer resourceTransformer) {
    try {
        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 8
Source File: XMLUtils.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Validator getValidator() throws IOException, SAXException {
	if (validator == null) {
		SchemaFactory xmlSchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		File schemafile = new File(schemaFilePathName);
		int idx = schemaFilePathName.lastIndexOf(schemafile.getName());
		String path = schemaFilePathName.substring(0, idx);
		xmlSchemaFactory.setResourceResolver(new XMLUtils().new ResourceResolver(path));
		Reader reader = new StringReader(convertSchemaToString(schemaFilePathName));
		Schema schema = xmlSchemaFactory.newSchema(new StreamSource(reader));
		validator = schema.newValidator();
	}
	return validator;
}
 
Example 9
Source File: RemoteResolvingStrategyTest.java    From validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalSchemaResolving() throws Exception {
    final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy();
    final SchemaFactory schemaFactory = s.createSchemaFactory();
    final Schema schema = schemaFactory.newSchema(Resolving.SCHEMA_WITH_REFERENCE.toURL());
    assertThat(schema).isNotNull();
}
 
Example 10
Source File: FileAccessPolicyProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(AccessPolicyProviderInitializationContext initializationContext) throws SecurityProviderCreationException {
    userGroupProviderLookup = initializationContext.getUserGroupProviderLookup();

    try {
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        authorizationsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(AUTHORIZATIONS_XSD));
    } catch (Exception e) {
        throw new SecurityProviderCreationException(e);
    }
}
 
Example 11
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 12
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 13
Source File: Bug4997818.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1() throws Exception {
    String xsd1 = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <import namespace='jaxp13_test2'/>\n"
            + "    <element name='test'/>\n" + "    <element name='child1'/>\n" + "</schema>\n";

    final NullPointerException EUREKA = new NullPointerException("NewSchema015");

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    StringReader reader = new StringReader(xsd1);
    StreamSource source = new StreamSource(reader);
    LSResourceResolver resolver = new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
            LSInput input;
            if (namespaceURI != null && namespaceURI.endsWith("jaxp13_test2")) {
                throw EUREKA;
            } else {
                input = null;
            }

            return input;
        }
    };
    schemaFactory.setResourceResolver(resolver);

    try {
        schemaFactory.newSchema(new Source[] { source });
        Assert.fail("NullPointerException was not thrown.");
    } catch (RuntimeException e) {
        if (e != EUREKA)
            throw e;
    }
}
 
Example 14
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 15
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 16
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 17
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 18
Source File: UserSession.java    From chipster with MIT License 4 votes vote down vote up
public static Schema getPreviousSchema() throws SAXException {
       SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	return factory.newSchema(new StreamSource(UserSession.class.getResourceAsStream("session.xsd")));
}
 
Example 19
Source File: TestPrintXML.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... args) throws Throwable {

        Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath();

        OutputAnalyzer output = ExecuteHelper.jfr("print", "--xml", "--stack-depth", "9999", recordingFile.toString());
        System.out.println(recordingFile);
        String xml = output.getStdout();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src"), "jfr.xsd"));

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setSchema(schema);
        factory.setNamespaceAware(true);

        SAXParser sp = factory.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        RecordingHandler handler = new RecordingHandler();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(new StringReader(xml)));

        // Verify that all data was written correctly
        List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile);
        Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime()));
        Iterator<RecordedEvent> it = events.iterator();
        for (XMLEvent xmlEvent : handler.events) {
            RecordedEvent re = it.next();
            if (!compare(re, xmlEvent.values)) {
                System.out.println("Expected:");
                System.out.println("----------------------");
                System.out.println(re);
                System.out.println();
                System.out.println("Was (XML)");
                System.out.println("----------------------");
                System.out.println(xmlEvent);
                System.out.println();
                throw new Exception("Event doesn't match");
            }
        }

    }
 
Example 20
Source File: EdfiRecordParser.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
/**
 * Parses and Validates an XML represented by the input stream against provided XSD and reports validation issues.
 *
 * @param input XML to parse and validate
 * @param schemaResource XSD resource
 * @throws SAXException If a SAX error occurs during XSD parsing.
 * @throws IOException If a IO error occurs during XSD/XML parsing.
 * @throws XmlParseException If a SAX error occurs during XML parsing.
 */
public void process(InputStream input, Resource schemaResource)
        throws SAXException, IOException, XmlParseException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

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

    this.parseAndValidate(input, schema.newValidatorHandler());
}