KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > LoggingTestCaseHid


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide;
21
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.PrintStream JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.Date JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.LinkedList JavaDoc;
30 import java.util.regex.Pattern JavaDoc;
31 import junit.framework.AssertionFailedError;
32 import junit.framework.TestResult;
33 import org.netbeans.junit.MockServices;
34 import org.netbeans.junit.NbTestCase;
35 import org.openide.util.Lookup;
36
37 /** Basic skeleton for logging test case.
38  *
39  * @author Jaroslav Tulach
40  */

41 public abstract class LoggingTestCaseHid extends NbTestCase {
42     static {
43         MockServices.setServices(new Class JavaDoc[] {ErrManager.class});
44     }
45
46     protected LoggingTestCaseHid (String JavaDoc name) {
47         super (name);
48     }
49     
50     /** If execution fails we wrap the exception with
51      * new log message.
52      */

53     protected void runTest () throws Throwable JavaDoc {
54         
55         assertNotNull ("ErrManager has to be in lookup", Lookup.getDefault().lookup(ErrManager.class));
56         
57         ErrManager.clear(getName(), getLog());
58         
59         try {
60             super.runTest ();
61         } catch (AssertionFailedError ex) {
62             AssertionFailedError ne = new AssertionFailedError (ex.getMessage () + " Log:\n" + ErrManager.messages);
63             ne.setStackTrace (ex.getStackTrace ());
64             throw ne;
65         } catch (IOException JavaDoc iex) {//#66208
66
IOException JavaDoc ne = new IOException JavaDoc (iex.getMessage () + " Log:\n" + ErrManager.messages);
67             ne.setStackTrace (iex.getStackTrace ());
68             throw ne;
69     } finally {
70             // do not write to log files anymore
71
ErrManager.clear(getName(), System.err);
72         }
73     }
74     
75     /** Registers hints for controlling thread switching in multithreaded
76      * applications.
77      * @param url the url to read the file from
78      * @exception IOException thrown when there is problem reading the url
79      */

80     protected final void registerSwitches(URL JavaDoc url, int timeout) throws IOException JavaDoc {
81         ByteArrayOutputStream JavaDoc os = new ByteArrayOutputStream JavaDoc();
82         InputStream JavaDoc is = url.openStream();
83         for (;;) {
84             int ch = is.read ();
85             if (ch == -1) break;
86             os.write (ch);
87         }
88         os.close();
89         is.close();
90         
91         registerSwitches(new String JavaDoc(os.toByteArray(), "utf-8"), timeout);
92     }
93     
94     /** Registers hints for controlling thread switching in multithreaded
95      * applications.
96     
97      */

98     protected final void registerSwitches(String JavaDoc order, int timeout) {
99         ErrManager.timeout = timeout;
100         
101         LinkedList JavaDoc switches = new LinkedList JavaDoc();
102         
103         HashMap JavaDoc exprs = new HashMap JavaDoc();
104         
105         int pos = 0;
106         for(;;) {
107             int thr = order.indexOf("THREAD:", pos);
108             if (thr == -1) {
109                 break;
110             }
111             int msg = order.indexOf("MSG:", thr);
112             if (msg == -1) {
113                 fail("After THREAD: there must be MSG: " + order.substring(thr));
114             }
115             int end = order.indexOf("THREAD:", msg);
116             if (end == -1) {
117                 end = order.length();
118             }
119             
120             String JavaDoc thrName = order.substring(pos + 7, msg).trim();
121             String JavaDoc msgText = order.substring(msg + 4, end).trim();
122             
123             Pattern JavaDoc p = (Pattern JavaDoc)exprs.get(msgText);
124             if (p == null) {
125                 p = Pattern.compile(msgText);
126                 exprs.put(msgText, p);
127             }
128             
129             Switch s = new Switch(thrName, p);
130             switches.add(s);
131             
132             pos = end;
133         }
134         
135         ErrManager.switches = switches;
136     }
137
138     //
139
// Logging support
140
//
141
public static final class ErrManager extends ErrorManager {
142         public static final StringBuffer JavaDoc messages = new StringBuffer JavaDoc ();
143         static java.io.PrintStream JavaDoc log = System.err;
144         
145         private String JavaDoc prefix;
146
147         private static LinkedList JavaDoc switches;
148         private static int timeout;
149         /** maps names of threads to their instances*/
150         private static java.util.Map JavaDoc threads = new java.util.HashMap JavaDoc();
151         
152         public ErrManager () {
153             this (null);
154         }
155         public ErrManager (String JavaDoc prefix) {
156             this.prefix = prefix;
157         }
158         
159         public Throwable JavaDoc annotate (Throwable JavaDoc t, int severity, String JavaDoc message, String JavaDoc localizedMessage, Throwable JavaDoc stackTrace, Date JavaDoc date) {
160             return t;
161         }
162         
163         public Throwable JavaDoc attachAnnotations (Throwable JavaDoc t, ErrorManager.Annotation[] arr) {
164             return t;
165         }
166         
167         public ErrorManager.Annotation[] findAnnotations (Throwable JavaDoc t) {
168             return null;
169         }
170         
171         public ErrorManager getInstance (String JavaDoc name) {
172             if (
173                 true
174             ) {
175                 return new ErrManager ('[' + name + "] ");
176             } else {
177                 // either new non-logging or myself if I am non-logging
178
return new ErrManager ();
179             }
180         }
181         
182         public void log (int severity, String JavaDoc s) {
183             StringBuffer JavaDoc oneMsg = new StringBuffer JavaDoc();
184             if (prefix != null) {
185                 oneMsg.append(prefix);
186             } else {
187                 oneMsg.append("[default] ");
188             }
189             oneMsg.append("THREAD:");
190             oneMsg.append(Thread.currentThread().getName());
191             oneMsg.append(" MSG:");
192             oneMsg.append(s);
193
194
195             messages.append(oneMsg.toString());
196             messages.append ('\n');
197
198             if (messages.length() > 40000) {
199                 messages.delete(0, 20000);
200             }
201
202             log.println(oneMsg.toString());
203             
204             if (switches != null) {
205                 boolean log = true;
206                 boolean expectingMsg = false;
207                 for(;;) {
208                     synchronized (switches) {
209                         if (switches.isEmpty()) {
210                             return;
211                         }
212
213
214                         Switch w = (Switch)switches.getFirst();
215                         String JavaDoc threadName = Thread.currentThread().getName();
216                         boolean foundMatch = false;
217
218                         if (w.matchesThread()) {
219                             if (!w.matchesMessage(s)) {
220                                 // same thread but wrong message => go on
221
return;
222                             }
223                             // the correct message from the right thread found
224
switches.removeFirst();
225                             if (switches.isEmpty()) {
226                                 // end of sample, make all run
227
switches.notifyAll();
228                                 return;
229                             }
230                             w = (Switch)switches.getFirst();
231                             if (w.matchesThread()) {
232                                 // next message is also from this thread, go on
233
return;
234                             }
235                             expectingMsg = true;
236                             foundMatch = true;
237                         } else {
238                             // compute whether we shall wait or not
239
java.util.Iterator JavaDoc it = switches.iterator();
240                             while (it.hasNext()) {
241                                 Switch check = (Switch)it.next();
242                                 if (check.matchesMessage(s)) {
243                                     expectingMsg = true;
244                                     break;
245                                 }
246                             }
247                         }
248
249                         // make it other thread run
250
Thread JavaDoc t = (Thread JavaDoc)threads.get(w.name);
251                         if (t != null) {
252                             if (log) {
253                                 messages.append("t: " + threadName + " interrupts: " + t.getName() + "\n");
254                             }
255                             t.interrupt();
256                         }
257                         threads.put(threadName, Thread.currentThread());
258                         
259 //
260
// if (log) {
261
// messages.append("t: " + Thread.currentThread().getName() + " log: " + s + " result: " + m + " for: " + w + "\n");
262
// }
263
if (!expectingMsg) {
264                             return;
265                         }
266
267                         // clear any interrupt that happend before
268
Thread.interrupted();
269                         try {
270                             if (log) {
271                                 messages.append("t: " + threadName + " log: " + s + " waiting\n");
272                             }
273                             switches.wait(timeout);
274                             if (log) {
275                                 messages.append("t: " + threadName + " log: " + s + " timeout\n");
276                             }
277                             return;
278                         } catch (InterruptedException JavaDoc ex) {
279                             // ok, we love to be interrupted => go on
280
if (log) {
281                                 messages.append("t: " + threadName + " log: " + s + " interrupted\n");
282                             }
283                             if (foundMatch) {
284                                 return;
285                             }
286                         }
287                     }
288                 }
289             }
290         }
291         
292         public void notify (int severity, Throwable JavaDoc t) {
293             log (severity, t.getMessage ());
294         }
295         
296         public boolean isNotifiable (int severity) {
297             return prefix != null;
298         }
299         
300         public boolean isLoggable (int severity) {
301             return prefix != null;
302         }
303
304         private static void clear(String JavaDoc n, PrintStream JavaDoc printStream) {
305             ErrManager.log = printStream;
306             ErrManager.messages.setLength(0);
307             ErrManager.messages.append ("Starting test ");
308             ErrManager.messages.append (n);
309             ErrManager.messages.append ('\n');
310             threads.clear();
311         }
312         
313     } // end of ErrManager
314

315     private static final class Switch {
316         private Pattern JavaDoc msg;
317         private String JavaDoc name;
318         
319         public Switch(String JavaDoc n, Pattern JavaDoc m) {
320             this.name = n;
321             this.msg = m;
322         }
323         
324         /** @return true if the thread name of the caller matches this switch
325          */

326         public boolean matchesThread() {
327             String JavaDoc thr = Thread.currentThread().getName();
328             return name.equals(thr);
329         }
330         
331         /** @return true if the message matches the one provided by this switch
332          */

333         public boolean matchesMessage(String JavaDoc logMsg) {
334             return msg.matcher(logMsg).matches();
335         }
336         
337         public String JavaDoc toString() {
338             return "Switch[" + name + "]: " + msg;
339         }
340     }
341 }
342
Popular Tags