Search in sources :

Example 86 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project sling by apache.

the class ConfigInstallTest method testDeferredConfigRemove.

@Test
public void testDeferredConfigRemove() throws Exception {
    final AtomicInteger transformerCount = new AtomicInteger();
    final ServiceTracker<ResourceTransformer, ResourceTransformer> st = new ServiceTracker<ResourceTransformer, ResourceTransformer>(bundleContext, ResourceTransformer.class, new ServiceTrackerCustomizer<ResourceTransformer, ResourceTransformer>() {

        @Override
        public void removedService(ServiceReference<ResourceTransformer> reference, ResourceTransformer service) {
            bundleContext.ungetService(reference);
            transformerCount.decrementAndGet();
        }

        @Override
        public void modifiedService(ServiceReference<ResourceTransformer> reference, ResourceTransformer service) {
        }

        @Override
        public ResourceTransformer addingService(ServiceReference<ResourceTransformer> reference) {
            transformerCount.incrementAndGet();
            return bundleContext.getService(reference);
        }
    });
    st.open();
    final AtomicInteger expectedCount = new AtomicInteger();
    final Condition cond = new Condition() {

        @Override
        boolean isTrue() throws Exception {
            return transformerCount.get() == expectedCount.get();
        }

        @Override
        String additionalInfo() {
            return "Resource transformer count is " + String.valueOf(transformerCount.get()) + ", should be " + String.valueOf(expectedCount.get());
        }
    };
    // get config admin bundle and wait for service
    final Bundle configAdmin = this.getConfigAdminBundle();
    assertNotNull("ConfigAdmin bundle must be found", configAdmin);
    waitForConfigAdmin(true);
    // when everything is up and running, we have two factories
    expectedCount.set(2);
    waitForCondition(null, cond);
    // check that configuration is not available
    final String cfgPid = getClass().getSimpleName() + ".deferred." + uniqueID();
    assertNull("Config " + cfgPid + " must not be found before test", findConfiguration(cfgPid));
    // create and install new configuration object, verify
    final Dictionary<String, Object> cfgData = new Hashtable<String, Object>();
    cfgData.put("foo", "bar");
    final InstallableResource[] rsrc = getInstallableResource(cfgPid, cfgData);
    installer.updateResources(URL_SCHEME, rsrc, null);
    waitForConfiguration("Config must be installed before stopping ConfigurationAdmin", cfgPid, true);
    this.waitForResource(URL_SCHEME + ":" + rsrc[0].getId(), ResourceState.INSTALLED);
    // Configuration uninstalls must be deferred if ConfigAdmin service is stopped
    configAdmin.stop();
    waitForConfigAdmin(false);
    // only bundle transformer
    expectedCount.set(1);
    waitForCondition(null, cond);
    // remove configuration
    installationEvents = 0;
    installer.updateResources(URL_SCHEME, null, new String[] { rsrc[0].getId() });
    waitForInstallationEvents(2);
    this.waitForResource(URL_SCHEME + ":" + rsrc[0].getId(), ResourceState.UNINSTALL);
    configAdmin.start();
    waitForConfigAdmin(true);
    // when everything is up and running, we have two transformers again
    expectedCount.set(2);
    waitForCondition(null, cond);
    waitForConfiguration("Config must be removed once ConfigurationAdmin restarts", cfgPid, false);
    st.close();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) InstallableResource(org.apache.sling.installer.api.InstallableResource) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResourceTransformer(org.apache.sling.installer.api.tasks.ResourceTransformer) Test(org.junit.Test)

Example 87 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project sling by apache.

the class RendererSelectorImpl method activate.

protected void activate(ComponentContext ctx) throws ServletException, NamespaceException {
    bundleContext = ctx.getBundleContext();
    renderersTracker = new ServiceTracker(ctx.getBundleContext(), Renderer.class.getName(), null);
    renderersTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker)

Example 88 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project stanbol by apache.

the class StanbolNamespacePrefixService method openTracker.

/**
     * 
     */
private void openTracker() {
    providersTracker = new ServiceTracker(bundleContext, NamespacePrefixProvider.class.getName(), new ServiceTrackerCustomizer() {

        @Override
        public void removedService(ServiceReference reference, Object service) {
            bundleContext.ungetService(reference);
            __sortedProviderRef = null;
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
            __sortedProviderRef = null;
        }

        @Override
        public Object addingService(ServiceReference reference) {
            Object service = bundleContext.getService(reference);
            if (StanbolNamespacePrefixService.this.equals(service)) {
                //we need not to track this instance
                bundleContext.ungetService(reference);
                return null;
            }
            __sortedProviderRef = null;
            return service;
        }
    });
    providersTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) ServiceReference(org.osgi.framework.ServiceReference)

Example 89 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project stanbol by apache.

the class Activator method start.

@Override
public void start(BundleContext context) throws Exception {
    bundleContext = context;
    //Note that this class implements ServiceTrackerCustomizer to init/stop
    // the BundleInstaller
    installerTracker = new ServiceTracker(context, OsgiInstaller.class.getName(), this);
    installerTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker)

Example 90 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project stanbol by apache.

the class ReferencedSiteComponent method activate.

@SuppressWarnings("unchecked")
@Activate
protected void activate(final ComponentContext ctx) throws ConfigurationException, YardException, InvalidSyntaxException {
    log.debug("in {} activate with properties {}", ReferencedSiteImpl.class.getSimpleName(), ctx.getProperties());
    if (ctx == null || ctx.getProperties() == null) {
        throw new IllegalStateException("No Component Context and/or Dictionary properties object parsed to the acticate methode");
    }
    this.cc = ctx;
    this.bc = ctx.getBundleContext();
    // create the SiteConfiguration based on the parsed properties
    // NOTE that the constructor also validation of the parsed configuration
    siteConfiguration = new ReferencedSiteConfigurationImpl(ctx.getProperties());
    if (PROHIBITED_SITE_IDS.contains(siteConfiguration.getId().toLowerCase())) {
        throw new ConfigurationException(SiteConfiguration.ID, String.format("The ID '%s' of this Referenced Site is one of the following " + "prohibited IDs: {} (case insensitive)", siteConfiguration.getId(), PROHIBITED_SITE_IDS));
    }
    log.info(" > initialise Referenced Site {}", siteConfiguration.getName());
    // if the accessUri is the same as the queryUri and both the
    // dereferencer and the entitySearcher uses the same component, than we 
    //need only one component for both dependencies.
    this.dereferencerEqualsEntitySearcherComponent = // (1) accessURI == queryURI
    siteConfiguration.getAccessUri() != null && siteConfiguration.getAccessUri().equals(siteConfiguration.getQueryUri()) && // (2) entity dereferencer == entity searcher
    siteConfiguration.getEntityDereferencerType() != null && siteConfiguration.getEntityDereferencerType().equals(siteConfiguration.getEntitySearcherType());
    // init the fieldMapper based on the configuration
    FieldMapper fieldMappings = new DefaultFieldMapperImpl(ValueConverterFactory.getDefaultInstance());
    if (siteConfiguration.getFieldMappings() != null) {
        log.debug(" > Initialise configured field mappings");
        for (String configuredMapping : siteConfiguration.getFieldMappings()) {
            FieldMapping mapping = FieldMappingUtils.parseFieldMapping(configuredMapping, nsPrefixService);
            if (mapping != null) {
                log.debug("   - add FieldMapping {}", mapping);
                fieldMappings.addMapping(mapping);
            }
        }
    }
    // now init the referenced Services
    initDereferencerAndEntitySearcher();
    // Reference to the cache!
    if (siteConfiguration.getCacheId() != null) {
        String cacheFilter = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, Cache.class.getName(), Cache.CACHE_YARD, siteConfiguration.getCacheId());
        cacheTracker = new ServiceTracker(ctx.getBundleContext(), ctx.getBundleContext().createFilter(cacheFilter), new ServiceTrackerCustomizer() {

            @Override
            public void removedService(ServiceReference reference, Object service) {
                if (service.equals(cache)) {
                    cache = (Cache) cacheTracker.getService();
                    updateServiceRegistration(bc, siteConfiguration, dereferencerComponentInstance, entitySearcherComponentInstance, cache, nsPrefixService, offlineMode);
                }
                bc.ungetService(reference);
            }

            @Override
            public void modifiedService(ServiceReference reference, Object service) {
                //the service.ranking might have changed ... so check if the
                //top ranked Cache is a different one
                Cache newCache = (Cache) cacheTracker.getService();
                if (newCache == null || !newCache.equals(cache)) {
                    //set the new cahce
                    cache = newCache;
                    //and update the service registration
                    updateServiceRegistration(bc, siteConfiguration, dereferencerComponentInstance, entitySearcherComponentInstance, cache, nsPrefixService, offlineMode);
                }
            }

            @Override
            public Object addingService(ServiceReference reference) {
                Object service = bc.getService(reference);
                if (service != null) {
                    if (//the first added Service or
                    cacheTracker.getServiceReference() == null || //the new service as higher ranking as the current
                    (reference.compareTo(cacheTracker.getServiceReference()) > 0)) {
                        cache = (Cache) service;
                        updateServiceRegistration(bc, siteConfiguration, dereferencerComponentInstance, entitySearcherComponentInstance, cache, nsPrefixService, offlineMode);
                    }
                // else the new service has lower ranking as the currently use one
                }
                //else service == null -> ignore
                return service;
            }
        });
        cacheTracker.open();
    }
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) FieldMapping(org.apache.stanbol.entityhub.servicesapi.mapping.FieldMapping) ServiceReference(org.osgi.framework.ServiceReference) ReferencedSiteConfigurationImpl(org.apache.stanbol.entityhub.core.site.ReferencedSiteConfigurationImpl) ConfigurationException(org.osgi.service.cm.ConfigurationException) DefaultFieldMapperImpl(org.apache.stanbol.entityhub.core.mapping.DefaultFieldMapperImpl) FieldMapper(org.apache.stanbol.entityhub.servicesapi.mapping.FieldMapper) Cache(org.apache.stanbol.entityhub.servicesapi.yard.Cache) Activate(org.apache.felix.scr.annotations.Activate)

Aggregations

ServiceTracker (org.osgi.util.tracker.ServiceTracker)96 ServiceReference (org.osgi.framework.ServiceReference)32 Filter (org.osgi.framework.Filter)27 Activate (org.apache.felix.scr.annotations.Activate)18 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)14 Hashtable (java.util.Hashtable)12 BundleContext (org.osgi.framework.BundleContext)11 ConfigurationException (org.osgi.service.cm.ConfigurationException)10 ServiceTrackerCustomizer (org.osgi.util.tracker.ServiceTrackerCustomizer)10 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 Bundle (org.osgi.framework.Bundle)7 Dictionary (java.util.Dictionary)6 Converter (net.heartsome.cat.converter.Converter)6 AndFilter (net.heartsome.cat.converter.util.AndFilter)6 EqFilter (net.heartsome.cat.converter.util.EqFilter)6 Configuration (org.osgi.service.cm.Configuration)6 IOException (java.io.IOException)5 HashMap (java.util.HashMap)5 CdiContainer (org.osgi.service.cdi.CdiContainer)4