Java Code Examples for org.osgi.framework.Bundle#getBundleContext()

The following examples show how to use org.osgi.framework.Bundle#getBundleContext() . 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: EclipseLinkOSGiTransactionController.java    From lb-karaf-examples-jpa with Apache License 2.0 7 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 2
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 3
Source File: OsgiServiceUtil.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Release a service that was acquired using the {@link OsgiServiceUtil#getService(Class)}
 * method.
 * 
 * @param service
 */
public synchronized static void ungetService(Object service){
	if (service instanceof Optional) {
		throw new IllegalStateException("Optional is not a service");
	}
	ServiceReference<?> reference = serviceReferences.get(service);
	if (reference != null) {
		Bundle bundle = FrameworkUtil.getBundle(service.getClass());
		// fallback to our context ...
		if (bundle.getBundleContext() == null) {
			bundle = FrameworkUtil.getBundle(OsgiServiceUtil.class);
		}
		if (bundle.getBundleContext().ungetService(reference)) {
			serviceReferences.remove(service);
			logger.info("Release active service [" + service + "] from "
				+ serviceReferences.size() + " active references");
		} else {
			serviceReferences.remove(service);
			logger.info("Release not active service [" + service + "] from "
				+ serviceReferences.size() + " active references");
		}
		return;
	}
	logger.warn("Could not release service [" + service + "] from " + serviceReferences.size()
		+ " active references");
}
 
Example 4
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 5
Source File: ConfigProperties.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static String getProperty(Class<?> classParam, final String propertyStr, final String defaultValue) {
    String value = ConfigProperties.OVERRIDES.get(propertyStr);
    if (value != null) {
        return value;
    }

    Bundle bundle = FrameworkUtil.getBundle(classParam);

    if (bundle != null) {
        BundleContext bundleContext = bundle.getBundleContext();
        if (bundleContext != null) {
            value = bundleContext.getProperty(propertyStr);
        }
    }
    if (value == null) {
        value = System.getProperty(propertyStr, defaultValue);
    }

    if (value == null) {
        LOG.debug("ConfigProperties missing a value for {}, default {}", propertyStr, defaultValue);
    }

    return value;
}
 
Example 6
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 7
Source File: ClientResourcesUtils.java    From flow with Apache License 2.0 6 votes vote down vote up
private static ClientResources loadService() {
    try {
        Class.forName("org.osgi.framework.FrameworkUtil");
        Bundle bundle = FrameworkUtil.getBundle(ClientResources.class);
        if (bundle == null) {
            return getDefaultService(null);
        }
        BundleContext context = bundle.getBundleContext();

        ServiceReference<ClientResources> reference = context
                .getServiceReference(ClientResources.class);
        if (reference == null) {
            return getDefaultService(null);
        }
        LoggerFactory.getLogger(ClientResourcesUtils.class).trace(
                "OSGi environment is detected. Load client resources using OSGi service");
        return context.getService(reference);
    } catch (ClassNotFoundException exception) {
        return getDefaultService(exception);
    }
}
 
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: EclipseUtil.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a map of all loaded bundle symbolic names mapped to bundles
 * 
 * @return
 */
public static Map<String, BundleContext> getCurrentBundleContexts()
{
	Map<String, BundleContext> contexts = new HashMap<String, BundleContext>();

	BundleContext context = CorePlugin.getDefault().getContext();
	contexts.put(context.getBundle().getSymbolicName(), context);

	Bundle[] bundles = context.getBundles();
	for (Bundle bundle : bundles)
	{
		BundleContext bContext = bundle.getBundleContext();
		if (bContext == null)
		{
			continue;
		}
		contexts.put(bundle.getSymbolicName(), bContext);
	}

	return contexts;
}
 
Example 10
Source File: ClassLoaderUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private Framework getFramework() {
    if (mgmt != null) {
        Maybe<OsgiManager> osgiManager = ((ManagementContextInternal)mgmt).getOsgiManager();
        if (osgiManager.isPresent()) {
            OsgiManager osgi = osgiManager.get();
            return osgi.getFramework();
        }
    }

    // Requires that caller code is executed AFTER loading bundle brooklyn-core
    Bundle bundle = FrameworkUtil.getBundle(ClassLoaderUtils.class);
    if (bundle != null) {
        BundleContext bundleContext = bundle.getBundleContext();
        return (Framework) bundleContext.getBundle(0);
    } else {
        return null;
    }
}
 
Example 11
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 12
Source File: OsgiServiceUtil.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get a service from the OSGi service registry. <b>Always</b> release the service using the
 * {@link OsgiServiceUtil#ungetService(Object)} method after usage.
 * 
 * @param clazz
 * @param filter
 *            provide a filter to select a specific service instance if multiple available
 * @return
 */
public synchronized static <T extends Object> Optional<T> getService(Class<T> clazz,
	String filter){
	Bundle bundle = FrameworkUtil.getBundle(clazz);
	// fallback to our context ...
	if (bundle == null || bundle.getBundleContext() == null) {
		bundle = FrameworkUtil.getBundle(OsgiServiceUtil.class);
	}
	Collection<ServiceReference<T>> references = Collections.emptyList();
	try {
		references = bundle.getBundleContext().getServiceReferences(clazz, filter);
	} catch (InvalidSyntaxException e) {
		logger.error("Invalid filter syntax", e);
	}
	if (!references.isEmpty() && references.size() == 1) {
		ServiceReference<T> ref = references.iterator().next();
		T service = bundle.getBundleContext().getService(ref);
		if (service != null) {
			serviceReferences.put(service, ref);
			return Optional.of(service);
		}
	}
	return Optional.empty();
}
 
Example 13
Source File: HibernateUtil.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
private EntityManagerFactory getEntityManagerFactory() {
	if ( emf == null ) {
		Bundle thisBundle = FrameworkUtil.getBundle( HibernateUtil.class );
		// Could get this by wiring up OsgiTestBundleActivator as well.
		BundleContext context = thisBundle.getBundleContext();

		ServiceReference serviceReference = context.getServiceReference( PersistenceProvider.class.getName() );
		PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService( serviceReference );

		emf = persistenceProvider.createEntityManagerFactory( "unmanaged-jpa", null );
	}
	return emf;
}
 
Example 14
Source File: OSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the {@link BundleContext}, which is used for registration and unregistration of OSGi
 * services. By default it uses the bundle context of the test class itself. This method can be overridden
 * by concrete implementations to provide another bundle context.
 *
 * @return bundle context
 */
protected BundleContext getBundleContext() {
    final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
    if (bundle != null) {
        return bundle.getBundleContext();
    } else {
        return null;
    }
}
 
Example 15
Source File: JavaOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Initialize the {@link BundleContext}, which is used for registration and unregistration of OSGi services.
 *
 * <p>
 * This uses the bundle context of the test class itself.
 *
 * @return bundle context
 */
private @Nullable BundleContext initBundleContext() {
    final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
    if (bundle != null) {
        return bundle.getBundleContext();
    } else {
        return null;
    }
}
 
Example 16
Source File: JavaOSGiTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Initialize the {@link BundleContext}, which is used for registration and unregistration of OSGi services.
 *
 * <p>
 * This uses the bundle context of the test class itself.
 *
 * @return bundle context
 */
private @Nullable BundleContext initBundleContext() {
    final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
    if (bundle != null) {
        return bundle.getBundleContext();
    } else {
        return null;
    }
}
 
Example 17
Source File: ModelAdapterFactory.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private BundleContext getModelBundleContext(final ModelClass<?> modelClass) {
    BundleContext modelContext = null;
    Bundle modelBundle = FrameworkUtil.getBundle(modelClass.getType());
    if (modelBundle != null) {
        return modelBundle.getBundleContext();
    }
    return null;
}
 
Example 18
Source File: AdminBundleChecker.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Activate
public void start() {

	try {
		
		Bundle bundle = FrameworkUtil.getBundle(getClass());

		BundleContext ctx =  bundle.getBundleContext();
		
		Bundle[] bundles = ctx.getBundles();
		
		new AdminBundlesInstalled(ctx, bundles);
		

	}
	catch (Exception e) {
		_log.error(e);
	}
	
	System.out.println("START OPENCPS KERNEL ^_^");
}
 
Example 19
Source File: BootstrapListener.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void contextInitialized(final ServletContextEvent event) {
  log.info("Initializing");

  ServletContext servletContext = event.getServletContext();
  
  try {
    Properties properties = System.getProperties();
    if (properties == null) {
      throw new IllegalStateException("Missing bootstrap configuration properties");
    }

    // Ensure required properties exist
    requireProperty(properties, "karaf.base");
    requireProperty(properties, "karaf.data");

    File workDir = new File(properties.getProperty("karaf.data")).getCanonicalFile();
    Path workDirPath = workDir.toPath();
    DirectoryHelper.mkdir(workDirPath);

    if (hasProFeature(properties)) {
      if (shouldSwitchToOss(workDirPath)) {
        adjustEditionProperties(properties);
      }
      else {
        createProEditionMarker(workDirPath);
      }
    }

    selectDbFeature(properties);

    // pass bootstrap properties to embedded servlet listener
    servletContext.setAttribute("nexus.properties", properties);

    // are we already running in OSGi or should we embed OSGi?
    Bundle containingBundle = FrameworkUtil.getBundle(getClass());
    BundleContext bundleContext;
    if (containingBundle != null) {
      bundleContext = containingBundle.getBundleContext();
    }
    else {
      // when we support running in embedded mode this is where it'll go
      throw new UnsupportedOperationException("Missing OSGi container");
    }

    // bootstrap our chosen Nexus edition
    requireProperty(properties, NEXUS_EDITION);
    requireProperty(properties, NEXUS_DB_FEATURE);
    installNexusEdition(bundleContext, properties);

    // watch out for the real Nexus listener
    listenerTracker = new ListenerTracker(bundleContext, "nexus", servletContext);
    listenerTracker.open();

    // watch out for the real Nexus filter
    filterTracker = new FilterTracker(bundleContext, "nexus");
    filterTracker.open();

    listenerTracker.waitForService(0);
    filterTracker.waitForService(0);
  }
  catch (Exception e) {
    log.error("Failed to initialize", e);
    throw e instanceof RuntimeException ? ((RuntimeException) e) : new RuntimeException(e);
  }

  log.info("Initialized");
}
 
Example 20
Source File: OsgiHelper.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
/**
 * @return the bundle context, if we run in an OSGi environment, null otherwise
 */
public BundleContext findBundleContext() {

	final Bundle bundle = FrameworkUtil.getBundle( getClass());
	return bundle != null ? bundle.getBundleContext() : null;
}