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.mobilefirst.fiberlink.WebServiceRequest.java

/**
 * prettyFormatXML translates the input xml and creates the indentation you would like to achieve
 * @param input: XML String/*from   w  w  w .j ava2 s.c  o  m*/
 * @param indent: Integer for how much indent to specify
 */
public static String prettyFormatXML(String input, Integer 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);
        javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent.toString());
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:curam.molsa.test.customfunctions.MOLSADOMReader.java

/**
 * Transforms an inbound DOM document according to a specific stylesheet.
 * //w  ww.  j a va  2s  .  c  om
 * @param document
 * Contains the Inbound DOM document.
 * @param stylesheet
 * The file location of the stylesheet use to transform the document
 * @param rootElement
 * The expected root element of the transformed document
 * @return The transformed document
 */
public Document transformDocumentBasedOnXSL(final Document document, final String stylesheet,
        final String responseRootElement) throws ParserConfigurationException, SAXException, IOException {

    String xmlString = "";
    Document transformedDocument = null;
    final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    dbfac.setNamespaceAware(true);
    final DocumentBuilder builder = dbfac.newDocumentBuilder();

    try {
        final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(stylesheet);

        final Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(inputStream));
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        final StringWriter stringWriter = new StringWriter();
        final StreamResult streamResult = new StreamResult(stringWriter);
        final DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
        xmlString = stringWriter.toString();

        if (xmlString.contains(responseRootElement)) {
            transformedDocument = builder.parse(new InputSource(new StringReader(xmlString)));
        } else {
            transformedDocument = builder.newDocument();
        }

    } catch (final TransformerConfigurationException tcExp) {
        tcExp.printStackTrace();
    } catch (final TransformerException tExp) {
        tExp.printStackTrace();
    }
    return transformedDocument;
}

From source file:com.alfaariss.oa.util.configuration.handler.jdbc.JDBCConfigurationHandler.java

/**
 * Saves the database configuration using the update query.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//*w  ww.  ja v  a  2  s.c  om*/
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    Connection oConnection = null;
    OutputStream os = null;
    PreparedStatement ps = null;

    try {
        os = new ByteArrayOutputStream();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os));

        //Save to DB
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sUpdateQuery);
        ps.setString(1, os.toString());
        ps.setString(2, _sConfigId);
        ps.executeUpdate();
    } catch (SQLException e) {
        _logger.error("Database error while writing configuration, SQL eror", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (Exception e) {
        _logger.error("Internal error during during configuration save", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } finally {

        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            _logger.debug("Error closing configuration outputstream", e);
        }

        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Error closing statement", e);
        }

        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Error closing connection", e);
        }
    }
}

From source file:org.alloy.metal.xml.merge.MergeContext.java

/**
* Merge 2 xml document streams together into a final resulting stream. During
* the merge, various merge business rules are followed based on configuration
* defined for various merge points./*from   ww  w  . j  a  v  a2  s.c om*/
*
* @param stream1
* @param stream2
* @return the stream representing the merged document
* @throws org.broadleafcommerce.common.extensibility.context.merge.exceptions.MergeException
*/
public ResourceInputStream merge(ResourceInputStream stream1, ResourceInputStream stream2)
        throws MergeException {
    try {
        Document doc1 = builder.parse(stream1);
        Document doc2 = builder.parse(stream2);

        List<Node> exhaustedNodes = new ArrayList<Node>();

        // process any defined handlers
        for (MergeHandler handler : this.handlers) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Processing handler: " + handler.getXPath());
            }
            MergePoint point = new MergePoint(handler, doc1, doc2);
            List<Node> list = point.merge(exhaustedNodes);
            exhaustedNodes.addAll(list);
        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = tFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

        if (doc1.getDoctype() != null && doc1.getDoctype().getSystemId() != null) {
            xmlTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc1.getDoctype().getSystemId());
        }

        DOMSource source = new DOMSource(doc1);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
        StreamResult result = new StreamResult(writer);
        xmlTransformer.transform(source, result);

        byte[] itemArray = baos.toByteArray();

        return new ResourceInputStream(new ByteArrayInputStream(itemArray), stream2.getName(),
                stream1.getNames());
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*from  www  .  ja v  a  2s .  c om*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:com.krawler.formbuilder.servlet.workflowHandler.java

public void exportWorkFLow(HttpServletRequest request, HttpServletResponse response)
        throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
    try {/*  w  w  w  . j ava  2s .  co m*/

        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") + "bpmn.xpdl");
        if (file.exists()) {
            file.delete();
        }

        Writer output = new BufferedWriter(new FileWriter(file));

        JSONObject jsonobj = new JSONObject(workflow);
        JSONObject json_line = new JSONObject(linejson);
        createDocument();
        expwriteXml(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(sw.toString());

        output.close();

        /*response.setContentType("application/xml");
        response.setHeader("Content-Disposition", "attachment; filename=export.xml");
        OutputStream out = response.getOutputStream();
        OutputFormat format = new OutputFormat(dom);
        format.setIndenting(true);
        format.setEncoding("UTF-8");
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(dom);
        out.close();*/
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.XmlUtils.java

public static void showDomInConsole(Document doc, String description) {
    try {/*ww w .j a  v  a  2  s.co m*/
        javax.xml.transform.TransformerFactory tf = FactoryProvider.getTransformerFactory();
        javax.xml.transform.Transformer t = tf.newTransformer();

        javax.xml.transform.stream.StreamResult sr = new javax.xml.transform.stream.StreamResult(System.out);
        t.transform(new javax.xml.transform.dom.DOMSource(doc.getDocumentElement()), sr);
        t.setOutputProperty(OutputKeys.INDENT, "yes");
    } catch (Exception e) {
        logger.debug("Erreur lors de la visualisation du DOM du fichier asa!");
        e.printStackTrace();
    }
}

From source file:com.azaptree.services.command.http.handler.CommandServiceHandlerTest.java

public static String prettyFormat(final String input, final int indent) {
    try {/* w  ww. j ava 2  s  . co m*/
        final Source xmlInput = new StreamSource(new StringReader(input));
        final StringWriter stringWriter = new StringWriter();
        final StreamResult xmlOutput = new StreamResult(stringWriter);
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (final Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:com.google.enterprise.connector.salesforce.security.BaseAuthorizationManager.java

/**
 * Connector manager sends a collection of documentIDs to the connector 
 * to authorize for an authenticated context
 *
 * @param  col Collection  the docIDs to authorize
 * @param  id AuthenticationIdentity   the identity to auth
 * @return Collection of docs that are authorized
 *///w  w  w. ja  va 2  s .c o m

public Collection authorizeDocids(Collection col, AuthenticationIdentity id) {
    logger.log(Level.FINER, " SalesForceAuthorizationManager. authorizeDocids called for " + id.getUsername());

    //first see if we have a callable authorization module to try

    String callable_az_module = System
            .getProperty(BaseConstants.CALLABLE_AZ + "_" + connector.getInstanceName());

    if (callable_az_module != null) {
        logger.log(Level.FINE, "Using Loadable Authorization Module : " + callable_az_module);
        try {
            Class cls = Class.forName(callable_az_module);
            java.lang.reflect.Constructor co = cls.getConstructor();
            IAuthorizationModule icau = (IAuthorizationModule) co.newInstance();

            Collection auth_col = icau.authorizeDocids(col, id.getUsername());

            Collection ret_col = new ArrayList();

            for (Iterator i = auth_col.iterator(); i.hasNext();) {
                String did = (String) i.next();
                AuthorizationResponse ap = new AuthorizationResponse(true, did);
                ret_col.add(ap);
            }

            return ret_col;
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "Unable to load Authorization Module " + callable_az_module);
        }
    } else {
        logger.log(Level.FINER, "Using Default Authorization Module");
    }

    Iterator itr = col.iterator();
    logger.log(Level.FINER, " AUTHORIZING  BATCH OF : " + col.size() + " documents");

    //vector to hold the list of docs that will eventually get authorized
    Vector v_docIDs = new Vector();

    //create a string of 'docid1','docid2','docid3'  to send into the AZ query
    String doc_wildcard = "";
    while (itr.hasNext()) {
        String docID = (String) itr.next();
        v_docIDs.add(docID);
        doc_wildcard = doc_wildcard + "'" + docID + "'";
        if (itr.hasNext())
            doc_wildcard = doc_wildcard + ",";
    }

    //initialize the collection for the response
    Collection col_resp = new ArrayList();
    String query = connector.getAzquery();

    //substitute the doc IDs into the AZ query
    String modified_az_query = query.replace("$DOCIDS", doc_wildcard);
    modified_az_query = modified_az_query.replace("$USERID", id.getUsername());

    logger.log(Level.FINER, "Attempting Authorizing DocList " + modified_az_query);

    //get ready to submit the query
    SFQuery sfq = new SFQuery();
    //get the user's sessionID, login server thats in context
    //this step maynot be necessary if we use the connector's login context
    //instead of the users...
    //TODO: figure out which way is better later on
    Properties session_props = connector.getUserSession(id.getUsername());
    //not that it matters, how did the user authenticate..
    //if its strong (i.e, we got a session ID, we can submit a full AZ query)                      
    String auth_strength = (String) session_props.get(BaseConstants.AUTHENTICATION_TYPE);

    if (auth_strength.equals(BaseConstants.STRONG_AUTHENTICATION)) {
        logger.log(Level.FINER, "Using Strong Authentication");

        try {

            //following section is used if we want to AZ using the connectors authenticated super context
            //its commented out for now but we'll touch on this later
            // if (connector.getSessionID().equalsIgnoreCase("")){
            //     SalesForceLogin sfl = new SalesForceLogin(connector.getUsername(),connector.getPassword(),connector.getLoginsrv());
            //     if (sfl.isLoggedIn()){
            //        connector.setSessionID(sfl.getSessionID());
            //        connector.setEndPointServer(sfl.getEndPointServer());
            //     }
            //  }

            //for connector-managed sessions
            //todo figure out someway to purge the older sessions

            logger.log(Level.INFO,
                    "Submitting  [" + (String) session_props.getProperty(BaseConstants.LOGIN_SERVER) + "]  ["
                            + (String) session_props.getProperty(BaseConstants.SESSIONID) + "]");
            org.w3c.dom.Document az_resp = sfq.submitStatement(modified_az_query, BaseConstants.QUERY_TYPE,
                    (String) session_props.getProperty(BaseConstants.LOGIN_SERVER),
                    (String) session_props.getProperty(BaseConstants.SESSIONID));

            //if  using system session to check AZ
            //org.w3c.dom.Document az_resp =  sfq.submitStatement(modified_az_query, BaseConstants.QUERY_TYPE,connector.getEndPointServer() , connector.getSessionID());            

            //now transform the AZ SOAP response into the canonical form using
            //the AZ XLST provided.
            String encodedXSLT = connector.getAzxslt();
            byte[] decode = org.apache.commons.codec.binary.Base64.decodeBase64(encodedXSLT.getBytes());

            org.w3c.dom.Document az_xsl = Util.XMLStringtoDoc(new String(decode));

            logger.log(Level.FINER, "AZ Query Response " + Util.XMLDoctoString(az_resp));
            Document tx_xml = Util.TransformDoctoDoc(az_resp, az_xsl);
            tx_xml.getDocumentElement().normalize();
            logger.log(Level.FINER,
                    "AZ transform result for " + id.getUsername() + "  " + Util.XMLDoctoString(tx_xml));

            //TODO...figure out why I can use tx_xml as a document by itself
            //have to resort to convert tx_xml  to string and then back to Document 
            //for some reason
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringBuffer sb1 = new StringBuffer(Util.XMLDoctoString(tx_xml));
            ByteArrayInputStream bis = new ByteArrayInputStream(sb1.toString().getBytes("UTF-8"));
            Document doc = db.parse(bis);
            doc.getDocumentElement().normalize();

            //now that the soap response is transformed, extract the documents that were
            //authorized from the canonical XML AZ form
            NodeList nl_documents = doc.getElementsByTagName("azdecisions");
            //get the NodeList under <document>
            HashMap hm_azdecisions = new HashMap();
            ;
            Node n_documents = nl_documents.item(0);
            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.INDENT, "yes");

                    if (n_doc.getNodeName().equalsIgnoreCase("docID")) {
                        //ok...so this doc ID was returned so we'll allow/permit this
                        hm_azdecisions.put(n_doc.getFirstChild().getNodeValue(), "PERMIT");
                    }
                }
            }
            //for each doc ID we got in, iterate and authorize the docs that we got back..
            //TODO, ofcourse we could just forego this loop
            //and simply iterate the hm_azdecisions hashmap to create col_resp
            for (int i = 0; i < v_docIDs.size(); i++) {
                //a doc id we got to test
                String in_docID = (String) v_docIDs.get(i);
                //if the doc exists in the set we authorized
                //the more i write this the more i want to just iterate the hm_azdecisions
                //and get it over with...i'll work on that next week
                if (hm_azdecisions.containsKey(in_docID)) {
                    AuthorizationResponse ap = new AuthorizationResponse(true, in_docID);
                    col_resp.add(ap);
                }
            }

        } catch (Exception bex) {
            logger.log(Level.SEVERE, " ERROR SUBMITTING AZ Query " + bex);
        }
    }
    //if the user was just authenticated
    //we don't have the sessionid so we'lll authorize all docs.

    //WEAK_AUTH flag should never get set since
    //we've failed the AU attempt in the BaseAuthenticationManager already
    else if (auth_strength.equals(BaseConstants.WEAK_AUTHENTICATION)) {
        logger.log(Level.FINER, "Using Weak Authentication");
        if (connector.allowWeakAuth()) {

            col_resp = new ArrayList();
            for (int i = 0; i < v_docIDs.size(); i++) {
                String docID = (String) v_docIDs.get(i);
                logger.log(Level.FINER, "Authorizing " + docID);
                AuthorizationResponse ap = new AuthorizationResponse(true, docID);
                col_resp.add(ap);
            }
        }
    }
    return col_resp;
}