01: package org.objectweb.celtix.bus.jaxws;
02:
03: import java.util.concurrent.ExecutionException;
04: import java.util.concurrent.Future;
05: import java.util.concurrent.TimeUnit;
06: import java.util.concurrent.TimeoutException;
07: import java.util.logging.Level;
08: import java.util.logging.Logger;
09:
10: import javax.xml.ws.AsyncHandler;
11: import javax.xml.ws.Response;
12:
13: import org.objectweb.celtix.common.i18n.Message;
14: import org.objectweb.celtix.common.logging.LogUtils;
15:
16: public class AsyncCallbackFuture implements Future, Runnable {
17:
18: private static final Logger LOG = LogUtils
19: .getL7dLogger(AsyncCallbackFuture.class);
20: private final Response response;
21: private final AsyncHandler callback;
22: private boolean done;
23:
24: public AsyncCallbackFuture(Response r, AsyncHandler c) {
25: response = r;
26: callback = c;
27: }
28:
29: @SuppressWarnings("unchecked")
30: public synchronized void run() {
31: try {
32: callback.handleResponse(response);
33: } finally {
34: done = true;
35: notifyAll();
36: }
37: }
38:
39: public boolean cancel(boolean interrupt) {
40: return response.cancel(interrupt);
41: }
42:
43: public boolean isCancelled() {
44: return response.isCancelled();
45: }
46:
47: public boolean isDone() {
48: return done;
49: }
50:
51: public Object get() throws InterruptedException, ExecutionException {
52: waitForCallbackExecutionToFinish();
53: return null;
54: }
55:
56: public Object get(long timeout, TimeUnit unit)
57: throws InterruptedException, ExecutionException,
58: TimeoutException {
59: long ms = TimeUnit.MILLISECONDS.convert(timeout, unit);
60: waitForCallbackExecutionToFinish(ms);
61: return null;
62: }
63:
64: private synchronized void waitForCallbackExecutionToFinish() {
65: while (!done) {
66: LOG.fine("waiting for callback to finish execution.");
67: try {
68: wait();
69: } catch (InterruptedException ex) {
70: // deliberately ignore
71: }
72: }
73: }
74:
75: private synchronized void waitForCallbackExecutionToFinish(
76: long millis) throws TimeoutException {
77: while (!done && millis > 0) {
78: if (LOG.isLoggable(Level.FINE)) {
79: LOG
80: .fine("waiting (max "
81: + millis
82: + " milliseconds for callback to finish execution (max .");
83: }
84: long startedAt = System.currentTimeMillis();
85: try {
86: wait(millis);
87: } catch (InterruptedException ex) {
88: // deliberately ignore
89: millis -= System.currentTimeMillis() - startedAt;
90: }
91: }
92: if (!done) {
93: throw new TimeoutException(new Message(
94: "ASYNC_HANDLER_TIMEDOUT_EXC", LOG).toString());
95: }
96: }
97: }
|