use of org.osgi.framework.ServiceFactory in project sling by apache.
the class OsgiServiceUtilTest method testServiceFactoryViaManualRegistration.
@Test
public void testServiceFactoryViaManualRegistration() {
final ServiceFactory1 serviceFactory1 = new ServiceFactory1();
bundleContext.registerService(ServiceFactory1.class.getName(), new ServiceFactory() {
@Override
public Object getService(Bundle bundle, ServiceRegistration registration) {
return serviceFactory1;
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
// nothing to do
}
}, null);
assertSame(serviceFactory1, bundleContext.getService(bundleContext.getServiceReference(ServiceFactory1.class.getName())));
}
use of org.osgi.framework.ServiceFactory in project aries by apache.
the class ServiceRecipe method createService.
private void createService() {
try {
if (service == null) {
LOGGER.debug("Creating service instance");
//We can't use the BlueprintRepository because we don't know what interfaces
//to use yet! We have to be a bit smarter.
ExecutionContext old = ExecutionContext.Holder.setContext(blueprintContainer.getRepository());
try {
Object o = serviceRecipe.create();
if (o instanceof Convertible) {
o = blueprintContainer.getRepository().convert(o, new ReifiedType(Object.class));
validateClasses(o);
} else if (o instanceof UnwrapperedBeanHolder) {
UnwrapperedBeanHolder holder = (UnwrapperedBeanHolder) o;
if (holder.unwrapperedBean instanceof ServiceFactory) {
//If a service factory is used, make sure the proxy classes implement this
//interface so that later on, internalGetService will create the real
//service from it.
LOGGER.debug("{} implements ServiceFactory, creating proxy that also implements this", holder.unwrapperedBean);
Collection<Class<?>> cls = getClassesForProxying(holder.unwrapperedBean);
cls.add(blueprintContainer.loadClass("org.osgi.framework.ServiceFactory"));
o = BeanRecipe.wrap(holder, cls);
} else {
validateClasses(holder.unwrapperedBean);
o = BeanRecipe.wrap(holder, getClassesForProxying(holder.unwrapperedBean));
}
} else if (!(o instanceof ServiceFactory)) {
validateClasses(o);
}
service = o;
} catch (Exception e) {
LOGGER.error("Error retrieving service from " + this, e);
throw new ComponentDefinitionException(e);
} finally {
ExecutionContext.Holder.setContext(old);
}
LOGGER.debug("Service created: {}", service);
}
// When the service is first requested, we need to create listeners and call them
if (!initialServiceRegistration && listeners == null) {
LOGGER.debug("Creating listeners");
if (listenersRecipe != null) {
listeners = (List) createRecipe(listenersRecipe);
} else {
listeners = Collections.emptyList();
}
LOGGER.debug("Listeners created: {}", listeners);
if (registration.get() != null) {
LOGGER.debug("Calling listeners for initial service registration");
for (ServiceListener listener : listeners) {
listener.register(service, registrationProperties);
}
} else {
LOGGER.debug("Calling listeners for initial service unregistration");
for (ServiceListener listener : listeners) {
listener.unregister(service, registrationProperties);
}
}
}
} catch (RuntimeException e) {
LOGGER.error("Error retrieving service from " + this, e);
throw e;
}
}
use of org.osgi.framework.ServiceFactory in project aries by apache.
the class ProviderBundleTrackerCustomizerGenericCapabilityTest method mockSPIBundleContext4.
@SuppressWarnings("unchecked")
private BundleContext mockSPIBundleContext4() {
BundleContext implBC = EasyMock.createNiceMock(BundleContext.class);
implBC.registerService(EasyMock.anyString(), EasyMock.anyObject(), (Dictionary<String, ?>) EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<ServiceRegistration<Object>>() {
@Override
public ServiceRegistration<Object> answer() throws Throwable {
final String className = (String) EasyMock.getCurrentArguments()[0];
final Object serviceObject = EasyMock.getCurrentArguments()[1];
final Dictionary<String, Object> registrationProps = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
return new ServiceRegistrationImpl(className, serviceObject, registrationProps);
}
}).anyTimes();
implBC.getService(EasyMock.anyObject(ServiceReference.class));
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
ServiceRegistrationImpl reg = (ServiceRegistrationImpl) EasyMock.getCurrentArguments()[0];
Object svc = reg.getServiceObject();
if (svc instanceof ServiceFactory) {
return ((ServiceFactory) svc).getService(null, reg);
} else {
return svc;
}
}
}).anyTimes();
EasyMock.replay(implBC);
return implBC;
}
use of org.osgi.framework.ServiceFactory in project karaf by apache.
the class GuardProxyCatalogTest method testCreateProxy.
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object testCreateProxy(BundleContext bc, Class[] objectClasses, final Class[] proxyRegClasses, Object testService, final Map<ServiceReference, Object> serviceMap) throws Exception {
// A linked hash map to keep iteration order over the keys predictable
final LinkedHashMap<String, Class> objClsMap = new LinkedHashMap<>();
for (Class cls : objectClasses) {
objClsMap.put(cls.getName(), cls);
}
// A linked hash map to keep iteration order over the keys predictable
final LinkedHashMap<String, Class> proxyRegClsMap = new LinkedHashMap<>();
for (Class cls : proxyRegClasses) {
proxyRegClsMap.put(cls.getName(), cls);
}
// Create the object that is actually being tested here
GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
// The service being proxied has these properties
long serviceID = Long.MAX_VALUE;
final Hashtable<String, Object> serviceProps = new Hashtable<>();
serviceProps.put(Constants.OBJECTCLASS, objClsMap.keySet().toArray(new String[] {}));
serviceProps.put(Constants.SERVICE_ID, serviceID);
// will be overwritten
serviceProps.put(GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY, Arrays.asList("everyone"));
serviceProps.put("bar", "foo");
// The mock bundle context for the bundle providing the service is set up here
BundleContext providerBC = EasyMock.createMock(BundleContext.class);
// These are the expected service properties of the proxy registration. Note the proxy marker...
final Hashtable<String, Object> expectedProxyProps = new Hashtable<>(serviceProps);
expectedProxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
// This will check that the right proxy is being registered.
EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
if (!runningUnderCoverage) {
assertArrayEquals(proxyRegClsMap.keySet().toArray(new String[] {}), (String[]) EasyMock.getCurrentArguments()[0]);
Object svc = EasyMock.getCurrentArguments()[1];
assertTrue(svc instanceof ServiceFactory);
}
Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
for (String key : expectedProxyProps.keySet()) {
if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
assertTrue("The roles property should have been overwritten", !Arrays.asList("everyone").equals(props.get(key)));
} else {
assertEquals(expectedProxyProps.get(key), props.get(key));
}
}
ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
ServiceReference sr = mockServiceReference(props);
EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
reg.unregister();
EasyMock.expectLastCall().once();
EasyMock.replay(reg);
serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
return reg;
}).once();
EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
EasyMock.replay(providerBC);
// In some cases the proxy-creating code is looking for a classloader (e.g. when run through
// a coverage tool such as EclEmma). This will satisfy that.
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
EasyMock.replay(bw);
// The mock bundle that provides the original service (and also the proxy is registered with this)
Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
EasyMock.replay(providerBundle);
ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
// The mock bundle context for the client bundle
BundleContext clientBC = EasyMock.createMock(BundleContext.class);
EasyMock.expect(clientBC.getService(sr)).andReturn(testService).anyTimes();
EasyMock.replay(clientBC);
// The mock bundle that consumes the service
Bundle clientBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(clientBundle.getBundleId()).andReturn(2999L).anyTimes();
EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes();
EasyMock.expect(clientBundle.loadClass(EasyMock.isA(String.class))).andAnswer((IAnswer) () -> objClsMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
EasyMock.replay(clientBundle);
assertEquals("Precondition", 0, gpc.proxyMap.size());
assertEquals("Precondition", 0, gpc.createProxyQueue.size());
// Create the proxy for the service
gpc.proxyIfNotAlreadyProxied(sr);
assertEquals(1, gpc.proxyMap.size());
// The actual proxy creation is done asynchronously.
GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
assertNull("The registration shouldn't have happened yet", holder.registration);
assertEquals(1, gpc.createProxyQueue.size());
// Mimic the thread that works the queue to create the proxy
GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
ProxyManager pm = getProxyManager();
runnable.run(pm);
// The runnable should have put the actual registration in the holder
ServiceReference<?> proxySR = holder.registration.getReference();
for (String key : expectedProxyProps.keySet()) {
if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
assertTrue("The roles property should have been overwritten", !Arrays.asList("everyone").equals(proxySR.getProperty(key)));
} else {
assertEquals(expectedProxyProps.get(key), proxySR.getProperty(key));
}
}
// Check that the proxy registration was done on the original provider bundle's context
EasyMock.verify(providerBC);
// Test that the actual proxy invokes the original service...
ServiceFactory proxyServiceSF = (ServiceFactory) serviceMap.get(proxySR);
Object proxyService = proxyServiceSF.getService(clientBundle, null);
assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
return proxyService;
}
use of org.osgi.framework.ServiceFactory in project karaf by apache.
the class GuardProxyCatalogTest method testServiceFactoryBehaviour.
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testServiceFactoryBehaviour() throws Exception {
final Map<ServiceReference, Object> serviceMap = new HashMap<>();
TestServiceAPI testService = new TestService();
BundleContext bc = mockConfigAdminBundleContext();
GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
// The service being proxied has these properties
long serviceID = 117L;
final Hashtable<String, Object> serviceProps = new Hashtable<>();
serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName() });
serviceProps.put(Constants.SERVICE_ID, serviceID);
serviceProps.put("bar", 42L);
BundleContext providerBC = EasyMock.createMock(BundleContext.class);
EasyMock.expect(providerBC.registerService(EasyMock.isA(String[].class), EasyMock.anyObject(), EasyMock.isA(Dictionary.class))).andAnswer((IAnswer) () -> {
Dictionary<String, Object> props = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[2];
ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
ServiceReference sr = mockServiceReference(props);
EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
EasyMock.replay(reg);
serviceMap.put(sr, EasyMock.getCurrentArguments()[1]);
return reg;
}).once();
EasyMock.expect(providerBC.getService(EasyMock.isA(ServiceReference.class))).andAnswer(() -> serviceMap.get(EasyMock.getCurrentArguments()[0])).anyTimes();
EasyMock.replay(providerBC);
// In some cases the proxy-creating code is looking for a classloader (e.g. when run through
// a coverage tool such as EclEmma). This will satisfy that.
BundleWiring bw = EasyMock.createMock(BundleWiring.class);
EasyMock.expect(bw.getClassLoader()).andReturn(getClass().getClassLoader()).anyTimes();
EasyMock.replay(bw);
// The mock bundle that provides the original service (and also the proxy is registered with this)
Bundle providerBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(providerBundle.getBundleContext()).andReturn(providerBC).anyTimes();
EasyMock.expect(providerBundle.adapt(BundleWiring.class)).andReturn(bw).anyTimes();
EasyMock.replay(providerBundle);
ServiceReference sr = mockServiceReference(providerBundle, serviceProps);
// The mock bundle context for the client bundle
BundleContext clientBC = EasyMock.createMock(BundleContext.class);
EasyMock.expect(clientBC.getService(sr)).andReturn(testService).anyTimes();
EasyMock.replay(clientBC);
// The mock bundle that consumes the service
Bundle clientBundle = EasyMock.createNiceMock(Bundle.class);
EasyMock.expect(clientBundle.getBundleContext()).andReturn(clientBC).anyTimes();
EasyMock.replay(clientBundle);
gpc.proxyIfNotAlreadyProxied(sr);
// The actual proxy creation is done asynchronously.
GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
// Mimic the thread that works the queue to create the proxy
GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
assertEquals(117L, runnable.getOriginalServiceID());
ProxyManager pm = getProxyManager();
runnable.run(pm);
// The runnable should have put the actual registration in the holder
ServiceReference<?> proxySR = holder.registration.getReference();
// Check that the proxy registration was done on the original provider bundle's context
EasyMock.verify(providerBC);
// Test that the actual proxy invokes the original service...
ServiceFactory proxyServiceSF = (ServiceFactory) serviceMap.get(proxySR);
TestServiceAPI proxyService = (TestServiceAPI) proxyServiceSF.getService(clientBundle, null);
assertNotSame("The proxy should not be the same object as the original service", testService, proxyService);
assertEquals("Doing it", proxyService.doit());
EasyMock.reset(clientBC);
EasyMock.expect(clientBC.ungetService(sr)).andReturn(true).once();
EasyMock.replay(clientBC);
proxyServiceSF.ungetService(clientBundle, null, proxyService);
EasyMock.verify(clientBC);
}
Aggregations