Search in sources :

Example 16 with ServiceTrackerCustomizer

use of org.osgi.util.tracker.ServiceTrackerCustomizer 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 17 with ServiceTrackerCustomizer

use of org.osgi.util.tracker.ServiceTrackerCustomizer 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)

Example 18 with ServiceTrackerCustomizer

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

the class CacheComponent method activate.

@Activate
protected void activate(final ComponentContext context) throws ConfigurationException, YardException, IllegalStateException, InvalidSyntaxException {
    if (context == null || context.getProperties() == null) {
        throw new IllegalStateException(String.format("Invalid ComponentContext parsed in activate (context=%s)", context));
    }
    this.cc = context;
    Object value = context.getProperties().get(Cache.ADDITIONAL_MAPPINGS);
    if (value instanceof String[]) {
        this.additionalMappings = (String[]) value;
    } else if (value instanceof String) {
        this.additionalMappings = new String[] { (String) value };
    } else if (value instanceof Collection<?>) {
        try {
            additionalMappings = ((Collection<?>) value).toArray(new String[((Collection<?>) value).size()]);
        } catch (ArrayStoreException e) {
            throw new ConfigurationException(Cache.ADDITIONAL_MAPPINGS, "Additional Mappings MUST BE a String, String[] or Collection<String>!", e);
        }
    } else {
        additionalMappings = null;
    }
    String yardId = OsgiUtils.checkProperty(context.getProperties(), Cache.CACHE_YARD).toString();
    String cacheFilter = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, Yard.class.getName(), Yard.ID, yardId);
    yardTracker = new ServiceTracker(context.getBundleContext(), context.getBundleContext().createFilter(cacheFilter), new ServiceTrackerCustomizer() {

        //store the reference to the ComponentContext to avoid NPE if deactivate
        //is called for the CacheComponent
        final ComponentContext cc = context;

        @Override
        public void removedService(ServiceReference reference, Object service) {
            if (service.equals(yard)) {
                yard = (Yard) yardTracker.getService();
                updateServiceRegistration(cc, yard, additionalMappings, nsPrefixService);
            }
            cc.getBundleContext().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
            Yard newYard = (Yard) yardTracker.getService();
            if (newYard == null || !newYard.equals(cache)) {
                //set the new cahce
                yard = newYard;
                //and update the service registration
                updateServiceRegistration(cc, yard, additionalMappings, nsPrefixService);
            }
        }

        @Override
        public Object addingService(ServiceReference reference) {
            Object service = cc.getBundleContext().getService(reference);
            if (service != null) {
                if (//the first added Service or
                yardTracker.getServiceReference() == null || //the new service as higher ranking as the current
                (reference.compareTo(yardTracker.getServiceReference()) > 0)) {
                    yard = (Yard) service;
                    updateServiceRegistration(cc, yard, additionalMappings, nsPrefixService);
                }
            // else the new service has lower ranking as the currently use one
            }
            //else service == null -> ignore
            return service;
        }
    });
    yardTracker.open();
}
Also used : Yard(org.apache.stanbol.entityhub.servicesapi.yard.Yard) ComponentContext(org.osgi.service.component.ComponentContext) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) Collection(java.util.Collection) ServiceReference(org.osgi.framework.ServiceReference) Activate(org.apache.felix.scr.annotations.Activate)

Example 19 with ServiceTrackerCustomizer

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

the class EntityhubLinkingEngine method activate.

@Activate
@SuppressWarnings("unchecked")
protected void activate(ComponentContext ctx) throws ConfigurationException {
    Dictionary<String, Object> properties = ctx.getProperties();
    bundleContext = ctx.getBundleContext();
    EntityLinkerConfig linkerConfig = EntityLinkerConfig.createInstance(properties, prefixService);
    TextProcessingConfig textProcessingConfig = TextProcessingConfig.createInstance(properties);
    Object value = properties.get(SITE_ID);
    //init the EntitySource
    if (value == null) {
        throw new ConfigurationException(SITE_ID, "The ID of the Referenced Site is a required Parameter and MUST NOT be NULL!");
    }
    siteName = value.toString();
    if (siteName.isEmpty()) {
        throw new ConfigurationException(SITE_ID, "The ID of the Referenced Site is a required Parameter and MUST NOT be an empty String!");
    }
    //get the metadata later set to the enhancement engine
    String engineName;
    engineMetadata = new Hashtable<String, Object>();
    value = properties.get(PROPERTY_NAME);
    if (value == null || value.toString().isEmpty()) {
        throw new ConfigurationException(PROPERTY_NAME, "The EnhancementEngine name MUST BE configured!");
    } else {
        engineName = value.toString();
    }
    engineMetadata.put(PROPERTY_NAME, value);
    value = properties.get(Constants.SERVICE_RANKING);
    engineMetadata.put(Constants.SERVICE_RANKING, value == null ? Integer.valueOf(0) : value);
    //init the tracking entity searcher
    trackedServiceCount = 0;
    if (Entityhub.ENTITYHUB_IDS.contains(siteName.toLowerCase())) {
        entitySearcher = new EntityhubSearcher(bundleContext, 10, this);
    } else {
        entitySearcher = new ReferencedSiteSearcher(bundleContext, siteName, 10, this);
    }
    labelTokenizerTracker = new ServiceTracker(bundleContext, LabelTokenizer.class.getName(), new ServiceTrackerCustomizer() {

        @Override
        public Object addingService(ServiceReference reference) {
            Object service = bundleContext.getService(reference);
            if (service == null) {
                return service;
            }
            synchronized (labelTokenizersRefs) {
                labelTokenizersRefs.add(reference);
                ServiceReference higest;
                try {
                    higest = labelTokenizersRefs.last();
                } catch (NoSuchElementException e) {
                    higest = null;
                }
                EntityLinkingEngine engine = entityLinkingEngine;
                ServiceTracker tracker = labelTokenizerTracker;
                if (engine != null && tracker != null) {
                    LabelTokenizer lt = (LabelTokenizer) (reference.equals(higest) || higest == null ? service : tracker.getService(higest));
                    if (!lt.equals(engine.getLabelTokenizer())) {
                        log.info(" ... setting LabelTokenizer of Engine '{}' to {}", engine.getName(), lt);
                        engine.setLabelTokenizer(lt);
                    }
                }
            //if engine or tracker is null deactivate was already called
            }
            return service;
        }

        @Override
        public void removedService(ServiceReference reference, Object service) {
            synchronized (labelTokenizersRefs) {
                //override
                labelTokenizersRefs.remove(reference);
                EntityLinkingEngine engine = entityLinkingEngine;
                ServiceTracker tracker = labelTokenizerTracker;
                if (engine != null && tracker != null) {
                    if (labelTokenizersRefs.isEmpty()) {
                        log.info(" ... setting LabelTokenizer of Engine '{}' to null", engine.getName());
                        engine.setLabelTokenizer(null);
                    } else {
                        LabelTokenizer lt = (LabelTokenizer) tracker.getService(labelTokenizersRefs.last());
                        if (!lt.equals(engine.getLabelTokenizer())) {
                            log.info(" ... setting LabelTokenizer of Engine '{}' to {}", engine.getName(), lt);
                            engine.setLabelTokenizer(lt);
                        }
                    }
                }
            //if engine or tracker is null deactivate was already called
            }
            bundleContext.ungetService(reference);
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
            synchronized (labelTokenizersRefs) {
                //override
                labelTokenizersRefs.remove(reference);
                labelTokenizersRefs.add(reference);
                ServiceReference higest;
                try {
                    higest = labelTokenizersRefs.last();
                } catch (NoSuchElementException e) {
                    higest = null;
                }
                EntityLinkingEngine engine = entityLinkingEngine;
                ServiceTracker tracker = labelTokenizerTracker;
                if (engine != null && tracker != null) {
                    LabelTokenizer lt = (LabelTokenizer) (reference.equals(higest) || higest == null ? service : tracker.getService(higest));
                    if (!lt.equals(engine.getLabelTokenizer())) {
                        log.info(" ... setting LabelTokenizer of Engine '{}' to {}", engine.getName(), lt);
                        engine.setLabelTokenizer(lt);
                    }
                }
            //if engine or tracker is null deactivate was already called
            }
        }
    });
    //create the engine
    entityLinkingEngine = new EntityLinkingEngine(engineName, //the searcher might not be available
    entitySearcher, textProcessingConfig, linkerConfig, null);
    //start tracking
    labelTokenizerTracker.open();
    entitySearcher.open();
}
Also used : EntityLinkerConfig(org.apache.stanbol.enhancer.engines.entitylinking.config.EntityLinkerConfig) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) ServiceReference(org.osgi.framework.ServiceReference) EntityLinkingEngine(org.apache.stanbol.enhancer.engines.entitylinking.engine.EntityLinkingEngine) TextProcessingConfig(org.apache.stanbol.enhancer.engines.entitylinking.config.TextProcessingConfig) ConfigurationException(org.osgi.service.cm.ConfigurationException) LabelTokenizer(org.apache.stanbol.enhancer.engines.entitylinking.LabelTokenizer) NoSuchElementException(java.util.NoSuchElementException) Activate(org.apache.felix.scr.annotations.Activate)

Aggregations

ServiceReference (org.osgi.framework.ServiceReference)19 ServiceTrackerCustomizer (org.osgi.util.tracker.ServiceTrackerCustomizer)19 ServiceTracker (org.osgi.util.tracker.ServiceTracker)10 Activate (org.apache.felix.scr.annotations.Activate)9 ConfigurationException (org.osgi.service.cm.ConfigurationException)6 BundleContext (org.osgi.framework.BundleContext)4 Yard (org.apache.stanbol.entityhub.servicesapi.yard.Yard)3 SortedMap (java.util.SortedMap)2 KeystoreInstance (org.apache.karaf.jaas.config.KeystoreInstance)2 KeystoreManager (org.apache.karaf.jaas.config.KeystoreManager)2 Filter (org.osgi.framework.Filter)2 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)1 Maps.newHashMap (com.google.common.collect.Maps.newHashMap)1 Maps.newTreeMap (com.google.common.collect.Maps.newTreeMap)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Collection (java.util.Collection)1 Collections.emptyList (java.util.Collections.emptyList)1 Collections.singletonList (java.util.Collections.singletonList)1 HashMap (java.util.HashMap)1