use of io.netty.bootstrap.Bootstrap in project async-http-client by AsyncHttpClient.
the class NettyRequestSender method sendRequestWithNewChannel.
private <//
T> //
ListenableFuture<T> sendRequestWithNewChannel(//
Request request, //
ProxyServer proxy, //
NettyResponseFuture<T> future, //
AsyncHandler<T> asyncHandler, boolean performingNextRequest) {
// some headers are only set when performing the first request
HttpHeaders headers = future.getNettyRequest().getHttpRequest().headers();
Realm realm = future.getRealm();
Realm proxyRealm = future.getProxyRealm();
requestFactory.addAuthorizationHeader(headers, perConnectionAuthorizationHeader(request, proxy, realm));
requestFactory.setProxyAuthorizationHeader(headers, perConnectionProxyAuthorizationHeader(request, proxyRealm));
future.setInAuth(realm != null && realm.isUsePreemptiveAuth() && realm.getScheme() != AuthScheme.NTLM);
future.setInProxyAuth(proxyRealm != null && proxyRealm.isUsePreemptiveAuth() && proxyRealm.getScheme() != AuthScheme.NTLM);
// Do not throw an exception when we need an extra connection for a redirect
// FIXME why? This violate the max connection per host handling, right?
Bootstrap bootstrap = channelManager.getBootstrap(request.getUri(), proxy);
Object partitionKey = future.getPartitionKey();
// we disable channelPreemption when performing next requests
final boolean acquireChannelLock = !performingNextRequest;
try {
// redirect.
if (acquireChannelLock) {
// if there's an exception here, channel wasn't preempted and resolve won't happen
channelManager.acquireChannelLock(partitionKey);
}
} catch (Throwable t) {
abort(null, future, getCause(t));
// exit and don't try to resolve address
return future;
}
scheduleRequestTimeout(future);
//
RequestHostnameResolver.INSTANCE.resolve(request, proxy, asyncHandler).addListener(new SimpleFutureListener<List<InetSocketAddress>>() {
@Override
protected void onSuccess(List<InetSocketAddress> addresses) {
NettyConnectListener<T> connectListener = new NettyConnectListener<>(future, NettyRequestSender.this, channelManager, acquireChannelLock, partitionKey);
NettyChannelConnector connector = new NettyChannelConnector(request.getLocalAddress(), addresses, asyncHandler, clientState, config);
if (!future.isDone()) {
connector.connect(bootstrap, connectListener);
} else if (acquireChannelLock) {
channelManager.releaseChannelLock(partitionKey);
}
}
@Override
protected void onFailure(Throwable cause) {
if (acquireChannelLock) {
channelManager.releaseChannelLock(partitionKey);
}
abort(null, future, getCause(cause));
}
});
return future;
}
use of io.netty.bootstrap.Bootstrap in project pulsar by yahoo.
the class DiscoveryServiceTest method connectToService.
/**
* creates ClientHandler channel to connect and communicate with server
*
* @param serviceUrl
* @param latch
* @return
* @throws URISyntaxException
*/
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException {
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (tls) {
SslContextBuilder builder = SslContextBuilder.forClient();
builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
X509Certificate[] certificates = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
builder.keyManager(privateKey, (X509Certificate[]) certificates);
SslContext sslCtx = builder.build();
ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
}
ch.pipeline().addLast(new ClientHandler(latch));
}
});
URI uri = new URI(serviceUrl);
InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
b.connect(serviceAddress).addListener((ChannelFuture future) -> {
if (!future.isSuccess()) {
throw new IllegalStateException(future.cause());
}
});
return workerGroup;
}
use of io.netty.bootstrap.Bootstrap in project cradle by BingLau7.
the class EchoClient method start.
void start() throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
// 指定 EventLoopGroup 以处理客户端时间;需要适用于 NIO 的实现
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
// 连接远程节点,阻塞等待直到连接完成
ChannelFuture f = b.connect().sync();
// 阻塞,直到 Channel 关闭
f.channel().closeFuture().sync();
} finally {
// 关闭线程池并释放所有的资源
group.shutdownGracefully().sync();
}
}
use of io.netty.bootstrap.Bootstrap in project Glowstone by GlowstoneMC.
the class HttpClient method connect.
public static void connect(String url, EventLoop eventLoop, HttpCallback callback) {
URI uri = URI.create(url);
String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
SslContext sslCtx = null;
if ("https".equalsIgnoreCase(scheme)) {
if (port == -1)
port = 443;
try {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} catch (SSLException e) {
callback.error(e);
return;
}
} else if ("http".equalsIgnoreCase(scheme)) {
if (port == -1)
port = 80;
} else {
throw new IllegalArgumentException("Only http(s) is supported!");
}
new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.headers().set(HttpHeaderNames.HOST, host);
future.channel().writeAndFlush(request);
} else {
callback.error(future.cause());
}
});
}
use of io.netty.bootstrap.Bootstrap in project aerospike-client-java by aerospike.
the class NettyCommand method executeCommand.
private void executeCommand() {
try {
Node node = command.getNode(cluster);
conn = (NettyConnection) node.getAsyncConnection(eventState.index, null);
if (conn != null) {
InboundHandler handler = (InboundHandler) conn.channel.pipeline().last();
handler.command = this;
writeCommand();
return;
}
try {
final InboundHandler handler = new InboundHandler();
handler.command = this;
Bootstrap b = new Bootstrap();
b.group(eventLoop.eventLoop);
if (eventLoop.parent.isEpoll) {
b.channel(EpollSocketChannel.class);
} else {
b.channel(NioSocketChannel.class);
}
b.option(ChannelOption.TCP_NODELAY, true);
b.option(ChannelOption.AUTO_READ, false);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
conn = new NettyConnection(ch, cluster.maxSocketIdleNanos);
ChannelPipeline p = ch.pipeline();
if (eventLoop.parent.sslContext != null) {
//InetSocketAddress address = node.getAddress();
//p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc(), address.getHostString(), address.getPort()));
p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc()));
}
p.addLast(handler);
}
});
b.connect(node.getAddress());
} catch (Exception e) {
node.decrAsyncConnection(eventState.index);
throw e;
}
eventState.errors = 0;
} catch (AerospikeException.Connection ac) {
eventState.errors++;
onNetworkError(ac);
} catch (Exception e) {
// Fail without retry on unknown errors.
eventState.errors++;
fail();
notifyFailure(new AerospikeException(e));
}
}
Aggregations