KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jass > as > ActivityService


1 /**
2  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3  -
4  - JASS: Java Advanced tranSaction Support
5  -
6  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
7  -
8  - This module was originally developed by
9  -
10  - LSD (Distributed Systems Lab, http://lsd.ls.fi.upm.es/lsd/lsd.htm)
11  - at Universidad Politecnica de Madrid (UPM) as an ObjectWeb Consortium
12  - (http://www.objectweb.org) project.
13  -
14  - This project has been partially funded by the European Commission under
15  - the IST programme of V FP grant IST-2001-37126 and by the Spanish
16  - Ministry of Science & Technology (MCyT) grants TIC2002-10376-E and
17  - TIC2001-1586-C03-02
18  -
19  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
20  - The original code and portions created by LSD are
21  - Copyright (c) 2004 LSD (UPM)
22  - All rights reserved.
23  -
24  - Redistribution and use in source and binary forms, with or without
25  - modification, are permitted provided that the following conditions are met:
26  -
27  - -Redistributions of source code must retain the above copyright notice, this
28  - list of conditions and the following disclaimer.
29  -
30  - -Redistributions in binary form must reproduce the above copyright notice,
31  - this list of conditions and the following disclaimer in the documentation
32  - and/or other materials provided with the distribution.
33  -
34  - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
35  - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36  - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37  - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
38  - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
39  - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
40  - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
41  - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
42  - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
43  - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
44  - POSSIBILITY OF SUCH DAMAGE.
45  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
46  -
47  - Author: Francisco Perez Sorrosal (frperezs)
48  -
49  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
50 */

51
52 package org.objectweb.jass.as;
53
54 import java.util.Collections JavaDoc;
55 import java.util.HashMap JavaDoc;
56 import java.util.Map JavaDoc;
57
58 import javax.activity.ActivityCompletedException JavaDoc;
59 import javax.activity.ActivityCoordinator JavaDoc;
60 import javax.activity.ActivityNotProcessedException JavaDoc;
61 import javax.activity.ActivityPendingException JavaDoc;
62 import javax.activity.ActivityToken JavaDoc;
63 import javax.activity.CompletionStatus JavaDoc;
64 import javax.activity.ContextPendingException JavaDoc;
65 import javax.activity.GlobalId JavaDoc;
66 import javax.activity.InvalidActivityException JavaDoc;
67 import javax.activity.InvalidParentContextException JavaDoc;
68 import javax.activity.InvalidStateException JavaDoc;
69 import javax.activity.NoActivityException JavaDoc;
70 import javax.activity.NoImplementException JavaDoc;
71 import javax.activity.NotOriginatorException JavaDoc;
72 import javax.activity.Outcome JavaDoc;
73 import javax.activity.PropertyGroupUnknownException JavaDoc;
74 import javax.activity.ServiceAlreadyRegisteredException JavaDoc;
75 import javax.activity.ServiceInformation JavaDoc;
76 import javax.activity.ServiceNotRegisteredException JavaDoc;
77 import javax.activity.SignalSetUnknownException JavaDoc;
78 import javax.activity.Status JavaDoc;
79 import javax.activity.SystemException JavaDoc;
80 import javax.activity.TimeoutRangeException JavaDoc;
81 import javax.activity.ActivityManager JavaDoc;
82 import javax.activity.coordination.ServiceManager;
83 import javax.activity.propertygroup.PropertyGroup;
84 import javax.activity.propertygroup.PropertyGroupManager;
85 import javax.naming.Context JavaDoc;
86 import javax.naming.InitialContext JavaDoc;
87 import javax.naming.NamingException JavaDoc;
88 import javax.transaction.Transaction JavaDoc;
89
90 import org.apache.log4j.Logger;
91 import org.jboss.tm.TxManager;
92
93 /**
94  * Implements the access interface to the AS (UserActivity) available to HLSs.
95  * @author fran
96  * Date: Feb 12, 2004
97  * org.objectweb.jass.asUserActivityImpl.java
98  */

99 public class ActivityService implements ActivityManager JavaDoc {
100
101     // Constants --------------------------------------------------------------
102

103     // Default activity timeout (in seconds). Zero, means no timeout.
104
public static int DEFAULT_TIMEOUT = 0;
105     public static String JavaDoc SYNCHRONIZATION_SS_NAME =
106         "org.omg.CosActivity.Syncrhonization";
107     public static String JavaDoc CHILDLIFETIME_SS_NAME =
108         "org.omg.CosActivity.ChildLifetime";
109
110     // Attributes -------------------------------------------------------------
111

112     private static Logger log = Logger.getLogger(ActivityService.class);
113
114     // A refercence to the unique Activity Id Generator
115
private static ActivityIdGenerator activityIdGenerator = null;
116
117     // The ServiceManager asociated with each instance of UserActivity
118
protected ServiceManager sm = null;
119     // Information about the registered ServiceManager
120
private ServiceInformation JavaDoc serviceInformation = null;
121     // TODO : PropertyGroupManagers
122
private HashMap JavaDoc propertyGroupManagers = new HashMap JavaDoc();
123     // A table which contains non-finalized activities
124
// The keys are the Ids of the activities
125
private Map JavaDoc activities = Collections.synchronizedMap(new HashMap JavaDoc());
126     // DefaultTimeout for activities started here
127
private int defaultTimeout = DEFAULT_TIMEOUT;
128
129     // Constructors -----------------------------------------------------------
130

131     /**
132      * Default Constructor. It takes count of the number of service
133      * instances created.
134      */

135     public ActivityService() {
136
137         try {
138             Context JavaDoc ctx = new InitialContext JavaDoc();
139             log.info("Looking for a Transaction Manager...");
140             jbossTm = (TxManager) ctx.lookup("java:/TransactionManager");
141             log.info("TM found !!!");
142             // Remove next comment when the tm will be registered
143
// jbossTm.registerActivityService(this); // TEST Register AS in TM
144
} catch (NamingException JavaDoc e) {
145             e.printStackTrace();
146         }
147
148         instances = instances + 1;
149         log.debug("UserActivity instance number " + instances + " created!!!");
150     }
151
152     // Public -----------------------------------------------------------------
153

154     // UserActivity implementation --------------------------------------------
155

156     /**
157      * Create a new Activity and associate it with the current thread.
158      *
159      * @param timeout - the period (in seconds) within which the Activity
160      * must be completed. If it is not completed within this period then
161      * it is subject to being completed by the Activity service with
162      * the CompletionStatusFail status.
163      * @throws InvalidStateException - Thrown if the parent Activity has
164      * been marked as CompletionStatusFailOnly.
165      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager
166      * has been registered.
167      * @throws TimeoutRangeException - Thrown if timeout is less than -1 or
168      * if it is outside an administratively configured range in the deployed
169      * system.
170      * @throws SystemException
171      */

172     public void begin(int timeout)
173         throws
174             InvalidStateException JavaDoc,
175             ServiceNotRegisteredException JavaDoc,
176             TimeoutRangeException JavaDoc,
177             SystemException JavaDoc {
178
179         ActivityImpl newActivity = null; // The new activity...
180
ActivityIdImpl activityId = null; // ...and its Id
181
// Ancestror of the new created Activity
182
ActivityImpl superior = null;
183
184         boolean child = false; // Identifies the beginnig of a child activity
185

186         if (activityIdGenerator == null)
187             throw new SystemException JavaDoc("ActivityIdGenerator is not set !!!!!");
188         if (sm == null)
189             throw new ServiceNotRegisteredException JavaDoc();
190         if (timeout < -1)
191             throw new TimeoutRangeException JavaDoc();
192
193         ThreadInfo ti = getThreadInfo();
194         ActivityImpl currentActivity = ti.activity;
195
196         // If the currentActivity is not null, then new activity will be a
197
// child and its superior will be the current activity.
198
if (currentActivity != null) {
199             superior = currentActivity;
200             if (superior.getCompletionStatus()
201                 == CompletionStatus.CompletionStatusFailOnly)
202                 throw new InvalidStateException JavaDoc();
203             child = true;
204             disassociateThread(ti);
205             ti.tx = null; // TEST
206
log.info("Starting a CHILD activity of " + superior.getName());
207         } else
208             log.info("Starting a ROOT activity");
209
210         // New Activity Id generation
211
activityId = activityIdGenerator.newActivityId();
212
213         if (timeout == -1)
214             newActivity = new ActivityImpl(this, activityId, superior, 0);
215         else if (timeout == 0)
216             newActivity =
217                 new ActivityImpl(this, activityId, superior, defaultTimeout);
218         else
219             newActivity = new ActivityImpl(this, activityId, superior, timeout);
220
221         // Put the activity in the non-finalized activities HashMap
222
activities.put(activityId.print(), newActivity);
223         // Make active the new activity context
224
associateThread(ti, newActivity);
225
226         if (child) {
227             // Tell the parent that the new activity is a child of the actual
228
superior.addChild(newActivity);
229             // Now the child activity context is the active context on the thread
230
// TODO : Process the ChildLifetimeSS.
231
// TODO : SEE Activity Service Spec. (Pg.31)
232
}
233     }
234
235     /**
236      * Causes the active Activity context to complete with the specified
237      * CompletionStatus. If a CompletionSignalSet is used by the registered
238      * ServiceManager, then it will be driven by the Activity service to obtain
239      * completion signals to distribute to any registered Actions. If the
240      * Activity is nested within a parent, then the parent Activity becomes
241      * associated with the thread on completion of this operation. If there are
242      * any child active or suspended Activities or transactions and the
243      * CompletionStatus is CompletionStatusFail or CompletionStatusFailOnly
244      * then those child Activites will have their CompletionStatuses set to
245      * CompletionStatusFailOnly and any child transaction will be called to
246      * setRollbackOnly.
247      *
248      * @param completionStatus
249      * @return
250      */

251     public Outcome JavaDoc completeWithStatus(int completionStatus)
252         throws
253             NoActivityException JavaDoc,
254             ActivityPendingException JavaDoc,
255             ContextPendingException JavaDoc,
256             ServiceNotRegisteredException JavaDoc,
257             NotOriginatorException JavaDoc,
258             InvalidStateException JavaDoc,
259             ActivityNotProcessedException JavaDoc,
260             SystemException JavaDoc {
261
262         log.debug("completeWithStatus " + Thread.currentThread().getName());
263         Outcome JavaDoc out = null;
264
265         if (sm == null)
266             throw new ServiceNotRegisteredException JavaDoc();
267
268         ThreadInfo ti = getThreadInfo();
269         ActivityImpl currentActivity = ti.activity;
270         if (currentActivity == null)
271             throw new NoActivityException JavaDoc();
272
273         int compStat = getCompletionStatus();
274         ActivityImpl[] childs = currentActivity.getChilds();
275         if ((compStat == CompletionStatus.CompletionStatusSuccess)
276             && (childs != null))
277             throw new ContextPendingException JavaDoc();
278
279         try {
280             // Before completing the activity, we set the completion status
281
currentActivity.setCompletionStatus(completionStatus);
282             out = currentActivity.completeActivity();
283             currentActivity = (ActivityImpl) disassociateThread(ti);
284             if (currentActivity.getParent() != null) {
285                 associateThread(ti, (ActivityImpl) currentActivity.getParent());
286                 ti.tx =
287                     ((ActivityImpl) currentActivity.getParent()).getTransaction();
288                 //TEST
289
} else //TEST
290
ti.tx = null; //TEST
291
} catch (Exception JavaDoc e) {
292             e.printStackTrace();
293         }
294
295         return out;
296     }
297
298     /**
299      * Causes the active Activity context to be completed with its current
300      * CompletionStatus. If a CompletionSignalSet is used by the registered
301      * ServiceManager, then it will be driven by the Activity service to obtain
302      * completion signals to distribute to any registered Actions. If the
303      * Activity is nested within a parent, then the parent Activity becomes
304      * associated with the thread on completion of this operation. If there are
305      * any child active or suspended Activities or transactions and the
306      * CompletionStatus is CompletionStatusFail or CompletionStatusFailOnly
307      * then those child Activites will have their CompletionStatus set to
308      * CompletionStatusFailOnly and any child transaction will be called to
309      * setRollbackOnly.
310      *
311      * @return The Outcome returned is both set by and given meaning by the SignalSet used for
312      * completion. In the absence of a CompletionSignalSet a null Outcome object reference
313      * is returned.
314      */

315     public Outcome JavaDoc complete()
316         throws
317             NoActivityException JavaDoc,
318             ActivityPendingException JavaDoc,
319             ContextPendingException JavaDoc,
320             ServiceNotRegisteredException JavaDoc,
321             NotOriginatorException JavaDoc,
322             ActivityNotProcessedException JavaDoc,
323             SystemException JavaDoc {
324
325         log.debug("complete " + Thread.currentThread().getName());
326         Outcome JavaDoc out = null;
327
328         if (sm == null)
329             throw new ServiceNotRegisteredException JavaDoc();
330
331         ThreadInfo ti = getThreadInfo();
332         ActivityImpl currentActivity = ti.activity;
333         if (currentActivity == null)
334             throw new NoActivityException JavaDoc();
335
336         int compStat = getCompletionStatus();
337         ActivityImpl[] childs = currentActivity.getChilds();
338         if ((compStat == CompletionStatus.CompletionStatusSuccess)
339             && (childs != null)) {
340             
341             log.info("There are alive childs");
342             for(int i = 0;i<childs.length;i++)
343                 log.info("Child " + childs[i].getName());
344             throw new ContextPendingException JavaDoc();
345         }
346         try {
347             out = currentActivity.completeActivity();
348             currentActivity = (ActivityImpl) disassociateThread(ti);
349             if (currentActivity.getParent() != null) {
350                 associateThread(ti, (ActivityImpl) currentActivity.getParent());
351                 // TEST
352
ti.tx =
353                     ((ActivityImpl) currentActivity.getParent()).getTransaction();
354                 //TEST
355
} else // TEST
356
ti.tx = null; //TEST
357
} catch (Exception JavaDoc e) {
358             e.printStackTrace();
359         }
360         return out;
361     }
362
363     /** OK
364      * Sets the CompletionStatus of the active Activity. This method may be
365      * called multiple times before the Activity is completed, and the
366      * CompletionStatus may be changed between CompletionStatusSuccess and
367      * CompletionStatusFail to indicate a point in time value. Once the
368      * CompletionStatus has been set to CompletionStatusFailOnly, it may not
369      * be changed again.
370      *
371      * @param completionStatus - the CompletionStatus value to set.
372      * @throws NoActivityException - Thrown if there is no Activity associated
373      * with the calling thread of execution.
374      * @throws InvalidStateException - Thrown if an attempt is made to update a
375      * CompletionStatus of CompletionStatusFailOnly or if a null or invalid
376      * value is specified by completionStatus.
377      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager has
378      * been registered.
379      * @throws SystemException
380      */

381     public void setCompletionStatus(int completionStatus)
382         throws
383             NoActivityException JavaDoc,
384             InvalidStateException JavaDoc,
385             ServiceNotRegisteredException JavaDoc,
386             SystemException JavaDoc {
387
388         if (sm == null)
389             throw new ServiceNotRegisteredException JavaDoc();
390
391         ThreadInfo ti = getThreadInfo();
392         ActivityImpl currentActivity = ti.activity;
393
394         if (currentActivity == null)
395             throw new NoActivityException JavaDoc();
396         if (currentActivity.getCompletionStatus()
397             == CompletionStatus.CompletionStatusFailOnly)
398             throw new InvalidStateException JavaDoc();
399
400         // All conditions are OK
401
currentActivity.setCompletionStatus(completionStatus);
402     }
403
404     //OK
405
/**
406      * Returns the current value of the CompletionStatus of the active
407      * Activity.
408      *
409      * @return The CompletionStatus of the active Activity.
410      * @throws ServiceNotRegisteredException - Thrown if there is no Activity
411      * associated with the calling thread of execution.
412      * @throws NoActivityException - Thrown if no ServiceManager has been
413      * registered.
414      * @throws SystemException - Thrown if the Activity service encounters an
415      * unexpected error condition.
416      */

417     public int getCompletionStatus()
418         throws ServiceNotRegisteredException JavaDoc, NoActivityException JavaDoc, SystemException JavaDoc {
419
420         if (sm == null)
421             throw new ServiceNotRegisteredException JavaDoc();
422
423         ThreadInfo ti = getThreadInfo();
424         ActivityImpl currentActivity = ti.activity;
425
426         if (currentActivity == null)
427             throw new NoActivityException JavaDoc();
428
429         return currentActivity.getCompletionStatus();
430     }
431
432     /**
433      * Returns the current value of the Status of the active Activity.
434      *
435      * @return The Status of the active Activity.
436      * @throws ServiceNotRegisteredException Thrown if no ServiceManager
437      * has been registered.
438      * @throws SystemException Thrown if the Activity service encounters an
439      * unexpected error condition.
440      */

441     public int getStatus()
442         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
443
444         if (sm == null)
445             throw new ServiceNotRegisteredException JavaDoc();
446
447         ThreadInfo ti = getThreadInfo();
448         ActivityImpl currentActivity = ti.activity;
449
450         if (currentActivity != null)
451             return currentActivity.getStatus();
452         else
453             throw new SystemException JavaDoc();
454     }
455
456     // OK
457
/**
458      * Returns a printable string describing the active Activity.
459      *
460      * @return a printable string describing the active Activity.
461      * If no Activity is associated with the calling thread then null is returned.
462      * @throws ServiceNotRegisteredException Thrown if no ServiceManager has been registered.
463      * @throws SystemException - Thrown if the Activity service encounters an unexpected error condition.
464      */

465     public String JavaDoc getName()
466         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
467
468         if (sm == null)
469             throw new ServiceNotRegisteredException JavaDoc();
470
471         ThreadInfo ti = getThreadInfo();
472         ActivityImpl currentActivity = ti.activity;
473
474         if (currentActivity != null)
475             return currentActivity.getName();
476         else
477             return null;
478     }
479
480     // OK
481
/**
482      * Sets the default timeout, in seconds, after which an Activity may
483      * be automatically completed by the Activity service.
484      *
485      * @param timeout - the default timeout period (in seconds) used by
486      * any future Activities begun with a timeout value of zero. This default
487      * is used for an Activity that is begun with a timeout parameter value
488      * of 0.
489      * A value of -1 indicates no timeout. A value of 0 for the default timeout
490      * indicates that a system-managed value or implementation-specific default
491      * should be used. The timeout is a useful mechanism for protecting against
492      * clients that fail to end an Activity in a timely fashion.
493      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager
494      * has been registered.
495      * @throws TimeoutRangeException - Thrown if timeout is less
496      * than -1 or if it is outside an administratively configured range
497      * in the deployed system.
498      * @throws SystemException - Thrown if the Activity service encounters an
499      * unexpected error condition.
500      */

501     public void setTimeout(int timeout)
502         throws ServiceNotRegisteredException JavaDoc, TimeoutRangeException JavaDoc, SystemException JavaDoc {
503
504         if (timeout < -1)
505             throw new TimeoutRangeException JavaDoc();
506
507         // A default timeout of 0 implies the use of the default timeout value,
508
// represented by DEFAULT_TIMEOUT constant
509
if (timeout == 0)
510             defaultTimeout = DEFAULT_TIMEOUT;
511         else
512             defaultTimeout = timeout;
513     }
514
515     // OK
516
/**
517      * Returns the default timeout value.
518      *
519      * @return The default timeout value, in seconds.
520      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager
521      * has been registered.
522      * @throws SystemException
523      */

524     public int getTimeout()
525         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
526
527         if (sm == null)
528             throw new ServiceNotRegisteredException JavaDoc();
529
530         return defaultTimeout;
531     }
532
533     // OK
534
/**
535      * Returns the GlobalId of the active Activity.
536      *
537      * @return The GlobalId of the active Activity,
538      * or null if there is no Activity associated with the thread.
539      * @throws ServiceNotRegisteredException
540      * @throws SystemException
541      */

542     public GlobalId JavaDoc getGlobalId()
543         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
544
545         if (sm == null)
546             throw new ServiceNotRegisteredException JavaDoc();
547
548         ThreadInfo ti = getThreadInfo();
549         ActivityImpl currentActivity = ti.activity;
550
551         if (currentActivity != null)
552             return currentActivity.getGlobalId();
553         else
554             return null;
555     }
556
557     /**
558      * Causes the SignalSet specified by signalSetName to start producing
559      * signals for all registered Actions. This method is used to distribute
560      * Signals to Actions at times other than during completion. Pre-defined
561      * SignalSets, such as Synchronization, cannot be requested to produce
562      * signals via this method.
563      *
564      * @param signalSetName - the name of the SignalSet that is to produce the
565      * signals.
566      * @return The Outcome returned is both set by and given meaning by the
567      * SignalSet. A null Outcome object reference may be returned if the
568      * SignalSet does not produce an Outcome.
569      * @throws NoActivityException- Thrown if there is no Activity associated
570      * with the calling thread of execution.
571      * @throws SignalSetUnknownException
572      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager has
573      * been registered.
574      * @throws InvalidActivityException Thrown if an attempt is made to use the
575      * Synchronization or ChildLifetime SignalSets, or if the Activity is in
576      * the process of completion.
577      * @throws ActivityNotProcessedException
578      * @throws SystemException
579      */

580     public Outcome JavaDoc broadcast(java.lang.String JavaDoc signalSetName)
581         throws
582             NoActivityException JavaDoc,
583             SignalSetUnknownException JavaDoc,
584             ServiceNotRegisteredException JavaDoc,
585             InvalidActivityException JavaDoc,
586             ActivityNotProcessedException JavaDoc,
587             SystemException JavaDoc {
588
589         if (sm == null)
590             throw new ServiceNotRegisteredException JavaDoc();
591
592         ThreadInfo ti = getThreadInfo();
593         ActivityImpl currentActivity = ti.activity;
594
595         if (currentActivity == null)
596             throw new NoActivityException JavaDoc();
597         if ((signalSetName.equals(SYNCHRONIZATION_SS_NAME))
598             || (signalSetName.equals(SYNCHRONIZATION_SS_NAME))
599             || currentActivity.getStatus() == Status.StatusCompleting)
600             throw new InvalidActivityException JavaDoc();
601
602         return currentActivity.processSignalSet(
603             signalSetName,
604             currentActivity.getStatus());
605     }
606
607     // OK
608
/**
609      * Returns the ActivityCoordinator of the active Activity,
610      * or null if there is no Activity associated with the calling thread.
611      *
612      * @return ActivityCoordinator of the active Activity
613      * @throws ServiceNotRegisteredException
614      * @throws NoImplementException
615      * @throws SystemException
616      */

617     public ActivityCoordinator JavaDoc getCoordinator()
618         throws ServiceNotRegisteredException JavaDoc, NoImplementException JavaDoc, SystemException JavaDoc {
619
620         if (sm == null)
621             throw new ServiceNotRegisteredException JavaDoc();
622
623         ThreadInfo ti = getThreadInfo();
624         ActivityImpl currentActivity = ti.activity;
625
626         if (currentActivity != null)
627             return currentActivity;
628         else
629             return null;
630     }
631
632     // OK
633
/**
634      * Returns the ActivityCoordinator of the parent of the active Activity, or
635      * null if the active Activity is a top-level Activity. In some execution
636      * environments, such as a J2EE client, this method need not be implemented
637      * and calling it may result in a NoImplementationException.
638      *
639      * @return The ActivityCoordinator of the active Activity. If there is no Activity
640      * associated with the calling thread then a null object reference is returned.
641      * @throws ServiceNotRegisteredException - Thrown if no ServiceManager has been registered.
642      * @throws NoImplementException - Thrown if the Activity service does not provide an implementation
643      * of this method in the calling environment, for example if a J2EE client
644      * calls this method.
645      * @throws SystemException
646      */

647     public ActivityCoordinator JavaDoc getParentCoordinator()
648         throws ServiceNotRegisteredException JavaDoc, NoImplementException JavaDoc, SystemException JavaDoc {
649
650         if (sm == null)
651             throw new ServiceNotRegisteredException JavaDoc();
652
653         ThreadInfo ti = getThreadInfo();
654         ActivityImpl currentActivity = ti.activity;
655
656         if ((currentActivity != null) && (currentActivity.getParent() != null))
657             return currentActivity.getParent();
658         else
659             return null;
660     }
661
662     /**
663      * NOT YET IMPLEMENTED
664      */

665     public PropertyGroup getPropertyGroup(java.lang.String JavaDoc name)
666         throws
667             PropertyGroupUnknownException JavaDoc,
668             ServiceNotRegisteredException JavaDoc,
669             NoActivityException JavaDoc,
670             SystemException JavaDoc {
671
672         return null;
673     }
674
675     /**
676      * Registers a ServiceManager for the type of high-level service (HLS) whose activities
677      * are to be demarcated through the target UserActivity instance. The Activity service uses
678      * the properties of the registered ServiceManager to create and operate on Activities specific
679      * to that service. The UserActivity (or specialised ActivityManager) instance requires a
680      * ServiceManager to be registered with it before it may be used to begin new Activities.
681      *
682      * @param service - the ServiceManager for the HLS whose activities are to be demarcated
683      * through the target UserActivity instance.
684      * @throws PropertyGroupUnknownException - Thrown if the ServiceManager cannot obtain a
685      * PropertyGroupManager for one or more of the PropertyGroups it uses.
686      * @throws ServiceAlreadyRegisteredException - Thrown if a ServiceManager has already
687      * been registered with the UserActivity instance.
688      * @throws SystemException
689      */

690     public void registerService(ServiceManager service)
691         throws
692             PropertyGroupUnknownException JavaDoc,
693             ServiceAlreadyRegisteredException JavaDoc,
694             SystemException JavaDoc {
695
696         String JavaDoc[] propertyGroupNames = null;
697
698         if (sm != null)
699             throw new ServiceAlreadyRegisteredException JavaDoc();
700
701         sm = service;
702         serviceInformation = sm.getServiceInformation();
703         propertyGroupNames = sm.getPropertyGroupNames();
704         if (propertyGroupNames != null) {
705             for (int i = 0; i < propertyGroupNames.length; i++)
706                 try {
707                     PropertyGroupManager pgm =
708                         sm.getPropertyGroupManager(propertyGroupNames[i]);
709                     propertyGroupManagers.put(propertyGroupNames[i], pgm);
710                 } catch (PropertyGroupUnknownException JavaDoc e) {
711                     throw new PropertyGroupUnknownException JavaDoc();
712                 }
713         }
714         log.info(
715             "Service Manager "
716                 + serviceInformation.getServiceName()
717                 + " has been registered");
718
719     }
720
721     /**
722      * Returns the registered ServiceManager for this UserActivity instance.
723      *
724      * @return The ServiceManager for this UserActivity instance, or null if none
725      * has been registered.
726      * @throws SystemException
727      */

728     public ServiceManager getService() throws SystemException JavaDoc {
729
730         if (sm != null)
731             return sm;
732         else
733             return null;
734     }
735
736     /**
737      * NOT YET IMPLEMENTED
738      */

739     public ActivityCoordinator JavaDoc recreate(
740         GlobalId JavaDoc activity,
741         GlobalId JavaDoc parent,
742         boolean resume)
743         throws
744             ServiceNotRegisteredException JavaDoc,
745             ActivityCompletedException JavaDoc,
746             java.lang.IllegalArgumentException JavaDoc,
747             SystemException JavaDoc {
748
749         return null;
750     }
751
752     /**
753      * NOT YET IMPLEMENTED
754      */

755     public GlobalId JavaDoc[] recover()
756         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
757
758         return null;
759     }
760
761     /**
762      * NOT YET IMPLEMENTED
763      */

764     public void forget(GlobalId JavaDoc globalId)
765         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
766
767     }
768
769     // ActivityManager implementation ------------------------------
770

771     /**
772      * Suspends the association of the current Activity from the
773      * calling thread of execution along with any child Activities
774      * of the same ContextGroup nested within that Activity.
775      * If the suspended Activity is nested within a parent then the
776      * parent Activity becomes associated with the thread on
777      * completion of this method.
778      * @return An ActivityToken representing the suspended Activity.
779      * This ActivityToken maintains knowledge of the nested
780      * Activities and transactions that were suspended when the
781      * target Activity was suspended as well as any parent Activity
782      * that was established as a result of the suspend operation.
783      * The ActivityToken may be used on a subsequent call to resume
784      * but not to resumeAll or resumeGroup.
785      * If the calling thread is not associated with any Activity
786      * then null is returned.
787      */

788     public ActivityToken JavaDoc suspend()
789         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
790
791         ActivityContext context = null;
792
793         ThreadInfo ti = getThreadInfo();
794         ActivityImpl currentActivity = ti.activity;
795         Transaction JavaDoc currentTx = ti.tx; // TEST
796

797         if (currentActivity != null) {
798             ActivityImpl parent = (ActivityImpl) currentActivity.getParent();
799
800             log.warn(
801                 "SUSPEND: Disassociating activity "
802                     + ti.activity.getName()
803                     + " from thread "
804                     + Thread.currentThread().toString());
805             try {
806
807                 if ((currentTx != null)
808                     && currentTx.equals(jbossTm.getTransaction())) { // TEST
809
jbossTm.suspend();
810                     log.info("TX SUSPENDED");
811                 }
812             } catch (Exception JavaDoc e) {
813                 e.printStackTrace();
814             }
815             disassociateThread(ti);
816
817             if (parent != null) {
818                 log.warn(
819                     "SUSPEND: Associating activity "
820                         + parent.getName()
821                         + " to thread "
822                         + Thread.currentThread().toString());
823                 associateThread(ti, parent);
824                 // TEST It should be in associateThread
825
ti.tx = parent.getTransaction();
826                 if (ti.tx != null) { // TEST
827
try {
828                         jbossTm.resume(ti.tx);
829                         log.info("TX RESUMED");
830                     } catch (Exception JavaDoc e) {
831                         e.printStackTrace();
832                     }
833                 }
834                 context =
835                     new ActivityContext(currentActivity, parent.getGlobalId());
836             } else
837                 context = new ActivityContext(currentActivity, null);
838         }
839
840         return context;
841     }
842
843     /**
844      * Resumes the association of the Activity, and any nested
845      * Activities and transactions, represented by the
846      * ActivityToken with the calling thread of execution.
847      * The ActivityToken represents a hierarchy of one of more
848      * Activities and transactions and must have been obtained by
849      * a prior call to suspend. If there is an Activity
850      * associated with the thread prior to the method invocation
851      * then the re-associated Activity is resumed as a child of
852      * the Activity that is already on the thread. Any such
853      * parent Activity must be the same parent Activity within
854      * which the child Activity was originally begun.
855      * If the specified ActivityToken is null, then no new
856      * associated is made.
857      * @param activityToken - the ActivityToken to resume. The
858      * ActivityToken represents a hierarchy of one of more
859      * Activities and transactions and must have been obtained
860      * by a prior call to suspend.
861      */

862     public void resume(ActivityToken JavaDoc activityToken)
863         throws
864             InvalidActivityException JavaDoc,
865             InvalidParentContextException JavaDoc,
866             ServiceNotRegisteredException JavaDoc,
867             SystemException JavaDoc {
868
869         if (sm == null)
870             throw new ServiceNotRegisteredException JavaDoc();
871         if (activityToken == null)
872             throw new InvalidActivityException JavaDoc();
873
874         ActivityContext context = (ActivityContext) activityToken;
875
876         ThreadInfo ti = getThreadInfo();
877         ActivityImpl currentActivity = ti.activity;
878         
879         if (currentActivity != null) {
880             log.warn("current " + currentActivity.getName());
881             log.warn("parent " + context.getParent().print());
882             if (!currentActivity.getGlobalId().equals(context.getParent()))
883                 throw new InvalidParentContextException JavaDoc();
884
885             log.warn(
886                 "RESUME: Disassociating activity "
887                     + ti.activity.getName()
888                     + " from thread "
889                     + Thread.currentThread().toString());
890             disassociateThread(ti);
891             ti.tx = null; // TEST
892
}
893         log.warn(
894             "RESUME: Associating activity "
895                 + context.getActivity().getName()
896                 + " to thread "
897                 + Thread.currentThread().toString());
898         associateThread(ti, context.getActivity());
899         // TEST. It should be in associateThread
900
ti.tx = context.getActivity().getTransaction();
901         if (ti.tx != null) { // TEST
902
try {
903                 jbossTm.resume(ti.tx);
904                 log.info("TX RESUMED");
905             } catch (Exception JavaDoc e) {
906                 e.printStackTrace();
907             }
908         }
909     }
910
911     /**
912      * Not yet implemented.
913      */

914     public ActivityToken JavaDoc suspendGroup()
915         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
916         return null;
917     }
918
919     /**
920      * Not yet implemented.
921      */

922     public void resumeGroup(ActivityToken JavaDoc activityToken)
923         throws
924             InvalidActivityException JavaDoc,
925             InvalidParentContextException JavaDoc,
926             ServiceNotRegisteredException JavaDoc,
927             SystemException JavaDoc {
928     }
929
930     /**
931      * Not yet implemented.
932      */

933     public ActivityToken JavaDoc suspendAll()
934         throws ServiceNotRegisteredException JavaDoc, SystemException JavaDoc {
935         return null;
936     }
937
938     /**
939      * Not yet implemented.
940      */

941     public void resumeAll(ActivityToken JavaDoc activityToken)
942         throws
943             InvalidActivityException JavaDoc,
944             InvalidParentContextException JavaDoc,
945             ServiceNotRegisteredException JavaDoc,
946             SystemException JavaDoc {
947     }
948
949     /**
950      * Not yet implemented.
951      */

952     public GlobalId JavaDoc hibernate()
953         throws
954             ServiceNotRegisteredException JavaDoc,
955             InvalidActivityException JavaDoc,
956             SystemException JavaDoc {
957         return null;
958     }
959
960     /**
961      * Not yet implemented.
962      */

963     public void reactivate(GlobalId JavaDoc globalId)
964         throws
965             ActivityCompletedException JavaDoc,
966             InvalidParentContextException JavaDoc,
967             ServiceNotRegisteredException JavaDoc,
968             SystemException JavaDoc {
969     }
970
971     // My Public --------------------------------------------------------------
972

973     /**
974      * Sets the Activity Id Generator for all Activity Service instances.
975      *
976      * @param generator - A reference to the unique ActivityIdGenerator
977      */

978     public static void setActivityIdGenerator(ActivityIdGenerator generator) {
979         activityIdGenerator = generator;
980     }
981
982     /**
983      * Return the number of activities in the activities HashMap.
984      *
985      * @return Number of activities currently in the HashMap.
986      */

987     public int getNumberOfActivities() {
988         return activities.size();
989     }
990
991     // My Private -------------------------------------------------------------
992

993     /**
994      * Returns the name of current thread.
995      * @return the current thread name.
996      */

997     private String JavaDoc getThreadName() {
998         return Thread.currentThread().getName();
999     }
1000
1001    private void completeChilds(ActivityImpl currentActivity) {
1002        try {
1003            int compStat = getCompletionStatus();
1004            if ((compStat == CompletionStatus.CompletionStatusFail)
1005                || (compStat == CompletionStatus.CompletionStatusFailOnly)) {
1006                // Complete nested activities with CompletionStatusFailOnly
1007
// if they are active or suspended
1008
ActivityImpl[] childs = currentActivity.getChilds();
1009
1010                for (int i = 0; i < childs.length; i++) {
1011                    if (childs[i].getStatus() == Status.StatusActive)
1012                        childs[i].setCompletionStatus(
1013                            CompletionStatus.CompletionStatusFailOnly);
1014                }
1015            }
1016        } catch (ServiceNotRegisteredException JavaDoc e) {
1017            e.printStackTrace();
1018        } catch (NoActivityException JavaDoc e) {
1019            e.printStackTrace();
1020        } catch (SystemException JavaDoc e) {
1021            e.printStackTrace();
1022        } catch (InvalidStateException JavaDoc e) {
1023            e.printStackTrace();
1024        }
1025    }
1026
1027    // My Protected -----------------------------------------------------------
1028

1029    // Local thread info
1030
protected ThreadLocal JavaDoc threadActivity = new ThreadLocal JavaDoc();
1031
1032    /**
1033     * Obtains the info associated with the current thread
1034     * @return Information associated with the current thread
1035     */

1036    protected ThreadInfo getThreadInfo() {
1037
1038        ThreadInfo ret = (ThreadInfo) threadActivity.get();
1039
1040        if (ret == null) {
1041            ret = new ThreadInfo();
1042            threadActivity.set(ret);
1043        }
1044
1045        return ret;
1046    }
1047
1048    /**
1049     * Provides the association of an activity to a thread.
1050     *
1051     * @param ti - current thread info.
1052     * @param activity - the activity.
1053     */

1054    protected void associateThread(ThreadInfo ti, ActivityImpl activity) {
1055
1056        ti.activity = activity;
1057        activity.associateCurrentThread();
1058    }
1059
1060    /**
1061     * Provides the disassociation of an activity from a thread.
1062     *
1063     * @param ti - current thread info.
1064     * @return - the activity currently associated with the thread
1065     */

1066    protected ActivityCoordinator JavaDoc disassociateThread(ThreadInfo ti) {
1067
1068        ActivityImpl current = ti.activity;
1069        ti.activity = null;
1070        current.disassociateCurrentThread();
1071
1072        return current;
1073    }
1074
1075    /* PARA WSCAF */
1076    public void dissasociateThread() {
1077        ThreadInfo ti = getThreadInfo();
1078        ActivityImpl currentActivity = ti.activity;
1079        if (currentActivity != null) {
1080            currentActivity.disassociateCurrentThread();
1081            ti.activity = null;
1082            ti.tx = null; // TEST
1083
}
1084    }
1085
1086    /**
1087     * Removes the specified activity from the activities HashMap.
1088     *
1089     * @param activity - the activity to remove.
1090     */

1091    protected void releaseActivityImpl(ActivityImpl activity) {
1092
1093        try {
1094            activities.remove(activity.getGlobalId().print());
1095        } catch (SystemException JavaDoc e) {
1096            e.printStackTrace();
1097        }
1098        log.debug("Activities in this instance " + activities.size());
1099    }
1100
1101    // Inner classes --------------------------------------------------------------
1102

1103    /**
1104     * The thread-associated activity.
1105     */

1106    static class ThreadInfo {
1107        ActivityImpl activity = null;
1108        // TEST If the activity has a transacion associated
1109
Transaction JavaDoc tx = null;
1110    }
1111
1112    // Debug ------------------------------------------------------------------
1113

1114    /**
1115     * For JBOSS MBeans
1116     */

1117    private static int instances = 0;
1118
1119    public static int getInstances() {
1120        return instances;
1121    }
1122
1123    /**
1124     * For TM advices (Tx begin, commit, rollback...)
1125     */

1126    // JBoss Tx Manager
1127
private static TxManager jbossTm = null;
1128
1129    public void txBegin(Transaction JavaDoc tx) throws SystemException JavaDoc {
1130
1131        ThreadInfo ti = getThreadInfo();
1132        ActivityImpl currentActivity = ti.activity;
1133        Transaction JavaDoc currentTx = ti.tx;
1134
1135        log.info(getThreadName() + " " + tx + " has begin in JBoss TM");
1136
1137        if (currentActivity != null) {
1138            if (currentTx != null) {
1139                log.warn("A transaction exists!!! -> " + currentTx.toString());
1140            } else {
1141                ti.tx = tx;
1142                currentActivity.setTransaction(tx);
1143                log.info("Associated with " + currentActivity.getName());
1144            }
1145        }
1146    }
1147
1148    public void txCommit(Transaction JavaDoc tx) throws SystemException JavaDoc {
1149
1150        ThreadInfo ti = getThreadInfo();
1151        ActivityImpl currentActivity = ti.activity;
1152        Transaction JavaDoc currentTx = ti.tx;
1153
1154        log.info(getThreadName() + " " + tx + " has committed in JBoss TM");
1155
1156        if (currentActivity != null) {
1157            if (currentTx != null) {
1158                ti.tx = null;
1159                currentActivity.setTransaction(null);
1160                log.info("Disassociated from " + currentActivity.getName());
1161            } else
1162                log.warn("There is no transaction in " + currentActivity.getName());
1163        }
1164
1165    }
1166
1167    public void txRollback(Transaction JavaDoc tx) throws SystemException JavaDoc {
1168
1169        ThreadInfo ti = getThreadInfo();
1170        ActivityImpl currentActivity = ti.activity;
1171        Transaction JavaDoc currentTx = ti.tx;
1172
1173        log.info(getThreadName() + " " + tx + " has rolled-back in JBoss TM");
1174
1175        if (currentActivity != null) {
1176            if (currentTx != null) {
1177                ti.tx = null;
1178                currentActivity.setTransaction(null);
1179                log.info("Disassociated from " + currentActivity.getName());
1180            } else
1181                log.warn("There is no transaction in " + currentActivity.getName());
1182        }
1183
1184    }
1185
1186    // End Debug --------------------------------------------------------------
1187

1188}
Popular Tags