Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys INDENT.

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

From source file:com.sinet.gage.dlap.utils.XMLUtils.java

/**
 * @param String/*  w ww.ja  va  2s .c  o  m*/
 * @param String
 * @return String
 */
public static String parseXML(String xml, String rootElementName) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes()));

        Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0);
        // Imports a node from another document to this document,
        // without altering
        Document newDoc2 = db.newDocument();
        // or removing the source node from the original document
        Node copiedNode = newDoc2.importNode(element, true);
        // Adds the node to the end of the list of children of this node
        newDoc2.appendChild(copiedNode);

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");

        Writer out = new StringWriter();

        tf.transform(new DOMSource(newDoc2), new StreamResult(out));

        return out.toString();
    } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) {
        LOGGER.error("Exception in parsing xml from response: ", e);
    }
    return "";
}

From source file:Main.java

/**
 * Adds a new node to a file./*ww  w . j  a  va2 s  .  c  om*/
 *
 * @param nodeType {@link String} The type of the element to add.
 * @param idField {@link String} The name of the field used to identify this
 * node.
 * @param nodeID {@link String} The identifier for this node, so its data
 * can be later retrieved and modified.
 * @param destFile {@link File} The file where the node must be added.
 * @param attributes {@link ArrayList} of array of String. The arrays must
 * be bidimensional (first index must contain attribute name, second one
 * attribute value). Otherwise, an error will be thrown. However, if
 * <value>null</value>, it is ignored.
 */
public static void addNode(String nodeType, String idField, String nodeID, File destFile,
        ArrayList<String[]> attributes) {
    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            if (it.next().length != 2) {
                throw new IllegalArgumentException("Invalid attribute combination");
            }
        }
    }
    /*
     * XML DATA CREATION - BEGINNING
     */
    DocumentBuilder docBuilder;
    Document doc;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = docBuilder.parse(destFile);
    } catch (SAXException | IOException | ParserConfigurationException ex) {
        return;
    }

    Node index = doc.getFirstChild(), newElement = doc.createElement(nodeType);
    NamedNodeMap elementAttributes = newElement.getAttributes();

    Attr attrID = doc.createAttribute(idField);
    attrID.setValue(nodeID);
    elementAttributes.setNamedItem(attrID);

    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            String[] x = it.next();
            Attr currAttr = doc.createAttribute(x[0]);
            currAttr.setValue(x[1]);
            elementAttributes.setNamedItem(currAttr);
        }
    }

    index.appendChild(newElement);
    /*
     * XML DATA CREATION - END
     */

    /*
     * XML DATA DUMP - BEGINNING
     */
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException ex) {
        return;
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    try {
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        return;
    }

    String xmlString = result.getWriter().toString();
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(destFile))) {
        bufferedWriter.write(xmlString);
    } catch (IOException ex) {
    }
    /*
     * XML DATA DUMP - END
     */
}

From source file:com.github.caldav4j.methods.CalDAVReportTest.java

private String ElementoString(Element node) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    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(node);
    transformer.transform(source, result);

    String xmlString = result.getWriter().toString();
    log.info(xmlString);//  w  ww. j  a  v  a  2 s.com
    return xmlString;
}

From source file:com.cuubez.visualizer.processor.ConfigurationProcessor.java

private static String getDocumentAsString(Document doc)
        throws TransformerFactoryConfigurationError, TransformerException {

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);

    return result.getWriter().toString();
}

From source file:hd3gtv.as5kpc.protocol.ProtocolHandler.java

/**
 * @return maybe null//from   w  w w. j a  v  a2 s. co  m
 */
private ServerResponse send(Document document, ServerResponse response) throws IOException {
    byte[] message = null;
    try {
        DOMSource domSource = new DOMSource(document);
        StringWriter stringwriter = new StringWriter();
        StreamResult streamresult = new StreamResult(stringwriter);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(domSource, streamresult);
        message = stringwriter.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new IOException("Encoding XML is not supported", uee);
    } catch (TransformerException tc) {
        throw new IOException("Converting error between XML and String", tc);
    }

    if (log.isTraceEnabled()) {
        log.trace("Raw send >> " + new String(message, "UTF-8"));
    }

    /**
     * Send XML request
     */
    os.write(message);
    os.flush();

    /**
     * Wait and recevied XML response
     */
    int bytesRead;
    byte[] bytes = new byte[4092];
    try {
        while (socket.isConnected()) {
            try {
                while ((bytesRead = is.read(bytes)) != -1) {
                    try {
                        if (log.isTraceEnabled()) {
                            log.trace("Raw receive << " + new String(bytes, 0, bytesRead, "UTF-8"));
                        }
                        /**
                         * Decode XML response
                         */
                        ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0, bytesRead);
                        DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory.newDocumentBuilder();
                        xmlDocumentBuilder.setErrorHandler(null);
                        document = xmlDocumentBuilder.parse(bais);
                        Element root_element = document.getDocumentElement();

                        /**
                         * Check if result is valid/positive.
                         */
                        Element rply = (Element) root_element.getElementsByTagName("Reply").item(0);
                        String status = rply.getAttribute("Status").toLowerCase();
                        if (status.equals("ok") == false) {
                            String _message = "(no message)";
                            if (rply.hasAttribute("Msg")) {
                                _message = rply.getAttribute("Msg");
                            }

                            String error_type = "";
                            if (rply.hasAttribute("ErrNum")) {
                                int err = Integer.parseInt(rply.getAttribute("ErrNum"));
                                switch (err) {
                                case 1:
                                    error_type = "Command Error";
                                    break;
                                case 2:
                                    error_type = "System Error";
                                    break;
                                case 3:
                                    error_type = "XML format error";
                                    break;
                                case 4:
                                    error_type = "System BUSY";
                                    break;
                                default:
                                    break;
                                }
                            }

                            if (status.equals("warning")) {
                                log.warn(_message + ": " + error_type);
                            }
                            if (status.equals("error")) {
                                if (response instanceof ServerResponseClipdata
                                        && _message.toLowerCase().endsWith("does not exist")) {
                                    ((ServerResponseClipdata) response).not_found = true;
                                    return response;
                                } else {
                                    throw new IOException(
                                            "Server return: \"" + _message + ": " + error_type + "\"");
                                }
                            }
                        }

                        if (response != null) {
                            response.injectServerResponse(root_element);
                        }

                        return response;
                    } catch (ParserConfigurationException pce) {
                        log.error("DOM parser error", pce);
                    } catch (SAXException se) {
                        log.error("XML Struct error", se);
                    } catch (Exception e) {
                        log.error("Invalid response", e);
                    }
                }
            } catch (SocketTimeoutException soe) {
                Thread.sleep(100);
            }
        }
    } catch (InterruptedException e) {
    } catch (IOException e) {
        if (e.getMessage().equalsIgnoreCase("Socket closed")) {
            log.debug("Socket is closed, quit parser");
        } else {
            throw e;
        }
    }
    return null;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToXML.java

/**
 * @param items/*from   www.j  a  v  a  2  s.  com*/
 * @return
 */
public static void convertToXml(OutputStream outputStream, Document dom) {
    Transformer transformer = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    } catch (TransformerConfigurationException e) {
        LOGGER.error(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return;
    }
    try {
        transformer.transform(new DOMSource(dom), new StreamResult(outputStream));
    } catch (TransformerException e) {
        LOGGER.error("Transform failed with TransformerException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
}

From source file:PayHost.Utilities.java

/**
 * Make the http post response pretty with indentation
 *
 * @param input Response/*  w ww .  j av  a2  s . c  o m*/
 * @param indent Indentation level
 * @return String in pretty format
 */
public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (IllegalArgumentException | TransformerException e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:com.sangupta.clitools.file.Format.java

private void formatXML(File file) {
    try {/*from   www  .java 2s .  co m*/
        Source xmlInput = new StreamSource(file);
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", 4);

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        String out = xmlOutput.getWriter().toString();

        // add a new line after "?>< for next tag starting
        int index = out.indexOf("\"?><");
        if (index > 0) {
            out = out.substring(0, index + 3) + "\n" + out.substring(index + 3);
        }

        if (!this.overwrite) {
            System.out.println(out);
            return;
        }

        org.apache.commons.io.FileUtils.writeStringToFile(file, out);
    } catch (Exception e) {
        System.out.println("Unable to format file!");
        e.printStackTrace();
    }
}

From source file:hydrograph.ui.common.util.XMLUtil.java

/**
 * /* w w w.  j a v  a 2  s  .  c  om*/
 * Format given XML string
 * 
 * @param xmlString
 * @return String
 */
public static String formatXML(String xmlString) {

    try (Writer writer = new StringWriter()) {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(TRANSFORMER_INDENT_AMOUNT_KEY, INDENT_SPACE);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(writer);

        Document xmlDoc = convertStringToDocument(xmlString);

        if (xmlDoc == null) {
            return xmlString;
        }

        DOMSource source = new DOMSource(xmlDoc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (TransformerException e) {
        logger.debug("Unable to format XML string", e);
    } catch (IOException e) {
        logger.debug("Unable to format XML string", e);
    }

    return null;
}

From source file:net.sf.jabref.exporter.OpenOfficeDocumentCreator.java

private static void exportOpenOfficeCalcXML(File tmpFile, BibDatabase database, List<BibEntry> entries) {
    OOCalcDatabase od = new OOCalcDatabase(database, entries);

    try (Writer ps = new OutputStreamWriter(new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) {
        DOMSource source = new DOMSource(od.getDOMrepresentation());
        StreamResult result = new StreamResult(ps);
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.transform(source, result);
    } catch (Exception e) {
        throw new Error(e);
    }/*from  w w w .  j  av a2s  . c om*/

}