KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > examples > chat > Chat


1
2 package org.objectweb.proactive.examples.chat;
3
4 import java.io.IOException JavaDoc;
5 import java.util.Vector JavaDoc;
6
7 import org.apache.log4j.Logger;
8 import org.objectweb.proactive.ActiveObjectCreationException;
9 import org.objectweb.proactive.Body;
10 import org.objectweb.proactive.ProActive;
11 import org.objectweb.proactive.RunActive;
12 import org.objectweb.proactive.Service;
13 import org.objectweb.proactive.core.body.migration.Migratable;
14 import org.objectweb.proactive.core.body.migration.MigrationException;
15 import org.objectweb.proactive.core.config.ProActiveConfiguration;
16 import org.objectweb.proactive.core.group.ProActiveGroup;
17 import org.objectweb.proactive.core.mop.ClassNotReifiableException;
18 import org.objectweb.proactive.core.node.Node;
19 import org.objectweb.proactive.core.node.NodeException;
20 import org.objectweb.proactive.ext.migration.MigrationStrategyManagerImpl;
21
22 /**
23  * This class represents the Active Object who manages the communication between all the users.
24  *
25  * @author Laurent Baduel
26  */

27 public class Chat implements java.io.Serializable JavaDoc, RunActive {
28     
29     static Logger logger = Logger.getLogger(Chat.class.getName());
30     
31     /** The name of the user */
32     private String JavaDoc name = "";
33     /** The other chaters */
34     private Chat diffusionGroup = null;
35     /** An history of all recieved messages */
36     private Vector JavaDoc messageLogger;
37     /** The graphique interface */
38     private transient ChatGUI frame;
39     /** The migration strategy manager */
40     private MigrationStrategyManagerImpl migrationStrategy = null;
41     /** The list of users */
42     private String JavaDoc listOfName = "";
43
44     /**
45      * Constructor : The default constructor requiered to build Active Objects
46      */

47     public Chat () {}
48
49     /**
50      * Constructor : Specify the name of the user to build the Object
51      * @param identity - the name of the user
52      */

53     public Chat (String JavaDoc identity) {
54         this.name = identity;
55         this.messageLogger = new Vector JavaDoc();
56     }
57
58     /**
59      * Returns the name of the user
60      * @return the name of the user
61      */

62     public String JavaDoc getName() {
63         return this.name;
64     }
65
66     /**
67      * Returns the group of diffusion of the Object
68      * @return a typed group representing the other users of the chat
69      */

70     public Chat getDiffusionGroup() {
71         return this.diffusionGroup;
72     }
73     
74     /**
75      * Launchs a client without connecting to any other client
76      */

77     public void startAlone () {
78         try {
79             this.diffusionGroup = (Chat) ProActiveGroup.newGroup(Chat.class.getName()); }
80         catch (ClassNotReifiableException e) { e.printStackTrace(); }
81         catch (ClassNotFoundException JavaDoc e) { e.printStackTrace(); }
82         this.addIntoDiffusionGroup((Chat) ProActive.getStubOnThis(), this.name);
83         this.writeMessage(new Message(" *** " + this.name + " has joined the place"));
84     }
85
86     /**
87      * Launchs a client and connects it to the users known by a speified user (neighbour).
88      *
89      * A fully peer-to-peer system established with ONLY 4 LINES OF CODES !!!
90      * 1 - lookup for the neighbour
91      * 2 - copy the diffusion group of the neighbour
92      * 3 - register itself to the other users by the diffusion group
93      * 4 - add itself to it own diffusion group
94      *
95      * @param hostname - the name of the host of the neighbour
96      * @param userName - the name of user of the neighbour
97      */

98     public void connect (String JavaDoc hostName, String JavaDoc userName) {
99         Chat neighbour = null;
100         try {
101             neighbour = (Chat) ProActive.lookupActive(Chat.class.getName(), "//" + hostName + "/" + userName); // 1
102
this.diffusionGroup = neighbour.getDiffusionGroup(); // 2
103
this.writeUsersInTheList();
104             this.diffusionGroup.addIntoDiffusionGroup((Chat) ProActive.getStubOnThis(), this.name); // 3
105
ProActiveGroup.getGroup(this.diffusionGroup).add((Chat) ProActive.getStubOnThis()); //4
106
this.frame.list.append(this.name+"\n");
107             this.writeMessage(new Message(" *** " + this.name + " has joined the place"));
108         }
109         catch (ActiveObjectCreationException e) { e.printStackTrace(); }
110         catch (IOException JavaDoc e) {
111             this.writePrivateMessage(new Message(" *** WARNING : Unable to contact " + userName + "@" + hostName + " !"));
112             this.writePrivateMessage(new Message(" *** WARNING : Starting alone !"));
113             this.startAlone();
114         }
115     }
116
117     /**
118      * Adds a specified user to the group of diffusion
119      * @param c - the user to add
120      * @param name - the name of the user to add
121      */

122     public void addIntoDiffusionGroup(Chat c, String JavaDoc name) {
123         ProActiveGroup.getGroup(this.diffusionGroup).add(c);
124         this.frame.list.append(name + "\n");
125     }
126     
127     /**
128      * Disconnects the user from all the others (removes it from their diffusion group)
129      */

130     public void disconnect () {
131         this.writeMessage(new Message(" *** " + this.name + " has left"));
132         this.diffusionGroup.removeUserFromTheList(this.name);
133         this.diffusionGroup.removeFromDiffusionGroup((Chat) ProActive.getStubOnThis());
134         ProActiveGroup.getGroup(this.diffusionGroup).remove((Chat) ProActive.getStubOnThis());
135     }
136
137     /**
138      * Removes a specified user from the group of diffusion
139      * @param c - the user to remove
140      */

141     public void removeFromDiffusionGroup(Chat c) {
142         ProActiveGroup.getGroup(this.diffusionGroup).remove(c);
143     }
144
145
146     /**
147      * Specifies the activity of the user
148      */

149     public void runActivity(Body body) {
150         Service service = new Service(body);
151         this.register();
152         this.rebuildFrame();
153         this.initializeMigrationStrategy();
154         this.replayMessages();
155         while (body.isActive()) {
156             service.blockingServeOldest();
157         }
158     }
159
160     /**
161      * Builds the migration strategy manager
162      */

163     public void initializeMigrationStrategy () {
164         if (this.migrationStrategy == null) {
165             this.migrationStrategy = new MigrationStrategyManagerImpl((Migratable) ProActive.getBodyOnThis());
166             this.migrationStrategy.onDeparture("onDeparture");
167         }
168     }
169
170     /**
171      * To be executed on the departure (when the object begins to migrate to an other location)
172      */

173     public void onDeparture () {
174         this.disposeFrame();
175         this.unregister();
176     }
177
178     /**
179      * Registers the object on it current host
180      */

181     public void register () {
182         try {
183             ProActive.register(ProActive.getStubOnThis(), "//localhost/" + this.name); }
184         catch (IOException JavaDoc e) { e.printStackTrace(); }
185     }
186
187     /**
188      * Unregisters the object on it host
189      */

190     public void unregister () {
191         try {
192             ProActive.unregister("//localhost/" + this.name); }
193         catch (IOException JavaDoc e) { e.printStackTrace(); }
194     }
195
196     /**
197      * Destroys the graphic interface
198      */

199     public void disposeFrame() {
200         this.listOfName = this.frame.list.getText();
201         if (this.frame != null) {
202             this.frame.dispose();
203             this.frame = null;
204         }
205     }
206
207     /**
208      * Rebuild the graphic interface
209      */

210     public void rebuildFrame() {
211       this.frame = new ChatGUI((Chat)ProActive.getStubOnThis(),name);
212       this.frame.list.setText(this.listOfName);
213     }
214     
215     /**
216      * Replay the messages received by the user
217      */

218     public void replayMessages() {
219         for (int i=0 ; i < this.messageLogger.size() ; i++) {
220             this.frame.text.append(((Message)this.messageLogger.get(i)).toString());
221         }
222     }
223     
224     /**
225      * Migrates the object to the specified loaction
226      * @param nodeURL - the name of the node to migrate
227      */

228     public void migrateTo(String JavaDoc nodeURL) {
229         this.writePrivateMessage(new Message(" *** I move to " + nodeURL));
230         try {
231             ProActive.migrateTo(nodeURL); }
232         catch (MigrationException e) {
233             this.writePrivateMessage(new Message (" *** WARNING : Unable to move to " + nodeURL + " !"));
234         }
235     }
236
237
238     /**
239      * Writes a message to the user
240      * @param m - the message to write
241      */

242     public void writePrivateMessage (Message m) {
243         this.messageLogger.add(m);
244         this.frame.text.append(m.toString());
245     }
246
247     /**
248      * Writes a message to all the members of the diffusion group
249      * @param m - the message to write
250      */

251     public void writeMessage (Message m) {
252         this.diffusionGroup.writePrivateMessage(m);
253     }
254
255     /**
256      * Writes the name of all connected users in the list
257      */

258     public void writeUsersInTheList () {
259         java.util.Iterator JavaDoc it = ProActiveGroup.getGroup(this.diffusionGroup).iterator();
260         while (it.hasNext())
261             this.frame.list.append(((Chat) it.next()).getName()+"\n");
262     }
263
264     /**
265      * Removes the specified name of user from the list
266      * @param userName - the name to remove
267      */

268     public void removeUserFromTheList (String JavaDoc userName) {
269         this.frame.list.setText(this.frame.list.getText().replaceAll(userName+"\n",""));
270     }
271
272     public static void main (String JavaDoc[] args) {
273
274         String JavaDoc userName;
275         String JavaDoc neighbourHost = null;
276         String JavaDoc neighbourName = null;
277         ProActiveConfiguration.load();
278
279         if ((args.length != 1) && (args.length != 3)) {
280             logger.info("usage : chat.[sh|bat] UserName [ServerHost ServerName]");
281             System.exit(0);
282         }
283         
284         userName = args[0];
285         if (args.length == 3) {
286             neighbourHost = args[1];
287             neighbourName = args[2];
288         }
289
290
291         Chat chat = null;
292         try {
293             Object JavaDoc[] param = new Object JavaDoc[1]; param[0] = new String JavaDoc(userName);
294             chat = (Chat) ProActive.newActive(Chat.class.getName(), param, (Node) null); }
295         catch (ActiveObjectCreationException e) { e.printStackTrace(); }
296         catch (NodeException e) { e.printStackTrace(); }
297
298         if ((neighbourHost == null) || (neighbourName == null))
299             chat.startAlone();
300         else
301             chat.connect(neighbourHost,neighbourName);
302
303     }
304
305
306 }
307
Popular Tags