KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > ProActive


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;
32
33 import org.apache.log4j.Logger;
34
35 import org.objectweb.fractal.api.Component;
36 import org.objectweb.fractal.api.NoSuchInterfaceException;
37 import org.objectweb.fractal.api.factory.GenericFactory;
38 import org.objectweb.fractal.api.factory.InstantiationException;
39 import org.objectweb.fractal.util.Fractal;
40
41 import org.objectweb.proactive.core.Constants;
42 import org.objectweb.proactive.core.ProActiveException;
43 import org.objectweb.proactive.core.ProActiveRuntimeException;
44 import org.objectweb.proactive.core.body.LocalBodyStore;
45 import org.objectweb.proactive.core.body.MetaObjectFactory;
46 import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory;
47 import org.objectweb.proactive.core.body.UniversalBody;
48 import org.objectweb.proactive.core.body.future.Future;
49 import org.objectweb.proactive.core.body.future.FuturePool;
50 import org.objectweb.proactive.core.body.ibis.IbisRemoteBodyAdapter;
51 import org.objectweb.proactive.core.body.migration.Migratable;
52 import org.objectweb.proactive.core.body.migration.MigrationException;
53 import org.objectweb.proactive.core.body.proxy.BodyProxy;
54 import org.objectweb.proactive.core.body.request.BodyRequest;
55 import org.objectweb.proactive.core.body.rmi.RemoteBodyAdapter;
56 import org.objectweb.proactive.core.component.ComponentParameters;
57 import org.objectweb.proactive.core.component.ContentDescription;
58 import org.objectweb.proactive.core.component.ControllerDescription;
59 import org.objectweb.proactive.core.config.ProActiveConfiguration;
60 import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
61 import org.objectweb.proactive.core.descriptor.data.VirtualNode;
62 import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl;
63 import org.objectweb.proactive.core.descriptor.xml.ProActiveDescriptorHandler;
64 import org.objectweb.proactive.core.exceptions.NonFunctionalException;
65 import org.objectweb.proactive.core.exceptions.communication.ProActiveCommunicationException;
66 import org.objectweb.proactive.core.exceptions.creation.ProActiveCreationException;
67 import org.objectweb.proactive.core.exceptions.group.ProActiveGroupException;
68 import org.objectweb.proactive.core.exceptions.handler.HandlerCommunicationException;
69 import org.objectweb.proactive.core.exceptions.handler.HandlerCreationException;
70 import org.objectweb.proactive.core.exceptions.handler.HandlerGroupException;
71 import org.objectweb.proactive.core.exceptions.handler.HandlerMigrationException;
72 import org.objectweb.proactive.core.exceptions.handler.HandlerNonFunctionalException;
73 import org.objectweb.proactive.core.exceptions.handler.HandlerSecurityException;
74 import org.objectweb.proactive.core.exceptions.handler.HandlerServiceException;
75 import org.objectweb.proactive.core.exceptions.handler.IHandler;
76 import org.objectweb.proactive.core.exceptions.migration.ProActiveMigrationException;
77 import org.objectweb.proactive.core.exceptions.security.ProActiveSecurityException;
78 import org.objectweb.proactive.core.exceptions.service.ProActiveServiceException;
79 import org.objectweb.proactive.core.group.Group;
80 import org.objectweb.proactive.core.group.ProActiveGroup;
81 import org.objectweb.proactive.core.mop.ClassNotReifiableException;
82 import org.objectweb.proactive.core.mop.ConstructionOfProxyObjectFailedException;
83 import org.objectweb.proactive.core.mop.MOP;
84 import org.objectweb.proactive.core.mop.MOPException;
85 import org.objectweb.proactive.core.mop.StubObject;
86 import org.objectweb.proactive.core.node.Node;
87 import org.objectweb.proactive.core.node.NodeException;
88 import org.objectweb.proactive.core.node.NodeFactory;
89 import org.objectweb.proactive.core.runtime.ProActiveRuntime;
90 import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
91 import org.objectweb.proactive.core.runtime.RuntimeFactory;
92 import org.objectweb.proactive.core.util.UrlBuilder;
93
94 import java.net.UnknownHostException JavaDoc;
95
96 import java.util.HashMap JavaDoc;
97
98
99 public class ProActive {
100     protected static Logger logger = Logger.getLogger(ProActive.class.getName());
101
102     //
103
// -- STATIC MEMBERS -----------------------------------------------
104
//
105

106     /**
107      * This level is used for default handlers
108      */

109     static public HashMap JavaDoc defaultLevel = null;
110
111     /**
112      * VM level provides different strategies according to the virtual machine
113      */

114     static public HashMap JavaDoc VMLevel = null;
115
116     /**
117      * Code level is used for temporary handlers
118      */

119     static public HashMap JavaDoc codeLevel = null;
120
121     static {
122         ProActiveConfiguration.load();
123         Class JavaDoc c = org.objectweb.proactive.core.runtime.RuntimeFactory.class;
124
125         // Creation of lower levels of exception handling
126
defaultLevel = new HashMap JavaDoc();
127         VMLevel = new HashMap JavaDoc();
128         codeLevel = new HashMap JavaDoc();
129
130         // We create default handler and add them to default level
131
if (logger.isDebugEnabled()) {
132             logger.debug("Initialization of default level handlers");
133         }
134         setExceptionHandler(IHandler.ID_defaultLevel, null,
135             HandlerNonFunctionalException.class, NonFunctionalException.class);
136         setExceptionHandler(IHandler.ID_defaultLevel, null,
137             HandlerCommunicationException.class,
138             ProActiveCommunicationException.class);
139         setExceptionHandler(IHandler.ID_defaultLevel, null,
140             HandlerCreationException.class, ProActiveCreationException.class);
141         setExceptionHandler(IHandler.ID_defaultLevel, null,
142             HandlerGroupException.class, ProActiveGroupException.class);
143         setExceptionHandler(IHandler.ID_defaultLevel, null,
144             HandlerMigrationException.class, ProActiveMigrationException.class);
145         setExceptionHandler(IHandler.ID_defaultLevel, null,
146             HandlerSecurityException.class, ProActiveSecurityException.class);
147         setExceptionHandler(IHandler.ID_defaultLevel, null,
148             HandlerServiceException.class, ProActiveServiceException.class);
149
150         //ProActiveConfiguration.load();
151
}
152
153     //
154
// -- CONSTRUCTORS -----------------------------------------------
155
//
156
private ProActive() {
157     }
158
159     //
160
// -- PUBLIC METHODS -----------------------------------------------
161
//
162

163     /**
164      * Creates a new ActiveObject based on classname attached to a default node in the local JVM.
165      * @param classname the name of the class to instanciate as active
166      * @param constructorParameters the parameters of the constructor.
167      * @return a reference (possibly remote) on a Stub of the newly created active object
168      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
169      * @exception NodeException if the DefaultNode cannot be created
170      */

171     public static Object JavaDoc newActive(String JavaDoc classname,
172         Object JavaDoc[] constructorParameters)
173         throws ActiveObjectCreationException, NodeException {
174         // avoid ambiguity for method parameters types
175
Node nullNode = null;
176         return newActive(classname, constructorParameters, nullNode, null, null);
177     }
178
179     /**
180      * Creates a new ActiveObject based on classname attached to the node of the given URL.
181      * @param classname the name of the class to instanciate as active
182      * @param constructorParameters the parameters of the constructor.
183      * @param nodeURL the URL of the node where to create the active object. If null, the active object
184      * is created localy on a default node
185      * @return a reference (possibly remote) on a Stub of the newly created active object
186      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
187      * @exception NodeException if the node URL cannot be resolved as an existing Node
188      */

189     public static Object JavaDoc newActive(String JavaDoc classname,
190         Object JavaDoc[] constructorParameters, String JavaDoc nodeURL)
191         throws ActiveObjectCreationException, NodeException {
192         if (nodeURL == null) {
193             // avoid ambiguity for method parameters types
194
Node nullNode = null;
195             return newActive(classname, constructorParameters, nullNode, null,
196                 null);
197         } else {
198             return newActive(classname, constructorParameters,
199                 NodeFactory.getNode(nodeURL), null, null);
200         }
201     }
202
203     /**
204      * Creates a new ActiveObject based on classname attached to the given node or on
205      * a default node in the local JVM if the given node is null.
206      * @param classname the name of the class to instanciate as active
207      * @param constructorParameters the parameters of the constructor.
208      * @param node the possibly null node where to create the active object.
209      * @return a reference (possibly remote) on a Stub of the newly created active object
210      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
211      * @exception NodeException if the node was null and that the DefaultNode cannot be created
212      */

213     public static Object JavaDoc newActive(String JavaDoc classname,
214         Object JavaDoc[] constructorParameters, Node node)
215         throws ActiveObjectCreationException, NodeException {
216         return newActive(classname, constructorParameters, node, null, null);
217     }
218
219     /**
220      * Creates a new ActiveObject based on classname attached to the given node or on
221      * a default node in the local JVM if the given node is null.
222      * The object returned is a stub class that extends the target class and that is automatically
223      * generated on the fly. The Stub class reference a the proxy object that reference the body
224      * of the active object. The body referenced by the proxy can either be local of remote,
225      * depending or the respective location of the object calling the newActive and the active object
226      * itself.
227      * @param classname the name of the class to instanciate as active
228      * @param constructorParameters the parameters of the constructor of the object
229      * to instantiate as active. If some parameters are primitive types, the wrapper
230      * class types should be given here. null can be used to specify that no parameter
231      * are passed to the constructor.
232      * @param node the possibly null node where to create the active object. If null, the active object
233      * is created localy on a default node
234      * @param activity the possibly null activity object defining the different step in the activity of the object.
235      * see the definition of the activity in the javadoc of this classe for more information.
236      * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
237      * body associated to the reified object. If null the default ProActive MataObject factory is used.
238      * @return a reference (possibly remote) on a Stub of the newly created active object
239      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
240      * @exception NodeException if the node was null and that the DefaultNode cannot be created
241      */

242     public static Object JavaDoc newActive(String JavaDoc classname,
243         Object JavaDoc[] constructorParameters, Node node, Active activity,
244         MetaObjectFactory factory)
245         throws ActiveObjectCreationException, NodeException {
246         //using default proactive node
247
if (node == null) {
248             node = NodeFactory.getDefaultNode();
249         }
250
251         if (factory == null) {
252             factory = ProActiveMetaObjectFactory.newInstance();
253         }
254
255         try {
256             return createStubObject(classname, constructorParameters, node,
257                 activity, factory);
258         } catch (MOPException e) {
259             Throwable JavaDoc t = e;
260
261             if (e.getTargetException() != null) {
262                 t = e.getTargetException();
263             }
264
265             throw new ActiveObjectCreationException(t);
266         }
267     }
268
269     /**
270             * Creates a new set of active objects based on classname attached to the given virtualnode.
271             * @param classname classname the name of the class to instanciate as active
272             * @param constructorParameters constructorParameters the parameters of the constructor.
273             * @param virtualnode The virtualnode where to create active objects. Active objects will be created
274             * on each node mapped to the given virtualnode in XML deployment descriptor.
275             * @return Object a Group of references (possibly remote) on Stub of newly created active objects
276             * @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
277             * @throws NodeException if the virtualnode was null
278             */

279     public static Object JavaDoc newActive(String JavaDoc classname,
280         Object JavaDoc[] constructorParameters, VirtualNode virtualnode)
281         throws ActiveObjectCreationException, NodeException {
282         return ProActive.newActive(classname, constructorParameters,
283             virtualnode, null, null);
284     }
285
286     /**
287      * Creates a new ActiveObject based on classname attached to the given virtualnode.
288      * @param classname classname the name of the class to instanciate as active
289      * @param constructorParameters constructorParameters the parameters of the constructor.
290      * @param virtualnode The virtualnode where to create active objects. Active objects will be created
291      * on each node mapped to the given virtualnode in XML deployment descriptor.
292      * @param activity the possibly null activity object defining the different step in the activity of the object.
293      * see the definition of the activity in the javadoc of this classe for more information.
294      * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
295      * body associated to the reified object. If null the default ProActive MataObject factory is used.
296      * @return Object a Group of references (possibly remote) on Stub of newly created active objects
297      * @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
298      * @throws NodeException if the virtualnode was null
299      *
300      */

301     public static Object JavaDoc newActive(String JavaDoc classname,
302
303         Object JavaDoc[] constructorParameters, VirtualNode virtualnode,
304         Active activity, MetaObjectFactory factory)
305         throws ActiveObjectCreationException, NodeException {
306         if (virtualnode != null) {
307             if (!virtualnode.isActivated()) {
308                 virtualnode.activate();
309             }
310             Node[] nodeTab = virtualnode.getNodes();
311             Group aoGroup = null;
312             try {
313                 aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup(
314                             classname));
315             } catch (ClassNotFoundException JavaDoc e) {
316                 throw new ActiveObjectCreationException(
317                     "Cannot create group of active objects" + e);
318             } catch (ClassNotReifiableException e) {
319                 throw new ActiveObjectCreationException(
320                     "Cannot create group of active objects" + e);
321             }
322             for (int i = 0; i < nodeTab.length; i++) {
323                 Object JavaDoc tmp = newActive(classname, constructorParameters,
324                         (Node) nodeTab[i], activity, factory);
325                 aoGroup.add(tmp);
326             }
327
328             return aoGroup.getGroupByType();
329         } else {
330             throw new NodeException(
331                 "VirtualNode is null, unable to activate the object");
332         }
333     }
334
335     /**
336       * Creates a new ProActive component over the specified base class, according to the
337       * given component parameters, and returns a reference on the component of type Component.
338       * A reference on the active object base class can be retreived through the component parameters controller's
339       * method "getStubOnReifiedObject".
340       *
341       * @param classname the name of the base class. "Composite" if the component is a composite,
342       * "ParallelComposite" if the component is a parallel composite component
343       * @param constructorParameters the parameters of the constructor of the object
344       * to instantiate as active. If some parameters are primitive types, the wrapper
345       * class types should be given here. null can be used to specify that no parameter
346       * are passed to the constructor.
347       * @param node the possibly null node where to create the active object. If null, the active object
348       * is created localy on a default node
349       * @param activity the possibly null activity object defining the different step in the activity of the object.
350       * see the definition of the activity in the javadoc of this classe for more information.
351       * @param factory should be null for components (automatically created)
352       * @param componentParameters the parameters of the component
353       * @return a component representative of type Component
354       * @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
355       * @exception NodeException if the node was null and that the DefaultNode cannot be created
356       */

357     public static Component newActiveComponent(String JavaDoc classname,
358         Object JavaDoc[] constructorParameters, Node node, Active activity,
359         MetaObjectFactory factory, ComponentParameters componentParameters)
360         throws ActiveObjectCreationException, NodeException {
361         // COMPONENTS
362
try {
363             Component boot = Fractal.getBootstrapComponent();
364             GenericFactory cf = Fractal.getGenericFactory(boot);
365             return cf.newFcInstance(componentParameters.getComponentType(),
366                 new ControllerDescription(componentParameters.getName(),
367                     componentParameters.getHierarchicalType()),
368                 new ContentDescription(classname, constructorParameters, node,
369                     activity, factory));
370         } catch (NoSuchInterfaceException e) {
371             throw new ActiveObjectCreationException(e);
372         } catch (InstantiationException JavaDoc e) {
373             if (e.getCause() instanceof NodeException) {
374                 throw new NodeException(e);
375             } else {
376                 throw new ActiveObjectCreationException(e);
377             }
378         }
379     }
380
381     /**
382      * Creates a new ProActive component over the specified base class, according to the
383      * given component parameters, and returns a reference on the component of type Component.
384      *
385      * This method allows automatic of primitive components on Virtual Nodes. In that case, the appendix
386      * -cyclicInstanceNumber-<b><i>number</i></b> is added to the name of each of these components.
387      * If the component is not a primitive, only one instance of the component is created, on the first node
388      * retreived from the specified virtual node.
389      *
390      * A reference on the active object base class can be retreived through the component parameters controller's
391      * method "getStubOnReifiedObject".
392      *
393      * @param classname the name of the base class. "Composite" if the component is a composite,
394      * "ParallelComposite" if the component is a parallel composite component
395      * @param constructorParameters the parameters of the constructor of the object
396      * to instantiate as active. If some parameters are primitive types, the wrapper
397      * class types should be given here. null can be used to specify that no parameter
398      * are passed to the constructor.
399      * @param node the possibly null node where to create the active object. If null, the active object
400      * is created localy on a default node
401      * @param activity the possibly null activity object defining the different step in the activity of the object.
402      * see the definition of the activity in the javadoc of this class for more information.
403      * @param factory should be null for components (automatically created)
404      * @param componentParameters the parameters of the component
405      * @return a typed group of component representative elements, of type Component
406      * @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
407      * @exception NodeException if the node was null and that the DefaultNode cannot be created
408      */

409     public static Component newActiveComponent(String JavaDoc className,
410         Object JavaDoc[] constructorParameters, VirtualNode vn,
411         ComponentParameters componentParameters)
412         throws ActiveObjectCreationException, NodeException {
413             // COMPONENTS
414
try {
415                 Component boot = Fractal.getBootstrapComponent();
416                 GenericFactory cf = Fractal.getGenericFactory(boot);
417                 return cf.newFcInstance(componentParameters.getComponentType(),
418                     new ControllerDescription(componentParameters.getName(),
419                         componentParameters.getHierarchicalType()),
420                     new ContentDescription(className, constructorParameters, vn));
421             } catch (NoSuchInterfaceException e) {
422                 throw new ActiveObjectCreationException(e);
423             } catch (InstantiationException JavaDoc e) {
424                 if (e.getCause() instanceof NodeException) {
425                     throw new NodeException(e);
426                 } else {
427                     throw new ActiveObjectCreationException(e);
428                 }
429             }
430     }
431
432     /**
433      * Turns the target object into an ActiveObject attached to a default node in the local JVM.
434      * The type of the stub is is the type of the existing object.
435      * @param target The object to turn active
436      * @return a reference (possibly remote) on a Stub of the existing object
437      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
438      * @exception NodeException if the DefaultNode cannot be created
439      */

440     public static Object JavaDoc turnActive(Object JavaDoc target)
441         throws ActiveObjectCreationException, NodeException {
442         return turnActive(target, (Node) null);
443     }
444
445     /**
446      * Turns the target object into an Active Object and send it to the Node
447      * identified by the given url.
448      * The type of the stub is is the type of the existing object.
449      * @param target The object to turn active
450      * @param nodeURL the URL of the node where to create the active object on. If null, the active object
451      * is created localy on a default node
452      * @return a reference (possibly remote) on a Stub of the existing object
453      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
454      * @exception NodeException if the node was null and that the DefaultNode cannot be created
455      */

456     public static Object JavaDoc turnActive(Object JavaDoc target, String JavaDoc nodeURL)
457         throws ActiveObjectCreationException, NodeException {
458         if (nodeURL == null) {
459             return turnActive(target, target.getClass().getName(), null, null,
460                 null);
461         } else {
462             return turnActive(target, target.getClass().getName(),
463                 NodeFactory.getNode(nodeURL), null, null);
464         }
465     }
466
467     /**
468      * Turns the target object into an Active Object and send it to the given Node
469      * or to a default node in the local JVM if the given node is null.
470      * The type of the stub is is the type of the target object.
471      * @param target The object to turn active
472      * @param node The Node the object should be sent to or null to create the active
473      * object in the local JVM
474      * @return a reference (possibly remote) on a Stub of the target object
475      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
476      * @exception NodeException if the node was null and that the DefaultNode cannot be created
477      */

478     public static Object JavaDoc turnActive(Object JavaDoc target, Node node)
479         throws ActiveObjectCreationException, NodeException {
480         return turnActive(target, target.getClass().getName(), node, null, null);
481     }
482
483     /**
484      * Turns the target object into an Active Object and send it to the given Node
485      * or to a default node in the local JVM if the given node is null.
486      * The type of the stub is is the type of the target object.
487      * @param target The object to turn active
488      * @param node The Node the object should be sent to or null to create the active
489      * object in the local JVM
490      * @param activity the possibly null activity object defining the different step in the activity of the object.
491      * see the definition of the activity in the javadoc of this classe for more information.
492      * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
493      * body associated to the reified object. If null the default ProActive MataObject factory is used.
494      * @return a reference (possibly remote) on a Stub of the target object
495      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
496      * @exception NodeException if the node was null and that the DefaultNode cannot be created
497      */

498     public static Object JavaDoc turnActive(Object JavaDoc target, Node node, Active activity,
499         MetaObjectFactory factory)
500         throws ActiveObjectCreationException, NodeException {
501         return turnActive(target, target.getClass().getName(), node, activity,
502             factory);
503     }
504
505     /**
506      * Turns a Java object into an Active Object and send it to a remote Node or to a
507      * local node if the given node is null.
508      * The type of the stub is given by the parameter <code>nameOfTargetType</code>.
509      * @param target The object to turn active
510      * @param nameOfTargetType the fully qualified name of the type the stub class should
511      * inherit from. That type can be less specific than the type of the target object.
512      * @param node The Node the object should be sent to or null to create the active
513      * object in the local JVM
514      * @return a reference (possibly remote) on a Stub of the target object
515      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
516      * @exception NodeException if the node was null and that the DefaultNode cannot be created
517      */

518     public static Object JavaDoc turnActive(Object JavaDoc target, String JavaDoc nameOfTargetType,
519         Node node) throws ActiveObjectCreationException, NodeException {
520         return turnActive(target, nameOfTargetType, node, null, null);
521     }
522
523     /**
524      * Turns a Java object into an Active Object and send it to a remote Node or to a
525      * local node if the given node is null.
526      * The type of the stub is given by the parameter <code>nameOfTargetType</code>.
527      * A Stub is dynamically generated for the existing object. The result of the call
528      * will be an instance of the Stub class pointing to the proxy object pointing
529      * to the body object pointing to the existing object. The body can be remote
530      * or local depending if the existing is sent remotely or not.
531      * @param target The object to turn active
532      * @param nameOfTargetType the fully qualified name of the type the stub class should
533      * inherit from. That type can be less specific than the type of the target object.
534      * @param node The Node the object should be sent to or null to create the active
535      * object in the local JVM
536      * @param activity the possibly null activity object defining the different step in the activity of the object.
537      * see the definition of the activity in the javadoc of this classe for more information.
538      * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
539      * body associated to the reified object. If null the default ProActive MataObject factory is used.
540      * @return a reference (possibly remote) on a Stub of the target object
541      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
542      * @exception NodeException if the node was null and that the DefaultNode cannot be created
543      */

544     public static Object JavaDoc turnActive(Object JavaDoc target, String JavaDoc nameOfTargetType,
545         Node node, Active activity, MetaObjectFactory factory)
546         throws ActiveObjectCreationException, NodeException {
547         if (node == null) {
548             //using default proactive node
549
node = NodeFactory.getDefaultNode();
550         }
551
552         if (factory == null) {
553             factory = ProActiveMetaObjectFactory.newInstance();
554         }
555
556         try {
557             return createStubObject(target, nameOfTargetType, node, activity,
558                 factory);
559         } catch (MOPException e) {
560             Throwable JavaDoc t = e;
561
562             if (e.getTargetException() != null) {
563                 t = e.getTargetException();
564             }
565
566             throw new ActiveObjectCreationException(t);
567         }
568     }
569
570     /**
571      * Turns a Java object into an Active Object and send it to remote Nodes mapped to the given virtualnode in
572      * the XML deployment descriptor.
573      * The type of the stub is given by the parameter <code>nameOfTargetType</code>.
574      * @param target The object to turn active
575      * @param nameOfTargetType the fully qualified name of the type the stub class should
576      * inherit from. That type can be less specific than the type of the target object.
577      * @param virtualnode The VirtualNode where the target object will be turn into an Active Object
578      * Target object will be turned into an Active Object on each node mapped to the given virtualnode in XML deployment descriptor.
579      * @return an array of references (possibly remote) on a Stub of the target object
580      * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
581      * @exception NodeException if the node was null and that the DefaultNode cannot be created
582      */

583     public static Object JavaDoc turnActive(Object JavaDoc target, String JavaDoc nameOfTargetType,
584         VirtualNode virtualnode)
585         throws ActiveObjectCreationException, NodeException {
586         if (virtualnode != null) {
587             Node[] nodeTab = virtualnode.getNodes();
588             Group aoGroup = null;
589             try {
590                 aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup(
591                             target.getClass().getName()));
592             } catch (ClassNotFoundException JavaDoc e) {
593                 throw new ActiveObjectCreationException(
594                     "Cannot create group of active objects" + e);
595             } catch (ClassNotReifiableException e) {
596                 throw new ActiveObjectCreationException(
597                     "Cannot create group of active objects" + e);
598             }
599
600             for (int i = 0; i < nodeTab.length; i++) {
601                 Object JavaDoc tmp = turnActive(target, nameOfTargetType,
602                         (Node) nodeTab[i], null, null);
603                 aoGroup.add(tmp);
604             }
605
606             return aoGroup;
607         } else {
608             throw new NodeException(
609                 "VirtualNode is null, unable to active the object");
610         }
611     }
612
613     /**
614      * Registers an active object into a RMI registry. In fact it is the
615      * remote version of the body of the active object that is registered into the
616      * RMI Registry under the given URL.
617      * @param obj the active object to register.
618      * @param url the url under which the remote body is registered.
619      * @exception java.io.IOException if the remote body cannot be registered
620      */

621     public static void register(Object JavaDoc obj, String JavaDoc url)
622         throws java.io.IOException JavaDoc {
623         // Check if obj is really a reified object
624
if (!(MOP.isReifiedObject(obj))) {
625             throw new java.io.IOException JavaDoc("The given object " + obj +
626                 " is not a reified object");
627         }
628
629         // Find the appropriate remoteBody
630
org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy();
631
632         if (myProxy == null) {
633             throw new java.io.IOException JavaDoc(
634                 "Cannot find a Proxy on the stub object: " + obj);
635         }
636
637         BodyProxy myBodyProxy = (BodyProxy) myProxy;
638         UniversalBody body = myBodyProxy.getBody().getRemoteAdapter();
639
640         if (body instanceof RemoteBodyAdapter) {
641             RemoteBodyAdapter.register((RemoteBodyAdapter) body, url);
642             if (logger.isInfoEnabled()) {
643                 logger.info("Success at binding url " + url);
644             }
645         } else {
646             if (body instanceof IbisRemoteBodyAdapter) {
647                 IbisRemoteBodyAdapter.register((IbisRemoteBodyAdapter) body, url);
648                 if (logger.isInfoEnabled()) {
649                     logger.info("Success at binding url " + url);
650                 }
651             } else {
652                 throw new java.io.IOException JavaDoc(
653                     "Cannot reconize the type of this UniversalBody: " +
654                     body.getClass().getName());
655             }
656         }
657     }
658
659     /**
660      * Unregisters an active object previously registered into a RMI registry.
661      * @param url the url under which the active object is registered.
662      * @exception java.io.IOException if the remote object cannot be removed from the registry
663      */

664     public static void unregister(String JavaDoc url) throws java.io.IOException JavaDoc {
665         RemoteBodyAdapter.unregister(url);
666         if (logger.isDebugEnabled()) {
667             logger.debug("Success at unbinding url " + url);
668         }
669     }
670
671     /**
672      * Looks-up an active object previously registered in a RMI registry. In fact it is the
673      * remote version of the body of an active object that can be registered into the
674      * RMI Registry under a given URL. If the lookup is successful, the method reconstructs
675      * a Stub-Proxy couple and point it to the RemoteBody found.
676      * @param classname the fully qualified name of the class the stub should inherit from.
677      * @param url the url under which the remote body is registered.
678      * @return a remote reference on a Stub of type <code>classname</code> pointing to the
679      * remote body found
680      * @exception java.io.IOException if the remote body cannot be found under the given url
681      * or if the object found is not of type RemoteBody
682      * @exception ActiveObjectCreationException if the stub-proxy couple cannot be created
683      */

684     public static Object JavaDoc lookupActive(String JavaDoc classname, String JavaDoc url)
685         throws ActiveObjectCreationException, java.io.IOException JavaDoc {
686         UniversalBody b = null;
687         if ("ibis".equals(System.getProperty("proactive.communication.protocol"))) {
688             b = IbisRemoteBodyAdapter.lookup(url);
689         } else {
690             b = RemoteBodyAdapter.lookup(url);
691         }
692
693         try {
694             return createStubObject(classname, b);
695         } catch (MOPException e) {
696             Throwable JavaDoc t = e;
697
698             if (e.getTargetException() != null) {
699                 t = e.getTargetException();
700             }
701
702             throw new ActiveObjectCreationException("Exception occured when trying to create stub-proxy",
703                 t);
704         }
705     }
706
707     /**
708      * Blocks the calling thread until the object <code>future</code>
709      * is available. <code>future</code> must be the result object of an
710      * asynchronous call. Usually the the wait by necessity model take care
711      * of blocking the caller thread asking for a result not yet available.
712      * This method allows to block before the result is first used.
713      */

714     public static void waitFor(Object JavaDoc future) {
715         // If the object is not reified, it cannot be a future
716
if ((MOP.isReifiedObject(future)) == false) {
717             return;
718         } else {
719             org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
720
721             // If it is reified but its proxy is not of type future, we cannot wait
722
if (!(theProxy instanceof Future)) {
723                 return;
724             } else {
725                 ((Future) theProxy).waitFor();
726             }
727         }
728     }
729
730     /**
731      * Returns a <code>ProActiveDescriptor</code> that gives an object representation
732      * of the XML document located at the given url.
733      * @param xmlDescriptorUrl. The url of the XML document
734      * @return ProActiveDescriptor. The object representation of the XML document
735      * @throws ProActiveException if a problem occurs during the creation of the object
736      * @see org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor
737      * @see org.objectweb.proactive.core.descriptor.data.VirtualNode
738      * @see org.objectweb.proactive.core.descriptor.data.VirtualMachine
739      */

740     public static ProActiveDescriptor getProactiveDescriptor(
741         String JavaDoc xmlDescriptorUrl) throws ProActiveException {
742        RuntimeFactory.getDefaultRuntime();
743         if (!xmlDescriptorUrl.startsWith("file:")) {
744             xmlDescriptorUrl = "file:" + xmlDescriptorUrl;
745         }
746         ProActiveRuntimeImpl part = (ProActiveRuntimeImpl) ProActiveRuntimeImpl.getProActiveRuntime();
747         if (part.getDescriptor(xmlDescriptorUrl) != null) {
748             return part.getDescriptor(xmlDescriptorUrl);
749         }
750
751         try {
752             if (logger.isInfoEnabled()) {
753                 logger.info("************* Reading deployment descriptor: " +
754                     xmlDescriptorUrl + " ********************");
755             }
756             ProActiveDescriptorHandler proActiveDescriptorHandler = ProActiveDescriptorHandler.createProActiveDescriptor(xmlDescriptorUrl);
757             ProActiveDescriptor pad = (ProActiveDescriptor) proActiveDescriptorHandler.getResultObject();
758             part.registerDescriptor(xmlDescriptorUrl, pad);
759             return pad;
760         } catch (org.xml.sax.SAXException JavaDoc e) {
761             e.printStackTrace();
762             logger.fatal(
763                 "a problem occurs when getting the proActiveDescriptor");
764             throw new ProActiveException(e);
765         } catch (java.io.IOException JavaDoc e) {
766             e.printStackTrace();
767             logger.fatal(
768                 "a problem occurs during the ProActiveDescriptor object creation");
769             throw new ProActiveException(e);
770         }
771     }
772
773     /**
774      * Registers locally the given VirtualNode in a registry such RMIRegistry or JINI Lookup Service.
775      * The VirtualNode to register must exist on the local runtime. This is done when using XML Deployment Descriptors
776      * @param virtualNode the VirtualNode to register.
777      * @param registrationProtocol The protocol used for registration. At this time RMI and JINI are supported
778      * @param replacePreviousBinding
779      * @throws ProActiveException If the VirtualNode with the given name does not exist on the local runtime
780      */

781     public static void registerVirtualNode(VirtualNode virtualNode,
782         String JavaDoc registrationProtocol, boolean replacePreviousBinding)
783         throws ProActiveException {
784         if (!(virtualNode instanceof VirtualNodeImpl)) {
785             throw new ProActiveException(
786                 "Cannot register such virtualNode since it results from a lookup!");
787         }
788         String JavaDoc virtualnodeName = virtualNode.getName();
789         ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(registrationProtocol);
790         VirtualNode vn = part.getVirtualNode(virtualnodeName);
791         if (vn == null) {
792             throw new ProActiveException("VirtualNode " + virtualnodeName +
793                 " does not exist !");
794         }
795         part.registerVirtualNode(UrlBuilder.appendVnSuffix(virtualnodeName),
796             replacePreviousBinding);
797     }
798
799     /**
800      * Looks-up a VirtualNode previously registered in a registry(RMI or JINI)
801      * @param url The url where to perform the lookup
802      * @param protocol The protocol used to perform the lookup(RMI and JINI are supported)
803      * @return VirtualNode The virtualNode returned by the lookup
804      * @throws ProActiveException If no objects are bound with the given url
805      */

806     public static VirtualNode lookupVirtualNode(String JavaDoc url, String JavaDoc protocol)
807         throws ProActiveException {
808         ProActiveRuntime remoteProActiveRuntime = null;
809         try {
810             remoteProActiveRuntime = RuntimeFactory.getRuntime(UrlBuilder.buildVirtualNodeUrl(
811                         url), protocol);
812         } catch (UnknownHostException JavaDoc ex) {
813             throw new ProActiveException(ex);
814         }
815         return remoteProActiveRuntime.getVirtualNode(UrlBuilder.getNameFromUrl(
816                 url));
817     }
818
819     /**
820      * Unregisters the virtualNode previoulsy registered in a registry such as JINI or RMI.
821      * Calling this method removes the VirtualNode from the local runtime.
822      * @param virtualNode The VirtualNode to unregister
823      * @throws ProActiveException if a problem occurs whle unregistering the VirtualNode
824      */

825     public static void unregisterVirtualNode(VirtualNode virtualNode)
826         throws ProActiveException {
827         //VirtualNode vn = ((VirtualNodeStrategy)virtualNode).getVirtualNode();
828
if (!(virtualNode instanceof VirtualNodeImpl)) {
829             throw new ProActiveException(
830                 "Cannot unregister such virtualNode since it results from a lookup!");
831         }
832         String JavaDoc virtualNodeName = virtualNode.getName();
833         ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(((VirtualNodeImpl) virtualNode).getRegistrationProtocol());
834         part.unregisterVirtualNode(UrlBuilder.appendVnSuffix(
835                 virtualNode.getName()));
836         if (logger.isInfoEnabled()) {
837             logger.info("Success at unbinding " + virtualNodeName);
838         }
839     }
840
841     /**
842      * When an active object is created, it is associated with a Body that takes care
843      * of all non fonctionnal properties. Assuming that the active object is only
844      * accessed by the different Stub objects, all method calls end-up as Requests sent
845      * to this Body. Therefore the only thread calling the method of the active object
846      * is the active thread managed by the body. There is an unique mapping between the
847      * active thread and the body responsible for it. From any method in the active object
848      * the current thread caller of the method is the active thread. When a reified method wants
849      * to get a reference to the Body associated to the active object, it can invoke this
850      * method. Assuming that the current thread is the active thread, the associated body
851      * is returned.
852      * @return the body associated to the active object whose active thread is calling
853      * this method.
854      */

855     public static Body getBodyOnThis() {
856         return LocalBodyStore.getInstance().getCurrentThreadBody();
857     }
858
859     /**
860      * Returns a Stub-Proxy couple pointing to the local body associated to the active
861      * object whose active thread is calling this method.
862      * @return a Stub-Proxy couple pointing to the local body.
863      * @see #getBodyOnThis
864      */

865     public static StubObject getStubOnThis() {
866         Body body = getBodyOnThis();
867
868         if (logger.isDebugEnabled()) {
869             //logger.debug("ProActive: getStubOnThis() returns " + body);
870
}
871         if (body == null) {
872             return null;
873         }
874
875         return getStubForBody(body);
876     }
877
878     /**
879      * Migrates the active object whose active thread is calling this method to the
880      * same location as the active object given in parameter.
881      * This method must be called from an active object using the active thread as the
882      * current thread will be used to find which active object is calling the method.
883      * The object given as destination must be an active object.
884      * @param activeObject the active object indicating the destination of the migration.
885      * @exception MigrationException if the migration fails
886      * @see #getBodyOnThis
887      */

888     public static void migrateTo(Object JavaDoc activeObject) throws MigrationException {
889         migrateTo(getNodeFromURL(getNodeURLFromActiveObject(activeObject)));
890     }
891
892     /**
893      * Migrates the active object whose active thread is calling this method to the
894      * node caracterized by the given url.
895      * This method must be called from an active object using the active thread as the
896      * current thread will be used to find which active object is calling the method.
897      * The url must be the url of an existing node.
898      * @param nodeURL the url of an existing where to migrate to.
899      * @exception MigrationException if the migration fails
900      * @see #getBodyOnThis
901      */

902     public static void migrateTo(String JavaDoc nodeURL) throws MigrationException {
903         if (logger.isDebugEnabled()) {
904             logger.debug("migrateTo " + nodeURL);
905         }
906         ProActive.migrateTo(getNodeFromURL(nodeURL));
907     }
908
909     /**
910      * Migrates the active object whose active thread is calling this method to the
911      * given node.
912      * This method must be called from an active object using the active thread as the
913      * current thread will be used to find which active object is calling the method.
914      * @param node an existing node where to migrate to.
915      * @exception MigrationException if the migration fails
916      * @see #getBodyOnThis
917      */

918     public static void migrateTo(Node node) throws MigrationException {
919         if (logger.isDebugEnabled()) {
920             logger.debug("migrateTo " + node);
921         }
922         Body bodyToMigrate = getBodyOnThis();
923         if (!(bodyToMigrate instanceof Migratable)) {
924             throw new MigrationException(
925                 "This body cannot migrate. It doesn't implement Migratable interface");
926         }
927
928         ((Migratable) bodyToMigrate).migrateTo(node);
929     }
930
931     /**
932      * Migrates the given body to the same location as the active object given in parameter.
933      * This method can be called from any object and does not perform the migration.
934      * Instead it generates a migration request that is sent to the targeted body.
935      * Two strategies are possible :
936      * - the request is high priority and is processed before all existing requests
937      * the body may have received (priority = true)
938      * - the request is normal priority and is processed after all existing requests
939      * the body may have received (priority = false)
940      * The object given as destination must be an active object.
941      * @param bodyToMigrate the body to migrate.
942      * @param activeObject the active object indicating the destination of the migration.
943      * @param priority a boolean indicating the priority of the migration request sent to the body.
944      * @exception MigrationException if the migration fails
945      */

946     public static void migrateTo(Body bodyToMigrate, Object JavaDoc activeObject,
947         boolean priority) throws MigrationException {
948         migrateTo(bodyToMigrate,
949             getNodeFromURL(getNodeURLFromActiveObject(activeObject)), priority);
950     }
951
952     /**
953      * Migrates the given body to the node caracterized by the given url.
954      * This method can be called from any object and does not perform the migration.
955      * Instead it generates a migration request that is sent to the targeted body.
956      * Two strategies are possible :
957      * - the request is high priority and is processed before all existing requests
958      * the body may have received (priority = true)
959      * - the request is normal priority and is processed after all existing requests
960      * the body may have received (priority = false)
961      * The object given as destination must be an active object.
962      * @param bodyToMigrate the body to migrate.
963      * @param nodeURL the url of an existing where to migrate to.
964      * @param priority a boolean indicating the priority of the migration request sent to the body.
965      * @exception MigrationException if the migration fails
966      */

967     public static void migrateTo(Body bodyToMigrate, String JavaDoc nodeURL,
968         boolean priority) throws MigrationException {
969         ProActive.migrateTo(bodyToMigrate, getNodeFromURL(nodeURL), priority);
970     }
971
972     /**
973      * Migrates the body <code>bodyToMigrate</code> to the given node.
974      * This method can be called from any object and does not perform the migration.
975      * Instead it generates a migration request that is sent to the targeted body.
976      * Two strategies are possible :
977      * - the request is high priority and is processed before all existing requests
978      * the body may have received (priority = true)
979      * - the request is normal priority and is processed after all existing requests
980      * the body may have received (priority = false)
981      * The object given as destination must be an active object.
982      * @param bodyToMigrate the body to migrate.
983      * @param node an existing node where to migrate to.
984      * @param priority a boolean indicating the priority of the migration request sent to the body.
985      * @exception MigrationException if the migration fails
986      */

987     public static void migrateTo(Body bodyToMigrate, Node node, boolean priority)
988         throws MigrationException {
989         if (!(bodyToMigrate instanceof Migratable)) {
990             throw new MigrationException(
991                 "This body cannot migrate. It doesn't implement Migratable interface");
992         }
993
994         Object JavaDoc[] arguments = { node };
995
996         try {
997             BodyRequest request = new BodyRequest(bodyToMigrate, "migrateTo",
998                     new Class JavaDoc[] { Node.class }, arguments, priority);
999             request.send(bodyToMigrate);
1000        } catch (NoSuchMethodException JavaDoc e) {
1001            throw new MigrationException("Cannot find method migrateTo this body. Non sense since the body is instance of Migratable",
1002                e);
1003        } catch (java.io.IOException JavaDoc e) {
1004            throw new MigrationException("Cannot send the request to migrate", e);
1005        }
1006    }
1007
1008    /**
1009     * Blocks the calling thread until one of the futures in the vector is available.
1010     * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
1011     * @param futures vector of futures
1012     * @return index of the available future in the vector
1013     */

1014    public static int waitForAny(java.util.Vector JavaDoc futures) {
1015        FuturePool fp = getBodyOnThis().getFuturePool();
1016
1017        synchronized (fp) {
1018            while (true) {
1019                java.util.Iterator JavaDoc it = futures.iterator();
1020                int index = 0;
1021
1022                while (it.hasNext()) {
1023                    Object JavaDoc current = it.next();
1024
1025                    if (!(isAwaited(current))) {
1026                        return index;
1027                    }
1028
1029                    index++;
1030                }
1031                fp.waitForReply();
1032            }
1033        }
1034    }
1035
1036    /**
1037     * Blocks the calling thread until all futures in the vector are available.
1038     * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
1039     * @param futures vector of futures
1040     */

1041    public static void waitForAll(java.util.Vector JavaDoc futures) {
1042        FuturePool fp = getBodyOnThis().getFuturePool();
1043
1044        synchronized (fp) {
1045            boolean oneIsMissing = true;
1046
1047            while (oneIsMissing) {
1048                oneIsMissing = false;
1049
1050                java.util.Iterator JavaDoc it = futures.iterator();
1051
1052                while (it.hasNext()) {
1053                    Object JavaDoc current = it.next();
1054
1055                    if (isAwaited(current)) {
1056                        oneIsMissing = true;
1057                    }
1058                }
1059
1060                if (oneIsMissing) {
1061                    fp.waitForReply();
1062                }
1063            }
1064        }
1065    }
1066
1067    /**
1068     * Blocks the calling thread until the N-th of the futures in the vector is available.
1069     * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
1070     * @param futures vector of futures
1071     */

1072    public static void waitForTheNth(java.util.Vector JavaDoc futures, int n) {
1073        FuturePool fp = getBodyOnThis().getFuturePool();
1074
1075        synchronized (fp) {
1076            Object JavaDoc current = futures.get(n);
1077
1078            if (isAwaited(current)) {
1079                waitFor(current);
1080            }
1081        }
1082    }
1083
1084    /**
1085     * Return false if the object <code>future</code> is available.
1086     * This method is recursive, i.e. if result of future is a future too,
1087     * <CODE>isAwaited</CODE> is called again on this result, and so on.
1088     */

1089    public static boolean isAwaited(Object JavaDoc future) {
1090        // If the object is not reified, it cannot be a future
1091
if ((MOP.isReifiedObject(future)) == false) {
1092            return false;
1093        } else {
1094            org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
1095
1096            // If it is reified but its proxy is not of type future, we cannot wait
1097
if (!(theProxy instanceof Future)) {
1098                return false;
1099            } else {
1100                if (((Future) theProxy).isAwaited()) {
1101                    return true;
1102                } else {
1103                    return isAwaited(((Future) theProxy).getResult());
1104                }
1105            }
1106        }
1107    }
1108
1109    /**
1110     * Return the object contains by the future (ie its target).
1111     * If parameter is not a future, it is returned.
1112     * A wait-by-necessity occurs if future is not available.
1113     * This method is recursive, i.e. if result of future is a future too,
1114     * <CODE>getFutureValue</CODE> is called again on this result, and so on.
1115     */

1116    public static Object JavaDoc getFutureValue(Object JavaDoc future) {
1117        // If the object is not reified, it cannot be a future
1118
if ((MOP.isReifiedObject(future)) == false) {
1119            return future;
1120        } else {
1121            org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
1122
1123            // If it is reified but its proxy is not of type future, we cannot wait
1124
if (!(theProxy instanceof Future)) {
1125                return future;
1126            } else {
1127                Object JavaDoc o = ((Future) theProxy).getResult();
1128
1129                return getFutureValue(o);
1130            }
1131        }
1132    }
1133
1134    /**
1135     * Enable the automatic continuation mechanism for this active object.
1136     */

1137    public static void enableAC(Object JavaDoc obj) throws java.io.IOException JavaDoc {
1138        // Check if obj is really a reified object
1139
if (!(MOP.isReifiedObject(obj))) {
1140            throw new ProActiveRuntimeException("The given object " + obj +
1141                " is not a reified object");
1142        }
1143
1144        // Find the appropriate remoteBody
1145
org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy();
1146
1147        if (myProxy == null) {
1148            throw new ProActiveRuntimeException(
1149                "Cannot find a Proxy on the stub object: " + obj);
1150        }
1151
1152        BodyProxy myBodyProxy = (BodyProxy) myProxy;
1153        UniversalBody body = myBodyProxy.getBody().getRemoteAdapter();
1154        body.enableAC();
1155    }
1156
1157    /**
1158     * Disable the automatic continuation mechanism for this active object.
1159     */

1160    public static void disableAC(Object JavaDoc obj) throws java.io.IOException JavaDoc {
1161        // Check if obj is really a reified object
1162
if (!(MOP.isReifiedObject(obj))) {
1163            throw new ProActiveRuntimeException("The given object " + obj +
1164                " is not a reified object");
1165        }
1166
1167        // Find the appropriate remoteBody
1168
org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy();
1169
1170        if (myProxy == null) {
1171            throw new ProActiveRuntimeException(
1172                "Cannot find a Proxy on the stub object: " + obj);
1173        }
1174
1175        BodyProxy myBodyProxy = (BodyProxy) myProxy;
1176        UniversalBody body = myBodyProxy.getBody().getRemoteAdapter();
1177        body.disableAC();
1178    }
1179
1180    /**
1181     * Set an immmediate execution for the active object obj, ie request of name methodName
1182     * will be executed by the calling thread, and not add in the request queue.
1183     * BE CAREFULL : for the first release of this method, do not make use of getCurrentThreadBody nor
1184     * getStubOnThis in the method defined by methodName !!
1185     */

1186    public static void setImmediateService(Object JavaDoc obj, String JavaDoc methodName)
1187        throws java.io.IOException JavaDoc {
1188        // Check if obj is really a reified object
1189
if (!(MOP.isReifiedObject(obj))) {
1190            throw new ProActiveRuntimeException("The given object " + obj +
1191                " is not a reified object");
1192        }
1193
1194        // Find the appropriate remoteBody
1195
org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy();
1196
1197        if (myProxy == null) {
1198            throw new ProActiveRuntimeException(
1199                "Cannot find a Proxy on the stub object: " + obj);
1200        }
1201
1202        BodyProxy myBodyProxy = (BodyProxy) myProxy;
1203        UniversalBody body = myBodyProxy.getBody().getRemoteAdapter();
1204        body.setImmediateService(methodName);
1205    }
1206
1207    /**
1208     * @return the jobId associated with the object calling this method
1209     */

1210    public static String JavaDoc getJobId() {
1211        return ProActive.getBodyOnThis().getJobID();
1212    }
1213
1214    /**
1215     * Search an appropriate handler for a given non functional exception.
1216     * We first search in the highest level a handler for the real class of the exception. If the search fails, we try
1217     * with mother classes. When no handler is available in this level, we go down into the hierarchy of levels.
1218     * @param ex Exception for which we search a handler.
1219     * @return A reliable handler or null if no handler is available
1220     */

1221
1222    public static IHandler searchExceptionHandler(NonFunctionalException ex) {
1223        // an handler
1224
IHandler handler = null;
1225
1226        // Try to get an handler from code level
1227
if ((handler = searchExceptionHandler(ex, codeLevel,
1228                        IHandler.ID_codeLevel)) != null) {
1229            return handler;
1230        }
1231
1232        // Try to get an handler from object level (active object, future, proxy)
1233
// if (obj & (handler = searchExceptionHandler(ex, obj.getHandlerLevel())) != null) return handler;
1234
// Try to get an handler from VM level
1235
if ((handler = searchExceptionHandler(ex, VMLevel, IHandler.ID_VMLevel)) != null) {
1236            return handler;
1237        }
1238
1239        // Try to get an handler from default level or return null
1240
return searchExceptionHandler(ex, defaultLevel, IHandler.ID_defaultLevel);
1241    }
1242
1243    /**
1244     * Search an appropriate handler for a given non functional exception.
1245     * We first search in the highest level a handler for the real class of the exception. If the search fails, we try
1246     * with mother classes. When no handler is available in this level, we go down into the hierarchy of levels.
1247     * @param ex Exception for which we search a handler.
1248     * @param level The level where handlers are searched
1249     * @return A reliable handler or null if no handler is available
1250     */

1251    public static IHandler searchExceptionHandler(NonFunctionalException ex,
1252        HashMap JavaDoc level, int levelID) {
1253        // Test the capacity of the level
1254
if (level.isEmpty()) {
1255            return null;
1256        }
1257
1258        // We get the class of the raised exception
1259
Class JavaDoc exClass = ex.getClass();
1260        IHandler handler = null;
1261
1262        // Then we search if a handler exists in the given level
1263
// We stop when we find either right handler or none
1264
while ((handler == null) &&
1265                (exClass.getName().compareTo(NonFunctionalException.class.getName()) != 0)) {
1266            // Information
1267
if (logger.isDebugEnabled()) {
1268                // logger.debug("*** SEARCHING HANDLER FOR " + exClass.getName() + " IN LEVEL " + levelID);
1269
}
1270
1271            // Research algorithm
1272
if (level.containsKey(exClass)) {
1273                try {
1274                    handler = (IHandler) Class.forName(((Class JavaDoc) level.get(
1275                                exClass)).getName()).newInstance();
1276                } catch (Exception JavaDoc e) {
1277                    if (e instanceof ClassNotFoundException JavaDoc) {
1278                        if (logger.isDebugEnabled()) {
1279                            // logger.debug("*** Handler for " + exClass.getName() + " is invalid");
1280
}
1281                        break;
1282                    } else {
1283                        e.printStackTrace();
1284                    }
1285                }
1286            } else {
1287                exClass = exClass.getSuperclass();
1288            }
1289        }
1290
1291        // We return the handler
1292
return handler;
1293    }
1294
1295    /**
1296     * Add a new handler to a specific level.
1297     * Any existing handler is overwritten except at default level.
1298     * @param level ID representating the level where handlers are added.
1299     * @param obj The object containing a level. It is set to null if the <code>ID_level</code> represents default or VM level.
1300     * @param hName The handler associated to a non functional exception.
1301     * @param exName The class of the non functional exception which require a handler. It must be a subclass of <code>NonFunctionalException</code>.
1302     */

1303    public static void setExceptionHandler(int ID_level, Object JavaDoc obj,
1304        Class JavaDoc hName, Class JavaDoc exName) {
1305        // Information
1306
// System.out.print("*** SET [" +hName.getName() + "] FOR [" + exName.getName() + "] AT LEVEL " + ID_level + " ");
1307
// The correct level is identified
1308
HashMap JavaDoc level = null;
1309        switch (ID_level) {
1310        case (IHandler.ID_defaultLevel):
1311            level = defaultLevel;
1312            break;
1313        case (IHandler.ID_VMLevel):
1314            level = VMLevel;
1315            break;
1316        case (IHandler.ID_activeObjectLevel): // level = obj.getHandlerLevel();
1317
break;
1318        case (IHandler.ID_proxyLevel): // level = obj.getHandlerLevel();
1319
break;
1320        case (IHandler.ID_futureLevel): // level = obj.getHandlerLevel();
1321
break;
1322        case (IHandler.ID_codeLevel): // level = codeLevel;
1323
break;
1324        }
1325
1326        // We don't want to modify the default level except if no handler exists
1327
if (level == defaultLevel) {
1328            if (level.get(exName) == null) {
1329                level.put(exName, hName);
1330                if (logger.isDebugEnabled()) {
1331                    // logger.debug("...OK");
1332
}
1333            } else {
1334                if (logger.isDebugEnabled()) {
1335                    // logger.debug("...FAILED");
1336
}
1337            }
1338        } else {
1339            level.put(exName, hName);
1340            if (logger.isDebugEnabled()) {
1341                //logger.debug("...OK");
1342
}
1343        }
1344    }
1345
1346    /**
1347     * Remove the handler associated to a non functional exception.
1348     * @param level ID representating the level from where handlers are deleted.
1349     * @param obj The object containing a level. It is set to null if the <code>ID_level</code> represents default or VM level.
1350     * @param exName A non functional exception whoch does not require handler anymore at the given level.
1351     */

1352    public static IHandler unsetExceptionHandler(int ID_level, Object JavaDoc obj,
1353        Class JavaDoc exName) {
1354        // We keep a trace of the deleted handler
1355
IHandler handler = null;
1356
1357        // The correct level is identified
1358
HashMap JavaDoc level = null;
1359        switch (ID_level) {
1360        case (IHandler.ID_defaultLevel):
1361            level = defaultLevel;
1362            break;
1363        case (IHandler.ID_VMLevel):
1364            level = VMLevel;
1365            break;
1366        case (IHandler.ID_activeObjectLevel): // level = obj.getHandlerLevel();
1367
break;
1368        case (IHandler.ID_proxyLevel): // level = obj.getHandlerLevel();
1369
break;
1370        case (IHandler.ID_futureLevel): // level = obj.getHandlerLevel();
1371
break;
1372        case (IHandler.ID_codeLevel): // level = codeLevel;
1373
break;
1374        }
1375
1376        // We don't want to modify default level
1377
if (level != defaultLevel) {
1378            try {
1379                String JavaDoc hName = (String JavaDoc) ((Class JavaDoc) level.remove(exName)).getName();
1380                if (hName != null) {
1381                    handler = (IHandler) Class.forName(hName).newInstance();
1382                    if (logger.isDebugEnabled()) {
1383                        // logger.debug("*** REMOVE [" + handler.getClass().getName() + "] FOR [" + exName.getName() + "] AT LEVEL " + ID_level);
1384
}
1385                } else {
1386                    if (logger.isDebugEnabled()) {
1387                        //logger.debug("*** CAN'T REMOVE ANY HANDLER from DEFAULT LEVEL !");
1388
}
1389                }
1390            } catch (Exception JavaDoc e) {
1391                e.printStackTrace();
1392            }
1393        } else {
1394            if (logger.isDebugEnabled()) {
1395                // logger.debug("*** CAN'T REMOVE ANY HANDLER from DEFAULT LEVEL !");
1396
}
1397        }
1398
1399        // We return the deleted handler
1400
return handler;
1401    }
1402
1403    //
1404
// -- PRIVATE METHODS -----------------------------------------------
1405
//
1406
private static String JavaDoc getNodeURLFromActiveObject(Object JavaDoc o)
1407        throws MigrationException {
1408        //first we check if the parameter is an active object,
1409
if (!org.objectweb.proactive.core.mop.MOP.isReifiedObject(o)) {
1410            throw new MigrationException(
1411                "The parameter is not an active object");
1412        }
1413
1414        //now we get a reference on the remoteBody of this guy
1415
BodyProxy destProxy = (BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) o).getProxy();
1416
1417        return destProxy.getBody().getNodeURL();
1418    }
1419
1420    private static Node getNodeFromURL(String JavaDoc url) throws MigrationException {
1421        try {
1422            return NodeFactory.getNode(url);
1423        } catch (NodeException e) {
1424            throw new MigrationException("The node of given URL " + url +
1425                " cannot be localized", e);
1426        }
1427    }
1428
1429    // -------------------------------------------------------------------------------------------
1430
//
1431
// STUB CREATION
1432
//
1433
// -------------------------------------------------------------------------------------------
1434
private static StubObject getStubForBody(Body body) {
1435        try {
1436            return createStubObject(body.getReifiedObject(),
1437                new Object JavaDoc[] { body },
1438                body.getReifiedObject().getClass().getName());
1439        } catch (MOPException e) {
1440            throw new ProActiveRuntimeException(
1441                "Cannot create Stub for this Body e=" + e);
1442        }
1443    }
1444
1445    private static Object JavaDoc createStubObject(String JavaDoc className, UniversalBody body)
1446        throws MOPException {
1447        return createStubObject(className, null, new Object JavaDoc[] { body });
1448    }
1449
1450    private static Object JavaDoc createStubObject(String JavaDoc className,
1451        Object JavaDoc[] constructorParameters, Node node, Active activity,
1452        MetaObjectFactory factory) throws MOPException {
1453        return createStubObject(className, constructorParameters,
1454            new Object JavaDoc[] { node, activity, factory, ProActive.getJobId() });
1455    }
1456
1457    private static Object JavaDoc createStubObject(String JavaDoc className,
1458        Object JavaDoc[] constructorParameters, Object JavaDoc[] proxyParameters)
1459        throws MOPException {
1460        try {
1461            return MOP.newInstance(className, constructorParameters,
1462                Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters);
1463        } catch (ClassNotFoundException JavaDoc e) {
1464            throw new ConstructionOfProxyObjectFailedException(
1465                "Class can't be found e=" + e);
1466        }
1467    }
1468
1469    private static Object JavaDoc createStubObject(Object JavaDoc target,
1470        String JavaDoc nameOfTargetType, Node node, Active activity,
1471        MetaObjectFactory factory) throws MOPException {
1472        return createStubObject(target,
1473            new Object JavaDoc[] { node, activity, factory, ProActive.getJobId() },
1474            nameOfTargetType);
1475    }
1476
1477    private static StubObject createStubObject(Object JavaDoc object,
1478        Object JavaDoc[] proxyParameters, String JavaDoc nameOfTargetType)
1479        throws MOPException {
1480        try {
1481            return (StubObject) MOP.turnReified(nameOfTargetType,
1482                Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters, object);
1483        } catch (ClassNotFoundException JavaDoc e) {
1484            throw new ConstructionOfProxyObjectFailedException(
1485                "Class can't be found e=" + e);
1486        }
1487    }
1488}
1489
Popular Tags