Search in sources :

Example 11 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project ddf by codice.

the class TestRegistryStorePublisher method setup.

@Before
public void setup() {
    registryId = new AttributeImpl(RegistryObjectMetacardType.REGISTRY_ID, "registryId");
    mockRegPubService = mock(RegistryPublicationService.class);
    mockFedAdminService = mock(FederationAdminService.class);
    executorService = mock(ScheduledExecutorService.class);
    serviceReference = mock(ServiceReference.class);
    mockRegistryStore = mock(RegistryStore.class);
    mockServiceEvent = mock(ServiceEvent.class);
    bundleContext = mock(BundleContext.class);
    mockIdentity = mock(Metacard.class);
    optMetacard = Optional.of(mockIdentity);
    registryStorePublisher = spy(new RegistryStorePublisher() {

        @Override
        BundleContext getBundleContext() {
            return bundleContext;
        }
    });
    registryStorePublisher.setExecutor(executorService);
    registryStorePublisher.setFederationAdminService(mockFedAdminService);
    registryStorePublisher.setRegistryPublicationService(mockRegPubService);
    Dictionary<String, Object> eventProperties = new Hashtable<>();
    eventProperties.put(EventConstants.EVENT, mockServiceEvent);
    eventProperties.put(Constants.SERVICE_PID, "servicePid");
    event = new Event("org/osgi/framework/ServiceEvent/MODIFIED", eventProperties);
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RegistryStore(org.codice.ddf.registry.api.internal.RegistryStore) Hashtable(java.util.Hashtable) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) FederationAdminService(org.codice.ddf.registry.federationadmin.service.internal.FederationAdminService) Matchers.anyString(org.mockito.Matchers.anyString) ServiceReference(org.osgi.framework.ServiceReference) Metacard(ddf.catalog.data.Metacard) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceEvent(org.osgi.framework.ServiceEvent) Event(org.osgi.service.event.Event) RegistryPublicationService(org.codice.ddf.registry.federationadmin.service.internal.RegistryPublicationService) BundleContext(org.osgi.framework.BundleContext) Before(org.junit.Before)

Example 12 with ServiceEvent

use of org.osgi.framework.ServiceEvent in project ddf by codice.

the class RegistryStoreCleanupHandlerTest method handleEvent.

private void handleEvent(ServiceReference bindRef, ServiceReference eventRef, int serviceEventType, String searchRegId, List<Metacard> metacards) throws Exception {
    cleanupHandler.bindRegistryStore(bindRef);
    ServiceEvent serviceEvent = mock(ServiceEvent.class);
    when(serviceEvent.getType()).thenReturn(serviceEventType);
    when(serviceEvent.getServiceReference()).thenReturn(eventRef);
    eventProperties.put(EventConstants.EVENT, serviceEvent);
    when(federationAdmin.getInternalRegistryMetacards()).thenReturn(metacards);
    event = new Event("myevent", eventProperties);
    cleanupHandler.handleEvent(event);
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent) ServiceEvent(org.osgi.framework.ServiceEvent) Event(org.osgi.service.event.Event)

Example 13 with ServiceEvent

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

the class ServiceStateTest method createService.

private void createService(StateConfig stateConfig, final List<Notification> received, final List<AttributeChangeNotification> attributeChanges) throws Exception {
    BundleContext context = mock(BundleContext.class);
    Logger logger = mock(Logger.class);
    ServiceState serviceState = new ServiceState(context, stateConfig, logger);
    ServiceReference reference = mock(ServiceReference.class);
    Bundle b1 = mock(Bundle.class);
    when(b1.getBundleId()).thenReturn(new Long(9));
    when(b1.getSymbolicName()).thenReturn("bundle");
    when(b1.getLocation()).thenReturn("file:/location");
    when(reference.getBundle()).thenReturn(b1);
    when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
    when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] { "org.apache.aries.jmx.Mock" });
    when(context.getAllServiceReferences(null, null)).thenReturn(new ServiceReference[] { reference });
    ServiceEvent registeredEvent = mock(ServiceEvent.class);
    when(registeredEvent.getServiceReference()).thenReturn(reference);
    when(registeredEvent.getType()).thenReturn(ServiceEvent.REGISTERED);
    ServiceEvent modifiedEvent = mock(ServiceEvent.class);
    when(modifiedEvent.getServiceReference()).thenReturn(reference);
    when(modifiedEvent.getType()).thenReturn(ServiceEvent.MODIFIED);
    MBeanServer server = mock(MBeanServer.class);
    //setup for notification
    ObjectName objectName = new ObjectName(OBJECTNAME);
    serviceState.preRegister(server, objectName);
    serviceState.postRegister(true);
    //add NotificationListener to receive the events
    serviceState.addNotificationListener(new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            if (notification instanceof AttributeChangeNotification) {
                attributeChanges.add((AttributeChangeNotification) notification);
            } else {
                received.add(notification);
            }
        }
    }, null, null);
    // capture the ServiceListener registered with BundleContext to issue ServiceEvents
    ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
    verify(context).addServiceListener(argument.capture());
    //send events
    AllServiceListener serviceListener = argument.getValue();
    serviceListener.serviceChanged(registeredEvent);
    serviceListener.serviceChanged(modifiedEvent);
    //shutdown dispatcher via unregister callback
    serviceState.postDeregister();
    //check the ServiceListener is cleaned up
    verify(context).removeServiceListener(serviceListener);
    ExecutorService dispatcher = serviceState.getEventDispatcher();
    assertTrue(dispatcher.isShutdown());
    dispatcher.awaitTermination(2, TimeUnit.SECONDS);
    assertTrue(dispatcher.isTerminated());
}
Also used : AttributeChangeNotification(javax.management.AttributeChangeNotification) Bundle(org.osgi.framework.Bundle) Logger(org.apache.aries.jmx.Logger) AttributeChangeNotification(javax.management.AttributeChangeNotification) Notification(javax.management.Notification) ServiceReference(org.osgi.framework.ServiceReference) ObjectName(javax.management.ObjectName) AllServiceListener(org.osgi.framework.AllServiceListener) ServiceEvent(org.osgi.framework.ServiceEvent) ExecutorService(java.util.concurrent.ExecutorService) BundleContext(org.osgi.framework.BundleContext) MBeanServer(javax.management.MBeanServer) NotificationListener(javax.management.NotificationListener)

Example 14 with ServiceEvent

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

the class BundleEventHookTest method testNoDeadlockWhenSubsystemsInitializing.

/*
     * See https://issues.apache.org/jira/browse/ARIES-982.
     * 
     * When activating, the subsystems bundle must initialize the root subsystem
     * along with any persisted subsystems. Part of the root subsystem 
     * initialization consists of adding all pre-existing bundles as 
     * constituents. In order to ensure that no bundles are missed, a bundle
     * event hook is registered first. The bundle event hook cannot process
     * events until the initialization is complete. Another part of 
     * initialization consists of registering the root subsystem service.
     * Therefore, a potential deadlock exists if something reacts to the
     * service registration by installing an unmanaged bundle.
     */
@Test
public void testNoDeadlockWhenSubsystemsInitializing() throws Exception {
    final Bundle bundle = getSubsystemCoreBundle();
    bundle.stop();
    final AtomicBoolean completed = new AtomicBoolean(false);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    try {
        bundleContext.addServiceListener(new ServiceListener() {

            @Override
            public void serviceChanged(ServiceEvent event) {
                Future<?> future = executor.submit(new Runnable() {

                    public void run() {
                        try {
                            Bundle a = bundle.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
                            completed.set(true);
                            a.uninstall();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                try {
                    future.get();
                    completed.set(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0))");
        Future<?> future = executor.submit(new Runnable() {

            public void run() {
                try {
                    bundle.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        try {
            future.get(3, TimeUnit.SECONDS);
            assertTrue("Deadlock detected", completed.get());
        } catch (TimeoutException e) {
            fail("Deadlock detected");
        }
    } finally {
        executor.shutdownNow();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 15 with ServiceEvent

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

the class BundleEventHookTest method testIgnoreUninstalledOriginBundleInAsyncInstalledEvent.

/*
     * Because bundle events are queued for later asynchronous processing while
     * the root subsystem is initializing, it is possible to see an installed
     * event whose origin bundle has been uninstalled (i.e. the origin bundle's
     * revision will be null). These events should result in the installed
     * bundle being associated with the root subsystem.
     */
@Test
public void testIgnoreUninstalledOriginBundleInAsyncInstalledEvent() throws Exception {
    final Bundle core = getSubsystemCoreBundle();
    core.stop();
    final Bundle b = bundleContext.installBundle(BUNDLE_B, new FileInputStream(BUNDLE_B));
    // Ensure bundle B has a context.
    b.start();
    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 for bundle A using B's context.
                a.set(b.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
                // Ensure the origin bundle will be uninstalled before the event is processed.
                b.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 origin bundle was uninstalled");
    }
    assertBundleState(a.get(), Bundle.INSTALLED);
    assertBundleState(b, Bundle.UNINSTALLED);
    Subsystem root = getRootSubsystem();
    assertState(Subsystem.State.ACTIVE, root);
    assertConstituent(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)

Aggregations

ServiceEvent (org.osgi.framework.ServiceEvent)26 Test (org.junit.Test)18 BundleContext (org.osgi.framework.BundleContext)15 ServiceReference (org.osgi.framework.ServiceReference)13 Hashtable (java.util.Hashtable)9 Bundle (org.osgi.framework.Bundle)9 ServiceListener (org.osgi.framework.ServiceListener)7 HashMap (java.util.HashMap)5 FileInputStream (java.io.FileInputStream)4 IOException (java.io.IOException)4 Collection (java.util.Collection)4 ServiceRegistrationHolder (org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder)4 Dictionary (java.util.Dictionary)3 TimeoutException (java.util.concurrent.TimeoutException)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 RegistryStore (org.codice.ddf.registry.api.internal.RegistryStore)3 IAnswer (org.easymock.IAnswer)3 BundleException (org.osgi.framework.BundleException)3 ServiceRegistration (org.osgi.framework.ServiceRegistration)3 BundleWiring (org.osgi.framework.wiring.BundleWiring)3