View Javadoc

1   /*
2    * $Id: StringMessageUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.util;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.MuleRuntimeException;
15  import org.mule.api.transport.PropertyScope;
16  import org.mule.config.i18n.CoreMessages;
17  
18  import java.io.UnsupportedEncodingException;
19  import java.text.MessageFormat;
20  import java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Collection;
23  import java.util.List;
24  import java.util.Map;
25  import java.util.Set;
26  import java.util.TreeSet;
27  
28  /**
29   * Useful methods for formatting message strings for logging or exceptions.
30   */
31  // @ThreadSafe
32  public final class StringMessageUtils
33  {
34      // The maximum number of Collection and Array elements used for messages
35      public static final int MAX_ELEMENTS = 50;
36      public static final int DEFAULT_MESSAGE_WIDTH = 80;
37  
38      /** Do not instanciate. */
39      private StringMessageUtils ()
40      {
41          // no-op
42      }
43  
44      public static String getFormattedMessage(String msg, Object[] arguments)
45      {
46          if (arguments != null)
47          {
48              for (int i = 0; i < arguments.length; i++)
49              {
50                  arguments[i] = toString(arguments[i]);
51              }
52          }
53          return MessageFormat.format(msg, arguments);
54      }
55  
56      public static String getBoilerPlate(String message)
57      {
58          return getBoilerPlate(message, '*', DEFAULT_MESSAGE_WIDTH);
59      }
60  
61      public static String getBoilerPlate(String message, char c, int maxlength)
62      {
63          return getBoilerPlate(new ArrayList(Arrays.asList(new String[]{message})), c, maxlength);
64      }
65  
66      public static String getBoilerPlate(List messages, char c, int maxlength)
67      {
68          int size;
69          StringBuffer buf = new StringBuffer(messages.size() * maxlength);
70          int trimLength = maxlength - (c == ' ' ? 2 : 4);
71  
72          for (int i = 0; i < messages.size(); i++)
73          {
74              size = messages.get(i).toString().length();
75              if (size > trimLength)
76              {
77                  String temp = messages.get(i).toString();
78                  int k = i;
79                  int x;
80                  int len;
81                  messages.remove(i);
82                  while (temp.length() > 0)
83                  {
84                      len = (trimLength <= temp.length() ? trimLength : temp.length());
85                      String msg = temp.substring(0, len);
86                      x = msg.indexOf(SystemUtils.LINE_SEPARATOR);
87  
88                      if (x > -1)
89                      {
90                          msg = msg.substring(0, x);
91                          len = x + 1;
92                      }
93                      else
94                      {
95                          x = msg.lastIndexOf(' ');
96                          if (x > -1 && len == trimLength)
97                          {
98                              msg = msg.substring(0, x);
99                              len = x + 1;
100                         }
101                     }
102                     if (msg.startsWith(" "))
103                     {
104                         msg = msg.substring(1);
105                     }
106 
107                     temp = temp.substring(len);
108                     messages.add(k, msg);
109                     k++;
110                 }
111             }
112         }
113 
114         buf.append(SystemUtils.LINE_SEPARATOR);
115         if (c != ' ')
116         {
117             buf.append(StringUtils.repeat(c, maxlength));
118         }
119 
120         for (int i = 0; i < messages.size(); i++)
121         {
122             buf.append(SystemUtils.LINE_SEPARATOR);
123             if (c != ' ')
124             {
125                 buf.append(c);
126             }
127             buf.append(" ");
128             buf.append(messages.get(i));
129 
130             String osEncoding = CharSetUtils.defaultCharsetName();
131             int padding;
132             try
133             {
134                 padding = trimLength - messages.get(i).toString().getBytes(osEncoding).length;
135             }
136             catch (UnsupportedEncodingException ueex)
137             {
138                 throw new MuleRuntimeException(CoreMessages.failedToConvertStringUsingEncoding(osEncoding), ueex);
139             }
140             if (padding > 0)
141             {
142                 buf.append(StringUtils.repeat(' ', padding));
143             }
144             buf.append(' ');
145             if (c != ' ')
146             {
147                 buf.append(c);
148             }
149         }
150         buf.append(SystemUtils.LINE_SEPARATOR);
151         if (c != ' ')
152         {
153             buf.append(StringUtils.repeat(c, maxlength));
154         }
155         return buf.toString();
156     }
157 
158     public static String truncate(String message, int length, boolean includeCount)
159     {
160         if (message == null)
161         {
162             return null;
163         }
164         if (message.length() <= length)
165         {
166             return message;
167         }
168         String result = message.substring(0, length) + "...";
169         if (includeCount)
170         {
171             result += "[" + length + " of " + message.length() + "]";
172         }
173         return result;
174     }
175 
176     public static byte[] getBytes(String string)
177     {
178         try
179         {
180             return string.getBytes(FileUtils.DEFAULT_ENCODING);
181         }
182         catch (UnsupportedEncodingException e)
183         {
184             // We can ignore this as the encoding is validated on start up
185             return null;
186         }
187     }
188 
189     public static String getString(byte[] bytes, String encoding)
190     {
191         try
192         {
193             return new String(bytes, encoding);
194         }
195         catch (UnsupportedEncodingException e)
196         {
197             // We can ignore this as the encoding is validated on start up
198             return null;
199         }
200     }
201 
202     /**
203      * @see ArrayUtils#toString(Object, int)
204      * @see CollectionUtils#toString(Collection, int)
205      * @see MapUtils#toString(Map, boolean)
206      */
207     public static String toString(Object o)
208     {
209         if (o == null)
210         {
211             return "null";
212         }
213         else if (o instanceof Class)
214         {
215             return ((Class) o).getName();
216         }
217         else if (o instanceof Map)
218         {
219             return MapUtils.toString((Map) o, false);
220         }
221         else if (o.getClass().isArray())
222         {
223             return ArrayUtils.toString(o, MAX_ELEMENTS);
224         }
225         else if (o instanceof Collection)
226         {
227             return CollectionUtils.toString((Collection) o, MAX_ELEMENTS);
228         }
229         else
230         {
231             return o.toString();
232         }
233     }
234 
235     public static String headersToString(MuleMessage m)
236     {
237         if (m == null)
238         {
239             return null;
240         }
241         StringBuilder buf = new StringBuilder();
242         buf.append(SystemUtils.LINE_SEPARATOR).append("Message properties:").append(SystemUtils.LINE_SEPARATOR);
243 
244         for (int i = 0; i < PropertyScope.ALL_SCOPES.length; i++)
245         {
246             PropertyScope scope = PropertyScope.ALL_SCOPES[i];
247             try
248             {
249                 Set names = new TreeSet(m.getPropertyNames(scope));
250                 buf.append("  ").append(scope.getScopeName().toUpperCase()).append(" scoped properties:").append(SystemUtils.LINE_SEPARATOR);
251 
252                 for (Object name : names)
253                 {
254                     Object value = m.getProperty(name.toString(), scope);
255                     if (name.equals("password") || name.toString().contains("secret") || name.equals("pass"))
256                     {
257                         value = "****";
258                     }
259                     buf.append("    ").append(name).append("=").append(value).append(SystemUtils.LINE_SEPARATOR);
260                 }
261             }
262             catch (IllegalArgumentException e)
263             {
264                 // ignored
265             }
266         }
267         return buf.toString();
268     }
269 }