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

The following examples show how to use org.osgi.framework.BundleContext#getService() . 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: 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 2
Source File: OsgiLogServiceIntegrationTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void requireThatAllSupportedLogFrameworksAreConfigured() throws Exception {
    // need to explicitly set log level of root logger since integration suite now provides a logger config file,
    // which disables that setLevel() call of the OsgiLogManager.
    Logger.getLogger("").setLevel(Level.INFO);

    long now = System.currentTimeMillis();
    TestDriver driver = TestDriver.newApplicationBundleInstance("app-h-log.jar", false);
    BundleContext ctx = driver.osgiFramework().bundleContext();
    ServiceReference<?> ref = ctx.getServiceReference(LogReaderService.class.getName());
    LogReaderService reader = (LogReaderService)ctx.getService(ref);
    ArrayList<LogEntry> logEntries = Collections.list(reader.getLog());
    assertTrue(logEntries.size() >= 4);

    assertLogContainsEntry("[jdk14] hello world", logEntries, now);
    assertLogContainsEntry("[slf4j] hello world", logEntries, now);
    assertLogContainsEntry("[log4j] hello world", logEntries, now);
    assertLogContainsEntry("[jcl] hello world", logEntries, now);

    assertTrue(driver.close());
}
 
Example 3
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 4
Source File: Activator.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
public void start(final BundleContext context) throws Exception {
	final ServiceReference<RemoteOSGiService> sref = context.getServiceReference(RemoteOSGiService.class);
	if (sref == null) {
		System.err.println("Remote service not running. Cannot retrieve LEDService");
		return;
	}

	final RemoteOSGiService remote = context.getService(sref);

	final URI uri = (URI.create("r-osgi://192.168.7.4"));
	remote.connect(uri);
	final RemoteServiceReference[] rrefs = remote.getRemoteServiceReferences(uri, LEDService.class.getName(), null);
	if (rrefs == null || rrefs.length == 0) {
		System.err.println("No LEDService found on the remote device");
	}

	final LEDService service = (LEDService) remote.getRemoteService(rrefs[0]);

	client = new LEDClient(service);
	context.registerService(ShellCommandGroup.class, client, null);
}
 
Example 5
Source File: ServiceHelper.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieve all the Instances of a Service, optionally
 * filtered via serviceFilter if non-null else all the results are
 * returned if null.
 *
 * @param clazz The target class
 * @param bundle The caller
 * @param serviceFilter LDAP filter to be applied in the search
 */
private static Object[] getGlobalInstances(Class<?> clazz, Object bundle,
                                          String serviceFilter) {
    Object[] instances = null;
    try {
        Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
        if (ourBundle != null) {
            BundleContext bundleContext = ourBundle.getBundleContext();

            ServiceReference<?>[] services = bundleContext.getServiceReferences(clazz
                    .getName(), serviceFilter);

            if (services != null) {
                instances = new Object[services.length];
                for (int i = 0; i < services.length; i++) {
                    instances[i] = bundleContext.getService(services[i]);
                }
            }
        }
    } catch (IllegalStateException | InvalidSyntaxException e) {
        LOG.error("Error retrieving global instances of {} from caller {} with filter {}",
                clazz, bundle, serviceFilter, e);
    }
    return instances;
}
 
Example 6
Source File: SyntheticBundleInstaller.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private static void waitForReadyMarker(BundleContext context, String marker, Bundle bundle) {
    if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null) {
        return;
    }
    long startTime = System.nanoTime();
    ServiceReference<?> readyServiceRef = context.getServiceReference(ReadyService.class.getName());
    ReadyService readyService = (ReadyService) context.getService(readyServiceRef);
    ReadyMarker expected = new ReadyMarker(marker, bundle.getSymbolicName());
    while (!readyService.isReady(expected)) {
        if (System.nanoTime() - startTime > TimeUnit.SECONDS.toNanos(WAIT_TIMOUT)) {
            Assert.fail(MessageFormat.format("Timout waiting for marker {0} at bundle {1}", marker,
                    bundle.getSymbolicName()));
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    context.ungetService(readyServiceRef);
}
 
Example 7
Source File: Util.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static String getRelativeUrl() {
    BundleContext context = CarbonUIUtil.getBundleContext();
    ServiceReference reference =
            context.getServiceReference(RegistryService.class.getName());
    RegistryService registryService = (RegistryService) context.getService(reference);
    String url = null;
    try {
        Registry systemRegistry = registryService.getConfigSystemRegistry();
        Resource resource = systemRegistry.get(RegistryResources.CONNECTION_PROPS);
        String servicePath = resource.getProperty("service-path");
        String contextRoot = resource.getProperty("context-root");
        contextRoot = contextRoot.equals("/") ? "" : contextRoot;
        url = contextRoot + servicePath + "/WSDL2CodeService";
    } catch (Exception e) {
        log.error(e);
    }
    return url;
}
 
Example 8
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 9
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 10
Source File: MenuAdminClient.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private void setDefaultMenus(String loggedInUserName,
                             boolean isSuperTenant,
                             ArrayList<String> userPermission,
                             HttpServletRequest request) {
    BundleContext bundleContext = CarbonUIUtil.getBundleContext();
    if (bundleContext != null) {
        ServiceReference reference = bundleContext.getServiceReference(CarbonUIDefinitions.class.getName());
        CarbonUIDefinitions carbonUIDefinitions;
        if (reference != null) {
            carbonUIDefinitions = (CarbonUIDefinitions) bundleContext.getService(reference);
            Menu[] userMenus = carbonUIDefinitions.getMenuDefinitions(loggedInUserName,
                        isSuperTenant, userPermission,request);
            if (userMenus != null) {
                Set<Menu> menuList = new LinkedHashSet<Menu>();
                menuList.addAll(Arrays.<Menu>asList(userMenus));
                Menu[] customMenus =
                        (Menu[]) request.getSession().getAttribute(USER_CUSTOM_MENU_ITEMS);
                if (customMenus != null) {
                    menuList.addAll(Arrays.<Menu>asList(customMenus));
                }
                menus = menuList.toArray(new Menu[menuList.size()]);
            	if (log.isDebugEnabled()) {
                    log.debug("Found exiting menu items in OSGI context");
                }
            }
        }
    }
}
 
Example 11
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 12
Source File: ResourceBundleTracker.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ResourceBundleTracker(BundleContext bundleContext, LocaleProvider localeProvider) {
    super(bundleContext, Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE, null);
    this.localeProvider = localeProvider;
    pkgAdmin = (PackageAdmin) bundleContext
            .getService(bundleContext.getServiceReference(PackageAdmin.class.getName()));
    this.bundleLanguageResourceMap = new LinkedHashMap<>();
}
 
Example 13
Source File: ResourceBundleTracker.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public ResourceBundleTracker(BundleContext bundleContext, LocaleProvider localeProvider) {
    super(bundleContext, Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE, null);
    this.localeProvider = localeProvider;
    pkgAdmin = (PackageAdmin) bundleContext
            .getService(bundleContext.getServiceReference(PackageAdmin.class.getName()));
    this.bundleLanguageResourceMap = new LinkedHashMap<Bundle, LanguageResourceBundleManager>();
}
 
Example 14
Source File: Activator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void loadContextProviders(final BundleContext bundleContext) {
    try {
        final Collection<ServiceReference<ContextDataProvider>> serviceReferences =
                bundleContext.getServiceReferences(ContextDataProvider.class, null);
        for (final ServiceReference<ContextDataProvider> serviceReference : serviceReferences) {
            final ContextDataProvider provider = bundleContext.getService(serviceReference);
            ThreadContextDataInjector.contextDataProviders.add(provider);
        }
    } catch (final InvalidSyntaxException ex) {
        LOGGER.error("Error accessing context data provider", ex);
    }
}
 
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: Activator.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void log ( final int level, final String message )
{
    final BundleContext context = this.context;
    if ( context == null )
    {
        return;
    }

    final ServiceReference<LogService> ref = context.getServiceReference ( LogService.class );
    if ( ref == null )
    {
        return;
    }

    final LogService service = context.getService ( ref );
    if ( service == null )
    {
        return;
    }

    try
    {
        service.log ( level, message );
    }
    finally
    {
        context.ungetService ( ref );
    }
}
 
Example 17
Source File: ImportController.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public Entry ( final BundleContext context, final ServiceReference<Importer> reference )
{
    this.context = context;
    this.reference = reference;
    this.service = context.getService ( reference );
    this.description = this.service.getDescription ();
}
 
Example 18
Source File: ReChargeTarmedOpenCons.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
private boolean initCodeElementService(){
	BundleContext context =
		FrameworkUtil.getBundle(ReChargeTarmedOpenCons.class).getBundleContext();
	serviceRef = context.getServiceReference(ICodeElementService.class);
	if (serviceRef != null) {
		codeElementService = context.getService(serviceRef);
		return true;
	} else {
		return false;
	}
}
 
Example 19
Source File: OSGiJaxwsEndpointManager.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setBundleContext(BundleContext bundleContext) {
    this.bundleContext = bundleContext;
    this.mbeanServer = (MBeanServer)bundleContext
        .getService(bundleContext.getServiceReference(MBeanServer.class.getName()));
}
 
Example 20
Source File: MyBundleActivator.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public void start(BundleContext ctx) throws Exception {
    ServiceReference<?> containerRef = ctx.getServiceReference(CurrentContainer.class.getName());
    service = new MyService((CurrentContainer)ctx.getService(containerRef));
    registration = ctx.registerService(MyService.class.getName(), service, null);
}