Search in sources :

Example 31 with ServiceEvent

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);
}
Also used : NamespaceHandlerSet(org.apache.aries.blueprint.parser.NamespaceHandlerSet) Dictionary(java.util.Dictionary) BlueprintListener(org.osgi.service.blueprint.container.BlueprintListener) ProxyManager(org.apache.aries.proxy.ProxyManager) ArrayList(java.util.ArrayList) Properties(java.util.Properties) URI(java.net.URI) URL(java.net.URL) ReferenceMetadataImpl(org.apache.aries.blueprint.reflect.ReferenceMetadataImpl) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceRegistration(org.osgi.framework.ServiceRegistration) HashSet(java.util.HashSet) BeanMetadataImpl(org.apache.aries.blueprint.reflect.BeanMetadataImpl) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) RefMetadataImpl(org.apache.aries.blueprint.reflect.RefMetadataImpl) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 32 with ServiceEvent

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());
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) Subsystem(org.osgi.service.subsystem.Subsystem) AtomicReference(java.util.concurrent.atomic.AtomicReference) BundleException(org.osgi.framework.BundleException) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 33 with ServiceEvent

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<>());
}
Also used : InterceptedInstancesHooks(org.apache.karaf.service.interceptor.impl.runtime.hook.InterceptedInstancesHooks) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleActivator(org.osgi.framework.BundleActivator) Optional.ofNullable(java.util.Optional.ofNullable) InterceptorRegistry(org.apache.karaf.service.interceptor.impl.runtime.registry.InterceptorRegistry) EventListenerHook(org.osgi.framework.hooks.service.EventListenerHook) ServiceEvent(org.osgi.framework.ServiceEvent) ProxiesManager(org.apache.karaf.service.interceptor.impl.runtime.ProxiesManager) InterceptedServiceRegistry(org.apache.karaf.service.interceptor.impl.runtime.registry.InterceptedServiceRegistry) BundleContext(org.osgi.framework.BundleContext) Stream(java.util.stream.Stream) ProxyFactory(org.apache.karaf.service.interceptor.impl.runtime.proxy.ProxyFactory) FindHook(org.osgi.framework.hooks.service.FindHook) PropertiesManager(org.apache.karaf.service.interceptor.impl.runtime.PropertiesManager) INTERCEPTOR_PROPERTY(org.apache.karaf.service.interceptor.impl.runtime.ComponentProperties.INTERCEPTOR_PROPERTY) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) INTERCEPTORS_PROPERTY(org.apache.karaf.service.interceptor.impl.runtime.ComponentProperties.INTERCEPTORS_PROPERTY) ServiceRegistration(org.osgi.framework.ServiceRegistration) PropertiesManager(org.apache.karaf.service.interceptor.impl.runtime.PropertiesManager) InterceptorRegistry(org.apache.karaf.service.interceptor.impl.runtime.registry.InterceptorRegistry) ProxyFactory(org.apache.karaf.service.interceptor.impl.runtime.proxy.ProxyFactory) ServiceEvent(org.osgi.framework.ServiceEvent) Hashtable(java.util.Hashtable) InterceptedServiceRegistry(org.apache.karaf.service.interceptor.impl.runtime.registry.InterceptedServiceRegistry) ProxiesManager(org.apache.karaf.service.interceptor.impl.runtime.ProxiesManager) InterceptedInstancesHooks(org.apache.karaf.service.interceptor.impl.runtime.hook.InterceptedInstancesHooks)

Example 34 with ServiceEvent

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();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) SQLException(java.sql.SQLException) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) TransactionStatus(org.osgi.service.transaction.control.TransactionStatus) AtomicReference(java.util.concurrent.atomic.AtomicReference) XAResource(javax.transaction.xa.XAResource) RecoverableXAResource(org.osgi.service.transaction.control.recovery.RecoverableXAResource) TransactionException(org.osgi.service.transaction.control.TransactionException) ServiceEvent(org.osgi.framework.ServiceEvent) TransactionRolledBackException(org.osgi.service.transaction.control.TransactionRolledBackException) XAConnection(javax.sql.XAConnection)

Example 35 with ServiceEvent

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());
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Aggregations

ServiceEvent (org.osgi.framework.ServiceEvent)57 ServiceReference (org.osgi.framework.ServiceReference)31 Test (org.junit.Test)24 BundleContext (org.osgi.framework.BundleContext)24 ServiceListener (org.osgi.framework.ServiceListener)20 Bundle (org.osgi.framework.Bundle)18 Hashtable (java.util.Hashtable)15 ServiceRegistration (org.osgi.framework.ServiceRegistration)13 Collection (java.util.Collection)6 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)6 IOException (java.io.IOException)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 Dictionary (java.util.Dictionary)4 HashMap (java.util.HashMap)4 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)4 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3