Java Code Examples for org.osgi.framework.ServiceReference#getBundle()

The following examples show how to use org.osgi.framework.ServiceReference#getBundle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
public static boolean isAvailable(ServiceReference<?> serviceReference) {
    Bundle bundle = serviceReference.getBundle();

    if (bundle == null) {
        return false;
    }

    for (ServiceReference<?> registeredService :
        bundle.getRegisteredServices()) {

        if (registeredService.equals(serviceReference)) {
            return true;
        }
    }

    return false;
}
 
Example 2
Source File: LogFrameworkListener.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * The service event callback method inserts all service events into the
 * log.
 * 
 * Event of types REGISTERED, UNREGISTERED are assigned the log
 * level info.
 * 
 * Events of type MODIFIED are assigned the log level DEBUG.
 * 
 * @param se
 *            the service event that has occurred.
 */
public void serviceChanged(ServiceEvent se) {
    ServiceReference<?> sr = se.getServiceReference();
    Bundle bundle = sr.getBundle();
    String msg = null;
    int level = LogService.LOG_INFO;
    switch (se.getType()) {
    case ServiceEvent.REGISTERED:
        msg = "ServiceEvent REGISTERED";
        break;
    case ServiceEvent.UNREGISTERING:
        msg = "ServiceEvent UNREGISTERING";
        break;
    case ServiceEvent.MODIFIED:
        msg = "ServiceEvent MODIFIED";
        level = LogService.LOG_DEBUG;
        break;
    }
    lrsf.log(new LogEntryImpl(bundle, sr, level, msg));
}
 
Example 3
Source File: SystemMetatypeProvider.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get a loaded metatype provider, given a bundle.
 *
 * @return Provider if such provider is found, otherwise <tt>null</tt>.
 */
public MetaTypeInformation getMTP(Bundle b)
{
  final ServiceReference<?> cmSR = cmTracker.getServiceReference();

  MetaTypeInformation mti = null;

  if (cmSR != null && cmSR.getBundle() == b) {
    mti = cmMTP;
  } else if (b.getBundleId() == 0) {
    mti = this;
  } else {
    mti = providers.get(b);
  }

  return mti;
}
 
Example 4
Source File: ServiceComponentRuntimeImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private ServiceReferenceDTO getServiceReferenceDTO(ServiceReference<?> sr) {
  ServiceReferenceDTO res = new ServiceReferenceDTO();
  res.properties = new HashMap<String, Object>();
  for (String key : sr.getPropertyKeys()) {
    Object val = safeDTOObject(sr.getProperty(key));
    res.properties.put(key, val);
  }
  res.id = ((Long)sr.getProperty(Constants.SERVICE_ID)).longValue();
  Bundle [] using = sr.getUsingBundles();
  if (using != null) {
    res.usingBundles = new long [using.length];
    for (int i = 0; i < using.length; i++) {
      res.usingBundles[i] = using[i].getBundleId();
    }
  } else {
    res.usingBundles = new long [0];
  }
  Bundle b = sr.getBundle();
  if (b == null) {
    return null;
  }
  res.bundle = b.getBundleId();
  return res;
}
 
Example 5
Source File: ConfigurationAdminFactory.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Set<String> removeFromLocationToPids(ServiceReference<?> sr)
{
  HashSet<String> res = new HashSet<String>();
  if (sr != null) {
    Bundle bundle = sr.getBundle();
    final String bundleLocation = bundle.getLocation();
    final Hashtable<String, TreeSet<ServiceReference<?>>> pidsForLocation =
      locationToPids.get(bundleLocation);
    for (final Iterator<Entry<String, TreeSet<ServiceReference<?>>>> it =
      pidsForLocation.entrySet().iterator(); it.hasNext();) {
      final Entry<String, TreeSet<ServiceReference<?>>> entry = it.next();
      TreeSet<ServiceReference<?>> ssrs = entry.getValue();
      if (ssrs.remove(sr)) {
        res.add(entry.getKey());
        if (ssrs.isEmpty()) {
          it.remove();
        }
      }
    }
    if (pidsForLocation.isEmpty()) {
      locationToPids.remove(bundleLocation);
    }
  }
  return res;
}
 
Example 6
Source File: NetigsoServices.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(ServiceReference obj) {
    final Bundle bundle = obj.getBundle();
    if (bundle != null) {
        return bundle.getBundleContext().getService(obj);
    } else {
        return null;
    }
}
 
Example 7
Source File: NetigsoServices.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Class<? extends Object> type(ServiceReference obj) {
    String[] arr = (String[])obj.getProperty(Constants.OBJECTCLASS);
    if (arr.length > 0) {
        final Bundle bundle = obj.getBundle();
        if (bundle != null) try {
            return (Class<?>)bundle.loadClass(arr[0]);
        } catch (ClassNotFoundException ex) {
            Netigso.LOG.log(Level.INFO, "Cannot load service class", arr[0]); // NOI18N
        }
    }
    return Object.class;
}
 
Example 8
Source File: Concierge.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * unregister a service.
 * 
 * @param sref
 *            the service reference.
 */
void unregisterService(final ServiceReference<?> sref) {
	// remove all class entries
	final String[] clazzes = (String[]) sref
			.getProperty(Constants.OBJECTCLASS);
	serviceRegistry.removeAll(clazzes, sref);

	boolean isHook = false;

	for (int i = 0; i < clazzes.length; i++) {
		@SuppressWarnings("unchecked")
		final List<ServiceReference<?>> hookList = (List<ServiceReference<?>>) hooks
				.get(clazzes[i]);
		if (hookList != null) {
			isHook = true;
			hookList.remove(sref);
		}
		
		if(clazzes[i].equals(WovenClassListener.class.getName())){
			wovenClassListeners.remove(sref);
		}
	}

	final AbstractBundle bundle = (AbstractBundle) sref.getBundle();
	bundle.registeredServices.remove(sref);

	// dispose list, if empty
	if (bundle.registeredServices.isEmpty()) {
		bundle.registeredServices = null;
	}

	if (!isHook) {
		notifyServiceListeners(ServiceEvent.UNREGISTERING, sref, null);
	}

	if (LOG_ENABLED && DEBUG_SERVICES) {
		logger.log(LogService.LOG_INFO,
				"Framework: UNREGISTERED SERVICE " + sref);
	}
}
 
Example 9
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String showDevice(ServiceReference<?> sr)
{
  final StringBuffer sb = new StringBuffer();
  Object o =
    sr.getProperty(org.osgi.service.device.Constants.DEVICE_CATEGORY);
  if (o instanceof String) {
    sb.append(o);
  } else if (o instanceof String[]) {
    final String[] dca = (String[]) o;
    for (int i = 0; i < dca.length; i++) {
      if (i > 0) {
        sb.append('_');
      }
      sb.append(dca[i]);
    }
  }
  o = sr.getProperty(org.osgi.framework.Constants.SERVICE_ID);
  if (o != null) {
    sb.append(", sid=");
    sb.append(o);
  }
  final Bundle b = sr.getBundle();
  if (b != null) {
    sb.append(", bid=");
    sb.append(b.getBundleId());
  }
  return sb.toString();
}
 
Example 10
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String showDriver(ServiceReference<?> sr)
{
  final StringBuffer sb = new StringBuffer();
  final String s =
    (String) sr.getProperty(org.osgi.service.device.Constants.DRIVER_ID);
  sb.append(s != null ? s : "driver");
  final Bundle b = sr.getBundle();
  if (b != null) {
    sb.append(", bid=");
    sb.append(b.getBundleId());
  }
  return sb.toString();
}
 
Example 11
Source File: InternalAdminEvent.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void log(TrackedEventHandler handler, String txt)
{
  final ServiceReference<EventHandler> sr = handler.getServiceReference();
  final Bundle b = sr.getBundle();
  String binfo = (b != null) ?
    "  bundle.id=" + b.getBundleId() + "  bundle.name=" + b.getSymbolicName()
    : " No bundle info";
  Activator.log.error(txt + "  Service.id="
                      + sr.getProperty(Constants.SERVICE_ID) + binfo +
                      " topic=" + event.getTopic(), sr);
}
 
Example 12
Source File: Test5.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void prepare() {
  try {
    ServiceReference ref = bc.getServiceReference(Control.class.getName());
    bundle = ref.getBundle();
  } catch (Exception e) { 
    e.printStackTrace();
  }
}
 
Example 13
Source File: Framework.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
static void unregisterService(ServiceReference serviceReference) {
    services.remove(serviceReference);
    removeValue(classes_services, (String[]) serviceReference.getProperty(Constants.OBJECTCLASS), serviceReference);
    BundleImpl bundleImpl = (BundleImpl) serviceReference.getBundle();
    bundleImpl.registeredServices.remove(serviceReference);
    if (bundleImpl.registeredServices.isEmpty()) {
        bundleImpl.registeredServices = null;
    }
    notifyServiceListeners(4, serviceReference);
    if (DEBUG_SERVICES && log.isInfoEnabled()) {
        log.info("Framework: UNREGISTERED SERVICE " + serviceReference);
    }
}
 
Example 14
Source File: Test7.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void prepare() {
  ServiceReference ref = bc.getServiceReference(Control.class.getName());
  bundle = ref.getBundle();
}
 
Example 15
Source File: OSGiServiceCapabilityTracker.java    From carbon-kernel with Apache License 2.0 4 votes vote down vote up
@Override
public Object addingService(ServiceReference<Object> reference) {
    Object serviceObject = DataHolder.getInstance().getBundleContext().getService(reference);
    String serviceInterfaceClassName = ((String[]) reference.getProperty(OBJECT_CLASS))[0];
    String serviceImplClassName = serviceObject.getClass().getName();
    Bundle bundle = reference.getBundle();

    if (RequiredCapabilityListener.class.getName().equals(serviceInterfaceClassName)) {
        String componentKey = getNonEmptyStringAfterTrim((String) reference.getProperty(COMPONENT_NAME))
                .orElseThrow(() -> new StartOrderResolverException(COMPONENT_NAME + " value is missing in " +
                        "the services registered with the key " + serviceInterfaceClassName + ", " +
                        "implementation class name is " + serviceImplClassName));

        startupComponentManager.addRequiredCapabilityListener(
                (RequiredCapabilityListener) serviceObject, componentKey, reference.getBundle());

    } else if (CapabilityProvider.class.getName().equals(serviceInterfaceClassName)) {
        String capabilityName = getNonEmptyStringAfterTrim((String) reference.getProperty(CAPABILITY_NAME))
                .orElseThrow(() -> new StartOrderResolverException(CAPABILITY_NAME + " value is missing in " +
                        "the services registered with the key " + serviceInterfaceClassName + ", " +
                        "implementation class name is " + serviceImplClassName));

        CapabilityProviderCapability capabilityProvider = new CapabilityProviderCapability(
                CapabilityProvider.class.getName(),
                Capability.CapabilityType.OSGi_SERVICE,
                Capability.CapabilityState.AVAILABLE,
                capabilityName.trim(),
                bundle);

        startupComponentManager.addExpectedOrAvailableCapabilityProvider(capabilityProvider);

        CapabilityProvider provider = (CapabilityProvider) serviceObject;
        IntStream.range(0, provider.getCount())
                .forEach(count -> startupComponentManager.addExpectedCapability(
                        new OSGiServiceCapability(
                                capabilityName.trim(),
                                Capability.CapabilityType.OSGi_SERVICE,
                                Capability.CapabilityState.EXPECTED,
                                bundle,
                                true)));
    } else {
        if (Boolean.TRUE.equals(reference.getProperty(SKIP_CARBON_STARTUP_RESOLVER))) {
            logger.debug("Skipping tracking of service {} which implements {}.", serviceImplClassName,
                         serviceInterfaceClassName);
            return null;
        }

        logger.debug("Updating indirect dependencies in components for interface={} via the implementation={}",
                serviceInterfaceClassName, serviceImplClassName);
        startupComponentManager.updateCapability(new OSGiServiceCapability(
                serviceInterfaceClassName,
                Capability.CapabilityType.OSGi_SERVICE,
                Capability.CapabilityState.AVAILABLE,
                bundle,
                false));
    }

    return serviceObject;
}
 
Example 16
Source File: ProcessApplicationDeployer.java    From camunda-bpm-platform-osgi with Apache License 2.0 4 votes vote down vote up
public ProcessApplicationInterface addProcessApplication(ServiceReference<ProcessApplicationInterface> reference) {

    Bundle bundle = reference.getBundle();
    BundleContext bundleContext = bundle.getBundleContext();

    ClassLoader previous = Thread.currentThread().getContextClassLoader();

    try {
      ClassLoader cl = new BundleDelegatingClassLoader(bundle);

      Thread.currentThread().setContextClassLoader(
          new ClassLoaderWrapper(cl, ProcessEngineFactory.class.getClassLoader(), ProcessEngineConfiguration.class.getClassLoader(), previous));

      ProcessApplicationInterface app = bundleContext.getService(reference);

      app.deploy();
      return app;

    } finally {
      Thread.currentThread().setContextClassLoader(previous);
    }

  }