public void testRemoveServiceListener() throws Exception { ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { } }; Set listeners = mock.getServiceListeners(); mock.removeServiceListener(null); assertEquals(0, listeners.size()); mock.removeServiceListener(listener); assertEquals(0, listeners.size()); mock.addServiceListener(listener); assertEquals(1, listeners.size()); mock.removeServiceListener(listener); assertEquals(0, listeners.size()); }
@SuppressWarnings("rawtypes") public ServiceRegistration registerService(String[] clazzes, final Object service, Dictionary properties) { MockServiceRegistration reg = new MockServiceRegistration(properties); MockServiceReference ref = new MockServiceReference(getBundle(), properties, reg, clazzes) { @Override public Object getProperty(String key) { if (SERVICE_PROPERTY.equals(key)) { return service; } else { return super.getProperty(key); } } }; ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, ref); for (Iterator iter = serviceListeners.iterator(); iter.hasNext();) { ServiceListener listener = (ServiceListener) iter.next(); listener.serviceChanged(event); } return reg; }
public void testServiceReferenceMemberType() throws Exception { serviceFactoryBean.setMemberType(MemberType.SERVICE_REFERENCE); serviceFactoryBean.setInterfaces(new Class<?>[] { Runnable.class }); serviceFactoryBean.afterPropertiesSet(); Collection col = (Collection) serviceFactoryBean.getObject(); assertFalse(col.isEmpty()); assertSame(ref, col.iterator().next()); Set listeners = bundleContext.getServiceListeners(); ServiceListener list = (ServiceListener) listeners.iterator().next(); ServiceReference ref2 = new MockServiceReference(); list.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref2)); assertEquals(2, col.size()); Iterator iter = col.iterator(); iter.next(); assertSame(ref2, iter.next()); }
public void testUnbind() { interceptor.afterPropertiesSet(); assertEquals(1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); ServiceListener sl = (ServiceListener) bundleContext.getServiceListeners().iterator().next(); // save old ref and invalidate it so new services are not found ServiceReference oldRef = refs[0]; refs = null; sl.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, oldRef)); assertEquals(1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(1, SimpleTargetSourceLifecycleListener.UNBIND); }
public void testStickinessWhenABetterServiceIsAvailable() throws Exception { interceptor.setSticky(true); interceptor.afterPropertiesSet(); ServiceListener sl = (ServiceListener) bundleContext.getServiceListeners().iterator().next(); Dictionary props = new Hashtable(); // increase service ranking props.put(Constants.SERVICE_RANKING, 10); ServiceReference ref = new MockServiceReference(null, props, null); ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, ref); assertEquals(1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); sl.serviceChanged(event); assertEquals("the proxy is not sticky", 1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); }
public void testStickinessWhenServiceGoesDown() throws Exception { interceptor.setSticky(true); interceptor.afterPropertiesSet(); ServiceListener sl = (ServiceListener) bundleContext.getServiceListeners().iterator().next(); Dictionary props = new Hashtable(); // increase service ranking props.put(Constants.SERVICE_RANKING, 10); ServiceReference higherRankingRef = new MockServiceReference(null, props, null); refs = new ServiceReference[] { new MockServiceReference(), higherRankingRef }; assertTrue(Arrays.equals(bundleContext.getServiceReferences((String)null, null), refs)); assertEquals(1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); sl.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, refs[0])); assertEquals(2, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); assertSame("incorrect backing reference selected", higherRankingRef, ((ServiceReferenceProxy) interceptor .getServiceReference()).getTargetServiceReference()); }
/** * Test method for * {@link org.eclipse.gemini.blueprint.util.OsgiListenerUtils#addServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener, java.lang.String)}. */ public void testAddServiceListenerBundleContextServiceListenerString() { final List refs = new ArrayList(); ServiceListener list = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (ServiceEvent.REGISTERED == event.getType()) refs.add(event.getSource()); } }; OsgiListenerUtils.addServiceListener(bundleContext, list, (String) null); assertFalse(refs.isEmpty()); assertEquals(3, refs.size()); assertSame(ref1, refs.get(0)); assertSame(ref2, refs.get(1)); assertSame(ref3, refs.get(2)); }
/** * Test method for * {@link org.eclipse.gemini.blueprint.util.OsgiListenerUtils#addSingleServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener, java.lang.String)}. */ public void testAddSingleServiceListenerBundleContextServiceListenerString() { final List refs = new ArrayList(); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (ServiceEvent.REGISTERED == event.getType()) refs.add(event.getSource()); } }; OsgiListenerUtils.addSingleServiceListener(bundleContext, listener, (String) null); assertFalse(refs.isEmpty()); assertEquals(1, refs.size()); assertSame(ref1, refs.get(0)); }
public RemoteServiceAdminCore(BundleContext context, BundleContext apiContext, DistributionProvider provider) { this.bctx = context; this.apictx = apiContext; this.eventProducer = new EventProducer(bctx); this.provider = provider; // listen for exported services being unregistered so we can close the export this.exportedServiceListener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.UNREGISTERING) { removeServiceExports(event.getServiceReference()); } } }; try { String filter = "(" + RemoteConstants.SERVICE_EXPORTED_INTERFACES + "=*)"; context.addServiceListener(exportedServiceListener, filter); } catch (InvalidSyntaxException ise) { throw new RuntimeException(ise); // can never happen } }
@Test public void testListeners() throws Exception { Future<PentahoCacheProvidingService> serviceFuture; factory.init(); verify( bundleContext ).addServiceListener( serviceListenerCaptor.capture(), argThat( matchesFilter ) ); serviceFuture = factory.getProviderService( MOCK_PID ); assertThat( serviceFuture.isDone(), is( true ) ); assertThat( serviceFuture.get( 1, TimeUnit.SECONDS ), is( providingService ) ); ServiceListener serviceListener = serviceListenerCaptor.getValue(); serviceListener.serviceChanged( new ServiceEvent( ServiceEvent.UNREGISTERING, serviceReference ) ); serviceFuture = factory.getProviderService( MOCK_PID ); assertThat( serviceFuture.isDone(), is( false ) ); serviceListener.serviceChanged( new ServiceEvent( ServiceEvent.REGISTERED, serviceReference ) ); serviceFuture = factory.getProviderService( MOCK_PID ); assertThat( serviceFuture.isDone(), is( true ) ); assertThat( serviceFuture.get( 1, TimeUnit.SECONDS ), is( providingService ) ); }
private void registerForServiceNotAvailable(final Bundle bundle, final String filterDataSource) throws InvalidSyntaxException { //serviceHideManager.hideService(filterDataSource); context.addServiceListener(new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) { try { checkAndRunLiquibase(bundle); } catch (Exception e) { LOG.error( MessageFormat.format("An error occured while processing bundle {0} for liquibase extender.", bundle.getSymbolicName()), e); } context.removeServiceListener(this); //serviceHideManager.showService(filterDataSource); } } }, filterDataSource); }
@Before public void setup() throws Exception { serviceReference = context.mock(ServiceReference.class, "serviceReference"); bundleContext = context.mock(BundleContext.class); listener = context.mock(GDEventListener.class); eventManager = new EventManager(); eventManager.setContext(bundleContext); timer = new Timer(); timer.schedule(new ShutdownTask(), 3000); context.checking(new Expectations() { { //oneOf(bundleContext).createFilter(with(aNonNull(String.class))); allowing(bundleContext).addServiceListener(with(any(ServiceListener.class)), with(aNonNull(String.class))); allowing(bundleContext).removeServiceListener(with(any(ServiceListener.class))); allowing(bundleContext).getServiceReferences(with(any(Class.class)), with(any(String.class))); allowing(bundleContext).getServiceReferences(with(any(String.class)), with(any(String.class))); } }); registerDevice("zwave32"); registerDevice("zwave31"); registerDevice("dev"); }
/** * Called by the framework for initialisation when the Activator class is loaded. * The method first get a service reference on the osgi logging service, used for * logging whithin the bundle. * * If the method cannot get a reference to the logging service, a NullPointerException is thrown. * @param context * @throws BundleException */ public void start(BundleContext context) throws Exception { // TODO Auto-generated method stub Activator.bc = context; // we construct a listener to detect if the log service appear or disapear. String filter = "(objectclass=" + logServiceName + ")"; ServiceListener logServiceListener = new LogServiceListener(); try { bc.addServiceListener( logServiceListener, filter); // in case the service is already registered, we send a REGISTERED event to its listener. ServiceReference srLog = bc.getServiceReference( logServiceName ); if( srLog != null ) { logServiceListener.serviceChanged(new ServiceEvent( ServiceEvent.REGISTERED, srLog )); } } catch ( InvalidSyntaxException e ) { throw new BundleException("Error in filter string while registering LogServiceListener." + e.toString()); } piService = new PiService(); }
/** * Called by the framework for initialisation when the Activator class is * loaded. The method first get a service reference on the osgi logging * service, used for logging whithin the bundle. * * If the method cannot get a reference to the logging service, a * NullPointerException is thrown. * * @param context * @throws BundleException */ public void start(BundleContext context) throws BundleException { Activator.bc = context; // we construct a listener to detect if the log service appear or // disapear. String logFilter = "(objectclass=" + logServiceName + ")"; ServiceListener logServiceListener = new LogServiceListener(); try { bc.addServiceListener(logServiceListener, logFilter); // in case the service is already registered, we send a REGISTERED // event to its listener. ServiceReference srLog = bc.getServiceReference(logServiceName); if (srLog != null) { logServiceListener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, srLog)); } } catch (InvalidSyntaxException e) { throw new BundleException("Error in filter string while registering LogServiceListener." + e.toString()); } log(LogService.LOG_INFO, "Starting version " + bc.getBundle().getHeaders().get("Bundle-Version")); influxDbFactory.start(); }
public void testMandatoryServiceUnAvailableWhileWorking() { serviceFactoryBean.setInterfaces(new Class[] { Serializable.class }); serviceFactoryBean.afterPropertiesSet(); Collection col = (Collection) serviceFactoryBean.getObject(); assertFalse(col.isEmpty()); Set listeners = bundleContext.getServiceListeners(); ServiceListener list = (ServiceListener) listeners.iterator().next(); list.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref)); try { // disable filter col.isEmpty(); fail("should have thrown exception"); } catch (ServiceUnavailableException ex) { // expected } }
protected void removeService(Object service) { ServiceReference ref = new MockServiceReference(); for (Iterator iter = services.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue().equals(service)) { ref = (ServiceReference) entry.getKey(); continue; } } services.remove(ref); ServiceEvent event = new ServiceEvent(ServiceEvent.UNREGISTERING, ref); for (Iterator iter = context.getServiceListeners().iterator(); iter.hasNext();) { ServiceListener listener = (ServiceListener) iter.next(); listener.serviceChanged(event); } }
/** * Test method for * {@link org.springframework.osgi.util.OsgiListenerUtils#addServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener, java.lang.String)}. */ public void testAddServiceListenerBundleContextServiceListenerString() { final List refs = new ArrayList(); ServiceListener list = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (ServiceEvent.REGISTERED == event.getType()) refs.add(event.getSource()); } }; OsgiListenerUtils.addServiceListener(bundleContext, list, (String) null); assertFalse(refs.isEmpty()); assertEquals(3, refs.size()); assertSame(ref1, refs.get(0)); assertSame(ref2, refs.get(1)); assertSame(ref3, refs.get(2)); }
/** * Test method for * {@link org.springframework.osgi.util.OsgiListenerUtils#addSingleServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener, java.lang.String)}. */ public void testAddSingleServiceListenerBundleContextServiceListenerString() { final List refs = new ArrayList(); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (ServiceEvent.REGISTERED == event.getType()) refs.add(event.getSource()); } }; OsgiListenerUtils.addSingleServiceListener(bundleContext, listener, (String) null); assertFalse(refs.isEmpty()); assertEquals(1, refs.size()); assertSame(ref1, refs.get(0)); }
public void testActivator() throws Exception { ServiceRegistration sreg = mock(ServiceRegistration.class); BundleContext bc = mock(BundleContext.class); when(bc.registerService(anyString(), anyObject(), any(Dictionary.class))).thenReturn(sreg); Activator a = new Activator(); a.start(bc); verify(bc).registerService(eq(EventHook.class.getName()), isA(HidingEventHook.class), any(Dictionary.class)); verify(bc).registerService(eq(FindHook.class.getName()), isA(HidingFindHook.class), any(Dictionary.class)); verify(bc).addServiceListener(isA(ServiceJockeyListener.class)); verify(bc, never()).removeServiceListener((ServiceListener) anyObject()); verify(sreg, never()).unregister(); a.stop(bc); verify(bc).removeServiceListener(isA(ServiceJockeyListener.class)); verify(sreg, times(2)).unregister(); }
/** * Executed when the service is activated. * * @param context * the service's context * @throws InvalidSyntaxException */ protected void activate(final ComponentContext context) throws InvalidSyntaxException { log.info("activate"); bundleContext = context.getBundleContext(); sl = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.UNREGISTERING) { cache.unregisterComponentBindingsProvider(event .getServiceReference()); } else if (event.getType() == ServiceEvent.REGISTERED) { cache.registerComponentBindingsProvider(event .getServiceReference()); } } }; bundleContext.addServiceListener(sl, "(" + Constants.OBJECTCLASS + "=" + ComponentBindingsProvider.class.getName() + ")"); reloadCache(); log.info("Activation successful"); }
public void testServiceAliveDuringUnregistration() throws Exception { service = new Polygon(); ServiceRegistration reg = bundleContext.registerService(Shape.class.getName(), service, null); String filter = OsgiFilterUtils.unifyFilter(Shape.class, null); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (ServiceEvent.UNREGISTERING == event.getType()) { ServiceReference ref = event.getServiceReference(); Object aliveService = bundleContext.getService(ref); assertNotNull("services not available during unregistration", aliveService); assertSame(service, aliveService); } } }; try { bundleContext.addServiceListener(listener, filter); reg.unregister(); } finally { bundleContext.removeServiceListener(listener); } }
/** * Constructs a new <code>MockBundleContext</code> instance allowing both * the bundle and the context properties to be specified. * * @param bundle associated bundle * @param props context properties */ public MockBundleContext(Bundle bundle, Properties props) { this.bundle = (bundle == null ? new MockBundle(this) : bundle); properties = new Properties(DEFAULT_PROPERTIES); if (props != null) properties.putAll(props); // make sure the order is preserved this.serviceListeners = new LinkedHashSet<ServiceListener>(2); this.bundleListeners = new LinkedHashSet<BundleListener>(2); }
public void addServiceListener(ServiceListener listener) { try { addServiceListener(listener, null); } catch (InvalidSyntaxException ex) { throw new IllegalStateException("exception should not occur"); } }
public void testAddServiceListener() throws Exception { ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { } }; mock.addServiceListener(listener); assertEquals(1, mock.getServiceListeners().size()); assertSame(listener, mock.getServiceListeners().iterator().next()); }
private static void registerListener(BundleContext context, ServiceListener listener, String filter) { Assert.notNull(context); Assert.notNull(listener); try { // add listener context.addServiceListener(listener, filter); } catch (InvalidSyntaxException isex) { throw (RuntimeException) new IllegalArgumentException("Invalid filter").initCause(isex); } }
private static void dispatchServiceRegistrationEvents(ServiceReference[] alreadyRegistered, ServiceListener listener) { if (log.isTraceEnabled()) log.trace("Calling listener for already registered services: " + ObjectUtils.nullSafeToString(alreadyRegistered)); if (alreadyRegistered != null) { for (int i = 0; i < alreadyRegistered.length; i++) { listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, alreadyRegistered[i])); } } }
/** * Removes a service listener from the given bundle context. This method * simply takes care of any exceptions that might be thrown (in case the * context is invalid). * * @param context bundle context to unregister the listener from * @param listener service listener to unregister * @return true if the listener unregistration has succeeded, false * otherwise (for example if the bundle context is invalid) */ public static boolean removeServiceListener(BundleContext context, ServiceListener listener) { if (context == null || listener == null) return false; try { context.removeServiceListener(listener); return true; } catch (IllegalStateException e) { // Bundle context is no longer valid } return false; }
public void testMandatoryServiceUnAvailableWhileWorking() { serviceFactoryBean.setInterfaces(new Class<?>[] { Runnable.class }); serviceFactoryBean.afterPropertiesSet(); Collection col = (Collection) serviceFactoryBean.getObject(); assertFalse(col.isEmpty()); Set listeners = bundleContext.getServiceListeners(); ServiceListener list = (ServiceListener) listeners.iterator().next(); // disable filter list.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref)); col.isEmpty(); }
public void testRebindWhenServiceGoesDownButAReplacementIsFound() { interceptor.afterPropertiesSet(); assertEquals(1, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); ServiceListener sl = (ServiceListener) bundleContext.getServiceListeners().iterator().next(); // unregister the old service sl.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, refs[0])); // a new one is found since the mock context will return one again assertEquals(2, SimpleTargetSourceLifecycleListener.BIND); assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND); }
/** * Test method for * {@link org.eclipse.gemini.blueprint.util.OsgiListenerUtils#removeServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener)}. */ public void testRemoveServiceListenerBundleContextServiceListener() { ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { } }; OsgiListenerUtils.addSingleServiceListener(bundleContext, listener, (String) null); assertEquals(1, bundleContext.getServiceListeners().size()); OsgiListenerUtils.removeServiceListener(bundleContext, listener); }
/** * Waits for a <em>Spring powered</em> bundle, given by its symbolic name, * to be fully started. * * <p/>Forces the current (test) thread to wait for the a Spring application * context to be published under the given symbolic name. This method allows * waiting for full initialization of Spring OSGi bundles before starting * the actual test execution. * * @param context bundle context to use for service lookup * @param forBundleWithSymbolicName bundle symbolic name * @param timeout maximum time to wait (in seconds) for the application * context to be published */ protected void waitOnContextCreation(BundleContext context, String forBundleWithSymbolicName, long timeout) { // translate from seconds to milliseconds long time = timeout * SECOND; // use the counter to make sure the threads block final Counter counter = new Counter("waitForContext on bnd=" + forBundleWithSymbolicName); counter.increment(); String filter = "(org.springframework.context.service.name=" + forBundleWithSymbolicName + ")"; ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) counter.decrement(); } }; OsgiListenerUtils.addServiceListener(context, listener, filter); if (logger.isDebugEnabled()) logger.debug("Start waiting for Spring/OSGi bundle=" + forBundleWithSymbolicName); try { if (counter.waitForZero(time)) { waitingFailed(forBundleWithSymbolicName); } else if (logger.isDebugEnabled()) { logger.debug("Found applicationContext for bundle=" + forBundleWithSymbolicName); } } finally { // inform waiting thread context.removeServiceListener(listener); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Before public void setUp() throws Exception { factory = new GlobalEventExecutorModuleFactory(); super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,factory)); Filter mockFilter = mock(Filter.class); doReturn("mock").when(mockFilter).toString(); doReturn(mockFilter).when(mockedContext).createFilter(anyString()); doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString()); ServiceReference mockServiceRef = mock(ServiceReference.class); doReturn(new ServiceReference[]{mockServiceRef}).when(mockedContext). getServiceReferences(anyString(), anyString()); doReturn(mock(EventExecutor.class)).when(mockedContext).getService(mockServiceRef); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Before public void setUp() throws Exception { factory = new NettyThreadgroupModuleFactory(); super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,factory)); Filter mockFilter = mock(Filter.class); doReturn("mock").when(mockFilter).toString(); doReturn(mockFilter).when(mockedContext).createFilter(anyString()); doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString()); ServiceReference mockServiceRef = mock(ServiceReference.class); doReturn(new ServiceReference[]{mockServiceRef}).when(mockedContext). getServiceReferences(anyString(), anyString()); doReturn(mock(EventLoopGroup.class)).when(mockedContext).getService(mockServiceRef); }
public void testDiscoveryPlugin() throws Exception { BundleContext ctx = EasyMock.createMock(BundleContext.class); stubCreateFilter(ctx); ctx.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq("(objectClass=" + DiscoveryPlugin.class.getName() + ")")); ServiceReference<DiscoveryPlugin> sr1 = createAppendPlugin(ctx); ServiceReference<DiscoveryPlugin> sr2 = createPropertyPlugin(ctx); EasyMock.expect(ctx.getServiceReferences(DiscoveryPlugin.class.getName(), null)) .andReturn(new ServiceReference[]{sr1, sr2}).anyTimes(); EasyMock.replay(ctx); EndpointDescription endpoint = createEndpoint(); Map<String, Object> expectedProps = new HashMap<String, Object>(endpoint.getProperties()); expectedProps.put("endpoint.id", "http://google.de:80/test/sub/appended"); expectedProps.put("foo", "bar"); expectedProps.put("service.imported", "true"); final ZooKeeper zk = EasyMock.createNiceMock(ZooKeeper.class); String expectedFullPath = "/osgi/service_registry/org/foo/myClass/some.machine#9876##test"; EndpointDescription epd = new EndpointDescription(expectedProps); ByteArrayOutputStream bos = new ByteArrayOutputStream(); new EndpointDescriptionParser().writeEndpoint(epd, bos); byte[] data = bos.toByteArray(); expectCreated(zk, expectedFullPath, EasyMock.aryEq(data)); EasyMock.replay(zk); PublishingEndpointListener eli = new PublishingEndpointListener(zk, ctx); List<EndpointDescription> endpoints = getEndpoints(eli); assertEquals("Precondition", 0, endpoints.size()); eli.endpointAdded(endpoint, null); assertEquals(1, endpoints.size()); //TODO enable //EasyMock.verify(zk); }
@Test public void testAddingWithNullValues() throws InvalidSyntaxException { IMocksControl c = EasyMock.createControl(); DistributionProvider provider = c.createMock(DistributionProvider.class); ServiceReference<DistributionProvider> providerRef = c.createMock(ServiceReference.class); EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_INTENTS_SUPPORTED)).andReturn(null); EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_CONFIGS_SUPPORTED)).andReturn(null); BundleContext context = c.createMock(BundleContext.class); String filterSt = String.format("(objectClass=%s)", DistributionProvider.class.getName()); Filter filter = FrameworkUtil.createFilter(filterSt); EasyMock.expect(context.createFilter(filterSt)).andReturn(filter); EasyMock.expect(context.getService(providerRef)).andReturn(provider); ServiceRegistration rsaReg = c.createMock(ServiceRegistration.class); EasyMock.expect(context.registerService(EasyMock.isA(String.class), EasyMock.isA(ServiceFactory.class), EasyMock.isA(Dictionary.class))) .andReturn(rsaReg).atLeastOnce(); context.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.isA(String.class)); EasyMock.expectLastCall(); final BundleContext apiContext = c.createMock(BundleContext.class); c.replay(); DistributionProviderTracker tracker = new DistributionProviderTracker(context) { protected BundleContext getAPIContext() { return apiContext; }; }; tracker.addingService(providerRef); c.verify(); }
@Test public void testDontExportOwnServiceProxies() throws InvalidSyntaxException { IMocksControl c = EasyMock.createControl(); Bundle b = c.createMock(Bundle.class); BundleContext bc = c.createMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); bc.addServiceListener(EasyMock.<ServiceListener>anyObject(), EasyMock.<String>anyObject()); EasyMock.expectLastCall().anyTimes(); bc.removeServiceListener(EasyMock.<ServiceListener>anyObject()); EasyMock.expectLastCall().anyTimes(); Dictionary<String, String> d = new Hashtable<String, String>(); EasyMock.expect(b.getHeaders()).andReturn(d).anyTimes(); ServiceReference sref = c.createMock(ServiceReference.class); EasyMock.expect(sref.getBundle()).andReturn(b).anyTimes(); EasyMock.expect(sref.getPropertyKeys()) .andReturn(new String[]{"objectClass", "service.exported.interfaces"}).anyTimes(); EasyMock.expect(sref.getProperty("objectClass")).andReturn(new String[] {"a.b.C"}).anyTimes(); EasyMock.expect(sref.getProperty(RemoteConstants.SERVICE_IMPORTED)).andReturn(true).anyTimes(); EasyMock.expect(sref.getProperty("service.exported.interfaces")).andReturn("*").anyTimes(); DistributionProvider provider = c.createMock(DistributionProvider.class); c.replay(); RemoteServiceAdminCore rsaCore = new RemoteServiceAdminCore(bc, bc, provider); // must return an empty List as sref if from the same bundle List<ExportRegistration> exRefs = rsaCore.exportService(sref, null); assertNotNull(exRefs); assertEquals(0, exRefs.size()); // must be empty assertEquals(rsaCore.getExportedServices().size(), 0); c.verify(); }
/** * Starts the OSGi framework, installs and starts the bundles. * * @throws BundleException * if the framework could not be started */ public void start() throws BundleException { logger.info("Loading the OSGi Framework Factory"); FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator() .next(); logger.info("Creating the OSGi Framework"); framework = frameworkFactory.newFramework(frameworkConfiguration); logger.info("Starting the OSGi Framework"); framework.start(); context = framework.getBundleContext(); context.addServiceListener(new ServiceListener() { public void serviceChanged(ServiceEvent event) { ServiceReference serviceReference = event.getServiceReference(); if (event.getType() == ServiceEvent.REGISTERED) { Object property = serviceReference .getProperty("org.springframework.context.service.name"); if (property != null) { addStartedSpringContext(property.toString()); } } logger.fine((event.getType() == ServiceEvent.REGISTERED ? "Registering : " : "Unregistering : ") + serviceReference); } }); installedBundles = installBundles(bundlesToInstall); List<Bundle> bundlesToStart = new ArrayList<Bundle>(); for (Bundle bundle : installedBundles) { if ("org.springframework.osgi.extender".equals(bundle.getSymbolicName())) { springOsgiExtender = bundle; } else { bundlesToStart.add(bundle); } } startBundles(bundlesToStart); }
private void registerHttpServiceListener() throws InvalidSyntaxException { bundleContext.addServiceListener(new ServiceListener() { @Override public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED) { LOGGER.info("Http service registered"); httpServiceRegistered(); } } }, String.format("(&(%s=%s))", Constants.OBJECTCLASS, HttpService.class.getName())); }