KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > monolog > TestHelper


1 /**
2  * Copyright (C) 2002
3  */

4
5 package org.objectweb.util.monolog;
6
7 import junit.framework.TestCase;
8 import junit.textui.TestRunner;
9 import org.objectweb.util.monolog.api.Handler;
10 import org.objectweb.util.monolog.api.HandlerFactory;
11 import org.objectweb.util.monolog.api.LevelFactory;
12 import org.objectweb.util.monolog.api.LoggerFactory;
13 import org.objectweb.util.monolog.api.TopicalLogger;
14
15 import java.io.*;
16 import java.util.Vector JavaDoc;
17
18 /**
19  * This class is test helper which provides tool methods to check a log file.
20  * It extends TestCase to support the use with JUnit.
21  * @author Sebastien Chassande-Barrioz
22  */

23 public class TestHelper extends TestCase {
24     /**
25      * This constant field contains the list of the setter name needed to
26      * initialize this class.
27      */

28     public static final String JavaDoc[] SETTER_METHODS = {"setLoggerFactoryClassName",
29     };
30
31     /**
32      * The Logger factory used during the test
33      */

34     public static LoggerFactory lf = null;
35
36     /**
37      * The handler factory used during the test
38      */

39     public static HandlerFactory hf = null;
40
41     /**
42      * The level factory used during the test
43      */

44     public static LevelFactory lef = null;
45
46     /**
47      * The default file name specify by a setter method.
48      */

49     protected String JavaDoc fileName = null;
50
51     public TestHelper() {
52         super("");
53     }
54
55     public TestHelper(String JavaDoc s) {
56         super(s);
57     }
58
59     protected void setUp() throws Exception JavaDoc {
60         if (lf == null) {
61             synchronized(TestHelper.class) {
62                 lf = Monolog.getMonologFactory("monolog.properties");
63                 hf = (HandlerFactory) lf;
64                 lef = (LevelFactory) lf;
65             }
66         }
67     }
68
69     /**
70      * It assigns the LoggerFactory class name. This method tries to get an
71      * instance with this class name.
72      */

73     public void setLoggerFactoryClassName(String JavaDoc lfcn) {
74         try {
75             lf = (LoggerFactory) Class.forName(lfcn).newInstance();
76         }
77         catch (ClassCastException JavaDoc e) {
78             throw new UnsupportedOperationException JavaDoc(
79                 "The specified class is not a Logger factory: " + lfcn);
80         }
81         catch (Exception JavaDoc e) {
82             throw new UnsupportedOperationException JavaDoc(
83                 "Logger factory class is not availlable: " + lfcn);
84         }
85         if (lf instanceof HandlerFactory) {
86             hf = (HandlerFactory) lf;
87         }
88         if (lf instanceof LevelFactory) {
89             lef = (LevelFactory) lf;
90         }
91     }
92
93     /**
94      * It assigns the default log file name.
95      */

96     public void setOutputFile(String JavaDoc filename) {
97         fileName = filename;
98     }
99
100     /**
101      * It runs the test.
102      */

103     public static void run(Class JavaDoc c, String JavaDoc[] methods, String JavaDoc params[],
104                            String JavaDoc lfcn, String JavaDoc fn) {
105         try {
106             TestRunner.run(getTestSuite(c, methods, params, lfcn, fn));
107         }
108         catch (Exception JavaDoc e) {
109             e.printStackTrace();
110         }
111     }
112
113     /**
114      * It runs the test.
115      */

116     public static void run(Class JavaDoc c, String JavaDoc[] methods,
117                            String JavaDoc params[], String JavaDoc lfcn) {
118         try {
119             TestRunner.run(getTestSuite(c, methods, params, lfcn));
120         }
121         catch (Exception JavaDoc e) {
122             e.printStackTrace();
123         }
124     }
125
126     /**
127      * It retrieves a test suite.
128      */

129     public static TestSuite getTestSuite(Class JavaDoc c,
130                                          String JavaDoc[] methods,
131                                          String JavaDoc params[],
132                                          String JavaDoc lfcn,
133                                          String JavaDoc fn) {
134         Object JavaDoc[] myparams = new Object JavaDoc[params.length + 2];
135         myparams[0] = lfcn;
136         myparams[1] = fn;
137         for (int i = 0; i < params.length; i++) {
138             myparams[i + 2] = params[i];
139         }
140         String JavaDoc[] mymethods = new String JavaDoc[methods.length + 2];
141         mymethods[0] = "setLoggerFactoryClassName";
142         mymethods[1] = "setOutputFile";
143         for (int i = 0; i < methods.length; i++) {
144             mymethods[i + 2] = methods[i];
145         }
146         try {
147             return new TestSuite(c, mymethods, myparams);
148         }
149         catch (Exception JavaDoc e) {
150             e.printStackTrace();
151             return null;
152         }
153     }
154
155     public static TestSuite getTestSuite(Class JavaDoc c,
156                                          String JavaDoc[] methods,
157                                          String JavaDoc params[],
158                                          String JavaDoc lfcn) {
159         Object JavaDoc[] myparams = new Object JavaDoc[params.length + 1];
160         myparams[0] = lfcn;
161         for (int i = 0; i < params.length; i++) {
162             myparams[i + 1] = params[i];
163         }
164         String JavaDoc[] mymethods = new String JavaDoc[methods.length + 1];
165         mymethods[0] = "setLoggerFactoryClassName";
166         for (int i = 0; i < methods.length; i++) {
167             mymethods[i + 1] = methods[i];
168         }
169         try {
170             return new TestSuite(c, mymethods, myparams);
171         }
172         catch (Exception JavaDoc e) {
173             e.printStackTrace();
174             return null;
175         }
176     }
177
178     public static void main(String JavaDoc[] args) {
179         if (args == null || args.length <= 1) {
180             System.out.println("Invalid argument");
181             System.exit(1);
182         }
183         try {
184             File f = new File(args[0]);
185             f.delete();
186             f.createNewFile();
187             PrintStream ps = new PrintStream(new FileOutputStream(f));
188             String JavaDoc[] required = new String JavaDoc[args.length - 1];
189             for (int i = 0; i < required.length; i++) {
190                 required[i] = args[i + 1];
191                 ps.println(required[i]);
192             }
193             ps.flush();
194             ps.close();
195             TestHelper to = new TestHelper();
196             to.setOutputFile(args[0]);
197             to.assertInFileEquals("my message", required);
198             f.delete();
199         }
200         catch (IOException e) {
201             e.printStackTrace();
202             fail(e.getMessage());
203         }
204     }
205
206     /**
207      * It checks that the last line of the default log file is equals to a
208      * specified string.
209      * @param message is the error message if the string is not found.
210      * @param required is the string which must be file in the default log file
211      */

212     public void assertInFileEquals(String JavaDoc message, String JavaDoc required) {
213         String JavaDoc[] r = new String JavaDoc[1];
214         r[0] = required;
215         assertInFileEquals(message, fileName, r);
216     }
217
218     /**
219      * It checks that the last line of the specified log file is equals to a
220      * specified string.
221      * @param message is the error message if the string is not found.
222      * @param filename is the log file name
223      * @param required is the string which must be file in the default log file
224      */

225     public void assertInFileEquals(String JavaDoc message, String JavaDoc filename,
226                                    String JavaDoc required) {
227         String JavaDoc[] r = new String JavaDoc[1];
228         r[0] = required;
229         assertInFileEquals(message, filename, r);
230     }
231
232     /**
233      * It checks that the last lines of the default log file is equals to a
234      * specified string string.
235      * @param message is the error message if the string array is not found.
236      * @param required is the string array which must be file in the default
237      * log file.
238      */

239     public void assertInFileEquals(String JavaDoc message, String JavaDoc[] required) {
240         String JavaDoc[] text = getFirstLines(fileName, required.length);
241         // Check the String
242
for (int i = 0; i < required.length; i++) {
243             debug("found : text[" + i + "]=" + text[i] + " text[i].length = " + text[i].length());
244             debug("required : required[" + i + "]=" + required[i] + " required[i].length = " + required[i].length());
245             assertEquals(message + " " + i, required[i], text[i]);
246         }
247     }
248
249     /**
250      * It checks that the last lines of the specified log file is equals to a
251      * specified string string.
252      * @param message is the error message if the string array is not found.
253      * @param filename is the log file name
254      * @param required is the string array which must be file in the default
255      * log file.
256      */

257     public void assertInFileEquals(String JavaDoc message, String JavaDoc filename,
258                                    String JavaDoc[] required) {
259         String JavaDoc[] text = getFirstLines(filename, required.length);
260         // Check the String
261
for (int i = 0; i < required.length; i++) {
262             debug("found : text[" + i + "]=" + text[i]);
263             debug("required : required[" + i + "]=" + required[i]);
264             assertEquals(message + " " + i, required[i], text[i]);
265         }
266     }
267
268     /**
269      * Return the last lines of the default log file.
270      * @param linenumber is the number of line which must be retrieved.
271      * @return a string array which matches to the last line.
272      */

273     public String JavaDoc[] getLastLines(int linenumber) {
274         return getLastLines(fileName, linenumber);
275     }
276
277     /**
278      * Return the last lines of the default log file.
279      * @param linenumber is the number of line which must be retrieved.
280      * @return a string array which matches to the last line.
281      */

282     public String JavaDoc[] getFirstLines(int linenumber) {
283         return getFirstLines(fileName, linenumber);
284     }
285
286     /**
287      * Return the first lines of the specified log file.
288      * @param linenumber is the number of line which must be retrieved.
289      * @param filename is the log file name
290      * @return a string array which matches to the last line.
291      */

292     public String JavaDoc[] getFirstLines(String JavaDoc filename, int linenumber) {
293         if (filename==null || linenumber==0)
294             return(null);
295         Vector JavaDoc v = new Vector JavaDoc(linenumber);
296         try {
297             FileReader fr= new FileReader(filename);
298             LineNumberReader lnr = new LineNumberReader(fr);
299             String JavaDoc str = lnr.readLine();
300             int i=0;
301             while(i<linenumber && str != null) {
302                 v.addElement(str);
303                 str = lnr.readLine();
304                 i++;
305             }
306             int size = v.size();
307             String JavaDoc[] res = new String JavaDoc[size];
308             for (int j = 0; j < size; j++) {
309                 res[j] = (String JavaDoc) v.elementAt(j);
310             }
311             return res;
312         }
313         catch (Exception JavaDoc e) {
314             e.printStackTrace();
315 // fail(e.getMessage());
316
return null;
317         }
318     }
319     /**
320      * Return the last lines of the specified log file.
321      * @param linenumber is the number of line which must be retrieved.
322      * @param filename is the log file name
323      * @return a string array which matches to the last line.
324      */

325     public String JavaDoc[] getLastLines(String JavaDoc filename, int linenumber) {
326         if (filename==null || linenumber==0)
327             return(null);
328         Vector JavaDoc v = new Vector JavaDoc(linenumber);
329         try {
330             FileReader fr= new FileReader(filename);
331             LineNumberReader lnr = new LineNumberReader(fr);
332             String JavaDoc str = lnr.readLine();
333             int i=0;
334             while(str != null) {
335                 v.addElement(str);
336                 str = lnr.readLine();
337                 i++;
338             }
339             int size = v.size();
340             String JavaDoc[] res = new String JavaDoc[size];
341             for (int j = 0; j < size; j++) {
342                 res[j] = (String JavaDoc) v.elementAt(size-1-j);
343             }
344             return res;
345         }
346         catch (Exception JavaDoc e) {
347             e.printStackTrace();
348 // fail(e.getMessage());
349
return null;
350         }
351     }
352
353     /**
354      * It removes all handlers of the root logger.
355      */

356     public void quietRootLogger() {
357         TopicalLogger l = (TopicalLogger) lf.getLogger("root");
358         Handler[] hcs = l.getHandler();
359         Handler hc = hf.createHandler("handlerOfroot", "file");
360         hc.setAttribute(Handler.OUTPUT_ATTRIBUTE, "rootLogger.log");
361         hc.setAttribute(Handler.PATTERN_ATTRIBUTE, "%m%n");
362         hc.setAttribute("activation", lf);
363         try {
364             l.addHandler(hc);
365             for (int i = 0; i < hcs.length; i++) {
366                 l.removeHandler(hcs[i]);
367             }
368         }
369         catch (Exception JavaDoc e) {
370             fail("error" + e.getMessage());
371         }
372         l = null;
373     }
374
375     static boolean debug =
376             Boolean.valueOf(System.getProperty("monolog.test.debug")).booleanValue();
377
378     /**
379      * This methods is used to debug this helper.
380      */

381     protected void debug(String JavaDoc m) {
382        if (debug)
383             System.out.println(m);
384     }
385
386     private int next(int i, int max) {
387         return (i + 1 == max ? 0 : i + 1);
388     }
389 }
390
Popular Tags