use of org.osgi.framework.ServiceEvent in project aries by apache.
the class TransactionLogTest method doRecoveryRequired.
public void doRecoveryRequired(BiConsumer<XAResource, XAResource> ordering, TransactionStatus expectedFinalState) throws Exception {
//Register the recoverable resource
ArgumentCaptor<ServiceListener> captor = ArgumentCaptor.forClass(ServiceListener.class);
Mockito.verify(ctx).addServiceListener(captor.capture(), Mockito.anyString());
Mockito.when(ctx.getService(serviceRef)).thenReturn(new TestRecoverableResource("foo", dataSource));
captor.getValue().serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, serviceRef));
XAConnection xaConn = dataSource.getXAConnection();
AtomicReference<TransactionStatus> ref = new AtomicReference<TransactionStatus>();
try {
txControl.required(() -> {
txControl.getCurrentContext().postCompletion(ref::set);
Connection conn = xaConn.getConnection();
// conn.setAutoCommit(false);
XAResource dsResource = xaConn.getXAResource();
XAResource poison = Mockito.mock(XAResource.class);
Mockito.when(poison.prepare(Mockito.any())).thenAnswer(i -> {
conn.createStatement().execute("shutdown immediately");
Thread.sleep(1000);
return XA_OK;
});
ordering.accept(dsResource, poison);
return conn.createStatement().execute("Insert into TEST_TABLE values ( 'Hello World!' )");
});
} catch (TransactionException te) {
assertEquals(expectedFinalState, ref.get());
assertEquals(expectedFinalState == ROLLED_BACK, te instanceof TransactionRolledBackException);
} finally {
try {
xaConn.close();
} catch (SQLException sqle) {
}
}
setupServerAndDataSource();
}
use of org.osgi.framework.ServiceEvent in project karaf by apache.
the class GuardProxyCatalogTest method testHandleServiceModified.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleServiceModified() throws Exception {
Dictionary<String, Object> config = new Hashtable<>();
config.put(Constants.SERVICE_PID, "test.1.2.3");
config.put("service.guard", "(objectClass=" + TestServiceAPI.class.getName() + ")");
config.put("doit", "role.1");
Dictionary<String, Object> config2 = new Hashtable<>();
config2.put(Constants.SERVICE_PID, "test.1.2.4");
config2.put("service.guard", "(objectClass=" + TestServiceAPI2.class.getName() + ")");
config2.put("doit", "role.2");
BundleContext bc = mockConfigAdminBundleContext(config, config2);
GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
// The service being proxied has these properties
long serviceID = 1L;
final Hashtable<String, Object> serviceProps = new Hashtable<>();
serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName(), TestServiceAPI2.class.getName() });
serviceProps.put(Constants.SERVICE_ID, serviceID);
// will be overwritten
serviceProps.put(GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY, Arrays.asList("someone"));
Object myObject = new Object();
serviceProps.put("foo.bar", myObject);
BundleContext providerBC = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(providerBC.registerService(EasyMock.aryEq(new String[] { TestServiceAPI.class.getName(), TestServiceAPI2.class.getName() }), EasyMock.anyObject(), EasyMock.anyObject(Dictionary.class))).andAnswer((IAnswer) () -> {
final Dictionary props = (Dictionary) EasyMock.getCurrentArguments()[2];
assertEquals(Boolean.TRUE, props.get(GuardProxyCatalog.PROXY_SERVICE_KEY));
ServiceRegistration reg = EasyMock.createMock(ServiceRegistration.class);
ServiceReference sr = mockServiceReference(props);
EasyMock.expect(reg.getReference()).andReturn(sr).anyTimes();
reg.setProperties(EasyMock.isA(Dictionary.class));
EasyMock.expectLastCall().andAnswer(() -> {
ArrayList<String> oldKeys = Collections.list(props.keys());
for (String key : oldKeys) {
props.remove(key);
}
Dictionary<String, Object> newProps = (Dictionary<String, Object>) EasyMock.getCurrentArguments()[0];
for (String key : Collections.list(newProps.keys())) {
props.put(key, newProps.get(key));
}
return null;
}).once();
EasyMock.replay(reg);
return reg;
}).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);
gpc.proxyIfNotAlreadyProxied(sr);
GuardProxyCatalog.CreateProxyRunnable runnable = gpc.createProxyQueue.take();
runnable.run(getProxyManager());
ServiceRegistrationHolder holder = gpc.proxyMap.get(serviceID);
ServiceRegistration<?> reg = holder.registration;
for (String key : serviceProps.keySet()) {
if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
assertEquals(new HashSet(Arrays.asList("role.1", "role.2")), reg.getReference().getProperty(key));
} else {
assertEquals(serviceProps.get(key), reg.getReference().getProperty(key));
}
}
assertEquals(Boolean.TRUE, reg.getReference().getProperty(GuardProxyCatalog.PROXY_SERVICE_KEY));
// now change the original service and let the proxy react
serviceProps.put("test", "property");
assertEquals("Precondition, the mocked reference should have picked up this change", "property", sr.getProperty("test"));
gpc.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, sr));
assertEquals("Changing the service should not change the number of proxies", 1, gpc.proxyMap.size());
for (String key : serviceProps.keySet()) {
if (GuardProxyCatalog.SERVICE_GUARD_ROLES_PROPERTY.equals(key)) {
assertEquals(new HashSet(Arrays.asList("role.1", "role.2")), reg.getReference().getProperty(key));
} else {
assertEquals(serviceProps.get(key), reg.getReference().getProperty(key));
}
}
assertEquals("property", reg.getReference().getProperty("test"));
assertEquals(Boolean.TRUE, reg.getReference().getProperty(GuardProxyCatalog.PROXY_SERVICE_KEY));
}
use of org.osgi.framework.ServiceEvent in project karaf by apache.
the class GuardProxyCatalogTest method testProxyCreationThread.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testProxyCreationThread() throws Exception {
ProxyManager proxyManager = getProxyManager();
ConfigurationAdmin ca = EasyMock.createMock(ConfigurationAdmin.class);
EasyMock.expect(ca.listConfigurations(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
EasyMock.replay(ca);
ServiceReference pmSref = EasyMock.createMock(ServiceReference.class);
EasyMock.replay(pmSref);
ServiceReference pmSref2 = EasyMock.createMock(ServiceReference.class);
EasyMock.replay(pmSref2);
ServiceReference cmSref = EasyMock.createMock(ServiceReference.class);
EasyMock.replay(cmSref);
Bundle b = EasyMock.createMock(Bundle.class);
EasyMock.expect(b.getBundleId()).andReturn(23992734L).anyTimes();
EasyMock.replay(b);
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
EasyMock.expect(bc.createFilter(EasyMock.isA(String.class))).andAnswer(() -> FrameworkUtil.createFilter((String) EasyMock.getCurrentArguments()[0])).anyTimes();
final ServiceListener[] pmListenerHolder = new ServiceListener[1];
String pmFilter = "(&(objectClass=" + ProxyManager.class.getName() + ")" + "(!(" + GuardProxyCatalog.PROXY_SERVICE_KEY + "=*)))";
bc.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.eq(pmFilter));
EasyMock.expectLastCall().andAnswer(() -> {
pmListenerHolder[0] = (ServiceListener) EasyMock.getCurrentArguments()[0];
return null;
}).anyTimes();
EasyMock.expect(bc.getServiceReferences(EasyMock.anyObject(String.class), EasyMock.contains(ConfigurationAdmin.class.getName()))).andReturn(new ServiceReference[] { cmSref }).anyTimes();
EasyMock.expect(bc.getService(pmSref)).andReturn(proxyManager).anyTimes();
EasyMock.expect(bc.getService(pmSref2)).andReturn(proxyManager).anyTimes();
EasyMock.expect(bc.getService(cmSref)).andReturn(ca).anyTimes();
EasyMock.replay(bc);
// This should put a ServiceListener in the pmListenerHolder, the ServiceTracker does that
GuardProxyCatalog gpc = new GuardProxyCatalog(bc);
// The service being proxied has these properties
final Hashtable<String, Object> serviceProps = new Hashtable<>();
serviceProps.put(Constants.OBJECTCLASS, new String[] { TestServiceAPI.class.getName() });
serviceProps.put(Constants.SERVICE_ID, 162L);
final Map<ServiceReference<?>, Object> serviceMap = new HashMap<>();
// 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);
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();
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);
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());
assertEquals(1, gpc.createProxyQueue.size());
// The actual proxy creation is done asynchronously.
GuardProxyCatalog.ServiceRegistrationHolder holder = gpc.proxyMap.get(162L);
assertNull("The registration shouldn't have happened yet", holder.registration);
assertEquals(1, gpc.createProxyQueue.size());
Thread[] tarray = new Thread[Thread.activeCount()];
Thread.enumerate(tarray);
for (Thread t : tarray) {
if (t != null) {
assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
}
}
// make the proxy manager appear
pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref));
// give the system some time to send the events...
Thread.sleep(400);
Thread ourThread = null;
Thread[] tarray2 = new Thread[Thread.activeCount()];
Thread.enumerate(tarray2);
for (Thread t : tarray2) {
if (t != null) {
if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
ourThread = t;
}
}
}
assertNotNull(ourThread);
assertTrue(ourThread.isDaemon());
assertTrue(ourThread.isAlive());
assertNotNull(holder.registration);
assertEquals(0, gpc.createProxyQueue.size());
int numProxyThreads = 0;
pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, pmSref2));
// give the system some time to send the events...
Thread.sleep(300);
Thread[] tarray3 = new Thread[Thread.activeCount()];
Thread.enumerate(tarray3);
for (Thread t : tarray3) {
if (t != null) {
if (t.getName().equals(GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME)) {
numProxyThreads++;
}
}
}
assertEquals("Maximum 1 proxy thread, even if there is more than 1 proxy service", 1, numProxyThreads);
// Clean up thread
pmListenerHolder[0].serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, pmSref));
// Give the system some time to stop the threads...
Thread.sleep(300);
Thread[] tarray4 = new Thread[Thread.activeCount()];
Thread.enumerate(tarray4);
for (Thread t : tarray4) {
if (t != null) {
assertTrue(!GuardProxyCatalog.PROXY_CREATOR_THREAD_NAME.equals(t.getName()));
}
}
}
use of org.osgi.framework.ServiceEvent in project karaf by apache.
the class GuardingEventHookTest method testEventHookProxyEvents.
@SuppressWarnings("unchecked")
@Test
public void testEventHookProxyEvents() throws Exception {
BundleContext frameworkBC = mockBundleContext(0L);
Dictionary<String, Object> config = new Hashtable<>();
config.put("service.guard", "(service.id=*)");
BundleContext hookBC = mockConfigAdminBundleContext(frameworkBC, config);
GuardProxyCatalog gpc = new GuardProxyCatalog(hookBC);
// any service will match
Filter serviceFilter = FrameworkUtil.createFilter("(service.id=*)");
GuardingEventHook geh = new GuardingEventHook(hookBC, gpc, serviceFilter);
BundleContext client1BC = mockBundleContext(123L);
// Create a proxy service mock
Dictionary<String, Object> props = new Hashtable<>();
props.put(Constants.SERVICE_ID, 13L);
props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
ServiceReference<?> sref = mockServiceReference(props);
Map<BundleContext, Collection<ListenerInfo>> listeners = new HashMap<>();
listeners.put(client1BC, Collections.emptyList());
// Send the event. It should have no effect because the service is already a proxy for the client
assertEquals("Precondition", 0, gpc.proxyMap.size());
geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref), listeners);
assertEquals("No changes expected for the proxy map.", 0, gpc.proxyMap.size());
assertEquals("The event should be delivered to the client", 1, listeners.size());
// send the event to a different client, this client should also see the event as the proxy Service Factory is shared
Map<BundleContext, Collection<ListenerInfo>> listeners2 = new HashMap<>();
listeners2.put(mockBundleContext(51L), Collections.emptyList());
geh.event(new ServiceEvent(ServiceEvent.REGISTERED, sref), listeners2);
assertEquals("No changes expected for the proxy map.", 0, gpc.proxyMap.size());
assertEquals("The event should be delivered to the client", 1, listeners2.size());
}
use of org.osgi.framework.ServiceEvent in project karaf by apache.
the class GuardProxyCatalogTest method testHandleServiceUnregistering.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleServiceUnregistering() throws Exception {
BundleContext clientBC = openStrictMockBundleContext(mockBundle(12345L));
BundleContext client2BC = openStrictMockBundleContext(mockBundle(6L));
EasyMock.replay(clientBC);
EasyMock.replay(client2BC);
Hashtable<String, Object> props = new Hashtable<>();
long originalServiceID = 12345678901234L;
props.put(Constants.SERVICE_ID, new Long(originalServiceID));
props.put("foo", "bar");
ServiceReference<?> originalRef = mockServiceReference(props);
Hashtable<String, Object> props2 = new Hashtable<>();
long anotherServiceID = 5123456789012345L;
props2.put(Constants.SERVICE_ID, anotherServiceID);
ServiceReference<?> anotherRef = mockServiceReference(props2);
GuardProxyCatalog gpc = new GuardProxyCatalog(mockBundleContext());
ServiceRegistration<?> proxyReg = EasyMock.createMock(ServiceRegistration.class);
EasyMock.expect(proxyReg.getReference()).andReturn((ServiceReference) mockServiceReference(props)).anyTimes();
proxyReg.unregister();
EasyMock.expectLastCall().once();
EasyMock.replay(proxyReg);
ServiceRegistrationHolder srh = new GuardProxyCatalog.ServiceRegistrationHolder();
srh.registration = proxyReg;
ServiceRegistration<?> proxy2Reg = EasyMock.createMock(ServiceRegistration.class);
EasyMock.replay(proxy2Reg);
ServiceRegistrationHolder srh2 = new GuardProxyCatalog.ServiceRegistrationHolder();
srh2.registration = proxy2Reg;
gpc.proxyMap.put(originalServiceID, srh);
gpc.proxyMap.put(anotherServiceID, srh2);
assertEquals("Precondition", 2, gpc.proxyMap.size());
gpc.createProxyQueue.put(new MockCreateProxyRunnable(originalServiceID));
gpc.createProxyQueue.put(new MockCreateProxyRunnable(777));
assertEquals("Precondition", 2, gpc.createProxyQueue.size());
gpc.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, originalRef));
assertEquals("Registered events should be ignored", 2, gpc.proxyMap.size());
assertEquals("Registered events should be ignored", 2, gpc.createProxyQueue.size());
Hashtable<String, Object> proxyProps = new Hashtable<>(props);
proxyProps.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE);
ServiceReference<?> proxyRef = mockServiceReference(proxyProps);
gpc.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, proxyRef));
assertEquals("Unregistering the proxy should be ignored by the listener", 2, gpc.proxyMap.size());
assertEquals("Unregistering the proxy should be ignored by the listener", 2, gpc.createProxyQueue.size());
gpc.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, originalRef));
assertEquals("The proxy for this service should have been removed", 1, gpc.proxyMap.size());
assertEquals(anotherRef.getProperty(Constants.SERVICE_ID), gpc.proxyMap.keySet().iterator().next());
assertEquals("The create proxy job for this service should have been removed", 1, gpc.createProxyQueue.size());
assertEquals(777, gpc.createProxyQueue.iterator().next().getOriginalServiceID());
EasyMock.verify(proxyReg);
EasyMock.verify(proxy2Reg);
}
Aggregations