use of java.util.concurrent.FutureTask in project dubbo by alibaba.
the class RpcContext method asyncCall.
/**
* 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题.
* @param callable
* @return 通过future.get()获取返回结果.
*/
@SuppressWarnings("unchecked")
public <T> Future<T> asyncCall(Callable<T> callable) {
try {
try {
setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString());
final T o = callable.call();
//local调用会直接返回结果.
if (o != null) {
FutureTask<T> f = new FutureTask<T>(new Callable<T>() {
public T call() throws Exception {
return o;
}
});
f.run();
return f;
} else {
}
} catch (Exception e) {
throw new RpcException(e);
} finally {
removeAttachment(Constants.ASYNC_KEY);
}
} catch (final RpcException e) {
return new Future<T>() {
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return true;
}
public T get() throws InterruptedException, ExecutionException {
throw new ExecutionException(e.getCause());
}
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
};
}
return ((Future<T>) getContext().getFuture());
}
use of java.util.concurrent.FutureTask in project Smack by igniterealtime.
the class Socks5Client method getSocket.
/**
* Returns the initialized socket that can be used to transfer data between peers via the SOCKS5
* proxy.
*
* @param timeout timeout to connect to SOCKS5 proxy in milliseconds
* @return socket the initialized socket
* @throws IOException if initializing the socket failed due to a network error
* @throws XMPPErrorException if establishing connection to SOCKS5 proxy failed
* @throws TimeoutException if connecting to SOCKS5 proxy timed out
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws SmackException if the connection to the SOC
* @throws XMPPException
*/
public Socket getSocket(int timeout) throws IOException, XMPPErrorException, InterruptedException, TimeoutException, SmackException, XMPPException {
// wrap connecting in future for timeout
FutureTask<Socket> futureTask = new FutureTask<Socket>(new Callable<Socket>() {
@Override
public Socket call() throws IOException, SmackException {
// initialize socket
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(streamHost.getAddress(), streamHost.getPort());
socket.connect(socketAddress);
// initialize connection to SOCKS5 proxy
try {
establish(socket);
} catch (SmackException e) {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e2) {
LOGGER.log(Level.WARNING, "Could not close SOCKS5 socket", e2);
}
}
throw e;
}
return socket;
}
});
Thread executor = new Thread(futureTask);
executor.start();
// get connection to initiator with timeout
try {
return futureTask.get(timeout, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause != null) {
// case exceptions to comply with method signature
if (cause instanceof IOException) {
throw (IOException) cause;
}
if (cause instanceof SmackException) {
throw (SmackException) cause;
}
}
// throw generic Smack exception if unexpected exception was thrown
throw new SmackException("Error while connecting to SOCKS5 proxy", e);
}
}
use of java.util.concurrent.FutureTask in project Smack by igniterealtime.
the class IncomingFileTransfer method negotiateStream.
private InputStream negotiateStream() throws SmackException, XMPPErrorException, InterruptedException {
setStatus(Status.negotiating_transfer);
final StreamNegotiator streamNegotiator = negotiator.selectStreamNegotiator(recieveRequest);
setStatus(Status.negotiating_stream);
FutureTask<InputStream> streamNegotiatorTask = new FutureTask<InputStream>(new Callable<InputStream>() {
@Override
public InputStream call() throws Exception {
return streamNegotiator.createIncomingStream(recieveRequest.getStreamInitiation());
}
});
streamNegotiatorTask.run();
InputStream inputStream;
try {
inputStream = streamNegotiatorTask.get(15, TimeUnit.SECONDS);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause instanceof XMPPErrorException) {
throw (XMPPErrorException) cause;
}
if (cause instanceof InterruptedException) {
throw (InterruptedException) cause;
}
if (cause instanceof NoResponseException) {
throw (NoResponseException) cause;
}
if (cause instanceof SmackException) {
throw (SmackException) cause;
}
throw new SmackException("Error in execution", e);
} catch (TimeoutException e) {
throw new SmackException("Request timed out", e);
} finally {
streamNegotiatorTask.cancel(true);
}
setStatus(Status.negotiated);
return inputStream;
}
use of java.util.concurrent.FutureTask in project Smack by igniterealtime.
the class Socks5ByteStreamTest method testBiDirectionalSocks5BytestreamWithRemoteSocks5Proxy.
/**
* Socks5 bytestream should be successfully established using a Socks5 proxy provided by the
* XMPP server. The established connection should transfer data bidirectional if the Socks5
* proxy supports it.
* <p>
* Support for bidirectional Socks5 bytestream:
* <ul>
* <li>Openfire (3.6.4 and below) - no</li>
* <li>ejabberd (2.0.5 and higher) - yes</li>
* </ul>
* <p>
* This test will fail if the XMPP server doesn't provide any Socks5 proxies or the Socks5 proxy
* only allows Socks5 bytestreams in the context of a file transfer (like Openfire in default
* configuration, see xmpp.proxy.transfer.required flag).
*
* @throws Exception if no Socks5 proxies found or proxy is unwilling to activate Socks5
* bytestream
*/
public void testBiDirectionalSocks5BytestreamWithRemoteSocks5Proxy() throws Exception {
XMPPConnection initiatorConnection = getConnection(0);
// disable local socks5 proxy
SmackConfiguration.setLocalSocks5ProxyEnabled(false);
Socks5Proxy.getSocks5Proxy().stop();
assertFalse(Socks5Proxy.getSocks5Proxy().isRunning());
XMPPConnection targetConnection = getConnection(1);
// test data
final byte[] data = new byte[] { 1, 2, 3 };
final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();
Socks5BytestreamManager targetByteStreamManager = Socks5BytestreamManager.getBytestreamManager(targetConnection);
Socks5BytestreamListener incomingByteStreamListener = new Socks5BytestreamListener() {
public void incomingBytestreamRequest(Socks5BytestreamRequest request) {
try {
Socks5BytestreamSession session = request.accept();
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
InputStream inputStream = session.getInputStream();
byte[] receivedData = new byte[3];
inputStream.read(receivedData);
queue.put(receivedData);
session.close();
} catch (Exception e) {
fail(e.getMessage());
}
}
};
targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);
Socks5BytestreamManager initiatorByteStreamManager = Socks5BytestreamManager.getBytestreamManager(initiatorConnection);
Socks5BytestreamSession session = initiatorByteStreamManager.establishSession(targetConnection.getUser());
assertTrue(session.isMediated());
// verify stream
final byte[] receivedData = new byte[3];
final InputStream inputStream = session.getInputStream();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
public Integer call() throws Exception {
return inputStream.read(receivedData);
}
});
Thread executor = new Thread(futureTask);
executor.start();
try {
futureTask.get(2000, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
Socks5Proxy.getSocks5Proxy().start();
fail("Couldn't send data from target to inititator");
}
assertEquals("sent data not equal to received data", data, receivedData);
OutputStream outputStream = session.getOutputStream();
outputStream.write(data);
outputStream.flush();
outputStream.close();
assertEquals("received data not equal to sent data", data, queue.take());
session.close();
// reset default configuration
SmackConfiguration.setLocalSocks5ProxyEnabled(true);
Socks5Proxy.getSocks5Proxy().start();
}
use of java.util.concurrent.FutureTask in project spring-framework by spring-projects.
the class ExecutorBeanDefinitionParserTests method defaultExecutor.
@Test
public void defaultExecutor() throws Exception {
ThreadPoolTaskExecutor executor = this.context.getBean("default", ThreadPoolTaskExecutor.class);
assertEquals(1, getCorePoolSize(executor));
assertEquals(Integer.MAX_VALUE, getMaxPoolSize(executor));
assertEquals(Integer.MAX_VALUE, getQueueCapacity(executor));
assertEquals(60, getKeepAliveSeconds(executor));
assertEquals(false, getAllowCoreThreadTimeOut(executor));
FutureTask<String> task = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
return "foo";
}
});
executor.execute(task);
assertEquals("foo", task.get());
}
Aggregations