Search in sources :

Example 96 with ServiceTracker

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

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

the class TikaActivator method start.

//-----------------------------------------------------< BundleActivator >
public void start(final BundleContext context) throws Exception {
    bundleContext = context;
    detectorTracker = new ServiceTracker(context, Detector.class.getName(), this);
    parserTracker = new ServiceTracker(context, Parser.class.getName(), this);
    detectorTracker.open();
    parserTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker)

Example 98 with ServiceTracker

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

Example 99 with ServiceTracker

use of org.osgi.util.tracker.ServiceTracker in project bnd by bndtools.

the class OSGiTestCase method withService.

/**
	 * <p>
	 * Perform the specified operation against a service, if available.
	 * </p>
	 * <p>
	 * <strong>Example:</strong>
	 * </p>
	 * 
	 * <pre>
	 * String reply = withService(HelloService.class, null, 0, new Operation&lt;HelloService,String&gt;() {
	 * 	public String call(HelloService service) {
	 * 		return service.sayHello();
	 * 	}
	 * });
	 * </pre>
	 * 
	 * @param <S> The service type.
	 * @param <R> The result type.
	 * @param service The service class.
	 * @param filter An additional filter expression, or {@code
	 * null}.
	 * @param timeout The maximum time to wait (in ms) for a service to become
	 *            available; a zero or negative timeout implies we should fail
	 *            if the service is not immediatelt available.
	 * @param operation The operation to perform against the service.
	 * @throws Exception
	 */
protected <S, R> R withService(Class<S> service, String filter, long timeout, Operation<? super S, R> operation) throws Exception {
    BundleContext context = getBundleContext();
    ServiceTracker tracker = null;
    if (filter != null) {
        try {
            Filter combined = FrameworkUtil.createFilter("(" + Constants.OBJECTCLASS + "=" + service.getName() + ")");
            tracker = new ServiceTracker(context, combined, null);
        } catch (InvalidSyntaxException e) {
            fail("Invalid filter syntax.");
            return null;
        }
    } else {
        tracker = new ServiceTracker(context, service.getName(), null);
    }
    try {
        tracker.open();
        Object instance;
        if (timeout <= 0) {
            instance = tracker.getService();
        } else {
            instance = tracker.waitForService(timeout);
        }
        if (instance == null || !service.isInstance(instance))
            fail(MessageFormat.format("Service \"{0}\" not available.", service.getName()));
        @SuppressWarnings("unchecked") S casted = (S) instance;
        return operation.perform(casted);
    } catch (InterruptedException e) {
        fail("Interrupted.");
    } finally {
        tracker.close();
    }
    // unreachable
    return null;
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext)

Example 100 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)

Aggregations

ServiceTracker (org.osgi.util.tracker.ServiceTracker)115 ServiceReference (org.osgi.framework.ServiceReference)33 Filter (org.osgi.framework.Filter)28 ServiceTrackerCustomizer (org.osgi.util.tracker.ServiceTrackerCustomizer)19 Hashtable (java.util.Hashtable)18 Activate (org.apache.felix.scr.annotations.Activate)18 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)14 BundleContext (org.osgi.framework.BundleContext)12 ConfigurationException (org.osgi.service.cm.ConfigurationException)10 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 IOException (java.io.IOException)7 Dictionary (java.util.Dictionary)7 Bundle (org.osgi.framework.Bundle)7 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 HashMap (java.util.HashMap)5 CdiContainer (org.osgi.service.cdi.CdiContainer)4