reactor.netty.NettyOutbound Java Examples
The following examples show how to use
reactor.netty.NettyOutbound.
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: ReactorNettyTcpClient.java From spring-analysis-note with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) { inbound.withConnection(conn -> { if (logger.isDebugEnabled()) { logger.debug("Connected to " + conn.address()); } }); DirectProcessor<Void> completion = DirectProcessor.create(); TcpConnection<P> connection = new ReactorNettyTcpConnection<>(inbound, outbound, codec, completion); scheduler.schedule(() -> this.connectionHandler.afterConnected(connection)); inbound.withConnection(conn -> conn.addHandler(new StompMessageDecoder<>(codec))); inbound.receiveObject() .cast(Message.class) .publishOn(scheduler, PUBLISH_ON_BUFFER_SIZE) .subscribe( this.connectionHandler::handleMessage, this.connectionHandler::handleFailure, this.connectionHandler::afterConnectionClosed); return completion; }
Example #2
Source File: ReactorNettyTcpClient.java From java-technology-stack with MIT License | 6 votes |
@Override @SuppressWarnings("unchecked") public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) { inbound.withConnection(conn -> { if (logger.isDebugEnabled()) { logger.debug("Connected to " + conn.address()); } }); DirectProcessor<Void> completion = DirectProcessor.create(); TcpConnection<P> connection = new ReactorNettyTcpConnection<>(inbound, outbound, codec, completion); scheduler.schedule(() -> this.connectionHandler.afterConnected(connection)); inbound.withConnection(conn -> conn.addHandler(new StompMessageDecoder<>(codec))); inbound.receiveObject() .cast(Message.class) .publishOn(scheduler, PUBLISH_ON_BUFFER_SIZE) .subscribe( this.connectionHandler::handleMessage, this.connectionHandler::handleFailure, this.connectionHandler::afterConnectionClosed); return completion; }
Example #3
Source File: HttpOperations.java From reactor-netty with Apache License 2.0 | 6 votes |
@Override public final NettyOutbound sendFile(Path file, long position, long count) { Objects.requireNonNull(file); if (hasSentHeaders()) { return super.sendFile(file, position, count); } if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage()) && !HttpUtil.isContentLengthSet( outboundHttpMessage()) && count < Integer.MAX_VALUE) { outboundHttpMessage().headers() .setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count); } else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) { outboundHttpMessage().headers() .remove(HttpHeaderNames.CONTENT_LENGTH) .remove(HttpHeaderNames.TRANSFER_ENCODING); HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true); } return super.sendFile(file, position, count); }
Example #4
Source File: ReactorNettyTcpConnection.java From spring-analysis-note with MIT License | 5 votes |
public ReactorNettyTcpConnection(NettyInbound inbound, NettyOutbound outbound, ReactorNettyCodec<P> codec, DirectProcessor<Void> closeProcessor) { this.inbound = inbound; this.outbound = outbound; this.codec = codec; this.closeProcessor = closeProcessor; }
Example #5
Source File: HttpClientFinalizerSendInterceptor.java From skywalking with Apache License 2.0 | 5 votes |
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { EnhanceObjectCache enhanceObjectCache = (EnhanceObjectCache) objInst.getSkyWalkingDynamicField(); AbstractSpan span = ContextManager.activeSpan(); span.prepareForAsync(); if (!StringUtil.isEmpty(enhanceObjectCache.getUrl())) { URL url = new URL(enhanceObjectCache.getUrl()); ContextCarrier contextCarrier = new ContextCarrier(); AbstractSpan abstractSpan = ContextManager.createExitSpan( "SpringCloudGateway/sendRequest", contextCarrier, getPeer(url)); Tags.URL.set(abstractSpan, enhanceObjectCache.getUrl()); abstractSpan.prepareForAsync(); abstractSpan.setComponent(SPRING_CLOUD_GATEWAY); ContextManager.stopSpan(abstractSpan); ContextManager.stopSpan(span); BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> finalSender = (BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>>) allArguments[0]; allArguments[0] = new BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>>() { @Override public Publisher<Void> apply(HttpClientRequest request, NettyOutbound outbound) { Publisher publisher = finalSender.apply(request, outbound); CarrierItem next = contextCarrier.items(); while (next.hasNext()) { next = next.next(); request.requestHeaders().remove(next.getHeadKey()); request.requestHeaders().set(next.getHeadKey(), next.getHeadValue()); } return publisher; } }; enhanceObjectCache.setCacheSpan(abstractSpan); } enhanceObjectCache.setSpan1(span); }
Example #6
Source File: HttpSendFileTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private void assertSendFile(Function<HttpServerResponse, NettyOutbound> fn, boolean compression, int compressionSize, BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate, Consumer<String> bodyAssertion) { HttpServer server = HttpServer.create(); if (compressionPredicate != null) { server = server.compress(compressionPredicate); } if (compressionSize > -1) { server = server.compress(compressionSize); } DisposableServer context = customizeServerOptions(server) .handle((req, resp) -> fn.apply(resp)) .wiretap(true) .bindNow(); HttpClient client; if (compression) { client = HttpClient.create() .remoteAddress(context::address) .compress(true); } else { client = HttpClient.create() .remoteAddress(context::address); } Mono<String> response = customizeClientOptions(client) .wiretap(true) .get() .uri("/foo") .responseSingle((res, byteBufMono) -> byteBufMono.asString(StandardCharsets.UTF_8)); String body = response.block(Duration.ofSeconds(5)); context.disposeNow(); bodyAssertion.accept(body); }
Example #7
Source File: HttpSendFileTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private void assertSendFile(Function<HttpServerResponse, NettyOutbound> fn, boolean compression, int compressionSize, BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate) { assertSendFile(fn, compression, compressionSize, compressionPredicate, body -> assertThat(body).startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.") .contains("1024 mark here -><- 1024 mark here") .endsWith("End of File")); }
Example #8
Source File: HttpServerTests.java From reactor-netty with Apache License 2.0 | 5 votes |
private void doTestDropData( BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> serverFn, BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> clientFn) throws Exception { disposableServer = HttpServer.create() .port(0) .handle(serverFn) .wiretap(true) .bindNow(Duration.ofSeconds(30)); CountDownLatch latch = new CountDownLatch(1); String response = HttpClient.create() .port(disposableServer.port()) .wiretap(true) .doOnRequest((req, conn) -> conn.onTerminate() .subscribe(null, null, latch::countDown)) .request(HttpMethod.GET) .uri("/") .send(clientFn) .responseContent() .aggregate() .asString() .switchIfEmpty(Mono.just("Empty")) .block(Duration.ofSeconds(30)); assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(response).isEqualTo("Empty"); }
Example #9
Source File: HttpOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@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 |
@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 |
@Override public NettyOutbound sendFile(Path file) { try { return sendFile(file, 0L, Files.size(file)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(format(channel(), "Path not resolved"), e); } return then(sendNotFound()); } }
Example #12
Source File: HttpServerOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override public NettyOutbound sendHeaders() { if (hasSentHeaders()) { return this; } return then(Mono.empty()); }
Example #13
Source File: HttpClientFinalizer.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override public HttpClientFinalizer send( BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> sender) { Objects.requireNonNull(sender, "requestBody"); HttpClient dup = duplicate(); dup.configuration().body = sender; return (HttpClientFinalizer) dup; }
Example #14
Source File: TcpClient.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override public void accept(Connection c) { if (log.isDebugEnabled()) { log.debug(format(c.channel(), "Handler is being applied: {}"), handler); } Mono.fromDirect(handler.apply((NettyInbound) c, (NettyOutbound) c)) .subscribe(c.disposeSubscriber()); }
Example #15
Source File: ChannelOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@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 #16
Source File: ReactorClientHttpRequest.java From spring-analysis-note with MIT License | 5 votes |
public ReactorClientHttpRequest(HttpMethod method, URI uri, HttpClientRequest request, NettyOutbound outbound) { this.httpMethod = method; this.uri = uri; this.request = request; this.outbound = outbound; this.bufferFactory = new NettyDataBufferFactory(outbound.alloc()); }
Example #17
Source File: ReactorClientHttpRequest.java From java-technology-stack with MIT License | 5 votes |
public ReactorClientHttpRequest(HttpMethod method, URI uri, HttpClientRequest request, NettyOutbound outbound) { this.httpMethod = method; this.uri = uri; this.request = request; this.outbound = outbound; this.bufferFactory = new NettyDataBufferFactory(outbound.alloc()); }
Example #18
Source File: ChannelOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@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 #19
Source File: ChannelOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@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 #20
Source File: ChannelOperations.java From reactor-netty with Apache License 2.0 | 5 votes |
@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 #21
Source File: WebsocketOutbound.java From reactor-netty with Apache License 2.0 | 4 votes |
@Override default NettyOutbound sendString(Publisher<? extends String> dataStream, Charset charset) { return sendObject(Flux.from(dataStream) .map(stringToWebsocketFrame)); }
Example #22
Source File: ReactorClientHttpConnector.java From spring-analysis-note with MIT License | 4 votes |
private ReactorClientHttpRequest adaptRequest(HttpMethod method, URI uri, HttpClientRequest request, NettyOutbound nettyOutbound) { return new ReactorClientHttpRequest(method, uri, request, nettyOutbound); }
Example #23
Source File: ReactorNettyTcpConnection.java From java-technology-stack with MIT License | 4 votes |
public ReactorNettyTcpConnection(NettyInbound inbound, NettyOutbound outbound, ReactorNettyCodec<P> codec, DirectProcessor<Void> closeProcessor) { this.inbound = inbound; this.outbound = outbound; this.codec = codec; this.closeProcessor = closeProcessor; }
Example #24
Source File: HttpSendFileTests.java From reactor-netty with Apache License 2.0 | 4 votes |
private void assertSendFile(Function<HttpServerResponse, NettyOutbound> fn) { assertSendFile(fn, false, -1, (req, res) -> false); }
Example #25
Source File: TcpClientTests.java From reactor-netty with Apache License 2.0 | 4 votes |
@Test public void testIssue585_2() throws Exception { DisposableServer server = TcpServer.create() .port(0) .handle((req, res) -> res.send(req.receive() .retain())) .wiretap(true) .bindNow(); byte[] bytes = "test".getBytes(Charset.defaultCharset()); ByteBuf b1 = Unpooled.wrappedBuffer(bytes); ByteBuf b2 = Unpooled.wrappedBuffer(bytes); ByteBuf b3 = Unpooled.wrappedBuffer(bytes); WeakReference<ByteBuf> refCheck1 = new WeakReference<>(b1); WeakReference<ByteBuf> refCheck2 = new WeakReference<>(b2); WeakReference<ByteBuf> refCheck3 = new WeakReference<>(b3); Connection conn = TcpClient.create() .remoteAddress(server::address) .wiretap(true) .connectNow(); NettyOutbound out = conn.outbound(); out.sendObject(b1) .then() .block(Duration.ofSeconds(30)); Assertions.assertThat(b1.refCnt()).isEqualTo(0); b1 = null; checkReference(refCheck1); out.sendObject(b2) .then() .block(Duration.ofSeconds(30)); Assertions.assertThat(b2.refCnt()).isEqualTo(0); b2 = null; checkReference(refCheck2); out.sendObject(b3) .then() .block(Duration.ofSeconds(30)); Assertions.assertThat(b3.refCnt()).isEqualTo(0); b3 = null; checkReference(refCheck3); server.disposeNow(); conn.disposeNow(); }
Example #26
Source File: TcpClientTests.java From reactor-netty with Apache License 2.0 | 4 votes |
@Test public void testIssue585_1() throws Exception { DisposableServer server = TcpServer.create() .port(0) .handle((req, res) -> res.send(req.receive() .retain())) .wiretap(true) .bindNow(); CountDownLatch latch = new CountDownLatch(1); byte[] bytes = "test".getBytes(Charset.defaultCharset()); ByteBuf b1 = Unpooled.wrappedBuffer(bytes); ByteBuf b2 = Unpooled.wrappedBuffer(bytes); ByteBuf b3 = Unpooled.wrappedBuffer(bytes); WeakReference<ByteBuf> refCheck1 = new WeakReference<>(b1); WeakReference<ByteBuf> refCheck2 = new WeakReference<>(b2); WeakReference<ByteBuf> refCheck3 = new WeakReference<>(b3); Connection conn = TcpClient.create() .remoteAddress(server::address) .wiretap(true) .connectNow(); NettyOutbound out = conn.outbound(); Flux.concatDelayError( out.sendObject(Mono.error(new RuntimeException("test"))) .sendObject(b1) .then(), out.sendObject(Mono.error(new RuntimeException("test"))) .sendObject(b2) .then(), out.sendObject(Mono.error(new RuntimeException("test"))) .sendObject(b3) .then()) .doOnError(t -> latch.countDown()) .subscribe(conn.disposeSubscriber()); Assertions.assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); Assertions.assertThat(b1.refCnt()).isEqualTo(0); b1 = null; checkReference(refCheck1); Assertions.assertThat(b2.refCnt()).isEqualTo(0); b2 = null; checkReference(refCheck2); Assertions.assertThat(b3.refCnt()).isEqualTo(0); b3 = null; checkReference(refCheck3); server.disposeNow(); conn.disposeNow(); }
Example #27
Source File: TcpServerTests.java From reactor-netty with Apache License 2.0 | 4 votes |
private void assertSendFile(Function<NettyOutbound, NettyOutbound> fn) { DisposableServer context = TcpServer.create() .handle((in, out) -> in.receive() .asString() .flatMap(word -> "GOGOGO".equals(word) ? fn.apply(out).then() : out.sendString(Mono.just("NOPE")))) .wiretap(true) .bindNow(); assertNotNull(context); MonoProcessor<String> m1 = MonoProcessor.create(); MonoProcessor<String> m2 = MonoProcessor.create(); Connection client1 = TcpClient.create() .port(context.port()) .handle((in, out) -> { in.receive() .asString() .log("-----------------CLIENT1") .subscribe(m1::onNext); return out.sendString(Mono.just("gogogo")) .neverComplete(); }) .wiretap(true) .connectNow(); Connection client2 = TcpClient.create() .port(context.port()) .handle((in, out) -> { in.receive() .asString(StandardCharsets.UTF_8) .take(2) .reduceWith(String::new, String::concat) .log("-----------------CLIENT2") .subscribe(m2::onNext); return out.sendString(Mono.just("GOGOGO")) .neverComplete(); }) .wiretap(true) .connectNow(); assertNotNull(client2); String client1Response = m1.block(); String client2Response = m2.block(); client1.disposeNow(); client2.disposeNow(); context.disposeNow(); Assertions.assertThat(client1Response).isEqualTo("NOPE"); Assertions.assertThat(client2Response) .startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.") .contains("1024 mark here ->") .contains("<- 1024 mark here") .endsWith("End of File"); }
Example #28
Source File: TcpServerTests.java From reactor-netty with Apache License 2.0 | 4 votes |
@Test public void exposesNettyPipelineConfiguration() throws InterruptedException { final int port = SocketUtils.findAvailableTcpPort(); final CountDownLatch latch = new CountDownLatch(2); final TcpClient client = TcpClient.create().port(port); BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in, out) -> { in.receive() .asString() .subscribe(data -> { log.info("data " + data + " on " + in); latch.countDown(); }); return Flux.never(); }; TcpServer server = TcpServer.create() .doOnConnection(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(8 * 1024))) .port(port); DisposableServer connected = server.handle(serverHandler) .wiretap(true) .bindNow(); assertNotNull(connected); Connection clientContext = client.handle((in, out) -> out.sendString(Flux.just("Hello World!\n", "Hello 11!\n"))) .wiretap(true) .connectNow(); assertNotNull(clientContext); assertTrue("Latch was counted down", latch.await(10, TimeUnit.SECONDS)); connected.disposeNow(); clientContext.disposeNow(); }
Example #29
Source File: HttpOperations.java From reactor-netty with Apache License 2.0 | 4 votes |
@Override public <S> NettyOutbound sendUsing(Callable<? extends S> sourceInput, BiFunction<? super Connection, ? super S, ?> mappedInput, Consumer<? super S> sourceCleanup) { return parent.sendUsing(sourceInput, mappedInput, sourceCleanup); }
Example #30
Source File: HttpOperations.java From reactor-netty with Apache License 2.0 | 4 votes |
@Override public NettyOutbound sendObject(Object message) { return parent.sendObject(message); }