KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > 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.netbeans.core;
21 import java.beans.PropertyChangeEvent JavaDoc;
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.io.StringWriter JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36 import javax.swing.event.ChangeEvent JavaDoc;
37 import junit.framework.AssertionFailedError;
38 import junit.framework.TestResult;
39 import org.netbeans.junit.NbTestCase;
40 import org.openide.ErrorManager;
41 import org.openide.util.Enumerations;
42 import org.openide.util.Lookup;
43 import org.openide.util.lookup.AbstractLookup;
44 import org.openide.util.lookup.InstanceContent;
45 import org.openide.util.lookup.Lookups;
46 import org.openide.util.lookup.ProxyLookup;
47
48
49 /** Basic skeleton for logging test case in core.
50  *
51  * @author Jaroslav Tulach
52  */

53 public class LoggingTestCaseHid extends NbTestCase {
54     static {
55         org.netbeans.core.startup.MainLookup.register(new ErrManager());
56     }
57     
58     private HashSet JavaDoc unregister = new HashSet JavaDoc();
59     
60     protected LoggingTestCaseHid (String JavaDoc name) {
61         super (name);
62     }
63     
64     public void run(TestResult result) {
65         Lookup l = Lookup.getDefault();
66         
67         assertEquals("We can run only with our Lookup", org.netbeans.core.startup.MainLookup.class, l.getClass());
68         
69         super.run(result);
70         
71         for (Iterator JavaDoc it = unregister.iterator(); it.hasNext();) {
72             Object JavaDoc elem = it.next();
73
74             org.netbeans.core.startup.MainLookup.unregister(elem);
75         }
76     }
77
78     /** If execution fails we wrap the exception with
79      * new log message.
80      */

81     protected void runTest () throws Throwable JavaDoc {
82         
83         assertNotNull ("ErrManager has to be in lookup", Lookup.getDefault().lookup(ErrManager.class));
84         
85         ErrManager.clear(getName(), getLog());
86         
87         try {
88             super.runTest ();
89         } catch (AssertionFailedError ex) {
90             ErrManager.messages.append("\nGot exception: " + ex.getMessage());
91             Thread.sleep(1000);
92             AssertionFailedError ne = new AssertionFailedError (ex.getMessage () + " Log:\n" + ErrManager.messages);
93             ne.setStackTrace (ex.getStackTrace ());
94             throw ne;
95         } catch (IOException JavaDoc iex) {//#66208
96
ErrManager.messages.append("\nGot exception: " + iex.getMessage());
97             Thread.sleep(1000);
98             IOException JavaDoc ne = new IOException JavaDoc (iex.getMessage () + " Log:\n" + ErrManager.messages);
99             ne.setStackTrace (iex.getStackTrace ());
100             throw ne;
101         }
102     }
103     
104     /** Allows subclasses to register content for the lookup. Can be used in
105      * setUp and test methods, after that the content is cleared.
106      */

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

286     private static final class Switch {
287         private Pattern JavaDoc msg;
288         private String JavaDoc name;
289         
290         public Switch(String JavaDoc n, Pattern JavaDoc m) {
291             this.name = n;
292             this.msg = m;
293         }
294         
295         /** @return true if the thread name of the caller matches this switch
296          */

297         public boolean matchesThread() {
298             String JavaDoc thr = Thread.currentThread().getName();
299             return name.equals(thr);
300         }
301         
302         /** @return true if the message matches the one provided by this switch
303          */

304         public boolean matchesMessage(String JavaDoc logMsg) {
305             return msg.matcher(logMsg).matches();
306         }
307         
308         public String JavaDoc toString() {
309             return "Switch[" + name + "]: " + msg;
310         }
311     }
312 }
313
Popular Tags