KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > monolog > wrapper > common > AbstractFactory


1 /**
2  * Copyright (C) 2001-2003 France Telecom R&D
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package org.objectweb.util.monolog.wrapper.common;
19
20 import org.objectweb.util.monolog.api.Logger;
21 import org.objectweb.util.monolog.api.Handler;
22 import org.objectweb.util.monolog.api.Level;
23 import org.objectweb.util.monolog.api.BasicLevel;
24 import org.objectweb.util.monolog.api.MonologFactory;
25 import org.objectweb.util.monolog.api.MonologFactoryListener;
26
27 import java.util.ArrayList JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.HashSet JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Properties JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35
36 /**
37  *
38  * @author S.Chassande-Barrioz
39  */

40 public abstract class AbstractFactory
41     implements MonologFactory, Configurable {
42
43     public final static String JavaDoc CLASSLOADER_ISOLATION = "monolog.isolateclassloader";
44     
45     public static String JavaDoc[] handlerTypes = {
46         "console", "file", "rollingfile", "ntevent","jmx"
47     };
48
49     public static String JavaDoc[][] handlerType2className = null;
50
51     public static boolean classLoaderIsoltion = true;
52     
53     /**
54      * Root logger prefix, i.e. <code>rootLoggerName</code> followed by '.'.
55      */

56     protected static String JavaDoc rootLoggerPrefix = null;
57
58     /**
59      * Name of the root logger.
60      * This name intends to isolates the loggers associated to a class loader.
61      */

62     protected static String JavaDoc rootLoggerName = null;
63
64     /**
65      * Gets the prefix of the root logger.
66      */

67     public static String JavaDoc getRootLoggerPrefix() {
68       return rootLoggerPrefix;
69     }
70     
71     public static String JavaDoc getTopicWithoutPrefix(String JavaDoc topic) {
72         if (classLoaderIsoltion && rootLoggerPrefix != null
73                 && topic.startsWith(rootLoggerPrefix)) {
74             return topic.substring(rootLoggerPrefix.length());
75         } else {
76             return topic;
77         }
78     }
79
80     /**
81      * isolates the logger hierarchy for a given class loader
82      * by prepending the root logger name.
83      *
84      * @param name user defined name
85      * @return internal name
86      */

87     protected static String JavaDoc monoLoggerName(String JavaDoc name) {
88       if (!classLoaderIsoltion || name.startsWith(rootLoggerPrefix)) {
89           if (debug) {
90               debug("name already prefixed: " + name);
91           }
92           return name;
93       }
94       return rootLoggerPrefix + name;
95     }
96
97     /**
98      * Inidicates if the monolog wrapper must be logged itself.
99      */

100     public static boolean debug = false;
101
102     static {
103         debug = new Boolean JavaDoc(System.getProperty("monolog.debug")).booleanValue();
104         classLoaderIsoltion = Boolean.valueOf(
105                 System.getProperty(CLASSLOADER_ISOLATION, "true")).booleanValue();
106     }
107     
108     
109     /**
110      * This method must be only used to debug the Monolog wrappers.
111      * To active the log of monolog assign the "true" value to the system
112      * property "monolog.debug".
113      *
114      * @param m the message to log.
115      */

116     public static void debug(String JavaDoc m) {
117         if (debug) {
118             System.out.println(m);
119         }
120     }
121
122     public static void warn(String JavaDoc m) {
123         System.err.println("WARN: " + m);
124     }
125
126     /**
127      * The default resource bundle of this factory
128      */

129     protected String JavaDoc resourceBundleName = null;
130
131     /**
132      * This field references the level instances by their names.<br/>
133      * key = a level name<br/>
134      * value = the unique Level instance linked to the name.
135      */

136     protected Map JavaDoc nameToLevel = null;
137
138     /**
139      * This field reference the level names by their integer value.<br/>
140      * key = a java.lang.Integer which the value is the level<br/>
141      * value = a String or an ArrayList of String. The strings represent the
142      * name which match to the integer value. Indeed both name can be associated
143      * to the same integer value.
144      */

145     protected Map JavaDoc intToNames = null;
146
147     /**
148      * This field references the handler instance by their names.<br/>
149      * key = a String object which is an handler name.
150      * value = the unique handler instance which has the key for name.
151      */

152     protected Map JavaDoc handlers = null;
153     
154     /**
155      * This field references the MonolgFactoryListener instance by their names.<br/>
156      * key = a String object which is an handler name.
157      * value = the unique handler instance which has the key for name.
158      */

159     protected Collection JavaDoc monologFactoryListeners = null;
160
161     /**
162      * It initializes the default monolog level: INHERIT, DEBUG, INFO, WARN,
163      * ERROR, FATAL
164      */

165     public AbstractFactory() {
166         intToNames = new HashMap JavaDoc();
167         nameToLevel = new HashMap JavaDoc();
168         handlers = new HashMap JavaDoc();
169         monologFactoryListeners = new HashSet JavaDoc();
170         defineLevel(BasicLevel.LEVEL_INHERIT);
171         defineLevel(BasicLevel.LEVEL_DEBUG);
172         defineLevel(BasicLevel.LEVEL_INFO);
173         defineLevel(BasicLevel.LEVEL_WARN);
174         defineLevel(BasicLevel.LEVEL_ERROR);
175         defineLevel(BasicLevel.LEVEL_FATAL);
176         if (handlerType2className == null) {
177             synchronized(getClass()) {
178                 if (handlerType2className == null) {
179                     initHandlerType2className();
180                 }
181             }
182         }
183     }
184
185     public abstract String JavaDoc getWrapperName();
186
187     protected void initHandlerType2className() {
188         handlerType2className = getDefaultHandlerType2className();
189         for(int i=0; i<handlerType2className.length; i++) {
190             handlerTypes[i] = handlerType2className[i][0];
191         }
192
193         String JavaDoc hts = System.getProperty("monolog." + getWrapperName() + ".handlerTypes");
194         if (hts != null && hts.length() > 0) {
195             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(hts,",;:|.", false);
196             Map JavaDoc m = null;
197             if (st.hasMoreTokens()) {
198                 m = new HashMap JavaDoc();
199             }
200             while(st.hasMoreTokens()) {
201                 //Handler type
202
String JavaDoc ht = st.nextToken();
203                 //Handler class name
204
String JavaDoc hcn = System.getProperty("monolog.handlerType." + ht);
205                 if (hcn != null && hcn.length() > 0) {
206                     m.put(ht, hcn);
207                 } else {
208                     debug("Handler type '" + ht + "' not well defined: " + hcn);
209                 }
210             }
211             if (m != null && m.size() > 0) {
212                 //Copy old type
213
String JavaDoc[] newHT = new String JavaDoc[handlerTypes.length + m.size()];
214                 System.arraycopy(handlerTypes, 0, newHT, 0, handlerTypes.length);
215                 String JavaDoc[][] newHT2CN = new String JavaDoc[handlerTypes.length + m.size()][];
216                 System.arraycopy(handlerType2className, 0, newHT2CN, 0, handlerType2className.length);
217
218                 //Add the new ones
219
int i = handlerTypes.length;
220                 for(Iterator JavaDoc it = m.entrySet().iterator(); it.hasNext();) {
221                     Map.Entry JavaDoc me = (Map.Entry JavaDoc) it.next();
222                     handlerTypes[i] = (String JavaDoc) me.getKey();
223                     handlerType2className[i][0] = handlerTypes[i];
224                     handlerType2className[i][1] = (String JavaDoc) me.getValue();
225                 }
226                 handlerTypes = newHT;
227                 handlerType2className = newHT2CN;
228             }
229         }
230     }
231
232     abstract protected String JavaDoc[][] getDefaultHandlerType2className();
233
234     /**
235      * Insert a level into the data structure.<br/>
236      * If the level name is already used with other integer value, the null
237      * value is returned.<br/>
238      * If the level name is already used with the same integer value, the level
239      * found in the data structure is returned.<br/>
240      *
241      * @param l the Level instance which must be inserted.
242      * @return the Level instance or a null value.
243      */

244     private Level defineLevel(Level l) {
245         //System.out.println("def(" + l + ") begin");
246
String JavaDoc name = l.getName();
247         int value = l.getIntValue();
248         Level res = (Level) nameToLevel.get(name);
249         if (res != null) {
250             // The name is already defined.
251
return (res.getIntValue() == value ? res : null);
252         } else {
253             res = l;
254             nameToLevel.put(name, res);
255             Integer JavaDoc i = new Integer JavaDoc(value);
256             Object JavaDoc temp = intToNames.get(i);
257             if (temp != null) {
258                 if (temp instanceof String JavaDoc) {
259                     if (!((String JavaDoc) temp).equalsIgnoreCase(name)) {
260                         // The int value has already another name
261
// Add the new name to the other
262
ArrayList JavaDoc al = new ArrayList JavaDoc(5);
263                         al.add(temp);
264                         al.add(name);
265                         intToNames.put(i, al);
266                     }
267                 }
268                 else if (temp instanceof ArrayList JavaDoc) {
269                     // The int value has already several another name
270
ArrayList JavaDoc al = (ArrayList JavaDoc) temp;
271                     if (!al.contains(name)) {
272                         // Add the new name to the others
273
al.add(name);
274                     }
275                 }
276             }
277             else {
278                 // The int value does not have any name
279
intToNames.put(i, name);
280             }
281             //Calling the listeners
282
Iterator JavaDoc iterator = monologFactoryListeners.iterator ();
283             while (iterator.hasNext ()) {
284                 MonologFactoryListener mfl = ((MonologFactoryListener)iterator.next ());
285                 mfl.levelCreated (res);
286             }
287         }
288         //System.out.println("def(" + l + ") end");
289
return res;
290     }
291
292     // IMPLEMENTATION OF THE Configurable INTERFACE //
293
//----------------------------------------------//
294

295     public abstract void configure(Properties JavaDoc prop) throws Exception JavaDoc;
296
297     // IMPLEMENTATION OF INTERFACE LoggerFactory //
298
//-------------------------------------------//
299

300     public abstract Logger getLogger(String JavaDoc key);
301
302     public abstract Logger[] getLoggers();
303
304     public String JavaDoc getTopicPrefix() {
305         return rootLoggerPrefix;
306     }
307     
308     public String JavaDoc getResourceBundleName() {
309         return resourceBundleName;
310     }
311
312     public void setResourceBundleName(String JavaDoc rbn) {
313         resourceBundleName = rbn;
314     }
315
316
317     // IMPLEMENTATION OF THE HandlerFactory INTERFACE //
318
//------------------------------------------------//
319

320     public Handler createHandler(String JavaDoc hn, String JavaDoc handlertype) {
321         Handler res = (Handler) handlers.get(hn);
322         if (res != null) {
323             return res;
324         }
325         if (handlertype == null) {
326             return null;
327         }
328         int i =0;
329         for(;i<handlerType2className.length
330             && !handlerType2className[i][0].equalsIgnoreCase(handlertype); i++);
331         String JavaDoc handlerClassName;
332         if (i<handlerType2className.length) {
333             handlerClassName = handlerType2className[i][1];
334         } else {
335             handlerClassName = handlertype;
336         }
337         debug("Instanciating the handler '" + hn + "', class name=" + handlerClassName);
338         try {
339             res = (Handler) Class.forName(handlerClassName).newInstance();
340         } catch (Throwable JavaDoc e) {
341             warn("Impossible to instanciate the handler: name=" + hn
342                 + ", class name=" + handlerClassName +": " + e.getMessage());
343             e.printStackTrace(System.err);
344             return null;
345         }
346         res.setAttribute("handlertype", handlertype);
347         res.setName(hn);
348         handlers.put(hn, res);
349         //Calling the listeners
350
Iterator JavaDoc iterator = monologFactoryListeners.iterator ();
351         while (iterator.hasNext ()) {
352             MonologFactoryListener mfl = ((MonologFactoryListener)iterator.next ());
353             mfl.handlerCreated(res);
354         }
355         return res;
356     }
357
358     public Handler[] getHandlers() {
359         return (Handler[]) handlers.values().toArray(new Handler[0]);
360     }
361
362     public Handler getHandler(String JavaDoc hn) {
363         return (Handler) handlers.get(hn);
364     }
365
366     public Handler removeHandler(String JavaDoc hn) {
367         Handler res = (Handler) handlers.remove(hn);
368         if (res != null) {
369             //Calling the listeners
370
Iterator JavaDoc iterator = monologFactoryListeners.iterator ();
371             while (iterator.hasNext ()) {
372                 MonologFactoryListener mfl = ((MonologFactoryListener)iterator.next ());
373                 mfl.handlerRemoved(getHandler(hn));
374             }
375          }
376         return res;
377     }
378
379     // IMPLEMENTATION OF THE LevelFactory INTERFACE //
380
//-----------------------------------------------//
381

382     public Level defineLevel(String JavaDoc name, int value) {
383         return defineLevel(new LevelImpl(name, value));
384     }
385
386     public Level defineLevel(String JavaDoc name, String JavaDoc value) {
387         return defineLevel(new LevelImpl(name, value, this));
388     }
389
390     public Level getLevel(String JavaDoc name) {
391         return (Level) nameToLevel.get(name);
392     }
393
394     public Level getLevel(int value) {
395         Object JavaDoc temp = intToNames.get(new Integer JavaDoc(value));
396         if (temp == null) {
397             return null;
398         }
399         else if (temp instanceof String JavaDoc) {
400             return getLevel((String JavaDoc) temp);
401         }
402         else if (temp instanceof ArrayList JavaDoc) {
403             return getLevel((String JavaDoc) ((ArrayList JavaDoc) temp).get(0));
404         }
405         return null;
406     }
407
408     public Level[] getLevels() {
409         return (Level[]) nameToLevel.values().toArray(new Level[0]);
410     }
411
412     public void removeLevel(String JavaDoc name) {
413         Level removed = (Level) nameToLevel.remove(name);
414         if (removed != null) {
415             Integer JavaDoc i = new Integer JavaDoc(removed.getIntValue());
416             Object JavaDoc temp = intToNames.get(i);
417             if (temp instanceof String JavaDoc) {
418                 intToNames.remove(i);
419             } else if (temp instanceof ArrayList JavaDoc) {
420                 ((ArrayList JavaDoc) temp).remove(name);
421             }
422             //Calling the listeners
423
Iterator JavaDoc iterator = monologFactoryListeners.iterator ();
424              while (iterator.hasNext ()) {
425                 MonologFactoryListener mfl = ((MonologFactoryListener)iterator.next ());
426                 mfl.levelRemoved(removed);
427              }
428         }
429     }
430     // IMPLEMENTATION OF THE MonologFactoryListener INTERFACE //
431
//-----------------------------------------------//
432

433     public void addMonologFactoryListener (MonologFactoryListener mfl) {
434         monologFactoryListeners.add(mfl);
435     }
436     
437     public void removeMonologFactoryListener (MonologFactoryListener mfl) {
438         monologFactoryListeners.remove(mfl);
439     }
440 }
441
Popular Tags