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

The following examples show how to use javax.xml.validation.SchemaFactory#setErrorHandler() . 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 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 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: WSDLInlineSchemaValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void validate(WSDLModel model, 
                      Source saxSource, 
                      XsdBasedValidator.Handler handler,
                      LSResourceResolver resolver) {
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        if (resolver != null) {
            sf.setResourceResolver(resolver);
        }
        sf.setErrorHandler(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: XsdBasedValidator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected Schema getCompiledSchema(Source[] schemas,
        LSResourceResolver lsResourceResolver,
        ErrorHandler errorHandler) {
    
    Schema schema = null;
    
    // Create a compiled Schema object.
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setResourceResolver(lsResourceResolver);
    schemaFactory.setErrorHandler(errorHandler);
    try {
        schema = schemaFactory.newSchema(schemas);            
    } catch(SAXException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getCompiledSchema", ex);
    } 
    
    return schema;
}
 
Example 5
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 6
Source File: SchemaBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a schema from the given schema sources.
 * 
 * @param lang schema language, must not be null
 * @param schemaSources schema sources, must not be null
 * 
 * @return the constructed schema
 * 
 * @throws SAXException thrown if there is a problem converting the schema sources in to a schema
 */
protected static Schema buildSchema(SchemaLanguage lang, Source[] schemaSources) throws SAXException {
    if(lang == null){
        throw new IllegalArgumentException("Schema language may not be null");
    }
    
    if(schemaSources == null){
        throw new IllegalArgumentException("Schema sources may not be null");
    }
    
    SchemaFactory schemaFactory;

    if (lang == SchemaLanguage.XML) {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    } else {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI);
    }

    schemaFactory.setErrorHandler(new LoggingErrorHandler(LoggerFactory.getLogger(SchemaBuilder.class)));
    return schemaFactory.newSchema(schemaSources);
}
 
Example 7
Source File: DOMForest.java    From openjdk-jdk8u-backup 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 8
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 9
Source File: JBossCliXmlValidationTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void validateJBossCliXmlTestCase() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    final String jbossDist = TestSuiteEnvironment.getSystemProperty("jboss.dist");
    Document document = parser.parse(new File(jbossDist, "bin/jboss-cli.xml"));

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(new ErrorHandlerImpl());
    //schemaFactory.setResourceResolver(new XMLResourceResolver());

    Schema schema = schemaFactory.newSchema(resourceToURL("schema/wildfly-cli_3_4.xsd"));
    Validator validator = schema.newValidator();
    validator.validate(new DOMSource(document));

}
 
Example 10
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 11
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 12
Source File: DOMForest.java    From openjdk-8-source 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: 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 14
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 15
Source File: SchemaHandler.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Attempts to compile the schema. If successful, allows an XML document to be validated.
 * @return true if the schema has compiled successfully.
 */
public boolean compileSchema() {
    if (compiled) return true;

    errorHandler.reset();
    exceptionMessage = null;

    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setErrorHandler(errorHandler);
    //    factory.setResourceResolver(ResourceResolver.getInstance());
        schema = factory.newSchema(schemaSource);
        return compiled = errorHandler.isValid();
    }
    catch (Exception e) {
        exceptionMessage = "Schema compile failed with exception: " + e.getMessage();
        return false;
    }
}
 
Example 16
Source File: ModuleConfigTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void validateXmlSchema(final URL schemaUrl, final InputStream data) throws IOException, SAXException {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    schemaFactory.setErrorHandler(ERROR_HANDLER);

    final Schema schema = schemaFactory.newSchema(schemaUrl);
    final Validator validator = schema.newValidator();
    validator.validate(new StreamSource(data));
}
 
Example 17
Source File: SchemaFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testErrorHandler() {
    SchemaFactory sf = newSchemaFactory();
    assertNull(sf.getErrorHandler(), "When SchemaFactory is created, initially ErrorHandler should not be set.");

    ErrorHandler handler = new MyErrorHandler();
    sf.setErrorHandler(handler);
    assertSame(sf.getErrorHandler(), handler);

    sf.setErrorHandler(null);
    assertNull(sf.getErrorHandler());
}
 
Example 18
Source File: Bug5010072.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test1() throws Exception {
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

    ErrorHandler errorHandler = new ErrorHandler();
    schemaFactory.setErrorHandler(errorHandler);

    try {
        schemaFactory.newSchema(Bug5010072.class.getResource("Bug5010072.xsd"));
        Assert.fail("should fail to compile");
    } catch (SAXException e) {
        ; // as expected
    }
}
 
Example 19
Source File: ParserUtils.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
private static Schema getSchema(String schemaPublicId)
        throws SAXException {

    Schema schema = schemaCache.get(schemaPublicId);
    if (schema == null) {
        synchronized (schemaCache) {
            schema = schemaCache.get(schemaPublicId);
            if (schema == null) {
                SchemaFactory schemaFactory = SchemaFactory.newInstance(
                    XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schemaFactory.setResourceResolver(
                    new MyLSResourceResolver());
                schemaFactory.setErrorHandler(new MyErrorHandler());

                String path = schemaPublicId;
                if (schemaResourcePrefix != null) {
                    int index = schemaPublicId.lastIndexOf('/');
                    if (index != -1) {
                        path = schemaPublicId.substring(index+1);
                    }
                    path = schemaResourcePrefix + path;
                }

                InputStream input = null;
                if (isSchemaResourcePrefixFileUrl) {
                    try {
                        File f = new File(new URI(path));
                        if (f.exists()) { 
                            input = new FileInputStream(f);
                        }
                    } catch (Exception e) {
                        throw new SAXException(e);
                    }
                } else {
                    input = ParserUtils.class.getResourceAsStream(path);
                }

                if (input == null) {
      throw new SAXException(
                        Localizer.getMessage(
                            "jsp.error.internal.filenotfound",
                            schemaPublicId));
                }

                schema = schemaFactory.newSchema(new StreamSource(input));
                schemaCache.put(schemaPublicId, schema);
            }
        }
    }

    return schema;
}
 
Example 20
Source File: SchemaCompilerEx.java    From mwsc with MIT License 4 votes vote down vote up
public JAXBModelImpl bind() {
        // this has been problematic. turn it off.
//        if(!forest.checkSchemaCorrectness(this))
//            return null;

        // parse all the binding files given via XJC -b options.
        // this also takes care of the binding files given in the -episode option.
        for (InputSource is : opts.getBindFiles())
            parseSchema(is);
        
        // internalization
        SCDBasedBindingSet scdBasedBindingSet = forest.transform(opts.isExtensionMode());

        if(!NO_CORRECTNESS_CHECK) {
            // correctness check
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            sf.setErrorHandler(new DowngradingErrorHandler(this));
            forest.weakSchemaCorrectnessCheck(sf);
            if(hadError)
                return null;    // error in the correctness check. abort now
        }

        JCodeModel codeModel = new JCodeModel();

        ModelLoader gl = new ModelLoader(opts,codeModel,this);

        try {
            XSSchemaSet result = gl.createXSOM(forest, scdBasedBindingSet);
            if(result==null)
                return null;


            // we need info about each field, so we go ahead and generate the
            // skeleton at this point.
            // REVISIT: we should separate FieldRenderer and FieldAccessor
            // so that accessors can be used before we build the code.
            Model model = gl.annotateXMLSchema(result);
            if(model==null)   return null;

            if(hadError)        return null;    // if we have any error by now, abort

            context = model.generateCode(opts,this);
            if(context==null)   return null;

            if(hadError)        return null;

            return new JAXBModelImpl(context);
        } catch( SAXException e ) {
            // since XSOM uses our parser that scans DOM,
            // no parser error is possible.
            // all the other errors will be directed to ErrorReceiver
            // before it's thrown, so when the exception is thrown
            // the error should have already been reported.

            // thus ignore.
            return null;
        }
    }