KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ThreadAgent


1 /*
2 * MobiliTools: an implementation of the Object Management Group's
3 * Mobile Agent Facility specification.
4 * Copyright (C) 2003 France Telecom R&D
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 * MobiliTools $Name: $
21 *
22 * Contact: bruno.dillenseger@francetelecom.com
23 *
24 * Authors: Bruno Dillenseger
25 */

26
27
28 import org.objectweb.mobilitools.smi.api.Agency;
29 import org.objectweb.mobilitools.smi.api.*;
30 import org.objectweb.mobilitools.smi.goodies.RegionManager;
31
32
33 /**
34  * MobiliTools $Name: $, $Id: ThreadAgent.java,v 1.1.1.1 2003/03/28 14:47:58 dillense Exp $
35  * <P>
36  * This example class shows a straightforward implementation of a thread-based agent activity.
37  * The agent activity consists in continuously moving from agency to agency in its region.
38  * The agent takes an optional single integer argument, interpreted as a delay in ms (no argument means no delay).
39  * The easiest way to use this example is to use GUI-enabled agencies.
40  * <BR>NB : THIS EXAMPLE REQUIRES THE MAFFINDER TO BE RUNNING BEFORE LAUNCHING AGENCIES AND AGENTS.
41  * <P>
42  * At creation, the agent gets the latest list of agencies.
43  * While this list contains only one agency (it cannot be empty!), the agent loops on updating the list
44  * and waiting for the specified delay. As soon as the list contains at least two agencies,
45  * the agent begins to move, waiting for the specified delay between two consecutive moves.
46  * <UL>
47  * A move may fail for two reasons:
48  * <LI>If the target agency no longer exists or it is currently closing, the agent gets the latest list of agencies.
49  * <LI>If the agent's current agency is closing, the move is locally rejected and the agent terminates.
50  * </UL>
51  * If the update of agency list fails, the agent suspends itself.
52  */

53 public class ThreadAgent implements MobileObject, Runnable JavaDoc
54 {
55     /** agent's name */
56     protected Name my_name;
57     /** current host agency */
58     protected transient Agency my_agency;
59     /** latest list of agencies in current region */
60     protected volatile Location[] itinerary;
61     /** delay in ms between consecutive moves or agency list updates */
62     protected int pause = 0;
63     /** index in list of agencies for next move */
64     protected int step;
65     /** true if the agent is dead */
66     protected boolean dead = false;
67     /** true if the agent is suspended */
68     protected boolean suspended = false;
69
70
71     public ThreadAgent()
72     {
73     }
74
75
76     /**
77      * Update the list of agencies and set the itinerary index to zero.
78      * Suspend the agent if the list cannot be updated.
79      */

80     protected synchronized void resetItinerary()
81     {
82         try
83         {
84             itinerary = (new RegionManager(my_agency.getORB())).listAgencies(my_agency.getRegion(), null);
85             step = 0;
86         }
87         catch (BadOperation ex)
88         {
89             System.out.println(my_name + " could not update itinerary - suspending activity");
90             try
91             {
92                 my_agency.suspendLocalAgent(this);
93             }
94             catch (BadOperation ex2)
95             {
96                 System.err.println("Warning: could not suspend agent " + my_name + ":\n" + ex2);
97             }
98         }
99     }
100
101
102     /**
103      * Agent's thread creation.
104      */

105     protected void runActivity()
106     {
107         (new Thread JavaDoc(this, my_name.toString())).start();
108     }
109
110
111     ////////////////////////
112
// interface Runnable //
113
////////////////////////
114

115
116     /**
117      * Agent activity: wait for a while, then move to next agency in itinerary
118      * or update itinerary if it contains a single agency.
119     */

120     public void run()
121     {
122         try
123         {
124             Thread.sleep(pause);
125         }
126         catch (InterruptedException JavaDoc e)
127         {
128             System.err.println("Warning: interrupted sleep for " + my_name);
129         }
130         synchronized (this)
131         {
132             if (! (dead || suspended))
133             {
134                 if (itinerary.length == 1)
135                 {
136                     resetItinerary();
137                     runActivity();
138                 }
139                 else
140                 {
141                     if (step == itinerary.length)
142                     {
143                         step = 0;
144                     }
145                     try
146                     {
147                         my_agency.moveLocalAgent(this, itinerary[step++], "a_place");
148                     }
149                     catch (BadOperation e)
150                     {
151                         System.err.println(my_name + ": " + e.getMessage());
152                         resetItinerary();
153                         runActivity();
154                     }
155                 }
156             }
157         }
158     }
159
160
161     ////////////////////////////
162
// interface MobileObject //
163
////////////////////////////
164

165
166     /**
167      * Initialize the agent and create a thread to run the agent's autonomous activity
168      * @param arg if a non-empty String[], should hold a delay in ms as a single value;
169      * this delay is applied between two consecutive moves or itinerary updates.
170      * Otherwise, this delay is zero.
171      */

172     public void afterBirth(AgentSystem agency, AgentInfo entry, Object JavaDoc arg)
173         throws BadOperation
174     {
175         my_agency = (Agency)agency;
176         my_name = entry.getName();
177         if (arg instanceof String JavaDoc[])
178         {
179             String JavaDoc[] argStr = (String JavaDoc[])arg;
180             if (argStr.length != 0)
181             {
182                 try
183                 {
184                     pause = Integer.parseInt(argStr[0]);
185                 }
186                 catch (NumberFormatException JavaDoc e)
187                 {
188                     throw new BadOperation(BadOperation.REJECTED, "argument should be an String-formated integer", e);
189                 }
190             }
191         }
192         resetItinerary();
193         runActivity();
194     }
195
196
197     /**
198      * Make the agent's thread stop as soon as possible.
199      */

200     public synchronized void beforeSuspend()
201     {
202         System.out.println(my_name + " is suspended");
203         suspended = true;
204     }
205
206
207     /**
208      * Update the itinerary in current agency's region, and create a thread
209      * to run the agent's autonomous activity.
210      */

211     public synchronized void beforeResume()
212         throws BadOperation
213     {
214         suspended = false;
215         resetItinerary();
216         runActivity();
217     }
218
219
220     /**
221      * Nothing special to do before moving.
222      */

223     public void beforeMove(Location dummy1, String JavaDoc dummy2)
224     {
225     }
226
227
228     /**
229      * Create a thread after move to go on agent's autonomous activity in new host agency.
230      */

231     public void afterMove(AgentSystem agency, Location dummy1, String JavaDoc dummy2)
232     {
233         my_agency = (Agency)agency;
234         runActivity();
235     }
236
237
238     /**
239      * Nothing special to do if the agent transport/setup phase failed during a move.
240      */

241     public void afterMoveFailed(
242         Location dummy1,
243         String JavaDoc dummy2,
244         int dummy3,
245         String JavaDoc dummy4)
246     {
247     }
248
249
250     /**
251      * Make the agent's thread stop as soon as possible.
252      */

253     public synchronized void beforeDeath()
254     {
255         dead = true;
256         System.out.println(my_name + " is dead.");
257     }
258
259
260     /**
261      * Nothing special to do before agency shutdown (just face upcoming death...)
262      */

263     public void beforeShutdown()
264     {
265     }
266 }
267
Popular Tags