Search in sources :

Example 46 with ServiceTracker

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

the class RepoIndexTask method execute.

@Override
public void execute() throws BuildException {
    printCopyright(System.err);
    if (repositoryFile == null)
        throw new BuildException("Output file not specified");
    try {
        // Configure PojoSR
        Map<String, Object> pojoSrConfig = new HashMap<String, Object>();
        pojoSrConfig.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner());
        // Start PojoSR 'framework'
        Framework framework = new PojoServiceRegistryFactoryImpl().newFramework(pojoSrConfig);
        framework.init();
        framework.start();
        if (knownBundles) {
            registerKnownBundles(framework.getBundleContext());
        }
        // Look for indexer and run index generation
        ServiceTracker<ResourceIndexer, ResourceIndexer> tracker = new ServiceTracker<ResourceIndexer, ResourceIndexer>(framework.getBundleContext(), ResourceIndexer.class, null);
        tracker.open();
        ResourceIndexer index = tracker.waitForService(1000);
        if (index == null)
            throw new IllegalStateException("Timed out waiting for ResourceIndexer service.");
        // Flatten the file sets into a single list
        Set<File> fileList = new LinkedHashSet<File>();
        for (FileSet fileSet : fileSets) {
            DirectoryScanner ds = fileSet.getDirectoryScanner(getProject());
            File basedir = ds.getBasedir();
            String[] files = ds.getIncludedFiles();
            for (int i = 0; i < files.length; i++) fileList.add(new File(basedir, files[i]));
        }
        // Run
        try (OutputStream fos = Files.newOutputStream(repositoryFile.toPath())) {
            index.index(fileList, fos, config);
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) FileSet(org.apache.tools.ant.types.FileSet) HashMap(java.util.HashMap) ServiceTracker(org.osgi.util.tracker.ServiceTracker) OutputStream(java.io.OutputStream) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) ClasspathScanner(de.kalpatec.pojosr.framework.launch.ClasspathScanner) PojoServiceRegistryFactoryImpl(de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) Framework(org.osgi.framework.launch.Framework)

Example 47 with ServiceTracker

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

the class Index method main.

/**
	 * Main entry point. See -help for options.
	 * 
	 * @param args Program arguments
	 */
public static void main(String[] args) {
    try {
        // Configure PojoSR
        Map<String, Object> pojoSrConfig = new HashMap<String, Object>();
        pojoSrConfig.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner());
        // Start PojoSR 'framework'
        Framework framework = new PojoServiceRegistryFactoryImpl().newFramework(pojoSrConfig);
        framework.init();
        framework.start();
        // Look for indexer and run index generation
        ServiceTracker<ResourceIndexer, ResourceIndexer> tracker = new ServiceTracker<ResourceIndexer, ResourceIndexer>(framework.getBundleContext(), ResourceIndexer.class, null);
        tracker.open();
        ResourceIndexer index = tracker.waitForService(1000);
        if (index == null)
            throw new IllegalStateException("Timed out waiting for ResourceIndexer service.");
        // Process arguments
        Set<File> fileList = new LinkedHashSet<File>();
        Map<String, String> config = new HashMap<String, String>();
        File outputFile = processArgs(args, System.err, config, fileList, framework.getBundleContext());
        if (outputFile == null) {
            System.exit(1);
        }
        boolean verbose = Boolean.parseBoolean(config.get(ResourceIndexer.VERBOSE));
        if (verbose) {
            printCopyright(System.err);
        }
        try (@SuppressWarnings("null") OutputStream fos = Files.newOutputStream(outputFile.toPath())) {
            index.index(fileList, fos, config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
        System.exit(1);
    }
    // We really need to ensure all non-daemon threads -- which may have
    // been started by a bundle -- are terminated.
    System.exit(0);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) ServiceTracker(org.osgi.util.tracker.ServiceTracker) OutputStream(java.io.OutputStream) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) CmdLineException(org.kohsuke.args4j.CmdLineException) ClasspathScanner(de.kalpatec.pojosr.framework.launch.ClasspathScanner) PojoServiceRegistryFactoryImpl(de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl) File(java.io.File) Framework(org.osgi.framework.launch.Framework)

Example 48 with ServiceTracker

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

the class EntityCoMentionEngine method activate.

@Activate
@SuppressWarnings("unchecked")
protected void activate(ComponentContext ctx) throws ConfigurationException {
    super.activate(ctx);
    log.info("activate {}[name:{}]", getClass().getSimpleName(), getName());
    Dictionary<String, Object> properties = ctx.getProperties();
    //        bundleContext = ctx.getBundleContext();
    //extract TextProcessing and EnityLinking config from the provided properties
    textProcessingConfig = TextProcessingConfig.createInstance(properties);
    linkerConfig = EntityLinkerConfig.createInstance(properties, prefixService);
    //some of the confiugration is predefined
    linkerConfig.setNameField(CoMentionConstants.CO_MENTION_LABEL_FIELD);
    linkerConfig.setTypeField(CoMentionConstants.CO_MENTION_TYPE_FIELD);
    //there should not be more as 5 suggestions
    linkerConfig.setMaxSuggestions(5);
    //a single token is enough
    linkerConfig.setMinFoundTokens(1);
    //1/4 of the tokens
    linkerConfig.setMinLabelScore(0.24);
    //labelScore * token match factor
    linkerConfig.setMinMatchScore(linkerConfig.getMinLabelScore() * linkerConfig.getMinTokenMatchFactor());
    linkerConfig.setRedirectProcessingMode(RedirectProcessingMode.IGNORE);
    //remove all type mappings
    linkerConfig.setDefaultDcType(null);
    Set<IRI> mappedUris = new HashSet<IRI>(linkerConfig.getTypeMappings().keySet());
    for (IRI mappedUri : mappedUris) {
        linkerConfig.setTypeMapping(mappedUri.getUnicodeString(), null);
    }
    //parse confidence adjustment value (STANBOL-1219)
    Object value = properties.get(ADJUST_EXISTING_SUGGESTION_CONFIDENCE);
    final double confidenceAdjustment;
    if (value == null) {
        confidenceAdjustment = DEFAULT_CONFIDENCE_ADJUSTEMENT;
    } else if (value instanceof Number) {
        confidenceAdjustment = ((Number) value).doubleValue();
    } else {
        try {
            confidenceAdjustment = Double.parseDouble(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(ADJUST_EXISTING_SUGGESTION_CONFIDENCE, "The confidence adjustement value for existing suggestions " + "MUST BE a double value in the range [0..1)", e);
        }
    }
    if (confidenceAdjustment < 0 || confidenceAdjustment >= 1) {
        throw new ConfigurationException(ADJUST_EXISTING_SUGGESTION_CONFIDENCE, "The confidence adjustement value for existing suggestions " + "MUST BE a double value in the range [0..1) (parsed: " + confidenceAdjustment + ")!");
    }
    confidenceAdjustmentFactor = 1 - confidenceAdjustment;
    //get the metadata later set to the enhancement engine
    final BundleContext bc = ctx.getBundleContext();
    labelTokenizerTracker = new ServiceTracker(bc, LabelTokenizer.class.getName(), null);
    labelTokenizerTracker.open();
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceTracker(org.osgi.util.tracker.ServiceTracker) HashSet(java.util.HashSet) BundleContext(org.osgi.framework.BundleContext) Activate(org.apache.felix.scr.annotations.Activate)

Example 49 with ServiceTracker

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

the class MainLabelTokenizer method activate.

@Activate
protected void activate(ComponentContext ctx) {
    final BundleContext bundleContext = ctx.getBundleContext();
    final String managerServicePid = (String) ctx.getProperties().get(Constants.SERVICE_PID);
    labelTokenizerTracker = new ServiceTracker(bundleContext, LabelTokenizer.class.getName(), new ServiceTrackerCustomizer() {

        @Override
        public Object addingService(ServiceReference reference) {
            if (managerServicePid.equals(reference.getProperty(Constants.SERVICE_PID))) {
                //do not track this manager!
                return null;
            }
            LanguageConfiguration langConf = new LanguageConfiguration(SUPPORTED_LANUAGES, DEFAULT_LANG_CONF);
            try {
                langConf.setConfiguration(reference);
            } catch (ConfigurationException e) {
                log.error("Unable to track ServiceReference {} becuase of invalid LanguageConfiguration(" + SUPPORTED_LANUAGES + "=" + reference.getProperty(SUPPORTED_LANUAGES) + ")!", e);
                return null;
            }
            Object service = bundleContext.getService(reference);
            if (service != null) {
                ref2LangConfig.put(reference, langConf);
                langTokenizers.clear();
            }
            return service;
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
            if (managerServicePid.equals(reference.getProperty(Constants.SERVICE_PID))) {
                //ignore this service!
                return;
            }
            LanguageConfiguration langConf = new LanguageConfiguration(SUPPORTED_LANUAGES, DEFAULT_LANG_CONF);
            try {
                langConf.setConfiguration(reference);
                ref2LangConfig.put(reference, langConf);
                langTokenizers.clear();
            } catch (ConfigurationException e) {
                log.error("Unable to track ServiceReference {} becuase of invalid LanguageConfiguration(" + SUPPORTED_LANUAGES + "=" + reference.getProperty(SUPPORTED_LANUAGES) + ")!", e);
                if (ref2LangConfig.remove(reference) != null) {
                    langTokenizers.clear();
                }
            }
        }

        @Override
        public void removedService(ServiceReference reference, Object service) {
            if (managerServicePid.equals(reference.getProperty(Constants.SERVICE_PID))) {
                //ignore this service
                return;
            }
            bundleContext.ungetService(reference);
            if (ref2LangConfig.remove(reference) != null) {
                langTokenizers.clear();
            }
        }
    });
    labelTokenizerTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) LanguageConfiguration(org.apache.stanbol.enhancer.nlp.utils.LanguageConfiguration) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference) Activate(org.apache.felix.scr.annotations.Activate)

Example 50 with ServiceTracker

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

the class ManagedSiteComponent method activate.

/**
     * Activates this {@link ManagedSiteComponent}. This might be overridden to
     * perform additional configuration. In such cases super should be called
     * before the additional configuration steps.
     * @param context
     * @throws ConfigurationException
     * @throws YardException
     * @throws InvalidSyntaxException
     */
@Activate
protected void activate(final ComponentContext context) throws ConfigurationException, YardException, InvalidSyntaxException {
    this.bundleContext = context.getBundleContext();
    //NOTE that the constructor also validation of the parsed configuration
    this.siteConfiguration = new ManagedSiteConfigurationImpl(context.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 Managed Site {}", siteConfiguration.getId());
    SiteUtils.extractSiteMetadata(siteConfiguration, InMemoryValueFactory.getInstance());
    //Initialise the Yard
    final String yardId = siteConfiguration.getYardId();
    String yardFilterString = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, Yard.class.getName(), Yard.ID, yardId);
    Filter yardFilter = bundleContext.createFilter(yardFilterString);
    yardTracker = new ServiceTracker(bundleContext, yardFilter, new ServiceTrackerCustomizer() {

        @Override
        public void removedService(ServiceReference reference, Object service) {
            synchronized (yardReferenceLock) {
                if (reference.equals(yardReference)) {
                    deactivateManagedSite();
                    yardReference = null;
                }
                bundleContext.ungetService(reference);
            }
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
        }

        @Override
        public Object addingService(ServiceReference reference) {
            Yard yard = (Yard) bundleContext.getService(reference);
            synchronized (yardReferenceLock) {
                if (yardReference == null) {
                    if (yard != null) {
                        activateManagedSite(yard);
                        yardReference = reference;
                    } else {
                        log.warn("Unable to addService for ServiceReference because" + "unable to obtain referenced Yard via the BundleContext!");
                    }
                } else {
                    log.warn("Tracking two Yard instances with the Yard ID '{}' " + "configured for ManagedSite '{}'", yardId, siteConfiguration.getId());
                    log.warn("used  : {}", yardReference.getProperty(Constants.SERVICE_PID));
                    log.warn("unused: {}", reference.getProperty(Constants.SERVICE_PID));
                }
            }
            return yard;
        }
    });
    yardTracker.open();
//will be moved to a Solr specific implementation
//        //chaeck if we are allowed to init an yard with the provided id
//        boolean allowInit = false;
//        if(configAdmin!= null){
//            Configuration[] configs;
//            try {
//                String yardIdFilter = String.format("(%s=%s)",
//                    Yard.ID,yardId);
//                configs = configAdmin.listConfigurations(yardIdFilter);
//                if(configs == null || configs.length < 1){
//                    allowInit = true;
//                }
//            } catch (IOException e) {
//                log.warn("Unable to access ManagedService configurations ",e);
//            }
//        } else if (yardTracker.getService() == null){
//            log.warn("Unable to check for Yard configuration of ManagedSite {} "
//                + "Because the ConfigurationAdmin service is not available");
//            log.warn(" -> unable to create YardConfiguration");
//        }
//        if(allowInit){
//            //TODO: This has SolrYard specific code - this needs to be refactored
//            String factoryPid = "org.apache.stanbol.entityhub.yard.solr.impl.SolrYard";
//            try {
//                Configuration config = configAdmin.createFactoryConfiguration(factoryPid,null);
//                //configure the required properties
//                Dictionary<String,Object> yardConfig = new Hashtable<String,Object>();
//                yardConfig.put(Yard.ID, siteConfiguration.getYardId());
//                yardConfig.put(Yard.NAME, siteConfiguration.getYardId());
//                yardConfig.put(Yard.DESCRIPTION, "Yard for the ManagedSite "+siteConfiguration.getId());
//                yardConfig.put("org.apache.stanbol.entityhub.yard.solr.solrUri", siteConfiguration.getId());
//                yardConfig.put("org.apache.stanbol.entityhub.yard.solr.useDefaultConfig", true);
//                config.update(yardConfig); //this create the solrYard
//            } catch (IOException e) {
//                log.warn("Unable to create SolrYard configuration for MnagedSite "+siteConfiguration.getId(),e);
//            }
//        }
}
Also used : Yard(org.apache.stanbol.entityhub.servicesapi.yard.Yard) ConfigurationException(org.osgi.service.cm.ConfigurationException) Filter(org.osgi.framework.Filter) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) ServiceReference(org.osgi.framework.ServiceReference) Activate(org.apache.felix.scr.annotations.Activate)

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