KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > core > group > ProxyForGroup


1 /*
2  * ################################################################
3  *
4  * ProActive: The Java(TM) library for Parallel, Distributed,
5  * Concurrent computing with Security and Mobility
6  *
7  * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8  * Contact: proactive-support@inria.fr
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23  * USA
24  *
25  * Initial developer(s): The ProActive Team
26  * http://www.inria.fr/oasis/ProActive/contacts.html
27  * Contributor(s):
28  *
29  * ################################################################
30  */

31 package org.objectweb.proactive.core.group;
32
33 import java.lang.reflect.InvocationTargetException JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.ListIterator JavaDoc;
37 import java.util.Vector JavaDoc;
38
39 import org.apache.log4j.Logger;
40 import org.objectweb.proactive.Body;
41 import org.objectweb.proactive.ProActive;
42 import org.objectweb.proactive.core.UniqueID;
43 import org.objectweb.proactive.core.body.LocalBodyStore;
44 import org.objectweb.proactive.core.body.proxy.AbstractProxy;
45 import org.objectweb.proactive.core.component.ProActiveInterface;
46 import org.objectweb.proactive.core.group.spmd.MethodCallBarrier;
47 import org.objectweb.proactive.core.group.spmd.MethodCallSetSPMDGroup;
48 import org.objectweb.proactive.core.group.threadpool.ThreadPool;
49 import org.objectweb.proactive.core.mop.ConstructionOfReifiedObjectFailedException;
50 import org.objectweb.proactive.core.mop.ConstructorCall;
51 import org.objectweb.proactive.core.mop.MOP;
52 import org.objectweb.proactive.core.mop.MethodCall;
53 import org.objectweb.proactive.core.mop.StubObject;
54
55
56 public class ProxyForGroup extends AbstractProxy
57     implements org.objectweb.proactive.core.mop.Proxy, Group,
58         java.io.Serializable JavaDoc {
59
60     /** The logger for the Class */
61     protected static Logger logger = Logger.getLogger(ProxyForGroup.class.getName());
62
63     /** The name of the Class : all members of the group are "className" assignable */
64     protected String JavaDoc className;
65
66     /** The list of member : it contains exclusively StubObjects connected to Proxies */
67     protected Vector JavaDoc memberList;
68
69     /** Unique identificator for body (avoid infinite loop in some hierarchicals groups) */
70
71     // NOT FULLY IMPLEMENTED !!!
72
transient private UniqueID proxyForGroupID;
73
74     /** Number of awaited methodcall on the group's member. The Semantic is : we wait all call are done before continuing */
75     protected int waited = 0;
76
77     /** Flag to deternime the semantic of communication (broadcast or dispatching) */
78     protected boolean dispatching = false;
79
80     /** Flag to deternime the semantic of communication (unique serialization of parameters or not) */
81     protected boolean uniqueSerialization = false;
82
83     /** The stub of the typed group */
84     protected StubObject stub;
85
86     /** A pool of thread to serve the request */
87     transient private ThreadPool threadpool;
88
89     /* ----------------------- CONSTRUCTORS ----------------------- */
90     public ProxyForGroup(String JavaDoc nameOfClass)
91         throws ConstructionOfReifiedObjectFailedException {
92         this.className = nameOfClass;
93         this.memberList = new Vector JavaDoc();
94         this.proxyForGroupID = new UniqueID();
95         this.threadpool = new ThreadPool();
96     }
97
98     public ProxyForGroup(String JavaDoc nameOfClass, Integer JavaDoc size)
99         throws ConstructionOfReifiedObjectFailedException {
100         this.className = nameOfClass;
101         this.memberList = new Vector JavaDoc(size.intValue());
102         this.proxyForGroupID = new UniqueID();
103         this.threadpool = new ThreadPool();
104     }
105
106     public ProxyForGroup() throws ConstructionOfReifiedObjectFailedException {
107         this.memberList = new Vector JavaDoc();
108         this.proxyForGroupID = new UniqueID();
109         this.threadpool = new ThreadPool();
110     }
111
112     public ProxyForGroup(ConstructorCall c, Object JavaDoc[] p)
113         throws ConstructionOfReifiedObjectFailedException {
114         this.memberList = new Vector JavaDoc();
115         this.proxyForGroupID = new UniqueID();
116         this.threadpool = new ThreadPool();
117     }
118
119     /* ----------------------------- GENERAL ---------------------------------- */
120
121     /**
122      * Allows the Group to dispatch parameters.
123      */

124     protected void setDispatchingOn() {
125         this.dispatching = true;
126     }
127
128     /**
129      * Allows the Group to broadcast parameters.
130      */

131     protected void setDispatchingOff() {
132         this.dispatching = false;
133     }
134
135     /**
136      * Allows the Group to make an unique serialization of parameters.
137      */

138     protected void setUniqueSerializationOn() {
139         this.uniqueSerialization = true;
140     }
141
142     /**
143      * Removes the ability of the Group to make an unique serialization of parameters..
144      */

145     protected void setUniqueSerializationOff() {
146         this.uniqueSerialization = false;
147     }
148
149     /**
150      * Checks the semantic of communication of the Group.
151      * @return <code>true</code> if the "scatter option" is enabled.
152      */

153     protected boolean isDispatchingOn() {
154         return this.dispatching;
155     }
156
157     private boolean isDispatchingCall(MethodCall mc) {
158         for (int i = 0; i < mc.getNumberOfParameter(); i++)
159             if (ProActiveGroup.isScatterGroupOn(mc.getParameter(i))) {
160                 return true;
161             }
162         return false;
163     }
164
165     /* ------------------------ THE PROXY'S METHOD ------------------------ */
166
167     /**
168      * The proxy's method : implements the semantic of communication. This method invokes the
169      * method call <code>mc</code> on each members of the Group.
170      * @param <code>mc</code> the MethodCall to apply on each member of the Group.
171      * @return the result of the call : <b> the result of a method call on a typed group is a
172      * typed group</b>.
173      * @throws InvocationTargetException if a problem occurs when invoking the method on the members of the Group
174      */

175     public Object JavaDoc reify(MethodCall mc) throws InvocationTargetException JavaDoc {
176
177         //System.out.println("A method is called : " + mc.getName());
178

179         /* if the method called is toString, apply it to the proxy, not to the members */
180         if ("toString".equals(mc.getName())) {
181             return this.toString();
182         }
183
184         /* if the method called is hashCode, apply it to the proxy, not to the members */
185         if ("hashCode".equals(mc.getName())) {
186             return new Integer JavaDoc(this.hashCode());
187         }
188
189         /* result will be a stub on a proxy for group representing the group of results */
190         Object JavaDoc result = null;
191
192         /* check if the threadpool is big enough to make the call (is there is not enough thread, create new ones) */
193         this.threadpool.checkNumberOfThreads(this.memberList.size());
194
195         /* if OneWay : do not construct result */
196         if (AbstractProxy.isOneWayCall(mc)) {
197             this.oneWayCallOnGroup(mc);
198         }
199         /* Special case : the method returns void but is Synchronous because it throws Exception */
200         else if (mc.getReifiedMethod().getReturnType() == Void.TYPE) {
201             this.oneWayCallOnGroup(mc);
202         }
203         /* if the call is asynchronous the group of result will be a group a future */
204         else { // with group in general case : SYNC == ASYNC !!!!
205
result = this.asynchronousCallOnGroup(mc);
206         }
207
208         /* A barrier of synchronisation to be sur that all calls are done before continuing the execution */
209         this.threadpool.complete();
210
211         return result;
212     }
213
214     /* ------------ FOR ASYNCHRONOUS CALL ------------ */
215
216     /**
217      * Creates and initializes (and returns) the group of result, then launch threads for asynchronous call of each member.
218      * @param <code>mc</code> the MethodCall to be applied on each member of the Group.
219      * @return the result of the call.
220      */

221     protected synchronized Object JavaDoc asynchronousCallOnGroup(MethodCall mc) {
222         Object JavaDoc result;
223         Body body = ProActive.getBodyOnThis();
224
225         // Creates a stub + ProxyForGroup for representing the result
226
try {
227             Object JavaDoc[] paramProxy = new Object JavaDoc[0];
228             result = MOP.newInstance(mc.getReifiedMethod().getReturnType()
229                                        .getName(), null,
230                     ProxyForGroup.class.getName(), paramProxy);
231             ((ProxyForGroup) ((StubObject) result).getProxy()).className = mc.getReifiedMethod()
232                                                                              .getReturnType()
233                                                                              .getName();
234         } catch (Exception JavaDoc e) {
235             e.printStackTrace();
236             return null;
237         }
238
239         int size = this.memberList.size();
240
241         // Init the lists of result with null value to permit the "set(index)" operation
242
Vector JavaDoc memberListOfResultGroup = ((ProxyForGroup) ((StubObject) result).getProxy()).memberList;
243         for (int i = 0; i < size; i++) {
244             memberListOfResultGroup.add(null);
245         }
246
247         // Creating Threads
248
if (isDispatchingCall(mc) == false) {
249             if (uniqueSerialization) {
250                 mc.transformEffectiveArgumentsIntoByteArray();
251             }
252             for (int index = 0; index < this.memberList.size(); index++)
253                 this.threadpool.addAJob(new ProcessForAsyncCall(this,
254                         this.memberList, memberListOfResultGroup, index, mc,
255                         body));
256         } else { // isDispatchingCall == true
257
for (int index = 0; index < memberList.size(); index++) {
258                 Object JavaDoc[] individualEffectiveArguments = new Object JavaDoc[mc.getNumberOfParameter()];
259                 for (int i = 0; i < mc.getNumberOfParameter(); i++)
260                     if (ProActiveGroup.isScatterGroupOn(mc.getParameter(i))) {
261                         individualEffectiveArguments[i] = ProActiveGroup.get(mc.getParameter(
262                                     i),
263                                 index % ProActiveGroup.size(mc.getParameter(i)));
264                     } else {
265                         individualEffectiveArguments[i] = mc.getParameter(i);
266                     }
267                 this.threadpool.addAJob(new ProcessForAsyncCall(this,
268                         this.memberList, memberListOfResultGroup, index,
269                         new MethodCall(mc.getReifiedMethod(),
270                             individualEffectiveArguments), body));
271             }
272         }
273
274         LocalBodyStore.getInstance().setCurrentThreadBody(body);
275
276         return result;
277     }
278
279     /**
280      * Add the results (Future) into the typed group result at the correct poisition.
281      * @param <code>memberListOfResultGroup</code> the list of the typed group result.
282      * @param <code>result</code> the result of a call on member of a Group.
283      * @param <code>index</code> the rank of the result.
284      */

285     protected synchronized void addToListOfResult(
286         Vector JavaDoc memberListOfResultGroup, Object JavaDoc result, int index) {
287         memberListOfResultGroup.set(index, result);
288     }
289
290     /* -------------------- FOR ONEWAY CALL ---------------------- */
291
292     /**
293      * Launchs the threads for OneWay call of each member of the Group.
294      * @param <code>mc</code> the MethodCall to be applied on each member of the Group.
295      */

296     protected synchronized void oneWayCallOnGroup(MethodCall mc) {
297         Body body = ProActive.getBodyOnThis();
298         ExceptionList exceptionList = new ExceptionList();
299
300         // Creating Threads
301
if (isDispatchingCall(mc) == false) {
302             if (uniqueSerialization) {
303                 mc.transformEffectiveArgumentsIntoByteArray();
304             }
305             for (int index = 0; index < this.memberList.size(); index++)
306                 this.threadpool.addAJob(new ProcessForOneWayCall(this,
307                         this.memberList, index, mc, body, exceptionList));
308         } else { // isDispatchingCall == true
309
for (int index = 0; index < memberList.size(); index++) {
310                 Object JavaDoc[] individualEffectiveArguments = new Object JavaDoc[mc.getNumberOfParameter()];
311                 for (int i = 0; i < mc.getNumberOfParameter(); i++)
312                     if (ProActiveGroup.isScatterGroupOn(mc.getParameter(i))) {
313                         individualEffectiveArguments[i] = ProActiveGroup.get(mc.getParameter(
314                                     i),
315                                 index % ProActiveGroup.size(mc.getParameter(i)));
316                     } else {
317                         individualEffectiveArguments[i] = mc.getParameter(i);
318                     }
319                 this.threadpool.addAJob(new ProcessForOneWayCall(this,
320                         this.memberList, index,
321                         new MethodCall(mc.getReifiedMethod(),
322                             individualEffectiveArguments), body, exceptionList));
323             }
324         }
325
326         LocalBodyStore.getInstance().setCurrentThreadBody(body);
327
328         if (exceptionList.size() != 0) {
329             throw exceptionList;
330         }
331     }
332
333     /* ------------------- THE COLLECTION'S METHOD ------------------ */
334
335     /**
336      * If o is a reified object and if it is "assignableFrom" the class of the group, add it into the group<br>
337      * - if o is a group merge it into the group<br>
338      * - if o is not a reified object nor a group : do nothing<br>
339      * @param o - element whose presence in this group is to be ensured
340      * @return <code>true</code> if this collection changed as a result of the call
341      */

342     public boolean add(Object JavaDoc o) {
343         try {
344             if ((MOP.forName(this.className)).isAssignableFrom(o.getClass())) {
345
346                 /* if o is an reified object and if it is "assignableFrom" the class of the group, ... add it into the group */
347                 if (MOP.isReifiedObject(o)) {
348                     boolean result = this.memberList.add(o);
349
350                     /* in the particular case that o extends GroupMember, there are few more operations */
351                     if (o instanceof org.objectweb.proactive.core.group.GroupMember) {
352                         ((org.objectweb.proactive.core.group.GroupMember) o).setMyGroup(stub);
353                         ((org.objectweb.proactive.core.group.GroupMember) o).setMyRank(this.memberList.indexOf(
354                                 o));
355                     }
356                     return result;
357                 }
358                 // COMPONENTS
359

360                 /* if o is a reference on a component interface*/
361                 else if (o instanceof ProActiveInterface) {
362                     return this.memberList.add(o);
363                 } /* if o is a Group */ else if (o instanceof org.objectweb.proactive.core.group.ProxyForGroup) {
364
365                     /* like an addMerge call */
366                     return this.memberList.addAll(((org.objectweb.proactive.core.group.ProxyForGroup) o).memberList);
367                 } /* o is a standard Java object */ else {
368                     return this.memberList.add(o);
369                 }
370             } else {
371                 if (logger.isInfoEnabled()) {
372                     logger.info("uncompatible Object");
373                 }
374                 return false;
375             }
376         } catch (java.lang.ClassNotFoundException JavaDoc e) {
377             if (logger.isInfoEnabled()) {
378                 logger.info("Unknown class : " + this.className);
379             }
380         }
381         return true;
382     }
383
384     /**
385      * Adds all of the elements in the specified Collection to this Group.
386      * @param <code>c</code> - the elements to be inserted into this Group.
387      * @return <code>true</code> if this collection changed as a result of the call.
388      */

389     public boolean addAll(Collection JavaDoc c) {
390         boolean modified = false;
391         Iterator JavaDoc iterator = c.iterator();
392         while (iterator.hasNext()) {
393             modified |= this.add(iterator.next());
394         }
395         return modified;
396     }
397
398     /**
399      * Removes all of the elements from this group.
400      * This group will be empty after this method returns.
401      */

402     public void clear() {
403         this.memberList.clear();
404     }
405
406     /**
407      * This method returns true if and only if this group contains at least one element e such that <code>o.equals(e)</code>
408      * @return <code>true</code> if this collection contains the specified element.
409      */

410     public boolean contains(Object JavaDoc o) {
411         return this.memberList.contains(o);
412     }
413
414     /**
415      * Checks if this Group contains all of the elements in the specified collection.
416      * @param <code>c</code> - the collection to be checked for containment in this Group.
417      * @return <code>true</code> if this Group contains all of the elements in the specified collection
418      */

419     public boolean containsAll(Collection JavaDoc c) {
420         boolean contained;
421         Iterator JavaDoc iterator = c.iterator();
422         while (iterator.hasNext()) {
423             contained = this.contains(iterator.next());
424             if (!contained) {
425                 return false;
426             }
427         }
428         return true;
429     }
430
431     /**
432      * Compares the specified object with this group for equality.
433      * @param <o> the Object for wich we test the equality.
434      * @return <code>true</code> if <code>o</code> is the same Group as <code>this</code>.
435      */

436     public boolean equals(Object JavaDoc o) {
437         if (o instanceof org.objectweb.proactive.core.group.ProxyForGroup) {
438             return this.proxyForGroupID.equals(((org.objectweb.proactive.core.group.ProxyForGroup) o).proxyForGroupID);
439         } else {
440             return false;
441         }
442     }
443
444     /**
445      * Returns the hash code value for this Group.
446      * @return the hash code value for this Group.
447      */

448     public int hashCode() {
449         return this.memberList.hashCode();
450     }
451
452     /**
453      * Check if the group is empty.
454      * @return <code>true</code> if this collection contains no elements.
455      */

456     public boolean isEmpty() {
457         return this.memberList.isEmpty();
458     }
459
460     /**
461      * Returns an Iterator of the member in the Group.
462      * @return an Iterator of the member in the Group.
463      */

464     public Iterator JavaDoc iterator() {
465         return this.memberList.iterator();
466     }
467
468     /**
469      * Removes a single instance of the specified element from this Group, if it is present.
470      * It removes the first occurence e where <code>o.equals(e)</code> returns <code>true</code>.
471      * @param <code>o</code> the element to be removed from this Group (if present).
472      * @return <code>true> if the Group contained the specified element.
473      */

474     public boolean remove(Object JavaDoc o) {
475         return this.memberList.remove(o);
476     }
477
478     /**
479      * Removes all this Group's elements that are also contained in the specified collection.
480      * After this call returns, this collection will contain no elements in common with the specified collection.
481      * @param <code>c</code> - elements to be removed from this Group.
482      * @return <code>true</code> if this Group changed as a result of the call
483      */

484     public boolean removeAll(Collection JavaDoc c) {
485         boolean modified = false;
486         Iterator JavaDoc iterator = c.iterator();
487         while (iterator.hasNext()) {
488             modified |= this.remove(iterator.next());
489         }
490         return modified;
491     }
492
493     /**
494      * Retains only the elements in this Group that are contained in the specified collection.
495      * It removes from this Group all of its elements that are not contained in the specified collection.
496      * @param <code>c</code> - elements to be retained in this Group.
497      * @return <code>true</code> if this Group changed as a result of the call.
498      */

499     public boolean retainAll(Collection JavaDoc c) {
500         boolean modified = false;
501         Iterator JavaDoc iterator = c.iterator();
502         while (iterator.hasNext()) {
503             Object JavaDoc tmp = iterator.next();
504             if (this.contains(tmp)) {
505                 modified |= this.remove(tmp);
506             }
507         }
508         return modified;
509     }
510
511     /**
512      * Returns the number of member in this Group.
513      * @return the number of member in this Group.
514      */

515     public int size() {
516         return this.memberList.size();
517     }
518
519     /**
520      * Returns an array containing all of the elements in this Group in the correct order.
521      * @return an array containing all of the elements in this Group in the correct order.
522      */

523     public Object JavaDoc[] toArray() {
524         return this.memberList.toArray();
525     }
526
527     /**
528      * Returns an array containing all of the elements in this collection;
529      * the runtime type of the returned array is that of the specified array.
530      * @param <code>a</code> - the array into which the elements of this collection are to be stored, if it is big enough;
531      * otherwise, a new array of the same runtime type is allocated for this purpose.
532      * @return an array containing the elements of this collection.
533      */

534     public Object JavaDoc[] toArray(Object JavaDoc[] a) {
535         return this.memberList.toArray(a);
536     }
537
538     /* ---------------------- THE GROUP'S METHOD ------------------- */
539
540     /**
541      * Add all member of the group <code>ogroup</code> into the Group. <code>ogroup</code> can be :<br>
542      * - a typed group<br>
543      * - a Group<br>
544      * - a standard Object<br>
545      * but it have to be (or to extend) the Class of the Group.
546      * @param <code>ogroup</code> the object(s) to merge into the Group.
547      */

548     public void addMerge(Object JavaDoc oGroup) {
549         try {
550
551             /* check oGroup is an Reified Object and if it is "assignableFrom" the class of the group */
552             if ((MOP.isReifiedObject(oGroup)) &&
553                     ((MOP.forName(this.className)).isAssignableFrom(
554                         oGroup.getClass()))) {
555
556                 /* check oGroup is an object representing a group */
557                 if (((StubObject) oGroup).getProxy() instanceof org.objectweb.proactive.core.group.ProxyForGroup) {
558                     memberList.addAll(((ProxyForGroup) ((StubObject) oGroup).getProxy()).memberList);
559                 } /* if oGroup is a Standard Active Object (but not a group), just add it */ else {
560                     this.add(oGroup);
561                 }
562             } /* if oGroup is a Group */ else if (oGroup instanceof org.objectweb.proactive.core.group.ProxyForGroup) {
563                 memberList.addAll(((org.objectweb.proactive.core.group.ProxyForGroup) oGroup).memberList);
564             }
565         } catch (java.lang.ClassNotFoundException JavaDoc e) {
566             if (logger.isInfoEnabled()) {
567                 logger.info("Unknown class : " + this.className);
568             }
569         }
570     }
571
572     /**
573      * Returns the index of the first occurence of the specified Object <code>obj</code>.
574      * @param <code>obj</code> the obj tahat is searched in the Group.
575      * @return the rank of <code>obj</code> in the Group.
576      * -1 if the list does not contain this object.
577      */

578     public int indexOf(Object JavaDoc obj) {
579         return this.memberList.indexOf(obj);
580     }
581
582     /**
583      * Returns a list iterator of the members in this Group (in proper sequence).
584      * @return a list iterator of the members in this Group.
585      */

586     public ListIterator JavaDoc listIterator() {
587         return this.memberList.listIterator();
588     }
589
590     /**
591      * Removes the element at the specified position.
592      * @param <code>index</code> the rank of the object to remove in the Group.
593      */

594     public void remove(int index) {
595         this.memberList.remove(index);
596     }
597
598     /**
599      * Returns the i-th member of the group.
600      * @param <code>index</code> the rank of the object to return.
601      * @return the member of the Group at the specified rank.
602      */

603     public Object JavaDoc get(int i) {
604         return this.memberList.get(i);
605     }
606
607     /**
608      * Returns the ("higher") Class of group's member.
609      * @return the Class that all Group's members are (or extend).
610      * @throws java.lang.ClassNotFoundException if the class name of the Group is not known.
611      */

612     public Class JavaDoc getType() throws java.lang.ClassNotFoundException JavaDoc {
613         return MOP.forName(this.className);
614     }
615
616     /**
617      * Returns the full name of ("higher") Class of group's member
618      * @return the name of the Class that all Group's members are (or extend).
619      */

620     public String JavaDoc getTypeName() {
621         return this.className;
622     }
623
624     /**
625      * Returns an Object (a <b>typed group</b> Object) representing the Group
626      * @return a typed group corresponding to the Group.
627      */

628     public Object JavaDoc getGroupByType() {
629         Object JavaDoc result;
630         try { // a new proxy is generated
631
result = MOP.newInstance(this.className, null,
632                     ProxyForGroup.class.getName(), null);
633         } catch (Exception JavaDoc e) {
634             e.printStackTrace();
635             return null;
636         }
637         ProxyForGroup proxy = (ProxyForGroup) ((StubObject) result).getProxy();
638         proxy.memberList = this.memberList;
639         proxy.className = this.className;
640         proxy.proxyForGroupID = this.proxyForGroupID;
641         proxy.waited = this.waited;
642         return result;
643     }
644
645     // This is the best thing to do, but createStubObject has a private acces !!!! :
646
// // Instanciates the stub object
647
// StubObject stub = MOP.createStubObject(this.className, MOP.forName(this.className));
648
// // Connects the proxy to the stub
649
// stub.setProxy(this);
650
// return stub;
651
// }
652
// An other way is to "store" the stub and return it when asked
653

654     /**
655      * Creates a new group with all members of the group and all the members of the group <code>g</code>
656      * @param g - a group
657      * @return a group that contain all the members of the group and <code>g</code>. <code>null<code> if the class of the group is incompatible.
658      */

659     public Group union (Group g) {
660         try {
661             if ((MOP.forName(this.getTypeName())).isAssignableFrom(MOP.forName(g.getTypeName()))) {
662                 ProxyForGroup result = new ProxyForGroup(this.getTypeName());
663                 // add the members of this
664
Iterator JavaDoc it = this.iterator();
665                 while (it.hasNext()) {
666                     result.add(it.next());
667                 }
668                 // add the members of g
669
it = g.iterator();
670                 while (it.hasNext()) {
671                     result.add(it.next());
672                 }
673                 return result;
674             } }
675         catch (ClassNotFoundException JavaDoc e) { e.printStackTrace(); }
676         catch (ConstructionOfReifiedObjectFailedException e) { e.printStackTrace(); }
677         // the group are incompatible (i.e. they have not members of the the same class)
678
return null;
679     }
680
681     /**
682      * Creates a new group with all members that belong to the group and to the group <code>g</code>.
683      * @param g - a group
684      * @return a group that contain the common members of the group and <code>g</code>. <code>null<code> if the class of the group is incompatible.
685      */

686     public Group intersection (Group g) {
687         try {
688             if ((MOP.forName(this.getTypeName())).isAssignableFrom(MOP.forName(g.getTypeName()))) {
689                 ProxyForGroup result = new ProxyForGroup(this.getTypeName());
690                 Object JavaDoc member;
691                 Iterator JavaDoc it = this.iterator();
692                 // add the members of the group that belong to g
693
while (it.hasNext()) {
694                     member = it.next();
695                     if (g.indexOf(member) > -1) {
696                         result.add(member);
697                     }
698                 }
699                 return result;
700             } }
701         catch (ClassNotFoundException JavaDoc e) { e.printStackTrace(); }
702         catch (ConstructionOfReifiedObjectFailedException e) { e.printStackTrace(); }
703         // the group are incompatible (i.e. they have not members of the the same class)
704
return null;
705     }
706
707     /**
708      * Creates a new group with the members that belong to the group, but not to the group <code>g</code>.
709      * @param g - a group
710      * @return a group that contain the members of the group without the member <code>g</code>. <code>null<code> if the class of the group is incompatible.
711      */

712     public Group exclude (Group g) {
713         try {
714             if ((MOP.forName(this.getTypeName())).isAssignableFrom(MOP.forName(g.getTypeName()))) {
715                 ProxyForGroup result = new ProxyForGroup(this.getTypeName());
716                 Object JavaDoc member;
717                 Iterator JavaDoc it = this.iterator();
718                 while (it.hasNext()) {
719                     member = it.next();
720                     if (g.indexOf(member) < 0) {
721                         result.add(member);
722                     }
723                 }
724                 return result;
725             } }
726         catch (ClassNotFoundException JavaDoc e) { e.printStackTrace(); }
727         catch (ConstructionOfReifiedObjectFailedException e) { e.printStackTrace(); }
728         // the group are incompatible (i.e. they have not members of the the same class)
729
return null;
730     }
731
732     /**
733      * Creates a new group with all members that belong to the group or to the group <code>g</code>, but not to both.
734      * @param g - a group
735      * @return a group that contain the non-common members of the group and <code>g</code>. <code>null<code> if the class of the group is incompatible.
736      */

737     public Group difference (Group g) {
738         try {
739             if ((MOP.forName(this.getTypeName())).isAssignableFrom(MOP.forName(g.getTypeName()))) {
740                 ProxyForGroup result = new ProxyForGroup(this.getTypeName());
741                 Object JavaDoc member;
742                 Iterator JavaDoc it = this.iterator();
743                 // add the members of the group that do not belong to g
744
while (it.hasNext()) {
745                     member = it.next();
746                     if (g.indexOf(member) < 0) {
747                         result.add(member);
748                     }
749                 }
750                 it = g.iterator();
751                 // add the members of g that do not belong to the group
752
while (it.hasNext()) {
753                     member = it.next();
754                     if (this.indexOf(member) < 0) {
755                         result.add(member);
756                     }
757                 }
758                 return result;
759             } }
760         catch (ClassNotFoundException JavaDoc e) { e.printStackTrace(); }
761         catch (ConstructionOfReifiedObjectFailedException e) { e.printStackTrace(); }
762         // the group are incompatible (i.e. they have not members of the the same class)
763
return null;
764     }
765
766     /**
767      * Creates a new group with the members of the group begining at the index <code>begin</code> and ending at the index <code>end</code>.
768      * @param begin - the begining index
769      * @param end - the ending index
770      * @return a group that contain the members of the group from <code>begin</code> to <code>end</code>. <code>null</code> if <code>begin > end</code>.
771      */

772     public Group range (int begin, int end) {
773         // bag arguments => return null
774
if (begin > end) {
775             return null;
776         }
777         if (begin < 0) {
778             begin = 0;
779         }
780         if (end > this.size()) {
781             end = this.size();
782         }
783         try {
784             ProxyForGroup result = new ProxyForGroup(this.getTypeName());
785             for (int i = begin ; i <= end ; i++) {
786                 result.add(this.get(i));
787             }
788             return result;
789         }
790         catch (ConstructionOfReifiedObjectFailedException e) {
791             e.printStackTrace();
792             return null;
793         }
794     }
795
796     /**
797      * Strongly synchronizes all the members of the group
798      */

799     public void barrier () {
800         try {
801             this.reify(new MethodCallBarrier()); }
802         catch (InvocationTargetException JavaDoc e) {
803             logger.info("Unable to invoke the \"barrier\" method");
804             e.printStackTrace();
805         }
806     }
807
808     /**
809      * Communicates the SPMD Group to members
810      * @param spmdGroup - the SPMD group
811      */

812     public void setSPMDGroup (Object JavaDoc spmdGroup) {
813         try {
814             this.reify(new MethodCallSetSPMDGroup(spmdGroup)); }
815         catch (InvocationTargetException JavaDoc e) {
816             logger.info("Unable to set the SPMD group");
817             e.printStackTrace();
818         }
819     }
820
821     /**
822      * To debug, display the size of the Group and all its members with there position
823      */

824     public void display() {
825         logger.info("Number of member : " + memberList.size());
826         for (int i = 0; i < memberList.size(); i++)
827             logger.info(" " + i + " : " +
828                 memberList.get(i).getClass().getName());
829     }
830
831     /* ------------------- SYNCHRONIZATION -------------------- */
832
833     /**
834      * Waits that all the members are arrived.
835      */

836     public void waitAll() {
837         ProActive.waitForAll(this.memberList);
838     }
839
840     /**
841      * Waits that at least one member is arrived.
842      */

843     public void waitOne() {
844         ProActive.waitForAny(this.memberList);
845     }
846
847     /**
848      * Waits that the member at the specified rank is arrived.
849      * @param <code>index</code> the rank of the awaited member.
850      */

851     public void waitTheNth(int n) {
852         ProActive.waitFor(this.memberList.get(n));
853     }
854
855     /**
856      * Waits that at least <code>n</code> members are arrived.
857      * @param <code>n</code> the number of awaited members.
858      */

859     public void waitN(int n) {
860         for (int i = 0; i < n; i++) {
861             this.waitTheNth(i);
862         }
863     }
864
865     /**
866      * Waits that at least one member is arrived and returns it.
867      * @return a non-awaited member of the Group.
868      */

869     public Object JavaDoc waitAndGetOne() {
870         return this.memberList.get(ProActive.waitForAny(this.memberList));
871     }
872
873     /**
874      * Waits that the member at the specified rank is arrived and returns it.
875      * @param <code>n</code> the rank of the wanted member.
876      * @return the member (non-awaited) at the rank <code>n</code> in the Group.
877      */

878     public Object JavaDoc waitAndGetTheNth(int n) {
879         ProActive.waitForTheNth(this.memberList, n);
880         return this.memberList.get(n);
881     }
882
883     /**
884      * Waits that at least one member is arrived and returns its index.
885      * @return the index of a non-awaited member of the Group.
886      */

887     public int waitOneAndGetIndex() {
888         int index = 0;
889         this.memberList.get(ProActive.waitForAny(this.memberList));
890         while (ProActive.isAwaited(this.memberList.get(index))) {
891             index++;
892         }
893         return index;
894     }
895
896     /**
897      * Checks if all the members of the Group are awaited.
898      * @return <code>true</code> if all the members of the Group are awaited.
899      */

900     public boolean allAwaited() {
901         for (int i = 0; i < this.memberList.size(); i++)
902             if (!(ProActive.isAwaited(this.memberList.get(i)))) {
903                 return false;
904             }
905         return true;
906     }
907
908     /**
909      * Checks if all the members of the Group are arrived.
910      * @return <code>true</code> if all the members of the Group are arrived.
911      */

912     public boolean allArrived() {
913         for (int i = 0; i < this.memberList.size(); i++)
914             if (ProActive.isAwaited(this.memberList.get(i))) {
915                 return false;
916             }
917         return true;
918     }
919
920     /**
921      * Returns an ExceptionList containing all the throwables (exceptions and errors) occured
922      * when this group was built
923      * @return an ExceptionList
924      */

925     public ExceptionList getExceptionList() {
926         ExceptionList exceptionList = new ExceptionList();
927         for (int i = 0; i < this.memberList.size(); i++) {
928             if (this.memberList.get(i) instanceof Throwable JavaDoc) {
929                 exceptionList.add(new ExceptionInGroup(null,
930                         (Throwable JavaDoc) this.memberList.get(i)));
931             }
932         }
933         return exceptionList;
934     }
935
936     /**
937      * Removes all exceptions and null references contained in the Group.
938      * Exceptions (and null references) appears with communication/program-level/runtime errors
939      * and are stored in the Group.
940      * (After this operation the size of the Group decreases)
941      */

942     public void purgeExceptionAndNull() {
943         Iterator JavaDoc it = this.memberList.iterator();
944         while (it.hasNext()) {
945             Object JavaDoc element = (Object JavaDoc) it.next();
946             if ((element instanceof Throwable JavaDoc) || (element == null)) {
947                 it.remove();
948             }
949         }
950     }
951
952     /**
953      * Modifies the number of members served by one thread
954      * @param i - the new ratio
955      */

956     public void setRatioNemberToThread(int i) {
957         this.threadpool.ratio(i);
958     }
959
960     /* ---------------------- METHOD FOR SYNCHRONOUS CREATION OF A TYPED GROUP ---------------------- */
961
962     /**
963      * Builds the members using the threads (of the threadpool).
964      * @param <code>className</code> the name of the Class of the members.
965      * @param <code>param</code> an array that contains the parameters for the constructor of member.
966      * @param <code>node</code> the node where the member will be created.
967      */

968     protected void createMemberWithMultithread(String JavaDoc className,
969         Object JavaDoc[][] params, String JavaDoc[] nodeList) {
970         // Initializes the Group to the correct size
971
for (int i = 0; i < params.length; i++) {
972             this.memberList.add(null);
973         }
974         for (int i = 0; i < params.length; i++) {
975             this.threadpool.addAJob(new ProcessForGroupCreation(this,
976                     className, params[i], nodeList[i % nodeList.length], i));
977         }
978         this.threadpool.complete();
979     }
980
981     /**
982      * Sets an object to the specified position in the Group
983      * @param index - the position
984      * @param o - the object to add
985      */

986     protected void set(int index, Object JavaDoc o) {
987         this.memberList.set(index, o);
988     }
989
990     /* ------------------------ PRIVATE METHODS FOR SERIALIZATION --------------------- */
991     private void writeObject(java.io.ObjectOutputStream JavaDoc out)
992         throws java.io.IOException JavaDoc {
993         // this.threadpool.finalize();
994
out.defaultWriteObject();
995     }
996
997     private void readObject(java.io.ObjectInputStream JavaDoc in)
998         throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
999         in.defaultReadObject();
1000        this.proxyForGroupID = new UniqueID();
1001        this.threadpool = new ThreadPool();
1002    }
1003
1004}
1005
Popular Tags