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

The following examples show how to use org.osgi.framework.BundleContext#getServiceReference() . 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: DefaultServiceDirectory.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the reference to the implementation of the specified service.
 *
 * @param serviceClass service class
 * @param <T>          type of service
 * @return service implementation
 */
public static <T> T getService(Class<T> serviceClass) {
    Bundle bundle = FrameworkUtil.getBundle(serviceClass);
    if (bundle != null) {
        BundleContext bc = bundle.getBundleContext();
        if (bc != null) {
            ServiceReference<T> reference = bc.getServiceReference(serviceClass);
            if (reference != null) {
                T impl = bc.getService(reference);
                if (impl != null) {
                    return impl;
                }
            }
        }
    }
    throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found");
}
 
Example 2
Source File: ThingFactoryHelper.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> T withChannelTypeRegistry(Function<ChannelTypeRegistry, T> consumer) {
    BundleContext bundleContext = FrameworkUtil.getBundle(ThingFactoryHelper.class).getBundleContext();
    ServiceReference ref = bundleContext.getServiceReference(ChannelTypeRegistry.class.getName());
    try {
        ChannelTypeRegistry channelTypeRegistry = null;
        if (ref != null) {
            channelTypeRegistry = (ChannelTypeRegistry) bundleContext.getService(ref);
        }
        return consumer.apply(channelTypeRegistry);
    } finally {
        if (ref != null) {
            bundleContext.ungetService(ref);
        }
    }
}
 
Example 3
Source File: ThingFactoryHelper.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> T withChannelGroupTypeRegistry(Function<ChannelGroupTypeRegistry, T> consumer) {
    BundleContext bundleContext = FrameworkUtil.getBundle(ThingFactoryHelper.class).getBundleContext();
    ServiceReference ref = bundleContext.getServiceReference(ChannelGroupTypeRegistry.class.getName());
    try {
        ChannelGroupTypeRegistry channelGroupTypeRegistry = null;
        if (ref != null) {
            channelGroupTypeRegistry = (ChannelGroupTypeRegistry) bundleContext.getService(ref);
        }
        return consumer.apply(channelGroupTypeRegistry);
    } finally {
        if (ref != null) {
            bundleContext.ungetService(ref);
        }
    }
}
 
Example 4
Source File: ReconfigurableClient.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Try to locate the {@code MessagingClientFactoryRegistry} service in an OSGi execution context.
 * <p>
 * NOTE: this method is, by definition, quite dirty.
 * </p>
 * TODO: what happens when the registry component is being started, but the service is not yet registered. Wait? How long?
 * @return the located {@code MessagingClientFactoryRegistry} service, or {@code null} if the service cannot be
 * found, or if there is no OSGi execution context.
 */
public static MessagingClientFactoryRegistry lookupMessagingClientFactoryRegistryService( OsgiHelper osgiHelper ) {

	MessagingClientFactoryRegistry result = null;
	final Logger logger = Logger.getLogger( ReconfigurableClient.class.getName());

	BundleContext bundleCtx = osgiHelper.findBundleContext();
	if( bundleCtx != null ) {
		logger.info( "The messaging registry is used in an OSGi environment." );

		// There must be only *one* MessagingClientFactoryRegistry service.
		final ServiceReference<MessagingClientFactoryRegistry> reference =
				bundleCtx.getServiceReference( MessagingClientFactoryRegistry.class );

		// The service will be unget when this bundle stops. No need to worry!
		if( reference != null ) {
			logger.fine( "The service reference was found." );
			result = bundleCtx.getService( reference );
		}

	} else {
		logger.info( "The messaging registry is NOT used in an OSGi environment." );
	}

	return result;
}
 
Example 5
Source File: OsgiComponentServiceTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegistryServiceDynamicLoadOfComponent() throws BundleException, MalformedURLException, URISyntaxException {
    // inside eclipse the bundle context can be retrieved from the Activator.start method or using the FrameworkUtil
    // class.
    BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
    ServiceReference<DefinitionRegistryService> compServiceRef = bundleContext
            .getServiceReference(DefinitionRegistryService.class);
    if (compServiceRef != null) {
        DefinitionRegistryService defService = bundleContext.getService(compServiceRef);
        assertNotNull(defService);
        assertEquals(0, defService.getDefinitionsMapByType(Definition.class).size());
        installNewComponentBundle(bundleContext);
        assertEquals(1, defService.getDefinitionsMapByType(Definition.class).size());
    } else {
        fail("Failed to retrieve the Component service");
    }
}
 
Example 6
Source File: HealthRestServiceImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
protected BundleStateService getBundleStateService()
{
    // get bundle instance via the OSGi Framework Util class
    BundleContext ctx = FrameworkUtil.getBundle( BundleStateService.class ).getBundleContext();
    if ( ctx != null )
    {
        ServiceReference serviceReference = ctx.getServiceReference( BundleStateService.class.getName() );
        if ( serviceReference != null )
        {
            Object service = ctx.getService( serviceReference );
            if ( BundleStateService.class.isInstance( service ) )
            {
                return BundleStateService.class.cast( service );
            }
        }
    }

    throw new IllegalStateException( "Can not obtain handle of BundleStateService" );
}
 
Example 7
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Log message via specified BundleContext
 */
static void logBC(BundleContext bc, int level, String msg, Throwable t) {
  try {
    ServiceReference<LogService> sr = bc.getServiceReference(LogService.class);
    if (sr != null) {
      LogService log = bc.getService(sr);
      if (log != null) {
        log.log(level, msg, t);
        bc.ungetService(sr);
      }
    }
  } catch (IllegalStateException ise) {
    log(level, "Logging message for " + bc.getBundle() 
        + " since it was inactive: " + msg, t);
  }
}
 
Example 8
Source File: EclipseLinkOSGiTransactionController.java    From lb-karaf-examples-jpa with Apache License 2.0 6 votes vote down vote up
@Override
protected TransactionManager acquireTransactionManager() throws Exception {
    Bundle bundle = FrameworkUtil.getBundle(EclipseLinkOSGiTransactionController.class);
    BundleContext ctx = bundle.getBundleContext();

    if (ctx != null) {
        ServiceReference<?> ref = ctx.getServiceReference(TransactionManager.class.getName());

        if (ref != null) {
            TransactionManager manager = (TransactionManager) ctx.getService(ref);
            return manager;
        }
    }

    return super.acquireTransactionManager();
}
 
Example 9
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void start(BundleContext bc) throws Exception { 
  System.out.println(bc.getBundle().getHeaders()
                     .get(Constants.BUNDLE_NAME) + 
                     " starting..."); 
  Activator.bc = bc; 
  ServiceReference reference = 
    bc.getServiceReference(DateService.class.getName()); 

  if(reference != null) {
    DateService service = (DateService)bc.getService(reference); 
    System.out.println("Using DateService: formatting date: " + 
                       service.getFormattedDate(new Date())); 
    bc.ungetService(reference); 
  } else {
    System.out.println("No Service available!"); 
  }
}
 
Example 10
Source File: SFTPTransferJob.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected ITaskService getTaskService() {
	if (taskService == null) {
		BundleContext context = Activator.getDefault().getContext();
		if (taskServiceRef == null) {
			taskServiceRef = context.getServiceReference(ITaskService.class);
			if (taskServiceRef == null)
				throw new IllegalStateException("Task service not available"); //$NON-NLS-1$
		}
		taskService = context.getService(taskServiceRef);
		if (taskService == null)
			throw new IllegalStateException("Task service not available"); //$NON-NLS-1$
	}
	return taskService;
}
 
Example 11
Source File: Restore.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void copyPolicyFiles(BundleContext bundleContext) throws IOException {
    // Copy policy files to proper destination
    ServiceReference<XACMLPolicyManager> serviceRef = bundleContext.getServiceReference(XACMLPolicyManager.class);
    if (serviceRef == null) {
        throw new IllegalStateException("Policy Manager service is not available");
    }
    String policyFileLocation = (String) serviceRef.getProperty("policyFileLocation");
    LOGGER.trace("Identified policy directory as " + policyFileLocation);
    File policyDir = new File(policyFileLocation);
    File tmpPolicyDir = new File(RESTORE_PATH + File.separator + "policies");
    FileUtils.copyDirectory(tmpPolicyDir, policyDir);
}
 
Example 12
Source File: MyBundleActivator.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public void start(BundleContext ctx) throws Exception {
    ServiceReference<?> ref = ctx.getServiceReference(RuntimeException.class);
    if (ref != null) {
        throw (RuntimeException)ctx.getService(ref);
    }
}
 
Example 13
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 { 
  System.out.println(bc.getBundle().getHeaders()
                     .get(Constants.BUNDLE_NAME) + 
                     " starting..."); 
  Activator.bc = bc; 
  ServiceReference reference = 
    bc.getServiceReference(DateService.class.getName()); 

  DateService service = (DateService)bc.getService(reference); 
  System.out.println("Using DateService: formatting date: " + 
                     service.getFormattedDate(new Date())); 
  bc.ungetService(reference); 
}
 
Example 14
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 15
Source File: TLAEditorActivator.java    From tlaplus with MIT License 5 votes vote down vote up
private void setDarkThemeStatus () {
	final BundleContext context = Activator.getDefault().getBundle().getBundleContext();
	final ServiceReference<IThemeManager> serviceReference = context.getServiceReference(IThemeManager.class);
	
	if (serviceReference != null) {
        final IThemeManager manager = context.getService(serviceReference);

        if (manager != null) {
        	final Display d = Display.getDefault();
        	final IThemeEngine engine = manager.getEngineForDisplay(d);
        	final ITheme it = engine.getActiveTheme();
        	
        	if (it != null) {
        		boolean newThemeStatus = it.getId().startsWith(DARK_THEME_ID_PREFIX);
        		
        		if ((currentThemeIsDark == null) || (currentThemeIsDark.booleanValue() != newThemeStatus)) {
		if (currentThemeIsDark != null) {
			d.asyncExec(() -> {
				MessageDialog.openInformation(d.getActiveShell(), "Theme Change",
						"You will need to close any open views and editors, then re-open them, to have "
								+ "your theme change fully reflected (or restart the Toolbox.)");
			});
        			}
		
        			currentThemeIsDark = Boolean.valueOf(newThemeStatus);
        		}
        	}
        }
	}
}
 
Example 16
Source File: ThemeHelper.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
public ThemeHelper(BundleContext context) {
	this.context = context;
	this.serviceRef = context.getServiceReference(IThemeManager.class.getName());
	asOwner().bind(() -> context.ungetService(serviceRef));
	
	this.themeManager = blindCast(context.getService(serviceRef));
}
 
Example 17
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Calls package admin refresh packages and waits for the operation
 * to complete.
 *
 * @param bc context owning both resources and to install bundle from
 * @param bundles the inital list of bundles to refresh.
 * @return null on sucess, string with error message on failure.
 */
public static String refreshPackages(BundleContext bc,
                                     Bundle[] bundles)
{
  System.out.println("PackageAdmin.refreshPackages("
                     +Arrays.asList(bundles) +")");
  ServiceReference paSR
    = bc.getServiceReference(PackageAdmin.class.getName());
  if (null==paSR)
    return "No package admin service reference.";

  PackageAdmin pa = (PackageAdmin) bc.getService(paSR);
  if (null==pa)
    return "No package admin service.";

  final Object lock = new Object();

  FrameworkListener fListen = new FrameworkListener(){
      public void frameworkEvent(FrameworkEvent event)
      {
        System.out.println("Got framework event of type "+event.getType());
        if (event.getType()==FrameworkEvent.PACKAGES_REFRESHED) {
          synchronized(lock) {
            lock.notifyAll();
          }
        }
      }
    };
  bc.addFrameworkListener(fListen);

  try {
    pa.refreshPackages(bundles);
  } catch (Exception e) {
    e.printStackTrace();
    return "Failed to refresh packages, got exception " +e;
  }

  synchronized (lock) {
    try {
      lock.wait(30000L);
    } catch (InterruptedException ie) {
      System.err.println("Waiting or packages refreshed was interrupted.");
    }
  }
  System.out.println("PackageAdmin.refreshPackages("
                     +Arrays.asList(bundles) +") done.");

  bc.removeFrameworkListener(fListen);

  return null;
}
 
Example 18
Source File: EclipseUtil.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Set the debugging state of the platform
 */
public static void setPlatformDebugging(boolean debugEnabled)
{
	// Platform only sees a null value as "false" for this, so we need to hack around to set a null value
	// depending on what API version we're using. 4.3 and lower throw exceptions if we try to set the property to
	// null.
	final String propertyName = "osgi.debug"; //$NON-NLS-1$
	if (!debugEnabled && !isNewOSGIAPI())
	{
		// Can't set a null property on EnivronmentInfo in 4.3 and lower. So we need to hack using reflection against old API
		try
		{
			Class klazz = Class.forName("org.eclipse.osgi.framework.internal.core.FrameworkProperties"); //$NON-NLS-1$
			Method m = klazz.getMethod("clearProperty", String.class); //$NON-NLS-1$
			m.invoke(null, propertyName);
			return;
		}
		catch (ClassNotFoundException cnfe)
		{
			// assume it's because we're on a 4.4+ build where we follow with the logic below...
		}
		catch (Exception e)
		{
			IdeLog.logError(CorePlugin.getDefault(), e);
		}
	}
	BundleContext context = CorePlugin.getDefault().getContext();
	if (context == null)
	{
		return;
	}
	ServiceReference<EnvironmentInfo> ref = context.getServiceReference(EnvironmentInfo.class);
	if (ref == null)
	{
		return;
	}
	EnvironmentInfo info = context.getService(ref);
	if (info != null)
	{
		if (debugEnabled)
		{
			info.setProperty(propertyName, Boolean.toString(debugEnabled));
		}
		else
		{
			info.setProperty(propertyName, null);
		}
	}
}
 
Example 19
Source File: PrintMedicationHistoryHandler.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isFopServiceAvailable(){
	BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
	return bundleContext.getServiceReference(IFormattedOutputFactory.class) != null;
}
 
Example 20
Source File: Activator.java    From tracecompass with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Return the OSGi service with the given service interface.
 *
 * @param service
 *            service interface
 * @return the specified service or null if it's not registered
 */
public static @Nullable <T> T getService(Class<T> service) {
    BundleContext context = fPlugin.getBundle().getBundleContext();
    ServiceReference<T> ref = context.getServiceReference(service);
    return ((ref != null) ? context.getService(ref) : null);
}