001    /**
002     *   GRANITE DATA SERVICES
003     *   Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004     *
005     *   This file is part of the Granite Data Services Platform.
006     *
007     *   Granite Data Services is free software; you can redistribute it and/or
008     *   modify it under the terms of the GNU Lesser General Public
009     *   License as published by the Free Software Foundation; either
010     *   version 2.1 of the License, or (at your option) any later version.
011     *
012     *   Granite Data Services is distributed in the hope that it will be useful,
013     *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014     *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015     *   General Public License for more details.
016     *
017     *   You should have received a copy of the GNU Lesser General Public
018     *   License along with this library; if not, write to the Free Software
019     *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020     *   USA, or see <http://www.gnu.org/licenses/>.
021     */
022    package org.granite.logging;
023    
024    import java.lang.reflect.Array;
025    import java.util.ArrayList;
026    import java.util.Arrays;
027    import java.util.Calendar;
028    import java.util.Collection;
029    import java.util.Date;
030    import java.util.Formattable;
031    import java.util.HashMap;
032    import java.util.List;
033    import java.util.Map;
034    
035    /**
036     * @author Franck WOLFF
037     */
038    public class DefaultLoggingFormatter implements LoggingFormatter {
039    
040        private static final int MAX_COLLECTION_ITEMS = 100;
041    
042        private final int maxItems;
043    
044        public DefaultLoggingFormatter() {
045            this(MAX_COLLECTION_ITEMS);
046        }
047    
048        public DefaultLoggingFormatter(int maxItems) {
049            this.maxItems = maxItems;
050        }
051    
052        public String format(String message, Object... args) {
053            try {
054                for (int i = 0; i < args.length; i++)
055                    args[i] = convert(args[i]);
056    
057                return String.format(message, args);
058            } catch (Exception e) {
059                try {
060                    return "[FORMATTER ERROR] \"" + message + "\"(" + Arrays.toString(args) + ") - " + e;
061                } catch (Exception f) {
062                    return "[FORMATTER ERROR] \"" + message + "\"(" + f + ") - " + e;
063                }
064            }
065        }
066    
067        protected Object convert(Object o) {
068            if (o == null ||
069                o instanceof Formattable ||
070                o instanceof Number ||
071                o instanceof Character ||
072                o instanceof Boolean ||
073                o instanceof Date ||
074                o instanceof Calendar)
075                return o;
076    
077            try {
078                if (o instanceof String) {
079                    o = new StringBuilder().append('"').append(o).append('"').toString();
080                }
081                else if (o.getClass().isArray()) {
082                    Class<?> type = o.getClass().getComponentType();
083    
084                    if (maxItems < 0) {
085                        if (type.isPrimitive()) {
086                            if (type == Byte.TYPE)
087                                return Arrays.toString((byte[])o);
088                            if (type == Character.TYPE)
089                                return Arrays.toString((char[])o);
090                            if (type == Integer.TYPE)
091                                 return Arrays.toString((int[])o);
092                            if (type == Double.TYPE)
093                                return Arrays.toString((double[])o);
094                            if (type == Long.TYPE)
095                                return Arrays.toString((long[])o);
096                            if (type == Float.TYPE)
097                                return Arrays.toString((float[])o);
098                            if (type == Short.TYPE)
099                                return Arrays.toString((short[])o);
100                            if (type == Boolean.TYPE)
101                                return Arrays.toString((boolean[])o);
102                            return "[Array of unknown primitive type: " + type + "]"; // Should never append...
103                        }
104                        return Arrays.toString((Object[])o);
105                    }
106    
107                    final int max = Math.min(maxItems, Array.getLength(o));
108                    List<Object> list = new ArrayList<Object>(max);
109    
110                    for (int i = 0; i < max; i++)
111                        list.add(Array.get(o, i));
112                    if (max < Array.getLength(o))
113                        list.add("(first " + max + '/' + Array.getLength(o) + " elements only...)");
114    
115                    o = list;
116                }
117                else if (o instanceof Collection<?> && maxItems >= 0) {
118    
119                    Collection<?> coll = (Collection<?>)o;
120                    final int max = Math.min(maxItems, coll.size());
121                    List<Object> list = new ArrayList<Object>(max);
122    
123                    int i = 0;
124                    for (Object item : coll) {
125                        if (i >= max) {
126                            list.add("(first " + max + '/' + coll.size() + " elements only...)");
127                            break;
128                        }
129                        list.add(item);
130                        i++;
131                    }
132    
133                    o = list;
134                }
135                else if (o instanceof Map<?, ?> && maxItems >= 0) {
136                    Map<?, ?> map = (Map<?, ?>)o;
137                    final int max = Math.min(maxItems, map.size());
138                    Map<Object, Object> copy = new HashMap<Object, Object>(max);
139    
140                    int i = 0;
141                    for (Map.Entry<?, ?> item : map.entrySet()) {
142                        if (i >= max) {
143                            copy.put("(first " + max + '/' + map.size() + " elements only...)", "...");
144                            break;
145                        }
146                        copy.put(item.getKey(), item.getValue());
147                        i++;
148                    }
149    
150                    o = copy;
151                }
152                else {
153                    o = o.toString();
154                }
155    
156                return o;
157            } catch (Exception e) {
158                return o.getClass().getName() + " (exception: " + e.toString() + ")";
159            }
160        }
161    }