Search in sources :

Example 86 with ConfigurationException

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

the class EntityLinkerConfig method setConfiguration.

/**
 * Sets the configuration as parsed by the {@link Dictionary} to the
 * parsed {@link EntityLinkerConfig}.
 * @param linkerConfig the instance to apply the configuration to
 * @param configuration the configuration
 * @param prefixService Optionally a namespace prefix service used to
 * convert '{prefix}:{localname}' parameters in the configuration to URIs.
 * If <code>null</code> is parsed this feature is not supported and parameters
 * are not changed.
 * @throws ConfigurationException in case the configuration is invalid
 */
public static void setConfiguration(EntityLinkerConfig linkerConfig, Dictionary<String, Object> configuration, NamespacePrefixService prefixService) throws ConfigurationException {
    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(new IRI(getFullName(prefixService, 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(new IRI(getFullName(prefixService, 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(new IRI(getFullName(prefixService, REDIRECT_FIELD, value.toString())));
    }
    // init MAX_SUGGESTIONS
    value = configuration.get(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(SUGGESTIONS, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        maxSuggestions = null;
    }
    if (maxSuggestions != null) {
        if (maxSuggestions < 1) {
            throw new ConfigurationException(SUGGESTIONS, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMaxSuggestions(maxSuggestions);
    }
    // init INCLUDE_SIMILAR_SCORE
    value = configuration.get(INCLUDE_SIMILAR_SCORE);
    if (value instanceof Boolean) {
        linkerConfig.setIncludeSuggestionsWithSimilarScore((Boolean) value);
    } else if (value != null) {
        linkerConfig.setIncludeSuggestionsWithSimilarScore(Boolean.parseBoolean(value.toString()));
    }
    // 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 Label Score parameters
    value = configuration.get(MIN_LABEL_SCORE);
    Double minLabelMatchFactor = null;
    if (value instanceof Number) {
        minLabelMatchFactor = Double.valueOf(((Number) value).doubleValue());
    } else if (value != null) {
        try {
            minLabelMatchFactor = Double.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_LABEL_SCORE, "Parsed value '" + value + "' is not an valid double!");
        }
    }
    try {
        linkerConfig.setMinLabelScore(minLabelMatchFactor);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(MIN_LABEL_SCORE, e.getMessage());
    }
    value = configuration.get(MIN_TEXT_SCORE);
    Double minTextMatchFactor = null;
    if (value instanceof Number) {
        minTextMatchFactor = Double.valueOf(((Number) value).doubleValue());
    } else if (value != null) {
        try {
            minTextMatchFactor = Double.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_TEXT_SCORE, "Parsed value '" + value + "' is not an valid double!");
        }
    }
    try {
        linkerConfig.setMinTextScore(minTextMatchFactor);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(MIN_TEXT_SCORE, e.getMessage());
    }
    value = configuration.get(MIN_MATCH_FACTOR);
    Double minMatchFactor = null;
    if (value instanceof Number) {
        minMatchFactor = Double.valueOf(((Number) value).doubleValue());
    } else if (value != null) {
        try {
            minMatchFactor = Double.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_MATCH_FACTOR, "Parsed value '" + value + "' is not an valid double!");
        }
    }
    try {
        linkerConfig.setMinMatchScore(minMatchFactor);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(MIN_MATCH_FACTOR, e.getMessage());
    }
    value = configuration.get(MIN_CHUNK_MATCH_SCORE);
    Double minChunkMatchScore = null;
    if (value instanceof Number) {
        minChunkMatchScore = Double.valueOf(((Number) value).doubleValue());
    } else if (value != null) {
        try {
            minChunkMatchScore = Double.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MIN_CHUNK_MATCH_SCORE, "Parsed value '" + value + "' is not an valid double!");
        }
    }
    try {
        linkerConfig.setMinChunkMatchScore(minChunkMatchScore);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(MIN_CHUNK_MATCH_SCORE, e.getMessage());
    }
    // init LEMMA_MATCHING_STATE
    value = configuration.get(LEMMA_MATCHING_STATE);
    if (value instanceof Boolean) {
        linkerConfig.setLemmaMatchingState((Boolean) value);
    } else if (value != null) {
        linkerConfig.setLemmaMatchingState(Boolean.parseBoolean(value.toString()));
    }
    // init MAX_SEARCH_TOKENS
    value = configuration.get(MAX_SEARCH_TOKENS);
    Integer maxSearchTokens;
    if (value instanceof Integer) {
        maxSearchTokens = (Integer) value;
    } else if (value != null) {
        try {
            maxSearchTokens = Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MAX_SEARCH_TOKENS, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        maxSearchTokens = null;
    }
    if (maxSearchTokens != null) {
        if (maxSearchTokens < 1) {
            throw new ConfigurationException(MAX_SEARCH_TOKENS, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMaxSearchTokens(maxSearchTokens);
    }
    // init the MAX_SEARCH_TOKEN_DISTANCE
    value = configuration.get(MAX_SEARCH_TOKEN_DISTANCE);
    Integer maxSearchDistance;
    if (value instanceof Integer) {
        maxSearchDistance = (Integer) value;
    } else if (value != null) {
        try {
            maxSearchDistance = Integer.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new ConfigurationException(MAX_SEARCH_TOKEN_DISTANCE, "Values MUST be valid Integer values > 0", e);
        }
    } else {
        maxSearchDistance = null;
    }
    if (maxSearchDistance != null) {
        if (maxSearchDistance < 1) {
            throw new ConfigurationException(MAX_SEARCH_TOKEN_DISTANCE, "Values MUST be valid Integer values > 0");
        }
        linkerConfig.setMaxSearchDistance(maxSearchDistance);
    }
    // init the REDIRECT_PROCESSING_MODE
    value = configuration.get(REDIRECT_MODE);
    if (value != null) {
        try {
            linkerConfig.setRedirectProcessingMode(RedirectProcessingMode.valueOf(value.toString()));
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(REDIRECT_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_SCORE);
    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_SCORE, "Unable to parse the minimum token match factor from the parsed value " + value, e);
        }
        if (minTokenMatchFactor < 0) {
            minTokenMatchFactor = EntityLinkerConfig.DEFAULT_MIN_TOKEN_SCORE;
        }
    } else {
        minTokenMatchFactor = EntityLinkerConfig.DEFAULT_MIN_TOKEN_SCORE;
    }
    if (minTokenMatchFactor == 0 || minTokenMatchFactor > 1) {
        throw new ConfigurationException(MIN_TOKEN_SCORE, "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];
                // support for ns:localName
                targetType = getFullName(prefixService, TYPE_MAPPINGS, 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()) {
                        // support for ns:localName
                        sourceType = getFullName(prefixService, TYPE_MAPPINGS, 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");
    }
    // dereference entities
    value = configuration.get(DEREFERENCE_ENTITIES);
    if (value instanceof Boolean) {
        linkerConfig.setDereferenceEntitiesState(((Boolean) value).booleanValue());
    } else if (value != null && !value.toString().isEmpty()) {
        linkerConfig.setDereferenceEntitiesState(Boolean.parseBoolean(value.toString()));
    }
    if (linkerConfig.isDereferenceEntitiesEnabled()) {
        log.warn("DereferenceEntities is deprecated for the Engine. Please use the " + "EntityhubDereferenceEngine instead (see STANBOL-1223 for details)");
    }
    if (linkerConfig.isDereferenceEntitiesEnabled()) {
        value = configuration.get(DEREFERENCE_ENTITIES_FIELDS);
        if (value instanceof String[]) {
            for (String field : (String[]) value) {
                if (field != null && !field.isEmpty()) {
                    linkerConfig.getDereferencedFields().add(new IRI(getFullName(prefixService, DEREFERENCE_ENTITIES_FIELDS, field)));
                }
            }
        } else if (value instanceof Collection<?>) {
            for (Object field : (Collection<?>) value) {
                if (field != null && !field.toString().isEmpty()) {
                    linkerConfig.getDereferencedFields().add(new IRI(getFullName(prefixService, DEREFERENCE_ENTITIES_FIELDS, field.toString())));
                }
            }
        } else if (value instanceof String) {
            if (!value.toString().isEmpty()) {
                linkerConfig.getDereferencedFields().add(new IRI(getFullName(prefixService, DEREFERENCE_ENTITIES_FIELDS, value.toString())));
            }
        } else if (value != null) {
            throw new ConfigurationException(DEREFERENCE_ENTITIES_FIELDS, "Dereference Entities_Fields MUST BE parsed as String[], Collection<String> or " + "String (single value). The actual value '" + value + "'(type: '" + value.getClass() + "') is NOT supported");
        } else {
            // value == null
            log.debug("No deference fields for entity configured");
        }
    }
    // init USE ENTITY RANKINGS (STANBOL-1030)
    value = configuration.get(RANK_EQUAL_SCORES_BASED_ON_ENTITY_RANKINGS);
    if (value instanceof Boolean) {
        linkerConfig.setRankEqualScoresBasedOnEntityRankings(((Boolean) value).booleanValue());
    } else if (value != null) {
        linkerConfig.setRankEqualScoresBasedOnEntityRankings(Boolean.parseBoolean(value.toString()));
    } else {
        linkerConfig.setRankEqualScoresBasedOnEntityRankings(DEFAULT_RANK_EQUAL_SCORES_BASED_ON_ENTITY_RANKINGS);
    }
    // init WRITE ENTITY RANKINGS (STANBOL-1292)
    value = configuration.get(WRITE_ENTITY_RANKINGS);
    if (value instanceof Boolean) {
        linkerConfig.setWriteEntityRankings(((Boolean) value).booleanValue());
    } else if (value != null) {
        linkerConfig.setWriteEntityRankings(Boolean.parseBoolean(value.toString()));
    } else {
        linkerConfig.setWriteEntityRankings(DEFAULT_WRITE_ENTITY_RANKINGS);
    }
    // init the list of whitelisted/blacklisted types
    value = configuration.get(ENTITY_TYPES);
    // first collect and cleanup the config
    List<String> entityTypesConfig;
    if (value == null) {
        entityTypesConfig = Collections.emptyList();
    } else if (value instanceof String[]) {
        entityTypesConfig = new ArrayList<String>();
        for (String type : (String[]) value) {
            if (type != null) {
                type = type.trim();
                if (!type.isEmpty()) {
                    entityTypesConfig.add(type);
                }
            }
        }
    } else if (value instanceof Collection<?>) {
        entityTypesConfig = new ArrayList<String>();
        for (Object o : (Collection<Object>) value) {
            if (o != null) {
                String type = o.toString().trim();
                if (!type.isEmpty()) {
                    entityTypesConfig.add(type);
                }
            }
        }
    } else if (value instanceof String) {
        // support parsing single values as string
        String type = value.toString().trim();
        if (type.isEmpty()) {
            entityTypesConfig = Collections.emptyList();
        } else {
            entityTypesConfig = Collections.singletonList(type);
        }
    } else {
        throw new ConfigurationException(ENTITY_TYPES, "The list of ignored types (if present) " + "MUST BE a collection or a string array (present: " + value.getClass().getName() + ")!");
    }
    // apply the config
    for (int i = 0; i < entityTypesConfig.size(); i++) {
        String type = entityTypesConfig.get(i);
        if ("*".equals(type)) {
            linkerConfig.setDefaultWhitelistTypes(Boolean.TRUE);
        } else {
            boolean blacklisted = type.charAt(0) == '!';
            if (blacklisted && type.length() < 2) {
                throw new ConfigurationException(ENTITY_TYPES, "The list of whitelisted/blacklisted " + "MUST NOT contain '!' (configured: " + entityTypesConfig + ")!");
            }
            IRI uri = new IRI(getFullName(prefixService, ENTITY_TYPES, blacklisted ? type.substring(1) : type));
            if (blacklisted) {
                linkerConfig.addBlacklistType(uri, Integer.valueOf(i));
            } else {
                linkerConfig.addWhitelistType(uri, Integer.valueOf(i));
            }
        }
    }
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ConfigurationException(org.osgi.service.cm.ConfigurationException) Collection(java.util.Collection)

Example 87 with ConfigurationException

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

the class EntityCoReferenceEngine method activate.

@SuppressWarnings("unchecked")
@Activate
protected void activate(ComponentContext ctx) throws ConfigurationException {
    super.activate(ctx);
    Dictionary<String, Object> config = ctx.getProperties();
    /* Step 1 - initialize the {@link NounPhraseFilterer} with the language config */
    String languages = (String) config.get(CONFIG_LANGUAGES);
    if (languages == null || languages.isEmpty()) {
        throw new ConfigurationException(CONFIG_LANGUAGES, "The Languages Config is a required Parameter and MUST NOT be NULL or an empty String!");
    }
    nounPhraseFilterer = new NounPhraseFilterer(languages.split(","));
    /* Step 2 - initialize the {@link CoreferenceFinder} */
    String referencedSiteID = null;
    Object referencedSiteIDfromConfig = config.get(REFERENCED_SITE_ID);
    if (referencedSiteIDfromConfig == null) {
        throw new ConfigurationException(REFERENCED_SITE_ID, "The ID of the Referenced Site is a required Parameter and MUST NOT be NULL!");
    }
    referencedSiteID = referencedSiteIDfromConfig.toString();
    if (referencedSiteID.isEmpty()) {
        throw new ConfigurationException(REFERENCED_SITE_ID, "The ID of the Referenced Site is a required Parameter and MUST NOT be an empty String!");
    }
    if (Entityhub.ENTITYHUB_IDS.contains(referencedSiteID.toLowerCase())) {
        log.debug("Init NamedEntityTaggingEngine instance for the Entityhub");
        referencedSiteID = null;
    }
    int maxDistance;
    Object maxDistanceFromConfig = config.get(MAX_DISTANCE);
    if (maxDistanceFromConfig == null) {
        maxDistance = Constants.MAX_DISTANCE_DEFAULT_VALUE;
    } else if (maxDistanceFromConfig instanceof Number) {
        maxDistance = ((Number) maxDistanceFromConfig).intValue();
    } else {
        try {
            maxDistance = Integer.parseInt(maxDistanceFromConfig.toString());
        } catch (NumberFormatException nfe) {
            throw new ConfigurationException(MAX_DISTANCE, "The Max Distance parameter must be a number");
        }
    }
    if (maxDistance < -1) {
        throw new ConfigurationException(MAX_DISTANCE, "The Max Distance parameter must not be smaller than -1");
    }
    String entityUriBase = (String) config.get(ENTITY_URI_BASE);
    if (entityUriBase == null || entityUriBase.isEmpty()) {
        throw new ConfigurationException(ENTITY_URI_BASE, "The Entity Uri Base parameter cannot be empty");
    }
    String spatialAttrForPerson = (String) config.get(SPATIAL_ATTR_FOR_PERSON);
    String spatialAttrForOrg = (String) config.get(SPATIAL_ATTR_FOR_ORGANIZATION);
    String spatialAttrForPlace = (String) config.get(SPATIAL_ATTR_FOR_PLACE);
    String orgAttrForPerson = (String) config.get(ORG_ATTR_FOR_PERSON);
    String entityClassesToExclude = (String) config.get(ENTITY_CLASSES_TO_EXCLUDE);
    corefFinder = new CoreferenceFinder(languages.split(","), siteManager, entityhub, referencedSiteID, maxDistance, entityUriBase, spatialAttrForPerson, spatialAttrForOrg, spatialAttrForPlace, orgAttrForPerson, entityClassesToExclude);
    log.info("activate {}[name:{}]", getClass().getSimpleName(), getName());
}
Also used : CoreferenceFinder(org.apache.stanbol.enhancer.engines.entitycoreference.impl.CoreferenceFinder) ConfigurationException(org.osgi.service.cm.ConfigurationException) NounPhraseFilterer(org.apache.stanbol.enhancer.engines.entitycoreference.impl.NounPhraseFilterer) Activate(org.apache.felix.scr.annotations.Activate)

Example 88 with ConfigurationException

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

the class LuceneLabelTokenizer method activate.

@Activate
protected void activate(ComponentContext ctx) throws ConfigurationException {
    // init the Solr ResourceLoader used for initialising the components
    resourceLoader = new StanbolResourceLoader(parentResourceLoader);
    // init the Solr CharFilterFactory (optional)
    Object value = ctx.getProperties().get(PROPERTY_CHAR_FILTER_FACTORY);
    if (value != null && !value.toString().isEmpty() && !DEFAULT_CLASS_NAME_CONFIG.equals(value)) {
        Entry<String, Map<String, String>> charFilterConfig = parseConfigLine(PROPERTY_CHAR_FILTER_FACTORY, value.toString());
        charFilterFactory = initAnalyzer(PROPERTY_CHAR_FILTER_FACTORY, charFilterConfig.getKey(), CharFilterFactory.class, charFilterConfig.getValue());
    } else {
        charFilterFactory = null;
    }
    // now initialise the TokenizerFactory (required)
    value = ctx.getProperties().get(PROPERTY_TOKENIZER_FACTORY);
    if (value == null || value.toString().isEmpty() || DEFAULT_CLASS_NAME_CONFIG.equals(value)) {
        throw new ConfigurationException(PROPERTY_TOKENIZER_FACTORY, "The class name of the Lucene Tokemizer MUST BE configured");
    }
    Entry<String, Map<String, String>> tokenizerConfig = parseConfigLine(PROPERTY_CHAR_FILTER_FACTORY, value.toString());
    tokenizerFactory = initAnalyzer(PROPERTY_TOKENIZER_FACTORY, tokenizerConfig.getKey(), TokenizerFactory.class, tokenizerConfig.getValue());
    // initialise the list of Token Filters
    Collection<String> values;
    value = ctx.getProperties().get(PROPERTY_TOKEN_FILTER_FACTORY);
    if (value == null) {
        values = Collections.emptyList();
    } else if (value instanceof Collection<?>) {
        values = new ArrayList<String>(((Collection<?>) value).size());
        for (Object v : (Collection<Object>) value) {
            values.add(v.toString());
        }
    } else if (value instanceof String[]) {
        values = Arrays.asList((String[]) value);
    } else if (value instanceof String) {
        values = Collections.singleton((String) value);
    } else {
        throw new ConfigurationException(PROPERTY_TOKEN_FILTER_FACTORY, "The type '" + value.getClass() + "' of the parsed value is not supported (supported are " + "Collections, String[] and String values)!");
    }
    for (String filterConfigLine : values) {
        if (filterConfigLine == null || filterConfigLine.isEmpty() || DEFAULT_CLASS_NAME_CONFIG.equals(filterConfigLine)) {
            // ignore null, empty and the default value
            continue;
        }
        Entry<String, Map<String, String>> filterConfig = parseConfigLine(PROPERTY_CHAR_FILTER_FACTORY, filterConfigLine);
        TokenFilterFactory tff = initAnalyzer(PROPERTY_TOKEN_FILTER_FACTORY, filterConfig.getKey(), TokenFilterFactory.class, filterConfig.getValue());
        filterFactories.add(tff);
    }
    // init the language configuration
    value = ctx.getProperties().get(LabelTokenizer.SUPPORTED_LANUAGES);
    if (value == null) {
        throw new ConfigurationException(LabelTokenizer.SUPPORTED_LANUAGES, "The language " + "configuration MUST BE present!");
    }
    langConf.setConfiguration(ctx.getProperties());
}
Also used : StanbolResourceLoader(org.apache.stanbol.commons.solr.utils.StanbolResourceLoader) TokenizerFactory(org.apache.lucene.analysis.util.TokenizerFactory) ConfigurationException(org.osgi.service.cm.ConfigurationException) CharFilterFactory(org.apache.lucene.analysis.util.CharFilterFactory) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map) TokenFilterFactory(org.apache.lucene.analysis.util.TokenFilterFactory) Activate(org.apache.felix.scr.annotations.Activate)

Example 89 with ConfigurationException

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

the class LuceneLabelTokenizer method initAnalyzer.

private <T> T initAnalyzer(String property, String analyzerName, Class<T> type, Map<String, String> config) throws ConfigurationException {
    Class<? extends T> analyzerClass;
    try {
        analyzerClass = resourceLoader.findClass(analyzerName, type);
    } catch (SolrException e) {
        throw new ConfigurationException(PROPERTY_CHAR_FILTER_FACTORY, "Unable find " + type.getSimpleName() + " '" + analyzerName + "'!", e);
    }
    Constructor<? extends T> constructor;
    try {
        constructor = analyzerClass.getConstructor(Map.class);
    } catch (NoSuchMethodException e1) {
        throw new ConfigurationException(PROPERTY_CHAR_FILTER_FACTORY, "Unable find " + type.getSimpleName() + "constructor with parameter Map<String,String> " + "for class " + analyzerClass + " (analyzer: '" + analyzerName + "') !");
    }
    addLuceneMatchVersionIfNotPresent(config);
    T analyzer;
    try {
        analyzer = constructor.newInstance(config);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(property, "Unable to instantiate " + type.getSimpleName() + ' ' + analyzerClass + " (analyzer: " + analyzerName + "') !", e);
    } catch (InstantiationException e) {
        throw new ConfigurationException(property, "Unable to instantiate " + type.getSimpleName() + ' ' + analyzerClass + " (analyzer: " + analyzerName + "') !", e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(property, "Unable to instantiate " + type.getSimpleName() + ' ' + analyzerClass + " (analyzer: " + analyzerName + "') !", e);
    } catch (InvocationTargetException e) {
        throw new ConfigurationException(property, "Unable to instantiate " + type.getSimpleName() + ' ' + analyzerClass + " (analyzer: " + analyzerName + "') !", e);
    }
    if (analyzer instanceof ResourceLoaderAware) {
        try {
            ((ResourceLoaderAware) analyzer).inform(resourceLoader);
        } catch (IOException e) {
            throw new ConfigurationException(PROPERTY_CHAR_FILTER_FACTORY, "Could not load configuration");
        }
    }
    return analyzer;
}
Also used : IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ResourceLoaderAware(org.apache.lucene.analysis.util.ResourceLoaderAware) HashMap(java.util.HashMap) Map(java.util.Map) SolrException(org.apache.solr.common.SolrException)

Example 90 with ConfigurationException

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

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