Search in sources :

Example 6 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 7 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 8 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 9 with ServiceEvent

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

the class RegistryStoreCleanupHandler method handleEvent.

@Override
public void handleEvent(Event event) {
    Object eventProperty = event.getProperty(EventConstants.EVENT);
    if (!cleanupRelatedMetacards || eventProperty == null || !(eventProperty instanceof ServiceEvent)) {
        return;
    }
    if (((ServiceEvent) eventProperty).getType() != ServiceEvent.UNREGISTERING) {
        return;
    }
    Object servicePid = ((ServiceEvent) event.getProperty(EventConstants.EVENT)).getServiceReference().getProperty(Constants.SERVICE_PID);
    if (servicePid == null) {
        return;
    }
    RegistryStore service = registryStorePidToServiceMap.get(servicePid);
    if (service == null) {
        return;
    }
    registryStorePidToServiceMap.remove(servicePid);
    LOGGER.info("Removing registry entries associated with remote registry {}", service.getId());
    executor.execute(() -> {
        String registryId = service.getRegistryId();
        try {
            Security security = Security.getInstance();
            List<Metacard> metacards = security.runAsAdminWithException(() -> federationAdminService.getInternalRegistryMetacards().stream().filter(m -> RegistryUtility.getStringAttribute(m, RegistryObjectMetacardType.REMOTE_REGISTRY_ID, "").equals(registryId)).collect(Collectors.toList()));
            List<String> idsToDelete = metacards.stream().map(Metacard::getId).collect(Collectors.toList());
            if (!idsToDelete.isEmpty()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Removing {} registry entries that came from {}. Removed entries: {}", metacards.size(), service.getId(), metacards.stream().map(m -> m.getTitle() + ":" + m.getId()).collect(Collectors.joining(", ")));
                }
                security.runAsAdminWithException(() -> {
                    federationAdminService.deleteRegistryEntriesByMetacardIds(idsToDelete);
                    return null;
                });
            }
        } catch (PrivilegedActionException e) {
            LOGGER.info("Unable to clean up registry metacards after registry store {} was deleted", service.getId(), e);
        }
    });
}
Also used : Metacard(ddf.catalog.data.Metacard) RegistryStore(org.codice.ddf.registry.api.internal.RegistryStore) PrivilegedActionException(java.security.PrivilegedActionException) ServiceEvent(org.osgi.framework.ServiceEvent) Security(org.codice.ddf.security.common.Security)

Example 10 with ServiceEvent

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

the class ApplicationServiceImplTest method testServiceChanged.

/**
     * Tests  the {@link ApplicationServiceImpl#setConfigFileName(String)} method
     *
     * @throws Exception
     */
@Test
public void testServiceChanged() throws Exception {
    Set<Repository> activeRepos = new HashSet<>(Arrays.asList(mainFeatureRepo, noMainFeatureRepo1));
    FeaturesService featuresService = createMockFeaturesService(activeRepos, null, null);
    when(bundleContext.getService(mockFeatureRef)).thenReturn(featuresService);
    ApplicationServiceImpl appService = new ApplicationServiceImpl(bundleStateServices) {

        @Override
        protected BundleContext getContext() {
            return bundleContext;
        }
    };
    appService.setConfigFileName("foo");
    ServiceReference<ConfigurationAdmin> testConfigAdminRef = mock(ServiceReference.class);
    ConfigurationAdmin testConfigAdmin = mock(ConfigurationAdmin.class);
    Configuration testConfig = mock(Configuration.class);
    when(bundleContext.getServiceReference(ConfigurationAdmin.class)).thenReturn(testConfigAdminRef);
    when(bundleContext.getService(testConfigAdminRef)).thenReturn(testConfigAdmin);
    when(testConfigAdmin.getConfiguration(ApplicationServiceImpl.class.getName())).thenReturn(testConfig);
    Dictionary<String, Object> testProperties = new Hashtable<>();
    testProperties.put("test1", "foo");
    testProperties.put("test2", "bar");
    when(testConfig.getProperties()).thenReturn(testProperties);
    ServiceEvent serviceEvent = mock(ServiceEvent.class);
    when(serviceEvent.getType()).thenReturn(ServiceEvent.REGISTERED);
    appService.serviceChanged(serviceEvent);
    assertThat(testConfig.getProperties().size(), is(testProperties.size()));
    assertThat(testConfig.getProperties().get("test1"), is("foo"));
}
Also used : Configuration(org.osgi.service.cm.Configuration) Hashtable(java.util.Hashtable) Mockito.anyString(org.mockito.Mockito.anyString) Repository(org.apache.karaf.features.Repository) ServiceEvent(org.osgi.framework.ServiceEvent) FeaturesService(org.apache.karaf.features.FeaturesService) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) HashSet(java.util.HashSet) 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