org/objectweb/proactive/core/component/identity/ProActiveComponentImpl.java

00001 /* 
00002  * ################################################################
00003  * 
00004  * ProActive: The Java(TM) library for Parallel, Distributed, 
00005  *            Concurrent computing with Security and Mobility
00006  * 
00007  * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
00008  * Contact: proactive@objectweb.org
00009  * 
00010  * This library is free software; you can redistribute it and/or
00011  * modify it under the terms of the GNU Lesser General Public
00012  * License as published by the Free Software Foundation; either
00013  * version 2.1 of the License, or any later version.
00014  *  
00015  * This library is distributed in the hope that it will be useful,
00016  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00017  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018  * Lesser General Public License for more details.
00019  * 
00020  * You should have received a copy of the GNU Lesser General Public
00021  * License along with this library; if not, write to the Free Software
00022  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
00023  * USA
00024  *  
00025  *  Initial developer(s):               The ProActive Team
00026  *                        http://www.inria.fr/oasis/ProActive/contacts.html
00027  *  Contributor(s): 
00028  * 
00029  * ################################################################
00030  */ 
00031 package org.objectweb.proactive.core.component.identity;
00032 
00033 import java.io.Serializable;
00034 import java.lang.reflect.Constructor;
00035 import java.util.ArrayList;
00036 import java.util.HashMap;
00037 import java.util.Iterator;
00038 import java.util.List;
00039 import java.util.Map;
00040 import java.util.Vector;
00041 
00042 import org.apache.log4j.Logger;
00043 import org.objectweb.fractal.api.Component;
00044 import org.objectweb.fractal.api.Interface;
00045 import org.objectweb.fractal.api.NoSuchInterfaceException;
00046 import org.objectweb.fractal.api.Type;
00047 import org.objectweb.fractal.api.control.BindingController;
00048 import org.objectweb.fractal.api.control.ContentController;
00049 import org.objectweb.fractal.api.control.NameController;
00050 import org.objectweb.fractal.api.factory.InstantiationException;
00051 import org.objectweb.fractal.api.type.ComponentType;
00052 import org.objectweb.fractal.api.type.InterfaceType;
00053 import org.objectweb.proactive.Body;
00054 import org.objectweb.proactive.core.ProActiveRuntimeException;
00055 import org.objectweb.proactive.core.UniqueID;
00056 import org.objectweb.proactive.core.body.migration.MigrationException;
00057 import org.objectweb.proactive.core.component.ComponentParameters;
00058 import org.objectweb.proactive.core.component.Constants;
00059 import org.objectweb.proactive.core.component.ControllerDescription;
00060 import org.objectweb.proactive.core.component.ProActiveInterface;
00061 import org.objectweb.proactive.core.component.config.ComponentConfigurationHandler;
00062 import org.objectweb.proactive.core.component.controller.AbstractProActiveController;
00063 import org.objectweb.proactive.core.component.controller.AbstractRequestHandler;
00064 import org.objectweb.proactive.core.component.controller.ComponentParametersController;
00065 import org.objectweb.proactive.core.component.controller.ProActiveController;
00066 import org.objectweb.proactive.core.component.controller.RequestHandler;
00067 import org.objectweb.proactive.core.component.exceptions.InterfaceGenerationFailedException;
00068 import org.objectweb.proactive.core.component.gen.MetaObjectInterfaceClassGenerator;
00069 import org.objectweb.proactive.core.component.interception.InputInterceptor;
00070 import org.objectweb.proactive.core.component.interception.OutputInterceptor;
00071 import org.objectweb.proactive.core.component.representative.ProActiveComponentRepresentativeFactory;
00072 import org.objectweb.proactive.core.component.type.ProActiveInterfaceType;
00073 import org.objectweb.proactive.core.group.ProActiveComponentGroup;
00074 import org.objectweb.proactive.core.mop.MOP;
00075 import org.objectweb.proactive.core.mop.StubObject;
00076 import org.objectweb.proactive.core.node.Node;
00077 import org.objectweb.proactive.core.util.log.Loggers;
00078 import org.objectweb.proactive.core.util.log.ProActiveLogger;
00079 
00080 
00087 public class ProActiveComponentImpl extends AbstractRequestHandler
00088     implements ProActiveComponent, Interface, Serializable {
00089     protected static final Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS);
00090     private transient ProActiveComponent representativeOnMyself = null;
00091 
00092     private Map<String, Interface> functionalItfs = new HashMap<String, Interface>();
00093     private Map<String, ProActiveController> controlItfs = new HashMap<String, ProActiveController>();
00094     private Map<String, Interface> collectionItfsMembers = new HashMap<String, Interface>();
00095     private Body body;
00096     private RequestHandler firstControllerRequestHandler;
00097 
00098     // need Vector-specific operations for inserting elements
00099     private Vector<AbstractProActiveController> inputInterceptors = new Vector<AbstractProActiveController>();
00100     private Vector<AbstractProActiveController> outputInterceptors = new Vector<AbstractProActiveController>();
00101 
00102     public ProActiveComponentImpl() {
00103     }
00104 
00115     public ProActiveComponentImpl(ComponentParameters componentParameters,
00116         Body myBody) {
00117         this.body = myBody;
00118         boolean component_is_primitive = componentParameters.getHierarchicalType()
00119                                                             .equals(Constants.PRIMITIVE);
00120 
00121         // add interface references
00122         ArrayList<Interface> interface_references_list = new ArrayList<Interface>(4);
00123 
00124         // 1. component identity
00125         interface_references_list.add(this);
00126 
00127         // 2. control interfaces
00128         addControllers(componentParameters, component_is_primitive);
00129 
00130         // 3. external functional interfaces
00131         addFunctionalInterfaces(componentParameters, component_is_primitive);
00132 
00133         //        Set<String> s = controlItfs.keySet();
00134         //        for (Iterator iter = s.iterator(); iter.hasNext();) {
00135         //                      String key = (String) iter.next();
00136         //                      ((AbstractProActiveController)controlItfs.get(key)).init();
00137         //              }
00138 
00139         // put all in a table
00140         //        interfaceReferences = (Interface[]) interface_references_list.toArray(new Interface[interface_references_list.size()]);
00141         if (logger.isDebugEnabled()) {
00142             logger.debug("created component : " +
00143                 componentParameters.getControllerDescription().getName());
00144         }
00145     }
00146 
00151     private void addFunctionalInterfaces(
00152         ComponentParameters componentParameters, boolean component_is_primitive) {
00153         // ProActiveInterfaceType[] interface_types =
00154         // (ProActiveInterfaceType[])componentParameters.getComponentType()
00155         // .getFcInterfaceTypes();
00156         InterfaceType[] tmp = componentParameters.getComponentType()
00157                                                  .getFcInterfaceTypes();
00158         ProActiveInterfaceType[] interface_types = new ProActiveInterfaceType[tmp.length];
00159         System.arraycopy(tmp, 0, interface_types, 0, tmp.length);
00160 
00161         try {
00162             for (int i = 0; i < interface_types.length; i++) {
00163                 ProActiveInterface itf_ref = null;
00164 
00165                 if (interface_types[i].isFcCollectionItf()) {
00166                     // members of collection itfs are created dynamically
00167                     continue;
00168                 }
00169                 if (interface_types[i].isFcMulticastItf()) {
00170                     itf_ref = createInterfaceOnGroupOfDelegatees(interface_types[i]);
00171                     //                    itf_ref = ProActiveComponentGroup.newComponentInterfaceGroup(interface_types[i],
00172                     //                            getFcItfOwner());
00173                 } else {
00174                     // no interface generated for client itfs of primitive
00175                     // components
00176                     if (!(interface_types[i].isFcClientItf() &&
00177                             component_is_primitive)) {
00178 
00179                         itf_ref = MetaObjectInterfaceClassGenerator.instance()
00180                                                                    .generateFunctionalInterface(interface_types[i].getFcItfName(),
00181                                 this, interface_types[i]);
00182                         // server functional interfaces are external interfaces (at
00183                         // least they are tagged as external)
00184 
00185                         // set delegation link
00186                         if (componentParameters.getHierarchicalType()
00187                                                    .equals(Constants.PRIMITIVE)) {
00188                             if (!interface_types[i].isFcCollectionItf()) {
00189                                 if (!interface_types[i].isFcClientItf()) {
00190                                     (itf_ref).setFcItfImpl(getReferenceOnBaseObject());
00191                                 } else if (interface_types[i].isFcClientItf()) {
00192                                     (itf_ref).setFcItfImpl(null);
00193                                 }
00194                             }
00195                         }
00196                     }
00197 
00198                     // non multicast client itf of primitive comp : do nothing
00199                 }
00200 
00201                 functionalItfs.put(interface_types[i].getFcItfName(), itf_ref);
00202             }
00203         } catch (Exception e) {
00204             if (logger.isDebugEnabled()) {
00205                 logger.debug("cannot create interface references : " +
00206                     e.getMessage());
00207             }
00208 
00209             throw new RuntimeException("cannot create interface references : " +
00210                 e.getMessage());
00211         }
00212     }
00213 
00214     private void addControllers(ComponentParameters componentParameters,
00215         boolean isPrimitive) {
00216         ComponentConfigurationHandler componentConfiguration = ProActiveComponentImpl.loadControllerConfiguration(componentParameters.getControllerDescription()
00217                                                                                                                                      .getControllersConfigFileLocation());
00218         Map controllers = componentConfiguration.getControllers();
00219         List inputInterceptorsSignatures = componentConfiguration.getInputInterceptors();
00220         inputInterceptors.setSize(inputInterceptorsSignatures.size());
00221         List outputInterceptorsSignatures = componentConfiguration.getOutputInterceptors();
00222         outputInterceptors.setSize(outputInterceptorsSignatures.size());
00223 
00224         // Properties controllers =
00225         // loadControllersConfiguration(componentParameters.getControllerDescription().getControllersConfigFile());
00226         Iterator iteratorOnControllers = controllers.keySet().iterator();
00227         AbstractProActiveController lastController = null;
00228 
00229         while (iteratorOnControllers.hasNext()) {
00230             Class<?> controllerClass = null;
00231             AbstractProActiveController currentController;
00232             String controllerItfName = (String) iteratorOnControllers.next();
00233 
00234             try {
00235                 Class<?> controllerItf = Class.forName(controllerItfName);
00236                 controllerClass = Class.forName((String) controllers.get(
00237                             controllerItf.getName()));
00238                 Constructor<?> controllerClassConstructor = controllerClass.getConstructor(new Class[] {
00239                             Component.class
00240                         });
00241                 currentController = (AbstractProActiveController) controllerClassConstructor.newInstance(new Object[] {
00242                             this
00243                         });
00244 
00245                 // add interceptor
00246                 if (InputInterceptor.class.isAssignableFrom(controllerClass)) {
00247                     // keep the sequence order of the interceptors
00248                     inputInterceptors.setElementAt(currentController,
00249                         inputInterceptorsSignatures.indexOf(
00250                             controllerClass.getName()));
00251                 } else if (inputInterceptorsSignatures.contains(
00252                             controllerClass.getName())) {
00253                     logger.error(controllerClass.getName() +
00254                         " was specified as input interceptor in the configuration file, but it is not an input interceptor since it does not implement the InputInterceptor interface");
00255                 }
00256 
00257                 if (OutputInterceptor.class.isAssignableFrom(controllerClass)) {
00258                     outputInterceptors.setElementAt(currentController,
00259                         outputInterceptorsSignatures.indexOf(
00260                             controllerClass.getName()));
00261                 } else if (outputInterceptorsSignatures.contains(
00262                             controllerClass.getName())) {
00263                     logger.error(controllerClass.getName() +
00264                         " was specified as output interceptor in the configuration file, but it is not an output interceptor since it does not implement the OutputInterceptor interface");
00265                 }
00266             } catch (Exception e) {
00267                 e.printStackTrace();
00268                 throw new ProActiveRuntimeException(
00269                     "could not create controller " +
00270                     controllers.get(controllerItfName) + " : " +
00271                     e.getMessage(), e);
00272             }
00273 
00274             // there are some special cases for some controllers
00275             if (ComponentParametersController.class.isAssignableFrom(
00276                         controllerClass)) {
00277                 ((ComponentParametersController) currentController).setComponentParameters(componentParameters);
00278             }
00279 
00280             if (BindingController.class.isAssignableFrom(controllerClass)) {
00281                 if ((componentParameters.getHierarchicalType()
00282                                             .equals(Constants.PRIMITIVE) &&
00283                         (componentParameters.getClientInterfaceTypes().length == 0))) {
00284                     // bindingController = null;
00285                     if (logger.isDebugEnabled()) {
00286                         logger.debug("user component class of '" +
00287                             componentParameters.getName() +
00288                             "' does not have any client interface. It will have no BindingController");
00289                     }
00290 
00291                     continue;
00292                 }
00293  
00294             }
00295 
00296             if (ContentController.class.isAssignableFrom(controllerClass)) {
00297                 if (isPrimitive) {
00298                     // no content controller here
00299                     continue;
00300                 }
00301             }
00302 
00303             if (NameController.class.isAssignableFrom(controllerClass)) {
00304                 ((NameController) currentController).setFcName(componentParameters.getName());
00305             }
00306 
00307             if (lastController != null) {
00308                 lastController.setNextHandler(currentController);
00309             } else {
00310                 firstControllerRequestHandler = currentController;
00311             }
00312 
00313             lastController = currentController;
00314             controlItfs.put(currentController.getFcItfName(), currentController);
00315         }
00316 
00317         // add the "component" control itfs
00318         lastController.setNextHandler(this);
00319     }
00320 
00326     public static ComponentConfigurationHandler loadControllerConfiguration(
00327         String controllerConfigFileLocation) {
00328         try {
00329             return ComponentConfigurationHandler.createComponentConfigurationHandler(controllerConfigFileLocation);
00330         } catch (Exception e) {
00331             logger.error("could not load controller config file : " +
00332                 controllerConfigFileLocation +
00333                 ". Reverting to default controllers configuration.");
00334 
00335             try {
00336                 return ComponentConfigurationHandler.createComponentConfigurationHandler(ControllerDescription.DEFAULT_COMPONENT_CONFIG_FILE_LOCATION);
00337             } catch (Exception e1) {
00338                 logger.error(
00339                     "could not load default controller config file either. Check that the default controller config file is available in your classpath at : " +
00340                     ControllerDescription.DEFAULT_COMPONENT_CONFIG_FILE_LOCATION);
00341                 throw new ProActiveRuntimeException(
00342                     "could not load default controller config file either. Check that the default controller config file is available on your system at : " +
00343                     ControllerDescription.DEFAULT_COMPONENT_CONFIG_FILE_LOCATION,
00344                     e1);
00345             }
00346         }
00347     }
00348 
00349     // returns a generated interface reference, whose impl field is a group
00350     // It is able to handle multiple bindings
00351     private ProActiveInterface createInterfaceOnGroupOfDelegatees(
00352         ProActiveInterfaceType itfType) throws Exception {
00353         ProActiveInterface itf_ref = MetaObjectInterfaceClassGenerator.instance()
00354                                                                       .generateFunctionalInterface(itfType.getFcItfName(),
00355                 this, itfType);
00356 
00357         // create a group of impl target objects
00358         ProActiveInterface itf_ref_group = ProActiveComponentGroup.newComponentInterfaceGroup(itfType,
00359                 this);
00360         itf_ref.setFcItfImpl(itf_ref_group);
00361         return itf_ref;
00362     }
00363 
00364     /*
00365      * see {@link org.objectweb.fractal.api.Component#getFcInterface(String)}
00366      */
00367     public Object getFcInterface(String interfaceName)
00368         throws NoSuchInterfaceException {
00369         if (!("attribute-controller".equals(interfaceName)) &&
00370                 (interfaceName.endsWith("-controller") ||
00371                 interfaceName.equals("component"))) {
00372             if (!controlItfs.containsKey(interfaceName)) {
00373                 throw new NoSuchInterfaceException(interfaceName);
00374             }
00375             return (controlItfs.get(interfaceName));
00376         }
00377         if (functionalItfs.containsKey(interfaceName)) {
00378             return functionalItfs.get(interfaceName);
00379         }
00380 
00381         // a member of a collection itf?
00382         InterfaceType[] itfTypes = ((ComponentType) getFcType()).getFcInterfaceTypes();
00383         for (int i = 0; i < itfTypes.length; i++) {
00384             InterfaceType type = itfTypes[i];
00385             if (type.isFcCollectionItf()) {
00386                 if ((interfaceName.startsWith(type.getFcItfName()) &&
00387                         !type.getFcItfName().equals(interfaceName))) {
00388                     if (collectionItfsMembers.containsKey(interfaceName)) {
00389                         return collectionItfsMembers.get(interfaceName);
00390                     } else {
00391                         //                                       generate a new interface and add it to the list of members of collection its
00392                         try {
00393                             Interface clientItf = MetaObjectInterfaceClassGenerator.instance()
00394                                                                                    .generateFunctionalInterface(interfaceName,
00395                                     this, (ProActiveInterfaceType) itfTypes[i]);
00396                             collectionItfsMembers.put(interfaceName, clientItf);
00397                             return clientItf;
00398                         } catch (InterfaceGenerationFailedException e1) {
00399                             // TODO Auto-generated catch block
00400                             e1.printStackTrace();
00401                         }
00402                     }
00403                 }
00404             }
00405         }
00406 
00407         throw new NoSuchInterfaceException(interfaceName);
00408     }
00409 
00410     /*
00411      * see {@link org.objectweb.fractal.api.Component#getFcInterfaces()}
00412      */
00413     public Object[] getFcInterfaces() {
00414         return functionalItfs.values().toArray();
00415     }
00416 
00417     /*
00418      * see {@link org.objectweb.fractal.api.Component#getFcType()}
00419      */
00420     public Type getFcType() {
00421         try {
00422             return ((ComponentParametersController) getFcInterface(Constants.COMPONENT_PARAMETERS_CONTROLLER)).getComponentParameters()
00423                     .getComponentType();
00424         } catch (NoSuchInterfaceException nsie) {
00425             throw new ProActiveRuntimeException("cannot retreive the type of the component",
00426                 nsie);
00427         }
00428     }
00429 
00433     public String getFcItfName() {
00434         return Constants.COMPONENT;
00435     }
00436 
00440     public Component getFcItfOwner() {
00441         return (Component) this;
00442     }
00443 
00447     public Type getFcItfType() {
00448         return getFcType();
00449     }
00450 
00454     public boolean isFcInternalItf() {
00455         return true;
00456     }
00457 
00464     public Object getReferenceOnBaseObject() {
00465         return getBody().getReifiedObject();
00466     }
00467 
00472     public ComponentParameters getComponentParameters()
00473         throws NoSuchInterfaceException {
00474         // return componentParameters;
00475         return ((ComponentParametersController) getFcInterface(Constants.COMPONENT_PARAMETERS_CONTROLLER)).getComponentParameters();
00476     }
00477 
00481     public Body getBody() {
00482         return body;
00483     }
00484 
00489     public UniqueID getID() {
00490         return getBody().getID();
00491     }
00492 
00498     public ProActiveComponent getRepresentativeOnThis() {
00499         // optimization : cache self reference 
00500         if (representativeOnMyself != null) {
00501             return representativeOnMyself;
00502         }
00503 
00504         try {
00505             return representativeOnMyself = ProActiveComponentRepresentativeFactory.instance()
00506                                                                                    .createComponentRepresentative((ComponentType) getFcType(),
00507                     getComponentParameters().getHierarchicalType(),
00508                     ((StubObject) MOP.turnReified(body.getReifiedObject()
00509                                                       .getClass().getName(),
00510                         org.objectweb.proactive.core.Constants.DEFAULT_BODY_PROXY_CLASS_NAME,
00511                         new Object[] { body }, body.getReifiedObject(), null)).getProxy(),
00512                     getComponentParameters().getControllerDescription()
00513                         .getControllersConfigFileLocation());
00514         } catch (Exception e) {
00515             throw new ProActiveRuntimeException("This component could not generate a reference on itself",
00516                 e);
00517         }
00518     }
00519 
00523     public RequestHandler getControllerRequestHandler() {
00524         return firstControllerRequestHandler;
00525     }
00526 
00527     public List<AbstractProActiveController> getInputInterceptors() {
00528         return inputInterceptors;
00529     }
00530 
00531     public List<AbstractProActiveController> getOutputInterceptors() {
00532         return outputInterceptors;
00533     }
00534 
00535     public void migrateControllersDependentActiveObjectsTo(Node node)
00536         throws MigrationException {
00537         for (Iterator iter = controlItfs.values().iterator(); iter.hasNext();) {
00538             ProActiveController controller = (ProActiveController) iter.next();
00539             controller.migrateDependentActiveObjectsTo(node);
00540         }
00541     }
00542 
00543     private void writeObject(java.io.ObjectOutputStream out)
00544         throws java.io.IOException {
00545         //        System.out.println("writing ProActiveComponentImpl");
00546         out.defaultWriteObject();
00547     }
00548 
00549     private void readObject(java.io.ObjectInputStream in)
00550         throws java.io.IOException, ClassNotFoundException {
00551         //        System.out.println("reading ProActiveComponentImpl");
00552         in.defaultReadObject();
00553     }
00554 }

Generated on Mon Jan 22 15:16:07 2007 for ProActive by  doxygen 1.5.1