List of usage examples for io.netty.bootstrap Bootstrap resolver
AddressResolverGroup resolver
To view the source code for io.netty.bootstrap Bootstrap resolver.
Click Source Link
From source file:com.linecorp.armeria.client.HttpClientFactory.java
License:Apache License
HttpClientFactory(EventLoopGroup workerGroup, boolean shutdownWorkerGroupOnClose, Map<ChannelOption<?>, Object> socketOptions, Consumer<? super SslContextBuilder> sslContextCustomizer, Function<? super EventLoopGroup, ? extends AddressResolverGroup<? extends InetSocketAddress>> addressResolverGroupFactory, int initialHttp2ConnectionWindowSize, int initialHttp2StreamWindowSize, int http2MaxFrameSize, int maxHttp1InitialLineLength, int maxHttp1HeaderSize, int maxHttp1ChunkSize, long idleTimeoutMillis, boolean useHttp2Preface, boolean useHttp1Pipelining, KeyedChannelPoolHandler<? super PoolKey> connectionPoolListener, MeterRegistry meterRegistry) { final Bootstrap baseBootstrap = new Bootstrap(); baseBootstrap.channel(TransportType.socketChannelType(workerGroup)); baseBootstrap.resolver(addressResolverGroupFactory.apply(workerGroup)); socketOptions.forEach((option, value) -> { @SuppressWarnings("unchecked") final ChannelOption<Object> castOption = (ChannelOption<Object>) option; baseBootstrap.option(castOption, value); });// w w w .j a v a 2 s. c om this.workerGroup = workerGroup; this.shutdownWorkerGroupOnClose = shutdownWorkerGroupOnClose; this.baseBootstrap = baseBootstrap; this.sslContextCustomizer = sslContextCustomizer; this.initialHttp2ConnectionWindowSize = initialHttp2ConnectionWindowSize; this.initialHttp2StreamWindowSize = initialHttp2StreamWindowSize; this.http2MaxFrameSize = http2MaxFrameSize; this.maxHttp1InitialLineLength = maxHttp1InitialLineLength; this.maxHttp1HeaderSize = maxHttp1HeaderSize; this.maxHttp1ChunkSize = maxHttp1ChunkSize; this.idleTimeoutMillis = idleTimeoutMillis; this.useHttp2Preface = useHttp2Preface; this.useHttp1Pipelining = useHttp1Pipelining; this.connectionPoolListener = new ConnectionPoolListenerImpl(connectionPoolListener); this.meterRegistry = meterRegistry; clientDelegate = new HttpClientDelegate(this); eventLoopScheduler = new EventLoopScheduler(workerGroup); }
From source file:com.linecorp.armeria.client.NonDecoratingClientFactory.java
License:Apache License
private NonDecoratingClientFactory(SessionOptions options, Function<TransportType, ThreadFactory> threadFactoryFactory) { requireNonNull(options, "options"); requireNonNull(threadFactoryFactory, "threadFactoryFactory"); final Bootstrap baseBootstrap = new Bootstrap(); baseBootstrap.channel(channelType()); baseBootstrap.resolver(options.addressResolverGroup().orElseGet(DnsAddressResolverGroup5657::new)); baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConvertUtils.safeLongToInt(options.connectTimeoutMillis())); baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true); final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup(); if (eventLoopOption.isPresent()) { eventLoopGroup = eventLoopOption.get(); closeEventLoopGroup = false;//from www . j av a 2 s. c o m } else { eventLoopGroup = createGroup(threadFactoryFactory); closeEventLoopGroup = true; } this.baseBootstrap = baseBootstrap; this.options = options; }
From source file:com.linecorp.armeria.client.RemoteInvokerFactory.java
License:Apache License
private RemoteInvokerFactory(RemoteInvokerOptions options, Function<TransportType, ThreadFactory> threadFactoryFactory) { requireNonNull(options, "options"); requireNonNull(threadFactoryFactory, "threadFactoryFactory"); final Bootstrap baseBootstrap = new Bootstrap(); baseBootstrap.channel(channelType()); baseBootstrap.resolver(options.addressResolverGroup().orElseGet( () -> new DnsAddressResolverGroup(datagramChannelType(), DnsServerAddresses.defaultAddresses()))); baseBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ConvertUtils.safeLongToInt(options.connectTimeoutMillis())); baseBootstrap.option(ChannelOption.SO_KEEPALIVE, true); final Optional<EventLoopGroup> eventLoopOption = options.eventLoopGroup(); if (eventLoopOption.isPresent()) { eventLoopGroup = eventLoopOption.get(); closeEventLoopGroup = false;// w w w.j a v a 2s. c o m } else { eventLoopGroup = createGroup(threadFactoryFactory); closeEventLoopGroup = true; } final EnumMap<SessionProtocol, RemoteInvoker> remoteInvokers = new EnumMap<>(SessionProtocol.class); final HttpRemoteInvoker remoteInvoker = new HttpRemoteInvoker(baseBootstrap, options); SessionProtocol.ofHttp().forEach(protocol -> remoteInvokers.put(protocol, remoteInvoker)); this.remoteInvokers = Collections.unmodifiableMap(remoteInvokers); }
From source file:io.vertx.core.dns.HostnameResolutionTest.java
License:Open Source License
@Test public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception { CountDownLatch listenLatch = new CountDownLatch(1); NetServer server = vertx.createNetServer().connectHandler(so -> { });// w w w. j ava 2 s . co m try { server.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown())); awaitLatch(listenLatch); AtomicReference<Thread> channelThread = new AtomicReference<>(); CountDownLatch connectLatch = new CountDownLatch(1); Bootstrap bootstrap = new Bootstrap(); bootstrap.channelFactory(((VertxInternal) vertx).transport().channelFactory(false)); bootstrap.group(vertx.nettyEventLoopGroup()); bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { channelThread.set(Thread.currentThread()); connectLatch.countDown(); } }); ChannelFuture channelFut = bootstrap.connect("localhost", 1234); awaitLatch(connectLatch); channelFut.addListener(v -> { assertTrue(v.isSuccess()); assertEquals(channelThread.get(), Thread.currentThread()); testComplete(); }); await(); } finally { server.close(); } }
From source file:io.vertx.test.core.HostnameResolutionTest.java
License:Open Source License
@Test public void testAsyncResolveConnectIsNotifiedOnChannelEventLoop() throws Exception { CountDownLatch listenLatch = new CountDownLatch(1); NetServer s = vertx.createNetServer().connectHandler(so -> { });//from w w w . jav a2 s. co m s.listen(1234, "localhost", onSuccess(v -> listenLatch.countDown())); awaitLatch(listenLatch); AtomicReference<Thread> channelThread = new AtomicReference<>(); CountDownLatch connectLatch = new CountDownLatch(1); Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.group(vertx.nettyEventLoopGroup()); bootstrap.resolver(((VertxInternal) vertx).nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { channelThread.set(Thread.currentThread()); connectLatch.countDown(); } }); ChannelFuture channelFut = bootstrap.connect("localhost", 1234); awaitLatch(connectLatch); channelFut.addListener(v -> { assertTrue(v.isSuccess()); assertEquals(channelThread.get(), Thread.currentThread()); testComplete(); }); await(); }
From source file:org.glowroot.common2.repo.util.HttpClient.java
License:Apache License
private String postOrGet(String url, byte /*@Nullable*/ [] content, @Nullable String contentType, final HttpProxyConfig httpProxyConfig, final @Nullable String passwordOverride) throws Exception { URI uri = new URI(url); String scheme = checkNotNull(uri.getScheme()); final boolean ssl = scheme.equalsIgnoreCase("https"); final String host = checkNotNull(uri.getHost()); final int port; if (uri.getPort() == -1) { port = ssl ? 443 : 80;/*from w w w . j a va 2s.co m*/ } else { port = uri.getPort(); } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); // TODO follow netty proxy support at https://github.com/netty/netty/issues/1133 final HttpProxyHandler httpProxyHandler = newHttpProxyHandlerIfNeeded(httpProxyConfig, passwordOverride); final HttpClientHandler handler = new HttpClientHandler(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (httpProxyHandler != null) { p.addLast(httpProxyHandler); } if (ssl) { SslContext sslContext = SslContextBuilder.forClient().build(); p.addLast(sslContext.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(handler); } }); if (!httpProxyConfig.host().isEmpty()) { // name resolution should be performed by the proxy server in case some proxy rules // depend on the remote hostname bootstrap.resolver(NoopAddressResolverGroup.INSTANCE); } HttpRequest request; if (content == null) { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); } else { request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), Unpooled.wrappedBuffer(content)); request.headers().set(HttpHeaderNames.CONTENT_TYPE, checkNotNull(contentType)); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length); } request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); Channel ch = bootstrap.connect(host, port).sync().channel(); if (httpProxyHandler != null) { // this line is needed to capture and throw connection exception properly httpProxyHandler.connectFuture().get(); } ch.writeAndFlush(request).get(); ch.closeFuture().sync().get(); Throwable exception = handler.exception; if (exception != null) { Throwables.propagateIfPossible(exception, Exception.class); throw new Exception(exception); } HttpResponseStatus responseStatus = checkNotNull(handler.responseStatus); int statusCode = responseStatus.code(); if (statusCode == 429) { throw new TooManyRequestsHttpResponseException(); } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Unexpected response status code: " + statusCode); } return checkNotNull(handler.responseContent); } finally { group.shutdownGracefully(0, 10, SECONDS).get(); } }
From source file:ws.wamp.jawampa.transport.netty.NettyWampClientConnectorProvider.java
License:Apache License
@Override public IWampConnector createConnector(final URI uri, IWampClientConnectionConfig configuration, List<WampSerialization> serializations, final SocketAddress proxyAddress) throws Exception { String scheme = uri.getScheme(); scheme = scheme != null ? scheme : ""; // Check if the configuration is a netty configuration. // However null is an allowed value final NettyWampConnectionConfig nettyConfig; if (configuration instanceof NettyWampConnectionConfig) { nettyConfig = (NettyWampConnectionConfig) configuration; } else if (configuration != null) { throw new ApplicationError(ApplicationError.INVALID_CONNECTION_CONFIGURATION); } else {//from w ww. j a va 2 s. c o m nettyConfig = null; } if (scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")) { // Check the host and port field for validity if (uri.getHost() == null || uri.getPort() == 0) { throw new ApplicationError(ApplicationError.INVALID_URI); } // Initialize SSL when required final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss"); final SslContext sslCtx0; if (needSsl && (nettyConfig == null || nettyConfig.sslContext() == null)) { // Create a default SslContext when we got none provided through the constructor try { sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { throw e; } } else if (needSsl) { sslCtx0 = nettyConfig.sslContext(); } else { sslCtx0 = null; } final String subProtocols = WampSerialization.makeWebsocketSubprotocolList(serializations); final int maxFramePayloadLength = (nettyConfig == null) ? NettyWampConnectionConfig.DEFAULT_MAX_FRAME_PAYLOAD_LENGTH : nettyConfig.getMaxFramePayloadLength(); // Return a factory that creates a channel for websocket connections return new IWampConnector() { @Override public IPendingWampConnection connect(final ScheduledExecutorService scheduler, final IPendingWampConnectionListener connectListener, final IWampConnectionListener connectionListener) { // Use well-known ports if not explicitly specified final int port; if (uri.getPort() == -1) { if (needSsl) port = 443; else port = 80; } else port = uri.getPort(); final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocols, false, new DefaultHttpHeaders(), maxFramePayloadLength); /** * Netty handler for that receives and processes WampMessages and state * events from the pipeline. * A new instance of this is created for each connection attempt. */ final ChannelHandler connectionHandler = new SimpleChannelInboundHandler<WampMessage>() { boolean connectionWasEstablished = false; /** Guard to prevent forwarding events aftert the channel was closed */ boolean wasClosed = false; @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (wasClosed) return; wasClosed = true; if (connectionWasEstablished) { connectionListener.transportClosed(); } else { // The transport closed before the websocket handshake was completed connectListener .connectFailed(new ApplicationError(ApplicationError.TRANSPORT_CLOSED)); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (wasClosed) return; wasClosed = true; if (connectionWasEstablished) { connectionListener.transportError(cause); } else { // The transport closed before the websocket handshake was completed connectListener.connectFailed(cause); } super.exceptionCaught(ctx, cause); } @Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { if (wasClosed) return; if (evt instanceof ConnectionEstablishedEvent) { ConnectionEstablishedEvent ev = (ConnectionEstablishedEvent) evt; final WampSerialization serialization = ev.serialization(); IWampConnection connection = new IWampConnection() { @Override public WampSerialization serialization() { return serialization; } @Override public boolean isSingleWriteOnly() { return false; } @Override public void sendMessage(WampMessage message, final IWampConnectionPromise<Void> promise) { ChannelFuture f = ctx.writeAndFlush(message); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess() || future.isCancelled()) promise.fulfill(null); else promise.reject(future.cause()); } }); } @Override public void close(boolean sendRemaining, final IWampConnectionPromise<Void> promise) { // sendRemaining is ignored. Remaining data is always sent ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.channel().close() .addListener(new ChannelFutureListener() { @Override public void operationComplete( ChannelFuture future) throws Exception { if (future.isSuccess() || future.isCancelled()) promise.fulfill(null); else promise.reject(future.cause()); } }); } }); } }; connectionWasEstablished = true; // Connection to the remote host was established // However the WAMP session is not established until the handshake was finished connectListener.connectSucceeded(connection); } } @Override protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception { if (wasClosed) return; assert (connectionWasEstablished); connectionListener.messageReceived(msg); } }; // If the assigned scheduler is a netty eventloop use this final EventLoopGroup nettyEventLoop; if (scheduler instanceof EventLoopGroup) { nettyEventLoop = (EventLoopGroup) scheduler; } else { connectListener.connectFailed(new ApplicationError(ApplicationError.INCOMATIBLE_SCHEDULER)); return IPendingWampConnection.Dummy; } Bootstrap b = new Bootstrap(); // things should be resolved on via the socks5 proxy if (proxyAddress != null) b.resolver(NoopAddressResolverGroup.INSTANCE); b.group(nettyEventLoop).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (proxyAddress != null) { p.addFirst("proxy", new Socks5ProxyHandler(proxyAddress)); } if (sslCtx0 != null) { p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), new WebSocketFrameAggregator( WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE), new WampClientWebsocketHandler(handshaker), connectionHandler); } }); final ChannelFuture connectFuture = b.connect(uri.getHost(), port); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Do nothing. The connection is only successful when the websocket handshake succeeds } else { // Remark: Might be called directly in addListener // Therefore addListener should be the last call // Remark2: This branch will be taken upon cancellation. // This is required by the contract. connectListener.connectFailed(future.cause()); } } }); // Return the connection in progress with the ability for cancellation return new IPendingWampConnection() { @Override public void cancelConnect() { connectFuture.cancel(false); } }; } }; } throw new ApplicationError(ApplicationError.INVALID_URI); }