Author: mes
Date: 2011-09-12 14:58:22 -0700 (Mon, 12 Sep 2011)
New Revision: 26762

Added:
   
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/AbstractCyActivator.java
   
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/internal/CyServiceListener.java
Modified:
   core3/api/branches/no-spring/service-api/pom.xml
Log:
added abstract activator

Modified: core3/api/branches/no-spring/service-api/pom.xml
===================================================================
--- core3/api/branches/no-spring/service-api/pom.xml    2011-09-12 21:42:35 UTC 
(rev 26761)
+++ core3/api/branches/no-spring/service-api/pom.xml    2011-09-12 21:58:22 UTC 
(rev 26762)
@@ -86,6 +86,12 @@
                        <version>${osgi.api.version}</version>
                        <scope>provided</scope>
                </dependency>
+        <dependency>
+            <groupId>org.osgi</groupId>
+            <artifactId>org.osgi.compendium</artifactId>
+            <version>${osgi.api.version}</version>
+            <scope>provided</scope>
+        </dependency>
        </dependencies>
 
 </project>

Added: 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/AbstractCyActivator.java
===================================================================
--- 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/AbstractCyActivator.java
                          (rev 0)
+++ 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/AbstractCyActivator.java
  2011-09-12 21:58:22 UTC (rev 26762)
@@ -0,0 +1,175 @@
+
+package org.cytoscape.service.util;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Properties;
+import org.osgi.framework.BundleContext; 
+import org.osgi.framework.BundleActivator; 
+import org.osgi.framework.ServiceRegistration; 
+import org.osgi.framework.ServiceReference; 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.cytoscape.service.util.internal.CyServiceListener;
+
+/**
+ * A simple BundleActivator with convenience methods for registering
+ * OSGi services and either getting references to single services or
+ * registering interest in all services of a specified type.  
+ *
+ * Users should extend this class and at implement the start(BundleContext bc)
+ * method.  
+ * 
+ */
+public abstract class AbstractCyActivator implements BundleActivator {
+
+       private static final Logger logger = 
LoggerFactory.getLogger(AbstractCyActivator.class);
+       
+       private final Map<Class,Map<Object,ServiceRegistration>> 
serviceRegistrations;
+       private final List<CyServiceListener> serviceListeners;
+       private final List<ServiceReference> gottenServices;
+
+       /**
+        * Constructor.
+        */
+       public AbstractCyActivator() {
+               serviceRegistrations = new 
HashMap<Class,Map<Object,ServiceRegistration>>();
+               serviceListeners = new ArrayList<CyServiceListener>();
+               gottenServices = new ArrayList<ServiceReference>();
+       }
+
+       /**
+        * A default implementation of the BundleActivator.stop() method that 
cleans
+        * up any services registered, services gotten, or services being 
listened
+        * for as determined by calls to the utility methods provided by this 
class. If
+        * you register a service, get a service, or listen for services 
outside yourself
+        * using normal calls to the OSGi API, you will need to clean 
everything up 
+        * yourself!
+        */
+       public void stop(BundleContext bc) {
+               // unregister and clear all services registered 
+               for ( Map<Object,ServiceRegistration> registrations : 
serviceRegistrations.values() )  {
+                       for ( ServiceRegistration reg : registrations.values() 
) 
+                               reg.unregister();
+                       registrations.clear();
+               }
+               serviceRegistrations.clear();
+
+               // unregister and clear all service listeners
+               for ( CyServiceListener listener : serviceListeners )
+                       listener.close();
+               serviceListeners.clear();
+
+               // unget and clear all services
+               for ( ServiceReference ref : gottenServices )
+                       bc.ungetService(ref);
+               gottenServices.clear();
+       }
+
+       /**
+        * A method that attempts to get a service of the specified type. If an 
+        * appropriate service is not found, an exception will be thrown.
+        * @param bc The BundleContext used to find services.
+        * @param serviceClass The class defining the type of service desired.
+        * @return A reference to a service of type serviceClass.
+        * @throws RuntimeException If the requested service can't be found.
+        */
+       protected <S> S getService(BundleContext bc, Class<S> serviceClass) {
+               try {
+                       ServiceReference ref = 
bc.getServiceReference(serviceClass.getName());
+                       if ( ref == null ) 
+                               throw new 
NullPointerException("ServiceReference is null for: " + serviceClass.getName());
+
+                       gottenServices.add(ref);        
+                       return serviceClass.cast( bc.getService(ref) );
+
+               } catch (Exception e) {
+                       throw new RuntimeException("Couldn't find service: " + 
serviceClass.getName(),e);
+               }
+       }
+
+       /**
+        * A method that attempts to get a service of the specified type and 
that
+        * passes the specified filter. If an appropriate service is not found, 
an 
+        * exception will be thrown.
+        * @param bc The BundleContext used to find services.
+        * @param serviceClass The class defining the type of service desired.
+        * @param filter The string defining the filter the service must pass.  
See OSGi's 
+        * service filtering syntax for more detail.
+        * @return A reference to a service of type serviceClass that passes 
the specified filter.
+        * @throws RuntimeException If the requested service can't be found.
+        */
+       protected <S> S getService(BundleContext bc, Class<S> serviceClass, 
String filter) {
+               try { 
+                       ServiceReference[] refs = 
bc.getServiceReferences(serviceClass.getName(),filter);
+                       if ( refs == null ) 
+                               throw new 
NullPointerException("ServiceReference is null for: " + serviceClass.getName() 
+ " with filter: " + filter);
+
+                       gottenServices.add(refs[0]);    
+                       return serviceClass.cast( bc.getService(refs[0]) );
+               } catch (Exception e) {
+                       throw new RuntimeException("Couldn't find service: " + 
serviceClass.getName() + " with filter: " + filter, e);
+               }
+       }
+
+       /**
+        * A method that will cause the specified register/unregister methods 
on the listener
+        * object to be called any time that a service of the specified type is 
registered or
+        * unregistered. 
+        * @param bc The BundleContext used to find services.
+        * @param listener Your object listening for service registrations.
+        * @param registerMethodName The name of the method to be called when a 
service is registered.
+        * @param unregisterMethodName The name of the method to be called when 
a service is unregistered.
+        * @param serviceClass The class defining the type of service desired.
+        */
+       protected void registerServiceListener(final BundleContext bc, final 
Object listener, final String registerMethodName, final String 
unregisterMethodName, final Class<?> serviceClass) {
+               try {
+                       CyServiceListener serviceListener = new 
CyServiceListener(bc, listener, registerMethodName, unregisterMethodName, 
serviceClass);
+                       serviceListener.open();
+                       serviceListeners.add( serviceListener );
+               } catch (Exception e) {
+                       throw new RuntimeException("Could not listen to 
services for object: " + listener + " with methods: " + registerMethodName + " 
and " + unregisterMethodName + " and service type: " + serviceClass, e); 
+               }
+       }
+
+       /**
+        * A utility method that registers the specified service object as an 
OSGi service for
+        * all interfaces that the object implements.
+        * @param bc The BundleContext used to find services.
+        * @param service The object to be registered as one or more services.
+        * @param props The service properties to be registered with each 
service. 
+        */
+       protected void registerAllServices(final BundleContext bc, final Object 
service, final Properties props) {
+               for ( Class<?> c : service.getClass().getInterfaces() ) 
+                       registerService(bc, service, c, props);
+       }
+
+       /**
+        * A utility method that registers the specified service object as an 
OSGi service of
+        * the specified type.
+        * @param bc The BundleContext used to find services.
+        * @param service The object to be registered as one or more services.
+        * @param serviceClass The class defining the type of service to be 
registered.
+        * @param props The service properties to be registered with each 
service. 
+        */
+       protected void registerService(final BundleContext bc, final Object 
service, final Class<?> serviceClass, final Properties props) {
+               if ( service == null )
+                       throw new NullPointerException( "service object is 
null" );
+               if ( serviceClass == null )
+                       throw new NullPointerException( "class is null" );
+               if ( props == null )
+                       throw new NullPointerException( "props are null" );
+               if ( bc == null )
+                       throw new IllegalStateException( "BundleContext is 
null" );
+
+               logger.debug("attempting to register service: " + 
service.toString() + " of type " + serviceClass.getName());
+               ServiceRegistration s = bc.registerService( 
serviceClass.getName(), service, props );
+
+               if ( !serviceRegistrations.containsKey(serviceClass) )
+                       serviceRegistrations.put(serviceClass, new 
HashMap<Object,ServiceRegistration>() );
+
+               serviceRegistrations.get(serviceClass).put(service,s);
+       }
+}

Added: 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/internal/CyServiceListener.java
===================================================================
--- 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/internal/CyServiceListener.java
                           (rev 0)
+++ 
core3/api/branches/no-spring/service-api/src/main/java/org/cytoscape/service/util/internal/CyServiceListener.java
   2011-09-12 21:58:22 UTC (rev 26762)
@@ -0,0 +1,125 @@
+
+/*
+ Copyright (c) 2006, 2007, The Cytoscape Consortium (www.cytoscape.org)
+
+ The Cytoscape Consortium is:
+ - Institute for Systems Biology
+ - University of California San Diego
+ - Memorial Sloan-Kettering Cancer Center
+ - Institut Pasteur
+ - Agilent Technologies
+
+ This library is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published
+ by the Free Software Foundation; either version 2.1 of the License, or
+ any later version.
+
+ This library is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
+ MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  The software and
+ documentation provided hereunder is on an "as is" basis, and the
+ Institute for Systems Biology and the Whitehead Institute
+ have no obligations to provide maintenance, support,
+ updates, enhancements or modifications.  In no event shall the
+ Institute for Systems Biology and the Whitehead Institute
+ be liable to any party for direct, indirect, special,
+ incidental or consequential damages, including lost profits, arising
+ out of the use of this software and its documentation, even if the
+ Institute for Systems Biology and the Whitehead Institute
+ have been advised of the possibility of such damage.  See
+ the GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this library; if not, write to the Free Software Foundation,
+ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+package org.cytoscape.service.util.internal;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.util.tracker.ServiceTracker;
+
+import java.lang.reflect.Method;
+import java.lang.NoSuchMethodException;
+import java.util.Properties;
+import java.util.Dictionary;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+
+public class CyServiceListener extends ServiceTracker {
+
+
+       private final BundleContext bc;
+       private final Object target;
+       private final Method registerMethod;
+       private final Method unregisterMethod;
+       private final Class<?> serviceClass;
+       private static final Logger logger = 
LoggerFactory.getLogger(CyServiceListener.class);
+       
+       public CyServiceListener(BundleContext bc, Object target, String 
registerMethodName, String unregisterMethodName, Class<?> serviceClass) throws 
NoSuchMethodException {
+               super(bc, serviceClass.getName(), null);
+               this.bc = bc;
+               this.target = target;
+               this.serviceClass = serviceClass;
+               this.registerMethod = getMethod(registerMethodName);
+               this.unregisterMethod = getMethod(unregisterMethodName);
+       }
+
+       /**
+        * Tries the different possible method declarations.
+        */
+       private Method getMethod(String name) throws NoSuchMethodException {
+               Method m; 
+               try {
+                       m = target.getClass().getMethod(name, serviceClass, 
Dictionary.class);
+               } catch (NoSuchMethodException e) {
+                       // Ignore exception and try different signature.
+                       // If we throw an exception here, we WANT it to 
+                       // propagate, because that signals an error.
+                       m = target.getClass().getMethod(name, serviceClass, 
Map.class);
+               }
+               return m;
+       }
+
+       /**
+        * Invokes the register method on the listener target class with the 
specified service.
+        */
+       @Override
+       public Object addingService(ServiceReference ref) {
+               try {
+                       Object service = super.addingService(ref);
+                       registerMethod.invoke(target, 
serviceClass.cast(service), getProperties(ref));
+                       return service;
+               } catch (Exception nse) {
+                       logger.warn("Failed to register service: ",nse);
+               }
+               return null;
+       }
+
+       /**
+        * Invokes the UNregister method on the listener target class with the 
specified service.
+        */
+       @Override
+       public void removedService(ServiceReference ref, Object service) {
+               super.removedService(ref, service);
+               try {
+                       unregisterMethod.invoke(target, 
serviceClass.cast(service), getProperties(ref));
+               } catch (Exception nse) {
+                       logger.warn("Failed to unregister service: ",nse);
+               }
+       }
+
+       /**
+        * Converts the service properties contained in a ServiceReference to a 
Properties object.
+        */
+       private Properties getProperties(ServiceReference ref) {
+               Properties props = new Properties();
+               for ( String key : ref.getPropertyKeys() )
+                       props.setProperty(key,(String)(ref.getProperty(key)));
+               return props;
+       }
+}

-- 
You received this message because you are subscribed to the Google Groups 
"cytoscape-cvs" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/cytoscape-cvs?hl=en.

Reply via email to