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.photon.phresco.plugins.xcode.Instrumentation.java

private void generateXMLReport(String location) {

    try {/*from   w  ww .  j  a v a2 s  .  co m*/
        String startTime = "";
        int total, pass, fail;
        total = pass = fail = 0;
        config = new XMLPropertyListConfiguration(location);
        ArrayList list = (ArrayList) config.getRoot().getChild(0).getValue();
        String key;

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(XMLConstants.TESTSUITES_NAME);
        doc.appendChild(root);
        Element testSuite = doc.createElement(XMLConstants.TESTSUITE_NAME);
        testSuite.setAttribute(XMLConstants.NAME, "FunctionalTestSuite");
        root.appendChild(testSuite);

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            startTime = config.getRoot().getChild(2).getValue().toString();

            break;
        }

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            ConfigurationNode con = config.getRoot().getChild(0);
            key = con.getName();

            if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.PASS)) {
                pass++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            } else if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.ERROR)) {
                fail++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            }

        }

        testSuite.setAttribute(XMLConstants.TESTS, String.valueOf(total));
        testSuite.setAttribute(XMLConstants.SUCCESS, String.valueOf(pass));
        testSuite.setAttribute(XMLConstants.FAILURES, String.valueOf(fail));

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

        File file = new File(project.getBasedir().getAbsolutePath() + File.separator + xmlResult);
        Writer bw = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(bw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);

    } catch (Exception e) {
        getLog().error("Interrupted while generating XML file");
    }
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

private static String transformElementNode(Node node) throws TransformerException {
    StringWriter stringWriter = new StringWriter();

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, Constants.YES);
    transformer.setOutputProperty(OutputKeys.INDENT, Constants.YES);
    transformer.transform(new DOMSource(node), new StreamResult(stringWriter));

    return stringWriter.toString().trim();
}

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }/* ww w .  j  a  v a2  s .  c  o m*/
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Turn an XML Source into a String.//ww w . ja  v  a2 s. c  o m
 * 
 * @param source
 *        the XML Source
 * @param indent
 *        if <em>true</em> then indent the result
 * @return the XML, as a String
 */
public String getXmlAsString(Source source, boolean indent) {
    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {
        Transformer xform = getTransformerFactory().newTransformer();
        if (indent) {
            xform.setOutputProperty(OutputKeys.INDENT, "yes");
            xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        }
        xform.transform(source, new StreamResult(byos));
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    return byos.toString();
}

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

private String ElementoString(Element node) throws TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

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

    String xmlString = result.getWriter().toString();
    log.info(xmlString);/*w  w w.  ja  v a2  s . c  o m*/
    return xmlString;
}

From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java

/**
 * Creates XML TransformerHandler/*from w ww  .  java 2 s .  c  o  m*/
 * @param xmlOutPath
 * @param dtdPath
 * @return
 * @throws IOException
 * @throws TransformerException
 */
public TransformerHandler getXMLTransformerHandler(OutputStream out) {
    StreamResult streamResult = new StreamResult(out);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = null;
    try {
        th = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        logger.error("Error on initiating TransformerHandler");
        e.printStackTrace();
    }
    Transformer serializer = th.getTransformer();
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    if (dtdPath != null)
        serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdPath);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    th.setResult(streamResult);
    return th;
}

From source file:net.sf.jabref.logic.mods.MODSEntry.java

@Override
public String toString() {
    StringWriter sresult = new StringWriter();
    try {/*www  .ja  v  a 2  s  .c o  m*/
        DOMSource source = new DOMSource(getDOMrepresentation());
        StreamResult result = new StreamResult(sresult);
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.transform(source, result);
    } catch (Exception e) {
        throw new Error(e);
    }
    return sresult.toString();
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static StringBuffer printDom(Node node, boolean indent, boolean omitXmlDeclaration) {
    StringWriter writer = new StringWriter();
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;//from w  w w . j  av a2 s  .com
    try {
        trans = transfac.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new SystemException("Error in XML configuration: " + e.getMessage(), e);
    }
    trans.setOutputProperty(OutputKeys.INDENT, (indent ? "yes" : "no"));
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // XALAN-specific
    trans.setParameter(OutputKeys.ENCODING, "utf-8");
    // Note: serialized XML does not contain xml declaration
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (omitXmlDeclaration ? "yes" : "no"));

    DOMSource source = new DOMSource(node);
    try {
        trans.transform(source, new StreamResult(writer));
    } catch (TransformerException e) {
        throw new SystemException("Error in XML transformation: " + e.getMessage(), e);
    }

    return writer.getBuffer();
}

From source file:org.syncope.core.util.ImportExport.java

public void export(final OutputStream os)
        throws SAXException, TransformerConfigurationException, CycleInMultiParentTreeException {

    StreamResult streamResult = new StreamResult(os);
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);//from  w  w w .  ja v a  2 s  . c om
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;
    try {
        // first read all tables...
        rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        Set<String> tableNames = new HashSet<String>();
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().equals("ACT_GE_PROPERTY")) {

                tableNames.add(tableName);
            }
        }
        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {

            doExportTable(handler, conn, tableName);
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}