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

The following are Jave code examples for showing how to use setCoalescing() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: butterfly   File: CompareXMLFiles.java   View Source Code Vote up 6 votes
@Override
protected boolean compare(File baselineFile, File comparisonFile) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

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

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document baselineXml = builder.parse(baselineFile);
        Document comparisonXml = builder.parse(comparisonFile);

        baselineXml.normalizeDocument();
        comparisonXml.normalizeDocument();

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

        return XMLUnit.compareXML(baselineXml, comparisonXml).similar();
    } catch (SAXException | IOException | ParserConfigurationException e) {
        throw new TransformationUtilityException("An exception happened when comparing the two XML files", e);
    }
}
 
Example 2
Project: butterfly   File: TransformationUtilityTestHelper.java   View Source Code Vote up 6 votes
/**
 * 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 3
Project: ibench   File: AbstractCheckExpectedOutputTester.java   View Source Code Vote up 6 votes
public void compareFile(String fileLeft, String fileRight) throws SAXException, IOException, ParserConfigurationException, TransformerException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	dbf.setCoalescing(true);
	dbf.setIgnoringElementContentWhitespace(true);
	dbf.setIgnoringComments(true);

	DocumentBuilder db = dbf.newDocumentBuilder();

	Document doc1 = db.parse(new File(expectedPath + "/" + fileRight + ".xml"));
	doc1.normalizeDocument();

	Document doc2 = db.parse(new File(OUT_DIR + "/" + fileLeft + ".xml"));
	doc2.normalizeDocument();

	assertEquals("Output <" + fileLeft + "> is not the same as expected output <" +
			fileRight + ">", 
			docToString(doc1), 
			docToString(doc2));
}
 
Example 4
Project: lams   File: BasicParserPool.java   View Source Code Vote up 6 votes
/**
 * 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 5
Project: openjdk-jdk10   File: Bug6794483Test.java   View Source Code Vote up 6 votes
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 6
Project: openjdk-jdk10   File: Bug6879614Test.java   View Source Code Vote up 6 votes
@Test
public void testAttributeCaching() {
    File xmlFile = new File(getClass().getResource("Bug6879614.xml").getFile());
    DocumentBuilderFactory _documentBuilderFactory = DocumentBuilderFactory.newInstance();
    _documentBuilderFactory.setValidating(false);
    _documentBuilderFactory.setIgnoringComments(true);
    _documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    _documentBuilderFactory.setCoalescing(true);
    _documentBuilderFactory.setExpandEntityReferences(true);
    _documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder _documentBuilder = null;
    try {
        _documentBuilder = _documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Document xmlDoc = null;
    try {
        xmlDoc = _documentBuilder.parse(xmlFile);
        if (xmlDoc == null) {
            System.out.println("Hello!!!, there is a problem here");
        } else {
            System.out.println("Good, the parsing went through fine.");
        }
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 7
Project: openjdk-jdk10   File: JAXPTestUtilities.java   View Source Code Vote up 6 votes
/**
 * 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
Project: joai-project   File: XMLDocReader.java   View Source Code Vote up 5 votes
/**
 *  Gets a org.w3c.dom.Document for this record. This method is optimized to create only one DOM when
 *  accessed multiple times for the same XMLDocReader.
 *
 * @return    A org.w3c.dom.Document, or null if unable to read.
 */
public org.w3c.dom.Document getW3CXmlDoc() {
	if (w3cXmlDoc != null)
		return w3cXmlDoc;

	DocumentBuilderFactory docfactory
		 = DocumentBuilderFactory.newInstance();
	docfactory.setCoalescing(true);
	docfactory.setExpandEntityReferences(true);
	docfactory.setIgnoringComments(true);

	docfactory.setNamespaceAware(true);

	// We must set validation false since jdk1.4 parser
	// doesn't know about schemas.
	docfactory.setValidating(false);

	// Ignore whitespace doesn't work unless setValidating(true),
	// according to javadocs.
	docfactory.setIgnoringElementContentWhitespace(false);
	try {
		DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
		w3cXmlDoc = docbuilder.parse(getXml());
	} catch (Throwable e) {
		return null;
	}
	return w3cXmlDoc;
}
 
Example 9
Project: ciguan   File: AsXmlTool.java   View Source Code Vote up 5 votes
/**
 * Parses the xml stream.
 *
 * @param pInputSource the input source
 * @return the document
 * @throws Exception the in case a problem occurred.
 */
public static Document parseXmlStream(InputSource pInputSource) throws Exception {
    DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
    tFactory.setIgnoringComments(true);
    tFactory.setCoalescing(true); // Convert CDATA to Text nodes
    tFactory.setNamespaceAware(false); // No namespaces: this is default
    tFactory.setValidating(false); // Don't validate DTD: also default
    DocumentBuilder tParser = tFactory.newDocumentBuilder();
    return tParser.parse(pInputSource);
}
 
Example 10
Project: ciguan   File: ConfigTestUtil.java   View Source Code Vote up 5 votes
public static Document getDocument(InputStream pStream) throws Exception {
	DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
	tFactory.setIgnoringComments(true);
	tFactory.setCoalescing(true); // Convert CDATA to Text nodes
	tFactory.setNamespaceAware(false); // No namespaces: this is default
	tFactory.setValidating(false); // Don't validate DTD: also default

	DocumentBuilder tParser = tFactory.newDocumentBuilder();

	return tParser.parse(pStream);
}
 
Example 11
Project: convertigo-engine   File: SchemaUtils.java   View Source Code Vote up 5 votes
protected DocumentBuilderFactory initialValue() {
	try {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setNamespaceAware(true);
		documentBuilderFactory.setCoalescing(true);
		documentBuilderFactory.setFeature("http://apache.org/xml/features/validation/schema/normalized-value", false);
		
		return documentBuilderFactory;
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 12
Project: lams   File: StaticBasicParserPool.java   View Source Code Vote up 5 votes
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializeFactory() throws XMLParserException {
    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);
    builderFactory = newFactory;
}
 
Example 13
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document load(String paramString) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(true);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	return localDocumentBuilder.parse(paramString);
}
 
Example 14
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document load(File paramFile) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(true);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	return localDocumentBuilder.parse(paramFile);
}
 
Example 15
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document loadString(String paramString) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(false);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	char[] arrayOfChar = new char[paramString.length()];
	paramString.getChars(0, paramString.length(), arrayOfChar, 0);
	InputSource localInputSource = new InputSource(new CharArrayReader(arrayOfChar));
	return localDocumentBuilder.parse(localInputSource);
}
 
Example 16
Project: LibraSock   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document blankDocument(String paramString) throws Exception {
	DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
	localDocumentBuilderFactory.setIgnoringComments(false);
	localDocumentBuilderFactory.setIgnoringElementContentWhitespace(false);
	localDocumentBuilderFactory.setValidating(false);
	localDocumentBuilderFactory.setCoalescing(false);
	DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
	Document localDocument = localDocumentBuilder.newDocument();
	Element localElement = localDocument.createElement(paramString);
	localDocument.appendChild(localElement);
	return localDocument;
}
 
Example 17
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   View Source Code Vote up 5 votes
/**
 * 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 18
Project: hashsdn-controller   File: AbstractFeatureWrapper.java   View Source Code Vote up 5 votes
private static boolean isConfigSnapshot(final String fileName) {
    if (!Files.getFileExtension(fileName).equals(CONFIG_FILE_SUFFIX)) {
        return false;
    }

    if (fileName.endsWith("jetty.xml")) {
        // Special case - ignore the jetty.xml file as it contains a DTD and causes a "Connection refused"
        // error when it tries to go out to the network to retrieve it. We don't want it trying to go out
        // to the network nor do we want an error logged trying to parse it.
        return false;
    }

    File file = new File(System.getProperty("karaf.home"), fileName);
    try (FileInputStream fis = new FileInputStream(file)) {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        builderFactory.setCoalescing(true);
        builderFactory.setIgnoringElementContentWhitespace(true);
        builderFactory.setIgnoringComments(true);

        Element root = builderFactory.newDocumentBuilder().parse(fis).getDocumentElement();
        return ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME.equals(root.getLocalName());
    } catch (final ParserConfigurationException | IOException | SAXException e) {
        LOG.error("Could not parse XML file {}", file, e);
        return false;
    }
}
 
Example 19
Project: joai-project   File: XMLDoc.java   View Source Code Vote up 4 votes
/**
 *  Reads and parses the XML from the given source.
 */		
private final void doParseDoc(
	InputSource xmlSource,
	boolean validating,			// does parser validate
	boolean namespaceAware,		// is parser namespace aware
	boolean expandEntities)		// expand Entity refs
throws XMLException
{
	this.doc = null;

	if (bugs >= 1)
		prtln("getXmlDoc: systemid: \"" + systemid + "\"");
	DocumentBuilderFactory factory = null;
	try {
		factory = DocumentBuilderFactory.newInstance();
	} catch (FactoryConfigurationError fce) {
		mkerror("factory config error: " + fce);
	}

	factory.setValidating(validating);
	factory.setNamespaceAware(namespaceAware);
	factory.setExpandEntityReferences(expandEntities); // expand Entity rfs

	factory.setCoalescing(true);	// convert CDATA nodes to Text nodes
	factory.setIgnoringElementContentWhitespace(true);

	DocumentBuilder bldr = null;
	try {
		bldr = factory.newDocumentBuilder();
	} catch (ParserConfigurationException pce) {
		mkerror("parser config exc: " + pce);
	}

	SimpleErrorHandler simpleErrorHandler
		= new SimpleErrorHandler(errors, warnings);
	bldr.setErrorHandler(simpleErrorHandler);

	try {
		doc = bldr.parse(xmlSource);
	} catch (IOException ioe) {
		mkerror("Could not read xml doc file \"" + systemid
			 + "\"  exc: " + ioe.getMessage());
	} catch (SAXException sxe) {
		mkerror("Could not parse xml doc file \"" + systemid
			 + "\"  exc: " + sxe.getMessage());
	}
	hasErrors = simpleErrorHandler.hasErrors();
	hasWarnings = simpleErrorHandler.hasWarnings();
	///try{
	///	xmlSource.getByteStream().close();
	///}catch(Throwable e){}
	///xmlSource = null;
}