Search in sources :

Example 91 with ConfigurationException

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

the class ListChain method activate.

@Override
protected void activate(ComponentContext ctx) throws ConfigurationException {
    super.activate(ctx);
    Object value = ctx.getProperties().get(PROPERTY_ENGINE_LIST);
    List<String> configuredChain = new ArrayList<String>();
    if (value instanceof String[]) {
        configuredChain.addAll(Arrays.asList((String[]) value));
    } else if (value instanceof List<?>) {
        for (Object o : (List<?>) value) {
            if (o != null) {
                configuredChain.add(o.toString());
            }
        }
    } else {
        throw new ConfigurationException(PROPERTY_ENGINE_LIST, "The engines of a List Chain MUST BE configured as Array/List of " + "Strings (parsed: " + (value != null ? value.getClass() : "null") + ")");
    }
    Set<String> engineNames = new HashSet<String>(configuredChain.size());
    BlankNodeOrIRI last = null;
    Graph ep = new SimpleGraph();
    BlankNodeOrIRI epNode = createExecutionPlan(ep, getName(), getChainProperties());
    log.debug("Parse ListChain config:");
    for (String line : configuredChain) {
        try {
            Entry<String, Map<String, List<String>>> parsed = ConfigUtils.parseConfigEntry(line);
            if (!engineNames.add(parsed.getKey())) {
                throw new ConfigurationException(PROPERTY_ENGINE_LIST, "The EnhancementEngine '" + parsed.getKey() + "' is mentioned" + "twice in the configured list!");
            }
            boolean optional = getState(parsed.getValue(), "optional");
            log.debug(" > Engine: {} ({})", parsed.getKey(), optional ? "optional" : "required");
            last = writeExecutionNode(ep, epNode, parsed.getKey(), optional, last == null ? null : Collections.singleton(last), getEnhancementProperties(parsed.getValue()));
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(PROPERTY_ENGINE_LIST, "Unable to parse Chain Configuraiton (message: '" + e.getMessage() + "')!", e);
        }
    }
    if (engineNames.isEmpty()) {
        throw new ConfigurationException(PROPERTY_ENGINE_LIST, "The configured chain MUST at least contain a single valid entry!");
    }
    this.engineNames = Collections.unmodifiableSet(engineNames);
    this.executionPlan = ep.getImmutableGraph();
}
Also used : ArrayList(java.util.ArrayList) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) ConfigurationException(org.osgi.service.cm.ConfigurationException) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Map(java.util.Map) HashSet(java.util.HashSet)

Example 92 with ConfigurationException

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

the class EntityhubComponent method activate.

@Activate
protected void activate(final ComponentContext context) throws ConfigurationException {
    this.bc = context.getBundleContext();
    Dictionary<?, ?> properties = context.getProperties();
    log.info("Activate Entityhub Component:");
    this.entityhubID = OsgiUtils.checkProperty(properties, ID).toString();
    if (entityhubID == null || entityhubID.isEmpty()) {
        throw new ConfigurationException(ID, "The id for the Entityhub MUST NOT be empty!");
    } else {
        log.debug("   + id: {}", entityhubID);
    }
    this.entityhubName = OsgiUtils.checkProperty(properties, NAME, this.entityhubID).toString();
    if (entityhubName.isEmpty()) {
        throw new ConfigurationException(NAME, "The name for the Entityhub MUST NOT be empty!");
    } else {
        log.debug("   + name: {}", entityhubName);
    }
    Object entityhubDescriptionObject = properties.get(DESCRIPTION);
    this.entityhubDescription = entityhubDescriptionObject == null ? null : entityhubDescriptionObject.toString();
    log.debug("   + description: {}", entityhubDescription == null ? "<none>" : entityhubDescription);
    this.entityhubPrefix = OsgiUtils.checkProperty(properties, PREFIX).toString();
    if (entityhubPrefix.isEmpty()) {
        throw new ConfigurationException(PREFIX, "The UIR preix for the Entityub MUST NOT be empty!");
    }
    try {
        new URI(entityhubPrefix);
        log.info("   + prefix: " + entityhubPrefix);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(PREFIX, "The URI prefix for the Entityhub " + "MUST BE an valid URI (prefix=" + entityhubPrefix + ")", e);
    }
    Object defaultSymbolState = properties.get(DEFAULT_SYMBOL_STATE);
    if (defaultSymbolState == null) {
        this.defaultSymblStateString = ManagedEntity.DEFAULT_SYMBOL_STATE.name();
    } else {
        this.defaultSymblStateString = defaultSymbolState.toString();
    }
    Object defaultMappingState = properties.get(DEFAULT_MAPPING_STATE);
    if (defaultMappingState == null) {
        this.defaultMappingStateString = EntityMapping.DEFAULT_MAPPING_STATE.name();
    } else {
        this.defaultMappingStateString = defaultMappingState.toString();
    }
    Object fieldMappingConfigObject = OsgiUtils.checkProperty(properties, FIELD_MAPPINGS);
    if (fieldMappingConfigObject instanceof String[]) {
        this.fieldMappingConfig = (String[]) fieldMappingConfigObject;
    } else {
        throw new ConfigurationException(FIELD_MAPPINGS, "Values for this property must be of type Stirng[]!");
    }
    String entityhubYardId = OsgiUtils.checkProperty(properties, ENTITYHUB_YARD_ID).toString();
    String filterString = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, Yard.class.getName(), Yard.ID, entityhubYardId);
    log.debug(" ... tracking EntityhubYard by Filter:" + filterString);
    Filter filter;
    try {
        filter = context.getBundleContext().createFilter(filterString);
    } catch (InvalidSyntaxException e) {
        throw new ConfigurationException(ENTITYHUB_YARD_ID, "Unable to parse OSGI filter '" + filterString + "' for configured Yard id '" + entityhubYardId + "'!", e);
    }
    entityhubYardTracker = new ServiceTracker(context.getBundleContext(), filter, new ServiceTrackerCustomizer() {

        final BundleContext bc = context.getBundleContext();

        @Override
        public void removedService(ServiceReference reference, Object service) {
            if (service.equals(entityhubYard)) {
                entityhubYard = (Yard) entityhubYardTracker.getService();
                updateServiceRegistration(bc, entityhubYard, siteManager, nsPrefixService);
            }
            bc.ungetService(reference);
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
            // the service.ranking might have changed ... so check if the
            // top ranked yard is a different one
            Yard newYard = (Yard) entityhubYardTracker.getService();
            if (newYard == null || !newYard.equals(entityhubYard)) {
                // set the new yard
                entityhubYard = newYard;
                // and update the service registration
                updateServiceRegistration(bc, entityhubYard, siteManager, nsPrefixService);
            }
        }

        @Override
        public Object addingService(ServiceReference reference) {
            Object service = bc.getService(reference);
            if (service != null) {
                if (// the first added Service or
                entityhubYardTracker.getServiceReference() == null || // the new service as higher ranking as the current
                (reference.compareTo(entityhubYardTracker.getServiceReference()) > 0)) {
                    entityhubYard = (Yard) service;
                    updateServiceRegistration(bc, entityhubYard, siteManager, nsPrefixService);
                }
            // else the new service has lower ranking as the currently use one
            }
            // else service == null -> ignore
            return service;
        }
    });
    // start the tracking
    entityhubYardTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ServiceReference(org.osgi.framework.ServiceReference) Yard(org.apache.stanbol.entityhub.servicesapi.yard.Yard) ConfigurationException(org.osgi.service.cm.ConfigurationException) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext) Activate(org.apache.felix.scr.annotations.Activate)

Example 93 with ConfigurationException

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

the class DirectoryDataFileProvider method activate.

@Activate
protected void activate(ComponentContext ctx) throws ConfigurationException {
    String folderName = requireProperty(ctx.getProperties(), DATA_FILES_FOLDER_PROP, String.class);
    dataFilesFolder = new File(folderName);
    if (!dataFilesFolder.exists()) {
        if (!dataFilesFolder.mkdirs()) {
            throw new ConfigurationException(DATA_FILES_FOLDER_PROP, "Unable to create the configured Directory " + dataFilesFolder);
        }
    } else if (!dataFilesFolder.isDirectory()) {
        throw new ConfigurationException(DATA_FILES_FOLDER_PROP, "The configured DataFile directory " + dataFilesFolder + " does already exists but is not a directory!");
    }
// else exists and is a directory!
}
Also used : ConfigurationException(org.osgi.service.cm.ConfigurationException) File(java.io.File) Activate(org.apache.felix.scr.annotations.Activate)

Example 94 with ConfigurationException

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

the class SolrDispatchFilterComponent method activate.

@Activate
protected void activate(ComponentContext context) throws ConfigurationException, ServletException {
    this.context = context;
    BundleContext bc = context.getBundleContext();
    Object value = context.getProperties().get(PROPERTY_SERVER_NAME);
    if (value == null || value.toString().isEmpty()) {
        throw new ConfigurationException(PROPERTY_SERVER_NAME, "The configured CoreContainer name MUST NOT be NULL nor empty!");
    }
    serverName = value.toString();
    String filterString = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, CoreContainer.class.getName(), SolrConstants.PROPERTY_SERVER_NAME, serverName);
    try {
        tracker = new ServiceTracker(bc, bc.createFilter(filterString), trackerCustomizer);
    } catch (InvalidSyntaxException e) {
        throw new ConfigurationException(PROPERTY_SERVER_NAME, "Unable to build Filter for parsed CoreContainer name '" + serverName + "'", e);
    }
    value = context.getProperties().get(PROPERTY_PREFIX_PATH);
    final String prefixPath;
    if (value != null) {
        prefix = value.toString();
        if (prefix.charAt(0) != '/') {
            prefix = '/' + prefix;
        }
        prefixPath = prefix;
        if (!prefix.endsWith("*")) {
            // TODO: check if this is a good idea
            prefix = prefix + "/.*";
        }
    } else {
        prefixPath = null;
        prefix = "/.*";
    }
    filterPrpoerties = new Hashtable<String, Object>();
    if (prefixPath != null) {
        filterPrpoerties.put("path-prefix", prefixPath);
    }
    // now start tracking! ...
    // ... as soon as the first CoreContainer is tracked the Filter will
    // be created and added to the ExtHttpService
    tracker.open();
}
Also used : CoreContainer(org.apache.solr.core.CoreContainer) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceTracker(org.osgi.util.tracker.ServiceTracker) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) BundleContext(org.osgi.framework.BundleContext) Activate(org.apache.felix.scr.annotations.Activate)

Example 95 with ConfigurationException

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

the class KeywordLinkingEngine method activateEntityLinkerConfig.

/**
 * Configures the parsed {@link EntityLinkerConfig} with the values of the
 * following properties:<ul>
 * <li>{@link #NAME_FIELD}
 * <li>{@link #TYPE_FIELD}
 * <li>{@link #REDIRECT_FIELD}
 * <li>{@link #REDIRECT_PROCESSING_MODE}
 * <li>{@link #MAX_SUGGESTIONS}
 * <li>{@link #MIN_SEARCH_TOKEN_LENGTH}
 * <li>{@link #MIN_FOUND_TOKENS}
 * <li> {@link #MIN_TOKEN_MATCH_FACTOR}
 * </ul>
 * This Method create an new {@link EntityLinkerConfig} instance only if
 * <code>{@link #linkerConfig} == null</code>. If the instance is already initialised
 * that all current values for keys missing in the parsed configuration are
 * preserved.
 * @param configuration the configuration
 * @throws ConfigurationException In case of an illegal value in the parsed configuration.
 * Note that all configuration are assumed as optional, therefore missing values will not
 * case a ConfigurationException.
 */
protected void activateEntityLinkerConfig(Dictionary<String, Object> configuration) throws ConfigurationException {
    if (linkerConfig == null) {
        this.linkerConfig = new EntityLinkerConfig();
    }
    Object value;
    value = configuration.get(NAME_FIELD);
    if (value != null) {
        if (value.toString().isEmpty()) {
            throw new ConfigurationException(NAME_FIELD, "The configured name field MUST NOT be empty");
        }
        linkerConfig.setNameField(NamespaceMappingUtils.getConfiguredUri(nsPrefixService, NAME_FIELD, value.toString()));
    }
    // init case sensitivity
    value = configuration.get(CASE_SENSITIVE);
    if (value instanceof Boolean) {
        linkerConfig.setCaseSensitiveMatchingState((Boolean) value);
    } else if (value != null && !value.toString().isEmpty()) {
        linkerConfig.setCaseSensitiveMatchingState(Boolean.valueOf(value.toString()));
    }
    // if NULL or empty use default
    // init TYPE_FIELD
    value = configuration.get(TYPE_FIELD);
    if (value != null) {
        if (value.toString().isEmpty()) {
            throw new ConfigurationException(TYPE_FIELD, "The configured name field MUST NOT be empty");
        }
        linkerConfig.setTypeField(NamespaceMappingUtils.getConfiguredUri(nsPrefixService, TYPE_FIELD, value.toString()));
    }
    // init REDIRECT_FIELD
    value = configuration.get(REDIRECT_FIELD);
    if (value != null) {
        if (value.toString().isEmpty()) {
            throw new ConfigurationException(NAME_FIELD, "The configured name field MUST NOT be empty");
        }
        linkerConfig.setRedirectField(NamespaceMappingUtils.getConfiguredUri(nsPrefixService, REDIRECT_FIELD, value.toString()));
    }
    // init MAX_SUGGESTIONS
    value = configuration.get(MAX_SUGGESTIONS);
    Integer maxSuggestions;
    if (value instanceof Integer) {
        maxSuggestions = (Integer) value;
    } else if (value != null) {
        try {
            maxSuggestions = Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MAX_SUGGESTIONS, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        maxSuggestions = null;
    }
    if (maxSuggestions != null) {
        if (maxSuggestions < 1) {
            throw new ConfigurationException(MAX_SUGGESTIONS, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMaxSuggestions(maxSuggestions);
    }
    // init MIN_FOUND_TOKENS
    value = configuration.get(MIN_FOUND_TOKENS);
    Integer minFoundTokens;
    if (value instanceof Integer) {
        minFoundTokens = (Integer) value;
    } else if (value != null) {
        try {
            minFoundTokens = Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_FOUND_TOKENS, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        minFoundTokens = null;
    }
    if (minFoundTokens != null) {
        if (minFoundTokens < 1) {
            throw new ConfigurationException(MIN_FOUND_TOKENS, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMinFoundTokens(minFoundTokens);
    }
    // init MIN_SEARCH_TOKEN_LENGTH
    value = configuration.get(MIN_SEARCH_TOKEN_LENGTH);
    Integer minSearchTokenLength;
    if (value instanceof Integer) {
        minSearchTokenLength = (Integer) value;
    } else if (value != null) {
        try {
            minSearchTokenLength = Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_SEARCH_TOKEN_LENGTH, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        minSearchTokenLength = null;
    }
    if (minSearchTokenLength != null) {
        if (minSearchTokenLength < 1) {
            throw new ConfigurationException(MIN_SEARCH_TOKEN_LENGTH, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMinSearchTokenLength(minSearchTokenLength);
    }
    // init the REDIRECT_PROCESSING_MODE
    value = configuration.get(REDIRECT_PROCESSING_MODE);
    if (value != null) {
        try {
            linkerConfig.setRedirectProcessingMode(RedirectProcessingMode.valueOf(value.toString()));
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(REDIRECT_PROCESSING_MODE, "Values MUST be one of " + Arrays.toString(RedirectProcessingMode.values()));
        }
    }
    // init the DEFAULT_LANGUAGE
    value = configuration.get(DEFAULT_MATCHING_LANGUAGE);
    if (value != null) {
        String defaultLang = value.toString().trim();
        if (defaultLang.isEmpty()) {
            linkerConfig.setDefaultLanguage(null);
        } else if (defaultLang.length() == 1) {
            throw new ConfigurationException(DEFAULT_MATCHING_LANGUAGE, "Illegal language code '" + defaultLang + "'! Language Codes MUST BE at least 2 chars long.");
        } else {
            linkerConfig.setDefaultLanguage(defaultLang);
        }
    }
    // init MIN_TOKEN_MATCH_FACTOR
    value = configuration.get(MIN_TOKEN_MATCH_FACTOR);
    float minTokenMatchFactor;
    if (value instanceof Number) {
        minTokenMatchFactor = ((Number) value).floatValue();
    } else if (value != null) {
        try {
            minTokenMatchFactor = Float.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_TOKEN_MATCH_FACTOR, "Unable to parse the minimum token match factor from the parsed value " + value, e);
        }
        if (minTokenMatchFactor < 0) {
            minTokenMatchFactor = EntityLinkerConfig.DEFAULT_MIN_TOKEN_MATCH_FACTOR;
        }
    } else {
        minTokenMatchFactor = EntityLinkerConfig.DEFAULT_MIN_TOKEN_MATCH_FACTOR;
    }
    if (minTokenMatchFactor == 0 || minTokenMatchFactor > 1) {
        throw new ConfigurationException(MIN_TOKEN_MATCH_FACTOR, "The minimum token match factor MUST be > 0 and <= 1 (negative values for the default)");
    }
    linkerConfig.setMinTokenMatchFactor(minTokenMatchFactor);
    // init type mappings
    value = configuration.get(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 Type Mappings");
        configs: for (Object o : (Iterable<?>) value) {
            if (o != null) {
                StringBuilder usage = new StringBuilder("useages: ");
                usage.append("a: '{uri}' short for {uri} > {uri} | ");
                usage.append("b: '{source1};{source2};..;{sourceN} > {target}'");
                String[] config = o.toString().split(">");
                if (config[0].isEmpty()) {
                    log.warn("Invalid Type Mapping Config '{}': Missing Source Type ({}) -> ignore this config", o, usage);
                    continue configs;
                }
                String[] sourceTypes = config[0].split(";");
                if (sourceTypes.length > 1 && (config.length < 2 || config[1].isEmpty())) {
                    log.warn("Invalid Type Mapping Config '{}': Missing Target Type '{}' ({}) -> ignore this config", o, usage);
                    continue configs;
                }
                String targetType = config.length < 2 ? sourceTypes[0] : config[1];
                targetType = NamespaceMappingUtils.getConfiguredUri(nsPrefixService, TYPE_MAPPINGS, // support for ns:localName
                targetType.trim());
                try {
                    // validate
                    new URI(targetType);
                } catch (URISyntaxException e) {
                    log.warn("Invalid URI '{}' in Type Mapping Config '{}' -> ignore this config", sourceTypes[0], o);
                    continue configs;
                }
                IRI targetUri = new IRI(targetType);
                for (String sourceType : sourceTypes) {
                    if (!sourceType.isEmpty()) {
                        sourceType = NamespaceMappingUtils.getConfiguredUri(nsPrefixService, TYPE_MAPPINGS, // support for ns:localName
                        sourceType.trim());
                        try {
                            // validate
                            new URI(sourceType);
                            IRI old = linkerConfig.setTypeMapping(sourceType, targetUri);
                            if (old == null) {
                                log.info(" > add type mapping {} > {}", sourceType, targetType);
                            } else {
                                log.info(" > set type mapping {} > {} (old: {})", new Object[] { sourceType, targetType, old.getUnicodeString() });
                            }
                        } catch (URISyntaxException e) {
                            log.warn("Invalid URI '{}' in Type Mapping Config '{}' -> ignore this source type", sourceTypes[0], o);
                        }
                    }
                }
            }
        }
    } else {
        log.debug("No Type mappings configured");
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) EntityLinkerConfig(org.apache.stanbol.enhancer.engines.keywordextraction.impl.EntityLinkerConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ConfigurationException(org.osgi.service.cm.ConfigurationException) Collection(java.util.Collection)

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