reactor.util.function.Tuples Java Examples

The following examples show how to use reactor.util.function.Tuples. 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: Migration_2018_12_13_SnapshotNodeId.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private void markFailed(Connection connection, Collection<Tuple2<String, String>> failedSnapshotDefinitions)
    throws Exception
{
    ResultSet resultSet = connection.createStatement(
        ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE).executeQuery(SD_SELECT_ALL);
    while (resultSet.next())
    {
        String rscName = resultSet.getString(SD_RES_NAME);
        String snapshotName = resultSet.getString(SD_NAME);
        if (failedSnapshotDefinitions.contains(Tuples.of(rscName, snapshotName)))
        {
            resultSet.updateLong(SD_FLAGS,
                (resultSet.getLong(SD_FLAGS) & ~SD_FLAG_SUCCESSFUL) | SD_FLAG_FAILED_DEPLOYMENT
            );
            resultSet.updateRow();
        }
    }
    resultSet.close();
}
 
Example #2
Source File: FluxIndexTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void customBackpressured() {
	AtomicLong counter = new AtomicLong(4);

	StepVerifier.create(
			Flux.range(0, 1000)
			    .hide()
			    .index((i, v) -> Tuples.of("#" + (i + 1), v))
	, 0)
	            .expectNoFusionSupport()
	            .thenRequest(1)
	            .expectNext(Tuples.of("#1", 0))
	            .expectNoEvent(Duration.ofMillis(100))
	            .thenRequest(3)
	            .expectNext(Tuples.of("#2", 1))
	            .expectNext(Tuples.of("#3", 2))
	            .expectNext(Tuples.of("#4", 3))
	            .thenRequest(Long.MAX_VALUE)
	            .thenConsumeWhile(t -> t.getT1().equals("#" + (t.getT2() + 1)),
			            it -> counter.incrementAndGet())
	            .verifyComplete();

	assertThat(counter.get()).isEqualTo(1000);
}
 
Example #3
Source File: ParallelFluxNameTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanOperator() throws Exception {
	Tuple2<String, String> tag1 = Tuples.of("foo", "oof");
	Tuple2<String, String> tag2 = Tuples.of("bar", "rab");
	Set<Tuple2<String, String>> tags = new HashSet<>();
	tags.add(tag1);
	tags.add(tag2);

	ParallelFlux<Integer> source = Flux.range(1, 4).parallel(3);
	ParallelFluxName<Integer> test = new ParallelFluxName<>(source, "foo", tags);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
	assertThat(test.scan(Scannable.Attr.PREFETCH))
			.isEqualTo(256)
			.isEqualTo(source.getPrefetch());

	assertThat(test.scan(Scannable.Attr.NAME)).isEqualTo("foo");

	final Stream<Tuple2<String, String>> scannedTags = test.scan(Scannable.Attr.TAGS);
	assertThat(scannedTags).isNotNull();
	assertThat(scannedTags.iterator()).containsExactlyInAnyOrder(tag1, tag2);
}
 
Example #4
Source File: ReactiveNeo4jTemplate.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
private <T> Mono<Tuple2<T, DynamicLabels>> determineDynamicLabels(
	T entityToBeSaved, Neo4jPersistentEntity<?> entityMetaData, @Nullable String inDatabase
) {
	return entityMetaData.getDynamicLabelsProperty().map(p -> {

		PersistentPropertyAccessor propertyAccessor = entityMetaData.getPropertyAccessor(entityToBeSaved);
		ReactiveNeo4jClient.RunnableSpecTightToDatabase runnableQuery = neo4jClient
			.query(() -> renderer.render(cypherGenerator.createStatementReturningDynamicLabels(entityMetaData)))
			.in(inDatabase)
			.bind(propertyAccessor.getProperty(entityMetaData.getRequiredIdProperty())).to(NAME_OF_ID)
			.bind(entityMetaData.getStaticLabels()).to(NAME_OF_STATIC_LABELS_PARAM);

		if (entityMetaData.hasVersionProperty()) {
			runnableQuery = runnableQuery
				.bind((Long) propertyAccessor.getProperty(entityMetaData.getRequiredVersionProperty()) - 1)
				.to(NAME_OF_VERSION_PARAM);
		}

		return runnableQuery.fetch().one()
			.map(m -> (Collection<String>) m.get(NAME_OF_LABELS))
			.switchIfEmpty(Mono.just(Collections.emptyList()))
			.zipWith(Mono.just((Collection<String>) propertyAccessor.getProperty(p)))
			.map(t -> Tuples.of(entityToBeSaved, new DynamicLabels(t.getT1(), t.getT2())));
	}).orElse(Mono.just(Tuples.of(entityToBeSaved, DynamicLabels.EMPTY)));
}
 
Example #5
Source File: FluxIndexTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultConditional() {
	AtomicLong counter = new AtomicLong(2);
	StepVerifier.create(
			Flux.range(0, 1000)
			    .hide()
			    .index()
			    .filter(it -> true)
	)
	            .expectNoFusionSupport()
	            .expectNext(Tuples.of(0L, 0))
	            .expectNextMatches(t -> t.getT1() == t.getT2().longValue())
	            .thenConsumeWhile(t -> t.getT1() == t.getT2().longValue(),
			            it -> counter.incrementAndGet())
	            .expectComplete()
	            .verify();

	assertThat(counter.get()).isEqualTo(1000);
}
 
Example #6
Source File: HttpClientWithTomcatTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void postUpload() throws Exception {
	HttpClient client =
			HttpClient.create()
			          .host("localhost")
			          .port(getPort())
			          .wiretap(true);

	Tuple2<Integer, String> res;
	Path file = Paths.get(getClass().getResource("/smallFile.txt").toURI());
	try (InputStream f = Files.newInputStream(file)) {
		res = client.post()
		            .uri("/multipart")
		            .sendForm((req, form) -> form.multipart(true)
		                                         .file("test", f)
		                                         .attr("attr1", "attr2")
		                                         .file("test2", f))
		            .responseSingle((r, buf) -> buf.asString().map(s -> Tuples.of(r.status().code(), s)))
		            .block(Duration.ofSeconds(30));
	}

	assertThat(res).as("response").isNotNull();
	assertThat(res.getT1()).as("status code").isEqualTo(200);
	assertThat(res.getT2()).as("response body reflecting request").contains("test attr1 test2 ");
}
 
Example #7
Source File: FunctionDeployerTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Test
public void testBootAppWithMultipleInputOutput() {
	String[] args = new String[] {
			"--spring.cloud.function.location=target/it/bootapp-multi/target/bootapp-multi-1.0.0.RELEASE-exec.jar",
			"--spring.cloud.function.function-name=fn"
	};
	ApplicationContext context = SpringApplication.run(DeployerApplication.class, args);
	FunctionCatalog catalog = context.getBean(FunctionCatalog.class);

	Function<Tuple2<Flux<Message<byte[]>>, Flux<Message<byte[]>>>, Flux<Message<byte[]>>> multiInputFunction = catalog
			.lookup("fn", "application/json");

	Message<byte[]> carEventMessage = MessageBuilder.withPayload("{\"carEvent\":\"CAR IS BUILT\"}".getBytes()).build();
	Message<byte[]> checkoutEventMessage = MessageBuilder.withPayload("{\"checkoutEvent\":\"CAR IS CHECKED OUT\"}".getBytes()).build();
	Flux<Message<byte[]>> carEventStream = Flux.just(carEventMessage);
	Flux<Message<byte[]>> checkoutEventStream = Flux.just(checkoutEventMessage);

	Flux<Message<byte[]>> result = multiInputFunction.apply(Tuples.of(carEventStream, checkoutEventStream));

	byte[] resutBytes = result.blockFirst().getPayload();
	assertThat(resutBytes).isEqualTo("{\"orderEvent\":\"CartEvent: CAR IS BUILT- CheckoutEvent: CAR IS CHECKED OUT\"}".getBytes());
}
 
Example #8
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testReactorSubscribeOn() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
             .filter(x -> {
                print("Executing Filter");
                return x < 100;
            })
            .doOnNext(x -> print("Next value is  "+x))
            .doFinally(x -> print("Closing "))
            .subscribeOn(Schedulers.single())
            .subscribe(x -> print("Sub received : "+x));
    Thread.sleep(500);
}
 
Example #9
Source File: TimeoutTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testTimeout() throws  Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            throw new RuntimeException("Value out of bounds");
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    CountDownLatch countDownLatch = new CountDownLatch(1);
    fibonacciGenerator
            .delayElements(Duration.ofSeconds(1))
            .timeout(Duration.ofMillis(500))
            .subscribe(System.out::println, e -> {
                System.out.println(e);
                countDownLatch.countDown();
            });
    countDownLatch.await();
}
 
Example #10
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Test
void timeDuration() {
    Duration negativeOne = Duration.ofSeconds(-1);
    Duration negativeOneDay = Duration.ofSeconds(-TimeUnit.DAYS.toSeconds(1) - 1);
    Duration oneDayOneSecond = Duration.ofSeconds(TimeUnit.DAYS.toSeconds(1) + 1);
    LocalTime lastSecond = LocalTime.of(23, 59, 59);
    LocalTime firstSecond = LocalTime.of(0, 0, 1);

    List<Tuple2<Duration, LocalTime>> dataCases = Arrays.asList(
        Tuples.of(negativeOne, lastSecond),
        Tuples.of(negativeOneDay, lastSecond),
        Tuples.of(oneDayOneSecond, firstSecond)
    );
    String tdl = "CREATE TEMPORARY TABLE test(id INT PRIMARY KEY AUTO_INCREMENT,value TIME)";
    complete(connection -> Mono.from(connection.createStatement(tdl).execute())
        .flatMap(IntegrationTestSupport::extractRowsUpdated)
        .thenMany(Flux.fromIterable(dataCases)
            .concatMap(pair -> testTimeDuration(connection, pair.getT1(), pair.getT2()))));
}
 
Example #11
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testFibonacci() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                System.out.println("generated " + state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    List<Long> fibonacciSeries = new LinkedList<>();
    int size = 50;
    fibonacciGenerator.take(size).subscribe(t -> {
        System.out.println("consuming " + t);
        fibonacciSeries.add(t);
    });
    System.out.println(fibonacciSeries);
    assertEquals(7778742049L, fibonacciSeries.get(size - 1).longValue());
}
 
Example #12
Source File: FluxNameTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanOperator() throws Exception {
	Tuple2<String, String> tag1 = Tuples.of("foo", "oof");
	Tuple2<String, String> tag2 = Tuples.of("bar", "rab");
	Set<Tuple2<String, String>> tags = new HashSet<>();
	tags.add(tag1);
	tags.add(tag2);

	Flux<Integer> source = Flux.range(1, 4).map(i -> i);
	FluxName<Integer> test = new FluxName<>(source, "foo", tags);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
	assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(-1);

	assertThat(test.scan(Scannable.Attr.NAME)).isEqualTo("foo");

	final Stream<Tuple2<String, String>> scannedTags = test.scan(Scannable.Attr.TAGS);
	assertThat(scannedTags).isNotNull();
	assertThat(scannedTags.iterator()).containsExactlyInAnyOrder(tag1, tag2);
}
 
Example #13
Source File: MonoDoOnEachTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void nextComplete() {
	List<Tuple2<Signal, Context>> signalsAndContext = new ArrayList<>();
	Mono.just(1)
	    .hide()
	    .doOnEach(s -> signalsAndContext.add(Tuples.of(s, s.getContext())))
	    .subscriberContext(Context.of("foo", "bar"))
	    .subscribe();

	assertThat(signalsAndContext)
			.hasSize(2)
			.allSatisfy(t2 -> {
				assertThat(t2.getT1())
						.isNotNull();
				assertThat(t2.getT2().getOrDefault("foo", "baz"))
						.isEqualTo("bar");
			});

	assertThat(signalsAndContext.stream().map(t2 -> t2.getT1().getType()))
			.containsExactly(SignalType.ON_NEXT, SignalType.ON_COMPLETE);
}
 
Example #14
Source File: FluxIndexTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultBackpressured() {
	AtomicLong counter = new AtomicLong(4);

	StepVerifier.create(
			Flux.range(0, 1000)
			    .hide()
				.index()
	, 0)
	            .expectNoFusionSupport()
	            .thenRequest(1)
	            .expectNext(Tuples.of(0L, 0))
	            .expectNoEvent(Duration.ofMillis(100))
	            .thenRequest(3)
	            .expectNext(Tuples.of(1L, 1))
	            .expectNext(Tuples.of(2L, 2))
	            .expectNext(Tuples.of(3L, 3))
	            .thenRequest(Long.MAX_VALUE)
	            .thenConsumeWhile(t -> t.getT1() == t.getT2().longValue(),
			            it -> counter.incrementAndGet())
	            .verifyComplete();

	assertThat(counter.get()).isEqualTo(1000);
}
 
Example #15
Source File: GatewayRSocketTests.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
	routingTable = mock(RoutingTable.class);

	this.metadataExtractor.metadataToExtract(FORWARDING_MIME_TYPE, Forwarding.class,
			"forwarding");

	MetadataEncoder encoder = new MetadataEncoder(Metadata.COMPOSITE_MIME_TYPE,
			this.rSocketStrategies);
	Forwarding metadata = Forwarding.of(1).with(WellKnownKey.SERVICE_NAME, "mock")
			.build();
	DataBuffer dataBuffer = encoder.metadata(metadata, FORWARDING_MIME_TYPE).encode();
	DataBuffer data = MetadataEncoder.emptyDataBuffer(rSocketStrategies);
	incomingPayload = PayloadUtils.createPayload(data, dataBuffer);

	RSocket rSocket = mock(RSocket.class);
	Tuple2<String, RSocket> tuple = Tuples.of("1111", rSocket);
	when(routingTable.findRSockets(any(TagsMetadata.class)))
			.thenReturn(Collections.singletonList(tuple));

	when(rSocket.requestResponse(any(Payload.class)))
			.thenReturn(Mono.just(DefaultPayload.create("response")));
}
 
Example #16
Source File: LeaderInSyncByPartitionFunction.java    From data-highway with Apache License 2.0 6 votes vote down vote up
public Map<TopicPartition, LeaderInSync> apply(int brokerId, Collection<String> topics) {
  return Mono
      .fromSupplier(() -> client.describeTopics(topics).all())
      .map(KafkaFutures::join)
      .flatMapIterable(Map::values)
      .flatMap(td -> Flux
          .fromIterable(td.partitions())
          .filter(tpi -> Flux.fromIterable(tpi.replicas()).any(n -> n.id() == brokerId).block())
          .map(tpi -> {
            TopicPartition partition = new TopicPartition(td.name(), tpi.partition());
            boolean leader = tpi.leader() == null ? false : tpi.leader().id() == brokerId;
            boolean inSync = Flux.fromIterable(tpi.isr()).any(n -> n.id() == brokerId).block();
            return Tuples.of(partition, new LeaderInSync(leader, inSync));
          }))
      .collectMap(Tuple2::getT1, Tuple2::getT2)
      .block();
}
 
Example #17
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testFibonacciRepeat() {
    Flux<Long> fibonacciGenerator = Flux.generate(
            () -> Tuples.<Long, Long>of(0L, 1L),
            (state, sink) -> {
                sink.next(state.getT1());
                return Tuples.of(state.getT2(), state.getT1() + state.getT2());
            });
    AtomicInteger integer = new AtomicInteger(0);
    fibonacciGenerator.take(10).repeat(() -> {
        return integer.getAndAdd(1) < 2;
    }).subscribe(t -> {
        System.out.println(t);
    });

}
 
Example #18
Source File: FreeCapacityFetcherProto.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private Flux<Tuple2<NodeName, ByteArrayInputStream>> assembleRequests(Set<NodeName> nodesFilter)
    throws AccessDeniedException
{
    Stream<Node> nodeStream = nodesFilter.isEmpty() ?
        nodeRepository.getMapForView(peerAccCtx.get()).values().stream() :
        nodesFilter.stream().map(nodeName -> ctrlApiDataLoader.loadNode(nodeName, true));

    Stream<Node> nodeWithThinStream = nodeStream.filter(this::hasThinPools);

    List<Tuple2<NodeName, Flux<ByteArrayInputStream>>> nameAndRequests = nodeWithThinStream
        .map(node -> Tuples.of(node.getName(), prepareFreeSpaceApiCall(node)))
        .collect(Collectors.toList());

    return Flux
        .fromIterable(nameAndRequests)
        .flatMap(nameAndRequest -> nameAndRequest.getT2()
            .map(byteStream -> Tuples.of(nameAndRequest.getT1(), byteStream))
        );
}
 
Example #19
Source File: FluxIndexedFuseableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultFused() {
	AtomicLong counter = new AtomicLong(2);
	StepVerifier.create(
			Flux.range(0, 1000)
			    .index()
	)
	            .expectFusion()
	            .expectNext(Tuples.of(0L, 0))
	            .expectNextMatches(t -> t.getT1() == t.getT2().longValue())
	            .thenConsumeWhile(t -> t.getT1() == t.getT2().longValue(),
			            it -> counter.incrementAndGet())
	            .expectComplete()
	            .verify();

	assertThat(counter.get()).isEqualTo(1000);
}
 
Example #20
Source File: WatchStoreImpl.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void addWatch(Watch watch, Disposable disposable)
    throws LinStorDataAlreadyExistsException
{
    Map<Integer, Tuple2<Watch, Disposable>> peerWatches = watchesByPeer.get(watch.getPeerId());
    if (peerWatches != null)
    {
        if (peerWatches.containsKey(watch.getPeerWatchId()))
        {
            throw new LinStorDataAlreadyExistsException("Watch with this ID already exists");
        }
    }

    String peerId = watch.getPeerId();
    Integer peerWatchId = watch.getPeerWatchId();
    if (peerId != null && peerWatchId != null)
    {
        watchesByPeer.computeIfAbsent(peerId, ignored -> new HashMap<>())
            .put(peerWatchId, Tuples.of(watch, disposable));
    }
}
 
Example #21
Source File: ReactorTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testExpectation() throws Exception {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        System.out.println("generating next of " + state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    StepVerifier.create(fibonacciGenerator.take(10))
            .expectNext(0L, 1L, 1L)
            .expectNextCount(7)
            .verifyComplete();

    // Expect error for validating errors
}
 
Example #22
Source File: QueryIntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Test
void timeDuration() {
    Duration negativeOne = Duration.ofSeconds(-1);
    Duration negativeOneDay = Duration.ofSeconds(-TimeUnit.DAYS.toSeconds(1) - 1);
    Duration oneDayOneSecond = Duration.ofSeconds(TimeUnit.DAYS.toSeconds(1) + 1);
    LocalTime lastSecond = LocalTime.of(23, 59, 59);
    LocalTime firstSecond = LocalTime.of(0, 0, 1);

    List<Tuple2<Duration, LocalTime>> dataCases = Arrays.asList(
        Tuples.of(negativeOne, lastSecond),
        Tuples.of(negativeOneDay, lastSecond),
        Tuples.of(oneDayOneSecond, firstSecond)
    );
    String tdl = "CREATE TEMPORARY TABLE test(id INT PRIMARY KEY AUTO_INCREMENT,value TIME)";
    complete(connection -> Mono.from(connection.createStatement(tdl).execute())
        .flatMap(IntegrationTestSupport::extractRowsUpdated)
        .thenMany(Flux.fromIterable(dataCases)
            .concatMap(pair -> testTimeDuration(connection, pair.getT1(), pair.getT2()))));
}
 
Example #23
Source File: R043_Zip.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void errorBreaksZip() throws Exception {
	//given
	final Flux<Integer> nums = Flux.just(1, 2, 3);
	final Flux<String> strs = Flux.concat(
			Flux.just("a", "b"),
			Flux.error(new RuntimeException("Opps"))
	);

	//when
	final Flux<Tuple2<Integer, String>> pairs = nums.zipWith(strs);

	//then
	pairs
			.as(StepVerifier::create)
			.expectNext(Tuples.of(1, "a"))
			.expectNext(Tuples.of(2, "b"))
			.verifyErrorMatches(e -> e.getMessage().equals("Opps"));
}
 
Example #24
Source File: FluxZipTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void pairWise3() {
	AtomicLong ref = new AtomicLong();
	Flux<Tuple2<Tuple2<Integer, String>, String>> f =
			Flux.zip(Flux.just(1), Flux.just("test"))
			    .zipWith(Flux.just("test2")
			                 .hide()
			                 .doOnRequest(ref::set), 1);

	Assert.assertTrue(f instanceof FluxZip);
	FluxZip<?, ?> s = (FluxZip<?, ?>) f;
	Assert.assertTrue(s.sources != null);
	Assert.assertTrue(s.sources.length == 2);

	Flux<Tuple2<Integer, String>> ff = f.map(t -> Tuples.of(t.getT1()
	                                                         .getT1(),
			t.getT1()
			 .getT2() + t.getT2()));

	ff.subscribeWith(AssertSubscriber.create())
	  .assertValues(Tuples.of(1, "testtest2"))
	  .assertComplete();
	Assert.assertTrue(ref.get() == 1);
}
 
Example #25
Source File: R043_Zip.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
/**
 * TODO Increase sleep at the end. You should see an exception after a while
 */
@Test
public void latest() throws Exception {
	//given
	final Flux<Long> fast = Flux.interval(Duration.ofMillis(100)).delayElements(Duration.ofMillis(1000));
	final Flux<Long> slow = Flux.interval(Duration.ofMillis(250));

	//when
	Flux.combineLatest(
			fast, slow,
			Tuples::of
	).subscribe(
			pair -> log.info("Got {}", pair)
	);

	//then
	TimeUnit.SECONDS.sleep(3);
}
 
Example #26
Source File: FibonacciConfigurer.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Bean
RouterFunction<ServerResponse> fibonacciEndpoint() {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.error(new RuntimeException("out of bound"));
        else
            sink.next(state.getT1());
        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });

    Flux<Long> delayedGenerator = fibonacciGenerator.delayElements(Duration.ofSeconds(1));

    RouterFunction<ServerResponse> fibonacciRoute =
            RouterFunctions.route(RequestPredicates.path("/fibonacci"),
                    request ->  ServerResponse.ok()
                                .body(fromPublisher(delayedGenerator, Long.class)));

    return fibonacciRoute;
}
 
Example #27
Source File: TimeoutTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testTimeout() throws  Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            throw new RuntimeException("Value out of bounds");
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    CountDownLatch countDownLatch = new CountDownLatch(1);
    fibonacciGenerator
            .delayElements(Duration.ofSeconds(1))
            .timeout(Duration.ofMillis(500))
            .subscribe(System.out::println, e -> {
                System.out.println(e);
                countDownLatch.countDown();
            });
    countDownLatch.await();
}
 
Example #28
Source File: MonoNameFuseableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanOperator() throws Exception {
	Tuple2<String, String> tag1 = Tuples.of("foo", "oof");
	Tuple2<String, String> tag2 = Tuples.of("bar", "rab");
	Set<Tuple2<String, String>> tags = new HashSet<>();
	tags.add(tag1);
	tags.add(tag2);

	Mono<Integer> source = Mono.just(1).map(i -> i);
	MonoNameFuseable<Integer> test = new MonoNameFuseable<>(source, "foo", tags);

	assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
	assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE);

	assertThat(test.scan(Scannable.Attr.NAME)).isEqualTo("foo");

	final Stream<Tuple2<String, String>> scannedTags = test.scan(Scannable.Attr.TAGS);
	assertThat(scannedTags).isNotNull();
	assertThat(scannedTags.iterator()).containsExactlyInAnyOrder(tag1, tag2);
}
 
Example #29
Source File: ErrorHandlingTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testUsingMethod() {
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    Closeable closable = () -> System.out.println("closing the stream");
    Flux.using(() -> closable, x -> fibonacciGenerator, e -> {
        try {
            e.close();
        } catch (Exception e1) {
            throw Exceptions.propagate(e1);
        }
    }).subscribe(System.out::println);
}
 
Example #30
Source File: SchedulerTest.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 6 votes vote down vote up
@Test
public void testParallelScheduler() throws Exception{
    Flux<Long> fibonacciGenerator = Flux.generate(() -> Tuples.<Long,
            Long>of(0L, 1L), (state, sink) -> {
        if (state.getT1() < 0)
            sink.complete();
        else
            sink.next(state.getT1());
        print("Generating next of "+ state.getT2());

        return Tuples.of(state.getT2(), state.getT1() + state.getT2());
    });
    fibonacciGenerator
            .filter(x -> {
                print("Executing Filter");
                return x < 100;
            }).delayElements(Duration.ZERO,Schedulers.parallel())
             .doOnNext(x -> print("Next value is  "+ x))
            .doFinally(x -> print("Closing "+x))
            .subscribe(x -> print("Sub received : "));
    Thread.sleep(500);
}