View Javadoc

1   /*
2    * $HeadURL: $
3    * $Date: $
4    * $Revision: $
5    * $Author: $
6    * 
7    * Copyright (c) 2005 MindTree Consulting Ltd. 
8    * 
9    * This file is part of Insight.
10   * 
11   * Insight is free software: you can redistribute it and/or modify it under the 
12   * terms of the GNU General Public License as published by the Free Software 
13   * Foundation, either version 3 of the License, or (at your option) any later 
14   * version.
15   * 
16   * Insight is distributed in the hope that it will be useful, but 
17   * WITHOUT ANY WARRANTY; without even the implied warranty of 
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General 
19   * Public License for more details.
20   * 
21   * You should have received a copy of the GNU General Public License along with 
22   * Insight.  If not, see <http://www.gnu.org/licenses/>.
23   */
24  
25  package com.mindtree.techworks.insight.preferences.util;
26  
27  import java.util.HashMap;
28  import java.util.StringTokenizer;
29  
30  import com.mindtree.techworks.insight.InsightConstants;
31  import com.mindtree.techworks.insight.gui.widgets.StatusBar;
32  import com.mindtree.techworks.insight.model.ReceiverFormat;
33  import com.mindtree.techworks.insight.preferences.PreferenceManager;
34  import com.mindtree.techworks.insight.preferences.model.Preference;
35  import com.mindtree.techworks.insight.preferences.model.PreferenceAttribute;
36  
37  /**
38   * The <code>Log4JPatternInterpeter</code> class interprets the pattern layout
39   * of Log4J and returns a pattern format that is recognized by the Log pattern
40   * receiver.
41   * <p>
42   * The following variables used in PatternLayout and the interpretation are:
43   * <ul>
44   * <li>%c - category LOGGER</li>
45   * <li>%C - Class name CLASS</li>
46   * <li>%d - date TIMESTAMP</li>
47   * <li>%l - location information FILE</li>
48   * <li>%F - location information FILE</li>
49   * <li>%L - Line number of caller LINE</li>
50   * <li>%m - application message MESSAGE</li>
51   * <li>%M - method name of caller METHOD</li>
52   * <li>%p - priority LEVEL</li>
53   * <li>%r - number of milliseconds elapsed time since start RELATIVETIME</li>
54   * <li>%t - thread name THREAD</li>
55   * <li>%x - NDC (nested diagnostic context) associated with the thread NDC
56   * <li>%n - Line feed
57   * </li>
58   * </ul>
59   * </p>
60   * 
61   * @author Regunath B
62   * @version 1.0, 04/12/30
63   * @see com.mindtree.techworks.insight.model.ReceiverFormat
64   */
65  public class Log4JPatternInterpeter {
66  
67  	/**
68  	 * Id of the Preference
69  	 */
70  	private static final String PREFERENCE_ID = "log4jPattern";
71  
72  	/**
73  	 * A string array for valid logging patterns.
74  	 */
75  	private static final String[] LOGGING_PATTERNS = {"primaryPattern","secondaryPattern"};
76  	
77  	/**
78  	 * Useful map of the Log4JPattern and the respective interpreted canonical
79  	 * keywords recognized by the receiver
80  	 */
81  	private static HashMap PATTERN_MATCH = new HashMap();
82  	static {
83  		PATTERN_MATCH.put("c", "LOGGER");
84  		PATTERN_MATCH.put("C", "CLASS");
85  		PATTERN_MATCH.put("d", "TIMESTAMP");
86  		PATTERN_MATCH.put("l", "FILE");
87  		PATTERN_MATCH.put("F", "FILE");
88  		PATTERN_MATCH.put("L", "LINE");
89  		PATTERN_MATCH.put("m", "MESSAGE");
90  		PATTERN_MATCH.put("M", "METHOD");
91  		PATTERN_MATCH.put("p", "LEVEL");
92  		PATTERN_MATCH.put("r", "RELATIVETIME");
93  		PATTERN_MATCH.put("t", "THREAD");
94  		PATTERN_MATCH.put("x", "NDC");
95  		// set of chars that are replaced with ""
96  		PATTERN_MATCH.put("n", "");
97  	}
98  
99  	/**
100 	 * Array of recognized patterns/characters
101 	 */
102 	private static final String [] RECOGNIZED_PATTERNS = { 
103 			"c", // 0
104 			"C", //1
105 			"d", //2
106 			"l", //3
107 			"F", //4
108 			"L", //5
109 			"m", //6
110 			"M", //7
111 			"p", //8
112 			"r", //9
113 			"t", //10
114 			"x", //11
115 			"n", //12
116 	};
117 
118 	/**
119 	 * Useful constant for specific indices in the above list of recognized
120 	 * patterns
121 	 */
122 	private static final int TIMESTAMP_INDEX = 2;
123 
124 	/**
125 	 * Useful Constant for characters
126 	 */
127 	private static final String PERCENT = "%";
128 
129 	/**
130 	 * Useful Constant for characters
131 	 */
132 	private static final char BRACKET_START = '{';
133 
134 	/**
135 	 * Useful Constant for characters
136 	 */
137 	private static final char BRACKET_END = '}';
138 
139 
140 	/**
141 	 * Gets the interpreted receiver-recognizable pattern for the specified
142 	 * Log4j pattern
143 	 * 
144 	 * @param log4jPattern the Log4j pattern to be interpreted
145 	 * @return the receiver recognizable ReceiverFormat
146 	 * @deprecated Use the
147 	 *             {@link Log4JPatternInterpeter#getInterpretedRecieverFormat() getInterpretedRecieverFormat()}
148 	 *             method instead.
149 	 */
150 	public static ReceiverFormat getInterpretedFormat (String log4jPattern) {
151 
152 		StringBuffer interpretedPattern = new StringBuffer();
153 		String timeFormat = null;
154 		StringTokenizer tokenizer = new StringTokenizer(log4jPattern, PERCENT);
155 		try {
156 			while (tokenizer.hasMoreTokens()) {
157 				String token = tokenizer.nextToken();
158 				for (int i = 0; i < RECOGNIZED_PATTERNS.length; i++ ) {
159 					int keyCharIndex = token.indexOf(RECOGNIZED_PATTERNS[i]);
160 					if (keyCharIndex > -1) { // there is a recognized keyword
161 						token = PATTERN_MATCH.get(RECOGNIZED_PATTERNS[i])
162 								+ token.substring(keyCharIndex + 1, token
163 										.length());
164 						int bracketIndex = token.indexOf(BRACKET_START);
165 						if (bracketIndex > -1) {
166 							if (i == TIMESTAMP_INDEX) { // Timestamp format
167 								// exists
168 								timeFormat = token.substring(bracketIndex + 1,
169 										token.indexOf(BRACKET_END));
170 							}
171 							token = token.substring(0, bracketIndex)
172 									+ token.substring(token
173 											.indexOf(BRACKET_END) + 1, token
174 											.length());
175 						}
176 						break;
177 					}
178 				}
179 				interpretedPattern.append(token);
180 			}
181 		} catch (Exception e) { // Catch all possible exceptions due to bad
182 			// pattern
183 			e.printStackTrace();
184 			StatusBar.getInstance().setDisplayText(0,
185 					InsightConstants.getLiteral("ERROR_LOG4J_PATTERN"), false);
186 			return new ReceiverFormat("", "", "");
187 		}
188 		return new ReceiverFormat(log4jPattern, interpretedPattern.toString()
189 				.trim(), timeFormat);
190 	}
191 
192 	/**
193 	 * Gets the interpreted Receiver Format from the Preferences
194 	 * 
195 	 * @return RecieverFormat from the Preferences
196 	 */
197 	public static ReceiverFormat[] getInterpretedRecieverFormat () {
198 
199 		Preference preference = PreferenceManager.getInstance().getPreference(
200 				PREFERENCE_ID);
201 		ReceiverFormat[] receiverFormat = new ReceiverFormat[LOGGING_PATTERNS.length];
202 		/*
203 		 *Trying to add support for multiple patterns by making receiver format an array.
204 		 */
205 		for(int i=0; i<LOGGING_PATTERNS.length; i++){
206 			PreferenceAttribute preferenceAttribute = preference.getPreferenceAttributeById(LOGGING_PATTERNS[i]);
207 			receiverFormat[i] = getInterpretedFormat(preferenceAttribute.getValue());
208 		}
209 		return receiverFormat;
210 	}
211 
212 	/**
213 	 * Entry method to test this interpreter
214 	 * 
215 	 * @param args
216 	 */
217 	public static void main (String [] args) {
218 
219 		//System.out.println(Log4JPatternInterpeter.getInterpretedFormat("%d{dd
220 		// MMM yyyy HH:mm:ss,SSS} %t %-5p %c{2} - %m%n"));
221 		//System.out.println(Log4JPatternInterpeter.getInterpretedFormat("%d
222 		// %-5p %c --> %M() [%t]: %m %n"));
223 		//System.out.println(Log4JPatternInterpeter.getInterpretedFormat("%d{HH:mm:ss,SSS}
224 		// [%-9t] %-5p [%-42c{3}] %x - %m%n"));
225 		System.out.println(Log4JPatternInterpeter
226 				.getInterpretedFormat("####<%d{MMM dd, yyyy hh:mm:ss a z}> %m%n"));
227 		//System.out.println(Log4JPatternInterpeter.getInterpretedRecieverFormat());
228 	}
229 
230 }