1 package org
.argeo
.osgi
.util
;
3 import java
.util
.concurrent
.CancellationException
;
4 import java
.util
.concurrent
.ExecutionException
;
5 import java
.util
.concurrent
.Future
;
6 import java
.util
.concurrent
.TimeUnit
;
7 import java
.util
.concurrent
.TimeoutException
;
8 import java
.util
.function
.Function
;
10 import org
.osgi
.framework
.BundleContext
;
11 import org
.osgi
.framework
.FrameworkUtil
;
12 import org
.osgi
.framework
.ServiceReference
;
13 import org
.osgi
.util
.tracker
.ServiceTracker
;
15 public class OnServiceRegistration
<R
> implements Future
<R
> {
16 private BundleContext ownBundleContext
= FrameworkUtil
.getBundle(OnServiceRegistration
.class).getBundleContext();
18 private ServiceTracker
<?
, ?
> st
;
21 private boolean cancelled
= false;
22 private Throwable exception
;
24 public <T
> OnServiceRegistration(Class
<T
> clss
, Function
<T
, R
> function
) {
25 this(null, clss
, function
);
28 public <T
> OnServiceRegistration(BundleContext bundleContext
, Class
<T
> clss
, Function
<T
, R
> function
) {
29 st
= new ServiceTracker
<T
, T
>(bundleContext
!= null ? bundleContext
: ownBundleContext
, clss
, null) {
32 public T
addingService(ServiceReference
<T
> reference
) {
33 T service
= super.addingService(reference
);
35 if (result
!= null)// we only want the first one
37 result
= function
.apply(service
);
39 } catch (Exception e
) {
47 st
.open(bundleContext
== null);
51 public boolean cancel(boolean mayInterruptIfRunning
) {
52 if (result
!= null || exception
!= null || cancelled
)
60 public boolean isCancelled() {
65 public boolean isDone() {
66 return result
!= null || cancelled
;
70 public R
get() throws InterruptedException
, ExecutionException
{
72 return tryGetResult();
76 public R
get(long timeout
, TimeUnit unit
) throws InterruptedException
, ExecutionException
, TimeoutException
{
77 st
.waitForService(TimeUnit
.MILLISECONDS
.convert(timeout
, unit
));
79 throw new TimeoutException("No result after " + timeout
+ " " + unit
);
80 return tryGetResult();
83 protected R
tryGetResult() throws ExecutionException
, CancellationException
{
85 throw new CancellationException();
86 if (exception
!= null)
87 throw new ExecutionException(exception
);
88 if (result
== null)// this should not happen
90 throw new IllegalStateException("No result available");
91 } catch (Exception e
) {
93 throw new ExecutionException(e
);