Search in sources :

Example 81 with ConfigurationException

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

the class RestfulLangidentEngine method activate.

/**
 * Activate and read the properties. Configures and initialises a POSTagger for each language configured in
 * CONFIG_LANGUAGES.
 *
 * @param ce the {@link org.osgi.service.component.ComponentContext}
 */
@Activate
protected void activate(ComponentContext ce) throws ConfigurationException, IOException {
    super.activate(ce);
    log.info("activate {} '{}'", getClass().getSimpleName(), getName());
    @SuppressWarnings("unchecked") Dictionary<String, Object> properties = ce.getProperties();
    Object value = properties.get(ANALYSIS_SERVICE_URL);
    if (value == null) {
        throw new ConfigurationException(ANALYSIS_SERVICE_URL, "The RESTful Language Identification Service URL is missing in the provided configuration!");
    } else {
        try {
            serviceUrl = new URI(value.toString());
            log.info("  ... service: {}", serviceUrl);
        } catch (URISyntaxException e) {
            throw new ConfigurationException(ANALYSIS_SERVICE_URL, "The parsed RESTful Language Identification Service URL '" + value + "'is not a valid URL!", e);
        }
    }
    String usr;
    String pwd;
    value = properties.get(ANALYSIS_SERVICE_USER);
    if (value != null && !value.toString().isEmpty()) {
        usr = value.toString();
        value = properties.get(ANALYSIS_SERVICE_PWD);
        pwd = value == null ? null : value.toString();
    } else {
        // no user set
        usr = null;
        pwd = null;
    }
    // init the http client
    httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Stanbol RESTful Language Identification Engine");
    httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);
    httpParams.setBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, true);
    connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(20);
    connectionManager.setDefaultMaxPerRoute(20);
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    if (usr != null) {
        log.info("  ... setting user to {}", usr);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(usr, pwd));
        // And add request interceptor to have preemptive authentication
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    }
}
Also used : PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) ConfigurationException(org.osgi.service.cm.ConfigurationException) URISyntaxException(java.net.URISyntaxException) BasicHttpParams(org.apache.http.params.BasicHttpParams) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Activate(org.apache.felix.scr.annotations.Activate)

Example 82 with ConfigurationException

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

the class RestfulNlpAnalysisEngine method activate.

/**
 * Activate and read the properties. Configures and initialises a POSTagger for each language configured in
 * CONFIG_LANGUAGES.
 *
 * @param ce the {@link org.osgi.service.component.ComponentContext}
 */
@Activate
protected void activate(ComponentContext ce) throws ConfigurationException, IOException {
    super.activate(ce);
    log.info("activate {} '{}'", getClass().getSimpleName(), getName());
    config = ce.getProperties();
    Object value = config.get(ANALYSIS_SERVICE_URL);
    if (value == null) {
        throw new ConfigurationException(ANALYSIS_SERVICE_URL, "The RESTful Analysis Service URL is missing in the provided configuration!");
    } else {
        try {
            analysisServiceUrl = new URI(value.toString());
            log.info("  ... service: {}", analysisServiceUrl);
        } catch (URISyntaxException e) {
            throw new ConfigurationException(ANALYSIS_SERVICE_URL, "The parsed RESTful Analysis Service URL '" + value + "'is not a valid URL!", e);
        }
    }
    String usr;
    String pwd;
    value = config.get(ANALYSIS_SERVICE_USER);
    if (value != null && !value.toString().isEmpty()) {
        usr = value.toString();
        value = config.get(ANALYSIS_SERVICE_PWD);
        pwd = value == null ? null : value.toString();
    } else {
        // no user set
        usr = null;
        pwd = null;
    }
    // init the http client
    httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Stanbol RESTful NLP Analysis Engine");
    httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);
    httpParams.setBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, true);
    connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(20);
    connectionManager.setDefaultMaxPerRoute(20);
    // NOTE: The list of supported languages is the combination of the
    // languages enabled by the configuration (#languageConfig) and the
    // languages supported by the RESTful NLP Analysis Service
    // (#supportedLanguages)
    // init the language configuration with the engine configuration
    languageConfig.setConfiguration(config);
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    if (usr != null) {
        log.info("  ... setting user to {}", usr);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(usr, pwd));
        // And add request interceptor to have preemptive authentication
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    }
    // STANBOL-1389: deactivated initialization during activation as this can create
    // issues in cases where Stanbol and the NLP service do run in the same
    // servlet container.
    // initRESTfulNlpAnalysisService();
    value = config.get(WRITE_TEXT_ANNOTATIONS_STATE);
    if (value instanceof Boolean) {
        this.writeTextAnnotations = ((Boolean) value).booleanValue();
    } else if (value != null) {
        this.writeTextAnnotations = Boolean.parseBoolean(value.toString());
    } else {
        this.writeTextAnnotations = DEFAULT_WRITE_TEXT_ANNOTATION_STATE;
    }
}
Also used : PoolingClientConnectionManager(org.apache.http.impl.conn.PoolingClientConnectionManager) ConfigurationException(org.osgi.service.cm.ConfigurationException) URISyntaxException(java.net.URISyntaxException) BasicHttpParams(org.apache.http.params.BasicHttpParams) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Activate(org.apache.felix.scr.annotations.Activate)

Example 83 with ConfigurationException

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

the class AbstractChain method activate.

protected void activate(ComponentContext ctx) throws ConfigurationException {
    this.context = ctx;
    Object value = ctx.getProperties().get(PROPERTY_NAME);
    if (value instanceof String) {
        name = (String) value;
        if (name.isEmpty()) {
            name = null;
            throw new ConfigurationException(PROPERTY_NAME, "The configured" + "name of a Chain MUST NOT be empty!");
        }
    } else {
        throw new ConfigurationException(PROPERTY_NAME, value == null ? "The name is a required property!" : "The name of a Chain MUST be an non empty String " + "(type: " + value.getClass() + " value: " + value + ")");
    }
    value = ctx.getProperties().get(PROPERTY_CHAIN_PROPERTIES);
    Collection<String> chainPropsConfig;
    if (value instanceof String[]) {
        chainPropsConfig = Arrays.asList((String[]) value);
    } else if (value instanceof Collection<?>) {
        chainPropsConfig = new ArrayList<String>(((Collection<?>) value).size());
        for (Object o : (Collection<?>) value) {
            if (o != null) {
                chainPropsConfig.add(o.toString());
            }
        }
    } else if (value instanceof String) {
        chainPropsConfig = Collections.singleton((String) value);
    } else if (value != null) {
        throw new ConfigurationException(PROPERTY_CHAIN_PROPERTIES, "Chain level EnhancementProperties can be parsed as String[]," + "Collection<String> or String (single value). The actually " + "parsed type was " + value.getClass().getName());
    } else {
        chainPropsConfig = Collections.emptyList();
    }
    chainProperties = ConfigUtils.getEnhancementProperties(chainPropsConfig);
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) ArrayList(java.util.ArrayList)

Example 84 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException 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 85 with ConfigurationException

use of org.osgi.service.cm.ConfigurationException 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)

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