org.osgi.framework.Bundle#getBundleContext ( )源码实例Demo

下面列出了org.osgi.framework.Bundle#getBundleContext ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
}
 
源代码2 项目: elexis-3-core   文件: OsgiServiceUtil.java
/**
 * 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");
}
 
@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");
}
 
源代码4 项目: ovsdb   文件: ConfigProperties.java
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;
}
 
@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()));
    }
}
 
源代码6 项目: flow   文件: ClientResourcesUtils.java
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);
    }
}
 
源代码7 项目: APICloud-Studio   文件: EclipseUtil.java
/**
 * 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;
}
 
源代码8 项目: brooklyn-server   文件: ClassLoaderUtils.java
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;
    }
}
 
源代码9 项目: onos   文件: DefaultServiceDirectory.java
/**
 * 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");
}
 
源代码10 项目: elexis-3-core   文件: OsgiServiceUtil.java
/**
 * 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();
}
 
@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();
}
 
@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()));
    }
}
 
private BundleContext getModelBundleContext(final ModelClass<?> modelClass) {
    BundleContext modelContext = null;
    Bundle modelBundle = FrameworkUtil.getBundle(modelClass.getType());
    if (modelBundle != null) {
        return modelBundle.getBundleContext();
    }
    return null;
}
 
源代码14 项目: openhab-core   文件: JavaOSGiTest.java
/**
 * 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;
    }
}
 
源代码15 项目: hibernate-demos   文件: HibernateUtil.java
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;
}
 
源代码16 项目: smarthome   文件: JavaOSGiTest.java
/**
 * 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;
    }
}
 
源代码17 项目: smarthome   文件: OSGiTest.java
/**
 * 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;
    }
}
 
源代码18 项目: opencps-v2   文件: AdminBundleChecker.java
@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 ^_^");
}
 
源代码19 项目: nexus-public   文件: BootstrapListener.java
@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");
}
 
源代码20 项目: roboconf-platform   文件: OsgiHelper.java
/**
 * @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;
}