Example #1
0
  /**
   * Called by all validation methods to do the real guts of the validation job.
   *
   * @param schema
   * @param xml
   * @param eh
   * @throws Exception
   */
  private static void validateRealGuts(Schema schema, Element xml, ErrorHandler eh)
      throws Exception {

    Resolver resolver = ResolverWrapper.getInstance();

    ValidatorHandler vh = schema.newValidatorHandler();
    vh.setResourceResolver(resolver.getXmlResolver());
    vh.setErrorHandler(eh);

    SAXOutputter so = new SAXOutputter(vh);
    eh.setSo(so);

    so.output(xml);
  }
  /**
   * Main entry point. Expects two arguments: the schema document, and the source document.
   *
   * @param args
   */
  public static void main(String[] args) {
    try {
      if (args.length != 2) {
        printUsage();
        return;
      }

      SchemaFactory schemaFactory;

      // Set a system property to force selection of the Saxon SchemaFactory implementation

      System.setProperty(
          "javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema",
          "com.saxonica.schema.SchemaFactoryImpl");

      schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

      schemaFactory.setErrorHandler(new LocalErrorHandler());
      // create a grammar object.
      Schema schemaGrammar = schemaFactory.newSchema(new File(args[0]));

      System.err.println("Created Grammar object for schema : " + args[0]);

      Resolver resolver = new Resolver();

      // create a validator to validate against the schema.
      ValidatorHandler schemaValidator = schemaGrammar.newValidatorHandler();
      schemaValidator.setResourceResolver(resolver);
      schemaValidator.setErrorHandler(new LocalErrorHandler());
      schemaValidator.setContentHandler(
          new LocalContentHandler(schemaValidator.getTypeInfoProvider()));

      System.err.println("Validating " + args[1] + " against grammar " + args[0]);
      SAXParserFactory parserFactory = SAXParserFactory.newInstance();
      parserFactory.setNamespaceAware(true);
      SAXParser parser = parserFactory.newSAXParser();
      XMLReader reader = parser.getXMLReader();
      reader.setContentHandler(schemaValidator);
      reader.parse(new InputSource(new File(args[1]).toURI().toString()));

      System.err.println("Validation successful");
    } catch (SAXException saxe) {
      exit(1, "Error: " + saxe.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      exit(2, "Fatal Error: " + e);
    }
  }
Example #3
0
  public Iterable<Object> startWithValidation(
      final Reader in, String namespace, String schemaSource) throws SAXException {
    try {
      SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
      Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream(schemaSource)));
      ValidatorHandler validator = schema.newValidatorHandler();
      validator.setContentHandler(parser);
      validator.setErrorHandler(parser);

      AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
      filter.setContentHandler(validator);
      return start(in, filter);
    } catch (IOException e) {
      throw new SAXException(tr("Failed to load XML schema."), e);
    }
  }
 public ValidatingMarshalRecord(MarshalRecord marshalRecord, XMLMarshaller xmlMarshaller) {
   this.marshalRecord = marshalRecord;
   Schema schema = xmlMarshaller.getSchema();
   ValidatorHandler validatorHandler = schema.newValidatorHandler();
   validatorHandler.setErrorHandler(
       new ValidatingMarshalRecordErrorHandler(marshalRecord, xmlMarshaller.getErrorHandler()));
   if (xmlMarshaller.isFragment()) {
     try {
       validatorHandler.startDocument();
     } catch (SAXException e) {
     }
   }
   validatingRecord = new ContentHandlerRecord();
   validatingRecord.setMarshaller(xmlMarshaller);
   validatingRecord.setContentHandler(validatorHandler);
   validatingRecord.setEqualNamespaceResolvers(marshalRecord.hasEqualNamespaceResolvers());
 }
  /**
   * Create a SAX parser with the associated features
   *
   * @param features Hashtable of SAX features, may be null
   */
  SAXParserImpl(SAXParserFactoryImpl spf, Hashtable features, boolean secureProcessing)
      throws SAXException {
    fSecurityManager = new XMLSecurityManager(secureProcessing);
    fSecurityPropertyMgr = new XMLSecurityPropertyManager();
    // Instantiate a SAXParser directly and not through SAX so that we use the right ClassLoader
    xmlReader = new JAXPSAXParser(this, fSecurityPropertyMgr, fSecurityManager);

    // JAXP "namespaceAware" == SAX Namespaces feature
    // Note: there is a compatibility problem here with default values:
    // JAXP default is false while SAX 2 default is true!
    xmlReader.setFeature0(NAMESPACES_FEATURE, spf.isNamespaceAware());

    // SAX "namespaces" and "namespace-prefixes" features should not
    // both be false.  We make them opposite for backward compatibility
    // since JAXP 1.0 apps may want to receive xmlns* attributes.
    xmlReader.setFeature0(NAMESPACE_PREFIXES_FEATURE, !spf.isNamespaceAware());

    // Avoid setting the XInclude processing feature if the value is false.
    // This will keep the configuration from throwing an exception if it
    // does not support XInclude.
    if (spf.isXIncludeAware()) {
      xmlReader.setFeature0(XINCLUDE_FEATURE, true);
    }

    xmlReader.setProperty0(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr);

    xmlReader.setProperty0(SECURITY_MANAGER, fSecurityManager);

    if (secureProcessing) {
      /**
       * By default, secure processing is set, no external access is allowed. However, we need to
       * check if it is actively set on the factory since we allow the use of the System Property or
       * jaxp.properties to override the default value
       */
      if (features != null) {

        Object temp = features.get(XMLConstants.FEATURE_SECURE_PROCESSING);
        if (temp != null) {
          boolean value = ((Boolean) temp).booleanValue();
          if (value && Constants.IS_JDK8_OR_ABOVE) {
            fSecurityPropertyMgr.setValue(
                XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD,
                XMLSecurityPropertyManager.State.FSP,
                Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
            fSecurityPropertyMgr.setValue(
                XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA,
                XMLSecurityPropertyManager.State.FSP,
                Constants.EXTERNAL_ACCESS_DEFAULT_FSP);
          }
        }
      }
    }

    // Set application's features, followed by validation features.
    setFeatures(features);

    // If validating, provide a default ErrorHandler that prints
    // validation errors with a warning telling the user to set an
    // ErrorHandler.
    if (spf.isValidating()) {
      fInitErrorHandler = new DefaultValidationErrorHandler(xmlReader.getLocale());
      xmlReader.setErrorHandler(fInitErrorHandler);
    } else {
      fInitErrorHandler = xmlReader.getErrorHandler();
    }
    xmlReader.setFeature0(VALIDATION_FEATURE, spf.isValidating());

    // Get the Schema object from the factory
    this.grammar = spf.getSchema();
    if (grammar != null) {
      XMLParserConfiguration config = xmlReader.getXMLParserConfiguration();
      XMLComponent validatorComponent = null;
      /** For Xerces grammars, use built-in schema validator. * */
      if (grammar instanceof XSGrammarPoolContainer) {
        validatorComponent = new XMLSchemaValidator();
        fSchemaValidationManager = new ValidationManager();
        fUnparsedEntityHandler = new UnparsedEntityHandler(fSchemaValidationManager);
        config.setDTDHandler(fUnparsedEntityHandler);
        fUnparsedEntityHandler.setDTDHandler(xmlReader);
        xmlReader.setDTDSource(fUnparsedEntityHandler);
        fSchemaValidatorComponentManager =
            new SchemaValidatorConfiguration(
                config, (XSGrammarPoolContainer) grammar, fSchemaValidationManager);
      }
      /** For third party grammars, use the JAXP validator component. * */
      else {
        validatorComponent = new JAXPValidatorComponent(grammar.newValidatorHandler());
        fSchemaValidationManager = null;
        fUnparsedEntityHandler = null;
        fSchemaValidatorComponentManager = config;
      }
      config.addRecognizedFeatures(validatorComponent.getRecognizedFeatures());
      config.addRecognizedProperties(validatorComponent.getRecognizedProperties());
      config.setDocumentHandler((XMLDocumentHandler) validatorComponent);
      ((XMLDocumentSource) validatorComponent).setDocumentHandler(xmlReader);
      xmlReader.setDocumentSource((XMLDocumentSource) validatorComponent);
      fSchemaValidator = validatorComponent;
    } else {
      fSchemaValidationManager = null;
      fUnparsedEntityHandler = null;
      fSchemaValidatorComponentManager = null;
      fSchemaValidator = null;
    }

    // Initial EntityResolver
    fInitEntityResolver = xmlReader.getEntityResolver();
  }