Search in sources :

Example 1 with ServiceEvent

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

the class LogSupportTest method testServiceEvent.

@Test
public void testServiceEvent() throws Exception {
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(Constants.OBJECTCLASS, new String[] { "some.class.Name" });
    props.put(Constants.SERVICE_ID, 999L);
    ServiceReference sr = Mockito.mock(ServiceReference.class);
    Mockito.when(sr.getBundle()).thenReturn(bundle);
    Mockito.when(sr.getProperty(Mockito.anyString())).then(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) throws Throwable {
            return props.get(invocation.getArguments()[0]);
        }
    });
    Mockito.when(sr.getPropertyKeys()).thenReturn(props.keySet().toArray(new String[] {}));
    ServiceEvent se = new ServiceEvent(ServiceEvent.REGISTERED, sr);
    logSupport.serviceChanged(se);
    Mockito.verify(testLogger).info("Service [999, [some.class.Name]] ServiceEvent REGISTERED", (Throwable) null);
}
Also used : HashMap(java.util.HashMap) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 2 with ServiceEvent

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

the class FSClassLoaderProvider method activate.

/**
	 * Activate this component. Create the root directory.
	 *
	 * @param componentContext
	 * @throws MalformedURLException
	 * @throws InvalidSyntaxException
	 * @throws MalformedObjectNameException
	 */
@Activate
protected void activate(final ComponentContext componentContext) throws MalformedURLException, InvalidSyntaxException, MalformedObjectNameException {
    // get the file root
    this.root = new File(componentContext.getBundleContext().getDataFile(""), "classes");
    this.root.mkdirs();
    this.rootURL = this.root.toURI().toURL();
    this.callerBundle = componentContext.getUsingBundle();
    classLoaderWriterListeners.clear();
    if (classLoaderWriterServiceListener != null) {
        componentContext.getBundleContext().removeServiceListener(classLoaderWriterServiceListener);
        classLoaderWriterServiceListener = null;
    }
    classLoaderWriterServiceListener = new ServiceListener() {

        @Override
        public void serviceChanged(ServiceEvent event) {
            ServiceReference<ClassLoaderWriterListener> reference = (ServiceReference<ClassLoaderWriterListener>) event.getServiceReference();
            if (event.getType() == ServiceEvent.MODIFIED || event.getType() == ServiceEvent.REGISTERED) {
                classLoaderWriterListeners.put(getId(reference), reference);
            } else {
                classLoaderWriterListeners.remove(getId(reference));
            }
        }

        private Long getId(ServiceReference<ClassLoaderWriterListener> reference) {
            return (Long) reference.getProperty(Constants.SERVICE_ID);
        }
    };
    componentContext.getBundleContext().addServiceListener(classLoaderWriterServiceListener, LISTENER_FILTER);
    // handle the MBean Installation
    if (mbeanRegistration != null) {
        mbeanRegistration.unregister();
        mbeanRegistration = null;
    }
    Hashtable<String, String> jmxProps = new Hashtable<String, String>();
    jmxProps.put("type", "ClassLoader");
    jmxProps.put("name", "FSClassLoader");
    final Hashtable<String, Object> mbeanProps = new Hashtable<String, Object>();
    mbeanProps.put(Constants.SERVICE_DESCRIPTION, "Apache Sling FSClassLoader Controller Service");
    mbeanProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
    mbeanProps.put("jmx.objectname", new ObjectName("org.apache.sling.classloader", jmxProps));
    mbeanRegistration = componentContext.getBundleContext().registerService(FSClassLoaderMBean.class.getName(), new FSClassLoaderMBeanImpl(this, componentContext.getBundleContext()), mbeanProps);
}
Also used : ClassLoaderWriterListener(org.apache.sling.commons.classloader.ClassLoaderWriterListener) ServiceListener(org.osgi.framework.ServiceListener) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) ObjectName(javax.management.ObjectName) ServiceEvent(org.osgi.framework.ServiceEvent) File(java.io.File) Activate(org.osgi.service.component.annotations.Activate)

Example 3 with ServiceEvent

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

the class SlingAuthenticatorServiceListenerTest method testDuplicateRegistration.

@Test
public void testDuplicateRegistration() {
    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", "/path1", "/path2" });
    listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref1));
    final ServiceReference<?> ref2 = createServiceReference(new String[] { "/path2", "/path3" });
    listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref2));
    assertPaths(cache, new String[] { "/path1", "/path2", "/path2", "/path3" }, new ServiceReference<?>[] { ref1, ref1, ref2, ref2 });
    listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref2));
    assertPaths(cache, new String[] { "/path1", "/path2" }, new ServiceReference<?>[] { ref1, ref1 });
    listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref1));
    assertTrue(cache.getHolders().isEmpty());
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 4 with ServiceEvent

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

the class SlingAuthenticatorServiceListenerTest method testAddRemoveRegistration.

@Test
public void testAddRemoveRegistration() {
    final PathBasedHolderCache<AuthenticationRequirementHolder> cache = new PathBasedHolderCache<AuthenticationRequirementHolder>();
    final BundleContext context = mock(BundleContext.class);
    final SlingAuthenticatorServiceListener listener = SlingAuthenticatorServiceListener.createListener(context, cache);
    assertTrue(cache.getHolders().isEmpty());
    final ServiceReference<?> ref = createServiceReference(new String[] { "/path1" });
    listener.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, ref));
    assertEquals(1, cache.getHolders().size());
    assertPaths(cache, new String[] { "/path1" }, new ServiceReference<?>[] { ref });
    assertEquals(ref, cache.getHolders().get(0).serviceReference);
    listener.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
    assertTrue(cache.getHolders().isEmpty());
}
Also used : ServiceEvent(org.osgi.framework.ServiceEvent) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 5 with ServiceEvent

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

the class ServiceEventAdapter method serviceChanged.

/**
 * Once a Service event is received this method assembles and posts an event
 * via the <tt>EventAdmin</tt> as specified in 113.6.5 OSGi R4 compendium.
 *
 * @param event The event to adapt.
 */
@Override
public void serviceChanged(final ServiceEvent event) {
    final Dictionary<String, Object> properties = new Hashtable<String, Object>();
    properties.put(EventConstants.EVENT, event);
    properties.put(EventConstants.SERVICE, event.getServiceReference());
    final Object id = event.getServiceReference().getProperty(EventConstants.SERVICE_ID);
    if (null != id) {
        try {
            properties.put(EventConstants.SERVICE_ID, new Long(id.toString()));
        } catch (NumberFormatException ne) {
            // LOG and IGNORE
            LogWrapper.getLogger().log(event.getServiceReference(), LogWrapper.LOG_WARNING, "Exception parsing " + EventConstants.SERVICE_ID + "=" + id, ne);
        }
    }
    final Object pid = event.getServiceReference().getProperty(EventConstants.SERVICE_PID);
    if (null != pid) {
        properties.put(EventConstants.SERVICE_PID, pid.toString());
    }
    final Object objectClass = event.getServiceReference().getProperty(Constants.OBJECTCLASS);
    if (null != objectClass) {
        if (objectClass instanceof String[]) {
            properties.put(EventConstants.SERVICE_OBJECTCLASS, objectClass);
        } else {
            properties.put(EventConstants.SERVICE_OBJECTCLASS, new String[] { objectClass.toString() });
        }
    }
    final StringBuffer topic = new StringBuffer(ServiceEvent.class.getName().replace('.', '/')).append('/');
    switch(event.getType()) {
        case ServiceEvent.REGISTERED:
            topic.append("REGISTERED");
            break;
        case ServiceEvent.MODIFIED:
            topic.append("MODIFIED");
            break;
        case ServiceEvent.UNREGISTERING:
            topic.append("UNREGISTERING");
            break;
        default:
            // IGNORE
            return;
    }
    try {
        getEventAdmin().postEvent(new Event(topic.toString(), properties));
    } catch (IllegalStateException e) {
    // This is o.k. - indicates that we are stopped.
    }
}
Also used : Hashtable(java.util.Hashtable) ServiceEvent(org.osgi.framework.ServiceEvent) ServiceEvent(org.osgi.framework.ServiceEvent) Event(org.osgi.service.event.Event)

Aggregations

ServiceEvent (org.osgi.framework.ServiceEvent)56 ServiceReference (org.osgi.framework.ServiceReference)30 Test (org.junit.Test)24 BundleContext (org.osgi.framework.BundleContext)23 ServiceListener (org.osgi.framework.ServiceListener)20 Bundle (org.osgi.framework.Bundle)18 Hashtable (java.util.Hashtable)14 ServiceRegistration (org.osgi.framework.ServiceRegistration)12 Collection (java.util.Collection)6 IOException (java.io.IOException)5 Dictionary (java.util.Dictionary)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)5 File (java.io.File)4 FileInputStream (java.io.FileInputStream)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