List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:org.betawares.jorre.Server.java
License:Open Source License
/** * Send a callback to the client with the specified channelId * // w w w. j a va2 s . c om * @param channelId id of the {@link Client} channel * @param callback {@link ClientCallback} object to send to client * @throws CommunicationException thrown if client channel cannot be found or is not connected */ public void callback(ChannelId channelId, ClientCallback callback) throws CommunicationException { Channel ch = clients.find(channelId); if (ch == null) { throw new CommunicationException("Invalid sessionId during callback"); } if (!ch.isActive()) { logger.error("Connection is not active"); throw new CommunicationException("No connection to client during callback"); } ch.writeAndFlush(callback).addListener((ChannelFutureListener) (ChannelFuture future) -> { if (!future.isSuccess()) { logger.error("Communication error", future.cause()); throw new CommunicationException("Communication error during callback", future.cause()); } }); }
From source file:org.conscrypt.testing.NettyServer.java
License:Apache License
public void start() { group = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(group);/* ww w.jav a2 s. com*/ b.channel(NioServerSocketChannel.class); b.option(SO_BACKLOG, 128); b.childOption(SO_KEEPALIVE, true); b.childHandler(new ChannelInitializer<Channel>() { @Override public void initChannel(final Channel ch) throws Exception { SslContext context = TestUtil.newNettyServerContext(cipher); SSLEngine sslEngine = context.newEngine(ch.alloc()); ch.pipeline().addFirst(new SslHandler(sslEngine)); ch.pipeline().addLast(new MessageDecoder()); } }); // Bind and start to accept incoming connections. ChannelFuture future = b.bind(port); try { future.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted waiting for bind"); } if (!future.isSuccess()) { throw new RuntimeException("Failed to bind", future.cause()); } channel = future.channel(); }
From source file:org.dcache.xrootd.protocol.messages.AsyncResponse.java
License:Open Source License
@Override public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) { try {//from w w w . j a v a 2 s. com int dlen = getDataLength(); ByteBuf header = ctx.alloc().buffer(8 + dlen); try { header.writeShort(0); header.writeShort(kXR_attn); header.writeInt(dlen); header.writeInt(kXR_asynresp); header.writeInt(0); } catch (Error | RuntimeException t) { promise.setFailure(t); header.release(); return; } ctx.write(header).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { promise.tryFailure(future.cause()); } } }); ChannelPromise channelPromise = ctx.newPromise(); channelPromise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.trySuccess(); } else { promise.tryFailure(future.cause()); } } }); ReferenceCountUtil.retain(response).writeTo(ctx, channelPromise); } finally { release(); } }
From source file:org.dcache.xrootd.protocol.messages.ZeroCopyReadResponse.java
License:Open Source License
@Override public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) { ByteBuf header = ctx.alloc().buffer(8); header.writeShort(request.getStreamId()); header.writeShort(kXR_ok);//from w w w.j av a2 s . c om header.writeInt(count); ctx.write(header).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { promise.tryFailure(future.cause()); } } }); ctx.write(new DefaultFileRegion(file, request.getReadOffset(), count)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.trySuccess(); } else { promise.tryFailure(future.cause()); } } }); }
From source file:org.dcache.xrootd.stream.ChunkedResponseWriteHandler.java
License:Open Source License
private boolean doFlush(final ChannelHandlerContext ctx) throws Exception { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null);/* www . j a v a 2 s .c o m*/ return false; } boolean flushed = false; while (channel.isWritable()) { if (currentWrite == null) { currentWrite = queue.poll(); } if (currentWrite == null) { break; } final PendingWrite currentWrite = this.currentWrite; final ChunkedResponse pendingMessage = currentWrite.msg; boolean endOfInput; Object message = null; try { message = pendingMessage.nextChunk(ctx.alloc()); endOfInput = pendingMessage.isEndOfInput(); } catch (final Throwable t) { this.currentWrite = null; if (message != null) { ReferenceCountUtil.release(message); } currentWrite.fail(t); break; } if (message == null) { // If message is null write an empty ByteBuf. // See https://github.com/netty/netty/issues/1671 message = Unpooled.EMPTY_BUFFER; } final int amount = amount(message); ChannelFuture f = ctx.write(message); if (endOfInput) { this.currentWrite = null; // Register a listener which will close the input once the write is complete. // This is needed because the Chunk may have some resource bound that can not // be closed before its not written. // // See https://github.com/netty/netty/issues/303 f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); currentWrite.success(); } } }); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); } } }); } // Always need to flush ctx.flush(); flushed = true; if (!channel.isActive()) { discard(new ClosedChannelException()); break; } } return flushed; }
From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java
License:Open Source License
/** * Send message with acquired channel./*from w w w . j a v a 2 s .com*/ * * Intended to be overridden, if message sending should be delayed to * complete a TLS handshake. * * @param channel acquired channel * @param endpointMatcher endpoint matcher * @param msg message to be send */ protected void send(final Channel channel, final EndpointContextMatcher endpointMatcher, final RawData msg) { EndpointContext context = contextUtil.buildEndpointContext(channel); /* * check, if the message should be sent with the established connection */ if (endpointMatcher != null && !endpointMatcher.isToBeSent(msg.getEndpointContext(), context)) { LOGGER.warn("TcpConnector drops {} bytes to {}:{}", msg.getSize(), msg.getAddress(), msg.getPort()); msg.onError(new EndpointMismatchException()); return; } msg.onContextEstablished(context); ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes())); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { msg.onSent(); } else if (future.isCancelled()) { msg.onError(new CancellationException()); } else { LOGGER.warn("TcpConnector drops {} bytes to {}:{} caused by", msg.getSize(), msg.getAddress(), msg.getPort(), future.cause()); msg.onError(future.cause()); } } }); }
From source file:org.eclipse.californium.elements.tcp.TcpServerConnector.java
License:Open Source License
@Override public void send(final RawData msg) { if (msg == null) { throw new NullPointerException("Message must not be null"); }//from ww w . j ava 2s .c o m if (msg.isMulticast()) { LOGGER.warn("TcpConnector drops {} bytes to multicast {}:{}", msg.getSize(), msg.getAddress(), msg.getPort()); msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!")); return; } if (bossGroup == null) { msg.onError(new IllegalStateException("TCP server connector not running!")); return; } Channel channel = activeChannels.get(msg.getInetSocketAddress()); if (channel == null) { // TODO: Is it worth allowing opening a new connection when in server mode? LOGGER.debug("Attempting to send message to an address without an active connection {}", msg.getAddress()); msg.onError(new EndpointUnconnectedException()); return; } EndpointContext context = contextUtil.buildEndpointContext(channel); final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher(); /* check, if the message should be sent with the established connection */ if (null != endpointMatcher && !endpointMatcher.isToBeSent(msg.getEndpointContext(), context)) { LOGGER.warn("TcpConnector drops {} bytes to {}:{}", msg.getSize(), msg.getAddress(), msg.getPort()); msg.onError(new EndpointMismatchException()); return; } msg.onContextEstablished(context); ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes())); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { msg.onSent(); } else if (future.isCancelled()) { msg.onError(new CancellationException()); } else { msg.onError(future.cause()); } } }); }
From source file:org.eclipse.milo.opcua.stack.client.UaTcpStackClient.java
License:Open Source License
public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client, Optional<ClientSecureChannel> existingChannel) { CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override// w ww . j av a 2 s .c o m protected void initChannel(SocketChannel channel) throws Exception { UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client, existingChannel, handshake); channel.pipeline().addLast(acknowledgeHandler); } }); try { URI uri = new URI(client.getEndpointUrl()).parseServerAuthority(); bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> { if (!f.isSuccess()) { handshake.completeExceptionally(f.cause()); } }); } catch (Throwable e) { UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, e); handshake.completeExceptionally(failure); } return handshake; }
From source file:org.eclipse.milo.opcua.stack.server.tcp.SocketServer.java
License:Open Source License
public synchronized void bind() throws ExecutionException, InterruptedException { if (channel != null) return; // Already bound CompletableFuture<Unit> bindFuture = new CompletableFuture<>(); bootstrap.bind(address).addListener(new ChannelFutureListener() { @Override//from w w w .j av a 2 s .com public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = future.channel(); bindFuture.complete(Unit.VALUE); } else { bindFuture.completeExceptionally(future.cause()); } } }); bindFuture.get(); }
From source file:org.elasticsearch.hadoop.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 ww w . j av a2 s . c o m Channel[] channels = new Channel[1]; channels[0] = connect.channel(); channels[0].closeFuture().addListener(new ChannelCloseListener(node)); return new NodeChannels(channels, channels, channels, channels, channels); }