io.netty.channel.ChannelPromise Java Examples
The following examples show how to use
io.netty.channel.ChannelPromise.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractEpollStreamChannel.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
/** * Splice from this {@link AbstractEpollStreamChannel} to another {@link AbstractEpollStreamChannel}. * The {@code len} is the number of bytes to splice. If using {@link Integer#MAX_VALUE} it will * splice until the {@link ChannelFuture} was canceled or it was failed. * * Please note: * <ul> * <li>both channels need to be registered to the same {@link EventLoop}, otherwise an * {@link IllegalArgumentException} is thrown. </li> * <li>{@link EpollChannelConfig#getEpollMode()} must be {@link EpollMode#LEVEL_TRIGGERED} for this and the * target {@link AbstractEpollStreamChannel}</li> * </ul> * */ public final ChannelFuture spliceTo(final AbstractEpollStreamChannel ch, final int len, final ChannelPromise promise) { if (ch.eventLoop() != eventLoop()) { throw new IllegalArgumentException("EventLoops are not the same."); } if (len < 0) { throw new IllegalArgumentException("len: " + len + " (expected: >= 0)"); } if (ch.config().getEpollMode() != EpollMode.LEVEL_TRIGGERED || config().getEpollMode() != EpollMode.LEVEL_TRIGGERED) { throw new IllegalStateException("spliceTo() supported only when using " + EpollMode.LEVEL_TRIGGERED); } checkNotNull(promise, "promise"); if (!isOpen()) { promise.tryFailure(SPLICE_TO_CLOSED_CHANNEL_EXCEPTION); } else { addToSpliceQueue(new SpliceInChannelTask(ch, len, promise)); failSpliceIfClosed(promise); } return promise; }
Example #2
Source File: AccessLogChannelHandler.java From zuul with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); if (msg instanceof HttpResponse) { state.response = (HttpResponse) msg; state.responseBodySize = 0; } if (msg instanceof HttpContent) { state.responseBodySize += ((HttpContent) msg).content().readableBytes(); } super.write(ctx, msg, promise); }
Example #3
Source File: DuplexHandler.java From PingAPI with MIT License | 6 votes |
/** * The write() method sends packets to the client * It needs to be overrode in order to listen for outgoing packets */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if(msg instanceof PacketStatusOutServerInfo) { PacketStatusOutServerInfo packet = (PacketStatusOutServerInfo) msg; PingReply reply = ServerInfoPacketHandler.constructReply(packet, ctx); this.event = new PingEvent(reply); for(PingListener listener : PingAPI.getListeners()) { listener.onPing(event); } if(!this.event.isCancelled()) { super.write(ctx, ServerInfoPacketHandler.constructPacket(reply), promise); } return; } else if(msg instanceof PacketStatusOutPong) { if(this.event != null && this.event.isPongCancelled()) { return; } } super.write(ctx, msg, promise); }
Example #4
Source File: NettyServerHandler.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
/** * Handler for commands sent from the stream. */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof SendGrpcFrameCommand) { sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise); } else if (msg instanceof SendResponseHeadersCommand) { sendResponseHeaders(ctx, (SendResponseHeadersCommand) msg, promise); } else if (msg instanceof CancelServerStreamCommand) { cancelStream(ctx, (CancelServerStreamCommand) msg, promise); } else if (msg instanceof ForcefulCloseCommand) { forcefulClose(ctx, (ForcefulCloseCommand) msg, promise); } else { AssertionError e = new AssertionError("Write called for unexpected type: " + msg.getClass().getName()); ReferenceCountUtil.release(msg); promise.setFailure(e); throw e; } }
Example #5
Source File: DuplexHandler.java From PingAPI with MIT License | 6 votes |
/** * The write() method sends packets to the client * It needs to be overrode in order to listen for outgoing packets */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if(msg instanceof PacketStatusOutServerInfo) { PacketStatusOutServerInfo packet = (PacketStatusOutServerInfo) msg; PingReply reply = ServerInfoPacketHandler.constructReply(packet, ctx); this.event = new PingEvent(reply); for(PingListener listener : PingAPI.getListeners()) { listener.onPing(event); } if(!this.event.isCancelled()) { super.write(ctx, ServerInfoPacketHandler.constructPacket(reply), promise); } return; } else if(msg instanceof PacketStatusOutPong) { if(this.event != null && this.event.isPongCancelled()) { return; } } super.write(ctx, msg, promise); }
Example #6
Source File: NioSocketChannel.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
private static void shutdownDone(ChannelFuture shutdownOutputFuture, ChannelFuture shutdownInputFuture, ChannelPromise promise) { Throwable shutdownOutputCause = shutdownOutputFuture.cause(); Throwable shutdownInputCause = shutdownInputFuture.cause(); if (shutdownOutputCause != null) { if (shutdownInputCause != null) { logger.debug("Exception suppressed because a previous exception occurred.", shutdownInputCause); } promise.setFailure(shutdownOutputCause); } else if (shutdownInputCause != null) { promise.setFailure(shutdownInputCause); } else { promise.setSuccess(); } }
Example #7
Source File: PublishPollServiceImplTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Test public void test_inflight_messages() throws NoMessageIdAvailableException { when(messageIDPool.takeIfAvailable(1)).thenReturn(1); when(messageIDPool.takeIfAvailable(2)).thenReturn(2); when(clientQueuePersistence.readInflight(eq("client"), anyLong(), anyInt())) .thenReturn(Futures.immediateFuture(ImmutableList.of(createPublish(1), new PUBREL(2)))); when(channel.isActive()).thenReturn(true); when(channel.newPromise()).thenReturn(mock(ChannelPromise.class)); when(channel.attr(ChannelAttributes.IN_FLIGHT_MESSAGES)).thenReturn(new TestChannelAttribute<>(new AtomicInteger(0))); publishPollService.pollInflightMessages("client", channel); verify(messageIDPool, times(2)).takeIfAvailable(anyInt()); verify(pipeline, times(1)).fireUserEventTriggered(any(PUBLISH.class)); verify(channelInactiveHandler, times(1)).addCallback(anyString(), any(ChannelInactiveHandler.ChannelInactiveCallback.class)); verify(channel).writeAndFlush(any(PubrelWithFuture.class)); }
Example #8
Source File: NettyServer.java From qpid-jms with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { LOG.trace("NettyServerHandler: Channel write: {}", msg); if (isWebSocketServer() && msg instanceof ByteBuf) { if (isFragmentWrites()) { ByteBuf orig = (ByteBuf) msg; int origIndex = orig.readerIndex(); int split = orig.readableBytes()/2; ByteBuf part1 = orig.copy(origIndex, split); LOG.trace("NettyServerHandler: Part1: {}", part1); orig.readerIndex(origIndex + split); LOG.trace("NettyServerHandler: Part2: {}", orig); BinaryWebSocketFrame frame1 = new BinaryWebSocketFrame(false, 0, part1); ctx.writeAndFlush(frame1); ContinuationWebSocketFrame frame2 = new ContinuationWebSocketFrame(true, 0, orig); ctx.write(frame2, promise); } else { BinaryWebSocketFrame frame = new BinaryWebSocketFrame((ByteBuf) msg); ctx.write(frame, promise); } } else { ctx.write(msg, promise); } }
Example #9
Source File: NioSctpServerChannel.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public ChannelFuture bindAddress(final InetAddress localAddress, final ChannelPromise promise) { if (eventLoop().inEventLoop()) { try { javaChannel().bindAddress(localAddress); promise.setSuccess(); } catch (Throwable t) { promise.setFailure(t); } } else { eventLoop().execute(new Runnable() { @Override public void run() { bindAddress(localAddress, promise); } }); } return promise; }
Example #10
Source File: HttpUploadHandlerTest.java From bazel with Apache License 2.0 | 6 votes |
private void uploadsShouldWork(boolean casUpload, EmbeddedChannel ch, HttpResponseStatus status) throws Exception { ByteArrayInputStream data = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5}); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(new UploadCommand(CACHE_URI, casUpload, "abcdef", data, 5), writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.method()).isEqualTo(HttpMethod.PUT); assertThat(request.headers().get(HttpHeaders.CONNECTION)) .isEqualTo(HttpHeaderValues.KEEP_ALIVE.toString()); HttpChunkedInput content = ch.readOutbound(); assertThat(content.readChunk(ByteBufAllocator.DEFAULT).content().readableBytes()).isEqualTo(5); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ch.writeInbound(response); assertThat(writePromise.isDone()).isTrue(); assertThat(ch.isOpen()).isTrue(); }
Example #11
Source File: TransportBase.java From krpc with Apache License 2.0 | 6 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof RpcData) { RpcData data = (RpcData) msg; String connId = getConnId(ctx); String key = getKey(connId); boolean enc = false; if( key != null && isRequest(data.getMeta()) ) { ReflectionUtils.updateEncrypt(data.getMeta(),1); enc = true; } int size = enc ? codec.getSize(data) + 16 : codec.getSize(data); ByteBuf out = ctx.alloc().buffer(size); codec.encode(data, out, key); ctx.writeAndFlush(out, promise); } else { super.write(ctx, msg, promise); } }
Example #12
Source File: AbstractBootstrap.java From arcusplatform with Apache License 2.0 | 6 votes |
private static void doBind0( final ChannelFuture regFuture, final Channel channel, final SocketAddress localAddress, final ChannelPromise promise) { // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up // the pipeline in its channelRegistered() implementation. channel.eventLoop().execute(new Runnable() { @Override public void run() { if (regFuture.isSuccess()) { channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } else { promise.setFailure(regFuture.cause()); } } }); }
Example #13
Source File: DuplexHandler.java From PingAPI with MIT License | 6 votes |
/** * The write() method sends packets to the client * It needs to be overrode in order to listen for outgoing packets */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if(msg instanceof PacketStatusOutServerInfo) { PacketStatusOutServerInfo packet = (PacketStatusOutServerInfo) msg; PingReply reply = ServerInfoPacketHandler.constructReply(packet, ctx); this.event = new PingEvent(reply); for(PingListener listener : PingAPI.getListeners()) { listener.onPing(event); } if(!this.event.isCancelled()) { super.write(ctx, ServerInfoPacketHandler.constructPacket(reply), promise); } return; } else if(msg instanceof PacketStatusOutPong) { if(this.event != null && this.event.isPongCancelled()) { return; } } super.write(ctx, msg, promise); }
Example #14
Source File: HeaderCodec.java From drift with Apache License 2.0 | 5 votes |
@Override public void write(ChannelHandlerContext context, Object message, ChannelPromise promise) { if (message instanceof ThriftFrame) { context.write(HeaderTransport.encodeFrame((ThriftFrame) message), promise); } else { context.write(message, promise); } }
Example #15
Source File: NettyServerHandlerTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test public void noGoAwaySentBeforeMaxConnectionIdleReached() throws Exception { maxConnectionIdleInNanos = TimeUnit.MINUTES.toNanos(30L); manualSetUp(); fakeClock().forwardTime(20, TimeUnit.MINUTES); // GO_AWAY not sent yet verifyWrite(never()).writeGoAway( any(ChannelHandlerContext.class), any(Integer.class), any(Long.class), any(ByteBuf.class), any(ChannelPromise.class)); assertTrue(channel().isOpen()); }
Example #16
Source File: MySQLEncoder.java From vertx-sql-client with Apache License 2.0 | 5 votes |
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof CommandBase<?>) { CommandBase<?> cmd = (CommandBase<?>) msg; write(cmd); } else { super.write(ctx, msg, promise); } }
Example #17
Source File: AccessLogHandlerH2.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("FutureReturnValueIgnored") public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { boolean lastContent = false; if (msg instanceof Http2HeadersFrame) { final Http2HeadersFrame responseHeaders = (Http2HeadersFrame) msg; final Http2Headers headers = responseHeaders.headers(); lastContent = responseHeaders.isEndStream(); accessLog.status(headers.status()) .chunked(true); } if (msg instanceof Http2DataFrame) { final Http2DataFrame data = (Http2DataFrame) msg; lastContent = data.isEndStream(); accessLog.increaseContentLength(data.content().readableBytes()); } if (lastContent) { ctx.write(msg, promise.unvoid()) .addListener(future -> { if (future.isSuccess()) { accessLog.log(); } }); return; } //"FutureReturnValueIgnored" this is deliberate ctx.write(msg, promise); }
Example #18
Source File: DuplexHandler.java From PingAPI with MIT License | 5 votes |
/** * In versions 1.8 and higher the connection is closed after two packets have been sent * Overriding this method is required to create animations for versions 1.8 through 1.8.3 */ @Override public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if(this.event == null || !this.event.isPongCancelled()) { super.close(ctx, future); } }
Example #19
Source File: AltsProtocolNegotiatorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Test public void flushShouldFailAllPromises() throws Exception { doHandshake(); channel .pipeline() .addFirst( new ChannelDuplexHandler() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { throw new Exception("Fake exception"); } }); // Write the message 1 character at a time. String message = "hello"; final AtomicInteger failures = new AtomicInteger(); for (int ix = 0; ix < message.length(); ++ix) { ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); @SuppressWarnings("unused") // go/futurereturn-lsc Future<?> possiblyIgnoredError = channel .write(in) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { failures.incrementAndGet(); } } }); } channel.flush(); // Verify that the promises fail. assertEquals(message.length(), failures.get()); }
Example #20
Source File: OrderedTopicHandlerTest.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
@Test(timeout = 4_000) public void test_remove_messages() throws Exception { InternalConfigurations.MAX_INFLIGHT_WINDOW_SIZE = 1; final PUBLISH publish1 = createPublish("topic", 1, QoS.AT_LEAST_ONCE); final PUBLISH publish2 = createPublish("topic", 2, QoS.AT_LEAST_ONCE); final PUBLISH publish3 = createPublish("topic", 3, QoS.AT_LEAST_ONCE); final PUBLISH publish4 = createPublish("topic", 4, QoS.AT_LEAST_ONCE); final ChannelPromise promise1 = channel.newPromise(); final ChannelPromise promise2 = channel.newPromise(); final ChannelPromise promise3 = channel.newPromise(); final ChannelPromise promise4 = channel.newPromise(); channel.writeAndFlush(publish1, promise1); channel.writeAndFlush(publish2, promise2); channel.writeAndFlush(publish3, promise3); channel.writeAndFlush(publish4, promise4); promise1.await(); assertEquals(3, orderedTopicHandler.queue.size()); channel.pipeline().fireChannelRead(new PUBACK(1)); promise2.await(); assertEquals(2, orderedTopicHandler.queue.size()); channel.pipeline().fireChannelRead(new PUBACK(2)); promise3.await(); channel.pipeline().fireChannelRead(new PUBACK(3)); promise4.await(); assertTrue(orderedTopicHandler.queue.isEmpty()); }
Example #21
Source File: DefaultHttp2ConnectionEncoderTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Test public void settingsWriteShouldNotUpdateSettings() throws Exception { Http2Settings settings = new Http2Settings(); settings.initialWindowSize(100); settings.maxConcurrentStreams(1000); settings.headerTableSize(2000); ChannelPromise promise = newPromise(); encoder.writeSettings(ctx, settings, promise); verify(writer).writeSettings(eq(ctx), eq(settings), eq(promise)); }
Example #22
Source File: LoggingHandler.java From netty.book.kor with MIT License | 5 votes |
@Override public void connect( ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception { if (logger.isEnabled(internalLevel)) { logger.log(internalLevel, format(ctx, "CONNECT", remoteAddress, localAddress)); } ctx.connect(remoteAddress, localAddress, promise); }
Example #23
Source File: RntbdRequestManager.java From azure-cosmosdb-java with MIT License | 5 votes |
/** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); }
Example #24
Source File: Http2ConnectionHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public ChannelFuture resetStream(final ChannelHandlerContext ctx, int streamId, long errorCode, ChannelPromise promise) { final Http2Stream stream = connection().stream(streamId); if (stream == null) { return resetUnknownStream(ctx, streamId, errorCode, promise.unvoid()); } return resetStream(ctx, stream, errorCode, promise); }
Example #25
Source File: ResponseOrderingHandler.java From drift with Apache License 2.0 | 5 votes |
@Override public void write(ChannelHandlerContext context, Object message, ChannelPromise promise) { if (message instanceof ThriftFrame) { // always re-enable auto read context.channel().config().setAutoRead(true); } context.write(message, promise); }
Example #26
Source File: StatsdMeterRegistryPublishTest.java From micrometer with Apache License 2.0 | 5 votes |
private void trackWritesForUdpClient(StatsdProtocol protocol, AtomicInteger writeCount) { if (protocol == StatsdProtocol.UDP) { await().until(() -> meterRegistry.client.get() != null); ((Connection) meterRegistry.client.get()) .addHandler(new LoggingHandler("udpclient", LogLevel.INFO)) .addHandler(new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { writeCount.incrementAndGet(); super.write(ctx, msg, promise); } }); } }
Example #27
Source File: SslHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private void closeOutboundAndChannel( final ChannelHandlerContext ctx, final ChannelPromise promise, boolean disconnect) throws Exception { if (!ctx.channel().isActive()) { if (disconnect) { ctx.disconnect(promise); } else { ctx.close(promise); } return; } outboundClosed = true; engine.closeOutbound(); ChannelPromise closeNotifyPromise = ctx.newPromise(); try { flush(ctx, closeNotifyPromise); } finally { // It's important that we do not pass the original ChannelPromise to safeClose(...) as when flush(....) // throws an Exception it will be propagated to the AbstractChannelHandlerContext which will try // to fail the promise because of this. This will then fail as it was already completed by safeClose(...). // We create a new ChannelPromise and try to notify the original ChannelPromise // once it is complete. If we fail to do so we just ignore it as in this case it was failed already // because of a propagated Exception. // // See https://github.com/netty/netty/issues/5931 safeClose(ctx, closeNotifyPromise, ctx.newPromise().addListener( new ChannelPromiseNotifier(false, promise))); } }
Example #28
Source File: NettyTransportClient.java From Sentinel with Apache License 2.0 | 5 votes |
@Override public ClusterResponse sendRequest(ClusterRequest request) throws Exception { if (!isReady()) { throw new SentinelClusterException(ClusterErrorMessages.CLIENT_NOT_READY); } if (!validRequest(request)) { throw new SentinelClusterException(ClusterErrorMessages.BAD_REQUEST); } int xid = getCurrentId(); try { request.setId(xid); channel.writeAndFlush(request); ChannelPromise promise = channel.newPromise(); TokenClientPromiseHolder.putPromise(xid, promise); if (!promise.await(ClusterClientConfigManager.getRequestTimeout())) { throw new SentinelClusterException(ClusterErrorMessages.REQUEST_TIME_OUT); } SimpleEntry<ChannelPromise, ClusterResponse> entry = TokenClientPromiseHolder.getEntry(xid); if (entry == null || entry.getValue() == null) { // Should not go through here. throw new SentinelClusterException(ClusterErrorMessages.UNEXPECTED_STATUS); } return entry.getValue(); } finally { TokenClientPromiseHolder.remove(xid); } }
Example #29
Source File: NettyClientHandlerTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Test public void cancelTwiceDifferentReasons() throws Exception { createStream(); cancelStream(Status.DEADLINE_EXCEEDED); verifyWrite().writeRstStream(eq(ctx()), eq(3), eq(Http2Error.CANCEL.code()), any(ChannelPromise.class)); ChannelFuture future = cancelStream(Status.CANCELLED); assertTrue(future.isSuccess()); }
Example #30
Source File: AbstractEpollStreamChannel.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) { if (promise == null) { // Closed via cancellation and the promise has been notified already. return; } // Use tryFailure() instead of setFailure() to avoid the race against cancel(). promise.tryFailure(cause); closeIfClosed(); }