reactor.netty.Connection Java Examples

The following examples show how to use reactor.netty.Connection. 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: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void onUncaughtException(Connection connection, Throwable error) {
	if (doOnRedirect != null && error instanceof RedirectClientException) {
		doOnRedirect.accept(connection.as(HttpClientOperations.class), connection);
		return;
	}
	HttpClientOperations ops = connection.as(HttpClientOperations.class);
	if (ops == null) {
		return;
	}
	if (doOnRequestError != null && ops.retrying && ops.responseState == null) {
		doOnRequestError.accept(connection.as(HttpClientOperations.class), error);
		return;
	}
	if (doOnResponseError != null && (ops.responseState != null) && !(error instanceof RedirectClientException)) {
		doOnResponseError.accept(connection.as(HttpClientOperations.class), error);
	}
}
 
Example #2
Source File: DiscardClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	TcpClient client =
			TcpClient.create()
			         .port(PORT)
			         .wiretap(WIRETAP);

	if (SECURE) {
		client = client.secure(
				spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)));
	}

	Connection connection =
			client.handle((in, out) -> {
			          // Discards the incoming data and releases the buffers
			          in.receive().subscribe();
			          return out.sendString(Flux.interval(Duration.ofMillis(100))
			                                    .map(l -> l + ""));
			      })
			      .connectNow();

	connection.onDispose()
	          .block();
}
 
Example #3
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpClientWithInetSocketAddress() throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(1);

	TcpClient client =
			TcpClient.create().port(echoServerPort);

	Connection s = client.handle((in, out) -> {
		in.receive()
		  .subscribe(d -> latch.countDown());

		return out.sendString(Flux.just("Hello"))
		   .neverComplete();
	})
	                     .wiretap(true)
	                     .connectNow(Duration.ofSeconds(5));

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

	s.disposeNow();

	assertThat("latch was counted down", latch.getCount(), is(0L));
}
 
Example #4
Source File: HttpTrafficHandler.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
	Channel channel = ctx.channel();
	if (channel.isActive()) {
		if (ctx.pipeline().get(NettyPipeline.H2MultiplexHandler) == null) {
			// Proceed with HTTP/1.x as per configuration
			ctx.fireChannelActive();
		}
		else if (ctx.pipeline().get(NettyPipeline.SslHandler) == null) {
			// Proceed with H2C as per configuration
			sendNewState(Connection.from(channel), ConnectionObserver.State.CONNECTED);
			ctx.flush();
			ctx.read();
		}
		else {
			// Proceed with H2 as per configuration
			sendNewState(Connection.from(channel), ConnectionObserver.State.CONNECTED);
		}
	}
}
 
Example #5
Source File: ServerTransportConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onStateChange(Connection connection, State newState) {
	if (channelGroup != null && newState == State.CONNECTED) {
		channelGroup.add(connection.channel());
		return;
	}
	if (doOnConnection != null && newState == State.CONFIGURED) {
		try {
			doOnConnection.accept(connection);
		}
		catch (Throwable t) {
			log.error(format(connection.channel(), ""), t);
			//"FutureReturnValueIgnored" this is deliberate
			connection.channel().close();
		}
	}
}
 
Example #6
Source File: HttpClientBeanPostProcessorTest.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
void mapConnect_should_setup_reactor_context_currentTraceContext() {
	TracingMapConnect tracingMapConnect = new TracingMapConnect(() -> traceContext);

	Mono<Connection> original = Mono.just(connection)
			.handle(new BiConsumer<Connection, SynchronousSink<Connection>>() {
				@Override
				public void accept(Connection t, SynchronousSink<Connection> ctx) {
					assertThat(ctx.currentContext().get(TraceContext.class))
							.isSameAs(traceContext);
					assertThat(ctx.currentContext().get(PendingSpan.class))
							.isNotNull();
				}
			});

	// Wrap and run the assertions
	tracingMapConnect.apply(original).log().subscribe();
}
 
Example #7
Source File: WebsocketServerTransport.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<CloseableChannel> start(ConnectionAcceptor acceptor) {
  Objects.requireNonNull(acceptor, "acceptor must not be null");
  return server
      .handle(
          (request, response) -> {
            response.headers(headers);
            return response.sendWebsocket(
                (in, out) ->
                    acceptor
                        .apply(new WebsocketDuplexConnection((Connection) in))
                        .then(out.neverComplete()),
                specBuilder.build());
          })
      .bind()
      .map(CloseableChannel::new);
}
 
Example #8
Source File: ChannelOperationsHandler.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
final public void channelInactive(ChannelHandlerContext ctx) {
	try {
		Connection connection = Connection.from(ctx.channel());
		ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
		if (ops != null) {
			ops.onInboundClose();
		}
		else {
			listener.onStateChange(connection, ConnectionObserver.State.DISCONNECTING);
		}
	}
	catch (Throwable err) {
		exceptionCaught(ctx, err);
	}
}
 
Example #9
Source File: NewConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onStateChange(Connection connection, State newState) {
	if (log.isDebugEnabled()) {
		log.debug(format(connection.channel(), "onStateChange({}, {})"), newState, connection);
	}
	if (newState == State.CONFIGURED) {
		sink.success(connection);
	}
	else if (newState == State.DISCONNECTING && connection.channel()
	                                                      .isActive()) {
		//"FutureReturnValueIgnored" this is deliberate
		connection.channel()
		          .close();
	}
	obs.onStateChange(connection, newState);
}
 
Example #10
Source File: VoiceSocket.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
Mono<Connection> setup(String address, int port) {
    return Mono.deferWithContext(
            context -> udpClient.host(address).port(port)
                    .observe(getObserver(context))
                    .doOnConnected(c -> log.debug(format(context, "Connected to {}"), c.address()))
                    .doOnDisconnected(c -> log.debug(format(context, "Disconnected from {}"), c.address()))
                    .handle((in, out) -> {
                        Mono<Void> inboundThen = in.receive().retain()
                                .doOnNext(buf -> logPayload(receiverLog, context, buf))
                                .doOnNext(this.inboundSink::next)
                                .then();

                        Mono<Void> outboundThen = out.send(outbound
                                .doOnNext(buf -> logPayload(senderLog, context, buf)))
                                .then();

                        in.withConnection(c -> c.onDispose(() -> log.debug(format(context, "Connection disposed"))));

                        return Mono.zip(inboundThen, outboundThen).then();
                    })
                    .connect());
}
 
Example #11
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(HttpClientRequest req, Connection connection) {
	PendingSpan pendingSpan = req.currentContext().getOrDefault(PendingSpan.class,
			null);
	if (pendingSpan == null) {
		return; // Somehow TracingMapConnect was not invoked.. skip out
	}

	// All completion hooks clear this reference. If somehow this has a span upon
	// re-entry, the state model in reactor-netty has changed and we need to
	// update this code!
	Span span = pendingSpan.getAndSet(null);
	if (span != null) {
		assert false : "span exists when it shouldn't!";
		span.abandon(); // abandon instead of break
	}

	// Start a new client span with the appropriate parent
	TraceContext parent = req.currentContext().getOrDefault(TraceContext.class,
			null);
	HttpClientRequestWrapper request = new HttpClientRequestWrapper(req);

	span = handler().handleSendWithParent(request, parent);
	parseConnectionAddress(connection, span);
	pendingSpan.set(span);
}
 
Example #12
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpClient() throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(1);

	Connection client = TcpClient.create()
	                             .host("localhost")
	                             .port(echoServerPort)
	                             .handle((in, out) -> {
		                               in.receive()
		                                 .log("conn")
		                                 .subscribe(s -> latch.countDown());

		                               return out.sendString(Flux.just("Hello World!"))
		                                  .neverComplete();
	                               })
	                             .wiretap(true)
	                             .connectNow();

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

	client.disposeNow();

	assertThat("latch was counted down", latch.getCount(), is(0L));
}
 
Example #13
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void portBindingException() {
	Connection conn =
			UdpServer.create()
			         .port(0)
			         .bindNow(Duration.ofSeconds(30));

	try {
		UdpServer.create()
		         .bindAddress(conn::address)
		         .bindNow(Duration.ofSeconds(30));
		fail("illegal-success");
	}
	catch (ChannelBindException e) {
		assertEquals(e.localPort(), ((InetSocketAddress) conn.address()).getPort());
		e.printStackTrace();
	}

	conn.disposeNow();
}
 
Example #14
Source File: HttpClientConnect.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void onStateChange(Connection connection, State newState) {
	if (newState == HttpClientState.RESPONSE_RECEIVED) {
		sink.success(connection);
		return;
	}
	if ((newState == State.CONFIGURED || newState == STREAM_CONFIGURED) &&
				HttpClientOperations.class == connection.getClass()) {
		if (log.isDebugEnabled()) {
			log.debug(format(connection.channel(), "Handler is being applied: {}"), handler);
		}

		Mono.defer(() -> Mono.fromDirect(handler.requestWithBody((HttpClientOperations) connection)))
		    .subscribe(connection.disposeSubscriber());
	}
}
 
Example #15
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpClient1ThreadAcquire() {

	LoopResources resources = LoopResources.create("test", 1, true);


	Connection client = TcpClient.create()
	                             .host("localhost")
	                             .port(echoServerPort)
	                             .runOn(resources)
	                             .wiretap(true)
	                             .connectNow();

	client.disposeNow();
	resources.dispose();

	assertThat("client was configured", client instanceof ChannelOperations);
}
 
Example #16
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<? extends Connection> apply(Mono<? extends Connection> mono) {
	// This function is invoked once per-request. We keep a reference to the
	// pending client span here, so that only one signal completes the span.
	PendingSpan pendingSpan = new PendingSpan();
	return mono.subscriberContext(context -> {
		TraceContext invocationContext = currentTraceContext.get();
		if (invocationContext != null) {
			// Read in this processor and also in ScopePassingSpanSubscriber
			context = context.put(TraceContext.class, invocationContext);
		}
		return context.put(PendingSpan.class, pendingSpan);
	}).doOnCancel(() -> {
		// Check to see if Subscription.cancel() happened before another signal,
		// like onComplete() completed the span (clearing the reference).
		Span span = pendingSpan.getAndSet(null);
		if (span != null) {
			span.error(CANCELLED_ERROR);
			span.finish();
		}
	});
}
 
Example #17
Source File: PooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public final Mono<? extends Connection> acquire(
		TransportConfig config,
		ConnectionObserver connectionObserver,
		@Nullable Supplier<? extends SocketAddress> remote,
		@Nullable AddressResolverGroup<?> resolverGroup) {
	Objects.requireNonNull(remote, "remoteAddress");
	Objects.requireNonNull(resolverGroup, "resolverGroup");
	return Mono.create(sink -> {
		SocketAddress remoteAddress = Objects.requireNonNull(remote.get(), "Remote Address supplier returned null");
		PoolKey holder = new PoolKey(remoteAddress, config.channelHash());
		PoolFactory<T> poolFactory = poolFactory(remoteAddress);
		InstrumentedPool<T> pool = channelPools.computeIfAbsent(holder, poolKey -> {
			if (log.isDebugEnabled()) {
				log.debug("Creating a new [{}] client pool [{}] for [{}]", name, poolFactory, remoteAddress);
			}

			InstrumentedPool<T> newPool = createPool(config, poolFactory, remoteAddress, resolverGroup);

			if (poolFactory.metricsEnabled || config.metricsRecorder() != null) {
				PooledConnectionProviderMetrics.registerMetrics(name,
						poolKey.hashCode() + "",
						Metrics.formatSocketAddress(remoteAddress),
						newPool.metrics());
			}
			return newPool;
		});

		pool.acquire(Duration.ofMillis(poolFactory.pendingAcquireTimeout))
		    .subscribe(createDisposableAcquire(connectionObserver, config.channelOperationsProvider(),
		            poolFactory.pendingAcquireTimeout, pool, sink));
	});
}
 
Example #18
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected CoreSubscriber<PooledRef<Connection>> createDisposableAcquire(
		ConnectionObserver connectionObserver,
		ChannelOperations.OnSetup opsFactory,
		long pendingAcquireTimeout,
		InstrumentedPool<Connection> pool,
		MonoSink<Connection> sink) {
	return new DisposableAcquire(connectionObserver, opsFactory, pendingAcquireTimeout, pool, sink);
}
 
Example #19
Source File: Http2StreamBridgeServerHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	if (secured == null) {
		secured = ctx.channel().parent().pipeline().get(SslHandler.class) != null;
	}
	if (remoteAddress == null) {
		remoteAddress =
				Optional.ofNullable(HAProxyMessageReader.resolveRemoteAddressFromProxyProtocol(ctx.channel().parent()))
				        .orElse(ctx.channel().parent().remoteAddress());
	}
	if (msg instanceof HttpRequest) {
		HttpRequest request = (HttpRequest) msg;
		HttpServerOperations ops;
		try {
			ops = new HttpServerOperations(Connection.from(ctx.channel()),
					listener,
					null,
					request,
					ConnectionInfo.from(ctx.channel().parent(),
					                    readForwardHeaders,
					                    request,
					                    secured,
					                    remoteAddress),
					cookieEncoder,
					cookieDecoder);
		}
		catch (RuntimeException e) {
			HttpServerOperations.sendDecodingFailures(ctx, e, msg);
			return;
		}
		ops.bind();
		listener.onStateChange(ops, ConnectionObserver.State.CONFIGURED);
	}
	ctx.fireChannelRead(msg);
}
 
Example #20
Source File: FluxReceiveTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue1016() throws Exception {
	EmbeddedChannel channel = new EmbeddedChannel();

	Connection connection = Connection.from(channel);
	ConnectionObserver observer = (conn, newState) -> {
		if (newState == ConnectionObserver.State.DISCONNECTING) {
			if (conn.channel().isActive() && !conn.isPersistent()) {
				conn.dispose();
			}
		}
	};
	ChannelOperations<?, ?> ops = new ChannelOperations<>(connection, observer);
	ops.bind();

	ByteBuf buffer = channel.alloc().buffer();
	buffer.writeCharSequence("testIssue1016", Charset.defaultCharset());
	ops.inbound.onInboundNext(buffer);

	CountDownLatch latch = new CountDownLatch(1);
	// There is a subscriber, but there is no request for an item
	ops.receive().subscribe(new TestSubscriber(latch));

	ops.onInboundError(new OutOfMemoryError());

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

	assertThat(buffer.refCnt()).isEqualTo(0);
}
 
Example #21
Source File: TcpServer.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Connection c) {
	if (log.isDebugEnabled()) {
		log.debug(format(c.channel(), "Handler is being applied: {}"), handler);
	}
	Mono.fromDirect(handler.apply(c.inbound(), c.outbound()))
	    .subscribe(c.disposeSubscriber());
}
 
Example #22
Source File: DefaultPooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void onStateChange(Connection connection, State newState) {
	if (newState == State.CONFIGURED) {
		sink.success(connection);
	}
	obs.onStateChange(connection, newState);
}
 
Example #23
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void tcpClientHandlesLineFeedData() throws InterruptedException {
	final int messages = 100;
	final CountDownLatch latch = new CountDownLatch(messages);
	final List<String> strings = new ArrayList<>();

	Connection client =
			TcpClient.create()
			         .host("localhost")
			         .port(echoServerPort)
			         .doOnConnected(c -> c.addHandlerLast("codec",
					                                 new LineBasedFrameDecoder(8 * 1024)))
			         .handle((in, out) ->
				        out.sendString(Flux.range(1, messages)
				                            .map(i -> "Hello World!" + i + "\n")
				                            .subscribeOn(Schedulers.parallel()))
				            .then( in.receive()
				                     .asString()
				                     .take(100)
				                     .flatMapIterable(s -> Arrays.asList(s.split("\\n")))
				                     .doOnNext(s -> {
					                     strings.add(s);
					                     latch.countDown();
				                     }).then())
			         )
			         .wiretap(true)
			         .connectNow(Duration.ofSeconds(15));

	assertTrue("Expected messages not received. Received " + strings.size() + " messages: " + strings,
			latch.await(15, TimeUnit.SECONDS));

	assertEquals(messages, strings.size());
	client.disposeNow();
}
 
Example #24
Source File: ClientTransportConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
ClientTransportDoOn(@Nullable ChannelGroup channelGroup,
		@Nullable Consumer<? super Connection> doOnConnected,
		@Nullable Consumer<? super Connection> doOnDisconnected) {
	this.channelGroup = channelGroup;
	this.doOnConnected = doOnConnected;
	this.doOnDisconnected = doOnDisconnected;
}
 
Example #25
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testTcpServerWithDomainSockets() throws Exception {
	assumeTrue(LoopResources.hasNativeSupport());
	DisposableServer disposableServer =
			TcpServer.create()
			         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
			         .wiretap(true)
			         .handle((in, out) -> out.send(in.receive().retain()))
			         .bindNow();

	Connection conn =
			TcpClient.create()
			         .remoteAddress(disposableServer::address)
			         .wiretap(true)
			         .connectNow();

	conn.outbound()
	    .sendString(Flux.just("1", "2", "3"))
	    .then()
	    .subscribe();

	CountDownLatch latch = new CountDownLatch(1);
	conn.inbound()
	    .receive()
	    .asString()
	    .doOnNext(s -> {
	        if (s.endsWith("3")) {
	            latch.countDown();
	        }
	    })
	    .subscribe();

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

	conn.disposeNow();
	disposableServer.disposeNow();
}
 
Example #26
Source File: HttpClientConnect.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<? extends Connection> connect() {
	HttpClientConfig config = configuration();

	Mono<? extends Connection> mono;
	if (config.deferredConf != null) {
		return config.deferredConf.apply(Mono.just(config))
		           .flatMap(MonoHttpConnect::new);
	}
	else {
		mono = new MonoHttpConnect(config);
	}

	if (config.doOnConnect() != null) {
		mono = mono.doOnSubscribe(s -> config.doOnConnect().accept(config));
	}

	if (config.doOnRequestError != null) {
		mono = mono.onErrorResume(error ->
				Mono.subscriberContext()
				    .doOnNext(ctx -> config.doOnRequestError.accept(new FailedHttpClientRequest(ctx, config), error))
				    .then(Mono.error(error)));
	}

	if (config.connector != null) {
		mono = config.connector.apply(mono);
	}
	return mono;
}
 
Example #27
Source File: ChannelOperationsHandler.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
	// When AbstractNioChannel.AbstractNioUnsafe.finishConnect/fulfillConnectPromise,
	// fireChannelActive will be triggered regardless that the channel might be closed in the meantime
	if (ctx.channel().isActive()) {
		Connection c = Connection.from(ctx.channel());
		listener.onStateChange(c, ConnectionObserver.State.CONNECTED);
		ChannelOperations<?, ?> ops = opsFactory.create(c, listener, null);
		if (ops != null) {
			ops.bind();
			listener.onStateChange(ops, ConnectionObserver.State.CONFIGURED);
		}
	}
}
 
Example #28
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 #29
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public <T extends Connection> T as(Class<T> clazz) {
	if (clazz == ChannelOperations.class) {
		@SuppressWarnings("unchecked")
		T thiz = (T) this;
		return thiz;
	}
	return Connection.super.as(clazz);
}
 
Example #30
Source File: WebsocketDuplexConnection.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance
 *
 * @param connection the {@link Connection} to for managing the server
 */
public WebsocketDuplexConnection(Connection connection) {
  this.connection = Objects.requireNonNull(connection, "connection must not be null");

  connection
      .channel()
      .closeFuture()
      .addListener(
          future -> {
            if (!isDisposed()) dispose();
          });
}