javax.xml.validation.SchemaFactory Java Examples

The following examples show how to use javax.xml.validation.SchemaFactory. 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: DOMForest.java    From openjdk-8 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 #2
Source File: DOMForest.java    From TencentKona-8 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: DOMForest.java    From hottub 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 #4
Source File: Bug4970380.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test1() throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    ValidatorHandler validatorHandler = schemaFactory.newSchema().newValidatorHandler();

    try {
        validatorHandler.getFeature("unknown1234");
        Assert.fail("SAXNotRecognizedException was not thrown.");
    } catch (SAXNotRecognizedException e) {
        ; // expected
    }

    if (!validatorHandler.getFeature("http://xml.org/sax/features/namespace-prefixes")) {
        // as expected
        System.out.println("getFeature(namespace-prefixes): OK");
    } else {
        Assert.fail("Expected false, returned true.");
    }
}
 
Example #5
Source File: CmmnXmlConverter.java    From flowable-engine 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(XSD_LOCATION));
    }

    if (schema == null) {
        schema = factory.newSchema(this.getClass().getClassLoader().getResource(XSD_LOCATION));
    }

    if (schema == null) {
        throw new CmmnXMLException("CMND XSD could not be found");
    }
    return schema;
}
 
Example #6
Source File: FeaturePropagationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSecureProcessingFeaturePropagationAndReset() throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    boolean value;
    value = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
    //default is true for JDK
    //assertFalse("Default value of feature on SchemaFactory should have been false.", value);
    assertTrue("Default value of feature on SchemaFactory should have been false.", value);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    Schema schema = makeSchema(factory, null);
    Validator validator = schema.newValidator();
    value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
    assertTrue("Value of feature on Validator should have been true.", value);
    validator.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
    value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
    assertFalse("Value of feature on Validator should have been false.", value);
    validator.reset();
    value = validator.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
    assertTrue("After reset, value of feature on Validator should be true.", value);
}
 
Example #7
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 #8
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 #9
Source File: AuthorizerFactory.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private Authorizers loadAuthorizersConfiguration() throws Exception {
    final File authorizersConfigurationFile = properties.getAuthorizersConfigurationFile();

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Authorizers> element = unmarshaller.unmarshal(XmlUtils.createSafeReader(new StreamSource(authorizersConfigurationFile)), Authorizers.class);
            return element.getValue();
        } catch (XMLStreamException | SAXException | JAXBException e) {
            throw new Exception("Unable to load the authorizer configuration file at: " + authorizersConfigurationFile.getAbsolutePath(), e);
        }
    } else {
        throw new Exception("Unable to find the authorizer configuration file at " + authorizersConfigurationFile.getAbsolutePath());
    }
}
 
Example #10
Source File: SchemaValidator.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Validate the XML content against the XSD.
 *
 * The whole XML content must be valid.
 */
static void validateXML(String xmlContent, String xsdPath, Properties resolvedProperties) throws Exception {
    String resolvedXml = resolveAllExpressions(xmlContent, resolvedProperties);

    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdPath);
    final Source source = new StreamSource(stream);

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(ERROR_HANDLER);
    schemaFactory.setResourceResolver(new JBossEntityResolver());
    Schema schema = schemaFactory.newSchema(source);
    javax.xml.validation.Validator validator = schema.newValidator();
    validator.setErrorHandler(ERROR_HANDLER);
    validator.setFeature("http://apache.org/xml/features/validation/schema", true);
    validator.validate(new StreamSource(new StringReader(resolvedXml)));
}
 
Example #11
Source File: QueryManagerConfigUnmarshaller.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Validates and unmarshalls XML into a {@link QueryManagerConfig} object.
 *
 * @param xmlStream - Reads the XML that will be unmarshalled. (not null)
 * @return A {@link QueryManagerConfig} loaded with the XMLs values.
 * @throws SAXException Could not load the schema the XML will be validated against.
 * @throws JAXBException Could not unmarshal the XML into a POJO.
 */
public static QueryManagerConfig unmarshall(final InputStream xmlStream) throws JAXBException, SAXException {
    requireNonNull(xmlStream);

    // Get an input stream to the XSD file that is packaged inside of the jar.
    final URL schemaURL = ClassLoader.getSystemResource(XSD_PATH);
    if(schemaURL == null) {
        throw new RuntimeException("The Class Loader was unable to find the following resource: " + XSD_PATH);
    }

    // Get the schema for the object.
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = sf.newSchema(schemaURL);

    // Configure the unmarhsaller to validate using the schema.
    final JAXBContext context = JAXBContext.newInstance(QueryManagerConfig.class);
    final Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(schema);

    // Perform the unmarshal.
    return (QueryManagerConfig) unmarshaller.unmarshal(xmlStream);
}
 
Example #12
Source File: DOMForest.java    From openjdk-jdk9 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 #13
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 #14
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
	if (logger.isDebugEnabled()) {
		logger.debug("Setting validation schema to " +
				StringUtils.arrayToCommaDelimitedString(this.schemaResources));
	}
	Assert.notEmpty(resources, "No resources given");
	Assert.hasLength(schemaLanguage, "No schema language provided");
	Source[] schemaSources = new Source[resources.length];
	XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
	for (int i = 0; i < resources.length; i++) {
		Resource resource = resources[i];
		Assert.isTrue(resource != null && resource.exists(), () -> "Resource does not exist: " + resource);
		InputSource inputSource = SaxResourceUtils.createInputSource(resource);
		schemaSources[i] = new SAXSource(xmlReader, inputSource);
	}
	SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
	if (this.schemaResourceResolver != null) {
		schemaFactory.setResourceResolver(this.schemaResourceResolver);
	}
	return schemaFactory.newSchema(schemaSources);
}
 
Example #15
Source File: SchemaCache.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public ValidatorHandler newValidator() {
    synchronized(this) {
        if(schema==null) {
            try {
                // do not disable secure processing - these are well-known schemas
                SchemaFactory sf = XmlFactory.createSchemaFactory(XMLConstants.W3C_XML_SCHEMA_NS_URI, false);
                schema = allowExternalAccess(sf, "file", false).newSchema(source);
            } catch (SAXException e) {
                // we make sure that the schema is correct before we ship.
                throw new AssertionError(e);
            }
        }
    }

    ValidatorHandler handler = schema.newValidatorHandler();
    return handler;
}
 
Example #16
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * validates <code>doc</code> using XML Schema defined <code>schemaURI</code>
 * @param doc document to be validated
 * @param schemaURI URI of XML Schema document
 * @throws SAXException if validation fails
 * @throws IOException if resolving resources fails
 */
public static void validate(Document doc, String schemaURI) throws SAXException, IOException {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    sf.setResourceResolver(MCREntityResolver.instance());
    Schema schema;
    try {
        schema = sf.newSchema(MCRURIResolver.instance().resolve(schemaURI, null));
    } catch (TransformerException e) {
        Throwable cause = e.getCause();
        if (cause == null) {
            throw new IOException(e);
        }
        if (cause instanceof SAXException) {
            throw (SAXException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw new IOException(e);
    }
    Validator validator = schema.newValidator();
    validator.setResourceResolver(MCREntityResolver.instance());
    validator.validate(new JDOMSource(doc));
}
 
Example #17
Source File: AccessControlSchemaXmlValidationTest.java    From jump-the-queue with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if the access-control-schema.xml is valid.
 *
 * @throws ParserConfigurationException If a DocumentBuilder cannot be created which satisfies the configuration
 *         requested.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If an error occurs during the validation.
 */
@Test
public void validateAccessControllSchema() throws ParserConfigurationException, SAXException, IOException {

  // parse an XML document into a DOM tree
  DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  String xmlPath = getClass().getResource("/config/app/security/access-control-schema.xml").getPath();
  Document document = parser.parse(new File(xmlPath));

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

  // load a WXS schema, represented by a Schema instance
  URL schemaPath = getClass().getResource("/com/devonfw/module/security/access-control-schema.xsd");
  Schema schema = factory.newSchema(schemaPath);

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

  // validate the DOM tree
  validator.validate(new DOMSource(document));
}
 
Example #18
Source File: Bug6975265Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() {
    try {
        File dir = new File(Bug6975265Test.class.getResource("Bug6975265").getPath());
        File files[] = dir.listFiles();
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        for (int i = 0; i < files.length; i++) {
            try {
                System.out.println(files[i].getName());
                Schema schema = schemaFactory.newSchema(new StreamSource(files[i]));
                Assert.fail("should report error");
            } catch (org.xml.sax.SAXParseException spe) {
                System.out.println(spe.getMessage());
                continue;
            }
        }
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
 
Example #19
Source File: ValidationWarningsTest.java    From openjdk-jdk9 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 #20
Source File: JaxbConverter.java    From conf4j with MIT License 5 votes vote down vote up
/**
 * Returns XSD schema by annotation of given class or null when schemat doesn not exist within the class
 *
 * @param clazz class to read schema
 * @return XSD schema or null
 */
Schema readXsdSchema(Class<?> clazz) throws SAXException {
    XmlSchema xmlSchema = clazz.getPackage().getAnnotation(XmlSchema.class);
    String schemaLocation = xmlSchema != null ? xmlSchema.location() : null;
    if (schemaLocation == null) {
        return null;
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    return schemaFactory.newSchema(getResource(schemaLocation));
}
 
Example #21
Source File: XMLValidation.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the XML data against the specified schema.
 * 
 * @param schemaFileURL
 *            The URL to the schema file.
 * @param xmlContent
 *            The XML data to be validated.
 * @throws SAXException
 * @throws IOException
 * @throws TransformerException 
 */
public static void validateXML(URL schemaFileURL, Document xmlContent)
        throws SAXException, IOException, TransformerException {
    SchemaFactory factory = SchemaFactory
            .newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory.newSchema(schemaFileURL);
    Validator validator = schema.newValidator();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    printDocument(xmlContent, byteArrayOutputStream);
    ByteArrayInputStream bis = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    validator.validate(new StreamSource(bis));
}
 
Example #22
Source File: DeviceSchema.java    From javaide with GNU General Public License v3.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 #23
Source File: ParticleTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() throws SAXException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(new StreamSource(ParticleTest.class.getResourceAsStream("upa01.xsd")));
    Validator validator = schema.newValidator();

    validator.validate(new StreamSource(ParticleTest.class.getResourceAsStream("upa01.xml")));
}
 
Example #24
Source File: XmlUtils.java    From fc-java-sdk with MIT License 5 votes vote down vote up
public static void validateXml(Node root, InputStream xsd)
    throws SAXException, IOException {
    try {
        Source source = new StreamSource(xsd);
        Schema schema = SchemaFactory.newInstance(
            XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);

        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(root));
    } finally {
        closeStream(xsd);
    }
}
 
Example #25
Source File: XmlUtil.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static SchemaFactory allowExternalAccess(SchemaFactory sf, String value, boolean disableSecureProcessing) {

        // if xml security (feature secure processing) disabled, nothing to do, no restrictions applied
        if (isXMLSecurityDisabled(disableSecureProcessing)) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "Xml Security disabled, no JAXP xsd external access configuration necessary.");
            }
            return sf;
        }

        if (System.getProperty("javax.xml.accessExternalSchema") != null) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "Detected explicitly JAXP configuration, no JAXP xsd external access configuration necessary.");
            }
            return sf;
        }

        try {
            sf.setProperty(ACCESS_EXTERNAL_SCHEMA, value);
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "Property \"{0}\" is supported and has been successfully set by used JAXP implementation.", new Object[]{ACCESS_EXTERNAL_SCHEMA});
            }
        } catch (SAXException ignored) {
            // nothing to do; support depends on version JDK or SAX implementation
            if (LOGGER.isLoggable(Level.CONFIG)) {
                LOGGER.log(Level.CONFIG, "Property \"{0}\" is not supported by used JAXP implementation.", new Object[]{ACCESS_EXTERNAL_SCHEMA});
            }
        }
        return sf;
    }
 
Example #26
Source File: SchemaFactoryTest.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args)
      throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    //todo 修复方式
//    factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
//    factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.NO_FEEDBACK_SINGLE_LINE
        .getBytes());
    StreamSource source = new StreamSource(byteArrayInputStream);
    Schema schema = factory.newSchema(source);
  }
 
Example #27
Source File: Bug6509668.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");

    InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xsd.getBytes()));
    StreamSource xsdSource = new StreamSource(reader);

    Schema schema = schemaFactory.newSchema(xsdSource);
    return schema.newValidatorHandler();
}
 
Example #28
Source File: TestXmlUtils.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test schema safety
 *
 * @throws SAXException
 *             failed to parse, should happen as this is an attack
 */
@Test(expected = SAXException.class)
public void testNewSafeSchemaFactory() throws SAXException {
    SchemaFactory schemaFactory = XmlUtils.newSafeSchemaFactory();
    assertNotNull(schemaFactory);
    Schema schema = XmlUtils.newSafeSchemaFactory().newSchema(new StreamSource(new StringReader(SCHEMA_XXE_ATTACK)));
    assertNotNull(schema);
}
 
Example #29
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 #30
Source File: DefaultIndexerComponentFactory.java    From hbase-indexer with Apache License 2.0 5 votes vote down vote up
private void validate(Document document) {
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = getClass().getResource("indexerconf.xsd");
        Schema schema = factory.newSchema(url);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (Exception e) {
        throw new IndexerConfException("Error validating index configuration against XML Schema.", e);
    }
}