Pretty Print SOAP Message and Display the SOAP message in HTML


In some situations it could be useful to pretty print a SOAP message to be able to show it in a html page.
Often applications that uses web services needs to log the SOAP messages that is sent to and from the services and then display them in some sort of administration application.
It would also perhaps be nice not to use the pre-tag but to embed the code along the rest of the html code.
In such a case the pretty print comes in handy. This example shows how to pretty print a SOAP message reading the unformatted envelope from a file, formats (pretty print) the message and writes it to a html file.


package com.javadb.prettyprintsoap;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;

/**
 *
 * @author www.javadb.com
 */

public class Main {

    /**
     * Does the actual pretty printing.
     *
     * @param inSoap
     * @return The pretty printed string.
     */

    public String prettyPrintSoap(String inSoap) {

        String soap = inSoap.replaceAll("\r\n", "");
        soap = soap.replaceAll("\t", "");
        soap = soap.replaceAll("[>]{1}[\\s]*[<]{1}", "><");
        soap = addLineBreaks(soap);

        BufferedReader reader = new BufferedReader(new StringReader(soap));

        int tabs = 0;
        int nrTabs = 1;
        StringBuilder b = new StringBuilder();
        boolean first = true;
        boolean flag = false;
        String line;
        try {
            while ((line = reader.readLine()) != null) {

                if (!first) {
                    if (line.startsWith("</")) {
                        if (tabs > 0) {
                            tabs -= nrTabs;
                        }
                    } else if (!line.endsWith("/>") && line.indexOf("</") == -1) {
                        if (!flag) {
                            tabs += nrTabs;
                        }
                        flag = false;
                    } else {
                        if (!flag) {
                            tabs += nrTabs;
                            flag = true;
                        }
                    }
                } else {
                    first = false;
                }
                tab(tabs, b, line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return inSoap;
        }

        soap = b.toString();
        soap = soap.replaceAll("<", "<");
        soap = soap.replaceAll(">", ">");
        soap = soap.replaceAll("\t", "     ");
        soap = soap.replaceAll("\r\n", "<br/>");

        return soap;
    }

    /**
     * Appends tab characters to the StringBuilder before adding a line of text
     * followed by a carriage return and linefeed.
     *
     * @param nr The number of tabs
     * @param b The StringBuilder instance
     * @param line The string to add.
     */

    private void tab(int nr, StringBuilder b, String line) {
        for (int i = 0; i < nr; i++) {
            b.append("\t");
        }
        b.append(line + "\r\n");
    }

    /**
     * Adds linebreaks between start and end tags.
     * @param inSoap
     * @return
     */

    private String addLineBreaks(String inSoap) {

        int currentpos = 0;
        int nextpos = 0;
        StringBuilder soap = new StringBuilder(inSoap);
        while ((nextpos = soap.indexOf("><", currentpos)) != -1) {

            String startTag, endTag;
            int start = nextpos - 1;
            int end = nextpos + 1;
            while (soap.charAt(start) != '<') {
                start--;
            }
            startTag = soap.substring(start + 1, nextpos);
            while (soap.charAt(end) != '>') {
                end++;
            }
            endTag = soap.substring(nextpos + 2, end);

            if (!startTag.startsWith("/") && endTag.startsWith("/")) {
                if (startTag.startsWith("/")) {
                    startTag = startTag.substring(1);
                } else if (startTag.endsWith("/")) {
                    startTag = startTag.substring(0, startTag.length() - 1);
                }
                if (endTag.startsWith("/")) {
                    endTag = endTag.substring(1);
                } else if (endTag.endsWith("/")) {
                    endTag = endTag.substring(0, endTag.length() - 1);
                }
            }
            if (!startTag.equals(endTag)) {
                soap.replace(nextpos, nextpos + 2, ">\r\n<");
                currentpos = nextpos;
            } else if (!startTag.startsWith(endTag)) {
                if (startTag.charAt(endTag.length()) != ' ') {
                    soap.replace(nextpos, nextpos + 2, ">\r\n<");
                    currentpos = nextpos;
                }
            } else {
                currentpos = nextpos + 2;
            }
            System.out.println(startTag + " " + endTag);
        }

        return soap.toString();
    }

    /**
     * Reads the soap to be formated from a file and then writes the
     * pretty printed soap message to a html file.
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {

        StringBuilder inSoap = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new FileReader("in.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                inSoap.append(line);
            }
            String formattedSoap = new Main().prettyPrintSoap(inSoap.toString());

            BufferedWriter writer = new BufferedWriter(new FileWriter("out.html"));

            writer.write(formattedSoap);

            writer.close();
            reader.close();


        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


This is what the SOAP message looks like when it is pretty printed and displayed as html:


<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
     <soap:Body xmlns:m="http://www.example.org/stock">
          <m:GetStockPrice>
               <m:StockName>IBM</m:StockName>
          </m:GetStockPrice>
     </soap:Body>
</soap:Envelope>


Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: