List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:object.client.ext.ObjectClient.java
private Channel connect() { try {// www. ja va2 s .co m //System.out.println("[connectioState] " + connectioState.name()); //System.out.println("Try to Connect on : " + remotehost + ":" + port); CompletableFuture<Channel> futureResult = new CompletableFuture<>(); ChannelFuture future = bootstrap.connect(remotehost, port); future.addListener((ChannelFutureListener) (ChannelFuture future1) -> { if (future1.isSuccess()) { futureResult.complete(future1.channel()); } else { futureResult.completeExceptionally(new TryConnectException(remotehost, port)); } }); future.awaitUninterruptibly(); return futureResult.join(); } catch (Exception ex) { return null; } }
From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java
License:Open Source License
/** * Wraps given {@link ChannelFuture} to ensure the event loops * shut down gracefully.//from ww w. ja v a 2 s . c o m * @param target the original channel future. * @param bossGroup the boss group. * @param workerGroup the worker group. * @return the wrapped future. */ @NotNull protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup, @NotNull final NioEventLoopGroup workerGroup) { return new ChannelFuture() { @Override public Channel channel() { return target.channel(); } /** * {@inheritDoc} */ @Override public ChannelFuture addListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.addListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture addListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.addListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListener( @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) { return target.removeListener(listener); } /** * {@inheritDoc} */ @Override public ChannelFuture removeListeners( @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) { return target.removeListeners(listeners); } /** * {@inheritDoc} */ @Override public ChannelFuture sync() throws InterruptedException { ChannelFuture result = null; try { result = target.sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } return result; } /** * {@inheritDoc} */ @Override public ChannelFuture syncUninterruptibly() { return target.syncUninterruptibly(); } /** * {@inheritDoc} */ @Override public ChannelFuture await() throws InterruptedException { return target.await(); } /** * {@inheritDoc} */ @Override public ChannelFuture awaitUninterruptibly() { return target.awaitUninterruptibly(); } /** * {@inheritDoc} */ @Override public boolean isSuccess() { return target.isSuccess(); } /** * {@inheritDoc} */ @Override public boolean isCancellable() { return target.isCancellable(); } /** * {@inheritDoc} */ @Override public Throwable cause() { return target.cause(); } /** * {@inheritDoc} */ @Override public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException { return target.await(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean await(final long timeoutMillis) throws InterruptedException { return target.await(timeoutMillis); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) { return target.awaitUninterruptibly(timeout, unit); } /** * {@inheritDoc} */ @Override public boolean awaitUninterruptibly(final long timeoutMillis) { return target.awaitUninterruptibly(timeoutMillis); } /** * {@inheritDoc} */ @Override public Void getNow() { return target.getNow(); } /** * {@inheritDoc} */ @Override public boolean cancel(final boolean mayInterruptIfRunning) { return target.cancel(mayInterruptIfRunning); } /** * {@inheritDoc} */ @Override public boolean isCancelled() { return target.isCancelled(); } /** * {@inheritDoc} */ @Override public boolean isDone() { return target.isDone(); } /** * {@inheritDoc} */ @Override public Void get() throws InterruptedException, ExecutionException { return target.get(); } /** * {@inheritDoc} */ @Override public Void get(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return target.get(timeout, unit); } }; }
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;/*w ww.j a v a 2s . c om*/ } // 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; }/*from www . ja va 2 s .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;/* w w w . j ava 2 s . c o m*/ } // 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;//from w w w . ja va2s .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."); }/*from w w w . j av a 2s. co 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) { 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 w w. java2 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.bookkeeper.proto.PacketProcessorBaseV3.java
License:Apache License
protected void sendResponse(StatusCode code, Object response, OpStatsLogger statsLogger) { final long writeNanos = MathUtils.nowInNano(); final long timeOut = requestProcessor.getWaitTimeoutOnBackpressureMillis(); if (timeOut >= 0 && !channel.isWritable()) { if (!requestProcessor.isBlacklisted(channel)) { synchronized (channel) { if (!channel.isWritable() && !requestProcessor.isBlacklisted(channel)) { final long waitUntilNanos = writeNanos + TimeUnit.MILLISECONDS.toNanos(timeOut); while (!channel.isWritable() && MathUtils.nowInNano() < waitUntilNanos) { try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { break; }/*from w w w . j a v a 2 s. co m*/ } if (!channel.isWritable()) { requestProcessor.blacklistChannel(channel); requestProcessor.handleNonWritableChannel(channel); } } } } if (!channel.isWritable()) { LOGGER.warn("cannot write response to non-writable channel {} for request {}", channel, StringUtils.requestToString(request)); requestProcessor.getRequestStats().getChannelWriteStats() .registerFailedEvent(MathUtils.elapsedNanos(writeNanos), TimeUnit.NANOSECONDS); statsLogger.registerFailedEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); return; } else { requestProcessor.invalidateBlacklist(channel); } } channel.writeAndFlush(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { long writeElapsedNanos = MathUtils.elapsedNanos(writeNanos); if (!future.isSuccess()) { requestProcessor.getRequestStats().getChannelWriteStats().registerFailedEvent(writeElapsedNanos, TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getChannelWriteStats() .registerSuccessfulEvent(writeElapsedNanos, TimeUnit.NANOSECONDS); } if (StatusCode.EOK == code) { statsLogger.registerSuccessfulEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); } else { statsLogger.registerFailedEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); } } }); }
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()); }// ww w . ja va2 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; }