Java Code Examples for reactor.core.publisher.Signal#isOnNext()

The following examples show how to use reactor.core.publisher.Signal#isOnNext() . 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: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
/** Returns true if the requested amount was overflown by the given signal */
final boolean checkRequestOverflow(Signal<T> s) {
	long r = requested;
	if (!s.isOnNext()
			|| r < 0 || r == Long.MAX_VALUE //was Long.MAX from beginning or switched to unbounded
			|| (establishedFusionMode == Fuseable.ASYNC && r != 0L)
			|| r >= produced) {
		return false;
	}
	else {
		//not really an expectation failure so customize the message
		setFailurePrefix("request overflow (", s,
				"expected production of at most %s; produced: %s; request overflown by signal: %s", r, produced, s);
		return true;
	}
}
 
Example 2
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean onSignal(Signal<T> actualSignal) {
	SignalEvent<T> signalEvent = (SignalEvent<T>) this.script.poll();
	Optional<AssertionError> error = signalEvent.test(actualSignal);
	if (error.isPresent()) {
		Exceptions.addThrowable(ERRORS, this, error.get());
		// #55 ensure the onError is added as a suppressed to the AssertionError
		if(actualSignal.isOnError()) {
			error.get().addSuppressed(actualSignal.getThrowable());
		}
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	if (actualSignal.isOnNext()) {
		unasserted--;
	}
	return false;
}
 
Example 3
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean consumeWhile(Signal<T> actualSignal, SignalConsumeWhileEvent<T> whileEvent) {
	if (actualSignal.isOnNext()) {
		if (whileEvent.test(actualSignal.get())) {
			//the value matches, gobble it up
			unasserted--;
			if (this.logger != null) {
				logger.debug("{} consumed {}", whileEvent.getDescription(), actualSignal);
			}
			return true;
		}
	}
	if (this.logger != null) {
		logger.debug("{} stopped at {}", whileEvent.getDescription(), actualSignal);
	}
	//stop evaluating the predicate
	this.script.poll();
	return false;
}
 
Example 4
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
Optional<AssertionError> test(Signal<T> signal, Iterator<? extends T> iterator) {
	if (signal.isOnNext()) {
		if (!iterator.hasNext()) {
			return Optional.empty();
		}
		T d2 = iterator.next();
		if (!Objects.equals(signal.get(), d2)) {
			return messageFormatter.failOptional(this, "expected : onNext(%s); actual: %s; iterable: %s",
					d2,
					signal.get(),
					iterable);
		}
		return iterator.hasNext() ? EXPECT_MORE : Optional.empty();

	}
	if (iterator.hasNext() || signal.isOnError()) {
		return messageFormatter.failOptional(this, "expected next value: %s; actual signal: %s; iterable: %s",
				iterator.hasNext() ? iterator.next() : "none",
				signal, iterable);
	}
	return Optional.empty();
}
 
Example 5
Source File: EventBroker.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private <T> byte[] serializeSignal(
    Integer peerWatchId,
    EventSerializer.Serializer<T> eventSerializer,
    String eventName,
    ObjectSignal<T> objectSignal
)
{
    EventIdentifier eventIdentifier = new EventIdentifier(eventName, objectSignal.getObjectIdentifier());
    Signal<T> signal = objectSignal.getSignal();

    CommonSerializer.CommonSerializerBuilder builder = commonSerializer.onewayBuilder(ApiConsts.API_EVENT);
    if (signal.isOnNext())
    {
        builder
            .event(peerWatchId, eventIdentifier, InternalApiConsts.EVENT_STREAM_VALUE)
            .bytes(eventSerializer.writeEventValue(signal.get()));
    }
    else
    if (signal.isOnComplete())
    {
        builder.event(peerWatchId, eventIdentifier, InternalApiConsts.EVENT_STREAM_CLOSE_REMOVED);
    }
    else
    if (signal.isOnError() && signal.getThrowable() instanceof PeerNotConnectedException)
    {
        builder.event(peerWatchId, eventIdentifier, InternalApiConsts.EVENT_STREAM_CLOSE_NO_CONNECTION);
    }
    else
    {
        throw new ImplementationError("Unexpected event signal " + signal);
    }
    return builder.build();
}
 
Example 6
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
final Optional<AssertionError> checkCountMismatch(SignalCountEvent<T> event, Signal<T> s) {
	long expected = event.count;
	if (!s.isOnNext()) {
		return messageFormatter.failOptional(event, "expected: count = %s; actual: counted = %s; signal: %s",
				expected,
				unasserted, s);
	}
	else {
		return Optional.empty();
	}
}
 
Example 7
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
boolean onSignalSequence(Signal<T> actualSignal,
		SignalSequenceEvent<T> sequenceEvent) {
	Iterator<? extends T> currentNextAs = this.currentNextAs;
	if (currentNextAs == null) {
		currentNextAs = sequenceEvent.iterable.iterator();
		this.currentNextAs = currentNextAs;
	}

	Optional<AssertionError> error =
			sequenceEvent.test(actualSignal, currentNextAs);

	if (error == EXPECT_MORE) {
		if (actualSignal.isOnNext()) {
			unasserted--;
		}
		return false;
	}
	if (!error.isPresent()) {
		this.currentNextAs = null;
		this.script.poll();
		if (actualSignal.isOnNext()) {
			unasserted--;
		}
	}
	else {
		Exceptions.addThrowable(ERRORS, this, error.get());
		if(actualSignal.isOnError()) {
			// #55 ensure the onError is added as a suppressed to the AssertionError
			error.get().addSuppressed(actualSignal.getThrowable());
		}
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	return false;
}
 
Example 8
Source File: DefaultPooledConnectionProviderTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue673_TimeoutException() throws InterruptedException {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((in, out) -> out.sendString(Mono.just("test")
			                                                 .delayElement(Duration.ofMillis(100))))
			         .wiretap(true)
			         .bindNow();
	DefaultPooledConnectionProvider provider =
			(DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue673_TimeoutException")
			                                             .maxConnections(1)
			                                             .pendingAcquireMaxCount(4)
			                                             .pendingAcquireTimeout(Duration.ofMillis(10))
			                                             .build();
	CountDownLatch latch = new CountDownLatch(2);

	try {
		AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
		List<? extends Signal<? extends Connection>> list =
				Flux.range(0, 5)
				    .flatMapDelayError(i ->
				        TcpClient.create(provider)
				                 .port(server.port())
				                 .doOnConnected(conn -> {
				                     ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools =
				                         provider.channelPools;
				                     pool.set(pools.get(pools.keySet().toArray()[0]));
				                 })
				                 .doOnDisconnected(conn -> latch.countDown())
				                 .handle((in, out) -> in.receive().then())
				                 .wiretap(true)
				                 .connect()
				                 .materialize(),
				    256, 32)
				    .collectList()
				    .doFinally(fin -> latch.countDown())
				    .block(Duration.ofSeconds(30));

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

		assertThat(list).isNotNull()
				.hasSize(5);

		int onNext = 0;
		int onError = 0;
		String msg = "Pool#acquire(Duration) has been pending for more than the configured timeout of 10ms";
		for (int i = 0; i < 5; i++) {
			Signal<? extends Connection> signal = list.get(i);
			if (signal.isOnNext()) {
				onNext++;
			}
			else if (signal.getThrowable() instanceof TimeoutException &&
							 msg.equals(signal.getThrowable().getMessage())) {
				onError++;
			}
		}
		assertThat(onNext).isEqualTo(1);
		assertThat(onError).isEqualTo(4);

		assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
		assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
	}
	finally {
		server.disposeNow();
		provider.dispose();
	}
}
 
Example 9
Source File: DefaultPooledConnectionProviderTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue951_MaxPendingAcquire() throws InterruptedException {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((in, out) -> out.sendString(Mono.just("test")
			                                                 .delayElement(Duration.ofMillis(100))))
			         .wiretap(true)
			         .bindNow();
	DefaultPooledConnectionProvider provider =
			(DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue951_MaxPendingAcquire")
			                                             .maxConnections(1)
			                                             .pendingAcquireTimeout(Duration.ofMillis(20))
			                                             .pendingAcquireMaxCount(1)
			                                             .build();
	CountDownLatch latch = new CountDownLatch(2);

	try {
		AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
		List<? extends Signal<? extends Connection>> list =
				Flux.range(0, 3)
				    .flatMapDelayError(i ->
				        TcpClient.create(provider)
				                 .port(server.port())
				                 .doOnConnected(conn -> {
				                     ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools =
				                         provider.channelPools;
				                     pool.set(pools.get(pools.keySet().toArray()[0]));
				                 })
				                 .doOnDisconnected(conn -> latch.countDown())
				                 .handle((in, out) -> in.receive().then())
				                 .wiretap(true)
				                 .connect()
				                 .materialize(),
				    256, 32)
				    .collectList()
				    .doFinally(fin -> latch.countDown())
				    .block(Duration.ofSeconds(30));

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

		assertThat(list).isNotNull()
				.hasSize(3);

		int onNext = 0;
		int onErrorTimeout = 0;
		int onErrorPendingAcquire = 0;
		String msg1 = "Pool#acquire(Duration) has been pending for more than the configured timeout of 20ms";
		String msg2 = "Pending acquire queue has reached its maximum size of 1";
		for (int i = 0; i < 3; i++) {
			Signal<? extends Connection> signal = list.get(i);
			if (signal.isOnNext()) {
				onNext++;
			}
			else if (signal.getThrowable() instanceof TimeoutException &&
							 msg1.equals(signal.getThrowable().getMessage())) {
				onErrorTimeout++;
			}
			else if (signal.getThrowable() instanceof PoolAcquirePendingLimitException &&
							 msg2.equals(signal.getThrowable().getMessage())) {
				onErrorPendingAcquire++;
			}
		}
		assertThat(onNext).isEqualTo(1);
		assertThat(onErrorTimeout).isEqualTo(1);
		assertThat(onErrorPendingAcquire).isEqualTo(1);

		assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
		assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
	}
	finally {
		server.disposeNow();
		provider.dispose();
	}
}
 
Example 10
Source File: Http2Tests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
public void doTestMaxActiveStreams(HttpClient baseClient, int maxActiveStreams, int expectedOnNext, int expectedOnError) throws Exception {
	SelfSignedCertificate cert = new SelfSignedCertificate();
	SslContextBuilder serverCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey());
	SslContextBuilder clientCtx = SslContextBuilder.forClient()
	                                               .trustManager(InsecureTrustManagerFactory.INSTANCE);
	disposableServer =
			HttpServer.create()
			          .protocol(HttpProtocol.H2)
			          .secure(spec -> spec.sslContext(serverCtx))
			          .route(routes ->
			              routes.post("/echo", (req, res) -> res.send(req.receive()
			                                                             .aggregate()
			                                                             .retain()
			                                                             .delayElement(Duration.ofMillis(100)))))
			          .port(0)
			          .http2Settings(setting -> setting.maxConcurrentStreams(maxActiveStreams))
			          .wiretap(true)
			          .bindNow();

	HttpClient client =
			baseClient.port(disposableServer.port())
			          .protocol(HttpProtocol.H2)
			          .secure(spec -> spec.sslContext(clientCtx))
			          .wiretap(true);

	CountDownLatch latch = new CountDownLatch(1);
	List<? extends Signal<? extends String>> list =
			Flux.range(0, 2)
			    .flatMapDelayError(i ->
			            client.post()
			                  .uri("/echo")
			                  .send(ByteBufFlux.fromString(Mono.just("doTestMaxActiveStreams")))
			                  .responseContent()
			                  .aggregate()
			                  .asString()
			                  .materialize(),
			    256, 32)
			    .collectList()
			    .doFinally(fin -> latch.countDown())
			    .block(Duration.ofSeconds(30));

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

	assertThat(list).isNotNull().hasSize(2);

	int onNext = 0;
	int onError = 0;
	String msg = "Max active streams is reached";
	for (int i = 0; i < 2; i++) {
		Signal<? extends String> signal = list.get(i);
		if (signal.isOnNext()) {
			onNext++;
		}
		else if (signal.getThrowable() instanceof IOException &&
				signal.getThrowable().getMessage().contains(msg)) {
			onError++;
		}
	}

	assertThat(onNext).isEqualTo(expectedOnNext);
	assertThat(onError).isEqualTo(expectedOnError);
}
 
Example 11
Source File: ValueFormatters.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(Signal value) {
	return value.isOnNext() && value.hasValue();
}