in testing/support/src/main/java/org/apache/servicemix/platform/testing/support/AbstractIntegrationTest.java [194:235]
public <T> T getOsgiService(Class<T> type, long timeout) {
// translate from seconds to miliseconds
long time = timeout * 1000;
// use the counter to make sure the threads block
final Counter counter = new Counter("waitForOsgiService on bnd=" + type.getName());
counter.increment();
final List<T> services = new ArrayList<T>();
ServiceListener listener = new ServiceListener() {
@SuppressWarnings("unchecked")
public void serviceChanged(ServiceEvent event) {
if (event.getType() == ServiceEvent.REGISTERED) {
services.add((T) bundleContext.getService(event.getServiceReference()));
counter.decrement();
}
}
};
String filter = OsgiFilterUtils.unifyFilter(type.getName(), null);
OsgiListenerUtils.addServiceListener(bundleContext, listener, filter);
if (logger.isDebugEnabled())
logger.debug("start waiting for OSGi service=" + type.getName());
try {
if (counter.waitForZero(time)) {
logger.warn("waiting for OSGi service=" + type.getName() + " timed out");
throw new RuntimeException("Gave up waiting for OSGi service '" + type.getName() + "' to be created");
}
else if (logger.isDebugEnabled()) {
logger.debug("found OSGi service=" + type.getName());
}
return services.get(0);
}
finally {
// inform waiting thread
bundleContext.removeServiceListener(listener);
}
}