1 package org.objectweb.celtix.bus.jaxws; 2 3 import java.util.concurrent.ExecutionException ; 4 import java.util.concurrent.Future ; 5 import java.util.concurrent.TimeUnit ; 6 import java.util.concurrent.TimeoutException ; 7 import java.util.logging.Level ; 8 import java.util.logging.Logger ; 9 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.getL7dLogger(AsyncCallbackFuture.class); 19 private final Response response; 20 private final AsyncHandler callback; 21 private boolean done; 22 23 public AsyncCallbackFuture(Response r, AsyncHandler c) { 24 response = r; 25 callback = c; 26 } 27 28 @SuppressWarnings ("unchecked") 29 public synchronized void run() { 30 try { 31 callback.handleResponse(response); 32 } finally { 33 done = true; 34 notifyAll(); 35 } 36 } 37 38 public boolean cancel(boolean interrupt) { 39 return response.cancel(interrupt); 40 } 41 42 public boolean isCancelled() { 43 return response.isCancelled(); 44 } 45 46 public boolean isDone() { 47 return done; 48 } 49 50 public Object get() throws InterruptedException , ExecutionException { 51 waitForCallbackExecutionToFinish(); 52 return null; 53 } 54 55 56 public Object get(long timeout, TimeUnit unit) 57 throws InterruptedException , ExecutionException , TimeoutException { 58 long ms = TimeUnit.MILLISECONDS.convert(timeout, unit); 59 waitForCallbackExecutionToFinish(ms); 60 return null; 61 } 62 63 private synchronized void waitForCallbackExecutionToFinish() { 64 while (!done) { 65 LOG.fine("waiting for callback to finish execution."); 66 try { 67 wait(); 68 } catch (InterruptedException ex) { 69 } 71 } 72 } 73 74 private synchronized void waitForCallbackExecutionToFinish(long millis) throws TimeoutException { 75 while (!done && millis > 0) { 76 if (LOG.isLoggable(Level.FINE)) { 77 LOG.fine("waiting (max " + millis 78 + " milliseconds for callback to finish execution (max ."); 79 } 80 long startedAt = System.currentTimeMillis(); 81 try { 82 wait(millis); 83 } catch (InterruptedException ex) { 84 millis -= System.currentTimeMillis() - startedAt; 86 } 87 } 88 if (!done) { 89 throw new TimeoutException (new Message("ASYNC_HANDLER_TIMEDOUT_EXC", 90 LOG).toString()); 91 } 92 } 93 } 94 | Popular Tags |