Search in sources :

Example 11 with ServiceListener

use of org.osgi.framework.ServiceListener in project aries by apache.

the class Aries1428Test method testBundleNotPartOfSubsystemInstallationResolves.

@Test
public void testBundleNotPartOfSubsystemInstallationResolves() throws Exception {
    final Bundle core = getSubsystemCoreBundle();
    core.stop();
    bundleContext.addServiceListener(new ServiceListener() {

        @Override
        public void serviceChanged(ServiceEvent event) {
            if (event.getType() == ServiceEvent.REGISTERED) {
                File file = new File(BUNDLE_A);
                try {
                    Bundle bundleA = bundleContext.installBundle(file.toURI().toString(), new FileInputStream(file));
                    bundleA.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }, "(objectClass=org.osgi.service.subsystem.Subsystem)");
    core.start();
    assertBundleState(Bundle.RESOLVED | Bundle.ACTIVE, BUNDLE_A, getRootSubsystem());
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) File(java.io.File) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) Test(org.junit.Test) SubsystemTest(org.apache.aries.subsystem.itests.SubsystemTest)

Example 12 with ServiceListener

use of org.osgi.framework.ServiceListener 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 13 with ServiceListener

use of org.osgi.framework.ServiceListener in project karaf by apache.

the class GuardProxyCatalogTest method testProxyCreationThread.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testProxyCreationThread() throws Exception {
    ProxyManager proxyManager = getProxyManager();
    ConfigurationAdmin ca = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(ca.listConfigurations(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
    EasyMock.replay(ca);
    ServiceReference pmSref = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(pmSref);
    ServiceReference pmSref2 = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(pmSref2);
    ServiceReference cmSref = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmSref);
    Bundle b = EasyMock.createMock(Bundle.class);
    EasyMock.expect(b.getBundleId()).andReturn(23992734L).anyTimes();
    EasyMock.replay(b);
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
    EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(() -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes();
    final ServiceListener[] pmListenerHolder = new ServiceListener[1];
    String pmFilter = "(&(objectClass=" + ProxyManager.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))";
    bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(pmFilter));
    EasyMock.expectLastCall().andAnswer(() -> {
        pmListenerHolder[0] = (ServiceListener) EasyMock.getCurrentArguments()[0];
        return null;
    }).anyTimes();
    EasyMock.expect(bc.getServiceReferences(EasyMock.anyObject(String.class), EasyMock.contains(ConfigurationAdmin.class.getName()))).andReturn(new ServiceReference[] { cmSref }).anyTimes();
    EasyMock.expect(bc.getService(pmSref)).andReturn(proxyManager).anyTimes();
    EasyMock.expect(bc.getService(pmSref2)).andReturn(proxyManager).anyTimes();
    EasyMock.expect(bc.getService(cmSref)).andReturn(ca).anyTimes();
    EasyMock.replay(bc);
    // This should put a ServiceListener in the pmListenerHolder, the ServiceTracker does that
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName() });
    serviceProps.put(Constants.SERVICE_ID, 162L);
    final Map<ServiceReference<?>, Object> serviceMap = new HashMap<>();
    // The mock bundle context for the bundle providing the service is set up here
    BundleContext providerBC = EasyMock.createMock(BundleContext.class);
    // These are the expected service properties of the proxy registration. Note the proxy marker...
    final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
    expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
        ServiceReference sr = mockServiceReference(props);
        EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
        reg.unregister();
        EasyMock.expectLastCall().once();
        EasyMock.replay(reg);
        serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
        return reg;
    }).once();
    EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
    EasyMock.replay(providerBC);
    // In some cases the proxy-creating code is looking for a classloader (e.g. when run through
    // a coverage tool such as EclEmma). This will satisfy that.
    BundleWiring bw = EasyMock.createMock(BundleWiring.class);
    EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
    EasyMock.replay(bw);
    // The mock bundle that provides the original service (and also the proxy is registered with this)
    Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
    EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
    EasyMock.replay(providerBundle);
    ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
    assertEquals("Precondition", 0, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    // Create the proxy for the service
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals(1, gpc.proxyMap.size());
    assertEquals(1, gpc.createProxyQueue.size());
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(162L);
    assertNull("The registration shouldn't have happened yet", holder.registration);
    assertEquals(1, gpc.createProxyQueue.size());
    Thread[] tarray = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray);
    for (Thread t : tarray) {
        if (t != null) {
            assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
        }
    }
    // make the proxy manager appear
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref));
    // give the system some time to send the events...
    Thread.sleep(400);
    Thread ourThread = null;
    Thread[] tarray2 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray2);
    for (Thread t : tarray2) {
        if (t != null) {
            if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
                ourThread = t;
            }
        }
    }
    assertNotNull(ourThread);
    assertTrue(ourThread.isDaemon());
    assertTrue(ourThread.isAlive());
    assertNotNull(holder.registration);
    assertEquals(0, gpc.createProxyQueue.size());
    int numProxyThreads = 0;
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref2));
    // give the system some time to send the events...
    Thread.sleep(300);
    Thread[] tarray3 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray3);
    for (Thread t : tarray3) {
        if (t != null) {
            if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
                numProxyThreads++;
            }
        }
    }
    assertEquals("Maximum 1 proxy thread, even if there is more than 1 proxy service", 1, numProxyThreads);
    // Clean up thread
    pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, pmSref));
    // Give the system some time to stop the threads...
    Thread.sleep(300);
    Thread[] tarray4 = new Thread[Thread.activeCount()];
    Thread.enumerate(tarray4);
    for (Thread t : tarray4) {
        if (t != null) {
            assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
        }
    }
}
Also used : Dictionary(java.util.Dictionary) ServiceListener(org.osgi.framework.ServiceListener) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceRegistration(org.osgi.framework.ServiceRegistration) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 14 with ServiceListener

use of org.osgi.framework.ServiceListener 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 15 with ServiceListener

use of org.osgi.framework.ServiceListener in project felix by apache.

the class Felix method addServiceListener.

/**
 * Implementation for BundleContext.addServiceListener().
 * Adds service listener to the listener list so that is
 * can listen for <code>ServiceEvent</code>s.
 *
 * @param bundle The bundle that registered the listener.
 * @param l The service listener to add to the listener list.
 * @param f The filter for the listener; may be null.
 */
void addServiceListener(BundleImpl bundle, ServiceListener l, String f) throws InvalidSyntaxException {
    Filter oldFilter;
    Filter newFilter = (f == null) ? null : FrameworkUtil.createFilter(f);
    oldFilter = m_dispatcher.addListener(bundle._getBundleContext(), ServiceListener.class, l, newFilter);
    // Invoke ListenerHook.removed() if filter updated.
    Set<ServiceReference<org.osgi.framework.hooks.service.ListenerHook>> listenerHooks = getHookRegistry().getHooks(org.osgi.framework.hooks.service.ListenerHook.class);
    if (oldFilter != null) {
        final Collection removed = Collections.singleton(new ListenerInfo(bundle, bundle._getBundleContext(), ServiceListener.class, l, oldFilter, null, true));
        for (ServiceReference<org.osgi.framework.hooks.service.ListenerHook> sr : listenerHooks) {
            org.osgi.framework.hooks.service.ListenerHook lh = getService(this, sr, false);
            if (lh != null) {
                try {
                    m_secureAction.invokeServiceListenerHookRemoved(lh, removed);
                } catch (Throwable th) {
                    m_logger.log(sr, Logger.LOG_WARNING, "Problem invoking service registry hook", th);
                } finally {
                    m_registry.ungetService(this, sr, null);
                }
            }
        }
    }
    // Invoke the ListenerHook.added() on all hooks.
    final Collection added = Collections.singleton(new ListenerInfo(bundle, bundle._getBundleContext(), ServiceListener.class, l, newFilter, null, false));
    for (ServiceReference<org.osgi.framework.hooks.service.ListenerHook> sr : listenerHooks) {
        org.osgi.framework.hooks.service.ListenerHook lh = getService(this, sr, false);
        if (lh != null) {
            try {
                m_secureAction.invokeServiceListenerHookAdded(lh, added);
            } catch (Throwable th) {
                m_logger.log(sr, Logger.LOG_WARNING, "Problem invoking service registry hook", th);
            } finally {
                m_registry.ungetService(this, sr, null);
            }
        }
    }
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) ServiceReference(org.osgi.framework.ServiceReference) ListenerInfo(org.apache.felix.framework.util.ListenerInfo) SimpleFilter(org.apache.felix.framework.capabilityset.SimpleFilter) Filter(org.osgi.framework.Filter) ShrinkableCollection(org.apache.felix.framework.util.ShrinkableCollection) Collection(java.util.Collection)

Aggregations

ServiceListener (org.osgi.framework.ServiceListener)28 ServiceEvent (org.osgi.framework.ServiceEvent)21 ServiceReference (org.osgi.framework.ServiceReference)16 Bundle (org.osgi.framework.Bundle)8 Test (org.junit.Test)7 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)6 IOException (java.io.IOException)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 ArrayList (java.util.ArrayList)4 TimeoutException (java.util.concurrent.TimeoutException)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 BundleContext (org.osgi.framework.BundleContext)4 BundleException (org.osgi.framework.BundleException)4 Hashtable (java.util.Hashtable)3 Dictionary (java.util.Dictionary)2 List (java.util.List)2 Entry (java.util.Map.Entry)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 ObjectName (javax.management.ObjectName)2