Search in sources :

Example 61 with Filter

use of org.osgi.framework.Filter in project ddf by codice.

the class ConfigurationAdminExt method addConfigurationData.

private void addConfigurationData(Map<String, Object> service, Configuration[] configs) {
    for (Configuration config : configs) {
        // ignore configuration object if it is invalid
        final String pid = config.getPid();
        if (!isAllowedPid(pid)) {
            continue;
        }
        Map<String, Object> configData = new HashMap<String, Object>();
        configData.put(MAP_ENTRY_ID, pid);
        String fpid = config.getFactoryPid();
        if (fpid != null) {
            configData.put(MAP_ENTRY_FPID, fpid);
        }
        // insert an entry for the PID
        try {
            ObjectClassDefinition ocd = getObjectClassDefinition(config);
            if (ocd != null) {
                configData.put(MAP_ENTRY_NAME, ocd.getName());
            } else {
                // no object class definition, use plain PID
                configData.put(MAP_ENTRY_NAME, pid);
            }
        } catch (IllegalArgumentException t) {
            // Catch exception thrown by getObjectClassDefinition so other configurations
            // are displayed
            // no object class definition, use plain PID
            configData.put(MAP_ENTRY_NAME, pid);
        }
        final Bundle bundle = getBoundBundle(config);
        if (null != bundle) {
            configData.put(MAP_ENTRY_BUNDLE, bundle.getBundleId());
            configData.put(MAP_ENTRY_BUNDLE_NAME, getName(bundle));
            configData.put(MAP_ENTRY_BUNDLE_LOCATION, bundle.getLocation());
        }
        Map<String, Object> propertiesTable = new HashMap<String, Object>();
        Dictionary<String, Object> properties = config.getProperties();
        if (properties != null) {
            Enumeration<String> keys = properties.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                propertiesTable.put(key, properties.get(key));
            }
        }
        // If the configuration property is a password, set its value to "password" so that
        // the real password value will be hidden.
        List<HashMap<String, Object>> metatypeList = (List<HashMap<String, Object>>) service.get("metatype");
        metatypeList.stream().filter(metatype -> AttributeDefinition.PASSWORD == (Integer) metatype.get("type")).forEach(metatype -> {
            String passwordProperty = (String) metatype.get("id");
            propertiesTable.put(passwordProperty, "password");
        });
        configData.put(MAP_ENTRY_PROPERTIES, propertiesTable);
        Map<String, Object> pluginDataMap = getConfigurationPluginData(configData.get(MAP_ENTRY_ID).toString(), Collections.unmodifiableMap(configData));
        if (pluginDataMap != null && !pluginDataMap.isEmpty()) {
            configData.putAll(pluginDataMap);
        }
        List<Map<String, Object>> configurations = null;
        if (service.containsKey(ENABLED_CONFIGURATION)) {
            configurations = (List<Map<String, Object>>) service.get(ENABLED_CONFIGURATION);
        } else if (service.containsKey(DISABLED_CONFIGURATION)) {
            configurations = (List<Map<String, Object>>) service.get(DISABLED_CONFIGURATION);
        } else {
            configurations = new ArrayList<Map<String, Object>>();
        }
        configurations.add(configData);
        if (((String) configData.get(MAP_ENTRY_ID)).contains(DISABLED_SERVICE_ID)) {
            configData.put(ENABLED, false);
        } else {
            configData.put(ENABLED, true);
        }
        service.put(ENABLED_CONFIGURATION, configurations);
    }
}
Also used : Constants(org.osgi.framework.Constants) Enumeration(java.util.Enumeration) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) MetaTypeInformation(org.osgi.service.metatype.MetaTypeInformation) ArrayList(java.util.ArrayList) Configuration(org.osgi.service.cm.Configuration) Locale(java.util.Locale) Map(java.util.Map) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) KeyValuePermission(ddf.security.permission.KeyValuePermission) IOException(java.io.IOException) AttributeDefinition(org.osgi.service.metatype.AttributeDefinition) Collectors(java.util.stream.Collectors) ConfigurationAdminPlugin(org.codice.ddf.ui.admin.api.plugin.ConfigurationAdminPlugin) BundleContext(org.osgi.framework.BundleContext) Sets(com.google.common.collect.Sets) MetaTypeService(org.osgi.service.metatype.MetaTypeService) List(java.util.List) Filter(org.osgi.framework.Filter) Entry(java.util.Map.Entry) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ManagedService(org.osgi.service.cm.ManagedService) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Collections(java.util.Collections) SecurityUtils(org.apache.shiro.SecurityUtils) FrameworkUtil(org.osgi.framework.FrameworkUtil) Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) HashMap(java.util.HashMap) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition)

Example 62 with Filter

use of org.osgi.framework.Filter in project ddf by codice.

the class ConfigurationAdminExt method getServices.

List<Map<String, Object>> getServices(String serviceClass, String serviceFilter, boolean ocdRequired) throws InvalidSyntaxException {
    List<Map<String, Object>> serviceList = new ArrayList<Map<String, Object>>();
    // find all ManagedServiceFactories to get the factoryPIDs
    ServiceReference[] refs = this.getBundleContext().getAllServiceReferences(serviceClass, serviceFilter);
    for (int i = 0; refs != null && i < refs.length; i++) {
        Object pidObject = refs[i].getProperty(Constants.SERVICE_PID);
        // only include valid PIDs
        if (pidObject instanceof String && isAllowedPid((String) pidObject)) {
            String pid = (String) pidObject;
            String name = pid;
            boolean haveOcd = !ocdRequired;
            final ObjectClassDefinition ocd = getObjectClassDefinition(refs[i].getBundle(), pid);
            if (ocd != null) {
                name = ocd.getName();
                haveOcd = true;
            }
            if (haveOcd) {
                Map<String, Object> service = new HashMap<String, Object>();
                service.put(MAP_ENTRY_ID, pid);
                service.put(MAP_ENTRY_NAME, name);
                serviceList.add(service);
            }
        }
    }
    return serviceList.stream().filter(service -> isPermittedToViewService((String) service.get("id"))).collect(Collectors.toList());
}
Also used : Constants(org.osgi.framework.Constants) Enumeration(java.util.Enumeration) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) MetaTypeInformation(org.osgi.service.metatype.MetaTypeInformation) ArrayList(java.util.ArrayList) Configuration(org.osgi.service.cm.Configuration) Locale(java.util.Locale) Map(java.util.Map) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServiceReference(org.osgi.framework.ServiceReference) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) KeyValuePermission(ddf.security.permission.KeyValuePermission) IOException(java.io.IOException) AttributeDefinition(org.osgi.service.metatype.AttributeDefinition) Collectors(java.util.stream.Collectors) ConfigurationAdminPlugin(org.codice.ddf.ui.admin.api.plugin.ConfigurationAdminPlugin) BundleContext(org.osgi.framework.BundleContext) Sets(com.google.common.collect.Sets) MetaTypeService(org.osgi.service.metatype.MetaTypeService) List(java.util.List) Filter(org.osgi.framework.Filter) Entry(java.util.Map.Entry) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ManagedService(org.osgi.service.cm.ManagedService) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Collections(java.util.Collections) SecurityUtils(org.apache.shiro.SecurityUtils) FrameworkUtil(org.osgi.framework.FrameworkUtil) Dictionary(java.util.Dictionary) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServiceReference(org.osgi.framework.ServiceReference) HashMap(java.util.HashMap) Map(java.util.Map) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition)

Example 63 with Filter

use of org.osgi.framework.Filter in project ddf by codice.

the class ConfigurationAdminExtTest method testListServicesExistingFilter.

/**
     * Tests the {@link ConfigurationAdminExt#listServices(String, String)} method for the case
     * where there is a filter returned by the bundleContext
     *
     * @throws Exception
     */
@Test
public void testListServicesExistingFilter() throws Exception {
    setUpTestConfig();
    setUpListServices();
    Filter testFilter = mock(Filter.class);
    List<ConfigurationAdminPlugin> testPluginList = new ArrayList<>();
    ConfigurationAdminPlugin testPlugin = mock(ConfigurationAdminPlugin.class);
    testPluginList.add(testPlugin);
    Map<String, Object> testConfigData = new HashMap<>();
    testConfigData.put(TEST_KEY, TEST_VALUE);
    when(testPlugin.getConfigurationData(anyString(), any(Map.class), any(BundleContext.class))).thenReturn(testConfigData);
    when(testFilter.match(any(Hashtable.class))).thenReturn(true);
    when(testBundleContext.createFilter(anyString())).thenReturn(testFilter);
    configurationAdminExt.setConfigurationAdminPluginList(testPluginList);
    List<Map<String, Object>> result = configurationAdminExt.listServices(TEST_FACT_FILTER, TEST_FILTER);
    assertThat("Should return the correct services.", (String) result.get(0).get("id"), is(TEST_PID));
    verify(testConfigAdmin, atLeastOnce()).listConfigurations(LIST_CONFIG_STRING);
}
Also used : Filter(org.osgi.framework.Filter) ConfigurationAdminPlugin(org.codice.ddf.ui.admin.api.plugin.ConfigurationAdminPlugin) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Mockito.anyString(org.mockito.Mockito.anyString) HashMap(java.util.HashMap) Map(java.util.Map) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 64 with Filter

use of org.osgi.framework.Filter 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 65 with Filter

use of org.osgi.framework.Filter in project sling by apache.

the class TenantProviderImpl method getTenants.

@Override
public Iterator<Tenant> getTenants(final String tenantFilter) {
    final Filter filter;
    if (tenantFilter != null && tenantFilter.length() > 0) {
        try {
            filter = FrameworkUtil.createFilter(tenantFilter);
        } catch (InvalidSyntaxException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    } else {
        filter = null;
    }
    Iterator<Tenant> result = call(new ResourceResolverTask<Iterator<Tenant>>() {

        @SuppressWarnings("unchecked")
        @Override
        public Iterator<Tenant> call(ResourceResolver resolver) {
            Resource tenantRootRes = resolver.getResource(tenantRootPath);
            if (tenantRootRes != null) {
                List<Tenant> tenantList = new ArrayList<Tenant>();
                Iterator<Resource> tenantResourceList = tenantRootRes.listChildren();
                while (tenantResourceList.hasNext()) {
                    Resource tenantRes = tenantResourceList.next();
                    if (filter == null || filter.matches(ResourceUtil.getValueMap(tenantRes))) {
                        TenantImpl tenant = new TenantImpl(tenantRes);
                        tenantList.add(tenant);
                    }
                }
                return tenantList.iterator();
            }
            return Collections.EMPTY_LIST.iterator();
        }
    });
    if (result == null) {
        // no filter or no resource resolver for calling
        result = Collections.<Tenant>emptyList().iterator();
    }
    return result;
}
Also used : Resource(org.apache.sling.api.resource.Resource) Tenant(org.apache.sling.tenant.Tenant) Filter(org.osgi.framework.Filter) Iterator(java.util.Iterator) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Filter (org.osgi.framework.Filter)167 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)63 ServiceTracker (org.osgi.util.tracker.ServiceTracker)42 ArrayList (java.util.ArrayList)41 ServiceReference (org.osgi.framework.ServiceReference)36 BundleContext (org.osgi.framework.BundleContext)27 Hashtable (java.util.Hashtable)25 List (java.util.List)23 Bundle (org.osgi.framework.Bundle)21 Dictionary (java.util.Dictionary)20 HashMap (java.util.HashMap)17 Test (org.junit.Test)17 Map (java.util.Map)15 IOException (java.io.IOException)9 Iterator (java.util.Iterator)9 Properties (java.util.Properties)8 SharePolicy (org.apache.aries.subsystem.scope.SharePolicy)7 Configuration (org.osgi.service.cm.Configuration)7 URL (java.net.URL)6 Collection (java.util.Collection)6