List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java
License:Apache License
protected NodeChannels connectToChannels(DiscoveryNode node) { final NodeChannels nodeChannels = new NodeChannels(new Channel[connectionsPerNodeRecovery], new Channel[connectionsPerNodeBulk], new Channel[connectionsPerNodeReg], new Channel[connectionsPerNodeState], new Channel[connectionsPerNodePing]); boolean success = false; try {// w ww. j a v a 2 s . co m int numConnections = connectionsPerNodeRecovery + connectionsPerNodeBulk + connectionsPerNodeReg + connectionsPerNodeState + connectionsPerNodeRecovery; final ArrayList<ChannelFuture> connections = new ArrayList<>(numConnections); final InetSocketAddress address = ((InetSocketTransportAddress) node.getAddress()).address(); for (int i = 0; i < numConnections; i++) { connections.add(bootstrap.connect(address)); } final Iterator<ChannelFuture> iterator = connections.iterator(); try { for (Channel[] channels : nodeChannels.getChannelArrays()) { for (int i = 0; i < channels.length; i++) { assert iterator.hasNext(); ChannelFuture future = iterator.next(); future.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!future.isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", future.cause()); } channels[i] = future.channel(); channels[i].closeFuture().addListener(new ChannelCloseListener(node)); } } if (nodeChannels.recovery.length == 0) { if (nodeChannels.bulk.length > 0) { nodeChannels.recovery = nodeChannels.bulk; } else { nodeChannels.recovery = nodeChannels.reg; } } if (nodeChannels.bulk.length == 0) { nodeChannels.bulk = nodeChannels.reg; } } catch (final RuntimeException e) { for (final ChannelFuture future : Collections.unmodifiableList(connections)) { FutureUtils.cancel(future); if (future.channel() != null && future.channel().isOpen()) { try { future.channel().close(); } catch (Exception inner) { e.addSuppressed(inner); } } } throw e; } success = true; } finally { if (success == false) { try { nodeChannels.close(); } catch (IOException e) { logger.trace("exception while closing channels", e); } } } return nodeChannels; }
From source file:org.elasticsearch.http.nio.NettyAdaptor.java
License:Apache License
@Override public void close() throws Exception { assert flushOperations.isEmpty() : "Should close outbound operations before calling close"; ChannelFuture closeFuture = nettyChannel.close(); // This should be safe as we are not a real network channel closeFuture.await();/*from w w w .ja va2 s . c o m*/ if (closeFuture.isSuccess() == false) { Throwable cause = closeFuture.cause(); ExceptionsHelper.dieOnError(cause); throw (Exception) cause; } }
From source file:org.elasticsearch.transport.netty4.Netty4Transport.java
License:Apache License
protected NodeChannels connectToChannelsLight(DiscoveryNode node) { InetSocketAddress address = ((InetSocketTransportAddress) node.getAddress()).address(); ChannelFuture connect = bootstrap.connect(address); connect.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!connect.isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", connect.cause()); }//from w w w. j av a2 s . co m Channel[] channels = new Channel[1]; channels[0] = connect.channel(); channels[0].closeFuture().addListener(new ChannelCloseListener(node)); NodeChannels nodeChannels = new NodeChannels(channels, channels, channels, channels, channels); onAfterChannelsConnected(nodeChannels); return nodeChannels; }
From source file:org.elasticsearch.transport.netty4.Netty4Transport.java
License:Apache License
protected NodeChannels connectToChannels(DiscoveryNode node) { final NodeChannels nodeChannels = new NodeChannels(new Channel[connectionsPerNodeRecovery], new Channel[connectionsPerNodeBulk], new Channel[connectionsPerNodeReg], new Channel[connectionsPerNodeState], new Channel[connectionsPerNodePing]); boolean success = false; try {//from www.ja v a2 s .co m int numConnections = connectionsPerNodeRecovery + connectionsPerNodeBulk + connectionsPerNodeReg + connectionsPerNodeState + connectionsPerNodeRecovery; final ArrayList<ChannelFuture> connections = new ArrayList<>(numConnections); final InetSocketAddress address = ((InetSocketTransportAddress) node.getAddress()).address(); for (int i = 0; i < numConnections; i++) { connections.add(bootstrap.connect(address)); } final Iterator<ChannelFuture> iterator = connections.iterator(); try { for (Channel[] channels : nodeChannels.getChannelArrays()) { for (int i = 0; i < channels.length; i++) { assert iterator.hasNext(); ChannelFuture future = iterator.next(); future.awaitUninterruptibly((long) (connectTimeout.millis() * 1.5)); if (!future.isSuccess()) { throw new ConnectTransportException(node, "connect_timeout[" + connectTimeout + "]", future.cause()); } channels[i] = future.channel(); channels[i].closeFuture().addListener(new ChannelCloseListener(node)); } } if (nodeChannels.recovery.length == 0) { if (nodeChannels.bulk.length > 0) { nodeChannels.recovery = nodeChannels.bulk; } else { nodeChannels.recovery = nodeChannels.reg; } } if (nodeChannels.bulk.length == 0) { nodeChannels.bulk = nodeChannels.reg; } } catch (final RuntimeException e) { for (final ChannelFuture future : Collections.unmodifiableList(connections)) { FutureUtils.cancel(future); if (future.channel() != null && future.channel().isOpen()) { try { future.channel().close(); } catch (Exception inner) { e.addSuppressed(inner); } } } throw e; } onAfterChannelsConnected(nodeChannels); success = true; } finally { if (success == false) { try { nodeChannels.close(); } catch (IOException e) { logger.trace("exception while closing channels", e); } } } return nodeChannels; }
From source file:org.freeswitch.esl.client.inbound.Client.java
License:Apache License
/** * Attempt to establish an authenticated connection to the nominated FreeSWITCH ESL server socket. * This call will block, waiting for an authentication handshake to occur, or timeout after the * supplied number of seconds./* w ww . j ava 2 s. co m*/ * * @param clientAddress a SocketAddress representing the endpoint to connect to * @param password server event socket is expecting (set in event_socket_conf.xml) * @param timeoutSeconds number of seconds to wait for the server socket before aborting */ public void connect(SocketAddress clientAddress, String password, int timeoutSeconds) throws InboundConnectionFailure { // If already connected, disconnect first if (canSend()) { close(); } log.info("Connecting to {} ...", clientAddress); EventLoopGroup workerGroup = new NioEventLoopGroup(); // Configure this client Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true); // Add ESL handler and factory InboundClientHandler handler = new InboundClientHandler(password, protocolListener); bootstrap.handler(new InboundChannelInitializer(handler)); // Attempt connection ChannelFuture future = bootstrap.connect(clientAddress); // Wait till attempt succeeds, fails or timeouts if (!future.awaitUninterruptibly(timeoutSeconds, TimeUnit.SECONDS)) { throw new InboundConnectionFailure("Timeout connecting to " + clientAddress); } // Did not timeout final Channel channel = future.channel(); // But may have failed anyway if (!future.isSuccess()) { log.warn("Failed to connect to [{}]", clientAddress, future.cause()); workerGroup.shutdownGracefully(); throw new InboundConnectionFailure("Could not connect to " + clientAddress, future.cause()); } log.info("Connected to {}", clientAddress); // Wait for the authentication handshake to call back while (!authenticatorResponded.get()) { try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } this.clientContext = Optional.of(new Context(channel, handler)); if (!authenticated) { throw new InboundConnectionFailure("Authentication failed: " + authenticationResponse.getReplyText()); } log.info("Authenticated"); }
From source file:org.glowroot.central.SyntheticMonitorService.java
License:Apache License
private static ListenableFuture<HttpResponseStatus> runPing(String url) throws Exception { URI uri = new URI(url); String scheme = uri.getScheme(); if (scheme == null) { throw new IllegalStateException("URI missing scheme"); }//from w ww. jav a 2s .c om final boolean ssl = uri.getScheme().equalsIgnoreCase("https"); final String host = uri.getHost(); if (host == null) { throw new IllegalStateException("URI missing host"); } final int port; if (uri.getPort() == -1) { port = ssl ? 443 : 80; } else { port = uri.getPort(); } final EventLoopGroup group = new NioEventLoopGroup(); final HttpClientHandler httpClientHandler = new HttpClientHandler(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); 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(httpClientHandler); } }); final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); request.headers().set("Glowroot-Transaction-Type", "Synthetic"); ChannelFuture future = bootstrap.connect(host, port); final SettableFuture<HttpResponseStatus> settableFuture = SettableFuture.create(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { Channel ch = future.channel(); if (future.isSuccess()) { ch.writeAndFlush(request); } ch.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { HttpResponseStatus responseStatus = httpClientHandler.responseStatus; if (HttpResponseStatus.OK.equals(responseStatus)) { settableFuture.set(responseStatus); } else { settableFuture.setException( new Exception("Unexpected http response status: " + responseStatus)); } } else { settableFuture.setException(future.cause()); } group.shutdownGracefully(); } }); } }); return settableFuture; }
From source file:org.glowroot.local.ui.HttpServices.java
License:Apache License
@SuppressWarnings("argument.type.incompatible") static void addErrorListener(ChannelFuture future) { future.addListener(new ChannelFutureListener() { @Override// www.j av a2 s . c o m public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause == null) { return; } if (shouldLogException(cause)) { logger.error(cause.getMessage(), cause); } future.channel().close(); } }); }
From source file:org.glowroot.ui.HttpServices.java
License:Apache License
@SuppressWarnings("argument.type.incompatible") static void addErrorListener(ChannelFuture future) { future.addListener(new GenericFutureListener<ChannelFuture>() { @Override/* w w w .j av a 2 s.co m*/ public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause == null) { return; } if (shouldLogException(cause)) { logger.error(cause.getMessage(), cause); } future.channel().close(); } }); }
From source file:org.graylog2.gelfclient.transport.GelfTcpTransport.java
License:Apache License
@Override protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final GelfSenderThread senderThread = new GelfSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()) .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()) .remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() { @Override//www . ja va 2 s . c o m protected void initChannel(SocketChannel ch) throws Exception { if (config.isTlsEnabled()) { LOG.debug("TLS enabled."); final SslContext sslContext; if (!config.isTlsCertVerificationEnabled()) { // If the cert should not be verified just use an insecure trust manager. LOG.debug("TLS certificate verification disabled!"); sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else if (config.getTlsTrustCertChainFile() != null) { // If a cert chain file is set, use it. LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile()); sslContext = SslContext.newClientContext(config.getTlsTrustCertChainFile()); } else { // Otherwise use the JVM default cert chain. sslContext = SslContext.newClientContext(); } ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); } // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then. // The graylog2-server uses '\0'-bytes as delimiter for TCP frames. ch.pipeline().addLast(new GelfMessageJsonEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // We do not receive data. } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected!"); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); if (config.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize()); } bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.debug("Connected!"); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { @SuppressWarnings("unchecked") final List<SingleMetric> in = (List<SingleMetric>) msg; LOG.trace("Received some metrics: {}", in); fifo.addAll(in);//from ww w. j a v a 2 s.c o m synchronized (connectingMutex) { // make sure to only open one connection at a time if (isConnecting) return; } if (senderChannel != null) { sendToChannel(senderChannel); return; } ChannelFuture cf = connectRestServer(ctx.channel().eventLoop().parent()); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { synchronized (connectingMutex) { isConnecting = false; } if (!future.isSuccess()) { Throwable cause = future.cause(); if (cause instanceof ConnectException) { LOG.warn("Sending failed: " + cause.getLocalizedMessage()); } else { LOG.warn("Something went wrong: " + cause); } } else { // the remote is up. senderChannel = future.channel(); sendToChannel(senderChannel); } } }); }