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:io.fabric8.tooling.archetype.builder.ArchetypeHelper.java
/** * Serializes the Document to a File./*from w ww . j a v a 2s . c o m*/ * * @param document * @param file * @throws IOException */ protected void writeXmlDocument(Document document, File file) throws IOException { try { Transformer tr = transformerFactory.newTransformer(); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream fileOutputStream = new FileOutputStream(file); tr.transform(new DOMSource(document), new StreamResult(fileOutputStream)); fileOutputStream.close(); } catch (Exception e) { throw new IOException(e.getMessage(), e); } }
From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java
private void run(Coord from, Coord to, long departureTime) { Locale locale = new Locale("en", "UK"); String pattern = "###.000000"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale); df.applyPattern(pattern);/*from w w w. j a v a 2 s .com*/ // Construct data //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat) //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">" + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\"" + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>" + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\"" + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "<Prod prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>" + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "") + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>" + "</ConReq>" + "</ReqC>"; PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/"); post.setRequestBody(text); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); // Display status code // System.out.println("Response status code: " + result); // Display response // System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(post.getResponseBodyAsStream()); if (writeOutput) { BufferedWriter writer = IOUtils.getBufferedWriter(filename); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult res = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, res); writer.flush(); writer.close(); } Node connectionList = document.getFirstChild().getFirstChild().getFirstChild(); NodeList connections = connectionList.getChildNodes(); int amount = connections.getLength(); for (int i = 0; i < amount; i++) { Node connection = connections.item(i); Node overview = connection.getFirstChild(); ; while (!overview.getNodeName().equals("Overview")) { overview = overview.getNextSibling(); } System.out.println(overview.getChildNodes().item(3).getTextContent()); int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent()); String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3); System.out.println(time); Date rideTime = VBBDATE.parse(time); int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds(); System.out.println(seconds + "s; transfers: " + transfers); if (seconds < this.bestRideTime) { this.bestRideTime = seconds; this.bestTransfers = transfers; } } } catch (Exception e) { this.bestRideTime = -1; this.bestTransfers = -1; } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); post.abort(); } }
From source file:com.krawler.formbuilder.servlet.workflowHandler.java
public String exportBPELFile(HttpServletRequest request, HttpServletResponse response) { Writer output = null;//from ww w . j a v a2s . com try { String workflow = request.getParameter("jsonnodeobj"); String linejson = request.getParameter("linejson"); String processId = request.getParameter("flowid"); String containerId = request.getParameter("containerId"); this.parentSplit = request.getParameter("parentSplit"); String path = ConfigReader.getinstance().get("workflowpath") + processId; path = path + System.getProperty("file.separator") + "Export"; File fdir = new File(path); if (!fdir.exists()) { fdir.mkdirs(); } File file = new File(fdir + System.getProperty("file.separator") + "flow.bpel"); if (file.exists()) { file.delete(); } output = new BufferedWriter(new FileWriter(file)); JSONObject jsonobj = new JSONObject(workflow); JSONObject json_line = new JSONObject(linejson); createDocument(); expwritebpel(jsonobj, containerId, processId, json_line); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans1 = transfac.newTransformer(); trans1.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans1.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult kwcresult = new StreamResult(sw); DOMSource kwcsource = new DOMSource(dom); trans1.transform(kwcsource, kwcresult); output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); output.write("\n"); output.write(sw.toString()); output.close(); return "{success:true}"; } catch (TransformerConfigurationException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } catch (JSONException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } catch (IOException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } finally { try { output.close(); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); return "{success:true}"; } } }
From source file:com.action.ExportAction.java
public File exportXMLAction(File file) throws Exception { //document//from w w w. jav a 2 s. c om DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element reportsElement = document.createElement("reports");// reportsElement.setAttribute("date", (new Date()).toString()); document.appendChild(reportsElement); System.out.println("exportXMLAction:" + tableCode); String[] ids = tableCode.split(","); for (String id : ids) { System.out.println("id:" + id); List<JQ_zhibiao_entity> list = Export.getDuizhaoByJqTbCode(id); document = Export.exportXML(reportsElement, document, list, id); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(file)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); pw.close(); return file; }
From source file:com.google.visualization.datasource.render.HtmlRenderer.java
/** * Transforms a document to a valid html string. * * @param document The document to transform * * @return A string representation of a valid html. *//*from www .ja v a 2s . com*/ private static String transformDocumentToHtmlString(Document document) { // Generate a CharSequence from the xml document. Transformer transformer = null; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e) { log.error("Couldn't create a transformer", e); throw new RuntimeException("Couldn't create a transformer. This should never happen.", e); } transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01//EN"); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.VERSION, "4.01"); DOMSource source = new DOMSource(document); Writer writer = new StringWriter(); StreamResult result = new StreamResult(writer); try { transformer.transform(source, result); } catch (TransformerException e) { log.error("Couldn't transform", e); throw new RuntimeException("Couldn't transform. This should never happen.", e); } return writer.toString(); }
From source file:ca.uviccscu.lp.utils.Utils.java
public static String documentToString(Document d) throws TransformerConfigurationException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(d); transformer.transform(source, result); String str = result.getWriter().toString(); return str;/*from w ww .j a v a 2s .c o m*/ }
From source file:org.apache.camel.component.cm.CMSenderOneMessageImpl.java
private String createXml(final CMMessage message) { try {//w w w . j ava 2s . c o m final ByteArrayOutputStream xml = new ByteArrayOutputStream(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // Get the DocumentBuilder final DocumentBuilder docBuilder = factory.newDocumentBuilder(); // Create blank DOM Document final DOMImplementation impl = docBuilder.getDOMImplementation(); final Document doc = impl.createDocument(null, "MESSAGES", null); // ROOT Element es MESSAGES final Element root = doc.getDocumentElement(); // AUTHENTICATION element final Element authenticationElement = doc.createElement("AUTHENTICATION"); final Element productTokenElement = doc.createElement("PRODUCTTOKEN"); authenticationElement.appendChild(productTokenElement); final Text productTokenValue = doc.createTextNode("" + productToken); productTokenElement.appendChild(productTokenValue); root.appendChild(authenticationElement); // MSG Element final Element msgElement = doc.createElement("MSG"); root.appendChild(msgElement); // <FROM>VALUE</FROM> final Element fromElement = doc.createElement("FROM"); fromElement.appendChild(doc.createTextNode(message.getSender())); msgElement.appendChild(fromElement); // <BODY>VALUE</BODY> final Element bodyElement = doc.createElement("BODY"); bodyElement.appendChild(doc.createTextNode(message.getMessage())); msgElement.appendChild(bodyElement); // <TO>VALUE</TO> final Element toElement = doc.createElement("TO"); toElement.appendChild(doc.createTextNode(message.getPhoneNumber())); msgElement.appendChild(toElement); // <DCS>VALUE</DCS> - if UNICODE - messageOut.isGSM338Enc // false if (message.isUnicode()) { final Element dcsElement = doc.createElement("DCS"); dcsElement.appendChild(doc.createTextNode("8")); msgElement.appendChild(dcsElement); } // <REFERENCE>VALUE</REFERENCE> -Alfanum final String id = message.getIdAsString(); if (id != null && !id.isEmpty()) { final Element refElement = doc.createElement("REFERENCE"); refElement.appendChild(doc.createTextNode("" + message.getIdAsString())); msgElement.appendChild(refElement); } // <MINIMUMNUMBEROFMESSAGEPARTS>1</MINIMUMNUMBEROFMESSAGEPARTS> // <MAXIMUMNUMBEROFMESSAGEPARTS>8</MAXIMUMNUMBEROFMESSAGEPARTS> if (message.isMultipart()) { final Element minMessagePartsElement = doc.createElement("MINIMUMNUMBEROFMESSAGEPARTS"); minMessagePartsElement.appendChild(doc.createTextNode("1")); msgElement.appendChild(minMessagePartsElement); final Element maxMessagePartsElement = doc.createElement("MAXIMUMNUMBEROFMESSAGEPARTS"); maxMessagePartsElement.appendChild(doc.createTextNode(Integer.toString(message.getMultiparts()))); msgElement.appendChild(maxMessagePartsElement); } // Creatate XML as String final Transformer aTransformer = TransformerFactory.newInstance().newTransformer(); aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(doc); final Result dest = new StreamResult(xml); aTransformer.transform(src, dest); return xml.toString(); } catch (final TransformerException e) { LOG.error("Cant serialize CMMessage {}: ", message, e); throw new XMLConstructionException(e); } catch (final ParserConfigurationException e) { LOG.error("Cant serialize CMMessage {}: ", message, e); throw new XMLConstructionException(e); } }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
private static String transformToString(Document document) { try {/* w w w.j av a 2 s .c om*/ TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(document), new StreamResult(buffer)); return buffer.toString(); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:XMLConfig.java
/** Saves configuration to an output stream * @param os output stream/*w w w . j av a 2 s .c om*/ */ public void save(OutputStream os) { if (isDelegated()) { _parent.save(os); return; } // Prepare the DOM document for writing Source source = new DOMSource(_document); /* // Prepare the output file Result result = new StreamResult(os); */ // Write the DOM document to the file try { TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", Integer.valueOf(2)); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(source, new StreamResult(new OutputStreamWriter(os, "utf-8"))); /* Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, result); */ } catch (TransformerException e) { throw new XMLConfigException("Error in save", e); } catch (UnsupportedEncodingException e) { throw new XMLConfigException("Error in save", e); } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute DML// w w w. j av a 2 s .c o m * * @param userDB * @param strQuery * @param listParam * @param resultType * @throws Exception */ public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final String resultType) throws Exception { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); Object effectObject = runSQLOther(userDB, strQuery, listParam); String strReturn = ""; if (resultType.equals(RESULT_TYPE.CSV.name())) { final StringWriter stWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stWriter, ','); String[] arryString = new String[2]; arryString[0] = "effectrow"; arryString[1] = String.valueOf(effectObject); csvWriter.writeNext(arryString); strReturn = stWriter.toString(); } else if (resultType.equals(RESULT_TYPE.JSON.name())) { final JsonArray jsonArry = new JsonArray(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("effectrow", String.valueOf(effectObject)); jsonArry.add(jsonObj); strReturn = JSONUtil.getPretty(jsonArry.toString()); } else {//if(resultType.equals(RESULT_TYPE.XML.name())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); Element row = doc.createElement("Row"); results.appendChild(row); Element node = doc.createElement("effectrow"); node.appendChild(doc.createTextNode(String.valueOf(effectObject))); row.appendChild(node); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); final StringWriter stWriter = new StringWriter(); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); strReturn = stWriter.toString(); } return strReturn; }