List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:org.aotorrent.common.TorrentEngine.java
License:Apache License
/** * Adds new peers to this engine./*w ww . ja v a 2s . co m*/ * <p>If particular peer is already exist, it will be ignored.</p> * * @param peers Peers to append */ public void appendPeers(Collection<InetSocketAddress> peers) { synchronized (peerConnections) { peers.removeAll(peerConnections.keySet()); for (SocketAddress peer : peers) { if (peer.equals(address)) { continue; } final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.remoteAddress(peer); bootstrap.handler(new OutboundChannelInitializer(this)); final ChannelFuture connect = bootstrap.connect(); connect.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { final Throwable cause = future.cause(); if (cause != null) { LOGGER.error("Error {}", cause.getLocalizedMessage()); return; } final Channel channel = future.channel(); final HandshakeRequest handshakeRequest = new HandshakeRequest(getInfoHash(), peerId); final byte[] msg = handshakeRequest.toTransmit(); channel.writeAndFlush(msg); } }); } } }
From source file:org.apache.activemq.artemis.core.protocol.stomp.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return;/*from w w w . j ava 2s. com*/ } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false); this.handshaker = wsFactory.newHandshaker(req); if (this.handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and // wrap it in a binary web socket frame before letting the wsencoder send it on the wire future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER); } else { // Handshake failed, fire an exceptionCaught event future.channel().pipeline().fireExceptionCaught(future.cause()); } } }); } }
From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public Connection createConnection() { if (channelClazz == null) { return null; }/* w ww . ja v a 2s . c o m*/ // HORNETQ-907 - strip off IPv6 scope-id (if necessary) SocketAddress remoteDestination = new InetSocketAddress(host, port); InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress(); if (inetAddress instanceof Inet6Address) { Inet6Address inet6Address = (Inet6Address) inetAddress; if (inet6Address.getScopeId() != 0) { try { remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort()); } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } } ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination); ChannelFuture future; //port 0 does not work so only use local address if set if (localPort != 0) { SocketAddress localDestination; if (localAddress != null) { localDestination = new InetSocketAddress(localAddress, localPort); } else { localDestination = new InetSocketAddress(localPort); } future = bootstrap.connect(remoteDestination, localDestination); } else { future = bootstrap.connect(remoteDestination); } future.awaitUninterruptibly(); if (future.isSuccess()) { final Channel ch = future.channel(); SslHandler sslHandler = ch.pipeline().get(SslHandler.class); if (sslHandler != null) { Future<Channel> handshakeFuture = sslHandler.handshakeFuture(); if (handshakeFuture.awaitUninterruptibly(30000)) { if (handshakeFuture.isSuccess()) { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } else { ch.close().awaitUninterruptibly(); ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause()); return null; } } else { //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds")); ch.close().awaitUninterruptibly(); return null; } } if (httpUpgradeEnabled) { // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler. try { //get this first incase it removes itself HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade"); URI uri = new URI("http", null, host, port, null, null, null); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); final String endpoint = ConfigurationHelper.getStringProperty( TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration); if (endpoint != null) { request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint); } // Get 16 bit nonce and base 64 encode it byte[] nonce = randomBytes(16); String key = base64(nonce); request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key); ch.attr(REMOTING_KEY).set(key); ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request); // Send the HTTP request. ch.writeAndFlush(request); if (!httpUpgradeHandler.awaitHandshake()) { return null; } } catch (URISyntaxException e) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e); return null; } } else { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } // No acceptor on a client connection Listener connectionListener = new Listener(); NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false); connectionListener.connectionCreated(null, conn, protocolManager.getName()); return conn; } else { Throwable t = future.cause(); if (t != null && !(t instanceof ConnectException)) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause()); } return null; } }
From source file:org.apache.activemq.artemis.core.server.protocol.stomp.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return;// ww w . jav a 2s. c om } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false); this.httpRequest = req; this.handshaker = wsFactory.newHandshaker(req); if (this.handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and // wrap it in a binary web socket frame before letting the wsencoder send it on the wire future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER); } else { // Handshake failed, fire an exceptionCaught event future.channel().pipeline().fireExceptionCaught(future.cause()); } } }); } }
From source file:org.apache.activemq.artemis.core.server.protocol.websocket.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return;/* ww w .j a va 2s . co m*/ } // Handshake String supportedProtocolsCSV = StringUtil.joinStringList(supportedProtocols, ","); WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( this.getWebSocketLocation(req), supportedProtocolsCSV, false, maxFramePayloadLength); this.httpRequest = req; this.handshaker = wsFactory.newHandshaker(req); if (this.handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toActiveMQBuffer and // wrap it in a binary web socket frame before letting the wsencoder send it on the wire future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder", BINARY_WEBSOCKET_ENCODER); } else { // Handshake failed, fire an exceptionCaught event future.channel().pipeline().fireExceptionCaught(future.cause()); } } }); } }
From source file:org.apache.activemq.transport.amqp.client.transport.NettyTcpTransport.java
License:Apache License
@Override public void connect() throws IOException { if (listener == null) { throw new IllegalStateException("A transport listener must be set before connection attempts."); }// w w w . j a v a 2s. com final SslHandler sslHandler; if (isSSL()) { try { sslHandler = NettyTransportSupport.createSslHandler(getRemoteLocation(), getSslOptions()); } catch (Exception ex) { // TODO: can we stop it throwing Exception? throw IOExceptionSupport.create(ex); } } else { sslHandler = null; } group = new NioEventLoopGroup(1); bootstrap = new Bootstrap(); bootstrap.group(group); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel connectedChannel) throws Exception { configureChannel(connectedChannel, sslHandler); } }); configureNetty(bootstrap, getTransportOptions()); ChannelFuture future = bootstrap.connect(getRemoteHost(), getRemotePort()); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { handleException(future.channel(), IOExceptionSupport.create(future.cause())); } } }); try { connectLatch.await(); } catch (InterruptedException ex) { LOG.debug("Transport connection was interrupted."); Thread.interrupted(); failureCause = IOExceptionSupport.create(ex); } if (failureCause != null) { // Close out any Netty resources now as they are no longer needed. if (channel != null) { channel.close().syncUninterruptibly(); channel = null; } if (group != null) { group.shutdownGracefully(QUIET_PERIOD, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS); group = null; } throw failureCause; } else { // Connected, allow any held async error to fire now and close the transport. channel.eventLoop().execute(new Runnable() { @Override public void run() { if (failureCause != null) { channel.pipeline().fireExceptionCaught(failureCause); } } }); } }
From source file:org.apache.activemq.transport.netty.NettyTcpTransport.java
License:Apache License
@Override public void connect() throws IOException { if (listener == null) { throw new IllegalStateException("A transport listener must be set before connection attempts."); }//from w ww. jav a 2 s . c o m final SslHandler sslHandler; if (isSSL()) { try { sslHandler = NettyTransportSupport.createSslHandler(getRemoteLocation(), getSslOptions()); } catch (Exception ex) { // TODO: can we stop it throwing Exception? throw IOExceptionSupport.create(ex); } } else { sslHandler = null; } group = new NioEventLoopGroup(1); bootstrap = new Bootstrap(); bootstrap.group(group); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel connectedChannel) throws Exception { configureChannel(connectedChannel, sslHandler); } }); configureNetty(bootstrap, getTransportOptions()); ChannelFuture future = bootstrap.connect(getRemoteHost(), getRemotePort()); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { handleException(future.channel(), IOExceptionSupport.create(future.cause())); } } }); try { connectLatch.await(); } catch (InterruptedException ex) { LOG.debug("Transport connection was interrupted."); Thread.interrupted(); failureCause = IOExceptionSupport.create(ex); } if (failureCause != null) { // Close out any Netty resources now as they are no longer needed. if (channel != null) { channel.close().syncUninterruptibly(); channel = null; } if (group != null) { Future<?> fut = group.shutdownGracefully(0, SHUTDOWN_TIMEOUT, TimeUnit.MILLISECONDS); if (!fut.awaitUninterruptibly(2 * SHUTDOWN_TIMEOUT)) { LOG.trace("Channel group shutdown failed to complete in allotted time"); } group = null; } throw failureCause; } else { // Connected, allow any held async error to fire now and close the transport. channel.eventLoop().execute(new Runnable() { @Override public void run() { if (failureCause != null) { channel.pipeline().fireExceptionCaught(failureCause); } } }); } }
From source file:org.apache.camel.component.netty4.ClientModeTCPNettyServerBootstrapFactory.java
License:Apache License
protected Channel openChannel(ChannelFuture channelFuture) throws Exception { // blocking for channel to be done if (LOG.isTraceEnabled()) { LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout()); }//from www .jav a 2 s .com // here we need to wait it in other thread final CountDownLatch channelLatch = new CountDownLatch(1); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture cf) throws Exception { channelLatch.countDown(); } }); try { channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { throw new CamelException( "Interrupted while waiting for " + "connection to " + configuration.getAddress()); } if (!channelFuture.isDone() || !channelFuture.isSuccess()) { ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress()); if (channelFuture.cause() != null) { cause.initCause(channelFuture.cause()); } throw cause; } Channel answer = channelFuture.channel(); if (LOG.isDebugEnabled()) { LOG.debug("Creating connector to address: {}", configuration.getAddress()); } return answer; }
From source file:org.apache.camel.component.netty4.handlers.ServerResponseFutureListener.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { // if it was not a success then thrown an exception if (!future.isSuccess()) { Exception e = new CamelExchangeException("Cannot write response to " + remoteAddress, exchange, future.cause()); consumer.getExceptionHandler().handleException(e); }/*w w w. j a va2s . co m*/ // should channel be closed after complete? Boolean close; if (exchange.hasOut()) { close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } else { close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } // should we disconnect, the header can override the configuration boolean disconnect = consumer.getConfiguration().isDisconnect(); if (close != null) { disconnect = close; } if (disconnect) { if (LOG.isTraceEnabled()) { LOG.trace("Closing channel when complete at address: {}", remoteAddress); } NettyHelper.close(future.channel()); } }
From source file:org.apache.camel.component.netty4.NettyProducer.java
License:Apache License
public boolean process(final Exchange exchange, AsyncCallback callback) { if (!isRunAllowed()) { if (exchange.getException() == null) { exchange.setException(new RejectedExecutionException()); }/*from ww w.j a v a2 s. c om*/ callback.done(true); return true; } Object body; try { body = getRequestBody(exchange); if (body == null) { noReplyLogger.log("No payload to send for exchange: " + exchange); callback.done(true); return true; } } catch (Exception e) { exchange.setException(e); callback.done(true); return true; } // set the exchange encoding property if (getConfiguration().getCharsetName() != null) { exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(getConfiguration().getCharsetName())); } if (LOG.isTraceEnabled()) { LOG.trace("Pool[active={}, idle={}]", pool.getNumActive(), pool.getNumIdle()); } // get a channel from the pool Channel existing; try { existing = pool.borrowObject(); if (existing != null) { LOG.trace("Got channel from pool {}", existing); } } catch (Exception e) { exchange.setException(e); callback.done(true); return true; } // we must have a channel if (existing == null) { exchange.setException(new CamelExchangeException("Cannot get channel from pool", exchange)); callback.done(true); return true; } // need to declare as final final Channel channel = existing; final AsyncCallback producerCallback = new NettyProducerCallback(channel, callback); // setup state as attachment on the channel, so we can access the state later when needed putState(channel, new NettyCamelState(producerCallback, exchange)); // here we need to setup the remote address information here InetSocketAddress remoteAddress = null; if (!isTcp()) { remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort()); } // write body NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() { public void operationComplete(ChannelFuture channelFuture) throws Exception { LOG.trace("Operation complete {}", channelFuture); if (!channelFuture.isSuccess()) { // no success the set the caused exception and signal callback and break exchange.setException(channelFuture.cause()); producerCallback.done(false); return; } // if we do not expect any reply then signal callback to continue routing if (!configuration.isSync()) { try { // should channel be closed after complete? Boolean close; if (ExchangeHelper.isOutCapable(exchange)) { close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } else { close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } // should we disconnect, the header can override the configuration boolean disconnect = getConfiguration().isDisconnect(); if (close != null) { disconnect = close; } if (disconnect) { if (LOG.isTraceEnabled()) { LOG.trace("Closing channel when complete at address: {}", getEndpoint().getConfiguration().getAddress()); } NettyHelper.close(channel); } } finally { // signal callback to continue routing producerCallback.done(false); } } } }); // continue routing asynchronously return false; }