Search in sources :

Example 36 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project jackrabbit-oak by apache.

the class DocumentCachingDataStoreStatsTest method testUseCachingBlobStore.

@Test
public void testUseCachingBlobStore() {
    ServiceRegistration delegateReg = context.bundleContext().registerService(AbstractSharedCachingDataStore.class.getName(), mock(AbstractSharedCachingDataStore.class), null);
    assertNotNull(context.getService(AbstractSharedCachingDataStore.class));
    registerBlobStore();
    registerDocumentNodeStoreService(true);
    assertServiceActivated();
    ConsolidatedDataStoreCacheStats dataStoreStats = context.registerInjectActivateService(new ConsolidatedDataStoreCacheStats());
    assertNotNull(context.getService(ConsolidatedDataStoreCacheStatsMBean.class));
    deactivate(dataStoreStats, context.bundleContext());
    unregisterDocumentNodeStoreService();
    unregisterBlobStore();
    delegateReg.unregister();
}
Also used : AbstractSharedCachingDataStore(org.apache.jackrabbit.oak.plugins.blob.AbstractSharedCachingDataStore) ConsolidatedDataStoreCacheStats(org.apache.jackrabbit.oak.plugins.blob.ConsolidatedDataStoreCacheStats) ConsolidatedDataStoreCacheStatsMBean(org.apache.jackrabbit.oak.api.jmx.ConsolidatedDataStoreCacheStatsMBean) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Example 37 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project jackrabbit-oak by apache.

the class LuceneIndexProviderService method deactivate.

@Deactivate
private void deactivate() throws InterruptedException, IOException {
    for (ServiceRegistration reg : regs) {
        reg.unregister();
    }
    for (Registration reg : oakRegs) {
        reg.unregister();
    }
    if (backgroundObserver != null) {
        backgroundObserver.close();
    }
    if (externalIndexObserver != null) {
        externalIndexObserver.close();
    }
    if (indexProvider != null) {
        indexProvider.close();
        indexProvider = null;
    }
    if (documentQueue != null) {
        documentQueue.close();
    }
    if (nrtIndexFactory != null) {
        nrtIndexFactory.close();
    }
    //Close the copier first i.e. before executorService
    if (indexCopier != null) {
        indexCopier.close();
    }
    if (executorService != null) {
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
    }
    InfoStream.setDefault(InfoStream.NO_OUTPUT);
}
Also used : ServiceRegistration(org.osgi.framework.ServiceRegistration) Registration(org.apache.jackrabbit.oak.spi.whiteboard.Registration) ServiceRegistration(org.osgi.framework.ServiceRegistration) Deactivate(org.apache.felix.scr.annotations.Deactivate)

Example 38 with ServiceRegistration

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

the class BundleInstallSupportImpl method resolveBundles.

/* (non-Javadoc)
     * @see org.apache.karaf.features.internal.service.Regions#resolveBundles(java.util.Set, java.util.Map, java.util.Map)
     */
@Override
public void resolveBundles(Set<Bundle> bundles, final Map<Resource, List<Wire>> wiring, Map<Resource, Bundle> resToBnd) {
    // Make sure it's only used for us
    final Thread thread = Thread.currentThread();
    // Translate wiring
    final Map<Bundle, Resource> bndToRes = new HashMap<>();
    for (Resource res : resToBnd.keySet()) {
        bndToRes.put(resToBnd.get(res), res);
    }
    // Hook
    final ResolverHook hook = new ResolverHook() {

        @Override
        public void filterResolvable(Collection<BundleRevision> candidates) {
        }

        @Override
        public void filterSingletonCollisions(BundleCapability singleton, Collection<BundleCapability> collisionCandidates) {
        }

        @Override
        public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) {
            if (Thread.currentThread() == thread) {
                // osgi.ee capabilities are provided by the system bundle, so just ignore those
                if (ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE.equals(requirement.getNamespace())) {
                    return;
                }
                Bundle sourceBundle = requirement.getRevision().getBundle();
                Resource sourceResource = bndToRes.get(sourceBundle);
                Set<Resource> wired = new HashSet<>();
                // Get a list of allowed wired resources
                wired.add(sourceResource);
                for (Wire wire : wiring.get(sourceResource)) {
                    wired.add(wire.getProvider());
                    if (HostNamespace.HOST_NAMESPACE.equals(wire.getRequirement().getNamespace())) {
                        for (Wire hostWire : wiring.get(wire.getProvider())) {
                            wired.add(hostWire.getProvider());
                        }
                    }
                }
                // Remove candidates that are not allowed
                for (Iterator<BundleCapability> candIter = candidates.iterator(); candIter.hasNext(); ) {
                    BundleCapability cand = candIter.next();
                    BundleRevision br = cand.getRevision();
                    if ((br.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) {
                        br = br.getWiring().getRequiredWires(null).get(0).getProvider();
                    }
                    Resource res = bndToRes.get(br.getBundle());
                    if (!wired.contains(br) && !wired.contains(res)) {
                        candIter.remove();
                    }
                }
            }
        }

        @Override
        public void end() {
        }
    };
    ResolverHookFactory factory = triggers -> hook;
    ServiceRegistration<ResolverHookFactory> registration = systemBundleContext.registerService(ResolverHookFactory.class, factory, null);
    try {
        FrameworkWiring frameworkWiring = systemBundleContext.getBundle().adapt(FrameworkWiring.class);
        frameworkWiring.resolveBundles(bundles);
    } finally {
        registration.unregister();
    }
}
Also used : DigraphHelper(org.apache.karaf.features.internal.region.DigraphHelper) ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) Region(org.eclipse.equinox.region.Region) RegionFilterBuilder(org.eclipse.equinox.region.RegionFilterBuilder) ExecutionEnvironmentNamespace(org.osgi.framework.namespace.ExecutionEnvironmentNamespace) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) FeaturesService(org.apache.karaf.features.FeaturesService) FrameworkListener(org.osgi.framework.FrameworkListener) HashSet(java.util.HashSet) BundleCapability(org.osgi.framework.wiring.BundleCapability) Map(java.util.Map) Bundle(org.osgi.framework.Bundle) BundleRevision(org.osgi.framework.wiring.BundleRevision) BundleException(org.osgi.framework.BundleException) ServiceRegistration(org.osgi.framework.ServiceRegistration) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Resource(org.osgi.resource.Resource) Collection(java.util.Collection) FrameworkStartLevel(org.osgi.framework.startlevel.FrameworkStartLevel) Feature(org.apache.karaf.features.Feature) FrameworkEvent(org.osgi.framework.FrameworkEvent) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) Set(java.util.Set) IOException(java.io.IOException) ResolverHook(org.osgi.framework.hooks.resolver.ResolverHook) FileInputStream(java.io.FileInputStream) File(java.io.File) BundleContext(org.osgi.framework.BundleContext) BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) RegionDigraph(org.eclipse.equinox.region.RegionDigraph) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) Wire(org.osgi.resource.Wire) BundleUtils(org.apache.karaf.util.bundles.BundleUtils) HostNamespace(org.osgi.framework.namespace.HostNamespace) InputStream(java.io.InputStream) ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) HashMap(java.util.HashMap) ResolverHook(org.osgi.framework.hooks.resolver.ResolverHook) Bundle(org.osgi.framework.Bundle) Resource(org.osgi.resource.Resource) FrameworkWiring(org.osgi.framework.wiring.FrameworkWiring) Wire(org.osgi.resource.Wire) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) BundleRevision(org.osgi.framework.wiring.BundleRevision) Collection(java.util.Collection) BundleCapability(org.osgi.framework.wiring.BundleCapability) HashSet(java.util.HashSet)

Example 39 with ServiceRegistration

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

the class GuardProxyCatalogTest method testCreateProxy.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Dictionary<String, Object> testCreateProxy(BundleContext bc, Class intf, final Class proxyRegClass, Object testService) throws Exception {
    // Create the object that is actually being tested here
    GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
    // The service being proxied has these properties
    long serviceID = 456L;
    final Hashtable<String, Object> serviceProps = new Hashtable<>();
    serviceProps.put(Constants.OBJECTCLASS, new String[] { intf.getName() });
    serviceProps.put(Constants.SERVICE_ID, serviceID);
    serviceProps.put(".foo", 123L);
    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);
    // This will check that the right proxy is being registered.
    EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
        if (!runningUnderCoverage) {
            assertArrayEquals(new String[] { proxyRegClass.getName() }, (String[]) EasyMock.getCurrentArguments()[0]);
            Object svc = EasyMock.getCurrentArguments()[1];
            assertTrue(svc instanceof ServiceFactory);
        }
        Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
        for (String key : expectedProxyProps.keySet()) {
            assertEquals(expectedProxyProps.get(key), props.get(key));
        }
        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());
    // The actual proxy creation is done asynchronously.
    GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
    assertNull("The registration shouldn't have happened yet", holder.registration);
    assertEquals(1, gpc.createProxyQueue.size());
    // Mimic the thread that works the queue to create the proxy
    GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
    ProxyManager pm = getProxyManager();
    runnable.run(pm);
    // The runnable should have put the actual registration in the holder
    ServiceReference<?> proxySR = holder.registration.getReference();
    for (String key : expectedProxyProps.keySet()) {
        assertEquals(expectedProxyProps.get(key), proxySR.getProperty(key));
    }
    // Check that the proxy registration was done on the original provider bundle's context
    EasyMock.verify(providerBC);
    // Test that the actual proxy invokes the original service...
    Object proxyService = serviceMap.get(proxySR);
    assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
    // Attempt to proxy the service again, make sure that no re-proxying happens
    assertEquals("Precondition", 1, gpc.proxyMap.size());
    assertEquals("Precondition", 0, gpc.createProxyQueue.size());
    gpc.proxyIfNotAlreadyProxied(sr);
    assertEquals("No additional proxy should have been created", 1, gpc.proxyMap.size());
    assertEquals("No additional work on the queue is expected", 0, gpc.createProxyQueue.size());
    Dictionary<String, Object> proxyProps = getServiceReferenceProperties(proxySR);
    gpc.close();
    // checks that the unregister call was made
    EasyMock.verify(holder.registration);
    return proxyProps;
}
Also used : Dictionary(java.util.Dictionary) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ServiceFactory(org.osgi.framework.ServiceFactory) CreateProxyRunnable(org.apache.karaf.service.guard.impl.GuardProxyCatalog.CreateProxyRunnable) Hashtable(java.util.Hashtable) Bundle(org.osgi.framework.Bundle) ServiceRegistrationHolder(org.apache.karaf.service.guard.impl.GuardProxyCatalog.ServiceRegistrationHolder) BundleWiring(org.osgi.framework.wiring.BundleWiring) ProxyManager(org.apache.aries.proxy.ProxyManager) AsmProxyManager(org.apache.aries.proxy.impl.AsmProxyManager) ServiceReference(org.osgi.framework.ServiceReference) IAnswer(org.easymock.IAnswer) BundleContext(org.osgi.framework.BundleContext) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 40 with ServiceRegistration

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

the class ITFilterSupport method filterUsingWildcard.

@Test
public void filterUsingWildcard() throws Exception {
    TestAppender ta1 = registerAppender("filterUsingWildcard1", "app1");
    TestAppender ta2 = registerAppender("filterUsingWildcard2", "app2");
    //Set additivity to false to prevent other appender like CONSOLE from
    //interfering
    org.slf4j.Logger baz1 = LoggerFactory.getLogger("filterUsingWildcard1.foo.baz");
    ((ch.qos.logback.classic.Logger) baz1).setAdditive(false);
    org.slf4j.Logger baz2 = LoggerFactory.getLogger("filterUsingWildcard2.foo.baz");
    ((ch.qos.logback.classic.Logger) baz2).setAdditive(false);
    final List<String> msgs = new ArrayList<String>();
    Filter stf = new Filter<ILoggingEvent>() {

        @Override
        public FilterReply decide(ILoggingEvent event) {
            msgs.add(event.getMessage());
            return FilterReply.NEUTRAL;
        }
    };
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("appenders", "*");
    ServiceRegistration sr = bundleContext.registerService(Filter.class.getName(), stf, props);
    delay();
    baz1.info("baz1-1");
    baz2.info("baz2-1");
    assertEquals(2, msgs.size());
}
Also used : Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) MatchingFilter(ch.qos.logback.classic.turbo.MatchingFilter) TurboFilter(ch.qos.logback.classic.turbo.TurboFilter) Filter(ch.qos.logback.core.filter.Filter) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Aggregations

ServiceRegistration (org.osgi.framework.ServiceRegistration)188 Test (org.junit.Test)80 Hashtable (java.util.Hashtable)61 BundleContext (org.osgi.framework.BundleContext)35 Bundle (org.osgi.framework.Bundle)26 Dictionary (java.util.Dictionary)23 Properties (java.util.Properties)22 HashMap (java.util.HashMap)21 ServiceReference (org.osgi.framework.ServiceReference)21 ArrayList (java.util.ArrayList)18 Map (java.util.Map)13 IOException (java.io.IOException)8 ServiceFactory (org.osgi.framework.ServiceFactory)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 URL (java.net.URL)6 HashSet (java.util.HashSet)6 List (java.util.List)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 ObjectName (javax.management.ObjectName)5 InitialContext (javax.naming.InitialContext)5