org.osgi.framework.Filter

Here are the examples of the java api class org.osgi.framework.Filter taken from open source projects.

1. EndpointDescription#matches()

Project: karaf-cellar
File: EndpointDescription.java
/**
     * Tests the properties of this <code>EndpointDescription</code> against
     * the given filter using a case insensitive match.
     *
     * @param filter The filter to test.
     * @return <code>true</code> If the properties of this
     *         <code>EndpointDescription</code> match the filter,
     *         <code>false</code> otherwise.
     * @throws IllegalArgumentException If <code>filter</code> contains an
     *                                  invalid filter string that cannot be parsed.
     */
public boolean matches(String filter) {
    Filter f;
    try {
        f = FrameworkUtil.createFilter(filter);
    } catch (InvalidSyntaxException e) {
        IllegalArgumentException iae = new IllegalArgumentException(e.getMessage());
        iae.initCause(e);
        throw iae;
    }
    Dictionary dictionary = new Properties();
    for (Map.Entry<String, Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        dictionary.put(key, value);
    }
    /*
           * we can use matchCase here since properties already supports case
           * insensitive key lookup.
           */
    return f.matchCase(dictionary);
}

2. EnOceanBaseDriver#registerServiceFrom()

Project: smarthome
File: EnOceanBaseDriver.java
/* The functions that come below are used to register the necessary services */
private ServiceTracker registerServiceFrom(BundleContext bundleContext, Class objectClass, ServiceTrackerCustomizer listener) {
    String filter = "(objectClass=" + (objectClass).getName() + ')';
    Filter deviceAdminFilter;
    try {
        deviceAdminFilter = bundleContext.createFilter(filter);
    } catch (InvalidSyntaxException e) {
        Logger.e(TAG, e.getMessage());
        return null;
    }
    ServiceTracker serviceTracker = new ServiceTracker(bundleContext, deviceAdminFilter, listener);
    serviceTracker.open();
    return serviceTracker;
}

3. AdapterManagerTest#createMultipleAdaptersComponentContext()

Project: sling
File: AdapterManagerTest.java
/**
     * Helper method to create a mock component context
     */
protected ComponentContext createMultipleAdaptersComponentContext(final ServiceReference firstServiceReference, final ServiceReference secondServiceReference) throws Exception {
    final BundleContext bundleCtx = this.context.mock(BundleContext.class);
    final Filter filter = this.context.mock(Filter.class);
    final ComponentContext ctx = this.context.mock(ComponentContext.class);
    this.context.checking(new Expectations() {

        {
            allowing(ctx).locateService(with(any(String.class)), with(firstServiceReference));
            will(returnValue(new FirstImplementationAdapterFactory()));
            allowing(ctx).locateService(with(any(String.class)), with(secondServiceReference));
            will(returnValue(new SecondImplementationAdapterFactory()));
            allowing(ctx).getBundleContext();
            will(returnValue(bundleCtx));
            allowing(bundleCtx).createFilter(with(any(String.class)));
            will(returnValue(filter));
            allowing(bundleCtx).addServiceListener(with(any(ServiceListener.class)), with(any(String.class)));
            allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(any(String.class)));
            will(returnValue(null));
            allowing(bundleCtx).removeServiceListener(with(any(ServiceListener.class)));
            allowing(bundleCtx).registerService(with(Adaption.class.getName()), with(AdaptionImpl.INSTANCE), with(any(Dictionary.class)));
            will(returnValue(null));
        }
    });
    return ctx;
}

4. AdapterManagerTest#createComponentContext()

Project: sling
File: AdapterManagerTest.java
/**
     * Helper method to create a mock component context
     */
protected ComponentContext createComponentContext() throws Exception {
    final BundleContext bundleCtx = this.context.mock(BundleContext.class);
    final Filter filter = this.context.mock(Filter.class);
    final ComponentContext ctx = this.context.mock(ComponentContext.class);
    this.context.checking(new Expectations() {

        {
            allowing(ctx).locateService(with(any(String.class)), with(any(ServiceReference.class)));
            will(returnValue(new MockAdapterFactory()));
            allowing(ctx).getBundleContext();
            will(returnValue(bundleCtx));
            allowing(bundleCtx).createFilter(with(any(String.class)));
            will(returnValue(filter));
            allowing(bundleCtx).addServiceListener(with(any(ServiceListener.class)), with(any(String.class)));
            allowing(bundleCtx).getServiceReferences(with(any(String.class)), with(any(String.class)));
            will(returnValue(null));
            allowing(bundleCtx).removeServiceListener(with(any(ServiceListener.class)));
            allowing(bundleCtx).registerService(with(Adaption.class.getName()), with(AdaptionImpl.INSTANCE), with(any(Dictionary.class)));
            will(returnValue(null));
        }
    });
    return ctx;
}

5. AdapterWebConsolePlugin#activate()

Project: sling
File: AdapterWebConsolePlugin.java
protected void activate(final ComponentContext ctx) throws InvalidSyntaxException {
    this.bundleContext = ctx.getBundleContext();
    this.adapterServiceReferences = new HashMap<ServiceReference, List<AdaptableDescription>>();
    this.adapterBundles = new HashMap<Bundle, List<AdaptableDescription>>();
    for (final Bundle bundle : this.bundleContext.getBundles()) {
        if (bundle.getState() == Bundle.ACTIVE) {
            addBundle(bundle);
        }
    }
    this.bundleContext.addBundleListener(this);
    final Filter filter = this.bundleContext.createFilter("(&(adaptables=*)(adapters=*)(" + Constants.OBJECTCLASS + "=" + AdapterFactory.SERVICE_NAME + "))");
    this.adapterTracker = new ServiceTracker(this.bundleContext, filter, this);
    this.adapterTracker.open();
}

6. HashedWheelTimerModuleTest#setUp()

Project: controller
File: HashedWheelTimerModuleTest.java
@SuppressWarnings({ "rawtypes", "unchecked" })
@Before
public void setUp() throws Exception {
    factory = new HashedWheelTimerModuleFactory();
    threadFactory = new NamingThreadFactoryModuleFactory();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory, threadFactory));
    Filter mockFilter = mock(Filter.class);
    doReturn("mock").when(mockFilter).toString();
    doReturn(mockFilter).when(mockedContext).createFilter(anyString());
    doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
    ServiceReference mockServiceRef = mock(ServiceReference.class);
    doReturn(new ServiceReference[] { mockServiceRef }).when(mockedContext).getServiceReferences(anyString(), anyString());
    doReturn(mock(Timer.class)).when(mockedContext).getService(mockServiceRef);
}

7. NettyThreadgroupModuleTest#setUp()

Project: controller
File: NettyThreadgroupModuleTest.java
@SuppressWarnings({ "rawtypes", "unchecked" })
@Before
public void setUp() throws Exception {
    factory = new NettyThreadgroupModuleFactory();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
    Filter mockFilter = mock(Filter.class);
    doReturn("mock").when(mockFilter).toString();
    doReturn(mockFilter).when(mockedContext).createFilter(anyString());
    doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
    ServiceReference mockServiceRef = mock(ServiceReference.class);
    doReturn(new ServiceReference[] { mockServiceRef }).when(mockedContext).getServiceReferences(anyString(), anyString());
    doReturn(mock(EventLoopGroup.class)).when(mockedContext).getService(mockServiceRef);
}

8. GlobalEventExecutorModuleTest#setUp()

Project: controller
File: GlobalEventExecutorModuleTest.java
@SuppressWarnings({ "rawtypes", "unchecked" })
@Before
public void setUp() throws Exception {
    factory = new GlobalEventExecutorModuleFactory();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
    Filter mockFilter = mock(Filter.class);
    doReturn("mock").when(mockFilter).toString();
    doReturn(mockFilter).when(mockedContext).createFilter(anyString());
    doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
    ServiceReference mockServiceRef = mock(ServiceReference.class);
    doReturn(new ServiceReference[] { mockServiceRef }).when(mockedContext).getServiceReferences(anyString(), anyString());
    doReturn(mock(EventExecutor.class)).when(mockedContext).getService(mockServiceRef);
}

9. StaticConfigurationAdmin#listConfigurations()

Project: bnd
File: StaticConfigurationAdmin.java
@Override
public Configuration[] listConfigurations(String filterStr) throws IOException, InvalidSyntaxException {
    Filter filter = filterStr != null ? FrameworkUtil.createFilter(filterStr) : null;
    List<StaticConfiguration> result = new ArrayList<StaticConfiguration>(configsMap.size());
    for (StaticConfiguration config : configsMap.values()) {
        if (filter == null || filter.match(config.getProperties()))
            result.add(config);
    }
    return result.toArray(new Configuration[0]);
}

10. AbstractJPATransactionTest#getService()

Project: aries
File: AbstractJPATransactionTest.java
private <T> T getService(Class<T> clazz, String filter, long timeout) throws InvalidSyntaxException {
    Filter f = FrameworkUtil.createFilter(filter == null ? "(|(foo=bar)(!(foo=bar)))" : filter);
    ServiceTracker<T, T> tracker = new ServiceTracker<T, T>(context, clazz, null) {

        @Override
        public T addingService(ServiceReference<T> reference) {
            return f.match(reference) ? super.addingService(reference) : null;
        }
    };
    tracker.open();
    try {
        T t = tracker.waitForService(timeout);
        if (t == null) {
            throw new NoSuchElementException(clazz.getName());
        }
        return t;
    } catch (InterruptedException e) {
        throw new RuntimeException("Error waiting for service " + clazz.getName(), e);
    } finally {
        trackers.add(tracker);
    }
}

11. AbstractTransactionTest#getService()

Project: aries
File: AbstractTransactionTest.java
private <T> T getService(Class<T> clazz, String filter, long timeout) throws InvalidSyntaxException {
    Filter f = FrameworkUtil.createFilter(filter == null ? "(|(foo=bar)(!(foo=bar)))" : filter);
    ServiceTracker<T, T> tracker = new ServiceTracker<T, T>(context, clazz, null) {

        @Override
        public T addingService(ServiceReference<T> reference) {
            return f.match(reference) ? super.addingService(reference) : null;
        }
    };
    tracker.open();
    try {
        T t = tracker.waitForService(timeout);
        if (t == null) {
            throw new NoSuchElementException(clazz.getName());
        }
        return t;
    } catch (InterruptedException e) {
        throw new RuntimeException("Error waiting for service " + clazz.getName(), e);
    } finally {
        trackers.add(tracker);
    }
}

12. Activator#start()

Project: aries
File: Activator.java
public void start(BundleContext ctx) {
    context = ctx;
    // Expose blueprint namespace handler if xbean is present
    try {
        nshReg = JdbcNamespaceHandler.register(ctx);
    } catch (NoClassDefFoundError e) {
        LOGGER.warn("Unable to register JDBC blueprint namespace handler (xbean-blueprint not available).");
    } catch (Exception e) {
        LOGGER.error("Unable to register JDBC blueprint namespace handler", e);
    }
    Filter filter;
    String flt = "(&(|(objectClass=javax.sql.XADataSource)(objectClass=javax.sql.DataSource))(!(aries.managed=true)))";
    try {
        filter = context.createFilter(flt);
    } catch (InvalidSyntaxException e) {
        throw new IllegalStateException(e);
    }
    t = new ServiceTracker<CommonDataSource, ManagedDataSourceFactory>(ctx, filter, this);
    tm = new SingleServiceTracker<AriesTransactionManager>(ctx, AriesTransactionManager.class, this);
    tm.open();
}

13. Activator#start()

Project: aries
File: Activator.java
@Override
public void start(BundleContext context) throws Exception {
    Filter filter = context.createFilter("(&(objectClass=java.lang.String)(test=testCompositeServiceImports))");
    st = new ServiceTracker<String, String>(context, filter, null);
    st.open();
    String svc = st.waitForService(5000);
    if ("testCompositeServiceImports".equals(svc)) {
        Dictionary<String, Object> props = new Hashtable<String, Object>();
        props.put("test", "tb4");
        context.registerService(String.class, "tb4", props);
    }
}

14. Activator#start()

Project: aries
File: Activator.java
public void start(BundleContext context) throws Exception {
    ctx = context;
    logger = new Logger(ctx);
    Filter filter = getFilter(context, PACKAGE_ADMIN, START_LEVEL, PERMISSION_ADMIN, CONFIG_ADMIN, USER_ADMIN, PROVISIONING_SERVICE);
    tracker = new ServiceTracker(context, filter, this);
    tracker.open();
    stateConfig = StateConfig.register(context);
    registerMBean(ServiceStateMBean.class.getName(), new Factory<ServiceStateMBean>() {

        public ServiceStateMBean create() {
            return new ServiceState(ctx, stateConfig, logger);
        }
    }, ServiceStateMBean.OBJECTNAME, _serviceStateMbean);
}

15. Activator#start()

Project: apache-aries
File: Activator.java
public void start(BundleContext ctx) {
    context = ctx;
    // Expose blueprint namespace handler if xbean is present
    try {
        nshReg = JdbcNamespaceHandler.register(ctx);
    } catch (NoClassDefFoundError e) {
        LOGGER.warn("Unable to register JDBC blueprint namespace handler (xbean-blueprint not available).");
    } catch (Exception e) {
        LOGGER.error("Unable to register JDBC blueprint namespace handler", e);
    }
    Filter filter;
    String flt = "(&(|(objectClass=javax.sql.XADataSource)(objectClass=javax.sql.DataSource))(!(aries.managed=true)))";
    try {
        filter = context.createFilter(flt);
    } catch (InvalidSyntaxException e) {
        throw new IllegalStateException(e);
    }
    t = new ServiceTracker<CommonDataSource, ManagedDataSourceFactory>(ctx, filter, this);
    tm = new SingleServiceTracker<AriesTransactionManager>(ctx, AriesTransactionManager.class, this);
    tm.open();
}

16. Activator#start()

Project: apache-aries
File: Activator.java
@Override
public void start(BundleContext context) throws Exception {
    Filter filter = context.createFilter("(&(objectClass=java.lang.String)(test=testCompositeServiceImports))");
    st = new ServiceTracker<String, String>(context, filter, null);
    st.open();
    String svc = st.waitForService(5000);
    if ("testCompositeServiceImports".equals(svc)) {
        Dictionary<String, Object> props = new Hashtable<String, Object>();
        props.put("test", "tb4");
        context.registerService(String.class, "tb4", props);
    }
}

17. Activator#start()

Project: apache-aries
File: Activator.java
public void start(BundleContext context) throws Exception {
    ctx = context;
    logger = new Logger(ctx);
    Filter filter = getFilter(context, PACKAGE_ADMIN, START_LEVEL, PERMISSION_ADMIN, CONFIG_ADMIN, USER_ADMIN, PROVISIONING_SERVICE);
    tracker = new ServiceTracker(context, filter, this);
    tracker.open();
    stateConfig = StateConfig.register(context);
    registerMBean(ServiceStateMBean.class.getName(), new Factory<ServiceStateMBean>() {

        public ServiceStateMBean create() {
            return new ServiceState(ctx, stateConfig, logger);
        }
    }, ServiceStateMBean.OBJECTNAME, _serviceStateMbean);
}

18. ScopeAdminTest#createScope()

Project: aries
File: ScopeAdminTest.java
//    @org.ops4j.pax.exam.junit.Configuration
//    public static Option[] configuration() {
//        Option[] options = options(
//            // Log
//            mavenBundle("org.ops4j.pax.logging", "pax-logging-api"),
//            mavenBundle("org.ops4j.pax.logging", "pax-logging-service"),
//            // Felix Config Admin
//            mavenBundle("org.apache.felix", "org.apache.felix.configadmin"),
//            // Felix mvn url handler
//            mavenBundle("org.ops4j.pax.url", "pax-url-mvn"),
//
//
//            // this is how you set the default log level when using pax logging (logProfile)
//            systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"),
//
//            // Bundles
//            mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit"),
//            mavenBundle("org.apache.aries.application", "org.apache.aries.application.api"),
//            mavenBundle("org.apache.aries", "org.apache.aries.util"),
//            mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils"),
//            mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.api"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.impl"),
//
//            // org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"),
//
//            PaxRunnerOptions.rawPaxRunnerOption("config", "classpath:ss-runner.properties"),
//
//            equinox().version("3.7.0.v20110221")
//        );
//        options = updateOptions(options);
//        return options;
//    }
private Scope createScope(Scope scope, String scopeName, String loc, String version) throws MalformedURLException, InvalidSyntaxException, BundleException, IOException {
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild(scopeName);
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + "(version=" + version + ")" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info1 = new InstallInfo("helloIsolation_" + scopeName, new URL(loc));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info1);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        b.start();
    }
    return childScopeUpdate.getScope();
}

19. ScopeAdminTest#testScopeAffinity()

Project: aries
File: ScopeAdminTest.java
// test ability to select the helloIsolation package from which scope it wants to use
// not necessarily the highest version one by default.
@Test
@Ignore
public void testScopeAffinity() throws Exception {
    // install helloIsolation 0.3 in scope_test1
    Scope scope1 = createScope(scope, "scope_test1", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "0.3");
    // install helloIsolation 2.0 in scope_test2
    Scope scope2 = createScope(scope, "scope_test2", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "2.0");
    // install helloIsolationRef 2.0 in scope_test3
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test3");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    Scope scope3 = childScopeUpdate.getScope();
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    /*final Filter filter1 = FrameworkUtil.createFilter(
                "(&" + 
                  "(osgi.package=org.apache.aries.subsystem.example.helloIsolation)" +
                  "(bundle-symbolic-name=org.apache.aries.subsystem.example.helloIsolation)" + 
                  "(bundle-version<=1.1)" + 
                ")");*/
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + //"(scopeName=scope_test1)" +  
    ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test3
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        try {
            b.start();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("should be able to start helloIsolationRef in scope_test1");
        }
    }
    /*  // install helloIsolationRef in root scope
        URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT");
        Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream());
   
        try {
            helloIsolationRef.start();
        } catch (Exception ex) {
            fail("should be able to start helloIsolationRef");
        }*/
    // remove child scope - cleanup
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    scopes.clear();
    //        scopes.add(scope1);
    //        scopes.add(scope2);
    //        scopes.add(scope3);
    su.commit();
    assertTrue(scope.getChildren().isEmpty());
    assertTrue(scope.newScopeUpdate().getChildren().isEmpty());
}

20. ScopeAdminTest#testPackageSharingFromRootScope()

Project: aries
File: ScopeAdminTest.java
// test sharing the helloIsolation package & service from the root scope.
@Test
public void testPackageSharingFromRootScope() throws Exception {
    // install helloIsolationRef1 bundle in the root scope
    URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT");
    Bundle helloIsolation = bundleContext.installBundle("helloIsolation1-rootScope", url1.openStream());
    try {
        helloIsolation.start();
    } catch (Exception ex) {
        fail("should be able to start helloIsolation");
    }
    // make sure we are using a framework that provides composite admin service
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test1");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        try {
            b.start();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("should be able to start helloIsolationRef in scope_test1");
        }
    }
    // remove helloIsolation in root scope
    helloIsolation.uninstall();
    // remove child scope
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    childScopeUpdate = scopes.iterator().next();
    // obtain child scope admin from service registry
    //        String filter = "ScopeName=scope_test1";
    Scope childScopeAdmin = childScopeUpdate.getScope();
    assertEquals(scope, childScopeAdmin.getParent());
    scopes.remove(childScopeUpdate);
    su.commit();
    assertFalse(scope.getChildren().contains(childScopeAdmin));
    su = scope.newScopeUpdate();
    assertFalse(su.getChildren().contains(childScopeUpdate));
//        childScopeAdmin = null;
//        try {
//            childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT);
//        } catch (Exception ex) {
//            // ignore
//        }
//        assertNull("scope admin service for the scope should be unregistered", childScopeAdmin);
}

21. ScopeAdminTest#testPackageSharingFromTestScope()

Project: aries
File: ScopeAdminTest.java
// test sharing the helloIsolation package from the test scope.
@Test
@Ignore
public void testPackageSharingFromTestScope() throws Exception {
    // make sure we are using a framework that provides composite admin service
    assertNotNull("scope admin should not be null", scope);
    System.out.println("able to get scope admin service");
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test1");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT"));
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info1);
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        b.start();
    }
    // install helloIsolationRef1 bundle in the root scope
    URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT");
    Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream());
    try {
        helloIsolationRef.start();
    } catch (Exception ex) {
        fail("should be able to start helloIsolationRef by import packages from scope_test1");
    }
    // remove helloIsolationRef
    helloIsolationRef.uninstall();
    // remove child scope
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    childScopeUpdate = scopes.iterator().next();
    // obtain child scope admin from service registry
    //        String filter = "ScopeName=scope_test1";
    Scope childScopeAdmin = childScopeUpdate.getScope();
    assertEquals(scope, childScopeAdmin.getParent());
    scopes.remove(childScopeUpdate);
    su.commit();
    assertFalse(scope.getChildren().contains(childScopeAdmin));
    su = scope.newScopeUpdate();
    assertFalse(su.getChildren().contains(childScopeUpdate));
//        childScopeAdmin = null;
//        try {
//            childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT);
//        } catch (Exception ex) {
//            // ignore
//        }
//        assertNull("scope admin service for the scope should be unregistered", childScopeAdmin);
}

22. ConfigAdminPropsFileContentHandlerTest#testAries1352()

Project: aries
File: ConfigAdminPropsFileContentHandlerTest.java
@Test
public void testAries1352() throws Exception {
    // Same test than testConfigurationContentHandler, but an existing
    // configuration exists before the subsystem is installed.
    // The configuration should not be overwritten by the subsystem
    // installation.
    ConfigurationAdmin cm = bundleContext.getService(bundleContext.getServiceReference(ConfigurationAdmin.class));
    Configuration blahConf = cm.getConfiguration("com.blah.Blah", "?");
    Dictionary<String, Object> blahProps = new Hashtable<String, Object>(1);
    blahProps.put("configVal", "Hello");
    blahConf.update(blahProps);
    Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
    subsystem.start();
    // No configuration exists for the service Bar: configuration
    // values are loaded by the subsystem.
    Filter f = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
    ServiceTracker<String, String> barTracker = new ServiceTracker<String, String>(bundleContext, f, null);
    try {
        barTracker.open();
        String blahSvc = barTracker.waitForService(2000);
        assertEquals("Bar!", blahSvc);
    } finally {
        barTracker.close();
    }
    // A configuration exists for Blah: the subsystem installation should
    // not overwrite it.
    Filter f2 = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
    ServiceTracker<String, String> blahTracker = new ServiceTracker<String, String>(bundleContext, f2, null);
    try {
        blahTracker.open();
        String blahSvc = blahTracker.waitForService(2000);
        assertEquals("Hello", blahSvc);
    } finally {
        blahTracker.close();
    }
    stopAndUninstallSubsystemSilently(subsystem);
    blahConf.delete();
}

23. ConfigAdminPropsFileContentHandlerTest#testConfigurationContentHandler()

Project: aries
File: ConfigAdminPropsFileContentHandlerTest.java
@Test
public void testConfigurationContentHandler() throws Exception {
    // This test works as follows: it first installs a subsystem (cmContent.esa)
    // that contains two configuration files (org.foo.Bar.cfg and com.blah.Blah.cfg)
    // These configuration files are marked as 'osgi.config' content type.
    // The ConfigAdminContentHandler handles the installation of this content
    // and registers them as configuration with the Config Admin Service.
    // The .esa file also contains an ordinary bundle that registers two
    // Config Admin ManagedServices. Each registerd under one of the PIDs.
    // Once they receive the expected configuration they each register a String
    // service to mark that they have.
    // After starting the subsystem this test waits for these 'String' services
    // to appear so that it knows that the whole process worked.
    Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
    subsystem.start();
    // Now check that both Managed Services (Config Admin services) have been configured
    // If they are configured correctly they will register a marker String service to
    // indicate this.
    Filter f = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
    ServiceTracker<String, String> barTracker = new ServiceTracker<String, String>(bundleContext, f, null);
    try {
        barTracker.open();
        String blahSvc = barTracker.waitForService(2000);
        assertEquals("Bar!", blahSvc);
    } finally {
        barTracker.close();
    }
    Filter f2 = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
    ServiceTracker<String, String> blahTracker = new ServiceTracker<String, String>(bundleContext, f2, null);
    try {
        blahTracker.open();
        String blahSvc = blahTracker.waitForService(2000);
        assertEquals("Blah!", blahSvc);
    } finally {
        blahTracker.close();
    }
    stopAndUninstallSubsystemSilently(subsystem);
}

24. SubsystemPermission#implies0()

Project: aries
File: SubsystemPermission.java
/**
	 * Internal implies method. Used by the implies and the permission
	 * collection implies methods.
	 * 
	 * @param requested The requested SubsystemPermision which has already been
	 *        validated as a proper argument. The requested SubsystemPermission
	 *        must not have a filter expression.
	 * @param effective The effective actions with which to start.
	 * @return {@code true} if the specified permission is implied by this
	 *         object; {@code false} otherwise.
	 */
boolean implies0(SubsystemPermission requested, int effective) {
    /* check actions first - much faster */
    effective |= action_mask;
    final int desired = requested.action_mask;
    if ((effective & desired) != desired) {
        return false;
    }
    /* Get our filter */
    Filter f = filter;
    if (f == null) {
        // it's "*"
        return true;
    }
    /* is requested a wildcard filter? */
    if (requested.subsystem == null) {
        return false;
    }
    Map<String, Object> requestedProperties = requested.getProperties();
    if (requestedProperties == null) {
        /*
			 * If the requested properties are null, then we have detected a
			 * recursion getting the subsystem location. So we return true to
			 * permit the subsystem location request in the SubsystemPermission
			 * check up the stack to succeed.
			 */
        return true;
    }
    return f.matches(requestedProperties);
}

25. ScopeAdminTest#createScope()

Project: apache-aries
File: ScopeAdminTest.java
//    @org.ops4j.pax.exam.junit.Configuration
//    public static Option[] configuration() {
//        Option[] options = options(
//            // Log
//            mavenBundle("org.ops4j.pax.logging", "pax-logging-api"),
//            mavenBundle("org.ops4j.pax.logging", "pax-logging-service"),
//            // Felix Config Admin
//            mavenBundle("org.apache.felix", "org.apache.felix.configadmin"),
//            // Felix mvn url handler
//            mavenBundle("org.ops4j.pax.url", "pax-url-mvn"),
//
//
//            // this is how you set the default log level when using pax logging (logProfile)
//            systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("DEBUG"),
//
//            // Bundles
//            mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit"),
//            mavenBundle("org.apache.aries.application", "org.apache.aries.application.api"),
//            mavenBundle("org.apache.aries", "org.apache.aries.util"),
//            mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils"),
//            mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.api"),
//            mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.scope.impl"),
//
//            // org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"),
//
//            PaxRunnerOptions.rawPaxRunnerOption("config", "classpath:ss-runner.properties"),
//
//            equinox().version("3.7.0.v20110221")
//        );
//        options = updateOptions(options);
//        return options;
//    }
private Scope createScope(Scope scope, String scopeName, String loc, String version) throws MalformedURLException, InvalidSyntaxException, BundleException, IOException {
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild(scopeName);
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + "(version=" + version + ")" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info1 = new InstallInfo("helloIsolation_" + scopeName, new URL(loc));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info1);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        b.start();
    }
    return childScopeUpdate.getScope();
}

26. ScopeAdminTest#testScopeAffinity()

Project: apache-aries
File: ScopeAdminTest.java
// test ability to select the helloIsolation package from which scope it wants to use
// not necessarily the highest version one by default.
@Test
@Ignore
public void testScopeAffinity() throws Exception {
    // install helloIsolation 0.3 in scope_test1
    Scope scope1 = createScope(scope, "scope_test1", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "0.3");
    // install helloIsolation 2.0 in scope_test2
    Scope scope2 = createScope(scope, "scope_test2", "mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT", "2.0");
    // install helloIsolationRef 2.0 in scope_test3
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test3");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    Scope scope3 = childScopeUpdate.getScope();
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    /*final Filter filter1 = FrameworkUtil.createFilter(
                "(&" + 
                  "(osgi.package=org.apache.aries.subsystem.example.helloIsolation)" +
                  "(bundle-symbolic-name=org.apache.aries.subsystem.example.helloIsolation)" + 
                  "(bundle-version<=1.1)" + 
                ")");*/
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + //"(scopeName=scope_test1)" +  
    ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test3
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        try {
            b.start();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("should be able to start helloIsolationRef in scope_test1");
        }
    }
    /*  // install helloIsolationRef in root scope
        URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT");
        Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream());
   
        try {
            helloIsolationRef.start();
        } catch (Exception ex) {
            fail("should be able to start helloIsolationRef");
        }*/
    // remove child scope - cleanup
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    scopes.clear();
    //        scopes.add(scope1);
    //        scopes.add(scope2);
    //        scopes.add(scope3);
    su.commit();
    assertTrue(scope.getChildren().isEmpty());
    assertTrue(scope.newScopeUpdate().getChildren().isEmpty());
}

27. ScopeAdminTest#testPackageSharingFromRootScope()

Project: apache-aries
File: ScopeAdminTest.java
// test sharing the helloIsolation package & service from the root scope.
@Test
public void testPackageSharingFromRootScope() throws Exception {
    // install helloIsolationRef1 bundle in the root scope
    URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT");
    Bundle helloIsolation = bundleContext.installBundle("helloIsolation1-rootScope", url1.openStream());
    try {
        helloIsolation.start();
    } catch (Exception ex) {
        fail("should be able to start helloIsolation");
    }
    // make sure we are using a framework that provides composite admin service
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test1");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        try {
            b.start();
        } catch (Exception ex) {
            ex.printStackTrace();
            fail("should be able to start helloIsolationRef in scope_test1");
        }
    }
    // remove helloIsolation in root scope
    helloIsolation.uninstall();
    // remove child scope
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    childScopeUpdate = scopes.iterator().next();
    // obtain child scope admin from service registry
    //        String filter = "ScopeName=scope_test1";
    Scope childScopeAdmin = childScopeUpdate.getScope();
    assertEquals(scope, childScopeAdmin.getParent());
    scopes.remove(childScopeUpdate);
    su.commit();
    assertFalse(scope.getChildren().contains(childScopeAdmin));
    su = scope.newScopeUpdate();
    assertFalse(su.getChildren().contains(childScopeUpdate));
//        childScopeAdmin = null;
//        try {
//            childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT);
//        } catch (Exception ex) {
//            // ignore
//        }
//        assertNull("scope admin service for the scope should be unregistered", childScopeAdmin);
}

28. ScopeAdminTest#testPackageSharingFromTestScope()

Project: apache-aries
File: ScopeAdminTest.java
// test sharing the helloIsolation package from the test scope.
@Test
@Ignore
public void testPackageSharingFromTestScope() throws Exception {
    // make sure we are using a framework that provides composite admin service
    assertNotNull("scope admin should not be null", scope);
    System.out.println("able to get scope admin service");
    ScopeUpdate su = scope.newScopeUpdate();
    ScopeUpdate childScopeUpdate = su.newChild("scope_test1");
    su.getChildren().add(childScopeUpdate);
    addPackageImportPolicy("org.osgi.framework", childScopeUpdate);
    addPackageImportPolicy("org.osgi.util.tracker", childScopeUpdate);
    Map<String, List<SharePolicy>> sharePolicies = childScopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    final Filter filter1 = FrameworkUtil.createFilter("(&" + "(osgi.wiring.package=org.apache.aries.subsystem.example.helloIsolation)" + ")");
    final Filter filter2 = FrameworkUtil.createFilter("(&" + "(scope.share.service=org.apache.aries.subsystem.example.helloIsolation.HelloIsolation)" + ")");
    List<SharePolicy> packagePolicies = sharePolicies.get(BundleRevision.PACKAGE_NAMESPACE);
    if (packagePolicies == null) {
        packagePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put(BundleRevision.PACKAGE_NAMESPACE, packagePolicies);
    }
    packagePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, BundleRevision.PACKAGE_NAMESPACE, filter1));
    List<SharePolicy> servicePolicies = sharePolicies.get("scope.share.service");
    if (servicePolicies == null) {
        servicePolicies = new ArrayList<SharePolicy>();
        sharePolicies.put("scope.share.service", servicePolicies);
    }
    servicePolicies.add(new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter2));
    // build up installInfo object for the scope
    InstallInfo info1 = new InstallInfo("helloIsolation", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolation/0.1-SNAPSHOT"));
    InstallInfo info2 = new InstallInfo("helloIsolationRef", new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT"));
    List<InstallInfo> bundlesToInstall = childScopeUpdate.getBundlesToInstall();
    bundlesToInstall.add(info1);
    bundlesToInstall.add(info2);
    // add bundles to be installed, based on subsystem content
    su.commit();
    // start all bundles in the scope scope_test1
    Collection<Bundle> bundlesToStart = childScopeUpdate.getScope().getBundles();
    for (Bundle b : bundlesToStart) {
        b.start();
    }
    // install helloIsolationRef1 bundle in the root scope
    URL url1 = new URL("mvn:org.apache.aries.subsystem/org.apache.aries.subsystem.example.helloIsolationRef/0.1-SNAPSHOT");
    Bundle helloIsolationRef = bundleContext.installBundle("helloIsolationRef1-rootScope", url1.openStream());
    try {
        helloIsolationRef.start();
    } catch (Exception ex) {
        fail("should be able to start helloIsolationRef by import packages from scope_test1");
    }
    // remove helloIsolationRef
    helloIsolationRef.uninstall();
    // remove child scope
    su = scope.newScopeUpdate();
    Collection<ScopeUpdate> scopes = su.getChildren();
    childScopeUpdate = scopes.iterator().next();
    // obtain child scope admin from service registry
    //        String filter = "ScopeName=scope_test1";
    Scope childScopeAdmin = childScopeUpdate.getScope();
    assertEquals(scope, childScopeAdmin.getParent());
    scopes.remove(childScopeUpdate);
    su.commit();
    assertFalse(scope.getChildren().contains(childScopeAdmin));
    su = scope.newScopeUpdate();
    assertFalse(su.getChildren().contains(childScopeUpdate));
//        childScopeAdmin = null;
//        try {
//            childScopeAdmin = getOsgiService(Scope.class, filter, DEFAULT_TIMEOUT);
//        } catch (Exception ex) {
//            // ignore
//        }
//        assertNull("scope admin service for the scope should be unregistered", childScopeAdmin);
}

29. ConfigAdminPropsFileContentHandlerTest#testAries1352()

Project: apache-aries
File: ConfigAdminPropsFileContentHandlerTest.java
@Test
public void testAries1352() throws Exception {
    // Same test than testConfigurationContentHandler, but an existing
    // configuration exists before the subsystem is installed.
    // The configuration should not be overwritten by the subsystem
    // installation.
    ConfigurationAdmin cm = bundleContext.getService(bundleContext.getServiceReference(ConfigurationAdmin.class));
    Configuration blahConf = cm.getConfiguration("com.blah.Blah", "?");
    Dictionary<String, Object> blahProps = new Hashtable<String, Object>(1);
    blahProps.put("configVal", "Hello");
    blahConf.update(blahProps);
    Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
    subsystem.start();
    // No configuration exists for the service Bar: configuration
    // values are loaded by the subsystem.
    Filter f = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
    ServiceTracker<String, String> barTracker = new ServiceTracker<String, String>(bundleContext, f, null);
    try {
        barTracker.open();
        String blahSvc = barTracker.waitForService(2000);
        assertEquals("Bar!", blahSvc);
    } finally {
        barTracker.close();
    }
    // A configuration exists for Blah: the subsystem installation should
    // not overwrite it.
    Filter f2 = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
    ServiceTracker<String, String> blahTracker = new ServiceTracker<String, String>(bundleContext, f2, null);
    try {
        blahTracker.open();
        String blahSvc = blahTracker.waitForService(2000);
        assertEquals("Hello", blahSvc);
    } finally {
        blahTracker.close();
    }
    stopAndUninstallSubsystemSilently(subsystem);
    blahConf.delete();
}

30. ConfigAdminPropsFileContentHandlerTest#testConfigurationContentHandler()

Project: apache-aries
File: ConfigAdminPropsFileContentHandlerTest.java
@Test
public void testConfigurationContentHandler() throws Exception {
    // This test works as follows: it first installs a subsystem (cmContent.esa)
    // that contains two configuration files (org.foo.Bar.cfg and com.blah.Blah.cfg)
    // These configuration files are marked as 'osgi.config' content type.
    // The ConfigAdminContentHandler handles the installation of this content
    // and registers them as configuration with the Config Admin Service.
    // The .esa file also contains an ordinary bundle that registers two
    // Config Admin ManagedServices. Each registerd under one of the PIDs.
    // Once they receive the expected configuration they each register a String
    // service to mark that they have.
    // After starting the subsystem this test waits for these 'String' services
    // to appear so that it knows that the whole process worked.
    Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
    subsystem.start();
    // Now check that both Managed Services (Config Admin services) have been configured
    // If they are configured correctly they will register a marker String service to
    // indicate this.
    Filter f = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
    ServiceTracker<String, String> barTracker = new ServiceTracker<String, String>(bundleContext, f, null);
    try {
        barTracker.open();
        String blahSvc = barTracker.waitForService(2000);
        assertEquals("Bar!", blahSvc);
    } finally {
        barTracker.close();
    }
    Filter f2 = bundleContext.createFilter("(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
    ServiceTracker<String, String> blahTracker = new ServiceTracker<String, String>(bundleContext, f2, null);
    try {
        blahTracker.open();
        String blahSvc = blahTracker.waitForService(2000);
        assertEquals("Blah!", blahSvc);
    } finally {
        blahTracker.close();
    }
    stopAndUninstallSubsystemSilently(subsystem);
}

31. SubsystemPermission#implies0()

Project: apache-aries
File: SubsystemPermission.java
/**
	 * Internal implies method. Used by the implies and the permission
	 * collection implies methods.
	 * 
	 * @param requested The requested SubsystemPermision which has already been
	 *        validated as a proper argument. The requested SubsystemPermission
	 *        must not have a filter expression.
	 * @param effective The effective actions with which to start.
	 * @return {@code true} if the specified permission is implied by this
	 *         object; {@code false} otherwise.
	 */
boolean implies0(SubsystemPermission requested, int effective) {
    /* check actions first - much faster */
    effective |= action_mask;
    final int desired = requested.action_mask;
    if ((effective & desired) != desired) {
        return false;
    }
    /* Get our filter */
    Filter f = filter;
    if (f == null) {
        // it's "*"
        return true;
    }
    /* is requested a wildcard filter? */
    if (requested.subsystem == null) {
        return false;
    }
    Map<String, Object> requestedProperties = requested.getProperties();
    if (requestedProperties == null) {
        /*
			 * If the requested properties are null, then we have detected a
			 * recursion getting the subsystem location. So we return true to
			 * permit the subsystem location request in the SubsystemPermission
			 * check up the stack to succeed.
			 */
        return true;
    }
    return f.matches(requestedProperties);
}

32. Activator#start()

Project: smarthome
File: Activator.java
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void start(final BundleContext bc) throws Exception {
    ruleEngine = new RuleEngine(bc);
    Hashtable props = new Hashtable(11);
    props.put(Constants.SERVICE_PID, "smarthome.rule.configuration");
    configReg = bc.registerService(ManagedService.class.getName(), ruleEngine, props);
    this.tManager = new TemplateManager(bc);
    mtManager = new ModuleTypeManager(bc, ruleEngine);
    ruleEngine.setModuleTypeManager(mtManager);
    ruleEngine.setCompositeModuleFactory(new CompositeModuleHandlerFactory(bc, mtManager, ruleEngine));
    ConnectionValidator.setManager(mtManager);
    templateRegistry = new TemplateRegistryImpl(tManager);
    templateRegistryReg = bc.registerService(TemplateRegistry.class.getName(), templateRegistry, null);
    moduleTypeRegistry = new ModuleTypeRegistryImpl(mtManager);
    moduleTypeRegistryReg = bc.registerService(ModuleTypeRegistry.class.getName(), moduleTypeRegistry, null);
    ruleEventFactory = new RuleEventFactory();
    ruleEventFactoryReg = bc.registerService(EventFactory.class.getName(), ruleEventFactory, null);
    ruleRegistry = new RuleRegistryImpl(ruleEngine, tManager, bc);
    Filter filter = bc.createFilter("(|(" + Constants.OBJECTCLASS + "=" + StorageService.class.getName() + ")(" + Constants.OBJECTCLASS + "=" + RuleProvider.class.getName() + ")(" + Constants.OBJECTCLASS + "=" + EventPublisher.class.getName() + "))");
    serviceTracker = new ServiceTracker(bc, filter, new ServiceTrackerCustomizer() {

        @Override
        public Object addingService(ServiceReference reference) {
            Object service = bc.getService(reference);
            if (service instanceof StorageService) {
                StorageService storage = (StorageService) service;
                if (storage != null) {
                    Storage<Boolean> storageDisabledRules = storage.getStorage("automation_rules_disabled", this.getClass().getClassLoader());
                    ruleRegistry.setDisabledRuleStorage(storageDisabledRules);
                    final ManagedRuleProvider managedRuleProvider = new ManagedRuleProvider(storage);
                    ruleRegistry.setManagedProvider(managedRuleProvider);
                    managedRuleProviderReg = bc.registerService(RuleProvider.class.getName(), managedRuleProvider, null);
                    return storage;
                }
            } else if (service instanceof RuleProvider) {
                RuleProvider rp = (RuleProvider) service;
                ruleRegistry.addProvider(rp);
                if (rp instanceof ManagedRuleProvider) {
                    ruleRegistryReg = bc.registerService(RuleRegistry.class.getName(), ruleRegistry, null);
                }
                return rp;
            } else if (service instanceof EventPublisher) {
                EventPublisher ep = (EventPublisher) service;
                ruleRegistry.setEventPublisher(ep);
                return ep;
            }
            return null;
        }

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

        @Override
        public void removedService(ServiceReference reference, Object service) {
            if (service instanceof StorageService) {
                if (managedRuleProviderReg != null) {
                    managedRuleProviderReg.unregister();
                    managedRuleProviderReg = null;
                }
            } else if (service instanceof EventPublisher) {
                if (ruleRegistry != null) {
                    ruleRegistry.unsetEventPublisher((EventPublisher) service);
                }
            } else if (service instanceof RuleProvider) {
                if (ruleRegistry != null) {
                    RuleProvider rp = (RuleProvider) service;
                    if (rp instanceof ManagedRuleProvider) {
                        ruleRegistry.removeManagedProvider((ManagedProvider<Rule, String>) rp);
                    } else {
                        ruleRegistry.removeProvider(rp);
                    }
                }
            }
        }
    });
    serviceTracker.open();
}

33. MockBundleContextTest#testObjectClassFilterDoesNotMatch()

Project: sling
File: MockBundleContextTest.java
@Test
public void testObjectClassFilterDoesNotMatch() throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(" + Constants.OBJECTCLASS + "=" + Integer.class.getName() + ")");
    ServiceRegistration serviceRegistration = bundleContext.registerService(Long.class.getName(), Long.valueOf(1), null);
    assertFalse(filter.match(serviceRegistration.getReference()));
}

34. MockBundleContextTest#testObjectClassFilterMatches()

Project: sling
File: MockBundleContextTest.java
@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()));
}

35. TenantProviderImpl#getTenants()

Project: sling
File: TenantProviderImpl.java
@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;
}

36. DataSourceIT#testDataSourceAsService()

Project: sling
File: DataSourceIT.java
@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"));
}

37. OSGiExtensionLoader#getExtension()

Project: opennlp
File: OSGiExtensionLoader.java
/**
   * Retrieves the
   *
   * @param clazz
   * @param id
   * @return
   */
<T> T getExtension(Class<T> clazz, String id) {
    if (context == null) {
        throw new IllegalStateException("OpenNLP Tools Bundle is not active!");
    }
    Filter filter;
    try {
        filter = FrameworkUtil.createFilter("(&(objectclass=" + clazz.getName() + ")(" + "opennlp" + "=" + id + "))");
    } catch (InvalidSyntaxException e) {
        throw new ExtensionNotLoadedException(e);
    }
    // NOTE: In 4.3 the parameters are <T, T>
    ServiceTracker extensionTracker = new ServiceTracker(context, filter, null);
    T extension = null;
    try {
        extensionTracker.open();
        try {
            extension = (T) extensionTracker.waitForService(30000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    } finally {
        extensionTracker.close();
    }
    if (extension == null) {
        throw new ExtensionNotLoadedException("No suitable extension found. Extension name: " + id);
    }
    return extension;
}

38. IndexerMojo#execute()

Project: bnd
File: IndexerMojo.java
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().debug("skip project as configured");
        return;
    }
    if (scopes == null || scopes.isEmpty()) {
        scopes = Arrays.asList("compile", "runtime");
    }
    getLog().debug("Indexing dependencies with scopes: " + scopes);
    getLog().debug("Including Transitive dependencies: " + includeTransitive);
    getLog().debug("Local file URLs permitted: " + localURLs);
    getLog().debug("Adding mvn: URLs as alternative content: " + addMvnURLs);
    DependencyResolutionRequest request = new DefaultDependencyResolutionRequest(project, session);
    request.setResolutionFilter(new DependencyFilter() {

        @Override
        public boolean accept(DependencyNode node, List<DependencyNode> parents) {
            if (node.getDependency() != null) {
                return scopes.contains(node.getDependency().getScope());
            }
            return false;
        }
    });
    DependencyResolutionResult result;
    try {
        result = resolver.resolve(request);
    } catch (DependencyResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    Map<File, ArtifactResult> dependencies = new HashMap<>();
    if (result.getDependencyGraph() != null && !result.getDependencyGraph().getChildren().isEmpty()) {
        discoverArtifacts(dependencies, result.getDependencyGraph().getChildren(), project.getArtifact().getId());
    }
    Map<String, ArtifactRepository> repositories = new HashMap<>();
    for (ArtifactRepository artifactRepository : project.getRemoteArtifactRepositories()) {
        repositories.put(artifactRepository.getId(), artifactRepository);
    }
    RepoIndex indexer = new RepoIndex();
    Filter filter;
    try {
        filter = FrameworkUtil.createFilter("(name=*.jar)");
    } catch (InvalidSyntaxException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    indexer.addAnalyzer(new KnownBundleAnalyzer(), filter);
    indexer.addURLResolver(new RepositoryURLResolver(dependencies, repositories));
    if (addMvnURLs) {
        indexer.addURLResolver(new MavenURLResolver(dependencies));
    }
    Map<String, String> config = new HashMap<String, String>();
    config.put(ResourceIndexer.PRETTY, "true");
    File outputFile = new File(targetDir, "index.xml");
    OutputStream output;
    try {
        targetDir.mkdirs();
        output = new FileOutputStream(outputFile);
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    getLog().debug("Indexing artifacts: " + dependencies.keySet());
    try {
        indexer.index(dependencies.keySet(), output, config);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
    if (fail) {
        throw new MojoExecutionException("One or more URI lookups failed");
    }
    File gzipOutputFile = new File(outputFile.getPath() + ".gz");
    try (InputStream is = new BufferedInputStream(new FileInputStream(outputFile));
        OutputStream gos = new GZIPOutputStream(new FileOutputStream(gzipOutputFile))) {
        byte[] bytes = new byte[4096];
        int read;
        while ((read = is.read(bytes)) != -1) {
            gos.write(bytes, 0, read);
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to create the gzipped output file");
    }
    attach(outputFile, "osgi-index", "xml");
    attach(gzipOutputFile, "osgi-index", "xml.gz");
}

39. AbstractTest#addServiceImportPolicy()

Project: aries
File: AbstractTest.java
protected void addServiceImportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    List<SharePolicy> policies = policyMap.get("scope.share.service");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("scope.share.service", policies);
    }
    policies.add(policy);
}

40. AbstractTest#addServiceExportPolicy()

Project: aries
File: AbstractTest.java
protected void addServiceExportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    List<SharePolicy> policies = policyMap.get("scope.share.service");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("scope.share.service", policies);
    }
    policies.add(policy);
}

41. AbstractTest#addPackageImportPolicy()

Project: aries
File: AbstractTest.java
protected void addPackageImportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "osgi.wiring.package", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    List<SharePolicy> policies = policyMap.get("osgi.wiring.package");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("osgi.wiring.package", policies);
    }
    policies.add(policy);
}

42. AbstractTest#addPackageExportPolicy()

Project: aries
File: AbstractTest.java
protected void addPackageExportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "osgi.wiring.package", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    List<SharePolicy> policies = policyMap.get("osgi.wiring.package");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("osgi.wiring.package", policies);
    }
    policies.add(policy);
}

43. CompositeServiceTest#testCompositeServiceImportExportWildcards()

Project: aries
File: CompositeServiceTest.java
@Test
public void testCompositeServiceImportExportWildcards() throws Exception {
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("test", "testCompositeServiceImports");
    ServiceRegistration<String> reg = bundleContext.registerService(String.class, "testCompositeServiceImports", props);
    Filter filter = bundleContext.createFilter("(&(objectClass=java.lang.String)(test=tb4))");
    ServiceTracker<String, String> st = new ServiceTracker<String, String>(bundleContext, filter, null);
    st.open();
    Subsystem subsystem = installSubsystemFromFile("composite2.esa");
    try {
        assertEquals(Subsystem.State.INSTALLED, subsystem.getState());
        subsystem.start();
        String svc = st.waitForService(5000);
        assertNotNull("The service registered by the bundle inside the composite cannot be found", svc);
        assertEquals(Subsystem.State.ACTIVE, subsystem.getState());
    } finally {
        subsystem.stop();
        uninstallSubsystem(subsystem);
        reg.unregister();
        st.close();
    }
}

44. BundleFrameworkConfigurationFactoryImpl#createBundleFrameworkConfig()

Project: aries
File: BundleFrameworkConfigurationFactoryImpl.java
public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx, AriesApplication app) {
    BundleFrameworkConfiguration config = null;
    DeploymentMetadata metadata = app.getDeploymentMetadata();
    /**
     * Set up framework config properties
     */
    Properties frameworkConfig = new Properties();
    // Problems occur if the parent framework has osgi.console set because the child framework
    // will also attempt to listen on the same port which will cause port clashs. Setting this
    // to null essentially turns the console off.
    frameworkConfig.put("osgi.console", "none");
    String flowedSystemPackages = EquinoxFrameworkUtils.calculateSystemPackagesToFlow(EquinoxFrameworkUtils.getSystemExtraPkgs(parentCtx), metadata.getImportPackage());
    frameworkConfig.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, flowedSystemPackages);
    /**
     * Set up BundleManifest for the framework bundle
     */
    Properties frameworkBundleManifest = new Properties();
    frameworkBundleManifest.put(Constants.BUNDLE_SYMBOLICNAME, metadata.getApplicationSymbolicName());
    frameworkBundleManifest.put(Constants.BUNDLE_VERSION, metadata.getApplicationVersion().toString());
    /**
     * Set up Import-Package header for framework manifest
     */
    // Extract the import packages and remove anything we already have available in the current framework
    Collection<Content> imports = EquinoxFrameworkUtils.calculateImports(metadata.getImportPackage(), EquinoxFrameworkUtils.getExportPackages(parentCtx));
    if (imports != null && !imports.isEmpty()) {
        StringBuffer buffer = new StringBuffer();
        for (Content i : imports) buffer.append(EquinoxFrameworkUtils.contentToString(i) + ",");
        frameworkBundleManifest.put(Constants.IMPORT_PACKAGE, buffer.substring(0, buffer.length() - 1));
    }
    /**
     * Set up CompositeServiceFilter-Import header for framework manifest
     */
    StringBuilder serviceImportFilter = new StringBuilder();
    String txRegsitryImport = "(" + Constants.OBJECTCLASS + "=" + EquinoxFrameworkConstants.TRANSACTION_REGISTRY_BUNDLE + ")";
    Collection<Filter> deployedServiceImports = metadata.getDeployedServiceImport();
    //if there are more services than the txRegistry import a OR group is required for the Filter
    if (deployedServiceImports.size() > 0) {
        serviceImportFilter.append("(|");
    }
    for (Filter importFilter : metadata.getDeployedServiceImport()) {
        serviceImportFilter.append(importFilter.toString());
    }
    serviceImportFilter.append(txRegsitryImport);
    //close the OR group if needed
    if (deployedServiceImports.size() > 0) {
        serviceImportFilter.append(")");
    }
    frameworkBundleManifest.put(EquinoxFrameworkConstants.COMPOSITE_SERVICE_FILTER_IMPORT, serviceImportFilter.toString());
    config = new BundleFrameworkConfigurationImpl(frameworkId, frameworkConfig, frameworkBundleManifest);
    return config;
}

45. ImportedServiceImpl#generateAttributeFilter()

Project: aries
File: ImportedServiceImpl.java
private Filter generateAttributeFilter(Map<String, String> attrsToPopulate) throws InvalidAttributeException {
    logger.debug(LOG_ENTRY, "generateAttributeFilter", new Object[] { attrsToPopulate });
    Filter result = null;
    try {
        attrsToPopulate.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE);
        if (_blueprintFilter != null) {
            // We may get blueprint filters of the form (&(a=b)(c=d)). We can't put these in 'whole' because we'll 
            // end up generating a filter of the form (&(objectClass=foo)(&(a=b)(c=d)) which subsequent calls to 
            // parseFilter will choke on. So as an interim fix we'll strip off a leading &( and trailing ) if present. 
            String reducedBlueprintFilter;
            if (_blueprintFilter.startsWith("(&")) {
                reducedBlueprintFilter = _blueprintFilter.substring(2, _blueprintFilter.length() - 1);
            } else {
                reducedBlueprintFilter = _blueprintFilter;
            }
            attrsToPopulate.put(ManifestHeaderProcessor.NESTED_FILTER_ATTRIBUTE, reducedBlueprintFilter);
        }
        if (_componentName != null) {
            attrsToPopulate.put("osgi.service.blueprint.compname", _componentName);
        }
        if (_iface != null) {
            attrsToPopulate.put(Constants.OBJECTCLASS, _iface);
        }
        _attribFilterString = ManifestHeaderProcessor.generateFilter(_attributes);
        if (!"".equals(_attribFilterString)) {
            result = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_attribFilterString));
        }
    } catch (InvalidSyntaxException isx) {
        InvalidAttributeException iax = new InvalidAttributeException("A syntax error occurred attempting to parse the blueprint filter string '" + _blueprintFilter + "' for element with id " + _id + ": " + isx.getLocalizedMessage(), isx);
        logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { isx });
        throw iax;
    }
    logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { result });
    return result;
}

46. AbstractTest#addServiceImportPolicy()

Project: apache-aries
File: AbstractTest.java
protected void addServiceImportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "scope.share.service", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    List<SharePolicy> policies = policyMap.get("scope.share.service");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("scope.share.service", policies);
    }
    policies.add(policy);
}

47. AbstractTest#addServiceExportPolicy()

Project: apache-aries
File: AbstractTest.java
protected void addServiceExportPolicy(Class<?> clazz, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter('(' + Constants.OBJECTCLASS + '=' + clazz.getName() + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "scope.share.service", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    List<SharePolicy> policies = policyMap.get("scope.share.service");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("scope.share.service", policies);
    }
    policies.add(policy);
}

48. AbstractTest#addPackageImportPolicy()

Project: apache-aries
File: AbstractTest.java
protected void addPackageImportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_IMPORT, "osgi.wiring.package", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_IMPORT);
    List<SharePolicy> policies = policyMap.get("osgi.wiring.package");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("osgi.wiring.package", policies);
    }
    policies.add(policy);
}

49. AbstractTest#addPackageExportPolicy()

Project: apache-aries
File: AbstractTest.java
protected void addPackageExportPolicy(String packageName, ScopeUpdate scopeUpdate) throws InvalidSyntaxException {
    Filter filter = bundleContext.createFilter("(osgi.wiring.package=" + packageName + ')');
    SharePolicy policy = new SharePolicy(SharePolicy.TYPE_EXPORT, "osgi.wiring.package", filter);
    Map<String, List<SharePolicy>> policyMap = scopeUpdate.getSharePolicies(SharePolicy.TYPE_EXPORT);
    List<SharePolicy> policies = policyMap.get("osgi.wiring.package");
    if (policies == null) {
        policies = new ArrayList<SharePolicy>();
        policyMap.put("osgi.wiring.package", policies);
    }
    policies.add(policy);
}

50. CompositeServiceTest#testCompositeServiceImportExportWildcards()

Project: apache-aries
File: CompositeServiceTest.java
@Test
public void testCompositeServiceImportExportWildcards() throws Exception {
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("test", "testCompositeServiceImports");
    ServiceRegistration<String> reg = bundleContext.registerService(String.class, "testCompositeServiceImports", props);
    Filter filter = bundleContext.createFilter("(&(objectClass=java.lang.String)(test=tb4))");
    ServiceTracker<String, String> st = new ServiceTracker<String, String>(bundleContext, filter, null);
    st.open();
    Subsystem subsystem = installSubsystemFromFile("composite2.esa");
    try {
        assertEquals(Subsystem.State.INSTALLED, subsystem.getState());
        subsystem.start();
        String svc = st.waitForService(5000);
        assertNotNull("The service registered by the bundle inside the composite cannot be found", svc);
        assertEquals(Subsystem.State.ACTIVE, subsystem.getState());
    } finally {
        subsystem.stop();
        uninstallSubsystem(subsystem);
        reg.unregister();
        st.close();
    }
}

51. BundleFrameworkConfigurationFactoryImpl#createBundleFrameworkConfig()

Project: apache-aries
File: BundleFrameworkConfigurationFactoryImpl.java
public BundleFrameworkConfiguration createBundleFrameworkConfig(String frameworkId, BundleContext parentCtx, AriesApplication app) {
    BundleFrameworkConfiguration config = null;
    DeploymentMetadata metadata = app.getDeploymentMetadata();
    /**
     * Set up framework config properties
     */
    Properties frameworkConfig = new Properties();
    // Problems occur if the parent framework has osgi.console set because the child framework
    // will also attempt to listen on the same port which will cause port clashs. Setting this
    // to null essentially turns the console off.
    frameworkConfig.put("osgi.console", "none");
    String flowedSystemPackages = EquinoxFrameworkUtils.calculateSystemPackagesToFlow(EquinoxFrameworkUtils.getSystemExtraPkgs(parentCtx), metadata.getImportPackage());
    frameworkConfig.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, flowedSystemPackages);
    /**
     * Set up BundleManifest for the framework bundle
     */
    Properties frameworkBundleManifest = new Properties();
    frameworkBundleManifest.put(Constants.BUNDLE_SYMBOLICNAME, metadata.getApplicationSymbolicName());
    frameworkBundleManifest.put(Constants.BUNDLE_VERSION, metadata.getApplicationVersion().toString());
    /**
     * Set up Import-Package header for framework manifest
     */
    // Extract the import packages and remove anything we already have available in the current framework
    Collection<Content> imports = EquinoxFrameworkUtils.calculateImports(metadata.getImportPackage(), EquinoxFrameworkUtils.getExportPackages(parentCtx));
    if (imports != null && !imports.isEmpty()) {
        StringBuffer buffer = new StringBuffer();
        for (Content i : imports) buffer.append(EquinoxFrameworkUtils.contentToString(i) + ",");
        frameworkBundleManifest.put(Constants.IMPORT_PACKAGE, buffer.substring(0, buffer.length() - 1));
    }
    /**
     * Set up CompositeServiceFilter-Import header for framework manifest
     */
    StringBuilder serviceImportFilter = new StringBuilder();
    String txRegsitryImport = "(" + Constants.OBJECTCLASS + "=" + EquinoxFrameworkConstants.TRANSACTION_REGISTRY_BUNDLE + ")";
    Collection<Filter> deployedServiceImports = metadata.getDeployedServiceImport();
    //if there are more services than the txRegistry import a OR group is required for the Filter
    if (deployedServiceImports.size() > 0) {
        serviceImportFilter.append("(|");
    }
    for (Filter importFilter : metadata.getDeployedServiceImport()) {
        serviceImportFilter.append(importFilter.toString());
    }
    serviceImportFilter.append(txRegsitryImport);
    //close the OR group if needed
    if (deployedServiceImports.size() > 0) {
        serviceImportFilter.append(")");
    }
    frameworkBundleManifest.put(EquinoxFrameworkConstants.COMPOSITE_SERVICE_FILTER_IMPORT, serviceImportFilter.toString());
    config = new BundleFrameworkConfigurationImpl(frameworkId, frameworkConfig, frameworkBundleManifest);
    return config;
}

52. ImportedServiceImpl#generateAttributeFilter()

Project: apache-aries
File: ImportedServiceImpl.java
private Filter generateAttributeFilter(Map<String, String> attrsToPopulate) throws InvalidAttributeException {
    logger.debug(LOG_ENTRY, "generateAttributeFilter", new Object[] { attrsToPopulate });
    Filter result = null;
    try {
        attrsToPopulate.put(ModellingConstants.OBR_SERVICE, ModellingConstants.OBR_SERVICE);
        if (_blueprintFilter != null) {
            // We may get blueprint filters of the form (&(a=b)(c=d)). We can't put these in 'whole' because we'll 
            // end up generating a filter of the form (&(objectClass=foo)(&(a=b)(c=d)) which subsequent calls to 
            // parseFilter will choke on. So as an interim fix we'll strip off a leading &( and trailing ) if present. 
            String reducedBlueprintFilter;
            if (_blueprintFilter.startsWith("(&")) {
                reducedBlueprintFilter = _blueprintFilter.substring(2, _blueprintFilter.length() - 1);
            } else {
                reducedBlueprintFilter = _blueprintFilter;
            }
            attrsToPopulate.put(ManifestHeaderProcessor.NESTED_FILTER_ATTRIBUTE, reducedBlueprintFilter);
        }
        if (_componentName != null) {
            attrsToPopulate.put("osgi.service.blueprint.compname", _componentName);
        }
        if (_iface != null) {
            attrsToPopulate.put(Constants.OBJECTCLASS, _iface);
        }
        _attribFilterString = ManifestHeaderProcessor.generateFilter(_attributes);
        if (!"".equals(_attribFilterString)) {
            result = FrameworkUtil.createFilter(FilterUtils.removeMandatoryFilterToken(_attribFilterString));
        }
    } catch (InvalidSyntaxException isx) {
        InvalidAttributeException iax = new InvalidAttributeException("A syntax error occurred attempting to parse the blueprint filter string '" + _blueprintFilter + "' for element with id " + _id + ": " + isx.getLocalizedMessage(), isx);
        logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { isx });
        throw iax;
    }
    logger.debug(LOG_EXIT, "generateAttributeFilter", new Object[] { result });
    return result;
}

53. CustomPollingImporterListServlet#activate()

Project: acs-aem-commons
File: CustomPollingImporterListServlet.java
@Activate
protected void activate(ComponentContext ctx) throws InvalidSyntaxException {
    BundleContext bundleContext = ctx.getBundleContext();
    StringBuilder builder = new StringBuilder();
    builder.append("(&(");
    builder.append(Constants.OBJECTCLASS).append("=").append(Importer.SERVICE_NAME).append(")");
    builder.append("(displayName=*))");
    Filter filter = bundleContext.createFilter(builder.toString());
    this.tracker = new ServiceTracker(bundleContext, filter, null);
    this.tracker.open();
}