java类org.osgi.framework.ServiceListener的实例源码

OsgiServiceDynamicInterceptorListenerTest.java 文件源码 项目:gemini.blueprint 阅读 37 收藏 0 点赞 0 评论 0
public void testRebindWhenServiceGoesDownButAReplacementIsFound() {
    interceptor.afterPropertiesSet();

    assertEquals(1, SimpleTargetSourceLifecycleListener.BIND);
    assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND);

    ServiceListener sl = (ServiceListener) bundleContext.getServiceListeners().iterator().next();

    // unregister the old service
    sl.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, refs[0]));

    // a new one is found since the mock context will return one again
    assertEquals(2, SimpleTargetSourceLifecycleListener.BIND);
    assertEquals(0, SimpleTargetSourceLifecycleListener.UNBIND);
}
OsgiListenerUtilsTest.java 文件源码 项目:gemini.blueprint 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Test method for
 * {@link org.eclipse.gemini.blueprint.util.OsgiListenerUtils#removeServiceListener(org.osgi.framework.BundleContext, org.osgi.framework.ServiceListener)}.
 */
public void testRemoveServiceListenerBundleContextServiceListener() {
    ServiceListener listener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
        }
    };

    OsgiListenerUtils.addSingleServiceListener(bundleContext, listener, (String) null);
    assertEquals(1, bundleContext.getServiceListeners().size());
    OsgiListenerUtils.removeServiceListener(bundleContext, listener);
}
AbstractSynchronizedOsgiTests.java 文件源码 项目:gemini.blueprint 阅读 22 收藏 0 点赞 0 评论 0
/**
 * Waits for a <em>Spring powered</em> bundle, given by its symbolic name,
 * to be fully started.
 * 
 * <p/>Forces the current (test) thread to wait for the a Spring application
 * context to be published under the given symbolic name. This method allows
 * waiting for full initialization of Spring OSGi bundles before starting
 * the actual test execution.
 * 
 * @param context bundle context to use for service lookup
 * @param forBundleWithSymbolicName bundle symbolic name
 * @param timeout maximum time to wait (in seconds) for the application
 * context to be published
 */
protected void waitOnContextCreation(BundleContext context, String forBundleWithSymbolicName, long timeout) {
    // translate from seconds to milliseconds
    long time = timeout * SECOND;

    // use the counter to make sure the threads block
    final Counter counter = new Counter("waitForContext on bnd=" + forBundleWithSymbolicName);

    counter.increment();

    String filter = "(org.springframework.context.service.name=" + forBundleWithSymbolicName + ")";

    ServiceListener listener = new ServiceListener() {

        public void serviceChanged(ServiceEvent event) {
            if (event.getType() == ServiceEvent.REGISTERED)
                counter.decrement();
        }
    };

    OsgiListenerUtils.addServiceListener(context, listener, filter);

    if (logger.isDebugEnabled())
        logger.debug("Start waiting for Spring/OSGi bundle=" + forBundleWithSymbolicName);

    try {
        if (counter.waitForZero(time)) {
            waitingFailed(forBundleWithSymbolicName);
        }
        else if (logger.isDebugEnabled()) {
            logger.debug("Found applicationContext for bundle=" + forBundleWithSymbolicName);
        }
    }
    finally {
        // inform waiting thread
        context.removeServiceListener(listener);
    }
}
GlobalEventExecutorModuleTest.java 文件源码 项目:hashsdn-controller 阅读 38 收藏 0 点赞 0 评论 0
@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);
}
NettyThreadgroupModuleTest.java 文件源码 项目:hashsdn-controller 阅读 28 收藏 0 点赞 0 评论 0
@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);
}
PublishingEndpointListenerTest.java 文件源码 项目:aries-rsa 阅读 28 收藏 0 点赞 0 评论 0
public void testDiscoveryPlugin() throws Exception {
    BundleContext ctx = EasyMock.createMock(BundleContext.class);
    stubCreateFilter(ctx);
    ctx.addServiceListener(EasyMock.isA(ServiceListener.class),
            EasyMock.eq("(objectClass=" + DiscoveryPlugin.class.getName() + ")"));

    ServiceReference<DiscoveryPlugin> sr1 = createAppendPlugin(ctx);
    ServiceReference<DiscoveryPlugin> sr2 = createPropertyPlugin(ctx);

    EasyMock.expect(ctx.getServiceReferences(DiscoveryPlugin.class.getName(), null))
            .andReturn(new ServiceReference[]{sr1, sr2}).anyTimes();
    EasyMock.replay(ctx);

    EndpointDescription endpoint = createEndpoint();

    Map<String, Object> expectedProps = new HashMap<String, Object>(endpoint.getProperties());
    expectedProps.put("endpoint.id", "http://google.de:80/test/sub/appended");
    expectedProps.put("foo", "bar");
    expectedProps.put("service.imported", "true");

    final ZooKeeper zk = EasyMock.createNiceMock(ZooKeeper.class);
    String expectedFullPath = "/osgi/service_registry/org/foo/myClass/some.machine#9876##test";

    EndpointDescription epd = new EndpointDescription(expectedProps);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    new EndpointDescriptionParser().writeEndpoint(epd, bos);
    byte[] data = bos.toByteArray();
    expectCreated(zk, expectedFullPath, EasyMock.aryEq(data));
    EasyMock.replay(zk);

    PublishingEndpointListener eli = new PublishingEndpointListener(zk, ctx);

    List<EndpointDescription> endpoints = getEndpoints(eli);
    assertEquals("Precondition", 0, endpoints.size());
    eli.endpointAdded(endpoint, null);
    assertEquals(1, endpoints.size());

    //TODO enable
    //EasyMock.verify(zk);
}
DistributionProviderTrackerTest.java 文件源码 项目:aries-rsa 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void testAddingWithNullValues() throws InvalidSyntaxException {
    IMocksControl c = EasyMock.createControl();
    DistributionProvider provider = c.createMock(DistributionProvider.class);

    ServiceReference<DistributionProvider> providerRef = c.createMock(ServiceReference.class);
    EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_INTENTS_SUPPORTED)).andReturn(null);
    EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_CONFIGS_SUPPORTED)).andReturn(null);

    BundleContext context = c.createMock(BundleContext.class);
    String filterSt = String.format("(objectClass=%s)", DistributionProvider.class.getName());
    Filter filter = FrameworkUtil.createFilter(filterSt);
    EasyMock.expect(context.createFilter(filterSt)).andReturn(filter);
    EasyMock.expect(context.getService(providerRef)).andReturn(provider);
    ServiceRegistration rsaReg = c.createMock(ServiceRegistration.class);
    EasyMock.expect(context.registerService(EasyMock.isA(String.class), EasyMock.isA(ServiceFactory.class),
                                            EasyMock.isA(Dictionary.class)))
        .andReturn(rsaReg).atLeastOnce();

    context.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.isA(String.class));
    EasyMock.expectLastCall();

    final BundleContext apiContext = c.createMock(BundleContext.class);
    c.replay();
    DistributionProviderTracker tracker = new DistributionProviderTracker(context) {
        protected BundleContext getAPIContext() {
            return apiContext;
        };
    };
    tracker.addingService(providerRef);
    c.verify();
}
RemoteServiceAdminCoreTest.java 文件源码 项目:aries-rsa 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void testDontExportOwnServiceProxies() throws InvalidSyntaxException {
    IMocksControl c = EasyMock.createControl();
    Bundle b = c.createMock(Bundle.class);
    BundleContext bc = c.createMock(BundleContext.class);

    EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
    bc.addServiceListener(EasyMock.<ServiceListener>anyObject(), EasyMock.<String>anyObject());
    EasyMock.expectLastCall().anyTimes();
    bc.removeServiceListener(EasyMock.<ServiceListener>anyObject());
    EasyMock.expectLastCall().anyTimes();

    Dictionary<String, String> d = new Hashtable<String, String>();
    EasyMock.expect(b.getHeaders()).andReturn(d).anyTimes();

    ServiceReference sref = c.createMock(ServiceReference.class);
    EasyMock.expect(sref.getBundle()).andReturn(b).anyTimes();
    EasyMock.expect(sref.getPropertyKeys())
        .andReturn(new String[]{"objectClass", "service.exported.interfaces"}).anyTimes();
    EasyMock.expect(sref.getProperty("objectClass")).andReturn(new String[] {"a.b.C"}).anyTimes();
    EasyMock.expect(sref.getProperty(RemoteConstants.SERVICE_IMPORTED)).andReturn(true).anyTimes();
    EasyMock.expect(sref.getProperty("service.exported.interfaces")).andReturn("*").anyTimes();

    DistributionProvider provider = c.createMock(DistributionProvider.class);

    c.replay();

    RemoteServiceAdminCore rsaCore = new RemoteServiceAdminCore(bc, bc, provider);

    // must return an empty List as sref if from the same bundle
    List<ExportRegistration> exRefs = rsaCore.exportService(sref, null);

    assertNotNull(exRefs);
    assertEquals(0, exRefs.size());

    // must be empty
    assertEquals(rsaCore.getExportedServices().size(), 0);

    c.verify();
}
OsgiLauncher.java 文件源码 项目:incubator-taverna-osgi 阅读 35 收藏 0 点赞 0 评论 0
/**
 * Starts the OSGi framework, installs and starts the bundles.
 *
 * @throws BundleException
 *             if the framework could not be started
 */
public void start() throws BundleException {
    logger.info("Loading the OSGi Framework Factory");
    FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator()
            .next();

    logger.info("Creating the OSGi Framework");
    framework = frameworkFactory.newFramework(frameworkConfiguration);
    logger.info("Starting the OSGi Framework");
    framework.start();

    context = framework.getBundleContext();
    context.addServiceListener(new ServiceListener() {
        public void serviceChanged(ServiceEvent event) {
            ServiceReference serviceReference = event.getServiceReference();
            if (event.getType() == ServiceEvent.REGISTERED) {
                Object property = serviceReference
                        .getProperty("org.springframework.context.service.name");
                if (property != null) {
                    addStartedSpringContext(property.toString());
                }
            }
            logger.fine((event.getType() == ServiceEvent.REGISTERED ? "Registering : "
                    : "Unregistering : ") + serviceReference);
        }
    });

    installedBundles = installBundles(bundlesToInstall);

    List<Bundle> bundlesToStart = new ArrayList<Bundle>();
    for (Bundle bundle : installedBundles) {
        if ("org.springframework.osgi.extender".equals(bundle.getSymbolicName())) {
            springOsgiExtender = bundle;
        } else {
            bundlesToStart.add(bundle);
        }
    }
    startBundles(bundlesToStart);
}
PlatformActivator.java 文件源码 项目:motech 阅读 31 收藏 0 点赞 0 评论 0
private void registerHttpServiceListener() throws InvalidSyntaxException {
    bundleContext.addServiceListener(new ServiceListener() {
        @Override
        public void serviceChanged(ServiceEvent event) {
            if (event.getType() == ServiceEvent.REGISTERED) {
                LOGGER.info("Http service registered");
                httpServiceRegistered();
            }
        }
    }, String.format("(&(%s=%s))", Constants.OBJECTCLASS, HttpService.class.getName()));
}


问题


面经


文章

微信
公众号

扫码关注公众号