Java Code Examples for org.osgi.framework.ServiceReference

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project camel-osgi, under directory /component/src/test/java/org/apache/camel/osgi/service/util/.

Source file: OsgiDefaultProxyCreatorTest.java

  36 
vote

@Test public void testCreateProxy() throws Exception {
  BundleContext bundleContext=mock(BundleContext.class);
  ServiceReference reference=mock(ServiceReference.class,RETURNS_MOCKS);
  when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[]{List.class.getName()});
  OsgiDefaultProxyCreator creator=new OsgiDefaultProxyCreator();
  Object proxy=creator.createProxy(bundleContext,reference,getClass().getClassLoader());
  assertThat(proxy,instanceOf(OsgiProxy.class));
  assertThat(proxy,instanceOf(ServiceReference.class));
  assertThat(proxy,instanceOf(List.class));
  verify(reference).getBundle();
}
 

Example 2

From project arquillian-container-osgi, under directory /bundle/src/main/java/org/jboss/arquillian/osgi/.

Source file: ArquillianBundleActivator.java

  32 
vote

private MBeanServer getMBeanServer(BundleContext context){
  ServiceReference sref=context.getServiceReference(MBeanServer.class.getName());
  if (sref != null) {
    MBeanServer mbeanServer=(MBeanServer)context.getService(sref);
    log.fine("Found MBeanServer fom service: " + mbeanServer.getDefaultDomain());
    return mbeanServer;
  }
  return findOrCreateMBeanServer();
}
 

Example 3

From project arquillian-container-osgi, under directory /testenricher-osgi/src/main/java/org/jboss/arquillian/testenricher/osgi/.

Source file: OSGiTestEnricher.java

  32 
vote

private PackageAdmin getPackageAdmin(){
  BundleContext context=getBundleContext();
  ServiceReference sref=context.getServiceReference(PackageAdmin.class.getName());
  PackageAdmin packageAdmin=(PackageAdmin)context.getService(sref);
  return packageAdmin;
}
 

Example 4

From project arquillian_deprecated, under directory /protocols/jmx-osgi-bundle/src/main/java/org/jboss/arquillian/osgi/.

Source file: ArquillianBundleActivator.java

  32 
vote

private MBeanServer getMBeanServer(BundleContext context){
  ServiceReference sref=context.getServiceReference(MBeanServer.class.getName());
  if (sref != null) {
    MBeanServer mbeanServer=(MBeanServer)context.getService(sref);
    log.debug("Found MBeanServer fom service: " + mbeanServer.getDefaultDomain());
    return mbeanServer;
  }
  return OSGiTestEnricher.findOrCreateMBeanServer();
}
 

Example 5

From project arquillian_deprecated, under directory /testenrichers/osgi/src/main/java/org/jboss/arquillian/testenricher/osgi/.

Source file: OSGiTestEnricher.java

  32 
vote

private Bundle getTestBundle(Class<?> testClass){
  Bundle testbundle=bundleInst.get();
  if (testbundle == null) {
    BundleContext bundleContext=getSystemBundleContext();
    ServiceReference sref=bundleContext.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin pa=(PackageAdmin)bundleContext.getService(sref);
    testbundle=pa.getBundle(testClass);
  }
  return testbundle;
}
 

Example 6

From project bamboo-sonar-integration, under directory /bamboo-sonar-web/src/main/java/com/marvelution/bamboo/plugins/sonar/web/proxy/.

Source file: OsgiServiceProxy.java

  32 
vote

/** 
 * Static helper method to get a  {@link OsgiServiceProxy} {@link Proxy}
 * @param tracker the {@link ServiceTracker} to get a {@link Proxy} for
 * @param type the {@link Class} type of the Service Object
 * @return the {@link Proxy}
 */
@SuppressWarnings("unchecked") public static <T>T getServiceProxy(ServiceTracker tracker,Class<T> type){
  ServiceReference reference=tracker.getServiceReference();
  if (reference.isAssignableTo(reference.getBundle(),type.getName())) {
    InvocationHandler handler=new OsgiServiceProxy(tracker);
    return (T)Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},handler);
  }
 else {
    throw new OsgiContainerException("Service '" + reference.getBundle().getClass() + "' is not of type "+ type);
  }
}
 

Example 7

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/osgi/.

Source file: OSGiServiceHelper.java

  32 
vote

/** 
 * This method returns one service instance, or <code>null</code> if no service is currently registered.
 * @param bundleContext the  {@link BundleContext} of your plugin. You can obtain aninstance of the  {@link BundleContext} through your Activator.
 * @param clazz The  {@link Class} of the service. Typically an Java Interface
 * @return service instance of the given {@link Class} type, or<code>null</code>
 */
@SuppressWarnings({"rawtypes","unchecked"}) public static <T>T getService(BundleContext bundleContext,Class<T> clazz){
  ServiceReference serviceReference=bundleContext.getServiceReference(clazz.getName());
  if (serviceReference == null) {
    return null;
  }
  Object service=bundleContext.getService(serviceReference);
  if (service == null) {
    return null;
  }
  return (T)service;
}
 

Example 8

From project blueprint-namespaces, under directory /blueprint/blueprint-annotation-impl/src/main/java/org/apache/aries/blueprint/annotation/impl/.

Source file: BlueprintAnnotationScannerImpl.java

  32 
vote

private BundleAnnotationFinder createBundleAnnotationFinder(Bundle bundle){
  ServiceReference sr=this.context.getServiceReference(PackageAdmin.class.getName());
  PackageAdmin pa=(PackageAdmin)this.context.getService(sr);
  BundleAnnotationFinder baf=null;
  try {
    baf=new BundleAnnotationFinder(pa,bundle);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  this.context.ungetService(sr);
  return baf;
}
 

Example 9

From project blueprint-namespaces, under directory /blueprint/blueprint-cm/src/main/java/org/apache/aries/blueprint/compendium/cm/.

Source file: CmManagedServiceFactory.java

  32 
vote

private void destroy(Object component,ServiceRegistration registration,int code){
  if (listeners != null) {
    ServiceReference ref=registration.getReference();
    for (    ServiceListener listener : listeners) {
      Hashtable props=JavaUtils.getProperties(ref);
      listener.unregister(component,props);
    }
  }
  destroyComponent(component,code);
  AriesFrameworkUtil.safeUnregisterService(registration);
}
 

Example 10

From project bundlemaker, under directory /main/org.bundlemaker.core.ui/src/org/bundlemaker/core/ui/internal/.

Source file: Activator.java

  32 
vote

/** 
 * <p> </p>
 * @return
 */
public IArtifactModelConfigurationProvider getArtifactModelConfigurationProvider(){
  ServiceReference serviceReference=_bundleContext.getServiceReference(IArtifactModelConfigurationProvider.class.getName());
  if (serviceReference != null) {
    IArtifactModelConfigurationProvider provider=(IArtifactModelConfigurationProvider)_bundleContext.getService(serviceReference);
    return provider;
  }
  return null;
}
 

Example 11

From project camel-osgi, under directory /component/src/test/java/org/apache/camel/osgi/service/util/.

Source file: OsgiDefaultProxyCreatorTest.java

  32 
vote

@Test(expected=IllegalArgumentException.class) public void testCreateProxyNoBundle() throws Exception {
  BundleContext bundleContext=mock(BundleContext.class);
  ServiceReference reference=mock(ServiceReference.class);
  OsgiDefaultProxyCreator creator=new OsgiDefaultProxyCreator();
  creator.createProxy(bundleContext,reference,getClass().getClassLoader());
}
 

Example 12

From project cilia-workbench, under directory /cilia-workbench-monitoring/src/fr/liglab/adele/cilia/workbench/monitoring/.

Source file: Activator.java

  32 
vote

/** 
 * Gets the application monitored in the service registry.
 * @return the applicationMonitored, or null if not found.
 */
@SuppressWarnings({"rawtypes","unchecked"}) public static MonitoredApplication getMonitoredApplication(){
  ServiceReference srvRef=retrieveAdminService(MonitoredApplication.class);
  if (srvRef == null)   return null;
  Object service=context.getService(srvRef);
  if (service == null)   return null;
 else   return (MonitoredApplication)service;
}
 

Example 13

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/monitor/statevariable/.

Source file: MonitorHandlerStateVar.java

  32 
vote

private ServiceReference retreiveEventAdmin(){
  ServiceReference[] refs=null;
  ServiceReference refEventAdmin;
  try {
    refs=m_bundleContext.getServiceReferences(EventAdmin.class.getName(),null);
  }
 catch (  InvalidSyntaxException e) {
    logger.error("Event Admin  service lookup unrecoverable error");
    throw new RuntimeException("Event Adminservice lookup unrecoverable error");
  }
  if (refs != null)   refEventAdmin=refs[0];
 else   refEventAdmin=null;
  return refEventAdmin;
}
 

Example 14

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/internals/factories/.

Source file: MediatorFactory.java

  32 
vote

public ServiceReference getReference(){
  ServiceReference sreference=super.getReference();
  try {
    ServiceReference[] serv=m_context.getAllServiceReferences(Factory.class.getName(),filter);
    if (serv != null && serv.length != 0) {
      return sreference;
    }
  }
 catch (  InvalidSyntaxException e1) {
  }
  return null;
}
 

Example 15

From project CIShell, under directory /clients/gui/org.cishell.reference.gui.datamanager/src/org/cishell/reference/gui/datamanager/.

Source file: Activator.java

  32 
vote

protected static DataManagerService getDataManagerService(){
  ServiceReference serviceReference=context.getServiceReference(DataManagerService.class.getName());
  DataManagerService manager=null;
  if (serviceReference != null) {
    manager=(DataManagerService)context.getService(serviceReference);
  }
  return manager;
}
 

Example 16

From project CIShell, under directory /clients/gui/org.cishell.reference.gui.datamanager/src/org/cishell/reference/gui/datamanager/.

Source file: Activator.java

  32 
vote

protected static LogService getLogService(){
  ServiceReference serviceReference=context.getServiceReference(DataManagerService.class.getName());
  LogService log=null;
  if (serviceReference != null) {
    log=(LogService)context.getService(context.getServiceReference(LogService.class.getName()));
  }
  return log;
}
 

Example 17

From project arquillian-showcase, under directory /osgi/src/test/java/com/acme/osgi/.

Source file: SimpleOSGiServiceTestCase.java

  31 
vote

@Test public void testBundleInjection() throws Exception {
  assertNotNull("Bundle injected",bundle);
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
  bundle.start();
  assertEquals("Bundle ACTIVE",Bundle.ACTIVE,bundle.getState());
  BundleContext context=bundle.getBundleContext();
  assertNotNull("BundleContext available",context);
  ServiceReference sref=context.getServiceReference(SimpleService.class.getName());
  assertNotNull("ServiceReference not null",sref);
  SimpleService service=(SimpleService)context.getService(sref);
  assertNotNull("Service not null",service);
  int sum=service.sum(1,2,3);
  assertEquals(6,sum);
  bundle.stop();
  assertEquals("Bundle RESOLVED",Bundle.RESOLVED,bundle.getState());
}
 

Example 18

From project bndtools, under directory /bndtools.core/src/bndtools/utils/.

Source file: ServiceUtils.java

  31 
vote

public static final <R,S,E extends Throwable>R usingService(BundleContext context,Class<S> clazz,ServiceOperation<R,S,E> operation) throws E {
  ServiceReference reference=context.getServiceReference(clazz.getName());
  if (reference != null) {
    @SuppressWarnings("unchecked") S service=(S)context.getService(reference);
    if (service != null) {
      try {
        return operation.execute(service);
      }
  finally {
        context.ungetService(reference);
      }
    }
  }
  return null;
}
 

Example 19

From project cellar, under directory /core/src/main/java/net/cellar/core/event/.

Source file: EventHandlerServiceRegistry.java

  31 
vote

/** 
 * Returns the appropriate  {@code EventHandler} found inside the {@code HandlerRegistry}.
 * @param event
 * @return
 */
public EventHandler<E> getHandler(E event){
  BundleContext bundleContext=((BundleReference)getClass().getClassLoader()).getBundle().getBundleContext();
  ServiceReference[] references=new ServiceReference[0];
  try {
    references=bundleContext.getServiceReferences("net.cellar.core.event.EventHandler",null);
    if (references != null && references.length > 0) {
      for (int i=0; i < references.length; i++) {
        ServiceReference ref=references[i];
        try {
          EventHandler handler=(EventHandler)bundleContext.getService(ref);
          if (handler.getType().equals(event.getClass())) {
            return handler;
          }
        }
 catch (        Exception ex) {
          logger.error("Failed to get handler from Service Reference.",ex);
        }
 finally {
          bundleContext.ungetService(ref);
        }
      }
    }
  }
 catch (  InvalidSyntaxException e) {
    logger.error("Failed to lookup Service Registry for Event Hanlders.",e);
  }
  return null;
}
 

Example 20

From project cilia-workbench, under directory /cilia-workbench-monitoring/src/fr/liglab/adele/cilia/workbench/monitoring/.

Source file: Activator.java

  31 
vote

/** 
 * Retrieve a service in the registry, thanks to a class.
 * @param clazz The class used to find the service reference
 * @return the service reference, null if not found
 */
@SuppressWarnings("rawtypes") private static ServiceReference retrieveAdminService(Class clazz){
  ServiceReference[] refs=null;
  ServiceReference refData;
  try {
    refs=context.getServiceReferences(clazz.getName(),null);
  }
 catch (  InvalidSyntaxException e) {
    throw new RuntimeException("Admin data service lookup unrecoverable error",e);
  }
  if (refs != null)   refData=refs[0];
 else {
    refData=null;
  }
  return refData;
}
 

Example 21

From project Android_1, under directory /org.eclipse.ecf.provider.zookeeper/src/org/eclipse/ecf/provider/zookeeper/core/.

Source file: AdvertisedService.java

  29 
vote

public AdvertisedService(ServiceReference ref){
  Assert.isNotNull(ref);
  this.serviceReference=ref;
  this.uuid=UUID.randomUUID().toString();
  String services[]=(String[])this.serviceReference.getProperty(Constants.OBJECTCLASS);
  for (  String k : this.serviceReference.getPropertyKeys()) {
    Object value=this.serviceReference.getProperty(k);
    if (value instanceof String && ((String)value).contains("localhost")) {
      this.properties.put(k,((String)value).replace("localhost",Geo.getHost()));
      continue;
    }
    this.properties.put(k,this.serviceReference.getProperty(k));
  }
  IServiceTypeID serviceTypeID=ServiceIDFactory.getDefault().createServiceTypeID(DiscoveryContainer.getSingleton().getConnectNamespace(),services,IServiceTypeID.DEFAULT_PROTO);
  serviceTypeID=new ZooServiceTypeID((DiscoveryNamespace)DiscoveryContainer.getSingleton().getConnectNamespace(),serviceTypeID,this.serviceReference.getProperty(Constants.SERVICE_ID).toString());
  serviceID=new ZooServiceID(DiscoveryContainer.getSingleton().getConnectNamespace(),serviceTypeID,Geo.getLocation());
  super.properties=new ServiceProperties(this.properties);
  this.properties.put(Constants.OBJECTCLASS,arrayToString(services));
  this.properties.put(LOCATION,Geo.getLocation());
  this.properties.put(WEIGHT,getWeight());
  this.properties.put(PRIORITY,getPriority());
  this.properties.put(NODE_PROPERTY_NAME_PROTOCOLS,arrayToString(IServiceTypeID.DEFAULT_PROTO));
  this.properties.put(NODE_PROPERTY_NAME_SCOPE,arrayToString(IServiceTypeID.DEFAULT_SCOPE));
  this.properties.put(NODE_PROPERTY_NAME_NA,IServiceTypeID.DEFAULT_NA);
  publishedServices.put(serviceTypeID.getInternal(),this);
}
 

Example 22

From project Android_1, under directory /org.eclipse.ecf.provider.zookeeper/src/org/eclipse/ecf/provider/zookeeper/core/.

Source file: DiscoveryContainer.java

  29 
vote

public void init(ServiceReference reference){
  if (initialized)   return;
  config.configure(reference);
  doStart();
  initialized=true;
}
 

Example 23

From project arkadiko, under directory /bundles/bundle-log-adapter/src/com/liferay/arkadiko/bundle/log/adapter/.

Source file: LogListenerImpl.java

  29 
vote

public void logged(LogEntry entry){
  Bundle bundle=entry.getBundle();
  int level=entry.getLevel();
  ServiceReference<?> serviceReference=entry.getServiceReference();
  Log log=_logFactory.getInstance(bundle.getSymbolicName());
  StringBuilder sb=new StringBuilder(3);
  sb.append(entry.getMessage());
  if (serviceReference != null) {
    sb.append(" ");
    sb.append(serviceReference.toString());
  }
  if ((level == LogService.LOG_DEBUG) && log.isDebugEnabled()) {
    log.debug(sb.toString(),entry.getException());
  }
 else   if ((level == LogService.LOG_ERROR) && log.isErrorEnabled()) {
    log.error(sb.toString(),entry.getException());
  }
 else   if ((level == LogService.LOG_INFO) && log.isInfoEnabled()) {
    log.info(sb.toString(),entry.getException());
  }
 else   if ((level == LogService.LOG_WARNING) && log.isWarnEnabled()) {
    log.warn(sb.toString(),entry.getException());
  }
}
 

Example 24

From project arkadiko, under directory /src/com/liferay/arkadiko/.

Source file: AKServiceTrackerInvocationHandler.java

  29 
vote

/** 
 * Adding service.
 * @param reference the reference
 * @return the object
 */
@Override public Object addingService(ServiceReference reference){
  Object service=context.getService(reference);
  if (service == _originalService) {
    return service;
  }
  while (!_methodQueue.isEmpty()) {
    MethodInvocation methodInvocation=_methodQueue.poll();
    Method method=methodInvocation.getMethod();
    Object[] arguments=methodInvocation.getArguments();
    try {
      return method.invoke(service,arguments);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
  _currentService=service;
  return service;
}
 

Example 25

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/osgi/.

Source file: OSGiServiceHelper.java

  29 
vote

/** 
 * This method returns a Collection of service instances, or an empty Collection if no service is currently registered.
 * @param bundleContext the  {@link BundleContext} of your plugin. You can obtain aninstance of the  {@link BundleContext} through your Activator.
 * @param clazz The  {@link Class} of the service. Typically an Java Interface
 * @param filter The filter expression or null for all services. See {@link BundleContext#getServiceReferences(Class,String)}.
 * @return Collection of service instances of the given {@link Class} type, oran empty Collection.
 */
@SuppressWarnings({"unchecked"}) public static <T>Collection<T> getServices(BundleContext bundleContext,Class<T> clazz,String filter){
  Collection<ServiceReference<T>> serviceReferences;
  try {
    serviceReferences=bundleContext.getServiceReferences(clazz,null);
  }
 catch (  InvalidSyntaxException e) {
    throw new RuntimeException(e);
  }
  if (serviceReferences.isEmpty()) {
    return Collections.EMPTY_LIST;
  }
  Collection<T> result=new ArrayList<T>(serviceReferences.size());
  for (  ServiceReference<T> sr : serviceReferences) {
    result.add(bundleContext.getService(sr));
  }
  return result;
}
 

Example 26

From project bndtools, under directory /bndtools.core/src/bndtools/.

Source file: LogServiceAdapter.java

  29 
vote

public void log(ServiceReference sr,int level,String message,Throwable exception){
switch (level) {
case LogService.LOG_ERROR:
    delegate.logError(message,exception);
  break;
case LogService.LOG_WARNING:
delegate.logWarning(message,exception);
break;
case LogService.LOG_INFO:
delegate.logInfo(message,exception);
break;
default :
delegate.logError("[Unknown level " + level + ", assumed error]"+ message,exception);
break;
}
}
 

Example 27

From project bundlemaker, under directory /main/org.bundlemaker.core.ui.mvn/src/org/bundlemaker/core/ui/mvn/.

Source file: Activator.java

  29 
vote

public void start(BundleContext context) throws Exception {
  super.start(context);
  plugin=this;
  _mvnRepositoriesServiceTracker=new ServiceTracker<IMvnRepositories,IMvnRepositories>(context,IMvnRepositories.class,null){
    @Override public IMvnRepositories addingService(    ServiceReference<IMvnRepositories> reference){
      IMvnRepositories mvnRepositories=super.addingService(reference);
      reset(mvnRepositories);
      return mvnRepositories;
    }
  }
;
  _mvnRepositoriesServiceTracker.open();
}
 

Example 28

From project cellar, under directory /core/src/main/java/net/cellar/core/control/.

Source file: ManageHandlersCommandHandler.java

  29 
vote

/** 
 * Returns a map containing all managed  {@code EventHandler}s and their status.
 * @param command
 * @return
 */
@Override public ManageHandlersResult execute(ManageHandlersCommand command){
  ManageHandlersResult result=new ManageHandlersResult(command.getId());
  BundleContext bundleContext=((BundleReference)getClass().getClassLoader()).getBundle().getBundleContext();
  ServiceReference[] references=new ServiceReference[0];
  try {
    references=bundleContext.getServiceReferences(EventHandler.class.getName(),EventHandler.MANAGED_FILTER);
    if (references != null && references.length > 0) {
      for (      ServiceReference ref : references) {
        EventHandler handler=(EventHandler)bundleContext.getService(ref);
        if (command.getHandlesName() != null && command.getHandlesName().equals(handler.getClass().getName())) {
          if (command.getStatus()) {
            handler.getSwitch().turnOn();
          }
 else           handler.getSwitch().turnOff();
        }
        result.getHandlers().put(handler.getClass().getName(),handler.getSwitch().getStatus().name());
      }
    }
  }
 catch (  InvalidSyntaxException e) {
    logger.error("Syntax error looking up service {} using filter {}",EventHandler.class.getName(),EventHandler.MANAGED_FILTER);
  }
 finally {
    if (references != null) {
      for (      ServiceReference ref : references) {
        bundleContext.ungetService(ref);
      }
    }
  }
  return result;
}