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:Exporters.SaveFileExporter.java
public void save(File outfile, DefaultMutableTreeNode root) throws Exception { System.out.println("===SaveFileExporter==save:" + outfile.getAbsolutePath()); // Create new XML document DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Create the root element Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("reportCompiler"); rootElement.setAttribute("date", getNow()); // Debugging to say when saved // TODO - figure out a universal means to get the current version of the generating tool // Initial thoughts would be to create a convenience class in Utils package with some // final variables that can be updated when issuing a release. doc.appendChild(rootElement);/*from w ww . jav a 2 s.co m*/ Element vulnerabilitiesElement = doc.createElement("vulnerabilities"); Enumeration enums = root.children(); while (enums.hasMoreElements()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) enums.nextElement(); Object obj = node.getUserObject(); if (obj instanceof Vulnerability) { Vulnerability vuln = (Vulnerability) obj; Element vulnElement = getVulnAsElement(vuln, doc); if (vulnElement != null) { vulnerabilitiesElement.appendChild(vulnElement); } } } rootElement.appendChild(vulnerabilitiesElement); // now write the XML file // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outfile); // Output to console for testing //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); }
From source file:com.esri.geoportal.commons.csw.client.impl.Client.java
@Override public String readMetadata(String id) throws Exception { LOG.debug(String.format("Executing readMetadata(id=%s)", id)); loadCapabilities();//from w ww.ja va 2s .c o m String getRecordByIdUrl = createGetMetadataByIdUrl(capabilites.get_getRecordByIDGetURL(), URLEncoder.encode(id, "UTF-8")); HttpGet getMethod = new HttpGet(getRecordByIdUrl); getMethod.setConfig(DEFAULT_REQUEST_CONFIG); try (CloseableHttpResponse httpResponse = httpClient.execute(getMethod); InputStream responseStream = httpResponse.getEntity().getContent();) { if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } String response = IOUtils.toString(responseStream, "UTF-8"); if (CONFIG_FOLDER_PATH.equals(profile.getMetadataxslt())) { return response; } // create transformer Templates template = TemplatesManager.getInstance().getTemplate(profile.getMetadataxslt()); Transformer transformer = template.newTransformer(); try (ByteArrayInputStream contentStream = new ByteArrayInputStream(response.getBytes("UTF-8"));) { // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(contentStream), new StreamResult(writer)); String intermediateResult = writer.toString(); // select url to get meta data DcList lstDctReferences = new DcList(intermediateResult); String xmlUrl = lstDctReferences.stream() .filter(v -> v.getValue().toLowerCase().endsWith(".xml") || v.getScheme().equals(SCHEME_METADATA_DOCUMENT)) .map(v -> v.getValue()).findFirst().orElse(""); // use URL to get meta data if (!xmlUrl.isEmpty()) { HttpGet getRequest = new HttpGet(xmlUrl); try (CloseableHttpResponse httpResp = httpClient.execute(getRequest); InputStream metadataStream = httpResp.getEntity().getContent();) { return IOUtils.toString(metadataStream, "UTF-8"); } } if (!intermediateResult.isEmpty()) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.INDENT, "yes"); ByteArrayInputStream intermediateStream = new ByteArrayInputStream( intermediateResult.getBytes("UTF-8")); StringWriter intermediateBuffer = new StringWriter(); tr.transform(new StreamSource(intermediateStream), new StreamResult(intermediateBuffer)); return intermediateBuffer.toString(); } catch (Exception ex) { return makeResourceFromCswResponse(response, id); } } return response; } } }
From source file:com.stratio.qa.cucumber.testng.CucumberReporter.java
@Override public void done() { try {/* w w w .ja v a 2 s . c o m*/ results.setAttribute("total", String.valueOf(getElementsCountByAttribute(suite, STATUS, ".*"))); results.setAttribute("passed", String.valueOf(getElementsCountByAttribute(suite, STATUS, "PASS"))); results.setAttribute("failed", String.valueOf(getElementsCountByAttribute(suite, STATUS, "FAIL"))); results.setAttribute("skipped", String.valueOf(getElementsCountByAttribute(suite, STATUS, "SKIP"))); suite.setAttribute("name", CucumberReporter.class.getName()); suite.setAttribute("duration-ms", String.valueOf(getTotalDuration(suite.getElementsByTagName("test-method")))); test.setAttribute("name", CucumberReporter.class.getName()); test.setAttribute("duration-ms", String.valueOf(getTotalDuration(suite.getElementsByTagName("test-method")))); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); URLOutputStream urlOS = null; try { urlOS = new URLOutputStream(Utils.toURL(url + cClass + additional + "TESTNG.xml")); this.writer = new UTF8OutputStreamWriter(urlOS); } catch (Exception e) { logger.error("error writing TESTNG.xml file", e); } StreamResult streamResult = new StreamResult(writer); DOMSource domSource = new DOMSource(document); transformer.transform(domSource, streamResult); jUnitSuite.setAttribute("name", callerClass + "." + featureName); jUnitSuite.setAttribute("tests", String.valueOf(getElementsCountByAttribute(suite, STATUS, ".*"))); jUnitSuite.setAttribute("failures", String.valueOf(getElementsCountByAttribute(suite, STATUS, "FAIL"))); jUnitSuite.setAttribute("skipped", String.valueOf(getElementsCountByAttribute(suite, STATUS, "SKIP"))); jUnitSuite.setAttribute("timestamp", new java.util.Date().toString()); jUnitSuite.setAttribute("time", String.valueOf(getTotalDurationMs(suite.getElementsByTagName("test-method")))); Transformer transformerJunit = TransformerFactory.newInstance().newTransformer(); transformerJunit.setOutputProperty(OutputKeys.INDENT, "yes"); try { urlOS = new URLOutputStream(Utils.toURL(url + cClass + additional + "JUNIT.xml")); this.writerJunit = new UTF8OutputStreamWriter(urlOS); } catch (Exception e) { logger.error("error writing TESTNG.xml file", e); } StreamResult streamResultJunit = new StreamResult(writerJunit); DOMSource domSourceJunit = new DOMSource(jUnitDocument); transformerJunit.transform(domSourceJunit, streamResultJunit); } catch (TransformerException e) { throw new CucumberException("Error transforming report.", e); } }
From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java
private XSSchemaSet parseSchema(Element schema) throws SchemaException { // Make sure that the schema parser sees all the namespace declarations DOMUtil.fixNamespaceDeclarations(schema); XSSchemaSet xss = null;/* w w w . j ava 2s. c o m*/ try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult result = new StreamResult(out); trans.transform(source, result); XSOMParser parser = createSchemaParser(); InputSource inSource = new InputSource(new ByteArrayInputStream(out.toByteArray())); // XXX: hack: it's here to make entity resolver work... inSource.setSystemId("SystemId"); // XXX: end hack inSource.setEncoding("utf-8"); parser.parse(inSource); xss = parser.getResult(); } catch (SAXException e) { throw new SchemaException("XML error during XSD schema parsing: " + e.getMessage() + "(embedded exception " + e.getException() + ") in " + shortDescription, e); } catch (TransformerException e) { throw new SchemaException("XML transformer error during XSD schema parsing: " + e.getMessage() + "(locator: " + e.getLocator() + ", embedded exception:" + e.getException() + ") in " + shortDescription, e); } catch (RuntimeException e) { // This sometimes happens, e.g. NPEs in Saxon if (LOGGER.isErrorEnabled()) { LOGGER.error("Unexpected error {} during parsing of schema:\n{}", e.getMessage(), DOMUtil.serializeDOMToString(schema)); } throw new SchemaException( "XML error during XSD schema parsing: " + e.getMessage() + " in " + shortDescription, e); } return xss; }
From source file:com.laex.j2objc.AntDelegate.java
/** * Append exclude pattern to xml.// ww w.j ava 2s. co m * * @param path * the path * @param pats * the pats * @throws ParserConfigurationException * the parser configuration exception * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. * @throws XPathExpressionException * the x path expression exception * @throws CoreException * the core exception * @throws TransformerException * the transformer exception */ private void appendExcludePatternToXML(IFile path, String[] pats) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, CoreException, TransformerException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(path.getContents()); XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); XPathExpression expr = xpath.compile("project/target/move/fileset"); Node node = (Node) expr.evaluate(dom, XPathConstants.NODE); NodeList children = node.getChildNodes(); // don't why the last node in the xml should be indexed by length - 2 Node excludeCopy = children.item(children.getLength() - 2).cloneNode(true); for (String pattern : pats) { if (StringUtils.isNotEmpty(pattern.trim())) { Node newnode = excludeCopy.cloneNode(true); newnode.getAttributes().getNamedItem("name").setNodeValue(pattern); node.appendChild(newnode); } } // Setup transformers TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(dom), new StreamResult(sw)); String output = sw.getBuffer().toString(); // save the ouput ByteArrayInputStream bis = new ByteArrayInputStream(output.getBytes("utf-8")); path.setContents(bis, 0, null); }
From source file:com.mirth.connect.plugins.datatypes.xml.XMLBatchAdaptor.java
private String toXML(Node node) throws Exception { Writer writer = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
public final void prettyPrint(Document xml) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(xml), new StreamResult(out)); System.out.println(out.toString()); }
From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java
public static void transformToFile(final File targetFile, final boolean asXml, final Document doc) throws TransformerConfigurationException, TransformerException, IOException { Transformer transformer;//from w w w . j a va 2 s .c o m Config config = CoverageReport.getConfig(); if (asXml) { transformer = getTransformer(null); } else { transformer = getTransformer('/' + JGenHtmlUtils.XSLT_NAME); transformer.setParameter("ext", config.getHtmlExt()); File cssFile = config.getCssFile(); if (cssFile != null) { transformer.setParameter("cssName", cssFile.getName()); } } DOMSource src = new DOMSource(doc); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult res; if (config.isGzip()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(targetFile)); res = new StreamResult(bos); transformer.transform(src, res); IOUtils.write(bos.toByteArray(), gzos); IOUtils.closeQuietly(gzos); } else { res = new StreamResult(targetFile); transformer.transform(src, res); } }
From source file:com.moviejukebox.tools.DOMHelper.java
/** * Write the Document out to a file using nice formatting * * @param doc The document to save/* ww w .j ava 2 s . co m*/ * @param localFile The file to write to * @return */ public static boolean writeDocumentToFile(Document doc, File localFile) { try { Transformer trans = TransformerFactory.newInstance().newTransformer(); // Define the output properties trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, YES); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); doc.setXmlStandalone(true); trans.transform(new DOMSource(doc), new StreamResult(localFile)); return true; } catch (IllegalArgumentException | DOMException | TransformerException error) { LOG.error("Error writing the document to {}", localFile); LOG.error("Message: {}", error.getMessage()); return false; } }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static void prettyPrintDOMWithEncoding(Document doc, String defaultEncoding, Result result) { Node firstChild = doc.getFirstChild(); boolean omitXMLDeclaration = false; String encoding = defaultEncoding; // default Encoding char set if non // is found in the PI if ((firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) && (firstChild.getNodeName().equals("xml"))) { omitXMLDeclaration = true;/*from w w w. j av a 2 s .co m*/ String piValue = firstChild.getNodeValue(); // extract from PI the encoding Char Set int encodingOffset = piValue.indexOf("encoding=\""); if (encodingOffset != -1) { encoding = piValue.substring(encodingOffset + 10); // remove the last " encoding = encoding.substring(0, encoding.length() - 1); } } try { Transformer t = getNewTransformer(); t.setOutputProperty(OutputKeys.ENCODING, encoding); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no"); t.transform(new DOMSource(doc), result); } catch (Exception e) { Engine.logEngine.error("Unexpected exception while pretty print DOM", e); } }