public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object service) { if (log.isTraceEnabled()) { log.trace("Unget service called by bundle " + OsgiStringUtils.nullSafeName(bundle) + " on registration " + OsgiStringUtils.nullSafeToString(serviceRegistration.getReference())); } Class<?> type = targetResolver.getType(); // handle SF beans if (ServiceFactory.class.isAssignableFrom(type)) { ServiceFactory sf = (ServiceFactory) targetResolver.getBean(); sf.ungetService(bundle, serviceRegistration, service); } if (createTCCLProxy) { synchronized (proxyCache) { // trigger purging of unused entries proxyCache.size(); } } }
public void testPrototypeServiceFactoryDestruction() throws Exception { ServiceFactory factory = new MockServiceFactory(); String beanName = "prototype-sf"; expect(beanFactory.isSingleton(beanName)).andReturn(false).times(2); expect(beanFactory.containsBean(beanName)).andReturn(true); expect(beanFactory.isPrototype(beanName)).andReturn(true); expect(beanFactory.getBean(beanName)).andReturn(factory); expect(beanFactory.getType(beanName)).andStubReturn((Class) factory.getClass()); exporter.setTargetBeanName(beanName); exporter.setInterfaces(new Class<?>[]{Serializable.class}); beanFactoryControl.replay(); exporter.afterPropertiesSet(); exporter.destroy(); }
public void testServiceFactoryListener() throws Exception { listener = new OsgiServiceRegistrationListenerAdapter(); listener.setTarget(new ServiceFactoryListener()); listener.setRegistrationMethod("registered"); listener.setUnregistrationMethod("unregistered"); listener.setBeanFactory(createMockBF()); listener.afterPropertiesSet(); Object service = new Object(); assertEquals(0, ServiceFactoryListener.REG_CALLS); assertEquals(0, ServiceFactoryListener.UNREG_CALLS); listener.registered(service, props); listener.unregistered(service, props); assertEquals(0, ServiceFactoryListener.REG_CALLS); assertEquals(0, ServiceFactoryListener.UNREG_CALLS); ServiceFactory factory = new MockServiceFactory(); listener.registered(factory, props); listener.unregistered(factory, props); assertEquals(1, ServiceFactoryListener.REG_CALLS); assertEquals(1, ServiceFactoryListener.UNREG_CALLS); }
boolean ungetService(Bundle bundle) { synchronized (this.useCounters) { if (this.service == null) { return false; } Integer num = (Integer) this.useCounters.get(bundle); if (num == null) { return false; } else if (num.intValue() == 1) { this.useCounters.remove(bundle); if (this.isServiceFactory) { ((ServiceFactory) this.service).ungetService(bundle, this.registration, this.cachedServices.get(bundle)); this.cachedServices.remove(bundle); } return false; } else { this.useCounters.put(bundle, Integer.valueOf(num.intValue() - 1)); return true; } } }
public Object getService(Bundle bundle, ServiceRegistration serviceRegistration) { Object bn = getBean(); // handle SF beans if (bn instanceof ServiceFactory) { bn = ((ServiceFactory) bn).getService(bundle, serviceRegistration); } if (createTCCLProxy) { // check proxy cache synchronized (proxyCache) { WeakReference value = (WeakReference) proxyCache.get(bn); Object proxy = null; if (value != null) { proxy = value.get(); } if (proxy == null) { proxy = createCLLProxy(bn); proxyCache.put(bn, new WeakReference(proxy)); } bn = proxy; } } return bn; }
/** * Registration method. * * @param classes * @param serviceProperties * @return the ServiceRegistration */ ServiceRegistration registerService(Class[] classes, Dictionary serviceProperties) { Assert.notEmpty( classes, "at least one class has to be specified for exporting (if autoExport is enabled then maybe the object doesn't implement any interface)"); // create an array of classnames (used for registering the service) String[] names = ClassUtils.toStringArray(classes); // sort the names in alphabetical order (eases debugging) Arrays.sort(names); log.info("Publishing service under classes [" + ObjectUtils.nullSafeToString(names) + "]"); ServiceFactory serviceFactory = new PublishingServiceFactory(classes, target, beanFactory, targetBeanName, (contextClassLoader == ExportContextClassLoader.SERVICE_PROVIDER), classLoader, aopClassLoader, bundleContext); if (isBeanBundleScoped()) serviceFactory = new OsgiBundleScope.BundleScopeServiceFactory(serviceFactory); return bundleContext.registerService(names, serviceFactory, serviceProperties); }
public Object getService(Bundle bundle, ServiceRegistration serviceRegistration) { if (log.isTraceEnabled()) { log.trace("Get service called by bundle " + OsgiStringUtils.nullSafeName(bundle) + " on registration " + OsgiStringUtils.nullSafeToString(serviceRegistration.getReference())); } targetResolver.activate(); Object bn = targetResolver.getBean(); // handle SF beans if (bn instanceof ServiceFactory) { bn = ((ServiceFactory) bn).getService(bundle, serviceRegistration); } if (createTCCLProxy) { // check proxy cache synchronized (proxyCache) { WeakReference<Object> value = proxyCache.get(bn); Object proxy = null; if (value != null) { proxy = value.get(); } if (proxy == null) { proxy = createCLLProxy(bn); proxyCache.put(bn, new WeakReference<Object>(proxy)); } bn = proxy; } } return bn; }
/** * Registration method. * * @param classes * @param serviceProperties * @return the ServiceRegistration */ ServiceRegistration registerService(Class<?>[] classes, final Dictionary serviceProperties) { Assert.notEmpty(classes, "at least one class has to be specified for exporting " + "(if autoExport is enabled then maybe the object doesn't implement any interface)"); // create an array of classnames (used for registering the service) final String[] names = ClassUtils.toStringArray(classes); // sort the names in alphabetical order (eases debugging) Arrays.sort(names); log.info("Publishing service under classes [" + ObjectUtils.nullSafeToString(names) + "]"); ServiceFactory serviceFactory = new PublishingServiceFactory(resolver, classes, (ExportContextClassLoaderEnum.SERVICE_PROVIDER .equals(contextClassLoader)), classLoader, aopClassLoader, bundleContext); if (isBeanBundleScoped()) serviceFactory = new OsgiBundleScope.BundleScopeServiceFactory(serviceFactory); if (System.getSecurityManager() != null) { AccessControlContext acc = SecurityUtils.getAccFrom(beanFactory); final ServiceFactory serviceFactoryFinal = serviceFactory; return AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() { public ServiceRegistration run() { return bundleContext.registerService(names, serviceFactoryFinal, serviceProperties); } }, acc); } else { return bundleContext.registerService(names, serviceFactory, serviceProperties); } }
public void testRegisterService() throws Exception { Class<?>[] clazz = new Class<?>[]{Serializable.class, HashMap.class, Cloneable.class, Map.class, LinkedHashMap.class}; String[] names = new String[clazz.length]; for (int i = 0; i < clazz.length; i++) { names[i] = clazz[i].getName(); } final Properties props = new Properties(); final ServiceRegistration reg = new MockServiceRegistration(); exporter.setBundleContext(new MockBundleContext() { public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { assertTrue(service instanceof ServiceFactory); return reg; } }); Object proxy = createMock(ServiceFactory.class); exporter.setTarget(proxy); exporter.setInterfaces(new Class<?>[]{ServiceFactory.class}); String beanName = "boo"; exporter.setTargetBeanName(beanName); expect(beanFactory.isSingleton(beanName)).andReturn(true); expect(beanFactory.isPrototype(beanName)).andReturn(false); expect(beanFactory.containsBean(beanName)).andReturn(true); expect(beanFactory.getBean(beanName)).andReturn(proxy); expect(beanFactory.getType(beanName)).andStubReturn((Class) ServiceFactory.class); beanFactoryControl.replay(); exporter.afterPropertiesSet(); assertSame(reg, exporter.registerService(clazz, props)); }
public void testServiceFactory() throws Exception { ServiceFactory factory = new MockServiceFactory(); ctx = new MockBundleContext(); exporter.setBundleContext(ctx); exporter.setBeanFactory(beanFactory); exporter.setInterfaces(new Class<?>[]{Serializable.class, Cloneable.class}); exporter.setTarget(factory); beanFactoryControl.replay(); exporter.afterPropertiesSet(); }
public void testPrototypeServiceFactory() throws Exception { ServiceFactory factory = new MockServiceFactory(); String beanName = "prototype-sf"; expect(beanFactory.isSingleton(beanName)).andReturn(false); expect(beanFactory.isPrototype(beanName)).andReturn(true); expect(beanFactory.containsBean(beanName)).andReturn(true); expect(beanFactory.getBean(beanName)).andReturn(factory); expect(beanFactory.getType(beanName)).andStubReturn((Class) factory.getClass()); exporter.setTargetBeanName(beanName); exporter.setInterfaces(new Class<?>[]{Serializable.class}); beanFactoryControl.replay(); exporter.afterPropertiesSet(); }
public void testNonSingletonServiceFactoryRegistration() throws Exception { TestRegistrationListener listener = new TestRegistrationListener(); ServiceFactory factory = new MockServiceFactory(); String beanName = "prototype-sf"; expect(beanFactory.isSingleton(beanName)).andReturn(false).times(3); expect(beanFactory.containsBean(beanName)).andReturn(true); expect(beanFactory.isPrototype(beanName)).andReturn(false); expect(beanFactory.getBean(beanName)).andReturn(factory); expect(beanFactory.getType(beanName)).andStubReturn((Class) factory.getClass()); exporter.setTargetBeanName(beanName); exporter.setInterfaces(new Class<?>[]{Serializable.class}); exporter.setListeners(new OsgiServiceRegistrationListener[]{listener}); beanFactoryControl.replay(); assertEquals(0, listener.registered.size()); assertEquals(0, listener.unregistered.size()); exporter.afterPropertiesSet(); assertEquals(1, listener.registered.size()); assertEquals(0, listener.unregistered.size()); assertNull(listener.registered.keySet().iterator().next()); exporter.destroy(); assertEquals(1, listener.unregistered.size()); assertNull(listener.unregistered.keySet().iterator().next()); }
public void testExtServiceFactoryListener() throws Exception { listener = new OsgiServiceRegistrationListenerAdapter(); listener.setTarget(new ExtServiceFactoryListener()); listener.setRegistrationMethod("registered"); listener.setUnregistrationMethod("unregistered"); listener.setBeanFactory(createMockBF()); listener.afterPropertiesSet(); Object service = new Object(); assertEquals(0, ServiceFactoryListener.REG_CALLS); assertEquals(0, ServiceFactoryListener.UNREG_CALLS); listener.registered(service, props); listener.unregistered(service, props); assertEquals(0, ServiceFactoryListener.REG_CALLS); assertEquals(0, ServiceFactoryListener.UNREG_CALLS); ServiceFactory factory = new MockServiceFactory(); listener.registered(factory, props); listener.unregistered(factory, props); assertEquals(1, ServiceFactoryListener.REG_CALLS); assertEquals(1, ServiceFactoryListener.UNREG_CALLS); ServiceFactory extFactory = new MockExtendedServiceFactory(); listener.registered(extFactory, props); listener.unregistered(extFactory, props); assertEquals(3, ServiceFactoryListener.REG_CALLS); assertEquals(3, ServiceFactoryListener.UNREG_CALLS); }
private Object getServiceAtIndex(int index) { Object sFactory = services.get(index); assertNotNull(sFactory); assertTrue(sFactory instanceof ServiceFactory); ServiceFactory fact = (ServiceFactory) sFactory; return fact.getService(null, null); }
@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(); }
ServiceReferenceImpl(Bundle bundle, Object obj, Dictionary<String, ?> dictionary, String[] strArr) { this.useCounters = new HashMap(0); this.cachedServices = null; if (obj instanceof ServiceFactory) { this.isServiceFactory = true; } else { this.isServiceFactory = false; checkService(obj, strArr); } this.bundle = bundle; this.service = obj; this.properties = dictionary == null ? new Hashtable() : new Hashtable(dictionary.size()); if (dictionary != null) { Enumeration keys = dictionary.keys(); while (keys.hasMoreElements()) { String str = (String) keys.nextElement(); this.properties.put(str, dictionary.get(str)); } } this.properties.put(Constants.OBJECTCLASS, strArr); Dictionary dictionary2 = this.properties; String str2 = Constants.SERVICE_ID; long j = nextServiceID + 1; nextServiceID = j; dictionary2.put(str2, Long.valueOf(j)); Integer num = dictionary == null ? null : (Integer) dictionary.get(Constants.SERVICE_RANKING); this.properties.put(Constants.SERVICE_RANKING, Integer.valueOf(num == null ? 0 : num.intValue())); this.registration = new ServiceRegistrationImpl(); }
public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object service) { Object bn = getBean(); // handle SF beans if (bn instanceof ServiceFactory) { ((ServiceFactory) bn).ungetService(bundle, serviceRegistration, service); } if (createTCCLProxy) { synchronized (proxyCache) { proxyCache.values().remove(new WeakReference(service)); } } }
public void testRegisterService() throws Exception { Class[] clazz = new Class[] { Serializable.class, HashMap.class, Cloneable.class, Map.class, LinkedHashMap.class }; String[] names = new String[clazz.length]; for (int i = 0; i < clazz.length; i++) { names[i] = clazz[i].getName(); } final Properties props = new Properties(); final ServiceRegistration reg = new MockServiceRegistration(); exporter.setBundleContext(new MockBundleContext() { public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { assertTrue(service instanceof ServiceFactory); return reg; } }); Object proxy = MockControl.createControl(ServiceFactory.class).getMock(); exporter.setTarget(proxy); exporter.setInterfaces(new Class[] { ServiceFactory.class }); String beanName = "boo"; exporter.setTargetBeanName(beanName); beanFactoryControl.expectAndReturn(beanFactory.isSingleton(beanName), false); beanFactoryControl.expectAndReturn(beanFactory.containsBean(beanName), true); beanFactoryControl.expectAndReturn(beanFactory.getType(beanName), proxy.getClass()); beanFactoryControl.replay(); exporter.afterPropertiesSet(); assertSame(reg, exporter.registerService(clazz, props)); }
@SuppressWarnings("unchecked") private <S> S adaptServiceFactory(S service) { if (service instanceof ServiceFactory) { ServiceFactory<S> factory = (ServiceFactory<S>) service; service = (S) new ServiceFactoryAdaptor<S>(factory); } return service; }
public BundleScopeServiceFactory(ServiceFactory serviceFactory) { Assert.notNull(serviceFactory); this.decoratedServiceFactory = serviceFactory; }
public void afterPropertiesSet() throws Exception { Assert.notNull(bundleContext, "required property 'bundleContext' has not been set"); hasNamedBean = StringUtils.hasText(targetBeanName); Assert.isTrue(hasNamedBean || target != null, "Either 'targetBeanName' or 'target' properties have to be set."); // if we have a name, we need a bean factory if (hasNamedBean) { Assert.notNull(beanFactory, "Required property 'beanFactory' has not been set."); } // initialize bean only when dealing with singletons and named beans if (hasNamedBean) { Assert.isTrue(beanFactory.containsBean(targetBeanName), "Cannot locate bean named '" + targetBeanName + "' inside the running bean factory."); if (beanFactory.isSingleton(targetBeanName)) { if (beanFactory instanceof ConfigurableListableBeanFactory) { ConfigurableListableBeanFactory clbf = (ConfigurableListableBeanFactory) beanFactory; BeanDefinition definition = clbf.getBeanDefinition(targetBeanName); if (!definition.isLazyInit()) { target = beanFactory.getBean(targetBeanName); targetClass = target.getClass(); } } } if (targetClass == null) { // lazily get the target class targetClass = beanFactory.getType(targetBeanName); } // when running inside a container, add the dependency between this bean and the target one addBeanFactoryDependency(); } else { targetClass = target.getClass(); } if (propertiesResolver == null) { propertiesResolver = new BeanNameServicePropertiesResolver(); ((BeanNameServicePropertiesResolver) propertiesResolver).setBundleContext(bundleContext); } // sanity check if (interfaces == null) { if (DefaultInterfaceDetector.DISABLED.equals(interfaceDetector)) throw new IllegalArgumentException( "No service interface(s) specified and auto-export discovery disabled; change at least one of these properties."); interfaces = new Class[0]; } // check visibility type else { if (!ServiceFactory.class.isAssignableFrom(targetClass)) { for (int interfaceIndex = 0; interfaceIndex < interfaces.length; interfaceIndex++) { Class<?> intf = interfaces[interfaceIndex]; Assert.isAssignable(intf, targetClass, "Exported service object does not implement the given interface: "); } } } // check service properties listener if (serviceProperties instanceof ServicePropertiesListenerManager) { propertiesListener = new PropertiesMonitor(); ((ServicePropertiesListenerManager) serviceProperties).addListener(propertiesListener); } boolean shouldRegisterAtStartup; synchronized (lock) { shouldRegisterAtStartup = registerAtStartup; } resolver = new LazyTargetResolver(target, beanFactory, targetBeanName, cacheTarget, getNotifier(), getLazyListeners()); if (shouldRegisterAtStartup) { registerService(); } }
public void registered(ServiceFactory service, Map serviceProperties) throws Exception { ServiceFactoryListener.REG_CALLS++; }
public void unregistered(ServiceFactory service, Map serviceProperties) throws Exception { ServiceFactoryListener.UNREG_CALLS++; }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testAddingRemoved() 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(""); EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_CONFIGS_SUPPORTED)).andReturn(""); 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(); c.reset(); rsaReg.unregister(); EasyMock.expectLastCall(); EasyMock.expect(context.ungetService(providerRef)).andReturn(true); c.replay(); tracker.removedService(providerRef, rsaReg); c.verify(); }
private ServiceRegistration<Application> registerApplication( ServiceFactory<Application> serviceFactory, Object... keyValues) { Dictionary<String, Object> properties = new Hashtable<>(); properties.put(JAX_RS_APPLICATION_BASE, "/test-application"); for (int i = 0; i < keyValues.length; i = i + 2) { properties.put(keyValues[i].toString(), keyValues[i + 1]); } ServiceRegistration<Application> serviceRegistration = bundleContext.registerService( Application.class, serviceFactory, properties); _registrations.add(serviceRegistration); return serviceRegistration; }
public void afterPropertiesSet() throws Exception { Assert.notNull(bundleContext, "required property 'bundleContext' has not been set"); hasNamedBean = StringUtils.hasText(targetBeanName); Assert.isTrue(hasNamedBean || target != null, "Either 'targetBeanName' or 'target' properties have to be set."); // if we have a name, we need a bean factory if (hasNamedBean) { Assert.notNull(beanFactory, "Required property 'beanFactory' has not been set."); } // initialize bean only when dealing with singletons and named beans if (hasNamedBean) { Assert.isTrue(beanFactory.containsBean(targetBeanName), "Cannot locate bean named '" + targetBeanName + "' inside the running bean factory."); if (beanFactory.isSingleton(targetBeanName)) { target = beanFactory.getBean(targetBeanName); targetClass = target.getClass(); } else { targetClass = beanFactory.getType(targetBeanName); } // when running inside a container, add the dependency between this bean and the target one addBeanFactoryDependency(); } else targetClass = target.getClass(); if (propertiesResolver == null) { propertiesResolver = new BeanNameServicePropertiesResolver(); ((BeanNameServicePropertiesResolver) propertiesResolver).setBundleContext(bundleContext); } // sanity check if (interfaces == null) { if (AutoExport.DISABLED.equals(autoExport)) throw new IllegalArgumentException( "No service interface(s) specified and auto-export discovery disabled; change at least one of these properties."); interfaces = new Class[0]; } // check visibility type else { if (!ServiceFactory.class.isAssignableFrom(targetClass)) { for (int interfaceIndex = 0; interfaceIndex < interfaces.length; interfaceIndex++) { Class intf = interfaces[interfaceIndex]; Assert.isAssignable(intf, targetClass, "Exported service object does not implement the given interface: "); } } } boolean shouldRegisterAtStartup; synchronized (lock) { shouldRegisterAtStartup = registerAtStartup; } if (shouldRegisterAtStartup) registerService(); }
@Override public <S> ServiceRegistration<S> registerService(Class<S> clazz, ServiceFactory<S> factory, Dictionary<String, ?> properties) { return null; }
ServiceFactoryAdaptor(ServiceFactory<S> delegate) { IllegalArgumentAssertion.assertNotNull(delegate, "delegate"); this.delegate = delegate; }
/** * * Implements <code>BundleActivator.start()</code> to register a * LogServiceFactory. * * @param bundleContext the framework context for the bundle * @throws Exception */ public void start(BundleContext bundleContext) throws Exception { Properties props = new Properties(); props.put("description", "An SLF4J LogService implementation."); ServiceFactory factory = new LogServiceFactory(); bundleContext.registerService(LogService.class.getName(), factory, props); }