KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > messaging > MessageHandler


1 /*
2  * $Id: MessageHandler.java,v 1.6.2.6 2003/02/25 14:09:20 jeremias Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 package org.apache.fop.messaging;
52
53 import org.apache.avalon.framework.logger.ConsoleLogger;
54 import org.apache.avalon.framework.logger.Logger;
55
56 import java.io.*;
57 import java.util.*;
58
59 /**
60  * The class MessageHandler contains the static methods log and error which
61  * should be used for any end user information instead of System.out.print() or
62  * System.err.print(). The class defines several output methods:
63  * writing to the screen (default), logging to a file, creating message events and repressing all
64  * output. If you don't want to change the default behaviour, you should be
65  * happy with MessageHandler.log(message) and MessageHandler.error(message)<br>
66  * The class MessageHandler also supports the setting of an id. If set every message
67  * has as a prefix an identifying string. That way Fop probably can also be used in
68  * environments, where more than one Fop instance are running in same JVM.<br>
69  * If Fop is embedded in a gui application or for any reasons the existing
70  * messaging system doesn't meet the programmer's requirements, one can add
71  * a MessageEvent listener to MessageHandler and handle the incoming messages
72  * in an appropriate way. See the class DefaultMessageListener, which is a trivial
73  * implementation of the MessageListener.
74  * Here is an example how to configure MessageHandler for the DefaultMessageListener (anybody
75  * can provide his own listener by extending MessageListener<br>
76  * <code>
77  * MessageHandler.setOutputMethod(MessageHandler.EVENT);
78  * MessageHandler.addListener(new DefaultMessageListener());
79  * </code><br>
80  * This examples shows, how to redirect the messages to a log file called fop.log.
81  * All messages are appended to this file.
82  * <code>
83  * MessageHandler.setOutputMethod(MessageHandler.FILE);
84  * MessageHandler.setLogfileName("\\fop.log",true);
85  * </code>
86  */

87
88 public class MessageHandler {
89     public static final int SCREEN = 0;
90     public static final int FILE = 1;
91     public static final int EVENT = 2;
92     public static final int NONE = 3; // this should always be the last method
93

94     private static Logger logger = null;
95     private static String logfileName = "fop.log";
96     private static PrintWriter writer;
97     private static int outputMethod = SCREEN;
98     private static boolean fileOpened = false;
99     private static boolean appendToFile = true;
100     private static String message = "";
101     private static String prefix = "";
102     private static Vector listeners = new Vector();
103     private static boolean IDisSet = false;
104     private static boolean quiet = false;
105
106     /**
107      * helper class to access the message
108      * @return a string containing the message
109      */

110
111     private static String getMessage() {
112         return message;
113     }
114
115     /**
116      * helper class which sets the message
117      * and adds a prefix which can contain
118      * the id of the thread which uses this messagehandler
119      */

120     private static void setMessage(String m) {
121         if (IDisSet) {
122             message = getID() + ":" + m;
123         } else {
124             message = m;
125         }
126     }
127
128     /**
129      * informs the user of the message
130      * @param message the message for the user
131      */

132     public static void log(String message) {
133         if (quiet) {
134             return;
135         }
136
137         if (logger == null) {
138             logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
139             logger.warn("Screen logger not set - Using ConsoleLogger.");
140         }
141
142         setMessage(message);
143         switch (outputMethod) {
144         case SCREEN:
145             logger.info(getMessage());
146             break;
147         case FILE:
148             if (fileOpened) {
149                 writer.print(getMessage());
150                 writer.flush();
151             } else {
152                 openFile();
153                 writer.print(getMessage());
154                 writer.flush();
155             }
156             break;
157         case EVENT:
158             setMessage(message);
159             Enumeration enum = listeners.elements();
160             while (enum.hasMoreElements()) {
161                 ((MessageListener)enum.nextElement()).processMessage(new MessageEvent(getMessage()));
162             }
163             break;
164         case NONE:
165             // do nothing
166
break;
167         default:
168             logger.info(message);
169         }
170     }
171
172     /**
173      * convenience method which adds a return to the message
174      * @param message the message for the user
175      */

176     public static void logln(String message) {
177         log(message);
178     }
179
180     /**
181      * error warning for the user
182      * @param errorMessage contains the warning string
183      */

184
185     public static void error(String errorMessage) {
186         if (logger == null) {
187             logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
188             logger.warn("Screen logger not set - Using ConsoleLogger.");
189         }
190
191         setMessage(errorMessage);
192         switch (outputMethod) {
193         case SCREEN:
194             logger.error(getMessage());
195             break;
196         case FILE:
197             if (fileOpened) {
198                 writer.print(getMessage());
199                 writer.flush();
200             } else {
201                 openFile();
202                 writer.print(getMessage());
203                 writer.flush();
204             }
205             break;
206         case EVENT:
207             setMessage(message);
208             Enumeration enum = listeners.elements();
209             while (enum.hasMoreElements()) {
210                 MessageEvent messEv = new MessageEvent(getMessage());
211                 messEv.setMessageType(MessageEvent.ERROR);
212                 ((MessageListener)enum.nextElement()).processMessage(messEv);
213             }
214             break;
215         case NONE:
216             // do nothing
217
break;
218         default:
219             logger.error(errorMessage);
220         }
221     }
222
223     /**
224      * convenience method which adds a return to the error message
225      * @param errorMessage the message for the user
226      */

227     public static void errorln(String errorMessage) {
228         error(errorMessage);
229     }
230
231     /**
232      * adds a MessageListener which listens for MessageEvents
233      * @param MessageListener the listener to add
234      */

235     public static void addListener(MessageListener listener) {
236         listeners.add(listener);
237     }
238
239     /**
240      * removes a MessageListener
241      * @param MessageListener the listener to remove
242      */

243     public static void removeListener(MessageListener listener) {
244         listeners.removeElement(listener);
245     }
246
247     /**
248      * Sets the Logger used for the screen output method.
249      * @param newLogger a logger for screen output. This may not be null.
250      */

251     public static void setScreenLogger(Logger newLogger) {
252         if (newLogger == null)
253             throw new NullPointerException();
254         logger = newLogger;
255     }
256
257     /**
258      * sets the output method
259      * @param method the output method to use, allowed values are<br>
260      * MessageHandler.SCREEN, MessageHandler.FILE, MessageHandler.EVENT
261      * MessageHandler.NONE
262      */

263     public static void setOutputMethod(int method) {
264         if (method > NONE) {
265             MessageHandler.error("Error: Unknown output method");
266         } else {
267             outputMethod = method;
268         }
269     }
270
271     /**
272      * informs what output method is set
273      * @return the output method
274      */

275     public static int getOutputMethod() {
276         return outputMethod;
277     }
278
279     /**
280      * sets the logfile name
281      * @param filename name of the logfile
282      * @param append if true, the logfile is appended
283      */

284     public static void setLogfileName(String filename, boolean append) {
285         logfileName = filename;
286         appendToFile = append;
287     }
288
289     /**
290      * returns the logfile name
291      * @return String containing the logfile name
292      */

293     public static String getLogfileName() {
294         return logfileName;
295     }
296
297     /**
298      * helper file which opens the file for output method FILE
299      */

300     private static void openFile() {
301         try {
302             writer =
303                 new PrintWriter(new FileWriter(logfileName, appendToFile),
304                                 true);
305             writer.println("\n==============================================");
306             fileOpened = true;
307         } catch (IOException ioe) {
308             System.err.println("Error: " + ioe);
309         }
310     }
311
312     /**
313      * if set to true an id string is prefixed to every message
314      * uses the thread info as an id for the message producer. Should be used if
315      * more than one instance of Fop is running in the same JVM
316      * this id becomes a prefix to every message
317      */

318     private static String getID() {
319         return Thread.currentThread().toString();
320     }
321
322     /**
323      * if set to true an id string is prefixed to every message
324      * uses the thread info as an id for the message producer. Should be used if
325      * more than one instance of Fop is running in the same JVM
326      * this id becomes a prefix to every message
327      *
328      * @param id boolean (default is false)
329      */

330
331     public static void setID(boolean id) {
332         IDisSet = id;
333     }
334
335     /**
336      * if set to true all normal messages are suppressed.
337      * error messages are displayed allthesame
338      *
339      * @param quietMode boolean (default is false)
340      */

341     public static void setQuiet(boolean quietMode) {
342         quiet = quietMode;
343     }
344
345 }
346
Popular Tags