felix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rickh...@apache.org
Subject svn commit: r449050 - in /incubator/felix/trunk/scr: ./ src/main/java/org/apache/felix/scr/
Date Fri, 22 Sep 2006 18:55:51 GMT
Author: rickhall
Date: Fri Sep 22 11:55:50 2006
New Revision: 449050

URL: http://svn.apache.org/viewvc?view=rev&rev=449050
Log:
Applied patch (FELIX-140) to remove generic activator and use bundle
inspection instead.

Added:
    incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java   (with props)
Removed:
    incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/GenericActivator.java
Modified:
    incubator/felix/trunk/scr/pom.xml
    incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/Activator.java
    incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ComponentManagerImpl.java
    incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ManagerFactory.java

Modified: incubator/felix/trunk/scr/pom.xml
URL: http://svn.apache.org/viewvc/incubator/felix/trunk/scr/pom.xml?view=diff&rev=449050&r1=449049&r2=449050
==============================================================================
--- incubator/felix/trunk/scr/pom.xml (original)
+++ incubator/felix/trunk/scr/pom.xml Fri Sep 22 11:55:50 2006
@@ -45,10 +45,10 @@
             </bundleActivator>
             <bundleSymbolicName>org.apache.felix.scr</bundleSymbolicName>
             <exportPackage>
-			  org.apache.felix.scr
-			</exportPackage>
-			<importPackage>
-              org.osgi.service.component, org.osgi.framework
+              org.apache.felix.scr
+            </exportPackage>
+            <importPackage>
+              org.osgi.service.log, org.osgi.service.component, org.osgi.framework
             </importPackage>			
           </osgiManifest>
         </configuration>

Modified: incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/Activator.java
URL: http://svn.apache.org/viewvc/incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/Activator.java?view=diff&rev=449050&r1=449049&r2=449050
==============================================================================
--- incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/Activator.java (original)
+++ incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/Activator.java Fri Sep 22 11:55:50 2006
@@ -1,231 +1,377 @@
-/*
- *   Copyright 2006 The Apache Software Foundation
- *
- *   Licensed under the Apache License, Version 2.0 (the "License");
- *   you may not use this file except in compliance with the License.
- *   You may obtain a copy of the License at
- *
- *       http://www.apache.org/licenses/LICENSE-2.0
- *
- *   Unless required by applicable law or agreed to in writing, software
- *   distributed under the License is distributed on an "AS IS" BASIS,
- *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *   See the License for the specific language governing permissions and
- *   limitations under the License.
- *
- */
-package org.apache.felix.scr;
-
-import java.lang.reflect.Method;
-import java.util.*;
-
-import org.osgi.framework.*;
-
-/**
- * This activator is used to cover requirement described in section 112.8.1 @@ -27,14
- * 37,202 @@ in active bundles.
- * 
- */
-public class Activator implements BundleActivator, SynchronousBundleListener
-{
-
-    // map of GenericActivator instances per Bundle indexed by Bundle symbolic
-    // name
-    private Map m_componentBundles;
-
-    /**
-     * Registers this instance as a (synchronous) bundle listener and loads the
-     * components of already registered bundles.
-     * 
-     * @param context The <code>BundleContext</code> of the SCR implementation
-     *      bundle.
-     */
-    public void start(BundleContext context) throws Exception
-    {
-        m_componentBundles = new HashMap();
-
-        // register for bundle updates
-        context.addBundleListener(this);
-
-        // 112.8.2 load all components of active bundles
-        loadAllComponents(context);
-    }
-
-    /**
-     * Unregisters this instance as a bundle listener and unloads all components
-     * which have been registered during the active life time of the SCR
-     * implementation bundle.
-     * 
-     * @param context The <code>BundleContext</code> of the SCR implementation
-     *      bundle.
-     */
-    public void stop(BundleContext context) throws Exception
-    {
-        // unregister as bundle listener
-        context.removeBundleListener(this);
-
-        // 112.8.2 dispose off all active components
-        disposeAllComponents();
-    }
-
-    // ---------- BundleListener Interface -------------------------------------
-
-    /**
-     * Loads and unloads any components provided by the bundle whose state
-     * changed. If the bundle has been started, the components are loaded. If
-     * the bundle is about to stop, the components are unloaded.
-     * 
-     * @param event The <code>BundleEvent</code> representing the bundle state
-     *      change.
-     */
-    public void bundleChanged(BundleEvent event)
-    {
-        if (event.getType() == BundleEvent.STARTED)
-        {
-            loadComponents(event.getBundle());
-        }
-        else if (event.getType() == BundleEvent.STOPPING)
-        {
-            disposeComponents(event.getBundle());
-        }
-    }
-
-    // ---------- Component Management -----------------------------------------
-
-    // Loads the components of all bundles currently active.
-    private void loadAllComponents(BundleContext context)
-    {
-        Bundle[] bundles = context.getBundles();
-        for (int i = 0; i < bundles.length; i++)
-        {
-            Bundle bundle = bundles[i];
-            if (bundle.getState() == Bundle.ACTIVE)
-            {
-                loadComponents(bundle);
-            }
-        }
-    }
-
-    /**
-     * Loads the components of the given bundle. If the bundle has no
-     * <i>Service-Component</i> header, this method has no effect. The
-     * fragments of a bundle are not checked for the header (112.4.1).
-     * <p>
-     * This method calls the {@link #getBundleContext(Bundle)} method to find
-     * the <code>BundleContext</code> of the bundle. If the context cannot be
-     * found, this method does not load components for the bundle.
-     */
-    private void loadComponents(Bundle bundle)
-    {
-        if (bundle.getHeaders().get("Service-Component") == null)
-        {
-            // no components in the bundle, abandon
-            return;
-        }
-
-        // there should be components, load them with a bundle context
-        BundleContext context = getBundleContext(bundle);
-        if (context == null)
-        {
-            GenericActivator.error("Cannot get BundleContext of bundle "
-                + bundle.getSymbolicName());
-            return;
-        }
-
-        GenericActivator ga = new GenericActivator();
-        try
-        {
-            ga.start(context);
-            m_componentBundles.put(bundle.getSymbolicName(), ga);
-        }
-        catch (Exception e)
-        {
-            GenericActivator.exception("Error while loading components "
-                + "of bundle " + bundle.getSymbolicName(), null, e);
-        }
-    }
-
-    /**
-     * Unloads components of the given bundle. If no components have been loaded
-     * for the bundle, this method has no effect.
-     */
-    private void disposeComponents(Bundle bundle)
-    {
-        String name = bundle.getSymbolicName();
-        GenericActivator ga = (GenericActivator) m_componentBundles.remove(name);
-        if (ga != null)
-        {
-            try
-            {
-                ga.dispose();
-            }
-            catch (Exception e)
-            {
-                GenericActivator.exception("Error while disposing components "
-                    + "of bundle " + name, null, e);
-            }
-        }
-    }
-
-    // Unloads all components registered with the SCR
-    private void disposeAllComponents()
-    {
-        for (Iterator it = m_componentBundles.values().iterator(); it.hasNext();)
-        {
-            GenericActivator ga = (GenericActivator) it.next();
-            try
-            {
-                ga.dispose();
-            }
-            catch (Exception e)
-            {
-                GenericActivator.exception(
-                    "Error while disposing components of bundle "
-                        + ga.getBundleContext().getBundle().getSymbolicName(),
-                    null, e);
-            }
-            it.remove();
-        }
-    }
-
-    /**
-     * Returns the <code>BundleContext</code> of the bundle.
-     * <p>
-     * This method assumes a <code>getContext</code> method returning a
-     * <code>BundleContext</code> instance to be present in the class of the
-     * bundle or any of its parent classes.
-     * 
-     * @param bundle The <code>Bundle</code> whose context is to be returned.
-     * 
-     * @return The <code>BundleContext</code> of the bundle or
-     *         <code>null</code> if no <code>getContext</code> method
-     *         returning a <code>BundleContext</code> can be found.
-     */
-    private BundleContext getBundleContext(Bundle bundle)
-    {
-        for (Class clazz = bundle.getClass(); clazz != null; clazz = clazz.getSuperclass())
-        {
-            try
-            {
-                Method m = clazz.getDeclaredMethod("getContext", null);
-                if (m.getReturnType().equals(BundleContext.class))
-                {
-                    m.setAccessible(true);
-                    return (BundleContext) m.invoke(bundle, null);
-                }
-            }
-            catch (NoSuchMethodException nsme)
-            {
-                // don't actually care, just try super class
-            }
-            catch (Throwable t)
-            {
-                GenericActivator.exception("Cannot get BundleContext for "
-                    + bundle.getSymbolicName(), null, t);
-            }
-        }
-
-        // fall back to nothing
-        return null;
-    }
+/*
+ *   Copyright 2006 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *   limitations under the License.
+ *
+ */
+package org.apache.felix.scr;
+
+import java.lang.reflect.Method;
+import java.util.*;
+
+import org.osgi.framework.*;
+import org.osgi.service.log.LogService;
+
+/**
+ * This activator is used to cover requirement described in section 112.8.1 @@ -27,14
+ * 37,202 @@ in active bundles.
+ * 
+ */
+public class Activator implements BundleActivator, SynchronousBundleListener, ServiceListener
+{
+    // name of the LogService class
+    private static final String LOGSERVICE_CLASS = LogService.class.getName();
+    
+    // Flag that sets tracing messages
+    private static boolean m_trace = true;
+    
+    // Flag that sets error messages
+    private static boolean m_error = true;
+
+    // A string containing the version number
+    private static String m_version = "1.0.0 (12012006)";
+
+    // this bundle's context
+    private BundleContext m_context;
+    
+    // the log service to log messages to
+    private static /* TODO: not very good, is it ? */ LogService m_logService;
+    
+    // map of BundleComponentActivator instances per Bundle indexed by Bundle symbolic
+    // name
+    private Map m_componentBundles;
+
+    // Static initializations based on system properties
+    static {
+        // Get system properties to see if traces or errors need to be displayed
+        String result = System.getProperty("ds.showtrace");
+        if(result != null && result.equals("true"))
+        {
+            m_trace = true;
+        }
+        result = System.getProperty("ds.showerrors");
+        if(result != null && result.equals("false"))
+        {
+            m_error = false;
+        }
+        result = System.getProperty("ds.showversion");
+        if(result != null && result.equals("true"))
+        {
+            System.out.println("[ Version = "+m_version+" ]\n");
+        }        
+    }
+
+    /**
+     * Registers this instance as a (synchronous) bundle listener and loads the
+     * components of already registered bundles.
+     * 
+     * @param context The <code>BundleContext</code> of the SCR implementation
+     *      bundle.
+     */
+    public void start(BundleContext context) throws Exception
+    {
+        m_context = context;
+        m_componentBundles = new HashMap();
+
+        // require the log service
+        ServiceReference logRef = context.getServiceReference(LOGSERVICE_CLASS);
+        if (logRef != null) {
+            m_logService = (LogService) context.getService(logRef);
+        }
+        context.addServiceListener(this,
+            "(" + Constants.OBJECTCLASS + "=" + LOGSERVICE_CLASS + ")");
+        
+        // register for bundle updates
+        context.addBundleListener(this);
+
+        // 112.8.2 load all components of active bundles
+        loadAllComponents(context);
+    }
+
+    /**
+     * Unregisters this instance as a bundle listener and unloads all components
+     * which have been registered during the active life time of the SCR
+     * implementation bundle.
+     * 
+     * @param context The <code>BundleContext</code> of the SCR implementation
+     *      bundle.
+     */
+    public void stop(BundleContext context) throws Exception
+    {
+        // unregister as bundle listener
+        context.removeBundleListener(this);
+
+        // 112.8.2 dispose off all active components
+        disposeAllComponents();
+    }
+
+    // ---------- BundleListener Interface -------------------------------------
+
+    /**
+     * Loads and unloads any components provided by the bundle whose state
+     * changed. If the bundle has been started, the components are loaded. If
+     * the bundle is about to stop, the components are unloaded.
+     * 
+     * @param event The <code>BundleEvent</code> representing the bundle state
+     *      change.
+     */
+    public void bundleChanged(BundleEvent event)
+    {
+        if (event.getType() == BundleEvent.STARTED)
+        {
+            loadComponents(event.getBundle());
+        }
+        else if (event.getType() == BundleEvent.STOPPING)
+        {
+            disposeComponents(event.getBundle());
+        }
+    }
+
+    //---------- ServiceListener ----------------------------------------------
+
+    // TODO:
+    public void serviceChanged(ServiceEvent event)
+    {
+        if (event.getType() == ServiceEvent.REGISTERED)
+        {
+            m_logService = (LogService) m_context.getService(event.getServiceReference());
+        }
+        else if (event.getType() == ServiceEvent.UNREGISTERING)
+        {
+            m_logService = null;
+            m_context.ungetService(event.getServiceReference());
+        }
+    }
+    
+    // ---------- Component Management -----------------------------------------
+
+    // Loads the components of all bundles currently active.
+    private void loadAllComponents(BundleContext context)
+    {
+        Bundle[] bundles = context.getBundles();
+        for (int i = 0; i < bundles.length; i++)
+        {
+            Bundle bundle = bundles[i];
+            if (bundle.getState() == Bundle.ACTIVE)
+            {
+                loadComponents(bundle);
+            }
+        }
+    }
+
+    /**
+     * Loads the components of the given bundle. If the bundle has no
+     * <i>Service-Component</i> header, this method has no effect. The
+     * fragments of a bundle are not checked for the header (112.4.1).
+     * <p>
+     * This method calls the {@link #getBundleContext(Bundle)} method to find
+     * the <code>BundleContext</code> of the bundle. If the context cannot be
+     * found, this method does not load components for the bundle.
+     */
+    private void loadComponents(Bundle bundle)
+    {
+        if (bundle.getHeaders().get("Service-Component") == null)
+        {
+            // no components in the bundle, abandon
+            return;
+        }
+
+        // there should be components, load them with a bundle context
+        BundleContext context = getBundleContext(bundle);
+        if (context == null)
+        {
+            error("Cannot get BundleContext of bundle "
+                + bundle.getSymbolicName());
+            return;
+        }
+
+        try
+        {
+            BundleComponentActivator ga = new BundleComponentActivator(context);
+            m_componentBundles.put(bundle.getSymbolicName(), ga);
+        }
+        catch (Exception e)
+        {
+            exception("Error while loading components "
+                + "of bundle " + bundle.getSymbolicName(), null, e);
+        }
+    }
+
+    /**
+     * Unloads components of the given bundle. If no components have been loaded
+     * for the bundle, this method has no effect.
+     */
+    private void disposeComponents(Bundle bundle)
+    {
+        String name = bundle.getSymbolicName();
+        BundleComponentActivator ga = (BundleComponentActivator) m_componentBundles.remove(name);
+        if (ga != null)
+        {
+            try
+            {
+                ga.dispose();
+            }
+            catch (Exception e)
+            {
+                exception("Error while disposing components "
+                    + "of bundle " + name, null, e);
+            }
+        }
+    }
+
+    // Unloads all components registered with the SCR
+    private void disposeAllComponents()
+    {
+        for (Iterator it = m_componentBundles.values().iterator(); it.hasNext();)
+        {
+            BundleComponentActivator ga = (BundleComponentActivator) it.next();
+            try
+            {
+                ga.dispose();
+            }
+            catch (Exception e)
+            {
+                exception(
+                    "Error while disposing components of bundle "
+                        + ga.getBundleContext().getBundle().getSymbolicName(),
+                    null, e);
+            }
+            it.remove();
+        }
+    }
+
+    /**
+     * Returns the <code>BundleContext</code> of the bundle.
+     * <p>
+     * This method assumes a <code>getContext</code> method returning a
+     * <code>BundleContext</code> instance to be present in the class of the
+     * bundle or any of its parent classes.
+     * 
+     * @param bundle The <code>Bundle</code> whose context is to be returned.
+     * 
+     * @return The <code>BundleContext</code> of the bundle or
+     *         <code>null</code> if no <code>getContext</code> method
+     *         returning a <code>BundleContext</code> can be found.
+     */
+    private BundleContext getBundleContext(Bundle bundle)
+    {
+        for (Class clazz = bundle.getClass(); clazz != null; clazz = clazz.getSuperclass())
+        {
+            try
+            {
+                Method m = clazz.getDeclaredMethod("getContext", null);
+                if (m.getReturnType().equals(BundleContext.class))
+                {
+                    m.setAccessible(true);
+                    return (BundleContext) m.invoke(bundle, null);
+                }
+            }
+            catch (NoSuchMethodException nsme)
+            {
+                // don't actually care, just try super class
+            }
+            catch (Throwable t)
+            {
+                exception("Cannot get BundleContext for "
+                    + bundle.getSymbolicName(), null, t);
+            }
+        }
+
+        // fall back to nothing
+        return null;
+    }
+    
+    
+    /**
+     * Method to display traces
+     *
+     * @param message a string to be displayed
+     * @param metadata ComponentMetadata associated to the message (can be null)
+    **/
+    static void trace(String message, ComponentMetadata metadata)
+    {
+        if(m_trace)
+        {
+            StringBuffer msg = new StringBuffer("--- ");
+            if(metadata != null) {
+                msg.append("[").append(metadata.getName()).append("] ");
+            }
+            msg.append(message);
+
+            LogService log = m_logService;
+            if (log == null)
+            {
+                System.out.println(msg);
+            }
+            else
+            {
+                log.log(LogService.LOG_DEBUG, msg.toString());
+            }
+        }
+    }
+
+    /**
+     * Method to display errors
+     *
+     * @param message a string to be displayed
+     **/
+    static void error(String message)
+    {
+        if(m_error)
+        {
+            StringBuffer msg = new StringBuffer("### ").append(message);
+
+            LogService log = m_logService;
+            if (log == null)
+            {
+                System.err.println(msg);
+            }
+            else
+            {
+                log.log(LogService.LOG_ERROR, msg.toString());
+            }
+        }
+    }
+
+    /**
+     * Method to display exceptions
+     *
+     * @param ex an exception
+     **/   
+    static void exception(String message, ComponentMetadata metadata, Throwable ex)
+    {
+         if(m_error)
+         {
+             StringBuffer msg = new StringBuffer("--- ");
+             if(metadata != null) {
+                 msg.append("[").append(metadata.getName()).append("] ");
+             }
+             msg.append("Exception with component : ");
+             msg.append(message).append(" ---");
+             
+             LogService log = m_logService;
+             if (log == null)
+             {
+                 System.err.println(msg);
+                 if (ex != null)
+                 {
+                     ex.printStackTrace(System.err);
+                 }
+             }
+             else
+             {
+                 log.log(LogService.LOG_ERROR, msg.toString(), ex);
+             }
+         }      
+    }
 }

Added: incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java
URL: http://svn.apache.org/viewvc/incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java?view=auto&rev=449050
==============================================================================
--- incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java (added)
+++ incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java Fri Sep 22 11:55:50 2006
@@ -0,0 +1,371 @@
+/*
+ *   Copyright 2006 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *   limitations under the License.
+ *
+ */
+package org.apache.felix.scr;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import org.apache.felix.scr.parser.KXml2SAXParser;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentException;
+
+/**
+ * The BundleComponentActivator is helper class to load and unload Components of
+ * a single bundle. It will read information from the metadata.xml file
+ * descriptors and create the corresponding managers.
+ */
+class BundleComponentActivator
+{	
+	// The bundle context
+    private BundleContext m_context = null;
+    
+    // This is a list of component instance managers that belong to a particular bundle
+    private List m_managers = new ArrayList();
+
+    // Global Registry of component names
+    private static Set m_componentNames = new HashSet();
+
+    /**
+     * Called upon starting of the bundle. This method invokes initialize() which
+     * parses the metadata and creates the instance managers
+     *
+     * @param   context  The bundle context passed by the framework
+     * @exception   Exception any exception thrown from initialize
+     */
+    BundleComponentActivator(BundleContext context) throws ComponentException
+    {
+    	// Stores the context
+        m_context = context;
+        
+        // Get the Metadata-Location value from the manifest
+        String descriptorLocations =
+            (String) m_context.getBundle().getHeaders().get("Service-Component");
+        if (descriptorLocations == null)
+        {
+            throw new ComponentException("Service-Component entry not found in the manifest");
+        }
+
+        initialize(descriptorLocations);
+    }
+
+    /**
+     * Gets the MetaData location, parses the meta data and requests the processing
+     * of binder instances
+     * 
+     * @param descriptorLocations A comma separated list of locations of
+     *      component descriptors. This must not be <code>null</code>.
+     *      
+     * @throws IllegalStateException If the bundle has already been uninstalled.
+     */
+    private void initialize(String descriptorLocations) {
+
+        // 112.4.1: The value of the the header is a comma separated list of XML entries within the Bundle 
+		StringTokenizer st = new StringTokenizer(descriptorLocations, ", ");
+        
+		while (st.hasMoreTokens()) {
+			String descriptorLocation = st.nextToken();
+			
+            URL descriptorURL = m_context.getBundle().getResource(descriptorLocation);
+            if (descriptorURL == null)
+            {
+                // 112.4.1 If an XML document specified by the header cannot be located in the bundle and its attached
+                // fragments, SCR must log an error message with the Log Service, if present, and continue.
+                Activator.error("Component descriptor entry '" + descriptorLocation + "' not found");
+                continue;
+            }
+
+			try {
+				InputStream stream = descriptorURL.openStream();
+
+				BufferedReader in = new BufferedReader(new InputStreamReader(stream)); 
+	            XmlHandler handler = new XmlHandler(); 
+	            KXml2SAXParser parser;
+
+	            parser = new KXml2SAXParser(in); 
+
+		        parser.parseXML(handler);
+
+		        // 112.4.2 Component descriptors may contain a single, root component element
+		        // or one or more component elements embedded in a larger document
+		        Iterator i = handler.getComponentMetadataList().iterator();
+		        while (i.hasNext()) {
+                    ComponentMetadata metadata = (ComponentMetadata) i.next();
+                	try
+                    {
+                        // validate the component metadata
+    		            validate(metadata);
+    		        	
+    	                // Request creation of the component manager
+    	                ComponentManager manager = ManagerFactory.createManager(this,metadata);
+                		
+                		if(metadata.isFactory())
+                        {
+                			// 112.2.4 SCR must register a Component Factory service on behalf ot the component
+                			// as soon as the component factory is satisfied
+                		}
+                		else if(metadata.isEnabled())
+                        {
+		                	// enable the component
+		                	manager.enable();
+		                }
+
+                		// register the manager
+                		m_managers.add(manager);
+                    }
+                    catch (Exception e)
+                    {
+						// There is a problem with this particular component, we'll log the error
+	                	// and proceed to the next one
+                        Activator.exception("Cannot register Component", metadata, e);
+					} 
+		        }
+		        
+		        stream.close();
+
+			}
+			catch ( IOException ex )
+            {
+				// 112.4.1 If an XML document specified by the header cannot be located in the bundle and its attached
+				// fragments, SCR must log an error message with the Log Service, if present, and continue.
+				
+				Activator.exception("Problem reading descriptor entry '"
+                    + descriptorLocation + "'", null, ex);
+			}
+			catch (Exception ex)
+            {
+                Activator.exception("General problem with descriptor entry '"
+                    + descriptorLocation + "'", null, ex);
+			}
+		}
+    }
+
+    /**
+    * Dispose of this component activator instance and all the component
+    * managers.
+    */
+    void dispose()
+    {
+        if (m_context == null) {
+            return;
+        }
+
+        Activator.trace("BundleComponentActivator : Bundle ["
+            + m_context.getBundle().getBundleId() + "] will destroy "
+            + m_managers.size() + " instances", null);
+
+        while (m_managers.size() !=0 )
+        {
+            ComponentManager manager = (ComponentManager) m_managers.get(0);
+            try
+            {
+                m_managers.remove(manager);
+                manager.dispose();
+            }
+            catch(Exception e)
+            {
+                Activator.exception("BundleComponentActivator : Exception invalidating",
+                    manager.getComponentMetadata(), e);
+            }
+            finally
+            {
+            	m_componentNames.remove(manager.getComponentMetadata().getName());
+            }
+            
+        }
+
+        Activator.trace("BundleComponentActivator : Bundle ["
+            + m_context.getBundle().getBundleId() + "] STOPPED", null);
+
+        m_context = null;
+    }
+
+   /**
+    * Returns the list of instance references currently associated to this activator
+    *
+    * @return the list of instance references
+    */
+    protected List getInstanceReferences()
+    {
+        return m_managers;
+    }
+
+    /**
+    * Returns the BundleContext
+    *
+    * @return the BundleContext
+    */
+    protected BundleContext getBundleContext()
+    {
+        return m_context;
+    }
+
+    /**
+     * Implements the <code>ComponentContext.enableComponent(String)</code>
+     * method by first finding the component(s) for the <code>name</code> and
+     * then starting a thread to actually enable all components found.
+     * <p>
+     * If no component matching the given name is found the thread is not
+     * started and the method does nothing. 
+     * 
+     * @param name The name of the component to enable or <code>null</code> to
+     *      enable all components.
+     */
+    void enableComponent(String name)
+    {
+        final ComponentManager[] cm = getSelectedComponents(name);
+        if (cm == null)
+        {
+            return;
+        }
+        
+        Thread enabler = new Thread("Component Enabling") 
+        {
+            public void run()
+            {
+                for (int i=0; i < cm.length; i++)
+                {
+                    try
+                    {
+                        cm[i].enable();
+                    }
+                    catch (Throwable t) 
+                    {
+                        Activator.exception("Cannot enable component",
+                            cm[i].getComponentMetadata(), t);
+                    }
+                }
+            }
+        };
+        enabler.start();
+    }
+    
+    /**
+     * Implements the <code>ComponentContext.disableComponent(String)</code>
+     * method by first finding the component(s) for the <code>name</code> and
+     * then starting a thread to actually disable all components found.
+     * <p>
+     * If no component matching the given name is found the thread is not
+     * started and the method does nothing. 
+     * 
+     * @param name The name of the component to disable or <code>null</code> to
+     *      disable all components.
+     */
+    void disableComponent(String name)
+    {
+        final ComponentManager[] cm = getSelectedComponents(name);
+        if (cm == null)
+        {
+            return;
+        }
+        
+        Thread disabler = new Thread("Component Disabling")
+        {
+            public void run()
+            {
+                for (int i=0; i < cm.length; i++)
+                {
+                    try
+                    {
+                        cm[i].dispose();
+                    }
+                    catch (Throwable t)
+                    {
+                        Activator.exception("Cannot disable component",
+                            cm[i].getComponentMetadata(), t);
+                    }
+                }
+            }
+        };
+        disabler.start();
+    }
+    
+    /**
+     * Returns an array of {@link ComponentManager} instances which match the
+     * <code>name</code>. If the <code>name</code> is <code>null</code> an
+     * array of all currently known component managers is returned. Otherwise
+     * an array containing a single component manager matching the name is
+     * returned if one is registered. Finally, if no component manager with the
+     * given name is registered, <code>null</code> is returned.
+     *  
+     * @param name The name of the component manager to return or
+     *      <code>null</code> to return an array of all component managers.
+     *      
+     * @return An array containing one or more component managers according
+     *      to the <code>name</code> parameter or <code>null</code> if no
+     *      component manager with the given name is currently registered.
+     */
+    private ComponentManager[] getSelectedComponents(String name) {
+        // if all components are selected
+        if (name == null)
+        {
+            return (ComponentManager[]) m_managers.toArray(new ComponentManager[m_managers.size()]);
+        }
+        
+        if (m_componentNames.contains(name))
+        {
+            // otherwise just find it
+            Iterator it = m_managers.iterator();
+            while (it.hasNext())
+            {
+                ComponentManager cm = (ComponentManager) it.next();
+                if (name.equals(cm.getComponentMetadata().getName())) {
+                    return new ComponentManager[]{ cm  };
+                }
+            }
+        }
+        
+        // if the component is not known
+        return null;
+    }
+
+    /**
+     * This method is used to validate that the component. This method verifies multiple things:
+     * 
+     * 1.- That the name attribute is set and is globally unique
+     * 2.- That an implementation class name has been set 
+     * 3.- That a delayed component provides a service and is not specified to be a factory
+     * - That the serviceFactory attribute for the provided service is not true if the component is a factory or immediate
+     * 
+     * If the component is valid, its name is registered
+     * 
+     * @throws A ComponentException if something is not right
+     */
+    void validate(ComponentMetadata component) throws ComponentException
+    {
+
+    	if(m_componentNames.contains(component.getName()))
+    	{
+    		throw new ComponentException("The component name '"+component.getName()+"' has already been registered.");
+    	}
+    	
+        component.validate();
+
+        // register the component after validation
+        m_componentNames.add(component.getName());
+    	
+        Activator.trace("Validated and registered component",component);
+    }
+}

Propchange: incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/BundleComponentActivator.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ComponentManagerImpl.java
URL: http://svn.apache.org/viewvc/incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ComponentManagerImpl.java?view=diff&rev=449050&r1=449049&r2=449050
==============================================================================
--- incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ComponentManagerImpl.java (original)
+++ incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ComponentManagerImpl.java Fri Sep 22 11:55:50 2006
@@ -29,7 +29,7 @@
  * implementation object's lifecycle.  
  *
  */
-public class ComponentManagerImpl implements ComponentManager, ComponentInstance
+class ComponentManagerImpl implements ComponentManager, ComponentInstance
 {
 	// States of the instance manager
 	static final int INSTANCE_CREATING = 0;
@@ -63,8 +63,8 @@
     // The ServiceRegistration
     private ServiceRegistration m_serviceRegistration = null;
 
-    // A reference to the GenericActivator
-    private GenericActivator m_activator = null;
+    // A reference to the BundleComponentActivator
+    private BundleComponentActivator m_activator = null;
 
     // The context that will be passed to the implementationObject
     private ComponentContext m_componentContext = null;
@@ -78,7 +78,7 @@
      * @param activator
      * @param metadata
      */
-    ComponentManagerImpl(GenericActivator activator,ComponentMetadata metadata)
+    ComponentManagerImpl(BundleComponentActivator activator, ComponentMetadata metadata)
     {
     	// Store the activator reference
         m_activator = activator;
@@ -94,7 +94,7 @@
      */
     public boolean enable() {
     	
-    	GenericActivator.trace("Enabling component", m_componentMetadata);
+        Activator.trace("Enabling component", m_componentMetadata);
     	
     	try
     	{
@@ -182,7 +182,7 @@
         // If the component is not immediate, this is not done at this moment
         if( m_componentMetadata.isImmediate() == true )
         {
-        	//GenericActivator.trace("Loading implementation class and creating instance for component '"+m_componentMetadata.getName()+"'");
+            //Activator.trace("Loading implementation class and creating instance for component '"+m_componentMetadata.getName()+"'");
         	try
 	        {
 	        	// 112.4.4 The class is retrieved with the loadClass method of the component's bundle
@@ -196,7 +196,7 @@
 	        catch (Exception ex)
 	        {
 	            // TODO: manage this exception when implementation object cannot be created
-	            GenericActivator.exception("Error during instantiation", m_componentMetadata, ex);
+	            Activator.exception("Error during instantiation", m_componentMetadata, ex);
 	            deactivate();
 	            //invalidate();
 	            return;
@@ -208,7 +208,7 @@
         // 3. Bind the target services
         it = m_dependencyManagers.iterator();
 
-        //GenericActivator.trace("Binding target services for component '"+m_componentMetadata.getName()+"'");
+        //Activator.trace("Binding target services for component '"+m_componentMetadata.getName()+"'");
         
         while (it.hasNext())
         {
@@ -222,7 +222,7 @@
             }
         }
         
-        //GenericActivator.trace("Calling activate for component '"+m_componentMetadata.getName()+"'");
+        //Activator.trace("Calling activate for component '"+m_componentMetadata.getName()+"'");
         
         // 4. Call the activate method, if present
 	        // We need to check if we are still validating because it is possible that when we
@@ -238,17 +238,17 @@
         		activateMethod.invoke(m_implementationObject, new Object[]{m_componentContext});
         	}
         	catch(NoSuchMethodException ex) {        		
-        		// We can safely ignore this one
-        		GenericActivator.trace("activate() method not implemented", m_componentMetadata);
+        	    // We can safely ignore this one
+        	    Activator.trace("activate() method not implemented", m_componentMetadata);
         	}
         	catch(IllegalAccessException ex) {
-        		// TODO: Log this exception?
-        		GenericActivator.trace("activate() method cannot be called", m_componentMetadata);
+        	    // TODO: Log this exception?
+        	    Activator.trace("activate() method cannot be called", m_componentMetadata);
         	}
         	catch(InvocationTargetException ex) {
-        		// TODO: 112.5.8 If the activate method throws an exception, SCR must log an error message
-        		// containing the exception with the Log Service
-        		GenericActivator.exception("The activate method has thrown an exception", m_componentMetadata, ex.getTargetException());
+        	    // TODO: 112.5.8 If the activate method throws an exception, SCR must log an error message
+        	    // containing the exception with the Log Service
+        	    Activator.exception("The activate method has thrown an exception", m_componentMetadata, ex.getTargetException());
         	}
         }
         
@@ -259,7 +259,7 @@
         // 5. Register provided services
         if(m_componentMetadata.getServiceMetadata() != null)
         {
-            GenericActivator.trace("registering services", m_componentMetadata);
+            Activator.trace("registering services", m_componentMetadata);
 
         	if( m_componentMetadata.isImmediate() == true ) {
 	        	// In the case the component is immediate, the implementation object is registered
@@ -298,7 +298,7 @@
 	        m_serviceRegistration.unregister();
 	        m_serviceRegistration = null;
 
-	        GenericActivator.trace("unregistering the services", m_componentMetadata);
+	        Activator.trace("unregistering the services", m_componentMetadata);
 	    }
 
         // 1.- Call the deactivate method, if present	    
@@ -313,17 +313,17 @@
 			}
 		}
 		catch(NoSuchMethodException ex) {
-			// We can safely ignore this one
-			GenericActivator.trace("deactivate() method is not implemented", m_componentMetadata);
+            // We can safely ignore this one
+			Activator.trace("deactivate() method is not implemented", m_componentMetadata);
 		}
 		catch(IllegalAccessException ex) {
 			// Ignored, but should it be logged?
-			GenericActivator.trace("deactivate() method cannot be called", m_componentMetadata);
+			Activator.trace("deactivate() method cannot be called", m_componentMetadata);
 		}
 		catch(InvocationTargetException ex) {
 			// TODO: 112.5.12 If the deactivate method throws an exception, SCR must log an error message
 			// containing the exception with the Log Service
-			GenericActivator.exception("The deactivate method has thrown and exception", m_componentMetadata, ex);
+			Activator.exception("The deactivate method has thrown and exception", m_componentMetadata, ex);
 		}
 
         // 2. Unbind any bound services
@@ -340,7 +340,7 @@
         m_componentContext = null;
         m_delayedComponentServiceFactory = null;
 
-        //GenericActivator.trace("InstanceManager from bundle ["+ m_activator.getBundleContext().getBundle().getBundleId() + "] was invalidated.");
+        //Activator.trace("InstanceManager from bundle ["+ m_activator.getBundleContext().getBundle().getBundleId() + "] was invalidated.");
 
         if (m_state != INSTANCE_DESTROYING)
         {
@@ -353,7 +353,7 @@
      */
     public synchronized void dispose()
     {
-        // CONCURRENCY NOTE: This method is only called from the GenericActivator or by application logic
+        // CONCURRENCY NOTE: This method is only called from the BundleComponentActivator or by application logic
     	// but not by the dependency managers
 
         // Theoretically this should never be in any state other than VALID or INVALID,
@@ -411,7 +411,7 @@
      * sets the state of the manager
     **/
     private synchronized void setState(int newState) {
-    	GenericActivator.trace("State transition : "+m_states[m_state]+" -> "+m_states[newState], m_componentMetadata);
+        Activator.trace("State transition : "+m_states[m_state]+" -> "+m_states[newState], m_componentMetadata);
     	
         m_state = newState;
         
@@ -497,7 +497,7 @@
                     if(retval == false && (max == 1))
                     {
                         // There was an exception when calling the bind method
-                        GenericActivator.error("Dependency Manager: Possible exception in the bind method during initialize()");
+                        Activator.error("Dependency Manager: Possible exception in the bind method during initialize()");
                         m_isValid = false;
                         //setStateDependency(DependencyChangeEvent.DEPENDENCY_INVALID);
                         return m_isValid;
@@ -563,7 +563,7 @@
             }
             catch (Exception e)
             {
-                GenericActivator.error("DependencyManager: exception while getting references :"+e);
+                Activator.error("DependencyManager: exception while getting references :"+e);
                 return null;
             }
         }
@@ -649,9 +649,8 @@
                     }
             	} 
             	catch(ClassNotFoundException ex2) {
-            		GenericActivator.exception("Cannot load class used as parameter "+parameterClassName,m_componentMetadata,ex2);
+            		Activator.exception("Cannot load class used as parameter "+parameterClassName,m_componentMetadata,ex2);
             	}
-
             }
                         
             return method;
@@ -678,7 +677,7 @@
 		            	// 112.3.1 If the method is not found , SCR must log an error
 		            	// message with the log service, if present, and ignore the method
 		            	// TODO: log error message
-		            	GenericActivator.trace("bind() method not found", m_componentMetadata);
+		                Activator.trace("bind() method not found", m_componentMetadata);
 		            	return false;
 		            }
 		            
@@ -709,7 +708,7 @@
 		        }
 		        catch(InvocationTargetException ex)
 		        {
-		        	GenericActivator.exception("DependencyManager : exception while invoking "+m_dependencyMetadata.getBind()+"()", m_componentMetadata, ex);
+		        	Activator.exception("DependencyManager : exception while invoking "+m_dependencyMetadata.getBind()+"()", m_componentMetadata, ex);
 		            return false;
 		        }
         	} else if( m_implementationObject == null && m_componentMetadata.isImmediate() == false) {
@@ -739,7 +738,7 @@
 	            try
 	            {
 	            	// TODO: me quede aqui por que el unbind method no funciona
-	            	GenericActivator.trace("getting unbind: "+m_dependencyMetadata.getUnbind(), m_componentMetadata);
+	                Activator.trace("getting unbind: "+m_dependencyMetadata.getUnbind(), m_componentMetadata);
 	            	Method unbindMethod = getBindingMethod(m_dependencyMetadata.getUnbind(), getInstance().getClass(), m_dependencyMetadata.getInterface());
 	            	
 		        	// Recover the object that is bound from the map.
@@ -756,7 +755,7 @@
 	                	// 112.3.1 If the method is not found , SCR must log an error
 	                	// message with the log service, if present, and ignore the method
 	                	// TODO: log error message
-	                	GenericActivator.trace("unbind() method not found", m_componentMetadata);
+	            	    Activator.trace("unbind() method not found", m_componentMetadata);
 	                	return false;
 	                }
 	
@@ -775,7 +774,7 @@
 	            	return false;
 	            }
 	            catch (InvocationTargetException ex) {
-	            	GenericActivator.exception("DependencyManager : exception while invoking "+m_dependencyMetadata.getUnbind()+"()", m_componentMetadata, ex);
+	                Activator.exception("DependencyManager : exception while invoking "+m_dependencyMetadata.getUnbind()+"()", m_componentMetadata, ex);
 	            	return false;
 	            }
 	            
@@ -829,14 +828,14 @@
                             //setStateDependency(DependencyChangeEvent.DEPENDENCY_INVALID);
                             try
                             {
-                                GenericActivator.trace("Dependency Manager: Static dependency is broken", m_componentMetadata);
+                                Activator.trace("Dependency Manager: Static dependency is broken", m_componentMetadata);
                                 deactivate();
-                                GenericActivator.trace("Dependency Manager: RECREATING", m_componentMetadata);
+                                Activator.trace("Dependency Manager: RECREATING", m_componentMetadata);
                                 activate();
                             }
                             catch(Exception ex)
                             {
-                            	GenericActivator.exception("Exception while recreating dependency ",m_componentMetadata, ex);
+                                Activator.exception("Exception while recreating dependency ",m_componentMetadata, ex);
                             }
                         }
                         // dynamic dependency
@@ -859,9 +858,9 @@
                                 {
                                     if (!m_dependencyMetadata.isOptional())
                                     {
-                                        GenericActivator.trace("Dependency Manager: Mandatory dependency not fullfilled and no replacements available... unregistering service...", m_componentMetadata);
+                                        Activator.trace("Dependency Manager: Mandatory dependency not fullfilled and no replacements available... unregistering service...", m_componentMetadata);
                                         deactivate();
-                                        GenericActivator.trace("Dependency Manager: Recreating", m_componentMetadata);
+                                        Activator.trace("Dependency Manager: Recreating", m_componentMetadata);
                                         activate();
                                     }
                                 }
@@ -875,7 +874,7 @@
                     if (m_boundServicesRefs.contains(evt.getServiceReference()) == true)
                     {
                         // This is a duplicate
-                        GenericActivator.trace("DependencyManager : ignoring REGISTERED ServiceEvent (already bound)", m_componentMetadata);
+                        Activator.trace("DependencyManager : ignoring REGISTERED ServiceEvent (already bound)", m_componentMetadata);
                     }
                     else
                     {
@@ -1037,14 +1036,12 @@
     		return ComponentManagerImpl.this;
     	}
 
-    	public void enableComponent(String arg0) {
-    		// TODO implement this method
-    		
+    	public void enableComponent(String name) {
+    	    m_activator.enableComponent(name);
     	}
 
-    	public void disableComponent(String arg0) {
-    		// TODO implement this method
-    		
+    	public void disableComponent(String name) {
+    	    m_activator.disableComponent(name);
     	}
 
     	public ServiceReference getServiceReference() {
@@ -1065,7 +1062,7 @@
     	
     	public Object getService(Bundle arg0, ServiceRegistration arg1) {
     		
-    		GenericActivator.trace("DelayedComponentServiceFactory.getService()", m_componentMetadata);
+    	    Activator.trace("DelayedComponentServiceFactory.getService()", m_componentMetadata);
     		// When the getServiceMethod is called, the implementation object must be created
     		
             // 1. Load the component implementation class
@@ -1084,7 +1081,7 @@
 	        catch (Exception ex)
 	        {
 	            // TODO: manage this exception when implementation object cannot be created
-	            GenericActivator.exception("Error during instantiation of the implementation object",m_componentMetadata,ex);
+	            Activator.exception("Error during instantiation of the implementation object",m_componentMetadata,ex);
 	            deactivate();
 	            //invalidate();
 	            return null;
@@ -1112,16 +1109,16 @@
         	}
         	catch(NoSuchMethodException ex) {
                 // We can safely ignore this one
-                GenericActivator.trace("activate() method is not implemented", m_componentMetadata);
+                Activator.trace("activate() method is not implemented", m_componentMetadata);
             }
             catch(IllegalAccessException ex) {
                 // Ignored, but should it be logged?
-                GenericActivator.trace("activate() method cannot be called", m_componentMetadata);
+                Activator.trace("activate() method cannot be called", m_componentMetadata);
             }
             catch(InvocationTargetException ex) {
                 // TODO: 112.5.8 If the activate method throws an exception, SCR must log an error message
                 // containing the exception with the Log Service
-                GenericActivator.exception("The activate method has thrown and exception", m_componentMetadata, ex);
+                Activator.exception("The activate method has thrown and exception", m_componentMetadata, ex);
             }
     		
     		return m_implementationObject;
@@ -1129,7 +1126,6 @@
 
     	public void ungetService(Bundle arg0, ServiceRegistration arg1, Object arg2) {
     		// TODO Auto-generated method stub
-
     	}
     }
 

Modified: incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ManagerFactory.java
URL: http://svn.apache.org/viewvc/incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ManagerFactory.java?view=diff&rev=449050&r1=449049&r2=449050
==============================================================================
--- incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ManagerFactory.java (original)
+++ incubator/felix/trunk/scr/src/main/java/org/apache/felix/scr/ManagerFactory.java Fri Sep 22 11:55:50 2006
@@ -23,8 +23,8 @@
  */
 public class ManagerFactory {
 	
-	static ComponentManager createManager(GenericActivator activator, ComponentMetadata metadata) {
-		GenericActivator.trace("ManagerFactory.createManager", metadata);
-		return new ComponentManagerImpl(activator,metadata);
+	static ComponentManager createManager(BundleComponentActivator activator, ComponentMetadata metadata) {
+	    Activator.trace("ManagerFactory.createManager", metadata);
+	    return new ComponentManagerImpl(activator,metadata);
 	}
-}
+}
\ No newline at end of file



Mime
View raw message