Java Code Examples for reactor.core.publisher.Flux#map()

The following examples show how to use reactor.core.publisher.Flux#map() . These examples are extracted from open source projects. 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
private void testTokenize(List<String> source, List<String> expected, boolean tokenizeArrayElements) {
	Flux<TokenBuffer> tokens = Jackson2Tokenizer.tokenize(
			Flux.fromIterable(source).map(this::stringBuffer),
			this.jsonFactory, this.objectMapper, tokenizeArrayElements);

	Flux<String> result = tokens
			.map(tokenBuffer -> {
				try {
					TreeNode root = this.objectMapper.readTree(tokenBuffer.asParser());
					return this.objectMapper.writeValueAsString(root);
				}
				catch (IOException ex) {
					throw new UncheckedIOException(ex);
				}
			});

	StepVerifier.FirstStep<String> builder = StepVerifier.create(result);
	expected.forEach(s -> builder.assertNext(new JSONAssertConsumer(s)));
	builder.verifyComplete();
}
 
Example 2
private void testTokenize(List<String> source, List<String> expected, boolean tokenizeArrayElements) {

		Flux<TokenBuffer> tokenBufferFlux = Jackson2Tokenizer.tokenize(
				Flux.fromIterable(source).map(this::stringBuffer),
				this.jsonFactory,
				tokenizeArrayElements);

		Flux<String> result = tokenBufferFlux
				.map(tokenBuffer -> {
					try {
						TreeNode root = this.objectMapper.readTree(tokenBuffer.asParser());
						return this.objectMapper.writeValueAsString(root);
					}
					catch (IOException ex) {
						throw new UncheckedIOException(ex);
					}
				});

		StepVerifier.FirstStep<String> builder = StepVerifier.create(result);
		expected.forEach(s -> builder.assertNext(new JSONAssertConsumer(s)));
		builder.verifyComplete();
	}
 
Example 3
@Override
public Publisher<?> body() {
	ReactorObjectReader reactorObjectReader = new ReactorObjectReader(jsonFactory);

	Flux<ByteBuffer> content = directContent();

	if(returnActualClass == ByteBuffer.class){
		return content;
	} else if(returnActualClass.isAssignableFrom(String.class)
			&& returnPublisherType == Mono.class){
		Charset charset = getCharset();
		return content.map(byteBuffer -> charset.decode(byteBuffer).toString());
	} else {
		if (returnPublisherType == Mono.class) {
			return reactorObjectReader.read(content, objectReader);
		} else if(returnPublisherType == Flux.class){
			return reactorObjectReader.readElements(content, objectReader);
		} else {
			throw new IllegalArgumentException("Unknown returnPublisherType: " + returnPublisherType);
		}
	}
}
 
Example 4
@Test
public void givenAListOfCapitalizedStrings_WhenTheFlatMapConvertsToUpperCaseTheStrings_ThenTheStringsAreInUpperCase() throws Exception {
    List<String> namesCapitalized =
            Arrays.asList("John", "Steve", "Rene");
    Iterator<String> namesCapitalizedIterator =
            namesCapitalized.iterator();
    Flux<String> fluxWithNamesCapitalized =
            Flux.fromIterable(namesCapitalized);

    Flux<String> fluxWithNamesInUpperCase = fluxWithNamesCapitalized
            .map(name -> name.toUpperCase());

    fluxWithNamesInUpperCase.subscribe(nameInUpperCase -> {
                String expectedString =
                        namesCapitalizedIterator.next().toUpperCase();

                Assert.assertEquals(expectedString, nameInUpperCase);
            }
    );
}
 
Example 5
@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 6
Source Project: tutorials   File: FooReporter.java    License: MIT License 5 votes vote down vote up
public static Flux<Foo> reportResult(Flux<Foo> input, String approach) {
    return input.map(foo -> {
        if (foo.getId() == null)
            throw new IllegalArgumentException("Null id is not valid!");
        logger.info("Reporting for approach {}: Foo with id '{}' name '{}' and quantity '{}'", approach, foo.getId(), foo.getFormattedName(), foo.getQuantity());
        return foo;
    });
}
 
Example 7
@Override
public Flux<Account> findByIdStream(Flux<Int32Value> idStream) {
    return idStream.map(id -> Account.newBuilder()
            .setId(id.getValue())
            .setEmail(faker.internet().emailAddress())
            .setPhone(faker.phoneNumber().cellPhone())
            .setNick(faker.name().name())
            .setStatus(1)
            .build());
}
 
Example 8
@Bean
public Function<Flux<Person>, Tuple3<Flux<Person>, Flux<String>, Flux<Integer>>> multiOutputAsTuplePojoIn() {
	return flux -> {
		Flux<Person> pubSubFlux = flux.publish().autoConnect(3);
		Flux<String> nameFlux = pubSubFlux.map(person -> person.getName());
		Flux<Integer> idFlux = pubSubFlux.map(person -> person.getId());
		return Tuples.of(pubSubFlux, nameFlux, idFlux);
	};
}
 
Example 9
@Override
public Flux<InvocationResponse> formatMethodResponse(Flux<JmapResponse> jmapResponses) {
    return jmapResponses.map(jmapResponse -> {
        ObjectMapper objectMapper = newConfiguredObjectMapper(jmapResponse);

        return new InvocationResponse(
                jmapResponse.getResponseName(),
                objectMapper.valueToTree(jmapResponse.getResponse()),
                jmapResponse.getMethodCallId());
    });
}
 
Example 10
@Test
public void mapTransformsItemsOnTheFly() throws Exception {
	//given
	final Flux<Integer> numbers = Flux.range(5, 4);

	//when
	final Flux<Integer> even = numbers.map(x -> x * 2);

	//then
	even
			.as(StepVerifier::create)
			.expectNext(10, 12, 14, 16)
			.verifyComplete();
}
 
Example 11
@Override
public Flux<Message<Bar>> apply(Flux<Message<Foo>> t) {
	return t.map(f -> MessageBuilder.withPayload(new Bar())
			.copyHeadersIfAbsent(f.getHeaders()).build());
}
 
Example 12
Source Project: spring-cloud-function   File: Exclaimer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Flux<String> apply(Flux<String> words) {
	return words.map(word -> word + "!!!");
}
 
Example 13
@Override
public Flux<O> apply(Flux<I> input) {
	return input.map(value -> this.getTarget().apply(value));
}
 
Example 14
@Override
public Flux<String> requestGlobals(Flux<String> actions) {
    return actions.map(text -> "received: " + text);
}
 
Example 15
@Override
public Flux<Bar> apply(Flux<Foo> t) {
	return t.map(f -> new Bar());
}
 
Example 16
@Override
public Flux<Foo> apply(Flux<String> flux) {
	return flux.map(foo -> new Foo(value() + ": " + foo.toUpperCase()));
}
 
Example 17
@RequestStreamMapping(value = "/requestStream", mimeType = "application/json")
public Flux<Integer> adder(Flux<Integer> input){
	return input.map(integer -> integer+1);
}
 
Example 18
private Flux<IntermediateTarget> resolveSpace(IntermediateTarget it) {
	/* NB: Now we have to consider three cases:
	 * Case 1: both spaceName and spaceRegex is empty => select all spaces (within the org)
	 * Case 2: spaceName is null, but spaceRegex is filled => filter all spaces with the regex
	 * Case 3: spaceName is filled, but spaceRegex is null => select a single space
	 * In cases 1 and 2, we need the list of all spaces in the org.
	 */
	
	if (it.getConfigTarget().getSpaceRegex() == null && it.getConfigTarget().getSpaceName() != null) {
		// Case 3: we have the spaceName, but we also need its id
		Mono<IntermediateTarget> itMono = this.cfAccessor.retrieveSpaceId(it.getResolvedOrgId(), it.getConfigTarget().getSpaceName())
				.map(ListSpacesResponse::getResources)
				.flatMap(resList -> {
					if (resList == null || resList.isEmpty()) {
						return Mono.empty();
					}
					
					return Mono.just(resList.get(0));
				})
				.map(res -> {
					it.setResolvedSpaceName(res.getEntity().getName());
					it.setResolvedSpaceId(res.getMetadata().getId());
					return it;
				}).doOnError(e -> log.warn(String.format("Error on retrieving space id for org '%s' and space '%s'", it.getResolvedOrgName(), it.getConfigTarget().getSpaceName()), e))
				.onErrorResume(__ -> Mono.empty());
		
		return itMono.flux();
	}
	
	// Case 1 & 2: Get all spaces in the current org
	Mono<ListSpacesResponse> responseMono = this.cfAccessor.retrieveSpaceIdsInOrg(it.getResolvedOrgId());

	Flux<SpaceResource> spaceResFlux = responseMono.map(ListSpacesResponse::getResources)
		.flatMapMany(Flux::fromIterable);
	
	if (it.getConfigTarget().getSpaceRegex() != null) {
		// Case 2
		final Pattern filterPattern = Pattern.compile(it.getConfigTarget().getSpaceRegex(), Pattern.CASE_INSENSITIVE);
		
		spaceResFlux = spaceResFlux.filter(spaceRes -> {
			Matcher m = filterPattern.matcher(spaceRes.getEntity().getName());
			return m.matches();
		});
	}
	
	return spaceResFlux.map(spaceRes -> {
		IntermediateTarget itnew = new IntermediateTarget(it);
		itnew.setResolvedSpaceId(spaceRes.getMetadata().getId());
		itnew.setResolvedSpaceName(spaceRes.getEntity().getName());
		
		return itnew;
	});
}
 
Example 19
@Override
public Flux<Foo> apply(Flux<String> flux) {
	return flux.map(foo -> new Foo(value() + ": " + foo.toUpperCase()));
}
 
Example 20
@GetMapping
public Flux<TaxiAvailableResponseDTO> getAvailableTaxis(@RequestParam("type") TaxiType taxiType, @RequestParam("latitude") Double latitude, @RequestParam("longitude") Double longitude, @RequestParam(value = "radius", defaultValue = "1") Double radius) {
    Flux<GeoResult<RedisGeoCommands.GeoLocation<String>>> availableTaxisFlux = taxiService.getAvailableTaxis(taxiType, latitude, longitude, radius);
    return availableTaxisFlux.map(r -> new TaxiAvailableResponseDTO(r.getContent().getName()));
}