use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project jersey by jersey.
the class NettyConnector method apply.
@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
final URI requestUri = jerseyRequest.getUri();
String host = requestUri.getHost();
int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if ("https".equals(requestUri.getScheme())) {
// making client authentication optional for now; it could be extracted to configurable property
JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
p.addLast(jdkSslContext.newHandler(ch.alloc()));
}
// http proxy
Configuration config = jerseyRequest.getConfiguration();
final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
if (proxyUri != null) {
final URI u = getProxyUri(proxyUri);
final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
}
p.addLast(new HttpClientCodec());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpContentDecompressor());
p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
}
});
// connect timeout
Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
if (connectTimeout > 0) {
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
}
// Make the connection attempt.
final Channel ch = b.connect(host, port).sync().channel();
// guard against prematurely closed channel
final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
@Override
public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
if (!settableFuture.isDone()) {
settableFuture.completeExceptionally(new IOException("Channel closed."));
}
}
};
ch.closeFuture().addListener(closeListener);
HttpRequest nettyRequest;
if (jerseyRequest.hasEntity()) {
nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
} else {
nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
}
// headers
for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
nettyRequest.headers().add(e.getKey(), e.getValue());
}
// host header - http 1.1
nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
if (jerseyRequest.hasEntity()) {
if (jerseyRequest.getLengthLong() == -1) {
HttpUtil.setTransferEncodingChunked(nettyRequest, true);
} else {
nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
}
}
if (jerseyRequest.hasEntity()) {
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
return jerseyChunkedInput;
}
});
if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
ch.write(new HttpChunkedInput(jerseyChunkedInput));
} else {
ch.write(jerseyChunkedInput);
}
executorService.execute(new Runnable() {
@Override
public void run() {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
try {
jerseyRequest.writeEntity();
} catch (IOException e) {
jerseyCallback.failure(e);
settableFuture.completeExceptionally(e);
}
}
});
ch.flush();
} else {
// close listener is not needed any more.
ch.closeFuture().removeListener(closeListener);
// Send the HTTP request.
ch.writeAndFlush(nettyRequest);
}
} catch (InterruptedException e) {
settableFuture.completeExceptionally(e);
return settableFuture;
}
return settableFuture;
}
use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project netty by netty.
the class Http2TestUtil method newVoidPromise.
static ChannelPromise newVoidPromise(final Channel channel) {
return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE) {
@Override
public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
throw new AssertionFailedError();
}
@Override
public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
throw new AssertionFailedError();
}
@Override
public boolean isVoid() {
return true;
}
@Override
public boolean tryFailure(Throwable cause) {
channel().pipeline().fireExceptionCaught(cause);
return true;
}
@Override
public ChannelPromise setFailure(Throwable cause) {
tryFailure(cause);
return this;
}
@Override
public ChannelPromise unvoid() {
ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
channel().pipeline().fireExceptionCaught(future.cause());
}
}
});
return promise;
}
};
}
use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project netty by netty.
the class ReentrantChannelTest method testCloseInFlush.
@Test
public void testCloseInFlush() throws Exception {
LocalAddress addr = new LocalAddress("testCloseInFlush");
ServerBootstrap sb = getLocalServerBootstrap();
sb.bind(addr).sync().channel();
Bootstrap cb = getLocalClientBootstrap();
setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
Channel clientChannel = cb.connect(addr).sync().channel();
clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {
@Override
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
promise.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
ctx.channel().close();
}
});
super.write(ctx, msg, promise);
ctx.channel().flush();
}
});
clientChannel.write(createTestBuf(2000)).sync();
clientChannel.closeFuture().sync();
assertLog("WRITE\nFLUSH\nCLOSE\n");
}
use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.
the class TCPServerBase method listen.
private synchronized io.netty.util.concurrent.Future<Channel> listen(SocketAddress localAddress, ContextInternal context) {
if (listening) {
throw new IllegalStateException("Listen already called");
}
this.listenContext = context;
this.listening = true;
this.eventLoop = context.nettyEventLoop();
SocketAddress bindAddress;
Map<ServerID, TCPServerBase> sharedNetServers = vertx.sharedTCPServers((Class<TCPServerBase>) getClass());
synchronized (sharedNetServers) {
actualPort = localAddress.port();
String hostOrPath = localAddress.isInetSocket() ? localAddress.host() : localAddress.path();
TCPServerBase main;
boolean shared;
ServerID id;
if (actualPort > 0 || localAddress.isDomainSocket()) {
id = new ServerID(actualPort, hostOrPath);
main = sharedNetServers.get(id);
shared = true;
bindAddress = localAddress;
} else {
if (actualPort < 0) {
id = new ServerID(actualPort, hostOrPath + "/" + -actualPort);
main = sharedNetServers.get(id);
shared = true;
bindAddress = SocketAddress.inetSocketAddress(0, localAddress.host());
} else {
id = new ServerID(actualPort, hostOrPath);
main = null;
shared = false;
bindAddress = localAddress;
}
}
if (main == null) {
try {
sslHelper = createSSLHelper();
sslHelper.validate(vertx);
worker = childHandler(listenContext, localAddress, sslHelper);
servers = new HashSet<>();
servers.add(this);
channelBalancer = new ServerChannelLoadBalancer(vertx.getAcceptorEventLoopGroup().next());
channelBalancer.addWorker(eventLoop, worker);
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(vertx.getAcceptorEventLoopGroup(), channelBalancer.workers());
if (sslHelper.isSSL()) {
bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
} else {
bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}
bootstrap.childHandler(channelBalancer);
applyConnectionOptions(localAddress.isDomainSocket(), bootstrap);
bindFuture = AsyncResolveConnectHelper.doBind(vertx, bindAddress, bootstrap);
bindFuture.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) res -> {
if (res.isSuccess()) {
Channel ch = res.getNow();
log.trace("Net server listening on " + hostOrPath + ":" + ch.localAddress());
if (shared) {
ch.closeFuture().addListener((ChannelFutureListener) channelFuture -> {
synchronized (sharedNetServers) {
sharedNetServers.remove(id);
}
});
}
if (bindAddress.isInetSocket()) {
actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
}
listenContext.addCloseHook(this);
metrics = createMetrics(localAddress);
} else {
if (shared) {
synchronized (sharedNetServers) {
sharedNetServers.remove(id);
}
}
listening = false;
}
});
} catch (Throwable t) {
listening = false;
return vertx.getAcceptorEventLoopGroup().next().newFailedFuture(t);
}
if (shared) {
sharedNetServers.put(id, this);
}
actualServer = this;
} else {
// Server already exists with that host/port - we will use that
actualServer = main;
metrics = main.metrics;
sslHelper = main.sslHelper;
worker = childHandler(listenContext, localAddress, sslHelper);
actualServer.servers.add(this);
actualServer.channelBalancer.addWorker(eventLoop, worker);
listenContext.addCloseHook(this);
}
}
return actualServer.bindFuture;
}
use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.
the class DatagramSocketImpl method listen.
private Future<DatagramSocket> listen(SocketAddress local) {
AddressResolver resolver = context.owner().addressResolver();
PromiseInternal<Void> promise = context.promise();
io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), local.host());
f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
if (res1.isSuccess()) {
ChannelFuture f2 = channel.bind(new InetSocketAddress(res1.getNow().getAddress(), local.port()));
if (metrics != null) {
f2.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Void>>) res2 -> {
if (res2.isSuccess()) {
metrics.listening(local.host(), localAddress());
}
});
}
f2.addListener(promise);
} else {
promise.fail(res1.cause());
}
});
return promise.future().map(this);
}
Aggregations