001/**
002 * Copyright (c) 2004-2011 QOS.ch
003 * All rights reserved.
004 *
005 * Permission is hereby granted, free  of charge, to any person obtaining
006 * a  copy  of this  software  and  associated  documentation files  (the
007 * "Software"), to  deal in  the Software without  restriction, including
008 * without limitation  the rights to  use, copy, modify,  merge, publish,
009 * distribute,  sublicense, and/or sell  copies of  the Software,  and to
010 * permit persons to whom the Software  is furnished to do so, subject to
011 * the following conditions:
012 *
013 * The  above  copyright  notice  and  this permission  notice  shall  be
014 * included in all copies or substantial portions of the Software.
015 *
016 * THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
017 * EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
018 * MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
019 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
020 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
021 * OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
022 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023 *
024 */
025package org.slf4j.helpers;
026
027import java.text.MessageFormat;
028import java.util.HashMap;
029import java.util.Map;
030
031// contributors: lizongbo: proposed special treatment of array parameter values
032// Joern Huxhorn: pointed out double[] omission, suggested deep array copy
033/**
034 * Formats messages according to very simple substitution rules. Substitutions
035 * can be made 1, 2 or more arguments.
036 *
037 * <p>
038 * For example,
039 *
040 * <pre>
041 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
042 * </pre>
043 *
044 * will return the string "Hi there.".
045 * <p>
046 * The {} pair is called the <em>formatting anchor</em>. It serves to designate
047 * the location where arguments need to be substituted within the message
048 * pattern.
049 * <p>
050 * In case your message contains the '{' or the '}' character, you do not have
051 * to do anything special unless the '}' character immediately follows '{'. For
052 * example,
053 *
054 * <pre>
055 * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
056 * </pre>
057 *
058 * will return the string "Set {1,2,3} is not equal to 1,2.".
059 *
060 * <p>
061 * If for whatever reason you need to place the string "{}" in the message
062 * without its <em>formatting anchor</em> meaning, then you need to escape the
063 * '{' character with '\', that is the backslash character. Only the '{'
064 * character should be escaped. There is no need to escape the '}' character.
065 * For example,
066 *
067 * <pre>
068 * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
069 * </pre>
070 *
071 * will return the string "Set {} is not equal to 1,2.".
072 *
073 * <p>
074 * The escaping behavior just described can be overridden by escaping the escape
075 * character '\'. Calling
076 *
077 * <pre>
078 * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
079 * </pre>
080 *
081 * will return the string "File name is C:\file.zip".
082 *
083 * <p>
084 * The formatting conventions are different than those of {@link MessageFormat}
085 * which ships with the Java platform. This is justified by the fact that
086 * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
087 * This local performance difference is both measurable and significant in the
088 * larger context of the complete logging processing chain.
089 *
090 * <p>
091 * See also {@link #format(String, Object)},
092 * {@link #format(String, Object, Object)} and
093 * {@link #arrayFormat(String, Object[])} methods for more details.
094 *
095 * @author Ceki G&uuml;lc&uuml;
096 * @author Joern Huxhorn
097 */
098final public class MessageFormatter {
099    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 = getThrowableCandidate(argArray);
157        Object[] args = argArray;
158        if (throwableCandidate != null) {
159            args = trimmedCopy(argArray);
160        }
161        return arrayFormat(messagePattern, args, throwableCandidate);
162    }
163    
164    static final Throwable getThrowableCandidate(Object[] argArray) {
165        if (argArray == null || argArray.length == 0) {
166            return null;
167        }
168
169        final Object lastEntry = argArray[argArray.length - 1];
170        if (lastEntry instanceof Throwable) {
171            return (Throwable) lastEntry;
172        }
173        return null;
174    }
175    private static Object[] trimmedCopy(Object[] argArray) {
176        if (argArray == null || argArray.length == 0) {
177            throw new IllegalStateException("non-sensical empty or null argument array");
178        }
179        final int trimemdLen = argArray.length - 1;
180        Object[] trimmed = new Object[trimemdLen];
181        System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
182        return trimmed;
183    }
184
185    final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) {
186
187        if (messagePattern == null) {
188            return new FormattingTuple(null, argArray, throwable);
189        }
190
191        if (argArray == null) {
192            return new FormattingTuple(messagePattern);
193        }
194
195        int i = 0;
196        int j;
197        // use string builder for better multicore performance
198        StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
199
200        int L;
201        for (L = 0; L < argArray.length; L++) {
202
203            j = messagePattern.indexOf(DELIM_STR, i);
204
205            if (j == -1) {
206                // no more variables
207                if (i == 0) { // this is a simple string
208                    return new FormattingTuple(messagePattern, argArray, throwable);
209                } else { // add the tail string which contains no variables and return
210                    // the result.
211                    sbuf.append(messagePattern, i, messagePattern.length());
212                    return new FormattingTuple(sbuf.toString(), argArray, throwable);
213                }
214            } else {
215                if (isEscapedDelimeter(messagePattern, j)) {
216                    if (!isDoubleEscaped(messagePattern, j)) {
217                        L--; // DELIM_START was escaped, thus should not be incremented
218                        sbuf.append(messagePattern, i, j - 1);
219                        sbuf.append(DELIM_START);
220                        i = j + 1;
221                    } else {
222                        // The escape character preceding the delimiter start is
223                        // itself escaped: "abc x:\\{}"
224                        // we have to consume one backward slash
225                        sbuf.append(messagePattern, i, j - 1);
226                        deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
227                        i = j + 2;
228                    }
229                } else {
230                    // normal case
231                    sbuf.append(messagePattern, i, j);
232                    deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
233                    i = j + 2;
234                }
235            }
236        }
237        // append the characters following the last {} pair.
238        sbuf.append(messagePattern, i, messagePattern.length());
239        return new FormattingTuple(sbuf.toString(), argArray, throwable);
240    }
241
242    final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
243
244        if (delimeterStartIndex == 0) {
245            return false;
246        }
247        char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
248        if (potentialEscape == ESCAPE_CHAR) {
249            return true;
250        } else {
251            return false;
252        }
253    }
254
255    final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
256        if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
257            return true;
258        } else {
259            return false;
260        }
261    }
262
263    // special treatment of array values was suggested by 'lizongbo'
264    private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
265        if (o == null) {
266            sbuf.append("null");
267            return;
268        }
269        if (!o.getClass().isArray()) {
270            safeObjectAppend(sbuf, o);
271        } else {
272            // check for primitive array types because they
273            // unfortunately cannot be cast to Object[]
274            if (o instanceof boolean[]) {
275                booleanArrayAppend(sbuf, (boolean[]) o);
276            } else if (o instanceof byte[]) {
277                byteArrayAppend(sbuf, (byte[]) o);
278            } else if (o instanceof char[]) {
279                charArrayAppend(sbuf, (char[]) o);
280            } else if (o instanceof short[]) {
281                shortArrayAppend(sbuf, (short[]) o);
282            } else if (o instanceof int[]) {
283                intArrayAppend(sbuf, (int[]) o);
284            } else if (o instanceof long[]) {
285                longArrayAppend(sbuf, (long[]) o);
286            } else if (o instanceof float[]) {
287                floatArrayAppend(sbuf, (float[]) o);
288            } else if (o instanceof double[]) {
289                doubleArrayAppend(sbuf, (double[]) o);
290            } else {
291                objectArrayAppend(sbuf, (Object[]) o, seenMap);
292            }
293        }
294    }
295
296    private static void safeObjectAppend(StringBuilder sbuf, Object o) {
297        try {
298            String oAsString = o.toString();
299            sbuf.append(oAsString);
300        } catch (Throwable t) {
301            Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t);
302            sbuf.append("[FAILED toString()]");
303        }
304
305    }
306
307    private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
308        sbuf.append('[');
309        if (!seenMap.containsKey(a)) {
310            seenMap.put(a, null);
311            final int len = a.length;
312            for (int i = 0; i < len; i++) {
313                deeplyAppendParameter(sbuf, a[i], seenMap);
314                if (i != len - 1)
315                    sbuf.append(", ");
316            }
317            // allow repeats in siblings
318            seenMap.remove(a);
319        } else {
320            sbuf.append("...");
321        }
322        sbuf.append(']');
323    }
324
325    private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
326        sbuf.append('[');
327        final int len = a.length;
328        for (int i = 0; i < len; i++) {
329            sbuf.append(a[i]);
330            if (i != len - 1)
331                sbuf.append(", ");
332        }
333        sbuf.append(']');
334    }
335
336    private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
337        sbuf.append('[');
338        final int len = a.length;
339        for (int i = 0; i < len; i++) {
340            sbuf.append(a[i]);
341            if (i != len - 1)
342                sbuf.append(", ");
343        }
344        sbuf.append(']');
345    }
346
347    private static void charArrayAppend(StringBuilder sbuf, char[] a) {
348        sbuf.append('[');
349        final int len = a.length;
350        for (int i = 0; i < len; i++) {
351            sbuf.append(a[i]);
352            if (i != len - 1)
353                sbuf.append(", ");
354        }
355        sbuf.append(']');
356    }
357
358    private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
359        sbuf.append('[');
360        final int len = a.length;
361        for (int i = 0; i < len; i++) {
362            sbuf.append(a[i]);
363            if (i != len - 1)
364                sbuf.append(", ");
365        }
366        sbuf.append(']');
367    }
368
369    private static void intArrayAppend(StringBuilder sbuf, int[] a) {
370        sbuf.append('[');
371        final int len = a.length;
372        for (int i = 0; i < len; i++) {
373            sbuf.append(a[i]);
374            if (i != len - 1)
375                sbuf.append(", ");
376        }
377        sbuf.append(']');
378    }
379
380    private static void longArrayAppend(StringBuilder sbuf, long[] a) {
381        sbuf.append('[');
382        final int len = a.length;
383        for (int i = 0; i < len; i++) {
384            sbuf.append(a[i]);
385            if (i != len - 1)
386                sbuf.append(", ");
387        }
388        sbuf.append(']');
389    }
390
391    private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
392        sbuf.append('[');
393        final int len = a.length;
394        for (int i = 0; i < len; i++) {
395            sbuf.append(a[i]);
396            if (i != len - 1)
397                sbuf.append(", ");
398        }
399        sbuf.append(']');
400    }
401
402    private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
403        sbuf.append('[');
404        final int len = a.length;
405        for (int i = 0; i < len; i++) {
406            sbuf.append(a[i]);
407            if (i != len - 1)
408                sbuf.append(", ");
409        }
410        sbuf.append(']');
411    }
412
413}