/** * Waits for the {@link ChefService} registration. * * @param bundleContext * @param api * @return */ public synchronized ChefService waitForChefService( BundleContext bundleContext, String name, String api) { ChefService chefService = null; try { for (int r = 0; r < 6; r++) { ServiceReference[] references = null; if (name != null) { references = bundleContext.getAllServiceReferences( ChefService.class.getName(), "(" + Constants.NAME + "=" + name + ")"); } else if (api != null) { references = bundleContext.getAllServiceReferences( ChefService.class.getName(), "(" + Constants.API + "=" + api + ")"); } if (references != null && references.length > 0) { chefService = (ChefService) bundleContext.getService(references[0]); return chefService; } Thread.sleep(10000L); } } catch (Exception e) { // noop } return chefService; }
public static FrameworkDTO newFrameworkDTO( BundleContext systemBundleContext, Map<String, String> configuration) { FrameworkDTO dto = new FrameworkDTO(); dto.properties = asProperties(configuration); if (systemBundleContext == null) { dto.bundles = newList(0); dto.services = newList(0); return dto; } Bundle[] bundles = systemBundleContext.getBundles(); int size = bundles == null ? 0 : bundles.length; List<BundleDTO> bundleDTOs = newList(size); for (int i = 0; i < size; i++) { bundleDTOs.add(newBundleDTO(bundles[i])); } dto.bundles = bundleDTOs; try { ServiceReference<?>[] references = systemBundleContext.getAllServiceReferences(null, null); size = references == null ? 0 : references.length; List<ServiceReferenceDTO> refDTOs = newList(size); for (int i = 0; i < size; i++) { ServiceReferenceDTO serviceRefDTO = getServiceReferenceDTO(references[i]); if (serviceRefDTO != null) { refDTOs.add(serviceRefDTO); } } dto.services = refDTOs; } catch (InvalidSyntaxException e) { dto.services = newList(0); } return dto; }
@SuppressWarnings({"rawtypes", "unchecked", "unused"}) private void logServiceProperties(final Class<?> klaz, final Object instance) throws Exception { final BundleContext context = bundleContext(); final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null); for (final ServiceReference reference : referenceArray) { final Object service = context.getService(reference); if (service == instance) { log.info("instance=" + instance); final String[] propKeyArray = reference.getPropertyKeys(); for (final String propKey : propKeyArray) { final Object propValue = reference.getProperty(propKey); log.info(propKey + "=" + propValue); } // final String[] nameArray = (String[]) reference // .getProperty("objectClass"); // for (final String name : nameArray) { // log.info("name=" + name); // } } } }
private Collection<CommandName> listCommands() { Set<CommandName> commands = new HashSet<>(); ServiceReference<?>[] refs; try { refs = context.getAllServiceReferences(null, "(osgi.command.scope=*)"); } catch (InvalidSyntaxException e) { // should never happen throw new RuntimeException(e); } for (ServiceReference<?> ref : refs) { String scope = (String) ref.getProperty("osgi.command.scope"); Object funcsObj = ref.getProperty("osgi.command.function"); String[] funcs; if (funcsObj instanceof String[]) funcs = (String[]) funcsObj; else if (funcsObj instanceof String) funcs = new String[] {(String) funcsObj}; else funcs = new String[0]; for (String func : funcs) { CommandName command = new CommandName(scope, func); commands.add(command); } } return commands; }
protected <T> T getOsgiService(Class<T> type, String filter, long timeout) { ServiceTracker tracker = null; try { String flt; if (filter != null) { if (filter.startsWith("(")) { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")"; } else { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))"; } } else { flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")"; } Filter osgiFilter = FrameworkUtil.createFilter(flt); tracker = new ServiceTracker(bundleContext, osgiFilter, null); tracker.open(true); // Note that the tracker is not closed to keep the reference // This is buggy, as the service reference may change i think Object svc = type.cast(tracker.waitForService(timeout)); if (svc == null) { Dictionary dic = bundleContext.getBundle().getHeaders(); System.err.println("Test bundle headers: " + explode(dic)); for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) { System.err.println("ServiceReference: " + ref); } for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) { System.err.println("Filtered ServiceReference: " + ref); } throw new RuntimeException("Gave up waiting for service " + flt); } return type.cast(svc); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
/** * fetchReferences. * * @return an array of {@link org.osgi.framework.ServiceReference} objects. */ public ServiceReference<?>[] fetchReferences() { try { LOGGER.debug( "Try to locate a suitable service for objectClass = " + serviceInterface + " and filter = " + filterString); return bundleContext.getAllServiceReferences(serviceInterface, filterString); } catch (InvalidSyntaxException e) { LOGGER.error("Creation of filter failed: {}", e.getMessage(), e); throw new RuntimeException("Creation of filter failed", e); } }
private BundleContext setupBundleContextMock(Object mockbean, List<ServiceReference> references) throws Exception { BundleContext bundleContext = Mockito.mock(BundleContext.class); ServiceReference ref = createReference(references, "sym"); ApplicationContext appContext = Mockito.mock(ApplicationContext.class); Mockito.when(appContext.getBean("bean")).thenReturn(mockbean); Mockito.when(bundleContext.getService(ref)).thenReturn(appContext); Mockito.when( bundleContext.getAllServiceReferences( "org.springframework.context.ApplicationContext", null)) .thenReturn(references.toArray(new ServiceReference[] {})); return bundleContext; }
protected void assertNoAllReferences(BundleContext bundleContext, String clazz, String filter) throws Exception { ServiceReference[] actual = bundleContext.getAllServiceReferences(clazz, filter); if (actual != null) log.debug( bundleContext + " got " + Arrays.asList(actual) + " for clazz=" + clazz + " filter=" + filter); else log.debug(bundleContext + " got nothing for clazz=" + clazz + " filter=" + filter); assertNull("Expected no references for clazz=" + clazz + " filter=" + filter, actual); }
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void testConfiguration_shouldHaveWrittenTheLaterOne() throws Exception { ServiceReference[] allServiceReferences = ctx.getAllServiceReferences(ConfigurationAdmin.class.getName(), null); for (ServiceReference serviceReference : allServiceReferences) { ConfigurationAdmin service = (ConfigurationAdmin) ctx.getService(serviceReference); try { org.osgi.service.cm.Configuration configuration = service.getConfiguration("tests"); assertEquals("myvalue2", configuration.getProperties().get("mykey")); return; } catch (Exception e) { // continue } } fail(); }
private Connector[] getAllConnectors() { try { BundleContext context = Platform.getBundle(Activator.PLUGIN_ID).getBundleContext(); ServiceReference[] refs = context.getAllServiceReferences( Server.class.getName(), "(managedServerName=defaultJettyServer)"); for (ServiceReference ref : refs) { Server server = (Server) context.getService(ref); return server.getConnectors(); } } catch (InvalidSyntaxException e) { IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Can not find jetty server.", e); Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); Platform.getLog(bundle).log(status); throw new RuntimeException("Can not find jetty server.", e); } throw new RuntimeException("Can not find jetty server."); }
/** * Returns the compute service when it becomes registered to the OSGi service registry. * * @param provider * @return */ public static synchronized ComputeService waitForComputeService( BundleContext bundleContext, String provider) { ComputeService computeService = null; try { for (int r = 0; r < 6; r++) { ServiceReference[] references = bundleContext.getAllServiceReferences( ComputeService.class.getName(), "(provider=" + provider + ")"); if (references != null && references.length > 0) { computeService = (ComputeService) bundleContext.getService(references[0]); return computeService; } Thread.sleep(10000L); } } catch (Exception e) { LOGGER.error("Error while waiting for service.", e); } return computeService; }
/** * Method to get Shell Service implementation * * @return */ public Shell getShell() { if (shell == null) { // Get all Services implement Shell interface try { ServiceReference<?>[] references = context.getAllServiceReferences(Shell.class.getName(), null); for (ServiceReference<?> ref : references) { shell = (Shell) context.getService(ref); return shell; } return null; } catch (InvalidSyntaxException e) { LOGGER.warning("Cannot load Shell on ProjectConfigurationController."); return null; } } else { return shell; } }
/** * Method to get TypeLocationService Service implementation * * @return */ public TypeLocationService getTypeLocationService() { if (typeLocationService == null) { // Get all TypeLocationService implement Shell interface try { ServiceReference<?>[] references = context.getAllServiceReferences(TypeLocationService.class.getName(), null); for (ServiceReference<?> ref : references) { typeLocationService = (TypeLocationService) context.getService(ref); return typeLocationService; } return null; } catch (InvalidSyntaxException e) { LOGGER.warning("Cannot load TypeLocationService on ProjectConfigurationController."); return null; } } else { return typeLocationService; } }
@SuppressWarnings({"rawtypes", "unchecked"}) private Bundle serviceBundle(final Class<?> klaz, final Object instance) throws Exception { final BundleContext context = bundleContext(); final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null); for (final ServiceReference reference : referenceArray) { final Object service = context.getService(reference); if (service == instance) { final Bundle bundle = reference.getBundle(); return bundle; } } log.error("bundle not found : klaz={} instance={}", klaz, instance); return null; }
@SuppressWarnings({"rawtypes", "unchecked", "unused"}) private Object serviceProperty(final Class<?> klaz, final Object instance, final String propName) throws Exception { final BundleContext context = bundleContext(); final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null); for (final ServiceReference reference : referenceArray) { final Object service = context.getService(reference); if (service == instance) { final Object propValue = reference.getProperty(propName); return propValue; } } log.error("property not found : {} {}", instance, propName); return null; }
@Test public void testGetServiceReferences() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); BundleContext context1 = bundle.getBundleContext(); assertNotNull(context1); assertNoGetReference(context1, A.class.getName()); assertNoReferences(context1, A.class.getName()); assertNoAllReferences(context1, A.class.getName()); assertNoGetReference(context1, B.class.getName()); assertNoReferences(context1, B.class.getName()); assertNoAllReferences(context1, B.class.getName()); Class<?> clazz = bundle.loadClass(A.class.getName()); Object service1 = clazz.newInstance(); ServiceRegistration sreg1 = context1.registerService(A.class.getName(), service1, null); assertNotNull(sreg1); ServiceReference sref1 = sreg1.getReference(); assertNotNull(sref1); assertGetReference(context1, A.class.getName(), sref1); assertReferences(context1, A.class.getName(), sref1); assertAllReferences(context1, A.class.getName(), sref1); assertNoGetReference(context1, B.class.getName()); assertNoReferences(context1, B.class.getName()); assertNoAllReferences(context1, B.class.getName()); sreg1.unregister(); assertNoGetReference(context1, A.class.getName()); assertNoReferences(context1, A.class.getName()); assertNoAllReferences(context1, A.class.getName()); assertNoGetReference(context1, B.class.getName()); assertNoReferences(context1, B.class.getName()); assertNoAllReferences(context1, B.class.getName()); try { context1.getServiceReference(null); fail("Should not be here!"); } catch (IllegalArgumentException t) { // expected } try { context1.getServiceReferences(null, "invalid"); fail("Should not be here!"); } catch (InvalidSyntaxException t) { // expected } try { context1.getAllServiceReferences(null, "invalid"); fail("Should not be here!"); } catch (InvalidSyntaxException t) { // expected } bundle.stop(); try { context1.getServiceReference(A.class.getName()); fail("Should not be here!"); } catch (IllegalStateException t) { // expected } try { context1.getServiceReferences(null, null); fail("Should not be here!"); } catch (IllegalStateException t) { // expected } try { context1.getAllServiceReferences(null, null); fail("Should not be here!"); } catch (IllegalStateException t) { // expected } } finally { bundle.uninstall(); } }
@Test public void testGetServiceReferencesNoWire() throws Exception { JavaArchive archiveA = ShrinkWrap.create(JavaArchive.class, "bundleA"); archiveA.addClass(A.class); archiveA.setManifest( new Asset() { public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName("bundleA"); builder.addExportPackages(A.class); return builder.openStream(); } }); Bundle bundleA = installBundle(archiveA); try { bundleA.start(); BundleContext contextA = bundleA.getBundleContext(); assertNotNull(contextA); Class<?> clazz = bundleA.loadClass(A.class.getName()); Object service = clazz.newInstance(); ServiceRegistration sreg1 = contextA.registerService(A.class.getName(), service, null); assertNotNull(sreg1); ServiceReference sref1 = sreg1.getReference(); assertNotNull(sref1); BundleContext systemContext = getFramework().getBundleContext(); ServiceReference sref = systemContext.getServiceReference(A.class.getName()); assertNotNull("Reference not null", sref); assertEquals(sref1, sref); ServiceReference[] srefs = systemContext.getServiceReferences(A.class.getName(), null); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); srefs = systemContext.getAllServiceReferences(A.class.getName(), null); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); sref = contextA.getServiceReference(A.class.getName()); assertNotNull("Reference not null", sref); assertEquals(sref1, sref); srefs = contextA.getServiceReferences(A.class.getName(), null); assertNotNull("References not null", srefs); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); srefs = contextA.getAllServiceReferences(A.class.getName(), null); assertNotNull("References not null", srefs); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); JavaArchive archiveB = ShrinkWrap.create(JavaArchive.class, "bundleB"); archiveB.setManifest( new Asset() { public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName("bundleB"); return builder.openStream(); } }); Bundle bundleB = installBundle(archiveB); try { bundleB.start(); BundleContext contextB = bundleB.getBundleContext(); assertNotNull(contextB); assertLoadClassFail(bundleB, A.class.getName()); // Verify that bundle B can see the service registered by bundle A // This is so because B does not have a wire to the service package // and can therefore not be constraint on this package. sref = contextB.getServiceReference(A.class.getName()); assertNotNull("Reference not null", sref); srefs = contextB.getServiceReferences(A.class.getName(), null); assertNotNull("References not null", srefs); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); srefs = contextB.getAllServiceReferences(A.class.getName(), null); assertNotNull("References not null", srefs); assertEquals(1, srefs.length); assertEquals(sref1, srefs[0]); } finally { bundleB.uninstall(); } } finally { bundleA.uninstall(); } }
public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { return delegate.getAllServiceReferences(clazz, filter); }