KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > coach > tracing > service > ThreadContext


1 /***************************************************************************/
2 /* COACH: Component Based Open Source Architecture for */
3 /* Distributed Telecom Applications */
4 /* See: http://www.objectweb.org/ */
5 /* */
6 /* Copyright (C) 2003 Lucent Technologies Nederland BV */
7 /* Bell Labs Advanced Technologies - EMEA */
8 /* */
9 /* Initial developer(s): Harold Batteram */
10 /* */
11 /* This library is free software; you can redistribute it and/or */
12 /* modify it under the terms of the GNU Lesser General Public */
13 /* License as published by the Free Software Foundation; either */
14 /* version 2.1 of the License, or (at your option) any later version. */
15 /* */
16 /* This library is distributed in the hope that it will be useful, */
17 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
18 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
19 /* Lesser General Public License for more details. */
20 /* */
21 /* You should have received a copy of the GNU Lesser General Public */
22 /* License along with this library; if not, write to the Free Software */
23 /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
24 /***************************************************************************/
25 package org.coach.tracing.service;
26
27 import org.omg.CORBA.Any JavaDoc;
28 import java.util.*;
29 import org.coach.tracing.api.*;
30
31 /**
32  * This class is used to maintain context information associated with an execution thread and the
33  * current active request.
34  */

35 public class ThreadContext
36 {
37     private static int frameCounter;
38     private String JavaDoc trailLabel = "";
39     private String JavaDoc threadId = "";
40     private String JavaDoc trailId = "";
41     private String JavaDoc senderThreadId = "";
42     private Stack requestStack;
43     private RequestContext requestContext;
44     private static int eventCounter = -1; // absolute event counter per process or virtual machine
45
private static String JavaDoc vmId;
46     private static HashMap contextMap = new HashMap();
47     private static Hashtable frameRequestContext = new Hashtable();
48     
49     static
50     {
51         try
52         {
53             // create an unique application id
54
java.io.File JavaDoc tmp = java.io.File.createTempFile("coach", "");
55             tmp.deleteOnExit();
56             vmId = java.net.InetAddress.getLocalHost().getHostName().replace('.', '_') + "_" + tmp.getName().substring(5);
57         }
58         catch (Exception JavaDoc e)
59         {
60             e.printStackTrace();
61         }
62     }
63
64     /**
65      * Private contructor.
66      * New instances are created as needed when getCurrentThreadContext is called.
67      */

68     private ThreadContext()
69     {
70         threadId = vmId + "_" + Thread.currentThread().getName();
71         trailId = threadId; // default
72
//creation of this objects associates the current thread with the object
73
requestStack = new Stack();
74         requestContext = new RequestContext();
75     }
76
77     /**
78      * Returns the ThreadContext for the current thread.
79      */

80     public static synchronized ThreadContext getCurrentThreadContext()
81     {
82         ThreadContext tc = null;
83         if (Thread.currentThread().getName().startsWith("AWT"))
84         {
85             // Associate the thread context with the current active frame rather then the
86
// thread id because Java uses a single thread for all GUI activities.
87
java.awt.Frame JavaDoc f = getCurrentFrame();
88             if (f != null)
89             {
90                 tc = (ThreadContext)(contextMap.get(f));
91             }
92         }
93         if (tc == null)
94         {
95             tc = (ThreadContext)(contextMap.get(vmId + "_" + Thread.currentThread().getName()));
96         }
97         if (tc == null)
98         {
99             tc = new ThreadContext();
100             contextMap.put(tc.getThreadId(), tc);
101         }
102         return tc;
103     }
104
105     /**
106      * Returns the ThreadContext data structure for the given thread id.
107      */

108     public static synchronized ThreadContext getThreadContext(String JavaDoc id)
109     {
110         ThreadContext tc = null;
111         if (id.indexOf("AWT-EventQueue") >= 0)
112         {
113             java.awt.Frame JavaDoc f = getCurrentFrame();
114             if (f != null)
115             {
116                 tc = (ThreadContext)(contextMap.get(f));
117 //System.err.println("*** getThreadContext: " + id + "\nComponent: " + tc.getComponentName() + "\nThreadId: " + tc.getThreadId());
118
}
119         }
120         if (tc == null)
121         {
122             tc = (ThreadContext)(contextMap.get(id));
123         }
124         if (tc == null)
125         {
126             tc = new ThreadContext();
127             contextMap.put(tc.getThreadId(), tc);
128         }
129         return tc;
130     }
131
132     private void setThreadId(String JavaDoc threadId)
133     {
134         this.threadId = threadId;
135     }
136
137     /**
138      * Returns the trail label for the current thread.
139      *
140      * @return The trail label for the current thread.
141      */

142     public String JavaDoc getTrailLabel()
143     {
144         return trailLabel;
145     }
146
147     /**
148      * Assigns a trail label to the current thread.
149      *
150      * @param label The trail label for the current thread.
151      */

152     public void setTrailLabel(String JavaDoc label)
153     {
154         trailLabel = label;
155     }
156
157     /**
158      * Returns the current active operation for the current thread.
159      *
160      * @return The current active operation for the current thread.
161      */

162     public String JavaDoc getCurrentOperation()
163     {
164         return requestContext.getCurrentOperation();
165     }
166
167     /**
168      * Assigns the current active operation to the current thread.
169      *
170      * @param opr The opertion name.
171      */

172     public void setCurrentOperation(String JavaDoc opr)
173     {
174         requestContext.setCurrentOperation(opr);
175     }
176         
177     /**
178      * Returns the current active message id for the current thread.
179      *
180      * @return The current active message id for the current thread.
181      */

182     public String JavaDoc getMessageId()
183     {
184         return requestContext.getMessageId();
185     }
186
187     /**
188      * Assigns the current active message id to the current thread.
189      *
190      * @param id The message id.
191      */

192     public void setMessageId(String JavaDoc id)
193     {
194         requestContext.setMessageId(id);
195     }
196
197     /**
198      * Returns the current active interface id for the current thread.
199      *
200      * @return The current active interface id for the current thread.
201      */

202     public String JavaDoc getCurrentInterfaceId()
203     {
204         return requestContext.getCurrentInterfaceId();
205     }
206
207     /**
208      * Assigns the current active interface id to the current thread.
209      *
210      * @param id The interface id.
211      */

212     public void setCurrentInterfaceId(String JavaDoc id)
213     {
214         requestContext.setCurrentInterfaceId(id);
215     }
216             
217     /**
218      * Returns the id for the current thread.
219      *
220      * @return The id for the current thread.
221      */

222     public String JavaDoc getThreadId()
223     {
224         return threadId;
225     }
226
227     /**
228      * Returns the trail id for the current thread.
229      *
230      * @return The trail id for the current thread.
231      */

232     public String JavaDoc getTrailId()
233     {
234         return trailId;
235     }
236         
237     /**
238      * Assigns the trail id to the current thread.
239      *
240      * @param id The trail id.
241      */

242     public void setTrailId(String JavaDoc id)
243     {
244         trailId = id;
245     }
246
247     /**
248      * Returns the total number of events in the process.
249      *
250      * @return The total number of events in the process.
251      */

252     public static synchronized int getEventCounter()
253     {
254         return eventCounter;
255     }
256
257     /**
258      * Increments and returns the total number of events in the process.
259      *
260      * @return The total number of events in the process plus one.
261      */

262     public static synchronized int incrementEventCounter()
263     {
264         return ++eventCounter;
265     }
266         
267     /**
268      * Returns the process id.
269      *
270      * @return The process id.
271      */

272     public String JavaDoc getVmId()
273     {
274         return vmId;
275     }
276
277     /**
278      * Returns the component name for the current active request.
279      *
280      * @return The name of the current component.
281      */

282     public String JavaDoc getComponentName()
283     {
284         return requestContext.getComponentName();
285     }
286     
287     /**
288      * Assigns the component name to the current request context.
289      *
290      * @param name The component name.
291      */

292     public void setComponentName(String JavaDoc name)
293     {
294         requestContext.setComponentName(name);
295     }
296
297     /**
298      * Returns the component type name for the current active request.
299      *
300      * @return The type name of the current component.
301      */

302     public String JavaDoc getComponentType()
303     {
304         return requestContext.getComponentType();
305     }
306
307     /**
308      * Assigns the component type name to the current request context.
309      *
310      * @param type The component type name.
311      */

312     public void setComponentType(String JavaDoc type)
313     {
314         requestContext.setComponentType(type);
315     }
316     
317     /**
318      * Returns the container name for the current active request.
319      *
320      * @return The name of the current container.
321      */

322     public static String JavaDoc getContainerName()
323     {
324         return RequestContext.getContainerName();
325     }
326
327     /**
328      * Assigns the container name to the current request context.
329      *
330      * @param name The container name.
331      */

332     public static void setContainerName(String JavaDoc name)
333     {
334         RequestContext.setContainerName(name);
335     }
336         
337     /**
338      * Returns the container type name for the current active request.
339      *
340      * @return The type name of the current container.
341      */

342     public static String JavaDoc getContainerType()
343     {
344         return RequestContext.getContainerType();
345     }
346
347     /**
348      * Assigns the container type name to the current request context.
349      *
350      * @param type The container type name.
351      */

352     public static void setContainerType(String JavaDoc type)
353     {
354         RequestContext.setContainerType(type);
355     }
356
357     /**
358      * Returns the object instance name for the current active request.
359      *
360      * @return The name of the current object instance.
361      */

362     public String JavaDoc getObjectInstanceId()
363     {
364         return requestContext.getObjectInstanceId();
365     }
366         
367     /**
368      * Assigns the object instance id to the current request context.
369      *
370      * @param id The object instance id.
371      */

372     public void setObjectInstanceId(String JavaDoc id)
373     {
374         requestContext.setObjectInstanceId(id);
375     }
376
377     /**
378      * Returns the object repository id for the current active request.
379      *
380      * @return The id of the current CORBA object.
381      */

382     public String JavaDoc getObjectRepositoryId()
383     {
384         return requestContext.getObjectRepositoryId();
385     }
386     
387     /**
388      * Assigns the object repository id to the current request context.
389      *
390      * @param id The object repository id.
391      */

392     public void setObjectRepositoryId(String JavaDoc id)
393     {
394         requestContext.setObjectRepositoryId(id);
395     }
396               
397     /**
398      * Pushes the current request context on a stack.
399      * This should be called just after an outgoing invocation for synchronous (two way) operations.
400      * The popRequestContext method should be called just before the return.
401      */

402     public void pushRequestContext()
403     {
404         requestStack.push(requestContext);
405         // clone the current request context to inherit component name, type etc.
406
requestContext = (RequestContext)requestContext.clone();
407     }
408     
409     /**
410      * Restores the request context from the top of the stack.
411      */

412     public void popRequestContext()
413     {
414         try
415         {
416             requestContext = (RequestContext)requestStack.pop();
417         }
418         catch (Exception JavaDoc e)
419         {
420         }
421     }
422
423     public void print()
424     {
425         System.err.println("*** ThreadContext ***");
426         System.err.println("trail id: " + getTrailId());
427         System.err.println("message id: " + getMessageId());
428         System.err.println("thread id: " + getThreadId());
429         System.err.println("process id: " + getVmId());
430         System.err.println("container name: " + getContainerName());
431         System.err.println("container type: " + getContainerType());
432         System.err.println("component name: " + getComponentName());
433         System.err.println("component type: " + getComponentType());
434         System.err.println("object instance id: " + getObjectInstanceId());
435         System.err.println("object repository id: " + getObjectRepositoryId());
436         System.err.println("operation: " + getCurrentOperation());
437         System.err.println("interface id: " + getCurrentInterfaceId());
438         System.err.println("event counter: " + getEventCounter());
439         System.err.println("request stack size: " + requestStack.size());
440     }
441
442     private RequestContext getRequestContext()
443     {
444           return requestContext;
445     }
446     
447     private void setRequestContext(RequestContext ctx)
448     {
449         requestContext = (RequestContext)ctx.clone();
450     }
451
452     /**
453      * Associate a component context with a frame object.
454      * First the thread context for the frame object is found, or created if it does not exist.
455      * Then the component context is set in the thread context.
456      *
457      * @param frame The frame object reference to associate with the component context.
458      */

459     public static void setFrameThreadContext(java.awt.Frame JavaDoc frame)
460     {
461         ThreadContext ftc = (ThreadContext)(contextMap.get(frame));
462         if (ftc == null)
463         {
464             // create a new thread context for this frame
465
ftc = new ThreadContext();
466             ftc.setThreadId(ftc.getThreadId() + "_GuiFrame_" + frameCounter++);
467             // set a unique trail id per frame
468
ftc.setTrailId(ftc.getThreadId());
469         }
470         
471         if (Thread.currentThread().getName().startsWith("AWT"))
472         {
473             // This frame is created from another AWT thread
474
// find the parent frame and obtain its context
475
java.awt.Frame JavaDoc parent = getCurrentFrame();
476             if (parent != null)
477             {
478                 ThreadContext parentFrameContext = (ThreadContext)(contextMap.get(parent));
479                 ftc.setRequestContext(parentFrameContext.getRequestContext());
480             }
481         }
482         else
483         {
484             // The frame context inherits the request context from the current thread
485
ftc.setRequestContext(getCurrentThreadContext().getRequestContext());
486         }
487         contextMap.put(frame, ftc);
488 //System.err.println("*** setFrameThreadContext:\nComponent: " + ftc.getComponentName() + "\nThreadId: " + ftc.getThreadId());
489

490     }
491
492     /**
493      * This method searches through the event source chain starting with the most current awt event until the parent frame is
494      * found.
495      */

496     private static java.awt.Frame JavaDoc getCurrentFrame()
497     {
498         java.awt.AWTEvent JavaDoc awtEvent = java.awt.EventQueue.getCurrentEvent();
499         if (awtEvent != null)
500         {
501             Object JavaDoc evtSrc = awtEvent.getSource();
502             while (evtSrc instanceof java.awt.Component JavaDoc)
503             {
504                 if (evtSrc instanceof java.awt.Frame JavaDoc)
505                 {
506                     // find the associated context
507
return (java.awt.Frame JavaDoc)evtSrc;
508                 }
509                 evtSrc = ((java.awt.Component JavaDoc)evtSrc).getParent();
510             }
511         }
512         return null;
513     }
514
515     /**
516      * Returns IDL struct PropagationContext which is used to pass
517      * information between CORBA calls.
518      */

519     public synchronized PropagationContext getPropagationContext()
520     {
521         PropagationContext propagationContext = new PropagationContext();
522         propagationContext.trail_label = getTrailLabel();
523         propagationContext.trail_id = getTrailId();
524         propagationContext.message_id = getMessageId();
525         return propagationContext;
526     }
527
528     /**
529      * The propagation context is passed through the iiop request.
530      */

531     public synchronized void setPropagationContext(PropagationContext propagationContext)
532     {
533         setTrailLabel(propagationContext.trail_label);
534         setTrailId(propagationContext.trail_id);
535         setMessageId(propagationContext.message_id);
536     }
537
538     /**
539      * The ORB request processor typicaly uses a thread pool from which worker threads are assigned
540      * to handle a request. When the request is completed, the current thread context must be
541      * cleared.
542      */

543     public synchronized void clearContext()
544     {
545         if (requestStack.size() == 0)
546         {
547             setTrailLabel("");
548             setTrailId("");
549             setMessageId("");
550             requestContext.clear();
551             requestStack.clear();
552         }
553     }
554
555     
556     /**
557      * The RequestContext class contains all variables associated with a request.
558      * When a new thread is spawn, the component name and type are inherited from the parent thread.
559      * Therefore, this class extends InheritableThreadLocal and overwrites the childValue method.
560      */

561     static class RequestContext extends InheritableThreadLocal JavaDoc implements Cloneable JavaDoc
562     {
563         private static String JavaDoc node_name = "";
564         private static String JavaDoc cnt_name = "";
565         private static String JavaDoc cnt_type = "";
566         // The componentId is inherited from the parent thread when a new child thread is started
567
private ComponentId componentId;
568         private String JavaDoc object_instance_id;
569         private String JavaDoc object_repository_id;
570         private String JavaDoc message_id = "";
571         private String JavaDoc currentInterfaceId = "";
572         private String JavaDoc currentOperation = "";
573         
574         public RequestContext()
575         {
576             // Use the ComponentId associated with the current thread if there is one.
577
componentId = (ComponentId)get();
578             if (componentId == null)
579             {
580                 // This thread does not have a ComponentId yet, create a new one.
581
componentId = new ComponentId("", "");
582                 set(componentId);
583             }
584         }
585     
586         public RequestContext(String JavaDoc name, String JavaDoc type)
587         {
588             componentId = new ComponentId(name, type);
589             // Set the componentId as thread local data so that it can be
590
// propagated to child threads.
591
set(componentId);
592         }
593
594         public void setComponentName(String JavaDoc name)
595         {
596             componentId.name = name;
597         }
598         
599         public void setComponentType(String JavaDoc type)
600         {
601             componentId.type = type;
602         }
603         
604         public String JavaDoc getCurrentInterfaceId()
605         {
606             return currentInterfaceId;
607         }
608     
609         public void setCurrentInterfaceId(String JavaDoc id)
610         {
611             currentInterfaceId = id;
612         }
613
614         public String JavaDoc getCurrentOperation()
615         {
616             return currentOperation;
617         }
618     
619         public void setCurrentOperation(String JavaDoc opr)
620         {
621             currentOperation = opr;
622         }
623             
624         public String JavaDoc getComponentName()
625         {
626             return componentId.name;
627         }
628     
629         public String JavaDoc getComponentType()
630         {
631             return componentId.type;
632         }
633     
634         public static String JavaDoc getContainerName()
635         {
636             return cnt_name;
637         }
638     
639         public static String JavaDoc getContainerType()
640         {
641             return cnt_type;
642         }
643
644         public void setObjectInstanceId(String JavaDoc instance_id)
645         {
646             object_instance_id = instance_id;
647         }
648         
649         public void setObjectRepositoryId(String JavaDoc repository_id)
650         {
651             object_repository_id = repository_id;
652         }
653         
654         public String JavaDoc getObjectInstanceId()
655         {
656             return object_instance_id;
657         }
658         
659         public String JavaDoc getObjectRepositoryId()
660         {
661             return object_repository_id;
662         }
663             
664         public static void setContainerName(String JavaDoc name)
665         {
666             cnt_name = name;
667         }
668
669         public static void setContainerType(String JavaDoc type)
670         {
671             cnt_type = type;
672         }
673         
674         public void setMessageId(String JavaDoc id)
675         {
676             message_id = id;
677         }
678
679         public String JavaDoc getMessageId()
680         {
681             return message_id;
682         }
683         
684         public void clear()
685         {
686             componentId.name = "";
687             componentId.type = "";
688             object_instance_id = "";
689             object_repository_id = "";
690             message_id = "";
691         }
692         
693         public Object JavaDoc clone()
694         {
695             RequestContext r = new RequestContext(getComponentName(), getComponentType());
696             r.object_instance_id = object_instance_id;
697             r.object_repository_id = object_repository_id;
698             r.currentInterfaceId = currentInterfaceId;
699             r.message_id = message_id;
700             return r;
701         }
702         
703         /**
704          * Overloaded member from InheritableThreadLocal to propagate parent data to
705          * the child thread. In our case, only the componentId is inherited because all other fields
706          * are set when an invocation is done.
707          */

708         protected Object JavaDoc childValue(Object JavaDoc parentValue)
709         {
710             return ((ComponentId)parentValue).clone();
711         }
712         
713         class ComponentId implements Cloneable JavaDoc {
714             public String JavaDoc name;
715             public String JavaDoc type;
716             
717             public ComponentId(String JavaDoc name, String JavaDoc type)
718             {
719                 this.name = name;
720                 this.type = type;
721             }
722             
723             public Object JavaDoc clone()
724             {
725                 return new ComponentId(name, type);
726             }
727         }
728     }
729 }
Popular Tags