reactor.util.function.Tuple2 Java Examples

The following examples show how to use reactor.util.function.Tuple2. 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: R053_Concurrency.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
/**
 * TODO Generate list of tuples, but this time by zipping ({@link Flux#zip(Publisher, Publisher)})
 * stream of domains with stream of responses.
 * Why does it fail?
 */
@Test
public void zipIsBroken() throws Exception {
	//given
	final Flux<Domain> domains = Domains.all();

	//when
	Flux<Html> responses = null; // TODO
	final Flux<Tuple2<URI, Html>> tuples = Flux.zip(
			domains.map(Domain::getUri),
			responses
	);

	//then
	final List<Tuple2<URI, Html>> list = tuples
			.collectList()
			.block();

	assertThat(list)
			.hasSize(500)
			.contains(Tuples.of(new URI("http://archive.org"), new Html("<html><title>http://archive.org</title></html>")))
			.contains(Tuples.of(new URI("http://github.com"), new Html("<html><title>http://github.com</title></html>")));

	list.forEach(pair ->
			assertThat(pair.getT2().getRaw()).contains(pair.getT1().getHost()));
}
 
Example #2
Source File: FluxPublishMulticastTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void pairWise() {
	AssertSubscriber<Tuple2<Integer, Integer>> ts = AssertSubscriber.create();

	range(1, 9).transform(o -> zip(o, o.skip(1)))
	           .subscribe(ts);

	ts.assertValues(Tuples.of(1, 2),
			Tuples.of(2, 3),
			Tuples.of(3, 4),
			Tuples.of(4, 5),
			Tuples.of(5, 6),
			Tuples.of(6, 7),
			Tuples.of(7, 8),
			Tuples.of(8, 9))
	  .assertComplete();
}
 
Example #3
Source File: BeanFactoryAwareFunctionRegistryMultiInOutTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Bean
public Function<Tuple2<Flux<String>, Flux<Integer>>, Flux<?>[]> repeater() {

	return tuple -> {
		Flux<String> stringFlux = tuple.getT1();
		Flux<Integer> integerFlux = tuple.getT2();

		Flux<Integer> sharedIntFlux = integerFlux.publish().autoConnect(2);

		Flux<String> repeated = stringFlux
				.zipWith(sharedIntFlux)
				.flatMap(t -> Flux.fromIterable(Collections.nCopies(t.getT2(), t.getT1())));

		Flux<Integer> sum = sharedIntFlux
				.buffer(3, 1)
				.map(l -> l.stream().mapToInt(Integer::intValue).sum());

		return new Flux[] { repeated, sum };
	};
}
 
Example #4
Source File: FluxReplayTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheFluxHistoryTTL() {

	Flux<Tuple2<Long, Integer>> source = Flux.just(1, 2, 3)
	                                         .delayElements(Duration.ofMillis(1000))
	                                         .replay(2, Duration.ofMillis(2000))
	                                         .hide()
	                                         .autoConnect()
	                                         .hide()
	                                         .elapsed();

	StepVerifier.create(source)
	            .expectNoFusionSupport()
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 1)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 3)
	            .verifyComplete();

	StepVerifier.create(source)
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 3)
	            .verifyComplete();

}
 
Example #5
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 #6
Source File: AbstractCloudFoundryTaskLauncher.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 6 votes vote down vote up
@Override
public int getRunningTaskExecutionCount() {

	Mono<Tuple2<String,String>> orgAndSpace = Mono.zip(organizationId, spaceId);

	Mono<ListTasksRequest> listTasksRequest = orgAndSpace.map(tuple->
			ListTasksRequest.builder()
			.state(TaskState.RUNNING)
			.organizationId(tuple.getT1())
			.spaceId(tuple.getT2())
			.build());

	return listTasksRequest.flatMap(request-> this.client.tasks().list(request))
			.map(listTasksResponse -> listTasksResponse.getPagination().getTotalResults())
			.doOnError(logError("Failed to list running tasks"))
			.doOnSuccess(count -> logger.info(String.format("There are %d running tasks", count)))
			.block(Duration.ofMillis(this.deploymentProperties.getStatusTimeout()));
}
 
Example #7
Source File: ScannableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanOrDefaultOverridesGlobalDefault() {
	Scannable emptyScannable = key -> null;

	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.BUFFERED, 123)).isEqualTo(123); //global 0
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.CAPACITY, 123)).isEqualTo(123); //global 0
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.PREFETCH, 123)).isEqualTo(123); //global 0

	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.LARGE_BUFFERED, 123L)).isEqualTo(123L); //global null
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM, 123L)).isEqualTo(123L); //global 0

	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.CANCELLED, true)).isTrue(); //global false
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.DELAY_ERROR, true)).isTrue(); //global false
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.TERMINATED, true)).isTrue(); //global false

	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.ERROR, new IllegalStateException())).isInstanceOf(IllegalStateException.class); //global null

	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.ACTUAL, Scannable.Attr.NULL_SCAN)).isSameAs(Scannable.Attr.NULL_SCAN); //global null
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.PARENT, Scannable.Attr.NULL_SCAN)).isSameAs(Scannable.Attr.NULL_SCAN); // global null

	List<Tuple2<String, String>> tags = Collections.singletonList(Tuples.of("some", "key"));
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.TAGS, tags.stream())).containsExactlyElementsOf(tags); //global null
	assertThat(emptyScannable.scanOrDefault(Scannable.Attr.NAME, "SomeName")).isEqualTo("SomeName"); // global null
}
 
Example #8
Source File: PendingRequestRSocket.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
/**
 * After processor receives onNext signal, get route from exchange attrs, create a new
 * exchange from payload. Copy exchange attrs. Execute filter chain, if successful,
 * execute request.
 * @param logCategory log category
 * @param payload payload.
 * @return
 */
protected Mono<Tuple2<RSocket, Success>> processor(String logCategory,
		Payload payload) {
	return rSocketProcessor
			.log(PendingRequestRSocket.class.getName() + "." + logCategory,
					Level.FINEST)
			.flatMap(rSocket -> {
				GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_STREAM,
						payload, metadataExtractor);
				exchange.getAttributes().put(ROUTE_ATTR, route);
				// exchange.getAttributes().putAll(pendingExchange.getAttributes());
				return Mono.just(rSocket)
						.zipWith(executeFilterChain(route.getFilters(), exchange));
			});

}
 
Example #9
Source File: FluxMergingTests.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void zipFluxes() {
  Flux<String> characterFlux = Flux
      .just("Garfield", "Kojak", "Barbossa");
  Flux<String> foodFlux = Flux
      .just("Lasagna", "Lollipops", "Apples");
  
  Flux<Tuple2<String, String>> zippedFlux = 
      Flux.zip(characterFlux, foodFlux);
  
  StepVerifier.create(zippedFlux)
        .expectNextMatches(p -> 
            p.getT1().equals("Garfield") && 
            p.getT2().equals("Lasagna"))
        .expectNextMatches(p -> 
            p.getT1().equals("Kojak") && 
            p.getT2().equals("Lollipops"))
        .expectNextMatches(p -> 
            p.getT1().equals("Barbossa") && 
            p.getT2().equals("Apples"))
        .verifyComplete();
}
 
Example #10
Source File: R047_TimestampIndex.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void timestamp() throws Exception {
	//given
	final Flux<String> ticker = Flux
			.interval(ofMillis(123))
			.map(lng -> "Item-" + lng);

	//when
	final Flux<Tuple2<Long, String>> stamped = ticker.timestamp();

	//then
	final Flux<Tuple2<Instant, String>> instants = stamped
			.map(tup -> tup.mapT1(Instant::ofEpochMilli));

	instants
			.subscribe(
					x -> log.info("Received {}", x)
			);

	TimeUnit.SECONDS.sleep(4);
}
 
Example #11
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 #12
Source File: FluxReplayTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheFluxFused() {

	Flux<Tuple2<Long, Integer>> source = Flux.just(1, 2, 3)
	                                         .delayElements(Duration.ofMillis(1000))
	                                         .replay()
	                                         .autoConnect()
	                                         .elapsed();

	StepVerifier.create(source)
	            .expectFusion(Fuseable.ANY)
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 1)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 3)
	            .verifyComplete();

	StepVerifier.create(source)
	            .expectFusion(Fuseable.ANY)
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 1)
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 3)
	            .verifyComplete();

}
 
Example #13
Source File: SimpleFifoPoolTest.java    From reactor-pool with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("acquire delays instead of allocating past maxSize")
void acquireDelaysNotAllocate() {
    AtomicInteger newCount = new AtomicInteger();
    SimpleFifoPool<PoolableTest> pool = new SimpleFifoPool<>(poolableTestConfig(2, 3,
            Mono.defer(() -> Mono.just(new PoolableTest(newCount.incrementAndGet())))));

    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();
    pool.withPoolable(poolable -> Mono.just(poolable).delayElement(Duration.ofMillis(500))).subscribe();

    final Tuple2<Long, PoolableTest> tuple2 = pool.withPoolable(Mono::just).elapsed().blockLast();

    assertThat(tuple2).isNotNull();

    assertThat(tuple2.getT1()).as("pending for 500ms").isCloseTo(500L, Offset.offset(50L));
    assertThat(tuple2.getT2().usedUp).as("discarded twice").isEqualTo(2);
    assertThat(tuple2.getT2().id).as("id").isLessThan(4);
}
 
Example #14
Source File: ScannableTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void taggedFluxTest() {
	Flux<Integer> tagged1 =
			Flux.range(1, 10)
			    .tag("1", "One");


	Flux<Integer> tagged2 = tagged1.filter(i -> i % 3 == 0)
	                               .tag("2", "Two")
	                               .hide();

	final Stream<Tuple2<String, String>> scannedTags1 = Scannable.from(tagged1).tags();
	assertThat(scannedTags1.iterator())
			.containsExactlyInAnyOrder(Tuples.of("1", "One"));

	final Stream<Tuple2<String, String>> scannedTags2 = Scannable.from(tagged2).tags();
	assertThat(scannedTags2.iterator())
			.containsExactlyInAnyOrder(Tuples.of("1", "One"), Tuples.of( "2", "Two"));
}
 
Example #15
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 #16
Source File: FluxReplayTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheFluxHistoryTTLFused() {
	Flux<Tuple2<Long, Integer>> source = Flux.just(1, 2, 3)
	                                         .delayElements(Duration.ofMillis(1000))
	                                         .replay(2, Duration.ofMillis(2000))
	                                         .autoConnect()
	                                         .elapsed();

	StepVerifier.create(source)
	            .expectFusion(Fuseable.ANY)
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 1)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 1000 && t.getT2() == 3)
	            .verifyComplete();

	StepVerifier.create(source)
	            .expectFusion(Fuseable.ANY)
	            .then(() -> vts.advanceTimeBy(Duration.ofSeconds(3)))
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 2)
	            .expectNextMatches(t -> t.getT1() == 0 && t.getT2() == 3)
	            .verifyComplete();
}
 
Example #17
Source File: ArgsTest.java    From rsc with Apache License 2.0 6 votes vote down vote up
@Test
void metadataComposite() {
	final Args args = new Args(new String[]{"tcp://localhost:8080", //
			"--metadataMimeType", "application/json", //
			"-m", "{\"hello\":\"world\"}", //
			"--metadataMimeType", "text/plain", //
			"-m", "bar"});
	final Tuple2<String, ByteBuf> metadata = args.composeMetadata();
	assertThat(metadata.getT1()).isEqualTo("message/x.rsocket.composite-metadata.v0");
	assertThat(metadata.getT2().toString(UTF_8)).doesNotContain("application/json");
	assertThat(metadata.getT2().toString(UTF_8)).contains("{\"hello\":\"world\"}");
	assertThat(metadata.getT2().toString(UTF_8)).doesNotContain("text/plain");
	assertThat(metadata.getT2().toString(UTF_8)).contains("bar");
	final List<ByteBuf> metadataList = args.metadata();
	final List<String> metadataMimeTypeList = args.metadataMimeType();
	assertThat(metadataList.stream().map(x -> x.toString(UTF_8)).collect(toList()))
			.containsExactly("{\"hello\":\"world\"}", "bar");
	assertThat(metadataMimeTypeList).containsExactly("application/json", "text/plain");
}
 
Example #18
Source File: FluxIndexTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void doNotCallToString() {
	Flux<ThrowsOnToString> source = Flux.just(new ThrowsOnToString());
	Flux<Tuple2<Long, ThrowsOnToString>> test = new FluxIndex<>(source, Flux.tuple2Function());

	StepVerifier.create(test)
			.expectNextCount(1)
			.verifyComplete();
}
 
Example #19
Source File: OrderingFluxTest.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testOrderedOutOfOrderAhead()
{
    Flux<Tuple2<Long, String>> flux = Flux
        .just(of(2L, "foo"), of(0L, "bar"), of(1L, "baz"))
        .concatWith(Flux.error(new RuntimeException()));

    StepVerifier.create(OrderingFlux.order(flux))
        .expectNext("bar")
        .expectNext("baz")
        .expectNext("foo")
        .expectError()
        .verify();
}
 
Example #20
Source File: FluxIndexTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Scenario<Integer, Tuple2<Long, Integer>>> scenarios_operatorSuccess() {
	return Arrays.asList(
			scenario(Flux::index),
			scenario(f -> f.index(Tuples::of))
	);
}
 
Example #21
Source File: R2dbcAppMetricsRepositoryTest.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
@Test
public void testByOrganization() {
    Flux<Tuple2<String, Long>> input = metricsRepo.byOrganization();
    StepVerifier.create(input)
        .assertNext(m -> {
            assertEquals(1L, m.getT2());
            assertEquals("zoo-labs", m.getT1());
        }).verifyComplete();
}
 
Example #22
Source File: WatchStoreImpl.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeWatchForPeerAndId(String peerId, Integer peerWatchId)
{
    Map<Integer, Tuple2<Watch, Disposable>> watchesForPeer = watchesByPeer.get(peerId);
    if (watchesForPeer != null)
    {
        Tuple2<Watch, Disposable> watch = watchesForPeer.remove(peerWatchId);
        if (watch != null)
        {
            removeWatches(Collections.singleton(watch));
        }
    }
}
 
Example #23
Source File: CtrlResponseUtils.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Combine responses from multiple nodes.
 * <p>
 * When the response from the node is successful, it is replaced with the given message.
 * <p>
 * When failures occur they are converted into responses and a {@link CtrlResponseUtils.DelayedApiRcException}
 * is emitted after all the updates have terminated.
 */
public static Flux<ApiCallRc> combineResponses(
    Flux<Tuple2<NodeName, Flux<ApiCallRc>>> responses,
    ResourceName rscName,
    String messageFormat
)
{
    return combineResponses(responses, rscName, Collections.emptySet(), messageFormat, messageFormat);
}
 
Example #24
Source File: R043_Zip.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void monoCompleted() throws Exception {
	//given
	final Mono<Integer> num = Mono.just(1);
	final Mono<String> str = Mono.just("a");

	//when
	final Mono<Tuple2<Integer, String>> pair = num.zipWith(str);

	//then
	assertThat(pair.block()).isNotNull();
}
 
Example #25
Source File: CtrlSatelliteUpdateCaller.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * See {@link CtrlSatelliteUpdateCaller}.
 */
public Flux<Tuple2<NodeName, Flux<ApiCallRc>>> updateSatellites(
    Resource rsc,
    Publisher<ApiCallRc> nextStepRef
)
{
    return updateSatellites(rsc.getDefinition(), nextStepRef);
}
 
Example #26
Source File: ApplicationController.java    From Moss with Apache License 2.0 5 votes vote down vote up
protected Mono<MossApplication> toApplication(String name, Flux<Instance> instances) {
    return instances.collectList().map(instanceList -> {
        MossApplication group = new MossApplication(name);
        group.setInstances(instanceList);
        group.setRegisterSource(instanceList.get(0).getRegistration().getSource());
        group.setInstanceNum(instanceList.size());
        group.setBuildVersion(getBuildVersion(instanceList));
        Tuple2<String, Instant> status = getStatus(instanceList);
        group.setStatus(status.getT1());
        group.setStatusTimestamp(status.getT2());
        return group;
    });
}
 
Example #27
Source File: MonoZipTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void pairWise() {
	Mono<Tuple2<Integer, String>> f = Mono.just(1)
	                                      .zipWith(Mono.just("test2"));

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

	f.subscribeWith(AssertSubscriber.create())
	 .assertValues(Tuples.of(1, "test2"))
	 .assertComplete();
}
 
Example #28
Source File: FluxIndexedFuseableTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void indexMapperThrows() {
	Flux<String> source = Flux.just("foo", "bar");
	Flux<Tuple2<Integer, String>> test = new FluxIndexFuseable<>(source,
			(i, v) -> {
				if (i == 0L) return Tuples.of(0, v);
				throw new IllegalStateException("boom-" + i);
			});

	StepVerifier.create(test)
	            .expectNext(Tuples.of(0, "foo"))
	            .verifyErrorSatisfies(e -> assertThat(e)
			            .isInstanceOf(IllegalStateException.class)
			            .hasMessage("boom-1"));
}
 
Example #29
Source File: MovieService.java    From spring-5-examples with MIT License 5 votes vote down vote up
public Flux<MovieEvent> streamEvents(final String id) {
  val movie = getById(id);
  return movie.flatMapMany(s -> {
    val interval = Flux.interval(Duration.ofSeconds(1));
    val stream = Stream.generate(() -> new MovieEvent(s, now()));
    val event = Flux.fromStream(stream);
    val tuple2Flux = Flux.zip(interval, event);
    return tuple2Flux.map(Tuple2::getT2);
  });
}
 
Example #30
Source File: HygienePolicyExecutorTask.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
private void notifyUsers(Tuple2<HygienePolicy, Workloads> tuple) {
    if (tuple.getT1().getNotifyeeTemplate() != null) {
        // Pull distinct Set<Space> from applications and service instances
        Flux
            .fromIterable(getSpaces(tuple.getT2()))
        // For each Space in Set<Space>, obtain SpaceUsers#getUsers()
            .concatMap(space -> spaceUsersService.findByOrganizationAndSpace(space.getOrganizationName(), space.getSpaceName()))
        // then pair with matching space(s) that contain applications and service instances
            .concatMap(spaceUser -> Flux.fromIterable(spaceUser.getUsers()))
            .distinct()
        // filter out account names that are not email addresses
            .filter(userName -> EmailValidator.isValid(userName))
            .concatMap(userName -> userSpacesService.getUserSpaces(userName))
        // Create a list where each item is a tuple of user account and filtered workloads
            .concatMap(userSpace -> filterWorkloads(userSpace, tuple.getT2()))
            .delayElements(Duration.ofMillis(250))
            .doOnNext(
                    userWorkloads -> {
                                publisher.publishEvent(
                                    new EmailNotificationEvent(this)
                                        .domain(settings.getAppsDomain())
                                        .from(tuple.getT1().getNotifyeeTemplate().getFrom())
                                        .recipient(userWorkloads.getT1().getAccountName())
                                        .subject(tuple.getT1().getNotifyeeTemplate().getSubject())
                                        .body(tuple.getT1().getNotifyeeTemplate().getBody())
                                        .attachments(buildAttachments(Tuples.of(tuple.getT1(), userWorkloads.getT2())))
                                );
                    }
            )
            .subscribe();
    }
}