Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setCoalescing()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setCoalescing() . 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: FilePreferencesXmlSupport.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Load an XML document from specified input stream, which must have the
 * requisite DTD URI.
 */
private static Document loadPrefsDoc(InputStream in) throws SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 2
Source File: BasicParserPool.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializePool() throws XMLParserException {
    if (!dirtyBuilderConfiguration) {
        // in case the pool was initialized by some other thread
        return;
    }

    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);

    poolVersion++;
    dirtyBuilderConfiguration = false;
    builderFactory = newFactory;
    builderPool.clear();
}
 
Example 3
Source File: XmlSupport.java    From java-ocr-api with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Document loadPrefsDoc(InputStream in)
    throws SAXException, IOException
{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringComments(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new Resolver());
        db.setErrorHandler(new EH());
        return db.parse(new InputSource(in));
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 4
Source File: Bug6794483Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public Document parseXmlFile(String fileName) throws Exception {
    System.out.println("Parsing XML file... " + fileName);
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setCoalescing(true);
    docBuilderFactory.setXIncludeAware(true);
    System.out.println("Include: " + docBuilderFactory.isXIncludeAware());
    docBuilderFactory.setNamespaceAware(true);
    docBuilderFactory.setExpandEntityReferences(true);

    docBuilder = docBuilderFactory.newDocumentBuilder();

    File sourceFile = new File(fileName);
    doc = docBuilder.parse(sourceFile);

    System.out.println("XML file parsed");
    return doc;

}
 
Example 5
Source File: JsonDataGeneratorTest.java    From json-data-generator with Apache License 2.0 6 votes vote down vote up
@Test
  public void testXmlTemplate() throws IOException, JsonDataGeneratorException, SAXException, ParserConfigurationException, XpathException {
      parser.generateTestDataJson(this.getClass().getClassLoader().getResource("xmlfunctionWithRepeat.xml"), outputStream);
      
      ByteArrayInputStream inputstream = new ByteArrayInputStream(outputStream.toByteArray());
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setIgnoringComments(true);
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(inputstream);
      XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();
      String value = simpleXpathEngine.evaluate("//root/tags", doc);
assertEquals(value.split(",").length, 7);
assertTrue(simpleXpathEngine.evaluate("//root/element[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/element[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[3]/name", doc).length() > 1);
  }
 
Example 6
Source File: DOMHelper.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example 7
Source File: JAXPTestUtilities.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compare contents of golden file with test output file by their document
 * representation.
 * Here we ignore the white space and comments. return true if they're
 * lexical identical.
 * @param goldfile Golden output file name.
 * @param resultFile Test output file name.
 * @return true if two file's document representation are identical.
 *         false if two file's document representation are not identical.
 * @throws javax.xml.parsers.ParserConfigurationException if the
 *         implementation is not available or cannot be instantiated.
 * @throws SAXException If any parse errors occur.
 * @throws IOException if an I/O error occurs reading from the file or a
 *         malformed or unmappable byte sequence is read .
 */
public static boolean compareDocumentWithGold(String goldfile, String resultFile)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    DocumentBuilder db = factory.newDocumentBuilder();

    Document goldD = db.parse(Paths.get(goldfile).toFile());
    goldD.normalizeDocument();
    Document resultD = db.parse(Paths.get(resultFile).toFile());
    resultD.normalizeDocument();
    return goldD.isEqualNode(resultD);
}
 
Example 8
Source File: TransformationUtilityTestHelper.java    From butterfly with MIT License 6 votes vote down vote up
/**
 * Assert that the specified XML file has not semantically changed,
 * although it might be identical to the original one due to format
 * changes, comments not being present, etc
 *
 * @param relativeFilePath relative path to file to be evaluated
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
protected void assertEqualsXml(String relativeFilePath) throws ParserConfigurationException, IOException, SAXException {
    File originalFile = new File(appFolder, relativeFilePath);
    File transformedFile = new File(transformedAppFolder, relativeFilePath);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document originalXml = builder.parse(originalFile);
    Document transformedXml = builder.parse(transformedFile);

    originalXml.normalizeDocument();
    transformedXml.normalizeDocument();

    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);

    Assert.assertTrue(XMLUnit.compareXML(originalXml, transformedXml).similar());
}
 
Example 9
Source File: StyleableEmailContentServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
protected static DocumentBuilder getDocumentBuilder(boolean coalesce) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setCoalescing(coalesce);
        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        String message = "Error constructing document builder";
        LOG.error(message, e);
        throw new WorkflowRuntimeException(message, e);
    }
}
 
Example 10
Source File: MicroHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToMicroNode () throws SAXException, IOException, ParserConfigurationException
{
  final String sXML = "<?xml version='1.0'?>" +
                      "<!DOCTYPE root [ <!ENTITY sc \"sc.exe\"> <!ELEMENT root (child, child2)> <!ELEMENT child (#PCDATA)> <!ELEMENT child2 (#PCDATA)> ]>" +
                      "<root attr='value'>" +
                      "<![CDATA[hihi]]>" +
                      "text" +
                      "&sc;" +
                      "<child xmlns='http://myns' a='b' />" +
                      "<child2 />" +
                      "<!-- comment -->" +
                      "<?stylesheet x y z?>" +
                      "</root>";
  final DocumentBuilderFactory aDBF = XMLFactory.createDefaultDocumentBuilderFactory ();
  aDBF.setCoalescing (false);
  aDBF.setIgnoringComments (false);
  final Document doc = aDBF.newDocumentBuilder ().parse (new StringInputStream (sXML, StandardCharsets.ISO_8859_1));
  assertNotNull (doc);
  final IMicroNode aNode = MicroHelper.convertToMicroNode (doc);
  assertNotNull (aNode);
  try
  {
    MicroHelper.convertToMicroNode (null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example 11
Source File: Support_Xml.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static Document domOf(String xml) throws Exception {
    // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);

    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilder builder = dbf.newDocumentBuilder();

    return builder.parse(stream);
}
 
Example 12
Source File: XMLLayoutTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parses the string as the body of an XML document and returns the document element.
 * @param source source string.
 * @return document element.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
private Element parse(final String source) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setCoalescing(true);

  DocumentBuilder builder = factory.newDocumentBuilder();
  Reader reader = new StringReader(source);
  Document doc = builder.parse(new InputSource(reader));

  return doc.getDocumentElement();
}
 
Example 13
Source File: HTMLLayoutTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parses the string as the body of an XML document and returns the document element.
 * @param source source string.
 * @return document element.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
private Document parse(final String source) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setCoalescing(true);

  DocumentBuilder builder = factory.newDocumentBuilder();
  Reader reader = new StringReader(source);

  return builder.parse(new InputSource(reader));
}
 
Example 14
Source File: DocumentBuilderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test the default functionality of newInstance method. To test
 * the isCoalescing method and setCoalescing This checks to see if the CDATA
 * and text nodes got combined In that case it will print "&lt;xml&gt;This
 * is not parsed&lt;/xml&gt; yet".
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory02() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(new File(XML_DIR, "DocumentBuilderFactory01.xml"));
    Element e = (Element) doc.getElementsByTagName("html").item(0);
    NodeList nl = e.getChildNodes();
    assertEquals(nl.getLength(), 1);
}
 
Example 15
Source File: XMLFactory.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link DocumentBuilderFactory} using the defaults defined in
 * this class ({@link #DEFAULT_DOM_NAMESPACE_AWARE},
 * {@link #DEFAULT_DOM_VALIDATING} etc.).
 *
 * @return Never <code>null</code>.
 */
@Nonnull
public static DocumentBuilderFactory createDefaultDocumentBuilderFactory ()
{
  final DocumentBuilderFactory aDocumentBuilderFactory = DocumentBuilderFactory.newInstance ();
  aDocumentBuilderFactory.setNamespaceAware (DEFAULT_DOM_NAMESPACE_AWARE);
  aDocumentBuilderFactory.setValidating (DEFAULT_DOM_VALIDATING);
  aDocumentBuilderFactory.setIgnoringElementContentWhitespace (DEFAULT_DOM_IGNORING_ELEMENT_CONTENT_WHITESPACE);
  aDocumentBuilderFactory.setExpandEntityReferences (DEFAULT_DOM_EXPAND_ENTITY_REFERENCES);
  aDocumentBuilderFactory.setIgnoringComments (DEFAULT_DOM_IGNORING_COMMENTS);
  aDocumentBuilderFactory.setCoalescing (DEFAULT_DOM_COALESCING);
  try
  {
    // Set secure processing to be the default. This is anyway the default in
    // JDK8
    aDocumentBuilderFactory.setFeature (EXMLParserFeature.SECURE_PROCESSING.getName (), true);
  }
  catch (final ParserConfigurationException ex1)
  {
    // Ignore
  }
  try
  {
    aDocumentBuilderFactory.setXIncludeAware (DEFAULT_DOM_XINCLUDE_AWARE);
  }
  catch (final UnsupportedOperationException ex)
  {
    // Ignore
  }
  return aDocumentBuilderFactory;
}
 
Example 16
Source File: JsSimpleDomParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
public JsSimpleDomParser() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setCoalescing(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: EmailNode.java    From rice with Educational Community License v2.0 4 votes vote down vote up
protected DocumentBuilder getDocumentBuilder(boolean coalesce) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(coalesce);
return dbf.newDocumentBuilder();
   }
 
Example 18
Source File: NoteConfigComponent.java    From rice with Educational Community License v2.0 4 votes vote down vote up
protected DocumentBuilder getDocumentBuilder(boolean coalesce) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(coalesce);
    return dbf.newDocumentBuilder();
}
 
Example 19
Source File: MXFFragmentBuilderTest.java    From regxmllib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    /* build the dictionaries */
    mds_catsup = buildDictionaryCollection(
        "registers/catsup/Elements.xml",
        "registers/catsup/Groups.xml",
        "registers/catsup/Types.xml"
    );

    assertNotNull(mds_catsup);

    /* build the dictionaries */
    mds_brown_sauce = buildDictionaryCollection(
        "registers/brown_sauce/Elements.xml",
        "registers/brown_sauce/Groups.xml",
        "registers/brown_sauce/Types.xml"
    );

    assertNotNull(mds_brown_sauce);

    /* build the dictionaries */
    mds_snapshot = buildDictionaryCollection(
        "registers/snapshot/Elements.xml",
        "registers/snapshot/Groups.xml",
        "registers/snapshot/Types.xml"
    );

    assertNotNull(mds_snapshot);

    mds_ponzu = buildDictionaryCollection(
        "registers/ponzu/Elements.xml",
        "registers/ponzu/Groups.xml",
        "registers/ponzu/Types.xml"
    );

    assertNotNull(mds_ponzu);


    /* setup the doc builder */
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    db = dbf.newDocumentBuilder();

    assertNotNull(db);
}
 
Example 20
Source File: XmlParserFactory.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
private DocumentBuilderFactory createDocumentBuilderFactory() {
	DocumentBuilderFactory result = DocumentBuilderFactory.newInstance();
	result.setNamespaceAware(namespaceAware);
	result.setCoalescing(coalescing);
	return result;
}