Search in sources :

Example 81 with Activate

use of org.apache.felix.scr.annotations.Activate in project stanbol by apache.

the class GraphChain method activate.

@Activate
@Override
protected void activate(ComponentContext ctx) throws ConfigurationException {
    super.activate(ctx);
    Object resource = ctx.getProperties().get(PROPERTY_GRAPH_RESOURCE);
    Object list = ctx.getProperties().get(PROPERTY_CHAIN_LIST);
    if (resource != null && !resource.toString().isEmpty()) {
        String[] config = resource.toString().split(";");
        String resourceName = config[0];
        String format = getValue(getParameters(config, 1), "format");
        if (format == null) {
            format = guessRdfFormat(getExtension(resourceName));
        } else if (format.isEmpty()) {
            throw new ConfigurationException(PROPERTY_GRAPH_RESOURCE, "The configured value for the 'format' parameter MUST NOT be" + "empty (configured: '" + resource + "')!");
        }
        if (format == null) {
            throw new ConfigurationException(PROPERTY_GRAPH_RESOURCE, "RDF formant for extension '" + getExtension(resourceName) + "' is not known. Please use the 'format' parameter to specify" + "it manually (configured: '" + resource + "')!");
        }
        ExecutionPlanListerner epl = new ExecutionPlanListerner(resourceName, format);
        if (tracker != null) {
            tracker.add(epl, resourceName, null);
        }
        internalChain = epl;
        mode = MODE.RESOURCE;
    } else if (list != null) {
        Set<String> configuredChain = new HashSet<String>();
        if (list instanceof String[]) {
            configuredChain.addAll(Arrays.asList((String[]) list));
        } else if (list instanceof Collection<?>) {
            for (Object o : (Collection<?>) list) {
                if (o instanceof String) {
                    configuredChain.add((String) o);
                }
            }
        } else {
            throw new ConfigurationException(PROPERTY_CHAIN_LIST, "The list based configuration of a ImmutableGraph Chain MUST BE " + "configured as a Array or Collection of Strings (parsed: " + (list != null ? list.getClass() : "null") + "). NOTE you can also " + "configure the ImmutableGraph by pointing to a resource with the graph as" + "value of the property '" + PROPERTY_GRAPH_RESOURCE + "'.");
        }
        Map<String, Map<String, List<String>>> config;
        try {
            config = parseConfig(configuredChain);
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(PROPERTY_CHAIN_LIST, "Unable to parse the execution plan configuraiton (message: '" + e.getMessage() + "')!", e);
        }
        if (config.isEmpty()) {
            throw new ConfigurationException(PROPERTY_CHAIN_LIST, "The configured execution plan MUST at least contain a single " + "valid execution node!");
        }
        internalChain = new ListConfigExecutionPlan(config, getChainProperties());
        mode = MODE.LIST;
    } else {
        // both PROPERTY_CHAIN_LIST and PROPERTY_GRAPH_RESOURCE are null
        throw new ConfigurationException(PROPERTY_GRAPH_RESOURCE, "The Execution Plan is a required property. It MUST BE configured" + "by one of the properties :" + Arrays.asList(PROPERTY_GRAPH_RESOURCE, PROPERTY_GRAPH_RESOURCE));
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ConfigurationException(org.osgi.service.cm.ConfigurationException) Collection(java.util.Collection) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) Activate(org.apache.felix.scr.annotations.Activate)

Example 82 with Activate

use of org.apache.felix.scr.annotations.Activate in project stanbol by apache.

the class PrefixccProviderComponent method activate.

@Activate
protected void activate(ComponentContext ctx) throws ConfigurationException {
    bc = ctx.getBundleContext();
    Object value = ctx.getProperties().get(UPDATE_INTERVAL);
    if (value instanceof Number) {
        updateInterval = ((Number) value).intValue();
    } else if (value != null && !value.toString().isEmpty()) {
        try {
            updateInterval = new BigDecimal(value.toString()).intValue();
        } catch (NumberFormatException e) {
            throw new ConfigurationException(UPDATE_INTERVAL, "Unable to parse integer value from the configured value '" + value + "' (type: " + value.getClass() + ")");
        }
    } else {
        updateInterval = DEFAULT_UPDATE_INTERVAL;
    }
    if (updateInterval < 0) {
        log.warn("Negative update interval '{}' configured. Will use default '{}'!", updateInterval, DEFAULT_UPDATE_INTERVAL);
        updateInterval = DEFAULT_UPDATE_INTERVAL;
    } else if (updateInterval == 0) {
        updateInterval = DEFAULT_UPDATE_INTERVAL;
    }
    // we need to copy over the service ranking
    providerProperties = new Hashtable<String, Object>();
    Object ranking = ctx.getProperties().get(Constants.SERVICE_RANKING);
    if (ranking != null) {
        providerProperties.put(Constants.SERVICE_RANKING, ranking);
    }
    updateProviderState();
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) BigDecimal(java.math.BigDecimal) Activate(org.apache.felix.scr.annotations.Activate)

Example 83 with Activate

use of org.apache.felix.scr.annotations.Activate 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 84 with Activate

use of org.apache.felix.scr.annotations.Activate 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 85 with Activate

use of org.apache.felix.scr.annotations.Activate 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)

Aggregations

Activate (org.apache.felix.scr.annotations.Activate)153 ConfigurationException (org.osgi.service.cm.ConfigurationException)31 ServiceTracker (org.osgi.util.tracker.ServiceTracker)20 BundleContext (org.osgi.framework.BundleContext)19 File (java.io.File)15 OsgiWhiteboard (org.apache.jackrabbit.oak.osgi.OsgiWhiteboard)12 URL (java.net.URL)11 Hashtable (java.util.Hashtable)11 ServiceReference (org.osgi.framework.ServiceReference)11 ServiceTrackerCustomizer (org.osgi.util.tracker.ServiceTrackerCustomizer)9 HashSet (java.util.HashSet)8 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7 Map (java.util.Map)6 Session (javax.jcr.Session)5 StandardMBean (javax.management.StandardMBean)5 Whiteboard (org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard)5 Filter (org.osgi.framework.Filter)5 InputStream (java.io.InputStream)4 ArrayList (java.util.ArrayList)4