Search in sources :

Example 76 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project stanbol by apache.

the class CeliLemmatizerEnhancementEngine method activate.

@Override
@Activate
protected void activate(ComponentContext ctx) throws IOException, ConfigurationException {
    super.activate(ctx);
    Dictionary<String, Object> properties = ctx.getProperties();
    this.licenseKey = Utils.getLicenseKey(properties, ctx.getBundleContext());
    String url = (String) properties.get(SERVICE_URL);
    if (url == null || url.isEmpty()) {
        throw new ConfigurationException(SERVICE_URL, String.format("%s : please configure the URL of the CELI Web Service (e.g. by" + "using the 'Configuration' tab of the Apache Felix Web Console).", getClass().getSimpleName()));
    }
    this.serviceURL = new URL(url);
    try {
        this.completeMorphoAnalysis = (Boolean) properties.get(MORPHOLOGICAL_ANALYSIS);
    } catch (Exception e) {
        this.completeMorphoAnalysis = false;
    }
    int conTimeout = Utils.getConnectionTimeout(properties, ctx.getBundleContext());
    this.client = new LemmatizerClientHTTP(this.serviceURL, this.licenseKey, conTimeout);
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) URL(java.net.URL) EngineException(org.apache.stanbol.enhancer.servicesapi.EngineException) SOAPException(javax.xml.soap.SOAPException) ConfigurationException(org.osgi.service.cm.ConfigurationException) InvalidContentException(org.apache.stanbol.enhancer.servicesapi.InvalidContentException) IOException(java.io.IOException) Activate(org.apache.felix.scr.annotations.Activate)

Example 77 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project stanbol by apache.

the class EntityhubDereferenceEngine method activate.

@Activate
@SuppressWarnings("unchecked")
protected void activate(ComponentContext ctx) throws ConfigurationException {
    Dictionary<String, Object> properties = ctx.getProperties();
    bundleContext = ctx.getBundleContext();
    log.info("> activate {}", getClass().getSimpleName());
    // get the metadata later set to the enhancement engine
    DereferenceEngineConfig engineConfig = new DereferenceEngineConfig(properties, prefixService);
    log.debug(" - engineName: {}", engineConfig.getEngineName());
    // parse the Entityhub Site used for dereferencing
    Object value = properties.get(SITE_ID);
    // init the EntitySource
    if (value == null) {
        // all referenced sites
        siteName = "*";
    } else {
        siteName = value.toString();
    }
    if (siteName.isEmpty()) {
        siteName = "*";
    }
    log.debug(" - siteName: {}", siteName);
    final boolean sharedPoolState;
    value = properties.get(SHARED_THREAD_POOL_STATE);
    if (value instanceof Boolean) {
        sharedPoolState = ((Boolean) value).booleanValue();
    } else if (value != null && !StringUtils.isBlank(value.toString())) {
        sharedPoolState = Boolean.parseBoolean(value.toString());
    } else {
        sharedPoolState = DEFAULT_SHARED_THREAD_POOL_STATE;
    }
    final ExecutorServiceProvider esProvider;
    log.debug(" - shared thread pool state: {}", sharedPoolState);
    if (sharedPoolState) {
        esProvider = new SharedExecutorServiceProvider(ctx.getBundleContext());
    } else {
        // we need to create our own ExecutorService
        value = properties.get(THREAD_POOL_SIZE);
        if (value instanceof Number) {
            this.threadPoolSize = ((Number) value).intValue();
        } else if (value != null) {
            try {
                this.threadPoolSize = Integer.parseInt(value.toString());
            } catch (NumberFormatException e) {
                throw new ConfigurationException(THREAD_POOL_SIZE, "Value '" + value + "'(type: " + value.getClass().getName() + ") can not be parsed " + "as Integer");
            }
        } else {
            this.threadPoolSize = DEFAULT_THREAD_POOL_SIZE;
        }
        if (threadPoolSize > 0) {
            String namePattern = getClass().getSimpleName() + "-" + engineConfig.getEngineName() + "-thread-%s";
            ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(namePattern).setDaemon(true).build();
            log.debug(" - create Threadpool(namePattern='{}' | size='{}')", namePattern, threadPoolSize);
            executorService = Executors.newFixedThreadPool(threadPoolSize, threadFactory);
        } else {
            log.debug(" - no thread pool configured (poolSize: {})", threadPoolSize);
            executorService = null;
        }
        esProvider = new StaticExecutorServiceProvider(executorService);
    }
    // init the tracking entity searcher
    trackedServiceCount = 0;
    if (Entityhub.ENTITYHUB_IDS.contains(siteName.toLowerCase())) {
        log.info("  ... init Entityhub dereferencer");
        entityDereferencer = new EntityhubDereferencer(bundleContext, this, esProvider);
    } else if (siteName.equals("*")) {
        log.info("  ... init dereferencer for all referenced sites");
        entityDereferencer = new SitesDereferencer(bundleContext, this, esProvider);
    } else {
        log.info(" ... init dereferencer for referenced site {}", siteName);
        entityDereferencer = new SiteDereferencer(bundleContext, siteName, this, esProvider);
    }
    // set the namespace prefix service to the dereferencer
    entityDereferencer.setNsPrefixService(prefixService);
    // now parse dereference field config
    entityDereferencer.setDereferencedFields(engineConfig.getDereferenceFields());
    entityDereferencer.setLdPath(engineConfig.getLdPathProgram());
    entityDereferenceEngine = new EntityDereferenceEngine(entityDereferencer, engineConfig, new // we want to use our own DereferenceContext impl
    DereferenceContextFactory() {

        @Override
        public DereferenceContext createContext(EntityDereferenceEngine engine, Map<String, Object> enhancementProperties) throws DereferenceConfigurationException {
            return new EntityhubDereferenceContext(engine, enhancementProperties);
        }
    });
    // NOTE: registration of this instance as OSGI service is done as soon as the
    // entityhub service backing the entityDereferencer is available.
    // finally start tracking
    entityDereferencer.open();
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) DereferenceContextFactory(org.apache.stanbol.enhancer.engines.dereference.DereferenceContextFactory) DereferenceEngineConfig(org.apache.stanbol.enhancer.engines.dereference.DereferenceEngineConfig) SharedExecutorServiceProvider(org.apache.stanbol.enhancer.engines.dereference.entityhub.shared.SharedExecutorServiceProvider) EntityDereferenceEngine(org.apache.stanbol.enhancer.engines.dereference.EntityDereferenceEngine) SharedExecutorServiceProvider(org.apache.stanbol.enhancer.engines.dereference.entityhub.shared.SharedExecutorServiceProvider) ConfigurationException(org.osgi.service.cm.ConfigurationException) DereferenceConfigurationException(org.apache.stanbol.enhancer.engines.dereference.DereferenceConfigurationException) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Map(java.util.Map) Activate(org.apache.felix.scr.annotations.Activate)

Example 78 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project stanbol by apache.

the class TrackingDereferencerBase method setLdPath.

/**
 * Setter for the LDPath program used for dereferencing Entities
 * @param ldpathProgramStr the LDPath program as String
 * @throws ConfigurationException if parsing the LDPath program fails
 */
public void setLdPath(String ldpathProgramStr) throws ConfigurationException {
    if (ldpathProgramStr == null || StringUtils.isBlank(ldpathProgramStr)) {
        ldpathProgram = null;
    } else {
        // validate the parsed LDPath program
        // when this method is called the real RDFBackend will not be available.
        // however we would like to parse/validate the parsed LDPath program
        // So we will create a pseudo RDFBackend sufficient to be used with the
        // parser
        final RDFBackend<Object> parseBackend = new ParseBackend<T>(valueFactory);
        // NOTE: calling execute(..) an this parseLdPath or even the
        // ldpathProgram will result in UnsupportedOperationException
        // but parsing is OK
        EntityhubLDPath parseLdPath = new EntityhubLDPath(parseBackend, valueFactory);
        try {
            ldpathProgram = parseLdPath.parseProgram(new StringReader(ldpathProgramStr));
        } catch (LDPathParseException e) {
            log.error("Unable to parse LDPath pogram: \n {}", ldpathProgramStr);
            throw new ConfigurationException(DereferenceConstants.DEREFERENCE_ENTITIES_LDPATH, "Unable to parse configured LDPath program ", e);
        }
        // finally validate if all mappings of the programm do use a URI as key
        for (org.apache.marmotta.ldpath.model.fields.FieldMapping<?, Object> mapping : ldpathProgram.getFields()) {
            try {
                new URI(mapping.getFieldName());
            } catch (URISyntaxException e) {
                throw new ConfigurationException(DereferenceConstants.DEREFERENCE_ENTITIES_LDPATH, "Parsed LDPath MUST use valid URIs as field names (invalid field name: '" + mapping.getFieldName() + "' | selector: '" + mapping.getSelector().getPathExpression(parseBackend) + "')!");
            }
        }
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ConfigurationException(org.osgi.service.cm.ConfigurationException) StringReader(java.io.StringReader) LDPathParseException(org.apache.marmotta.ldpath.exception.LDPathParseException) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)

Example 79 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project stanbol by apache.

the class CeliClassificationEnhancementEngine method activate.

@Override
@Activate
protected void activate(ComponentContext ctx) throws IOException, ConfigurationException {
    super.activate(ctx);
    @SuppressWarnings("unchecked") Dictionary<String, Object> properties = ctx.getProperties();
    this.licenseKey = Utils.getLicenseKey(properties, ctx.getBundleContext());
    String url = (String) properties.get(SERVICE_URL);
    if (url == null || url.isEmpty()) {
        throw new ConfigurationException(SERVICE_URL, String.format("%s : please configure the URL of the CELI Web Service (e.g. by" + "using the 'Configuration' tab of the Apache Felix Web Console).", getClass().getSimpleName()));
    }
    this.serviceURL = new URL(url);
    int conTimeout = Utils.getConnectionTimeout(properties, ctx.getBundleContext());
    this.client = new ClassificationClientHTTP(this.serviceURL, this.licenseKey, conTimeout);
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) URL(java.net.URL) Activate(org.apache.felix.scr.annotations.Activate)

Example 80 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException in project stanbol by apache.

the class CustomNERModelEnhancementEngine method activate.

protected void activate(ComponentContext ctx) throws IOException, ConfigurationException {
    super.activate(ctx);
    config = new NEREngineConfig();
    // this engine does not use default models
    config.getDefaultModelTypes().clear();
    Object value = ctx.getProperties().get(NAMED_ENTITY_TYPE_MAPPINGS);
    if (value instanceof String[]) {
        // support array
        value = Arrays.asList((String[]) value);
    } else if (value instanceof String) {
        // single value
        value = Collections.singleton(value);
    }
    if (value instanceof Collection<?>) {
        // and collection
        log.info("Init Named Entity Type Mappings");
        configs: for (Object o : (Iterable<?>) value) {
            if (o != null) {
                StringBuilder usage = new StringBuilder("useage: ");
                usage.append("'{namedEntityType} > {dc-type-uri}'");
                String[] config = o.toString().split(">");
                String namedEntityType = config[0].trim();
                if (namedEntityType.isEmpty()) {
                    log.warn("Invalid Type Mapping Config '{}': Missing namedEntityType ({}) -> ignore this config", o, usage);
                    continue configs;
                }
                if (config.length < 2 || config[1].isEmpty()) {
                    log.warn("Invalid Type Mapping Config '{}': Missing dc:type URI '{}' ({}) -> ignore this config", o, usage);
                    continue configs;
                }
                String dcTypeUri = config[1].trim();
                if (config.length > 2) {
                    log.warn("Configuration after 2nd '>' gets ignored. Will use mapping '{} > {}' from config {}", new Object[] { namedEntityType, dcTypeUri, o });
                }
                // TODO support short names (ns:localName)
                try {
                    // validate
                    new URI(dcTypeUri);
                } catch (URISyntaxException e) {
                    log.warn("Invalid URI '{}' in Type Mapping Config '{}' -> ignore this config", dcTypeUri, o);
                    continue configs;
                }
                this.config.setMappedType(namedEntityType, new IRI(dcTypeUri));
                log.info("  add mapping {} > {}", namedEntityType, dcTypeUri);
            }
        }
    } else {
        log.debug("No Type mappings configured");
    }
    value = ctx.getProperties().get(NAME_FINDER_MODELS);
    Set<String> nameFinderModelNames = new HashSet<String>();
    if (value instanceof String[]) {
        nameFinderModelNames.addAll(Arrays.asList((String[]) value));
        // remove null
        nameFinderModelNames.remove(null);
        // remove empty
        nameFinderModelNames.remove("");
    } else if (value instanceof Collection<?>) {
        for (Object o : ((Collection<?>) value)) {
            if (o != null) {
                nameFinderModelNames.add(o.toString());
            }
        }
        // remove empty
        nameFinderModelNames.remove("");
    } else if (value != null && !value.toString().isEmpty()) {
        // if a single String is parsed we support ',' as seperator
        String[] languageArray = value.toString().split(",");
        nameFinderModelNames.addAll(Arrays.asList(languageArray));
        // remove null
        nameFinderModelNames.remove(null);
        // remove empty
        nameFinderModelNames.remove("");
    } else {
        // no configuration
        throw new ConfigurationException(NAME_FINDER_MODELS, "Configurations for the " + getClass().getSimpleName() + " MUST HAVE at least a single custom " + "OpenNLP NameFinder model configured! Supported are comma separated " + "Strings, Arrays and Collections. Values are the file names of the " + "Modles. Models are Loaded via the Apache Stanbol DataFileProvider " + "Infrastructure (usually user wants to copy modles in the 'datafile' " + "directory under the {stanbol.home} directory - {working.dir}/stanbol" + "/datafiles).");
    }
    // register the configured models with the DataFileTracker
    modelFileListener = new NamedModelFileListener();
    Map<String, String> modelProperties = new HashMap<String, String>();
    modelProperties.put("Description", String.format("Statistical NameFinder (NER) model for OpenNLP as configured " + "for the %s (name: %s)", getClass().getSimpleName(), getName()));
    modelProperties.put("Model Type", TokenNameFinderModel.class.getSimpleName());
    log.info(" - register DataFileTracker for {}", nameFinderModelNames);
    for (String modelName : nameFinderModelNames) {
        dataFileTracker.add(modelFileListener, modelName, modelProperties);
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) TokenNameFinderModel(opennlp.tools.namefind.TokenNameFinderModel) HashMap(java.util.HashMap) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ConfigurationException(org.osgi.service.cm.ConfigurationException) Collection(java.util.Collection) HashSet(java.util.HashSet)

Aggregations

ConfigurationException (org.osgi.service.cm.ConfigurationException)190 Activate (org.apache.felix.scr.annotations.Activate)31 ServiceReference (org.osgi.framework.ServiceReference)30 Matcher (java.util.regex.Matcher)28 Hashtable (java.util.Hashtable)26 Properties (java.util.Properties)22 IOException (java.io.IOException)21 Test (org.junit.Test)21 ManagedService (org.osgi.service.cm.ManagedService)20 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)19 HashMap (java.util.HashMap)17 File (java.io.File)11 URISyntaxException (java.net.URISyntaxException)11 Collection (java.util.Collection)11 HashSet (java.util.HashSet)11 ServiceTracker (org.osgi.util.tracker.ServiceTracker)10 URI (java.net.URI)9 Dictionary (java.util.Dictionary)9 Map (java.util.Map)9 NotFoundException (org.opencastproject.util.NotFoundException)9