List of usage examples for javax.xml.transform OutputKeys INDENT
String INDENT
To view the source code for javax.xml.transform OutputKeys INDENT.
Click Source Link
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
public void writeXml(OutputStream fos) throws ConfigurationException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer;//from w w w. ja va2 s . c o m try { InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("strip-space.xsl"); StreamSource stream = new StreamSource(resourceAsStream); transformer = tFactory.newTransformer(stream); // transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Source src = new DOMSource(document); Result res = new StreamResult(fos); transformer.transform(src, res); } catch (TransformerConfigurationException e) { throw new ConfigurationException(e); } catch (TransformerException e) { throw new ConfigurationException(e); } finally { if (fos != null) { Utility.closeStream(fos); } } }
From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java
/** * Format the given XML document./*from w w w . j a v a 2s .co m*/ * * @param xml * @return * @throws SiteWhereException */ public static String format(Document xml) throws SiteWhereException { try { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); return out.toString(); } catch (Exception e) { throw new SiteWhereException("Unable to format XML document.", e); } }
From source file:com.ibm.xsp.webdav.DavXMLResponse.java
/** * Gets the transformer handler object where we write everything to * /*w w w .j av a2 s . c o m*/ * @param streamResult * the place where we write the result to * @return the body object to append XML tags to */ private TransformerHandler getSAXOutputObject(StreamResult streamResult) { // Factory pattern at work SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); // SAX2.0 ContentHandler that provides the append point and access to // serializing options TransformerHandler hd; try { hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");// Suitable // for // all // languages serializer.setOutputProperty(OutputKeys.METHOD, "xml"); if (this.extendedResult || true) { serializer.setOutputProperty(OutputKeys.INDENT, "yes"); } hd.setResult(streamResult); return hd; } catch (TransformerConfigurationException e) { LOGGER.error(e); } return null; }
From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java
private DocumentList traverse(String checkpoint) { // count the number of times the traverse() was called second_counter++;/*from w w w. ja v a 2 s .c o m*/ if (second_counter == 10) { // every 10 seconds print a message logger.log(Level.INFO, "[" + connector.getInstanceName() + "] Traverse after [" + checkpoint + "]"); second_counter = 0; } // set the current crawled checkpoint System.setProperty(this.getConnector().getInstanceName() + "_lcheckpoint", checkpoint); // initialize the basedocument list to return BaseDocumentList sdl = null; try { // convert a Date object into a 'numeric' format like // 200906010641010 Date conv_checkpoint = Util.getNumericDate_from_String(checkpoint); // if its the first time we're doing this...create the checkpoint // for now if (conv_checkpoint == null || checkpoint.equalsIgnoreCase("")) { Date now = new Date(); // hmmm...we could set the checkpoint here as either checkpoint = this.getConnector().getLastsync(); // or // checkpoint = Util.getNumericString_from_Date(now); } // initialize a document list with 0 items and now as the checkpoint sdl = new BaseDocumentList(0, checkpoint); // if your xslt is not processable, return nothing if (this.XSLTDoc == null) { logger.log(Level.SEVERE, "[" + connector.getInstanceName() + "] Response XSLT not compiled, not proceeded with transforms."); return sdl; } // ok...so our document list has nothing in it so lets go ask the // store if we // have any more docs to process... if (docListIndex.size() == 0) { getDocListAfter(checkpoint); } // now we have some docs in the document array we need to process if (docListIndex.size() > 0) { // get a doclist from the queue DocListEntry de = (DocListEntry) docListIndex.poll(); // now convert the doclistentry (which is a SOAP response doc) // XML to <document><document> logger.log(Level.FINE, "Attempting to convert string row to DOM object [" + de.getCheckpoint() + "]"); Document doc_in_xml = Util.XMLStringtoDoc(de.getResponseXML()); logger.log(Level.FINE, "Attempting to Transform DOM object to <document/> [" + de.getCheckpoint() + "]"); Document transformed_QueryResult = Util.TransformDoctoDoc(doc_in_xml, this.XSLTDoc); // TODO: DTD Validate the transformed SOAP query result logger.log(Level.FINE, "Extracting <document> objects from transformed response"); NodeList nl_documents = transformed_QueryResult.getElementsByTagName("documents"); // get the NodeList under <document> Node n_documents = nl_documents.item(0); Vector v_batch = new Vector(); for (int i = 0; i < n_documents.getChildNodes().getLength(); i++) { Node n_doc = n_documents.getChildNodes().item(i); if (n_doc.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); if (n_doc.getNodeName().equalsIgnoreCase("document")) { DOMResult dr = new DOMResult(); trans.transform(new DOMSource(n_doc), dr); Document newDoc = (Document) dr.getNode(); newDoc.getDocumentElement().normalize(); v_batch.add(newDoc); } } } logger.log(Level.FINE, "Found " + v_batch.size() + " documents in batch response"); // so now we've populated a vector (v_batch) with XML elements // of <document></document> // objects sdl = new BaseDocumentList(v_batch.size(), de.getCheckpoint()); for (int i = 0; i < v_batch.size(); i++) { // now convert each entry in the vector to a basedocument BaseSimpleDocument bdoc = this.convertXMLtoBaseDocument((Document) v_batch.get(i)); SimpleDocument sd = (SimpleDocument) bdoc; sdl.add(sd); } } if (sdl.size() > 0) { this.running_doc_counter = this.running_doc_counter + sdl.size(); logger.log(Level.INFO, "[" + connector.getInstanceName() + "]" + " Returning " + sdl.size() + " documents to the connector manager. "); } } catch (Exception ex) { logger.log(Level.SEVERE, "traverse() error " + ex); } // return the doclist return sdl; }
From source file:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java
private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException { /*<Mtbx>//from w w w . ja v a 2 s.c o m <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1"> <Parameter name="A" value="abc" type="string"/> <DataTable path="${WORKSPACE}\aa\bbb.xslx"/> . </Test> <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2"> <Parameter name="p1" value="123" type="int"/> <Parameter name="p4" value="123.4" type="float"/> . </Test> </Mtbx>*/ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Mtbx"); doc.appendChild(rootElement); for (TestExecutionInfo test : tests) { Element testElement = doc.createElement("Test"); String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName()) ? test.getPackageName() + "\\" : "") + test.getTestName(); testElement.setAttribute("name", packageAndTestName); String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + (StringUtils.isEmpty(test.getPackageName()) ? "" : OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getPackageName()) + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getTestName(); testElement.setAttribute("path", path); if (StringUtils.isNotEmpty(test.getDataTable())) { Element dataTableElement = doc.createElement("DataTable"); dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getDataTable()); testElement.appendChild(dataTableElement); } rootElement.appendChild(testElement); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { throw new IOException("Failed to build MTBX content : " + e.getMessage()); } }
From source file:com.vmware.identity.samlservice.Shared.java
/** * Print out XML node to a stream/* w w w .j a va 2 s. co m*/ * * @param xml * @param out * @throws TransformerConfigurationException * @throws TransformerFactoryConfigurationError * @throws TransformerException * @throws UnsupportedEncodingException */ private static final void prettyPrint(Node xml, OutputStream out) throws Exception { TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("indent-number", 4); Transformer tf = tFactory.newTransformer(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty(OutputKeys.METHOD, "xml"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5"); StreamResult result = new StreamResult(new OutputStreamWriter(out, "UTF-8")); tf.transform(new DOMSource(xml), result); }
From source file:com.microfocus.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java
private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException { /*<Mtbx>// w ww .j a va 2 s. c o m <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1"> <Parameter name="A" value="abc" type="string"/> <DataTable path="${WORKSPACE}\aa\bbb.xslx"/> . </Test> <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2"> <Parameter name="p1" value="123" type="int"/> <Parameter name="p4" value="123.4" type="float"/> . </Test> </Mtbx>*/ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Mtbx"); doc.appendChild(rootElement); for (TestExecutionInfo test : tests) { Element testElement = doc.createElement("Test"); String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName()) ? test.getPackageName() + "\\" : "") + test.getTestName(); testElement.setAttribute("name", packageAndTestName); String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + (StringUtils.isEmpty(test.getPackageName()) ? "" : SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getPackageName()) + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getTestName(); testElement.setAttribute("path", path); if (StringUtils.isNotEmpty(test.getDataTable())) { Element dataTableElement = doc.createElement("DataTable"); dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getDataTable()); testElement.appendChild(dataTableElement); } rootElement.appendChild(testElement); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { throw new IOException("Failed to build MTBX content : " + e.getMessage()); } }
From source file:org.apache.lens.regression.util.Util.java
public static final void prettyPrint(Document xml) throws TransformerFactoryConfigurationError, TransformerException { xml.normalize();// w w w .j a v a 2s . com Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult output = new StreamResult(new File(localFile)); Source input = new DOMSource(xml); transformer.transform(input, output); }
From source file:lu.tudor.santec.dicom.gui.header.Dcm2Xml.java
public void convert(File ifile, File ofile) throws IOException, TransformerConfigurationException { DicomInputStream dis = new DicomInputStream(ifile); FileOutputStream fos = null;/*from w ww. j a va 2 s . c om*/ try { TransformerHandler th = getTransformerHandler(); th.getTransformer().setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); th.setResult(ofile != null ? new StreamResult(fos = new FileOutputStream(ofile)) : new StreamResult(System.out)); final SAXWriter writer = new SAXWriter(th, comments ? th : null); writer.setBaseDir(baseDir); writer.setExclude(exclude); dis.setHandler(writer); dis.readDicomObject(new BasicDicomObject(), -1); } finally { if (fos != null) fos.close(); dis.close(); } }
From source file:apiconnector.TestDataFunctionality.java
public static String toPrettyString(String xml, int indent) throws Exception { // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags 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); }//from www .j a v a 2 s. c o m // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); }