View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.cxf.feature;
8   
9   import org.mule.api.MuleException;
10  import org.mule.module.xml.transformer.XmlPrettyPrinter;
11  import org.mule.util.StringUtils;
12  
13  import org.apache.cxf.Bus;
14  import org.apache.cxf.feature.LoggingFeature;
15  import org.apache.cxf.interceptor.InterceptorProvider;
16  
17  /**
18   * Same as the standard CXF LoggingFeature, but with pretty-printed XML 
19   * for the message payload.
20   */
21  public class PrettyLoggingFeature extends LoggingFeature
22  {
23      @Override
24      protected void initializeProvider(InterceptorProvider provider, Bus bus)
25      {
26          provider.getInInterceptors().add(new PrettyLoggingInInterceptor(getLimit()));
27          provider.getOutInterceptors().add(new PrettyLoggingOutInterceptor(getLimit()));
28      }
29      
30      /**
31       * Takes the log output from the standard CXF LoggingInterceptor, 
32       * disassembles it, pretty-prints the XML payload, then puts it all back 
33       * together again.
34       */
35      protected static String formatXmlPayload(String originalLogString)
36      {
37          String[] lines = originalLogString.split("\n");
38          
39          // Figure out which line has the payload on it
40          int payloadLine = -1;
41          for (int i=0; i<lines.length; ++i)
42          {
43              if (lines[i].startsWith("Payload: "))
44              {
45                  payloadLine = i;
46                  break;
47              }
48          }
49          if (payloadLine == -1)
50          {
51              System.err.println("Could not find a line which begins with 'Payload: '");
52              return originalLogString;
53          }
54          
55          // Extract the XML payload and format it
56          String payload = lines[payloadLine];
57          String xml = StringUtils.substringAfter(payload, "Payload: ");
58          XmlPrettyPrinter pp = new XmlPrettyPrinter();
59          try
60          {
61              xml = (String) pp.transform(xml);
62          }
63          catch (MuleException e)
64          {
65              System.err.println(e.getMessage());
66          }
67          
68          // Replace the payload line with the formatted XML and put it all back together again
69          lines[payloadLine] = "Payload: \n" + xml;
70          return StringUtils.join(lines, "\n");
71      }
72  }