use of org.osgi.framework.ServiceEvent in project aries by apache.
the class LifecyclePolicyTest method testStatic.
@Test
public void testStatic() throws Exception {
final ReferenceMetadataImpl ref = new ReferenceMetadataImpl();
ref.setId("ref");
ref.setRuntimeInterface(TestItf.class);
ref.setLifecycle(ExtendedReferenceMetadata.LIFECYCLE_STATIC);
final BeanMetadataImpl bean1 = new BeanMetadataImpl();
bean1.setId("bean1");
bean1.setRuntimeClass(Bean1.class);
bean1.setInitMethod("init");
bean1.setDestroyMethod("destroy");
bean1.addProperty("itf", new RefMetadataImpl("ref"));
final BeanMetadataImpl bean2 = new BeanMetadataImpl();
bean2.setId("bean2");
bean2.setRuntimeClass(Bean2.class);
bean2.setInitMethod("init");
bean2.setDestroyMethod("destroy");
bean2.addProperty("bean1", new RefMetadataImpl("bean1"));
Bundle bundle = EasyMock.createMock(Bundle.class);
BundleContext bundleContext = EasyMock.createMock(BundleContext.class);
Bundle extenderBundle = EasyMock.createMock(Bundle.class);
BundleContext extenderBundleContext = EasyMock.createMock(BundleContext.class);
BlueprintListener eventDispatcher = EasyMock.createMock(BlueprintListener.class);
NamespaceHandlerRegistry namespaceHandlerRegistry = EasyMock.createMock(NamespaceHandlerRegistry.class);
ProxyManager proxyManager = EasyMock.createMock(ProxyManager.class);
NamespaceHandlerSet namespaceHandlerSet = EasyMock.createMock(NamespaceHandlerSet.class);
TestItf itf = EasyMock.createMock(TestItf.class);
ServiceRegistration registration = EasyMock.createMock(ServiceRegistration.class);
ExecutorService executorService = Executors.newFixedThreadPool(1);
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
List<URL> pathList = new ArrayList<URL>();
Set<URI> namespaces = new HashSet<URI>();
BlueprintContainerImpl container = new BlueprintContainerImpl(bundle, bundleContext, extenderBundle, eventDispatcher, namespaceHandlerRegistry, executorService, timer, pathList, proxyManager, namespaces) {
private boolean repoCreated = false;
@Override
public BlueprintRepository getRepository() {
if (!repoCreated) {
getComponentDefinitionRegistry().registerComponentDefinition(ref);
getComponentDefinitionRegistry().registerComponentDefinition(bean1);
getComponentDefinitionRegistry().registerComponentDefinition(bean2);
repoCreated = true;
}
return super.getRepository();
}
};
ServiceReference svcRef1 = EasyMock.createMock(ServiceReference.class);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundle.getState()).andReturn(Bundle.ACTIVE).anyTimes();
EasyMock.expect(bundle.getBundleContext()).andReturn(bundleContext).anyTimes();
Hashtable<String, String> headers = new Hashtable<String, String>();
headers.put(Constants.BUNDLE_SYMBOLICNAME, "bundleSymbolicName;blueprint.aries.xml-validation:=false");
EasyMock.expect(bundle.getHeaders()).andReturn(headers).anyTimes();
eventDispatcher.blueprintEvent(EasyMock.<BlueprintEvent>anyObject());
EasyMock.expectLastCall().anyTimes();
EasyMock.expect(namespaceHandlerRegistry.getNamespaceHandlers(namespaces, bundle)).andReturn(namespaceHandlerSet).anyTimes();
EasyMock.expect(namespaceHandlerSet.getNamespaces()).andReturn(namespaces).anyTimes();
namespaceHandlerSet.addListener(container);
EasyMock.expectLastCall();
EasyMock.expect(bundleContext.getProperty(BlueprintConstants.XML_VALIDATION_PROPERTY)).andReturn(null);
Properties props = new Properties();
props.put("osgi.blueprint.container.version", Version.emptyVersion);
props.put("osgi.blueprint.container.symbolicname", "bundleSymbolicName");
EasyMock.expect(bundleContext.registerService(EasyMock.aryEq(new String[] { BlueprintContainer.class.getName() }), EasyMock.same(container), EasyMock.eq((Dictionary) props))).andReturn(registration);
bundleContext.addServiceListener(EasyMock.<org.osgi.framework.ServiceListener>anyObject(), EasyMock.<String>anyObject());
EasyMock.expectLastCall();
EasyMock.expect(bundleContext.getServiceReferences((String) null, "(objectClass=" + TestItf.class.getName() + ")")).andReturn(new ServiceReference[] { svcRef1 });
EasyMock.expect(bundleContext.getService(svcRef1)).andReturn(itf);
EasyMock.expect(bundle.loadClass("java.lang.Object")).andReturn((Class) Object.class).anyTimes();
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
container.run();
ReferenceRecipe recipe = (ReferenceRecipe) container.getRepository().getRecipe("ref");
recipe.start(container);
Bean2 bean2i = (Bean2) container.getRepository().create("bean2");
Assert.assertNotNull(bean2i);
Assert.assertEquals(1, Bean2.initialized);
Assert.assertEquals(0, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
//
// Unregister the service
//
// Given the lifecycle is 'static', this should cause the Bean1 and Bean2
// to be destroyed
//
EasyMock.reset(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundleContext.ungetService(svcRef1)).andReturn(false);
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
recipe.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, svcRef1));
Assert.assertEquals(1, Bean2.initialized);
Assert.assertEquals(1, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
//
// Re-register the service
//
// Given the lifecycle is 'static', this should cause the Bean1 and Bean2
// to be recreated
//
EasyMock.reset(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
EasyMock.expect(bundle.getSymbolicName()).andReturn("bundleSymbolicName").anyTimes();
EasyMock.expect(bundle.getVersion()).andReturn(Version.emptyVersion).anyTimes();
EasyMock.expect(bundleContext.getService(svcRef1)).andReturn(itf);
EasyMock.expect(bundle.loadClass("java.lang.Object")).andReturn((Class) Object.class).anyTimes();
EasyMock.replay(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
recipe.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, svcRef1));
Assert.assertEquals(2, Bean2.initialized);
Assert.assertEquals(1, Bean2.destroyed);
EasyMock.verify(bundle, bundleContext, extenderBundle, extenderBundleContext, eventDispatcher, namespaceHandlerRegistry, namespaceHandlerSet, proxyManager, svcRef1, registration);
}
use of org.osgi.framework.ServiceEvent in project aries by apache.
the class BundleEventHookTest method testIgnoreUninstalledBundleInAsyncInstalledEvent.
/*
* Because bundle events are queued for later asynchronous processing while
* the root subsystem is initializing, it is possible to see an installed
* event for a bundle that has been uninstalled (i.e. the bundle revision
* will be null). These events should be ignored.
*/
@Test
public void testIgnoreUninstalledBundleInAsyncInstalledEvent() throws Exception {
final Bundle core = getSubsystemCoreBundle();
core.stop();
final AtomicReference<Bundle> a = new AtomicReference<Bundle>();
bundleContext.addServiceListener(new ServiceListener() {
@SuppressWarnings("unchecked")
@Override
public void serviceChanged(ServiceEvent event) {
if ((event.getType() & (ServiceEvent.REGISTERED | ServiceEvent.MODIFIED)) == 0)
return;
if (a.get() != null)
// We've been here before and already done what needs doing.
return;
ServiceReference sr = (ServiceReference) event.getServiceReference();
bundleContext.getService(sr);
try {
// Queue up the installed event.
a.set(core.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
// Ensure the bundle will be uninstalled before the event is processed.
a.get().uninstall();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0)(subsystem.state=RESOLVED))");
try {
// Before the fix, this would fail due to an NPE resulting from a
// null bundle revision.
core.start();
} catch (BundleException e) {
e.printStackTrace();
fail("Subsystems failed to handle an asynchronous bundle installed event after the bundle was uninstalled");
}
assertBundleState(a.get(), Bundle.UNINSTALLED);
Subsystem root = getRootSubsystem();
assertState(Subsystem.State.ACTIVE, root);
assertNotConstituent(root, a.get().getSymbolicName());
}
use of org.osgi.framework.ServiceEvent in project karaf by apache.
the class InterceptorActivator method start.
@Override
public void start(final BundleContext context) throws InvalidSyntaxException {
final PropertiesManager propertiesManager = new PropertiesManager();
// todo: decouple these three services with a bus? here we use the activator to keep it simple
interceptedServiceRegistry = new InterceptedServiceRegistry(this::onServiceAddition, this::onServiceRemoval, propertiesManager);
interceptorRegistry = new InterceptorRegistry(this::onInterceptorAddition, this::onInterceptorRemoval, propertiesManager);
proxiesManager = new ProxiesManager(interceptorRegistry, interceptedServiceRegistry, new ProxyFactory(), propertiesManager);
// listen for interceptors and intercepted instances to be able to react on (un)registrations
context.addServiceListener(interceptedServiceRegistry, "(" + INTERCEPTORS_PROPERTY + "=true)");
context.addServiceListener(interceptorRegistry, "(" + INTERCEPTOR_PROPERTY + "=true)");
// register existing services/interceptors
ofNullable(context.getAllServiceReferences(null, "(" + INTERCEPTORS_PROPERTY + "=true)")).ifPresent(refs -> Stream.of(refs).forEach(ref -> interceptedServiceRegistry.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref))));
ofNullable(context.getAllServiceReferences(null, "(" + INTERCEPTOR_PROPERTY + "=true)")).ifPresent(refs -> Stream.of(refs).forEach(ref -> interceptorRegistry.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref))));
// ensure we filter out the proxied services to only return proxies
hooksRegistration = context.registerService(new String[] { FindHook.class.getName(), EventListenerHook.class.getName() }, new InterceptedInstancesHooks(context.getBundle().getBundleId()), new Hashtable<>());
}
use of org.osgi.framework.ServiceEvent in project aries by apache.
the class TransactionLogTest method doRecoveryRequired.
public void doRecoveryRequired(BiConsumer<XAResource, XAResource> ordering, TransactionStatus expectedFinalState) throws Exception {
//Register the recoverable resource
ArgumentCaptor<ServiceListener> captor = ArgumentCaptor.forClass(ServiceListener.class);
Mockito.verify(ctx).addServiceListener(captor.capture(), Mockito.anyString());
Mockito.when(ctx.getService(serviceRef)).thenReturn(new TestRecoverableResource("foo", dataSource));
captor.getValue().serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, serviceRef));
XAConnection xaConn = dataSource.getXAConnection();
AtomicReference<TransactionStatus> ref = new AtomicReference<TransactionStatus>();
try {
txControl.required(() -> {
txControl.getCurrentContext().postCompletion(ref::set);
Connection conn = xaConn.getConnection();
// conn.setAutoCommit(false);
XAResource dsResource = xaConn.getXAResource();
XAResource poison = Mockito.mock(XAResource.class);
Mockito.when(poison.prepare(Mockito.any())).thenAnswer(i -> {
conn.createStatement().execute("shutdown immediately");
Thread.sleep(1000);
return XA_OK;
});
ordering.accept(dsResource, poison);
return conn.createStatement().execute("Insert into TEST_TABLE values ( 'Hello World!' )");
});
} catch (TransactionException te) {
assertEquals(expectedFinalState, ref.get());
assertEquals(expectedFinalState == ROLLED_BACK, te instanceof TransactionRolledBackException);
} finally {
try {
xaConn.close();
} catch (SQLException sqle) {
}
}
setupServerAndDataSource();
}
use of org.osgi.framework.ServiceEvent in project sling by apache.
the class SlingAuthenticatorServiceListenerTest method testModifyRegistration.
@Test
public void testModifyRegistration() {
final PathBasedHolderCache<AuthenticationRequirementHolder> cache = new PathBasedHolderCache<AuthenticationRequirementHolder>();
final BundleContext context = mock(BundleContext.class);
final SlingAuthenticatorServiceListener listener = SlingAuthenticatorServiceListener.createListener(context, cache);
final ServiceReference<?> ref1 = createServiceReference(new String[] { "/path1", "/path2", "/path3" });
listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref1));
assertPaths(cache, new String[] { "/path1", "/path2", "/path3" }, new ServiceReference<?>[] { ref1, ref1, ref1 });
when(ref1.getProperty(AuthConstants.AUTH_REQUIREMENTS)).thenReturn(new String[] { "/path1", "/path4", "/path5" });
assertPaths(cache, new String[] { "/path1", "/path2", "/path3" }, new ServiceReference<?>[] { ref1, ref1, ref1 });
listener.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref1));
assertPaths(cache, new String[] { "/path1", "/path4", "/path5" }, new ServiceReference<?>[] { ref1, ref1, ref1 });
listener.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, ref1));
assertTrue(cache.getHolders().isEmpty());
}
Aggregations