/** @tests javax.xml.parsers.DocumentBuilderFactory#setExpandEntityReferences(boolean). */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setExpandEntityReferences",
      args = {boolean.class})
  public void test_setExpandEntityReferencesZ() {
    dbf.setExpandEntityReferences(true);
    assertTrue(dbf.isExpandEntityReferences());

    Exception parseException = null;
    DocumentBuilder parser = null;

    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      assertNotNull(document);

    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }

    dbf.setExpandEntityReferences(false);
    assertFalse(dbf.isExpandEntityReferences());
    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      assertNotNull(document);

    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }
  }
 @Override
 public SAXParseException[] validate(Source source, ValidationErrorHandler errorHandler)
     throws IOException {
   if (errorHandler == null) {
     errorHandler = new DefaultValidationErrorHandler();
   }
   Validator validator = schema.newValidator();
   validator.setErrorHandler(errorHandler);
   try {
     validator.validate(source);
     return errorHandler.getErrors();
   } catch (SAXException ex) {
     throw new XmlValidationException("Could not validate source: " + ex.getMessage(), ex);
   }
 }
Beispiel #3
0
  /**
   * Attempts to validate the given XML string using Java's XML validation facility. Requires Java
   * 1.5+.
   *
   * @param xml The XML string to validate.
   * @param label String describing the type of XML being validated.
   * @return whether or not validation was successful.
   */
  public static boolean validateXML(String xml, String label) {
    if (label == null) label = "XML";
    Exception exception = null;

    // get path to schema from root element using SAX
    LOGGER.info("Parsing schema path");
    ValidationSAXHandler saxHandler = new ValidationSAXHandler();
    try {
      // Java XML factories are not declared to be thread safe
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();
      InputStream is = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING));
      saxParser.parse(is, saxHandler);
    } catch (ParserConfigurationException exc) {
      exception = exc;
    } catch (SAXException exc) {
      exception = exc;
    } catch (IOException exc) {
      exception = exc;
    }
    if (exception != null) {
      LOGGER.warn("Error parsing schema path from {}", label, exception);
      return false;
    }
    String schemaPath = saxHandler.getSchemaPath();
    if (schemaPath == null) {
      LOGGER.error("No schema path found. Validation cannot continue.");
      return false;
    }
    LOGGER.info(schemaPath);

    LOGGER.info("Validating {}", label);

    // compile the schema
    URI schemaLocation = null;
    try {
      schemaLocation = new URI(schemaPath);
    } catch (URISyntaxException exc) {
      LOGGER.info("Error accessing schema at {}", schemaPath, exc);
      return false;
    }
    Schema schema = schemas.get().get(schemaLocation);
    if (schema == null) {
      try {
        schema = FACTORY.newSchema(schemaLocation.toURL());
        schemas.get().put(schemaLocation, schema);
      } catch (MalformedURLException exc) {
        LOGGER.info("Error parsing schema at {}", schemaPath, exc);
        return false;
      } catch (SAXException exc) {
        LOGGER.info("Error parsing schema at {}", schemaPath, exc);
        return false;
      }
    }

    // get a validator from the schema
    Validator validator = schema.newValidator();

    // prepare the XML source
    StringReader reader = new StringReader(xml);
    InputSource is = new InputSource(reader);
    SAXSource source = new SAXSource(is);

    // validate the XML
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    validator.setErrorHandler(errorHandler);
    try {
      validator.validate(source);
    } catch (IOException exc) {
      exception = exc;
    } catch (SAXException exc) {
      exception = exc;
    }
    final int errors = errorHandler.getErrorCount();
    if (errors > 0) {
      LOGGER.info("Error validating document: {} errors found", errors);
      return false;
    } else LOGGER.info("No validation errors found.");
    return errorHandler.ok();
  }
  /** @tests javax.xml.parsers.DocumentBuilderFactory#setCoalescing(boolean). */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setCoalescing",
      args = {boolean.class})
  public void test_setCoalescingZ() {
    dbf.setCoalescing(true);
    assertTrue(dbf.isCoalescing());

    textElements.clear();
    cdataElements.clear();
    Exception parseException = null;
    DocumentBuilder parser = null;

    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      goThroughDocument((Node) document, "");
      assertTrue(textElements.contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));
    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }

    dbf.setCoalescing(false);
    assertFalse(dbf.isCoalescing());

    textElements.clear();
    cdataElements.clear();

    try {
      parser = dbf.newDocumentBuilder();
      ValidationErrorHandler errorHandler = new ValidationErrorHandler();
      parser.setErrorHandler(errorHandler);

      Document document = parser.parse(getClass().getResourceAsStream("/recipt.xml"));

      parseException = errorHandler.getFirstException();

      goThroughDocument((Node) document, "");

      assertFalse(textElements.contains("BeefParmesan<title>withGarlicAngelHairPasta</title>"));

    } catch (Exception ex) {
      parseException = ex;
    }
    parser.setErrorHandler(null);

    if (parseException != null) {
      fail("Unexpected exception " + parseException.getMessage());
    }
  }