reactor.netty.FutureMono Java Examples

The following examples show how to use reactor.netty.FutureMono. 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: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTcpConfiguration_2() throws Exception {
	CountDownLatch latch = new CountDownLatch(10);
	LoopResources loop = LoopResources.create("testTcpConfiguration");
	ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	doTestTcpConfiguration(
			HttpServer.from(configureTcpServer(TcpServer.create(), loop, group, latch)),
			HttpClient.from(configureTcpClient(TcpClient.create(), loop, group, latch))
	);

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	FutureMono.from(group.close())
	          .then(loop.disposeLater())
	          .block(Duration.ofSeconds(30));
}
 
Example #2
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTcpConfiguration_1() throws Exception {
	CountDownLatch latch = new CountDownLatch(10);
	LoopResources loop = LoopResources.create("testTcpConfiguration");
	ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	doTestTcpConfiguration(
			HttpServer.create().tcpConfiguration(tcp -> configureTcpServer(tcp, loop, group, latch)),
			HttpClient.create().tcpConfiguration(tcp -> configureTcpClient(tcp, loop, group, latch))
	);

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	FutureMono.from(group.close())
	          .then(loop.disposeLater())
	          .block(Duration.ofSeconds(30));
}
 
Example #3
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Mono<Void> sendClose(CloseWebSocketFrame frame) {
	if (CLOSE_SENT.get(this) == 0) {
		//commented for now as we assume the close is always scheduled (deferFuture runs)
		//onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame));
		return FutureMono.deferFuture(() -> {
			if (CLOSE_SENT.getAndSet(this, 1) == 0) {
				discard();
				onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
				return channel().writeAndFlush(frame)
				                .addListener(ChannelFutureListener.CLOSE);
			}
			frame.release();
			return channel().newSucceededFuture();
		}).doOnCancel(() -> ReactorNetty.safeRelease(frame));
	}
	frame.release();
	return Mono.empty();
}
 
Example #4
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
final Mono<Void> withWebsocketSupport(String url,
		WebsocketServerSpec websocketServerSpec,
		BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<Void>> websocketHandler) {
	Objects.requireNonNull(websocketServerSpec, "websocketServerSpec");
	Objects.requireNonNull(websocketHandler, "websocketHandler");
	if (markSentHeaders()) {
		WebsocketServerOperations ops = new WebsocketServerOperations(url, websocketServerSpec, this);

		return FutureMono.from(ops.handshakerResult)
		                 .doOnEach(signal -> {
		                     if(!signal.hasError() && (websocketServerSpec.protocols() == null || ops.selectedSubprotocol() != null)) {
		                         websocketHandler.apply(ops, ops)
		                                         .subscribe(new WebsocketSubscriber(ops, signal.getContext()));
		                     }
		                 });
	}
	else {
		log.error(format(channel(), "Cannot enable websocket if headers have already been sent"));
	}
	return Mono.error(new IllegalStateException("Failed to upgrade to websocket"));
}
 
Example #5
Source File: UdpOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Join a multicast group.
 *
 * @param multicastAddress multicast address of the group to join
 *
 * @return a {@link Publisher} that will be complete when the group has been joined
 */
@Override
public Mono<Void> join(final InetAddress multicastAddress, @Nullable NetworkInterface iface) {
	if (null == iface && null != datagramChannel.config().getNetworkInterface()) {
		iface = datagramChannel.config().getNetworkInterface();
	}

	final ChannelFuture future;
	if (null != iface) {
		future = datagramChannel.joinGroup(new InetSocketAddress(multicastAddress,
				datagramChannel.localAddress()
				               .getPort()), iface);
	}
	else {
		future = datagramChannel.joinGroup(multicastAddress);
	}

	return FutureMono.from(future)
	                 .doOnSuccess(v -> {
	                     if (log.isInfoEnabled()) {
	                         log.info(format(future.channel(), "JOIN {}"), multicastAddress);
	                     }
	                 });
}
 
Example #6
Source File: UdpOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Leave a multicast group.
 *
 * @param multicastAddress multicast address of the group to leave
 *
 * @return a {@link Publisher} that will be complete when the group has been left
 */
@Override
public Mono<Void> leave(final InetAddress multicastAddress, @Nullable NetworkInterface iface) {
	if (null == iface && null != datagramChannel.config().getNetworkInterface()) {
		iface = datagramChannel.config().getNetworkInterface();
	}

	final ChannelFuture future;
	if (null != iface) {
		future = datagramChannel.leaveGroup(new InetSocketAddress(multicastAddress,
				datagramChannel.localAddress()
				               .getPort()), iface);
	}
	else {
		future = datagramChannel.leaveGroup(multicastAddress);
	}

	return FutureMono.from(future)
	                 .doOnSuccess(v -> {
	                     if (log.isInfoEnabled()) {
	                         log.info(format(future.channel(), "JOIN {}"), multicastAddress);
	                     }
	                 });
}
 
Example #7
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<?> receiveObject() {
	// Handle the 'Expect: 100-continue' header if necessary.
	// TODO: Respond with 413 Request Entity Too Large
	//   and discard the traffic or close the connection.
	//       No need to notify the upstream handlers - just log.
	//       If decoding a response, just throw an error.
	if (HttpUtil.is100ContinueExpected(nettyRequest)) {
		return FutureMono.deferFuture(() -> {
					if(!hasSentHeaders()) {
						return channel().writeAndFlush(CONTINUE);
					}
					return channel().newSucceededFuture();
				})

		                 .thenMany(super.receiveObject());
	}
	else {
		return super.receiveObject();
	}
}
 
Example #8
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Mono<Void> sendClose(CloseWebSocketFrame frame) {
	if (CLOSE_SENT.get(this) == 0) {
		//commented for now as we assume the close is always scheduled (deferFuture runs)
		//onTerminate().subscribe(null, null, () -> ReactorNetty.safeRelease(frame));
		return FutureMono.deferFuture(() -> {
			if (CLOSE_SENT.getAndSet(this, 1) == 0) {
				discard();
				onCloseState.onNext(new WebSocketCloseStatus(frame.statusCode(), frame.reasonText()));
				return channel().writeAndFlush(frame)
				                .addListener(ChannelFutureListener.CLOSE);
			}
			frame.release();
			return channel().newSucceededFuture();
		}).doOnCancel(() -> ReactorNetty.safeRelease(frame));
	}
	frame.release();
	return Mono.empty();
}
 
Example #9
Source File: HttpOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound sendObject(Object message) {
	if (!channel().isActive()) {
		ReactorNetty.safeRelease(message);
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (!(message instanceof ByteBuf)) {
		return super.sendObject(message);
	}
	ByteBuf b = (ByteBuf) message;
	return new PostHeadersNettyOutbound(FutureMono.deferFuture(() -> {
		if (markSentHeaderAndBody(b)) {
			try {
				afterMarkSentHeaders();
			}
			catch (RuntimeException e) {
				b.release();
				throw e;
			}
			if (HttpUtil.getContentLength(outboundHttpMessage(), -1) == 0) {
				log.debug(format(channel(), "Dropped HTTP content, " +
						"since response has Content-Length: 0 {}"), toPrettyHexDump(b));
				b.release();
				return channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER));
			}
			return channel().writeAndFlush(newFullBodyMessage(b));
		}
		return channel().writeAndFlush(b);
	}), this, b);
}
 
Example #10
Source File: HttpOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public NettyOutbound send(Publisher<? extends ByteBuf> source) {
	if (!channel().isActive()) {
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (source instanceof Mono) {
		return new PostHeadersNettyOutbound(((Mono<ByteBuf>)source)
				.flatMap(msg -> {
					if (markSentHeaderAndBody(msg)) {
						try {
							afterMarkSentHeaders();
						}
						catch (RuntimeException e) {
							ReferenceCountUtil.release(msg);
							return Mono.error(e);
						}
						if (HttpUtil.getContentLength(outboundHttpMessage(), -1) == 0) {
							log.debug(format(channel(), "Dropped HTTP content, " +
									"since response has Content-Length: 0 {}"), toPrettyHexDump(msg));
							msg.release();
							return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER)));
						}
						return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(msg)));
					}
					return FutureMono.from(channel().writeAndFlush(msg));
				})
				.doOnDiscard(ByteBuf.class, ByteBuf::release), this, null);
	}
	return super.send(source);
}
 
Example #11
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> send() {
	if (markSentHeaderAndBody()) {
		HttpMessage response = newFullBodyMessage(EMPTY_BUFFER);
		return FutureMono.deferFuture(() -> channel().writeAndFlush(response));
	}
	else {
		return Mono.empty();
	}
}
 
Example #12
Source File: ReactorNettyTcpClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<Void> shutdown() {
	if (this.stopping) {
		SettableListenableFuture<Void> future = new SettableListenableFuture<>();
		future.set(null);
		return future;
	}

	this.stopping = true;

	Mono<Void> result;
	if (this.channelGroup != null) {
		result = FutureMono.from(this.channelGroup.close());
		if (this.loopResources != null) {
			result = result.onErrorResume(ex -> Mono.empty()).then(this.loopResources.disposeLater());
		}
		if (this.poolResources != null) {
			result = result.onErrorResume(ex -> Mono.empty()).then(this.poolResources.disposeLater());
		}
		result = result.onErrorResume(ex -> Mono.empty()).then(stopScheduler());
	}
	else {
		result = stopScheduler();
	}

	return new MonoToListenableFutureAdapter<>(result);
}
 
Example #13
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
final Mono<Void> send() {
	if (!channel().isActive()) {
		return Mono.error(AbortedException.beforeSend());
	}
	if (markSentHeaderAndBody()) {
		HttpMessage request = newFullBodyMessage(Unpooled.EMPTY_BUFFER);
		return FutureMono.deferFuture(() -> channel().writeAndFlush(request));
	}
	else {
		return Mono.empty();
	}
}
 
Example #14
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testChannelGroupClosesAllConnections() throws Exception {
	MonoProcessor<Void> serverConnDisposed = MonoProcessor.create();

	ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor());

	CountDownLatch latch = new CountDownLatch(1);

	DisposableServer boundServer =
			TcpServer.create()
			         .port(0)
			         .doOnConnection(c -> {
			             c.onDispose()
			              .subscribe(serverConnDisposed);
			             group.add(c.channel());
			             latch.countDown();
			         })
			         .wiretap(true)
			         .bindNow();

	TcpClient.create()
	         .remoteAddress(boundServer::address)
	         .wiretap(true)
	         .connect()
	         .subscribe();

	assertTrue(latch.await(30, TimeUnit.SECONDS));

	boundServer.disposeNow();

	FutureMono.from(group.close())
	          .block(Duration.ofSeconds(30));

	serverConnDisposed.block(Duration.ofSeconds(5));
}
 
Example #15
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public <S> NettyOutbound sendUsing(Callable<? extends S> sourceInput,
		BiFunction<? super Connection, ? super S, ?> mappedInput,
		Consumer<? super S> sourceCleanup) {
	Objects.requireNonNull(sourceInput, "sourceInput");
	Objects.requireNonNull(mappedInput, "mappedInput");
	Objects.requireNonNull(sourceCleanup, "sourceCleanup");

	return then(Mono.using(
			sourceInput,
			s -> FutureMono.from(connection.channel()
			                               .writeAndFlush(mappedInput.apply(this, s))),
			sourceCleanup)
	);
}
 
Example #16
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound sendObject(Object message) {
	if (!channel().isActive()) {
		ReactorNetty.safeRelease(message);
		return then(Mono.error(AbortedException.beforeSend()));
	}
	return then(FutureMono.deferFuture(() -> connection.channel()
	                                                   .writeAndFlush(message)),
			() -> ReactorNetty.safeRelease(message));
}
 
Example #17
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound sendObject(Publisher<?> dataStream, Predicate<Object> predicate) {
	if (!channel().isActive()) {
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (dataStream instanceof Mono) {
		return then(((Mono<?>)dataStream).flatMap(m -> FutureMono.from(channel().writeAndFlush(m)))
		                                 .doOnDiscard(ReferenceCounted.class, ReferenceCounted::release));
	}
	return then(MonoSendMany.objectSource(dataStream, channel(), predicate));
}
 
Example #18
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound send(Publisher<? extends ByteBuf> dataStream, Predicate<ByteBuf> predicate) {
	if (!channel().isActive()) {
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (dataStream instanceof Mono) {
		return then(((Mono<?>)dataStream).flatMap(m -> FutureMono.from(channel().writeAndFlush(m)))
		                                 .doOnDiscard(ByteBuf.class, ByteBuf::release));
	}
	return then(MonoSendMany.byteBufSource(dataStream, channel(), predicate));
}
 
Example #19
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionCloseOnServerError() {
	Flux<String> content =
			Flux.range(1, 3)
			    .doOnNext(i -> {
			        if (i == 3) {
			            throw new RuntimeException("test");
			        }
			    })
			    .map(i -> "foo " + i);

	disposableServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, res) -> res.sendString(content))
			          .bindNow();

	AtomicReference<Channel> ch = new AtomicReference<>();
	Flux<ByteBuf> r =
			HttpClient.create()
			          .doOnResponse((res, c) -> ch.set(c.channel()))
			          .port(disposableServer.port())
			          .get()
			          .uri("/")
			          .responseContent();

	StepVerifier.create(r)
	            .expectNextCount(2)
	            .expectError(IOException.class)
	            .verify(Duration.ofSeconds(30));

	FutureMono.from(ch.get().closeFuture()).block(Duration.ofSeconds(30));
}
 
Example #20
Source File: ReactorNettyTcpClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<Void> shutdown() {
	if (this.stopping) {
		SettableListenableFuture<Void> future = new SettableListenableFuture<>();
		future.set(null);
		return future;
	}

	this.stopping = true;

	Mono<Void> result;
	if (this.channelGroup != null) {
		result = FutureMono.from(this.channelGroup.close());
		if (this.loopResources != null) {
			result = result.onErrorResume(ex -> Mono.empty()).then(this.loopResources.disposeLater());
		}
		if (this.poolResources != null) {
			result = result.onErrorResume(ex -> Mono.empty()).then(this.poolResources.disposeLater());
		}
		result = result.onErrorResume(ex -> Mono.empty()).then(stopScheduler());
	}
	else {
		result = stopScheduler();
	}

	return new MonoToListenableFutureAdapter<>(result);
}
 
Example #21
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue688() throws Exception {
	CountDownLatch connected = new CountDownLatch(1);
	CountDownLatch configured = new CountDownLatch(1);
	CountDownLatch disconnected = new CountDownLatch(1);

	ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor());

	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .childObserve((connection, newState) -> {
			             if (newState == ConnectionObserver.State.CONNECTED) {
			                 group.add(connection.channel());
			                 connected.countDown();
			             }
			             else if (newState == ConnectionObserver.State.CONFIGURED) {
			                 configured.countDown();
			             }
			             else if (newState == ConnectionObserver.State.DISCONNECTING) {
			                 disconnected.countDown();
			             }
			         })
			         .wiretap(true)
			         .bindNow();

	TcpClient.create()
	         .remoteAddress(server::address)
	         .wiretap(true)
	         .connect()
	         .subscribe();

	assertTrue(connected.await(30, TimeUnit.SECONDS));

	assertTrue(configured.await(30, TimeUnit.SECONDS));

	FutureMono.from(group.close())
	          .block(Duration.ofSeconds(30));

	assertTrue(disconnected.await(30, TimeUnit.SECONDS));

	server.disposeNow();
}
 
Example #22
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testChannelGroupClosesAllConnections() throws Exception {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .route(r -> r.get("/never",
			                  (req, res) -> res.sendString(Mono.never()))
			              .get("/delay10",
			                  (req, res) -> res.sendString(Mono.just("test")
			                                                   .delayElement(Duration.ofSeconds(10))))
			              .get("/delay1",
			                  (req, res) -> res.sendString(Mono.just("test")
			                                                   .delayElement(Duration.ofSeconds(1)))))
			          .wiretap(true)
			          .bindNow(Duration.ofSeconds(30));

	ConnectionProvider connectionProvider =
			ConnectionProvider.create("testChannelGroupClosesAllConnections", Integer.MAX_VALUE);

	ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor());

	CountDownLatch latch1 = new CountDownLatch(3);
	CountDownLatch latch2 = new CountDownLatch(3);

	HttpClient client = createHttpClientForContextWithAddress(connectionProvider);

	Flux.just("/never", "/delay10", "/delay1")
	    .flatMap(s ->
	            client.doOnConnected(c -> {
	                          c.onDispose()
	                           .subscribe(null, null, latch2::countDown);
	                          group.add(c.channel());
	                          latch1.countDown();
	                      })
	                  .get()
	                  .uri(s)
	                  .responseContent()
	                  .aggregate()
	                  .asString())
	    .subscribe();

	assertThat(latch1.await(30, TimeUnit.SECONDS)).isTrue();

	Mono.whenDelayError(FutureMono.from(group.close()), connectionProvider.disposeLater())
	    .block(Duration.ofSeconds(30));

	assertThat(latch2.await(30, TimeUnit.SECONDS)).isTrue();
}
 
Example #23
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
void _subscribe(CoreSubscriber<? super Void> s) {
	HttpDataFactory df = DEFAULT_FACTORY;

	try {
		HttpClientFormEncoder encoder = new HttpClientFormEncoder(df,
				parent.nettyRequest,
				false,
				HttpConstants.DEFAULT_CHARSET,
				HttpPostRequestEncoder.EncoderMode.RFC1738);

		formCallback.accept(parent, encoder);

		encoder = encoder.applyChanges(parent.nettyRequest);
		df = encoder.newFactory;

		if (!encoder.isMultipart()) {
			parent.requestHeaders.remove(HttpHeaderNames.TRANSFER_ENCODING);
		}

		// Returned value is deliberately ignored
		parent.addHandlerFirst(NettyPipeline.ChunkedWriter, new ChunkedWriteHandler());

		boolean chunked = HttpUtil.isTransferEncodingChunked(parent.nettyRequest);

		HttpRequest r = encoder.finalizeRequest();

		if (!chunked) {
			HttpUtil.setTransferEncodingChunked(r, false);
			HttpUtil.setContentLength(r, encoder.length());
		}

		ChannelFuture f = parent.channel()
		                        .writeAndFlush(r);

		Flux<Long> tail = encoder.progressFlux.onBackpressureLatest();

		if (encoder.cleanOnTerminate) {
			tail = tail.doOnCancel(encoder)
			           .doAfterTerminate(encoder);
		}

		if (encoder.isChunked()) {
			if (progressCallback != null) {
				progressCallback.accept(tail);
			}
			//"FutureReturnValueIgnored" this is deliberate
			parent.channel()
			      .writeAndFlush(encoder);
		}
		else {
			if (progressCallback != null) {
				progressCallback.accept(FutureMono.from(f)
				                                  .cast(Long.class)
				                                  .switchIfEmpty(Mono.just(encoder.length()))
				                                  .flux());
			}
		}
		s.onComplete();


	}
	catch (Throwable e) {
		Exceptions.throwIfJvmFatal(e);
		df.cleanRequestHttpData(parent.nettyRequest);
		s.onError(Exceptions.unwrap(e));
	}
}
 
Example #24
Source File: HttpOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> then() {
	if (!channel().isActive()) {
		return Mono.error(AbortedException.beforeSend());
	}

	if (hasSentHeaders()) {
		return Mono.empty();
	}

	return FutureMono.deferFuture(() -> {
		if (markSentHeaders(outboundHttpMessage())) {
			HttpMessage msg;

			if (HttpUtil.isContentLengthSet(outboundHttpMessage())) {
				outboundHttpMessage().headers()
						.remove(HttpHeaderNames.TRANSFER_ENCODING);
				if (HttpUtil.getContentLength(outboundHttpMessage(), 0) == 0) {
					markSentBody();
					msg = newFullBodyMessage(Unpooled.EMPTY_BUFFER);
				}
				else {
					msg = outboundHttpMessage();
				}
			}
			else {
				msg = outboundHttpMessage();
			}

			try {
				afterMarkSentHeaders();
			}
			catch (RuntimeException e) {
				ReferenceCountUtil.release(msg);
				throw e;
			}

			return channel().writeAndFlush(msg);
		}
		else {
			return channel().newSucceededFuture();
		}
	});
}
 
Example #25
Source File: HttpClientOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public NettyOutbound send(Publisher<? extends ByteBuf> source) {
	if (!channel().isActive()) {
		return then(Mono.error(AbortedException.beforeSend()));
	}
	if (source instanceof Mono) {
		return super.send(source);
	}
	if ((Objects.equals(method(), HttpMethod.GET) || Objects.equals(method(), HttpMethod.HEAD))) {

		ByteBufAllocator alloc = channel().alloc();
		return new PostHeadersNettyOutbound(Flux.from(source)
		                .collectList()
		                .doOnDiscard(ByteBuf.class, ByteBuf::release)
		                .flatMap(list -> {
			                if (markSentHeaderAndBody(list.toArray())) {
				                if (list.isEmpty()) {
					                return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER)));
				                }

				                ByteBuf output;
				                int i = list.size();
				                if (i == 1) {
					                output = list.get(0);
				                }
				                else {
					                CompositeByteBuf agg = alloc.compositeBuffer(list.size());

					                for (ByteBuf component : list) {
						                agg.addComponent(true, component);
					                }

					                output = agg;
				                }

				                if (output.readableBytes() > 0) {
					                return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(output)));
				                }
				                output.release();
				                return FutureMono.from(channel().writeAndFlush(newFullBodyMessage(Unpooled.EMPTY_BUFFER)));
			                }
			                for (ByteBuf bb : list) {
			                	if (log.isDebugEnabled()) {
			                		log.debug(format(channel(), "Ignoring accumulated bytebuf on http GET {}"), ByteBufUtil.prettyHexDump(bb));
				                }
			                	bb.release();
			                }
			                return Mono.empty();
		                }), this, null);
	}

	return super.send(source);
}
 
Example #26
Source File: DefaultLoopResources.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> disposeLater(Duration quietPeriod, Duration timeout) {
	return Mono.defer(() -> {
		long quietPeriodMillis = quietPeriod.toMillis();
		long timeoutMillis = timeout.toMillis();

		EventLoopGroup serverLoopsGroup = serverLoops.get();
		EventLoopGroup clientLoopsGroup = clientLoops.get();
		EventLoopGroup serverSelectLoopsGroup = serverSelectLoops.get();
		EventLoopGroup cacheNativeClientGroup = cacheNativeClientLoops.get();
		EventLoopGroup cacheNativeSelectGroup = cacheNativeSelectLoops.get();
		EventLoopGroup cacheNativeServerGroup = cacheNativeServerLoops.get();

		Mono<?> clMono = Mono.empty();
		Mono<?> sslMono = Mono.empty();
		Mono<?> slMono = Mono.empty();
		Mono<?> cnclMono = Mono.empty();
		Mono<?> cnslMono = Mono.empty();
		Mono<?> cnsrvlMono = Mono.empty();
		if (running.compareAndSet(true, false)) {
			if (clientLoopsGroup != null) {
				clMono = FutureMono.from((Future) clientLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (serverSelectLoopsGroup != null) {
				sslMono = FutureMono.from((Future) serverSelectLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (serverLoopsGroup != null) {
				slMono = FutureMono.from((Future) serverLoopsGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeClientGroup != null) {
				cnclMono = FutureMono.from((Future) cacheNativeClientGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeSelectGroup != null) {
				cnslMono = FutureMono.from((Future) cacheNativeSelectGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
			if (cacheNativeServerGroup != null) {
				cnsrvlMono = FutureMono.from((Future) cacheNativeServerGroup.shutdownGracefully(
						quietPeriodMillis, timeoutMillis, TimeUnit.MILLISECONDS));
			}
		}

		return Mono.when(clMono, sslMono, slMono, cnclMono, cnslMono, cnsrvlMono);
	});
}
 
Example #27
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private Mono<Void> send(ClientMessage message) {
    logger.debug("Request: {}", message);
    return FutureMono.from(connection.channel().writeAndFlush(message));
}
 
Example #28
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> forceClose() {
    return FutureMono.deferFuture(() -> connection.channel().close());
}
 
Example #29
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private Mono<Void> send(ClientMessage message) {
    logger.debug("Request: {}", message);
    return FutureMono.from(connection.channel().writeAndFlush(message));
}
 
Example #30
Source File: ReactorNettyClient.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> forceClose() {
    return FutureMono.deferFuture(() -> connection.channel().close());
}