1 /**
2  * Copyright (c) 2004-2011 QOS.ch
3  * All rights reserved.
4  *
5  * Permission is hereby granted, free  of charge, to any person obtaining
6  * a  copy  of this  software  and  associated  documentation files  (the
7  * "Software"), to  deal in  the Software without  restriction, including
8  * without limitation  the rights to  use, copy, modify,  merge, publish,
9  * distribute,  sublicense, and/or sell  copies of  the Software,  and to
10  * permit persons to whom the Software  is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The  above  copyright  notice  and  this permission  notice  shall  be
14  * included in all copies or substantial portions of the Software.
15  *
16  * THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
17  * EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
18  * MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
19  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21  * OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
22  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.slf4j.helpers;
26
27 import java.text.MessageFormat;
28 import java.util.HashMap;
29 import java.util.Map;
30
31 // contributors: lizongbo: proposed special treatment of array parameter values
32 // Joern Huxhorn: pointed out double[] omission, suggested deep array copy
33 /**
34  * Formats messages according to very simple substitution rules. Substitutions
35  * can be made 1, 2 or more arguments.
36  *
37  * <p>
38  * For example,
39  *
40  * <pre>
41  * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
42  * </pre>
43  *
44  * will return the string "Hi there.".
45  * <p>
46  * The {} pair is called the <em>formatting anchor</em>. It serves to designate
47  * the location where arguments need to be substituted within the message
48  * pattern.
49  * <p>
50  * In case your message contains the '{' or the '}' character, you do not have
51  * to do anything special unless the '}' character immediately follows '{'. For
52  * example,
53  *
54  * <pre>
55  * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
56  * </pre>
57  *
58  * will return the string "Set {1,2,3} is not equal to 1,2.".
59  *
60  * <p>
61  * If for whatever reason you need to place the string "{}" in the message
62  * without its <em>formatting anchor</em> meaning, then you need to escape the
63  * '{' character with '\', that is the backslash character. Only the '{'
64  * character should be escaped. There is no need to escape the '}' character.
65  * For example,
66  *
67  * <pre>
68  * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
69  * </pre>
70  *
71  * will return the string "Set {} is not equal to 1,2.".
72  *
73  * <p>
74  * The escaping behavior just described can be overridden by escaping the escape
75  * character '\'. Calling
76  *
77  * <pre>
78  * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
79  * </pre>
80  *
81  * will return the string "File name is C:\file.zip".
82  *
83  * <p>
84  * The formatting conventions are different than those of {@link MessageFormat}
85  * which ships with the Java platform. This is justified by the fact that
86  * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
87  * This local performance difference is both measurable and significant in the
88  * larger context of the complete logging processing chain.
89  *
90  * <p>
91  * See also {@link #format(String, Object)},
92  * {@link #format(String, Object, Object)} and
93  * {@link #arrayFormat(String, Object[])} methods for more details.
94  *
95  * @author Ceki G&uuml;lc&uuml;
96  * @author Joern Huxhorn
97  */

98 final public class MessageFormatter {
99     static final char DELIM_START = '{';
100     static final char DELIM_STOP = '}';
101     static final String DELIM_STR = "{}";
102     private static final char ESCAPE_CHAR = '\\';
103
104     /**
105      * Performs single argument substitution for the 'messagePattern' passed as
106      * parameter.
107      * <p>
108      * For example,
109      *
110      * <pre>
111      * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;);
112      * </pre>
113      *
114      * will return the string "Hi there.".
115      * <p>
116      *
117      * @param messagePattern
118      *          The message pattern which will be parsed and formatted
119      * @param arg
120      *          The argument to be substituted in place of the formatting anchor
121      * @return The formatted message
122      */

123     final public static FormattingTuple format(String messagePattern, Object arg) {
124         return arrayFormat(messagePattern, new Object[] { arg });
125     }
126
127     /**
128      *
129      * Performs a two argument substitution for the 'messagePattern' passed as
130      * parameter.
131      * <p>
132      * For example,
133      *
134      * <pre>
135      * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;);
136      * </pre>
137      *
138      * will return the string "Hi Alice. My name is Bob.".
139      *
140      * @param messagePattern
141      *          The message pattern which will be parsed and formatted
142      * @param arg1
143      *          The argument to be substituted in place of the first formatting
144      *          anchor
145      * @param arg2
146      *          The argument to be substituted in place of the second formatting
147      *          anchor
148      * @return The formatted message
149      */

150     final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) {
151         return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
152     }
153
154
155     final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
156         Throwable throwableCandidate = MessageFormatter.getThrowableCandidate(argArray);
157         Object[] args = argArray;
158         if (throwableCandidate != null) {
159             args = MessageFormatter.trimmedCopy(argArray);
160         }
161         return arrayFormat(messagePattern, args, throwableCandidate);
162     }
163
164     final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) {
165
166         if (messagePattern == null) {
167             return new FormattingTuple(null, argArray, throwable);
168         }
169
170         if (argArray == null) {
171             return new FormattingTuple(messagePattern);
172         }
173
174         int i = 0;
175         int j;
176         // use string builder for better multicore performance
177         StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
178
179         int L;
180         for (L = 0; L < argArray.length; L++) {
181
182             j = messagePattern.indexOf(DELIM_STR, i);
183
184             if (j == -1) {
185                 // no more variables
186                 if (i == 0) { // this is a simple string
187                     return new FormattingTuple(messagePattern, argArray, throwable);
188                 } else { // add the tail string which contains no variables and return
189                     // the result.
190                     sbuf.append(messagePattern, i, messagePattern.length());
191                     return new FormattingTuple(sbuf.toString(), argArray, throwable);
192                 }
193             } else {
194                 if (isEscapedDelimeter(messagePattern, j)) {
195                     if (!isDoubleEscaped(messagePattern, j)) {
196                         L--; // DELIM_START was escaped, thus should not be incremented
197                         sbuf.append(messagePattern, i, j - 1);
198                         sbuf.append(DELIM_START);
199                         i = j + 1;
200                     } else {
201                         // The escape character preceding the delimiter start is
202                         // itself escaped: "abc x:\\{}"
203                         // we have to consume one backward slash
204                         sbuf.append(messagePattern, i, j - 1);
205                         deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
206                         i = j + 2;
207                     }
208                 } else {
209                     // normal case
210                     sbuf.append(messagePattern, i, j);
211                     deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
212                     i = j + 2;
213                 }
214             }
215         }
216         // append the characters following the last {} pair.
217         sbuf.append(messagePattern, i, messagePattern.length());
218         return new FormattingTuple(sbuf.toString(), argArray, throwable);
219     }
220
221     final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
222
223         if (delimeterStartIndex == 0) {
224             return false;
225         }
226         char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
227         if (potentialEscape == ESCAPE_CHAR) {
228             return true;
229         } else {
230             return false;
231         }
232     }
233
234     final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
235         if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
236             return true;
237         } else {
238             return false;
239         }
240     }
241
242     // special treatment of array values was suggested by 'lizongbo'
243     private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
244         if (o == null) {
245             sbuf.append("null");
246             return;
247         }
248         if (!o.getClass().isArray()) {
249             safeObjectAppend(sbuf, o);
250         } else {
251             // check for primitive array types because they
252             // unfortunately cannot be cast to Object[]
253             if (o instanceof boolean[]) {
254                 booleanArrayAppend(sbuf, (boolean[]) o);
255             } else if (o instanceof byte[]) {
256                 byteArrayAppend(sbuf, (byte[]) o);
257             } else if (o instanceof char[]) {
258                 charArrayAppend(sbuf, (char[]) o);
259             } else if (o instanceof short[]) {
260                 shortArrayAppend(sbuf, (short[]) o);
261             } else if (o instanceof int[]) {
262                 intArrayAppend(sbuf, (int[]) o);
263             } else if (o instanceof long[]) {
264                 longArrayAppend(sbuf, (long[]) o);
265             } else if (o instanceof float[]) {
266                 floatArrayAppend(sbuf, (float[]) o);
267             } else if (o instanceof double[]) {
268                 doubleArrayAppend(sbuf, (double[]) o);
269             } else {
270                 objectArrayAppend(sbuf, (Object[]) o, seenMap);
271             }
272         }
273     }
274
275     private static void safeObjectAppend(StringBuilder sbuf, Object o) {
276         try {
277             String oAsString = o.toString();
278             sbuf.append(oAsString);
279         } catch (Throwable t) {
280             Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t);
281             sbuf.append("[FAILED toString()]");
282         }
283
284     }
285
286     private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
287         sbuf.append('[');
288         if (!seenMap.containsKey(a)) {
289             seenMap.put(a, null);
290             final int len = a.length;
291             for (int i = 0; i < len; i++) {
292                 deeplyAppendParameter(sbuf, a[i], seenMap);
293                 if (i != len - 1)
294                     sbuf.append(", ");
295             }
296             // allow repeats in siblings
297             seenMap.remove(a);
298         } else {
299             sbuf.append("...");
300         }
301         sbuf.append(']');
302     }
303
304     private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
305         sbuf.append('[');
306         final int len = a.length;
307         for (int i = 0; i < len; i++) {
308             sbuf.append(a[i]);
309             if (i != len - 1)
310                 sbuf.append(", ");
311         }
312         sbuf.append(']');
313     }
314
315     private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
316         sbuf.append('[');
317         final int len = a.length;
318         for (int i = 0; i < len; i++) {
319             sbuf.append(a[i]);
320             if (i != len - 1)
321                 sbuf.append(", ");
322         }
323         sbuf.append(']');
324     }
325
326     private static void charArrayAppend(StringBuilder sbuf, char[] a) {
327         sbuf.append('[');
328         final int len = a.length;
329         for (int i = 0; i < len; i++) {
330             sbuf.append(a[i]);
331             if (i != len - 1)
332                 sbuf.append(", ");
333         }
334         sbuf.append(']');
335     }
336
337     private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
338         sbuf.append('[');
339         final int len = a.length;
340         for (int i = 0; i < len; i++) {
341             sbuf.append(a[i]);
342             if (i != len - 1)
343                 sbuf.append(", ");
344         }
345         sbuf.append(']');
346     }
347
348     private static void intArrayAppend(StringBuilder sbuf, int[] a) {
349         sbuf.append('[');
350         final int len = a.length;
351         for (int i = 0; i < len; i++) {
352             sbuf.append(a[i]);
353             if (i != len - 1)
354                 sbuf.append(", ");
355         }
356         sbuf.append(']');
357     }
358
359     private static void longArrayAppend(StringBuilder sbuf, long[] a) {
360         sbuf.append('[');
361         final int len = a.length;
362         for (int i = 0; i < len; i++) {
363             sbuf.append(a[i]);
364             if (i != len - 1)
365                 sbuf.append(", ");
366         }
367         sbuf.append(']');
368     }
369
370     private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
371         sbuf.append('[');
372         final int len = a.length;
373         for (int i = 0; i < len; i++) {
374             sbuf.append(a[i]);
375             if (i != len - 1)
376                 sbuf.append(", ");
377         }
378         sbuf.append(']');
379     }
380
381     private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
382         sbuf.append('[');
383         final int len = a.length;
384         for (int i = 0; i < len; i++) {
385             sbuf.append(a[i]);
386             if (i != len - 1)
387                 sbuf.append(", ");
388         }
389         sbuf.append(']');
390     }
391
392     /**
393      * Helper method to determine if an {@link Object} array contains a {@link Throwable} as last element
394      *
395      * @param argArray
396      *          The arguments off which we want to know if it contains a {@link Throwable} as last element
397      * @return if the last {@link Object} in argArray is a {@link Throwable} this method will return it,
398      *          otherwise it returns null
399      */

400     public static Throwable getThrowableCandidate(final Object[] argArray) {
401         if (argArray == null || argArray.length == 0) {
402             return null;
403         }
404
405         final Object lastEntry = argArray[argArray.length - 1];
406         if (lastEntry instanceof Throwable) {
407             return (Throwable) lastEntry;
408         }
409
410         return null;
411     }
412
413     /**
414      * Helper method to get all but the last element of an array
415      *
416      * @param argArray
417      *          The arguments from which we want to remove the last element
418      *
419      * @return a copy of the array without the last element
420      */

421     public static Object[] trimmedCopy(final Object[] argArray) {
422         if (argArray == null || argArray.length == 0) {
423             throw new IllegalStateException("non-sensical empty or null argument array");
424         }
425
426         final int trimmedLen = argArray.length - 1;
427
428         Object[] trimmed = new Object[trimmedLen];
429
430         if (trimmedLen > 0) {
431             System.arraycopy(argArray, 0, trimmed, 0, trimmedLen);
432         }
433
434         return trimmed;
435     }
436
437 }
438