Java Code Examples for org.osgi.framework.BundleContext#getServiceReferences()

The following examples show how to use org.osgi.framework.BundleContext#getServiceReferences() . 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: Activator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the root file system location the OSGi instance area.
 */
public IPath getPlatformLocation() {
	BundleContext context = Activator.getDefault().getContext();
	Collection<ServiceReference<Location>> refs;
	try {
		refs = context.getServiceReferences(Location.class, Location.INSTANCE_FILTER);
	} catch (InvalidSyntaxException e) {
		// we know the instance location filter syntax is valid
		throw new RuntimeException(e);
	}
	if (refs.isEmpty())
		return null;
	ServiceReference<Location> ref = refs.iterator().next();
	Location location = context.getService(ref);
	try {
		if (location == null)
			return null;
		URL root = location.getURL();
		if (root == null)
			return null;
		// strip off file: prefix from URL
		return new Path(root.toExternalForm().substring(5));
	} finally {
		context.ungetService(ref);
	}
}
 
Example 2
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUnloadALoadedPlugin() throws Exception {
    GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    BundleContext context = bundle.getBundleContext();

    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), null);
    assertThat(allServiceReferences.length).isEqualTo(1);
    GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
    assertThat(getIntField(service, "loadCalled")).as("@Load should have been called").isEqualTo(1);

    bundleDescriptor.setBundle(bundle);
    pluginOSGiFramework.unloadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.UNINSTALLED);
    assertThat(getIntField(service, "unloadCalled")).as("@UnLoad should have been called").isEqualTo(1);
}
 
Example 3
Source File: TransformationHelper.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Queries the OSGi service registry for a service that provides a transformation service of
 * a given transformation type (e.g. REGEX, XSLT, etc.)
 *
 * @param context the bundle context which can be null
 * @param transformationType the desired transformation type
 * @return a service instance or null, if none could be found
 */
public static @Nullable TransformationService getTransformationService(@Nullable BundleContext context,
        String transformationType) {
    if (context != null) {
        String filter = "(smarthome.transform=" + transformationType + ")";
        try {
            Collection<ServiceReference<TransformationService>> refs = context
                    .getServiceReferences(TransformationService.class, filter);
            if (refs != null && refs.size() > 0) {
                return context.getService(refs.iterator().next());
            } else {
                LOGGER.debug("Cannot get service reference for transformation service of type {}",
                        transformationType);
            }
        } catch (InvalidSyntaxException e) {
            LOGGER.debug("Cannot get service reference for transformation service of type {}", transformationType,
                    e);
        }
    }
    return null;
}
 
Example 4
Source File: ControllerTracker.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public ControllerTracker ( final BundleContext context )
{
    this.context = context;

    this.context.addServiceListener ( this.listener );
    try
    {
        final ServiceReference<?>[] refs = context.getServiceReferences ( (String)null, (String)null );
        if ( refs != null )
        {
            for ( final ServiceReference<?> ref : refs )
            {
                handleAddingService ( ref );
            }
        }
    }
    catch ( final InvalidSyntaxException e )
    {
        // this should never happen
    }
}
 
Example 5
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidGoPluginOSGiBundle() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    BundleContext context = bundle.getBundleContext();
    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), null);
    assertThat(allServiceReferences.length).isEqualTo(1);

    try {
        GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
        service.pluginIdentifier();
        assertThat(getIntField(service, "loadCalled")).as("@Load should have been called").isEqualTo(1);
    } catch (Exception e) {
        fail(String.format("pluginIdentifier should have been called. Exception: %s", e.getMessage()));
    }
}
 
Example 6
Source File: Activator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void loadProvider(final BundleContext bundleContext, final BundleWiring bundleWiring) {
    final String filter = "(APIVersion>=2.6.0)";
    try {
        final Collection<ServiceReference<Provider>> serviceReferences = bundleContext.getServiceReferences(Provider.class, filter);
        Provider maxProvider = null;
        for (final ServiceReference<Provider> serviceReference : serviceReferences) {
            final Provider provider = bundleContext.getService(serviceReference);
            if (maxProvider == null || provider.getPriority() > maxProvider.getPriority()) {
                maxProvider = provider;
            }
        }
        if (maxProvider != null) {
            ProviderUtil.addProvider(maxProvider);
        }
    } catch (final InvalidSyntaxException ex) {
        LOGGER.error("Invalid service filter: " + filter, ex);
    }
    final List<URL> urls = bundleWiring.findEntries("META-INF", "log4j-provider.properties", 0);
    for (final URL url : urls) {
        ProviderUtil.loadProvider(url, bundleWiring.getClassLoader());
    }
}
 
Example 7
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidGoPluginOSGiBundleAndShouldBeDiscoverableThroughPluginIDFilter() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    String filterByPluginID = String.format("(%s=%s)", "PLUGIN_ID", "testplugin.descriptorValidator");
    BundleContext context = bundle.getBundleContext();
    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), filterByPluginID);
    assertThat(allServiceReferences.length).isEqualTo(1);

    try {
        GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
        service.pluginIdentifier();
    } catch (Exception e) {
        fail(String.format("pluginIdentifier should have been called. Exception: %s", e.getMessage()));
    }
}
 
Example 8
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidPluginWithMultipleExtensions_ImplementingDifferentExtensions() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor("valid-plugin-with-multiple-extensions", validMultipleExtensionPluginBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);
    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    BundleContext context = bundle.getBundleContext();
    String taskExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "task");
    String analyticsExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "analytics");

    ServiceReference<?>[] taskExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), taskExtensionFilter);
    assertThat(taskExtensionServiceReferences.length).isEqualTo(1);
    assertThat(((GoPlugin) context.getService(taskExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("task");

    ServiceReference<?>[] analyticsExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), analyticsExtensionFilter);
    assertThat(analyticsExtensionServiceReferences.length).isEqualTo(1);
    assertThat(((GoPlugin) context.getService(analyticsExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("analytics");
}
 
Example 9
Source File: OSGiServiceInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
private <T> Object getService(Object adaptable, Class<T> type, String filter,
        DisposalCallbackRegistry callbackRegistry, BundleContext modelContext) {
    // cannot use SlingScriptHelper since it does not support ordering by service ranking due to https://issues.apache.org/jira/browse/SLING-5665
    try {
        ServiceReference<?>[] refs = modelContext.getServiceReferences(type.getName(), filter);
        if (refs == null || refs.length == 0) {
            return null;
        } else {
            // sort by service ranking (lowest first) (see ServiceReference.compareTo)
            List<ServiceReference<?>> references = Arrays.asList(refs);
            Collections.sort(references);
            callbackRegistry.addDisposalCallback(new Callback(refs, modelContext));
            return modelContext.getService(references.get(references.size() - 1));
        }
    } catch (InvalidSyntaxException e) {
        log.error("invalid filter expression", e);
        return null;
    }
}
 
Example 10
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void start(BundleContext bc) throws Exception  { 
  Activator.bc = bc; 
  log("starting");
  
  String filter = "(objectclass=" + DateService.class.getName() + ")"; 
  bc.addServiceListener(listener, filter); 
  
  ServiceReference references[] = bc.getServiceReferences(null, filter); 
  for (int i = 0; references != null && i < references.length; i++) 
    { 
      listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, 
                                               references[i])); 
    } 
}
 
Example 11
Source File: Repositories.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Repositories(BundleContext bc) {
  this.bc = bc;
  synchronized (this) {
    final String clazz = Repository.class.getName();
    try {
      bc.addServiceListener(this, "(objectClass=" + clazz + ")");
      for (ServiceReference<Repository> sr : bc.getServiceReferences(Repository.class, null)) {
        RepositoryInfo ri = new RepositoryInfo(sr);
        repos.put(ri, ri);
      }
    } catch (InvalidSyntaxException _ignore) { }
  }
  xmlRepoFactoryTracker = new ServiceTracker<XmlBackedRepositoryFactory, XmlBackedRepositoryFactory>(bc, XmlBackedRepositoryFactory.class.getName(), null);
  xmlRepoFactoryTracker.open();
}
 
Example 12
Source File: ConsoleTty.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
SystemIn(BundleContext bc) {
    try {
        ServiceReference[] srl = bc.getServiceReferences(
                InputStream.class.getName(),
                "(service.pid=java.lang.System.in)");
        if (srl != null && srl.length == 1) {
            in = (InputStream) bc.getService(srl[0]);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    if (in == null) {
        in = System.in;
    }
}
 
Example 13
Source File: Command.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static ServiceReference<CommandGroup> matchCommandGroup(BundleContext bc,
                                                        String word)
    throws IOException
{
  ServiceReference<CommandGroup> res = null;
  Collection<ServiceReference<CommandGroup>> refs = null;
  try {
    refs = bc.getServiceReferences(CommandGroup.class,
                                   "(groupName=" + word + "*)");
  } catch (InvalidSyntaxException ignore) {
  }
  if (refs.size()==1) {
    // A single match, use it.
    res = refs.iterator().next();
  } else {
    // Multiple matches, check for exact match.
    for (ServiceReference<CommandGroup> srcg : refs) {
      if (word.equals(srcg.getProperty("groupName"))) {
        res = srcg;
        break;
      }
    }
  }
  if (SessionCommandGroup.NAME.startsWith(word)) {
    if (refs.isEmpty() || SessionCommandGroup.NAME.equals(word)) {
      return null;
    }
  } else if (res != null) {
    return res;
  } else if (refs.isEmpty()) {
    throw new IOException("No such command group: " + word);
  }
  throw new IOException("Several command groups starting with: " + word);
}
 
Example 14
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get all service references from the target BC.
 */
public static ServiceReference<?>[] getTargetBC_getServiceReferences()
{
  final BundleContext tbc = getTargetBC();
  if(null != tbc) {
    try {
      return tbc.getServiceReferences((String) null, null);
    } catch (final InvalidSyntaxException ise) {
      // Will not happen in this case!
    }
  }
  return null;
}
 
Example 15
Source File: CommandTty.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
SystemIn(BundleContext bc) {
  try {
    Collection<ServiceReference<InputStream>> srs =
      bc.getServiceReferences(InputStream.class,
                              "(service.pid=java.lang.System.in)");
    if (1==srs.size()) {
      in = bc.getService(srs.iterator().next());
    }
  } catch (Exception e) {
    e.printStackTrace(System.err);
  }
  if (in == null) {
    in = System.in;
  }
}
 
Example 16
Source File: ChannelAspectProcessor.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This actively scans for available aspects and returns their information
 * objects
 *
 * @param context
 *            the context to use
 * @return the result map, never returns <code>null</code>
 */
public static Map<String, ChannelAspectInformation> scanAspectInformations ( final BundleContext context )
{
    Collection<ServiceReference<ChannelAspectFactory>> refs;
    try
    {
        refs = context.getServiceReferences ( ChannelAspectFactory.class, null );
    }
    catch ( final InvalidSyntaxException e )
    {
        // this should never happen since we don't specific a filter
        return Collections.emptyMap ();
    }

    if ( refs == null )
    {
        return Collections.emptyMap ();
    }

    final Map<String, ChannelAspectInformation> result = new HashMap<> ( refs.size () );

    for ( final ServiceReference<ChannelAspectFactory> ref : refs )
    {
        final ChannelAspectInformation info = makeInformation ( ref );
        result.put ( info.getFactoryId (), info );
    }

    return result;
}
 
Example 17
Source File: ShellActivator.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * called, when the bundle is started.
 * 
 * @param context
 *            the bundle context.
 * 
 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
 */
public void start(final BundleContext context) throws Exception {
	ShellActivator.context = context;
	List<ShellCommandGroup> plugins = new ArrayList<ShellCommandGroup>();

	final ServiceReference<?> pkgAdminRef = context
			.getServiceReference("org.osgi.service.packageadmin.PackageAdmin");
	if (pkgAdminRef != null) {
		plugins.add(new PackageAdminCommandGroup(context
				.getService(pkgAdminRef)));
	}

	shell = new Shell(System.out, System.err,
			(ShellCommandGroup[]) plugins
					.toArray(new ShellCommandGroup[plugins.size()]));
	context.addServiceListener(shell, "(" + Constants.OBJECTCLASS + "="
			+ ShellCommandGroup.class.getName() + ")");

	final Collection<ServiceReference<ShellCommandGroup>> existingGroups = context
			.getServiceReferences(ShellCommandGroup.class, null);
	if (existingGroups != null) {
		for (final ServiceReference<ShellCommandGroup> group : existingGroups) {
			shell.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED,
					group));
		}
	}
}
 
Example 18
Source File: OSGiServiceInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private <T> Object[] getServices(Object adaptable, Class<T> type, String filter,
        DisposalCallbackRegistry callbackRegistry, BundleContext modelContext) {
    // cannot use SlingScriptHelper since it does not support ordering by service ranking due to https://issues.apache.org/jira/browse/SLING-5665
    try {
        ServiceReference<?>[] refs = modelContext.getServiceReferences(type.getName(), filter);
        if (refs == null || refs.length == 0) {
            return null;
        } else {
            // sort by service ranking (lowest first) (see ServiceReference.compareTo)
            List<ServiceReference<?>> references = Arrays.asList(refs);
            Collections.sort(references);
            // make highest service ranking being returned first
            Collections.reverse(references);
            callbackRegistry.addDisposalCallback(new Callback(refs, modelContext));
            List<Object> services = new ArrayList<>();
            for (ServiceReference<?> ref : references) {
                Object service = modelContext.getService(ref);
                if (service != null) {
                    services.add(service);
                }
            }
            return services.toArray();
        }
    } catch (InvalidSyntaxException e) {
        log.error("invalid filter expression", e);
        return null;
    }
}
 
Example 19
Source File: XOSGi.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link com.buschmais.xo.api.XOManagerFactory} for the XO unit
 * identified by name.
 * <p>
 * Internally it performs a lookup in the OSGi service registry to retrieve the
 * XOManagerFactory service that is bound to the given XO unit name. The bundle
 * providing this XO unit must be processed by the OSGi bundle listener.
 * </p>
 *
 * @param name
 *            The name of the XO unit.
 * @return The {@link com.buschmais.xo.api.XOManagerFactory}.
 */
public static XOManagerFactory createXOManagerFactory(String name) {
    if (OSGiUtil.isXOLoadedAsOSGiBundle()) {
        try {
            BundleContext bundleContext = FrameworkUtil.getBundle(XOSGi.class).getBundleContext();
            String filterString = "(name=" + name + ")";
            Collection<ServiceReference<XOManagerFactory>> xoManagerFactoryServices = bundleContext.getServiceReferences(XOManagerFactory.class,
                    filterString);
            for (ServiceReference<XOManagerFactory> xoManagerFactoryService : xoManagerFactoryServices) {
                XOManagerFactory xoManagerFactory = bundleContext.getService(xoManagerFactoryService);
                if (xoManagerFactory != null) {
                    xoManagerFactory.addCloseListener(new CloseAdapter() {

                        @Override
                        public void onAfterClose() {
                            bundleContext.ungetService(xoManagerFactoryService);
                        }

                    });
                    return xoManagerFactory;
                }
            }
        } catch (InvalidSyntaxException e) {
            throw new XOException("Cannot lookup service reference from bundle context.", e);
        }
    }
    throw new XOException("XO service not found.");
}
 
Example 20
Source File: ServiceRegistryStressTest.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
public void run(final BundleContext context) throws Exception {
	System.out.println("generating randomness");

	final byte[] bytes = new byte[NUM];
	random.nextBytes(bytes);

	final byte[] bytes2 = new byte[NUM / 10];
	random.nextBytes(bytes2);

	final ServiceRegistration<?>[] services = new ServiceRegistration[NUM];

	System.out.println("done");

	final float time = System.nanoTime();
	for (int i = 0; i < NUM; i++) {
		final Dictionary<String, Object> props = new Hashtable<String, Object>();

		props.put("key", bytes[i]);

		services[i] = context
				.registerService(CLS_NAME, new Object(), props);
	}
	System.out.println("elapsed time for registration: "
			+ (System.nanoTime() - time) / 1000000);

	final float time2 = System.nanoTime();
	for (int i = 0; i < NUM / 10; i++) {
		context.getServiceReferences((String) null, "(key=" + bytes2[i]
				+ ")");
	}
	System.out.println("elapsed time for lookup: "
			+ (System.nanoTime() - time2) / 1000000);

	final float time3 = System.nanoTime();
	for (int i = 0; i < NUM; i++) {
		services[i].unregister();
	}
	System.out.println("elapsed time for unregistration: "
			+ (System.nanoTime() - time3) / 1000000);

}