List of usage examples for com.google.common.io CharSource toString
public String toString()
From source file:org.onlab.util.XmlString.java
private String prettyPrintXml(CharSource inputXml) { try {//from w w w . j av a 2 s. co m Document document; boolean wasFragment = false; DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // do not print error to stderr docBuilder.setErrorHandler(new DefaultHandler()); try { document = docBuilder.parse(new InputSource(inputXml.openStream())); } catch (SAXException e) { log.debug("will retry assuming input is XML fragment", e); // attempt to parse XML fragments, adding virtual root try { document = docBuilder.parse(new InputSource( CharSource.concat(CharSource.wrap("<vroot>"), inputXml, CharSource.wrap("</vroot>")) .openStream())); wasFragment = true; } catch (SAXException e1) { log.debug("SAXException after retry", e1); // Probably wasn't fragment issue, throwing original throw e; } } document.normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Setup pretty print options Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Return pretty print xml string StringWriter strWriter = new StringWriter(); if (wasFragment) { // print everything but virtual root node added NodeList children = document.getDocumentElement().getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { t.transform(new DOMSource(children.item(i)), new StreamResult(strWriter)); } } else { t.transform(new DOMSource(document), new StreamResult(strWriter)); } return strWriter.toString(); } catch (Exception e) { log.warn("Pretty printing failed", e); try { String rawInput = inputXml.read(); log.debug(" failed input: \n{}", rawInput); return rawInput; } catch (IOException e1) { log.error("Failed to read from input", e1); return inputXml.toString(); } } }