Search in sources :

Example 26 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 27 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)

Example 28 with Filter

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

the class ManagedSiteComponent method activate.

/**
     * Activates this {@link ManagedSiteComponent}. This might be overridden to
     * perform additional configuration. In such cases super should be called
     * before the additional configuration steps.
     * @param context
     * @throws ConfigurationException
     * @throws YardException
     * @throws InvalidSyntaxException
     */
@Activate
protected void activate(final ComponentContext context) throws ConfigurationException, YardException, InvalidSyntaxException {
    this.bundleContext = context.getBundleContext();
    //NOTE that the constructor also validation of the parsed configuration
    this.siteConfiguration = new ManagedSiteConfigurationImpl(context.getProperties());
    if (PROHIBITED_SITE_IDS.contains(siteConfiguration.getId().toLowerCase())) {
        throw new ConfigurationException(SiteConfiguration.ID, String.format("The ID '%s' of this Referenced Site is one of the following " + "prohibited IDs: {} (case insensitive)", siteConfiguration.getId(), PROHIBITED_SITE_IDS));
    }
    log.info(" > initialise Managed Site {}", siteConfiguration.getId());
    SiteUtils.extractSiteMetadata(siteConfiguration, InMemoryValueFactory.getInstance());
    //Initialise the Yard
    final String yardId = siteConfiguration.getYardId();
    String yardFilterString = String.format("(&(%s=%s)(%s=%s))", Constants.OBJECTCLASS, Yard.class.getName(), Yard.ID, yardId);
    Filter yardFilter = bundleContext.createFilter(yardFilterString);
    yardTracker = new ServiceTracker(bundleContext, yardFilter, new ServiceTrackerCustomizer() {

        @Override
        public void removedService(ServiceReference reference, Object service) {
            synchronized (yardReferenceLock) {
                if (reference.equals(yardReference)) {
                    deactivateManagedSite();
                    yardReference = null;
                }
                bundleContext.ungetService(reference);
            }
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
        }

        @Override
        public Object addingService(ServiceReference reference) {
            Yard yard = (Yard) bundleContext.getService(reference);
            synchronized (yardReferenceLock) {
                if (yardReference == null) {
                    if (yard != null) {
                        activateManagedSite(yard);
                        yardReference = reference;
                    } else {
                        log.warn("Unable to addService for ServiceReference because" + "unable to obtain referenced Yard via the BundleContext!");
                    }
                } else {
                    log.warn("Tracking two Yard instances with the Yard ID '{}' " + "configured for ManagedSite '{}'", yardId, siteConfiguration.getId());
                    log.warn("used  : {}", yardReference.getProperty(Constants.SERVICE_PID));
                    log.warn("unused: {}", reference.getProperty(Constants.SERVICE_PID));
                }
            }
            return yard;
        }
    });
    yardTracker.open();
//will be moved to a Solr specific implementation
//        //chaeck if we are allowed to init an yard with the provided id
//        boolean allowInit = false;
//        if(configAdmin!= null){
//            Configuration[] configs;
//            try {
//                String yardIdFilter = String.format("(%s=%s)",
//                    Yard.ID,yardId);
//                configs = configAdmin.listConfigurations(yardIdFilter);
//                if(configs == null || configs.length < 1){
//                    allowInit = true;
//                }
//            } catch (IOException e) {
//                log.warn("Unable to access ManagedService configurations ",e);
//            }
//        } else if (yardTracker.getService() == null){
//            log.warn("Unable to check for Yard configuration of ManagedSite {} "
//                + "Because the ConfigurationAdmin service is not available");
//            log.warn(" -> unable to create YardConfiguration");
//        }
//        if(allowInit){
//            //TODO: This has SolrYard specific code - this needs to be refactored
//            String factoryPid = "org.apache.stanbol.entityhub.yard.solr.impl.SolrYard";
//            try {
//                Configuration config = configAdmin.createFactoryConfiguration(factoryPid,null);
//                //configure the required properties
//                Dictionary<String,Object> yardConfig = new Hashtable<String,Object>();
//                yardConfig.put(Yard.ID, siteConfiguration.getYardId());
//                yardConfig.put(Yard.NAME, siteConfiguration.getYardId());
//                yardConfig.put(Yard.DESCRIPTION, "Yard for the ManagedSite "+siteConfiguration.getId());
//                yardConfig.put("org.apache.stanbol.entityhub.yard.solr.solrUri", siteConfiguration.getId());
//                yardConfig.put("org.apache.stanbol.entityhub.yard.solr.useDefaultConfig", true);
//                config.update(yardConfig); //this create the solrYard
//            } catch (IOException e) {
//                log.warn("Unable to create SolrYard configuration for MnagedSite "+siteConfiguration.getId(),e);
//            }
//        }
}
Also used : Yard(org.apache.stanbol.entityhub.servicesapi.yard.Yard) ConfigurationException(org.osgi.service.cm.ConfigurationException) Filter(org.osgi.framework.Filter) ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) ServiceReference(org.osgi.framework.ServiceReference) Activate(org.apache.felix.scr.annotations.Activate)

Example 29 with Filter

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

the class DataSourceIT method testDataSourceAsService.

@SuppressWarnings("unchecked")
@Test
public void testDataSourceAsService() throws Exception {
    Configuration config = ca.createFactoryConfiguration(PID, null);
    Dictionary<String, Object> p = new Hashtable<String, Object>();
    p.put("url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    p.put("datasource.name", "test");
    p.put("initialSize", "5");
    p.put("defaultAutoCommit", "default");
    p.put("defaultReadOnly", "false");
    p.put("datasource.svc.properties", new String[] { "initSQL=SELECT 1" });
    p.put("maxActive", 70);
    config.update(p);
    Filter filter = context.createFilter("(&(objectclass=javax.sql.DataSource)(datasource.name=test))");
    ServiceTracker<DataSource, DataSource> st = new ServiceTracker<DataSource, DataSource>(context, filter, null);
    st.open();
    DataSource ds = st.waitForService(10000);
    assertNotNull(ds);
    Connection conn = ds.getConnection();
    assertNotNull(conn);
    //Cannot access directly so access via reflection
    assertEquals("70", getProperty(ds, "poolProperties.maxActive"));
    assertEquals("5", getProperty(ds, "poolProperties.initialSize"));
    assertEquals("SELECT 1", getProperty(ds, "poolProperties.initSQL"));
    assertEquals("false", getProperty(ds, "poolProperties.defaultReadOnly"));
    assertNull(getProperty(ds, "poolProperties.defaultAutoCommit"));
    config = ca.listConfigurations("(datasource.name=test)")[0];
    Dictionary dic = config.getProperties();
    dic.put("defaultReadOnly", Boolean.TRUE);
    config.update(dic);
    TimeUnit.MILLISECONDS.sleep(100);
    assertEquals("true", getProperty(ds, "poolProperties.defaultReadOnly"));
}
Also used : Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) Filter(org.osgi.framework.Filter) ServiceTracker(org.osgi.util.tracker.ServiceTracker) Hashtable(java.util.Hashtable) Connection(java.sql.Connection) DataSource(javax.sql.DataSource) Test(org.junit.Test)

Example 30 with Filter

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

the class MockBundleContextTest method testObjectClassFilterMatches.

@Test
public void testObjectClassFilterMatches() throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(" + Constants.OBJECTCLASS + "=" + Integer.class.getName() + ")");
    ServiceRegistration serviceRegistration = bundleContext.registerService(Integer.class.getName(), Integer.valueOf(1), null);
    assertTrue(filter.match(serviceRegistration.getReference()));
}
Also used : Filter(org.osgi.framework.Filter) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

Aggregations

Filter (org.osgi.framework.Filter)81 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)31 ServiceTracker (org.osgi.util.tracker.ServiceTracker)29 ArrayList (java.util.ArrayList)22 ServiceReference (org.osgi.framework.ServiceReference)20 Hashtable (java.util.Hashtable)18 Test (org.junit.Test)14 BundleContext (org.osgi.framework.BundleContext)13 List (java.util.List)12 Bundle (org.osgi.framework.Bundle)11 Dictionary (java.util.Dictionary)9 SharePolicy (org.apache.aries.subsystem.scope.SharePolicy)9 Configuration (org.osgi.service.cm.Configuration)9 HashMap (java.util.HashMap)7 Map (java.util.Map)6 IOException (java.io.IOException)5 URL (java.net.URL)5 InstallInfo (org.apache.aries.subsystem.scope.InstallInfo)5 ScopeUpdate (org.apache.aries.subsystem.scope.ScopeUpdate)5 Iterator (java.util.Iterator)4