Search in sources :

Example 66 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)

Example 67 with Filter

use of org.osgi.framework.Filter in project cytoscape-api by cytoscape.

the class CyServiceListenerTest method testCyServiceListenerTest.

@Before
public void testCyServiceListenerTest() throws Exception {
    String additionalFilter = "dummy filter";
    String filter = "(&" + "(" + Constants.OBJECTCLASS + "=" + DummyServiceInterface.class.getName() + ")" + additionalFilter + ")";
    bc = mock(BundleContext.class);
    Filter f = mock(Filter.class);
    when(bc.createFilter(filter)).thenReturn(f);
    service = new DummyServiceClass();
    ref = mock(ServiceReference.class);
    when(ref.getPropertyKeys()).thenReturn(new String[] { "" });
    when(ref.getProperty("")).thenReturn(new Properties());
    when(bc.getService(ref)).thenReturn((Object) service);
    target = new DummyListener();
    sl = new CyServiceListener<>(bc, target, "add", "remove", DummyServiceInterface.class, DummyServiceInterface.class, additionalFilter);
}
Also used : Filter(org.osgi.framework.Filter) Properties(java.util.Properties) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference) Before(org.junit.Before)

Example 68 with Filter

use of org.osgi.framework.Filter in project bnd by bndtools.

the class RepoIndex method generateResource.

private Tag generateResource(File file, Map<String, String> config) throws Exception {
    JarResource resource = new JarResource(file);
    List<Capability> caps = new AddOnlyList<Capability>(new LinkedList<Capability>());
    List<Requirement> reqs = new AddOnlyList<Requirement>(new LinkedList<Requirement>());
    Tag resourceTag = new Tag(Schema.ELEM_RESOURCE);
    try {
        // Read config settings and save in thread local state
        if (config != null) {
            URL rootURL;
            String rootURLStr = config.get(ResourceIndexer.ROOT_URL);
            if (rootURLStr != null) {
                File rootDir = new File(rootURLStr);
                if (rootDir.isDirectory())
                    rootURL = rootDir.toURI().toURL();
                else
                    rootURL = new URL(rootURLStr);
            } else
                rootURL = new File(System.getProperty("user.dir")).toURI().toURL();
            String urlTemplate = config.get(ResourceIndexer.URL_TEMPLATE);
            bundleAnalyzer.setStateLocal(new GeneratorState(rootURL.toURI().normalize(), urlTemplate, resolvers));
        } else {
            bundleAnalyzer.setStateLocal(null);
        }
        // Iterate over the analyzers
        try {
            synchronized (analyzers) {
                for (Pair<ResourceAnalyzer, Filter> entry : analyzers) {
                    ResourceAnalyzer analyzer = entry.getFirst();
                    Filter filter = entry.getSecond();
                    if (filter == null || filter.match(resource.getProperties())) {
                        try {
                            analyzer.analyzeResource(resource, caps, reqs);
                        } catch (Exception e) {
                            log(LogService.LOG_ERROR, MessageFormat.format("Error calling analyzer \"{0}\" on resource {1}.", analyzer.getClass().getName(), resource.getLocation()), e);
                            StringWriter writer = new StringWriter();
                            Formatter comment = new Formatter(writer);
                            comment.format("Error calling analyzer \"%s\" on resource %s with message %s and stack: ", analyzer.getClass().getName(), resource.getLocation(), e);
                            comment.close();
                            e.printStackTrace(new PrintWriter(writer));
                            resourceTag.addComment(writer.toString());
                        }
                    }
                }
            }
        } finally {
            bundleAnalyzer.setStateLocal(null);
        }
    } finally {
        resource.close();
    }
    for (Capability cap : caps) {
        Tag capTag = new Tag(Schema.ELEM_CAPABILITY);
        capTag.addAttribute(Schema.ATTR_NAMESPACE, cap.getNamespace());
        appendAttributeAndDirectiveTags(capTag, cap.getAttributes(), cap.getDirectives());
        resourceTag.addContent(capTag);
    }
    for (Requirement req : reqs) {
        Tag reqTag = new Tag(Schema.ELEM_REQUIREMENT);
        reqTag.addAttribute(Schema.ATTR_NAMESPACE, req.getNamespace());
        appendAttributeAndDirectiveTags(reqTag, req.getAttributes(), req.getDirectives());
        resourceTag.addContent(reqTag);
    }
    return resourceTag;
}
Also used : ResourceAnalyzer(org.osgi.service.indexer.ResourceAnalyzer) Capability(org.osgi.service.indexer.Capability) Formatter(java.util.Formatter) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Requirement(org.osgi.service.indexer.Requirement) AddOnlyList(org.osgi.service.indexer.impl.util.AddOnlyList) StringWriter(java.io.StringWriter) Filter(org.osgi.framework.Filter) FrameworkUtil.createFilter(org.osgi.framework.FrameworkUtil.createFilter) Tag(org.osgi.service.indexer.impl.util.Tag) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 69 with Filter

use of org.osgi.framework.Filter in project bndtools by bndtools.

the class ArbitraryNamespaceSearchPanel method validate.

private void validate() {
    try {
        if (namespace == null || namespace.length() == 0) {
            setError(null);
            setRequirement(null);
            return;
        }
        for (int i = 0; i < namespace.length(); i++) {
            char c = namespace.charAt(i);
            if ('.' == c) {
                if (i == 0 || i == namespace.length() - 1)
                    throw new IllegalArgumentException("Namespace cannot have leading or trailing '.' character");
                else if ('.' == namespace.charAt(i - 1))
                    throw new IllegalArgumentException("Namespace cannot have repeated '.' characters");
            } else if (!Character.isLetterOrDigit(c) && c != '-' && c != '_')
                throw new IllegalArgumentException(String.format("Invalid character in namespace: '%c'", c));
        }
        updateFilterExpressionHint(namespace);
        CapReqBuilder builder = new CapReqBuilder(namespace);
        if (filterStr != null && filterStr.trim().length() > 0) {
            try {
                Filter filter = FrameworkUtil.createFilter(filterStr.trim());
                builder.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString());
            } catch (InvalidSyntaxException e) {
                throw new IllegalArgumentException("Invalid filter string: " + e.getMessage());
            }
        }
        setRequirement(builder.buildSyntheticRequirement());
        setError(null);
    } catch (Exception e) {
        setError(e.getMessage());
        setRequirement(null);
    }
}
Also used : CapReqBuilder(aQute.bnd.osgi.resource.CapReqBuilder) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException)

Example 70 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)

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