Search in sources :

Example 6 with ServiceListener

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

the class ObrProbeTabUI method init.

// ///////////////////
// Plugin elements //
// ///////////////////
private void init() throws Exception {
    this.osgiON = new ObjectName(OSGI_ON);
    ServiceListener sl = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            synchronized (ObrProbeTabUI.this) {
                // Ignore additional services if we already have one.
                if ((event.getType() == ServiceEvent.REGISTERED) && (m_brsRef != null)) {
                    return;
                } else // Initialize the service if we don't have one.
                if ((event.getType() == ServiceEvent.REGISTERED) && (m_brsRef == null)) {
                    initializeService();
                } else // Unget the service if it is unregistering.
                if ((event.getType() == ServiceEvent.UNREGISTERING) && event.getServiceReference().equals(m_brsRef)) {
                    m_context.ungetService(m_brsRef);
                    m_brsRef = null;
                    m_brs = null;
                    // Try to get another service.
                    initializeService();
                }
            }
        }
    };
    try {
        m_context.addServiceListener(sl, "(objectClass=" + RepositoryAdmin.class.getName() + ")");
    } catch (InvalidSyntaxException ex) {
        System.err.println("OBRPlugin: " + ex);
    }
    // Create the gui.
    createUserInterface();
    // Now try to manually initialize the shell service
    // since one might already be available.
    initializeService();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) RepositoryAdmin(org.osgi.service.obr.RepositoryAdmin) ServiceEvent(org.osgi.framework.ServiceEvent) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ObjectName(javax.management.ObjectName)

Example 7 with ServiceListener

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

the class EventDispatcherTest method testFireServiceEvent.

public void testFireServiceEvent() {
    final Bundle b1 = getMockBundle();
    final Bundle b2 = getMockBundle();
    final Bundle b3 = getMockBundle();
    final Bundle b4 = getMockBundle();
    final Set calledHooks = new HashSet();
    final EventHook eh1 = new EventHook() {

        public void event(ServiceEvent event, Collection contexts) {
            calledHooks.add(this);
        }
    };
    final EventHook eh2 = new EventHook() {

        public void event(ServiceEvent event, Collection contexts) {
            calledHooks.add(this);
            for (Iterator it = contexts.iterator(); it.hasNext(); ) {
                BundleContext bc = (BundleContext) it.next();
                if (bc.getBundle() == b1) {
                    it.remove();
                }
                if (bc.getBundle() == b2) {
                    it.remove();
                }
            }
        }
    };
    Logger logger = new Logger();
    ServiceRegistry registry = new ServiceRegistry(logger, null);
    registry.registerService(b4, new String[] { EventHook.class.getName() }, eh1, new Hashtable());
    registry.registerService(b4, new String[] { EventHook.class.getName() }, eh2, new Hashtable());
    // -- Set up event dispatcher
    EventDispatcher ed = new EventDispatcher(logger, registry);
    // -- Register some listeners
    final List fired = Collections.synchronizedList(new ArrayList());
    ServiceListener sl1 = new ServiceListener() {

        public void serviceChanged(ServiceEvent arg0) {
            fired.add(this);
        }
    };
    ed.addListener(b1.getBundleContext(), ServiceListener.class, sl1, null);
    ServiceListener sl2 = new ServiceListener() {

        public void serviceChanged(ServiceEvent arg0) {
            fired.add(this);
        }
    };
    ed.addListener(b2.getBundleContext(), ServiceListener.class, sl2, null);
    ServiceListener sl3 = new ServiceListener() {

        public void serviceChanged(ServiceEvent arg0) {
            fired.add(this);
        }
    };
    ed.addListener(b3.getBundleContext(), ServiceListener.class, sl3, null);
    // --- make the invocation
    ServiceReference sr = EasyMock.createNiceMock(ServiceReference.class);
    EasyMock.expect(sr.getProperty(Constants.OBJECTCLASS)).andReturn(new String[] { "java.lang.String" }).anyTimes();
    sr.isAssignableTo(b1, String.class.getName());
    EasyMock.expectLastCall().andReturn(Boolean.TRUE).anyTimes();
    sr.isAssignableTo(b2, String.class.getName());
    EasyMock.expectLastCall().andReturn(Boolean.TRUE).anyTimes();
    sr.isAssignableTo(b3, String.class.getName());
    EasyMock.expectLastCall().andReturn(Boolean.TRUE).anyTimes();
    EasyMock.replay(new Object[] { sr });
    ServiceEvent event = new ServiceEvent(ServiceEvent.REGISTERED, sr);
    assertEquals("Precondition failed", 0, fired.size());
    Felix framework = new Felix(new HashMap());
    ed.fireServiceEvent(event, null, framework);
    assertEquals(1, fired.size());
    assertSame(sl3, fired.iterator().next());
    assertEquals(2, calledHooks.size());
    assertTrue(calledHooks.contains(eh1));
    assertTrue(calledHooks.contains(eh2));
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceReference(org.osgi.framework.ServiceReference) EventHook(org.osgi.framework.hooks.service.EventHook) ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext)

Example 8 with ServiceListener

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

the class ServiceTrackerTest method testTracking.

@Test
public void testTracking() throws InvalidSyntaxException {
    Bundle bundle = mock(Bundle.class);
    when(bundle.getState()).thenReturn(Bundle.ACTIVE);
    BundleContext context = Mockito.mock(BundleContext.class);
    @SuppressWarnings("unchecked") ServiceTrackerCustomizer<Runnable, Runnable> customizer = mock(ServiceTrackerCustomizer.class);
    @SuppressWarnings("unchecked") ServiceReference<Runnable> ref = mock(ServiceReference.class);
    Runnable service = mock(Runnable.class);
    when(customizer.addingService(ref)).thenReturn(service);
    Filter filter = mock(Filter.class);
    String filterString = "(objectClass=java.lang.Runnable)";
    when(context.createFilter(Mockito.eq(filterString))).thenReturn(filter);
    ServiceTracker<Runnable, Runnable> tracker = new ServiceTracker<Runnable, Runnable>(context, Runnable.class, customizer);
    tracker.open();
    ArgumentCaptor<ServiceListener> listenerCaptor = ArgumentCaptor.forClass(ServiceListener.class);
    verify(context).addServiceListener(listenerCaptor.capture(), Mockito.eq(filterString));
    ServiceListener listener = listenerCaptor.getValue();
    listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
    verify(customizer).addingService(ref);
    listener.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, ref));
    verify(customizer).modifiedService(ref, service);
    listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
    verify(customizer).removedService(ref, service);
    tracker.close();
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) Filter(org.osgi.framework.Filter) ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 9 with ServiceListener

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

the class MockBundleContextTest method testServiceListener.

@Test
public void testServiceListener() throws Exception {
    ServiceListener serviceListener = mock(ServiceListener.class);
    bundleContext.addServiceListener(serviceListener);
    // prepare test services
    String clazz1 = String.class.getName();
    Object service1 = new Object();
    bundleContext.registerService(clazz1, service1, null);
    verify(serviceListener).serviceChanged(any(ServiceEvent.class));
    bundleContext.removeServiceListener(serviceListener);
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) ServiceEvent(org.osgi.framework.ServiceEvent) Test(org.junit.Test)

Example 10 with ServiceListener

use of org.osgi.framework.ServiceListener in project liferay-ide by liferay.

the class LiferayUIPlugin method start.

/**
 * (non-Javadoc)
 * @see AbstractUIPlugin#start(org.osgi.framework.
 * BundleContext )
 */
@Override
public void start(BundleContext context) throws Exception {
    super.start(context);
    _addRepository();
    _plugin = this;
    _serviceListener = new ServiceListener() {

        @Override
        public void serviceChanged(ServiceEvent event) {
            String[] objectClass = (String[]) event.getServiceReference().getProperty("objectClass");
            if (event.getType() == ServiceEvent.UNREGISTERING) {
                if (objectClass[0].equals("org.eclipse.e4.ui.workbench.IWorkbench")) {
                    IPath location = Platform.getLocation();
                    File file = new File(location.append(".metadata/.plugins/org.eclipse.e4.workbench").toOSString(), "workbench.xmi");
                    String content = FileUtil.readContents(file, true);
                    if ((content != null) && (content.indexOf("label=\"Liferay\"") != -1)) {
                        content = content.replaceFirst("label=\"Liferay\"", "label=\"Liferay Plugins\"");
                        try (InputStream ins = new ByteArrayInputStream(content.getBytes())) {
                            FileUtil.writeFile(file, ins);
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    };
    context.addServiceListener(_serviceListener);
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) IPath(org.eclipse.core.runtime.IPath) ByteArrayInputStream(java.io.ByteArrayInputStream) ServiceEvent(org.osgi.framework.ServiceEvent) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) File(java.io.File) URISyntaxException(java.net.URISyntaxException) CoreException(org.eclipse.core.runtime.CoreException) BackingStoreException(org.osgi.service.prefs.BackingStoreException)

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