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

The following examples show how to use reactor.core.publisher.Flux#map() . 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: Jackson2TokenizerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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
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 3
Source File: FluxDemoTest.java    From Software-Architecture-with-Spring-5.0 with MIT License 6 votes vote down vote up
@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 4
Source File: JettyReactiveHttpResponse.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: Jackson2TokenizerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
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 6
Source File: R030_MapAndFilter.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@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 7
Source File: AccountServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@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
Source File: BeanFactoryAwareFunctionRegistryMultiInOutTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@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
Source File: FooReporter.java    From tutorials with 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 10
Source File: JmapResponseWriterImpl.java    From james-project with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: DispatchHandlerTests.java    From spring-cloud-sockets with Apache License 2.0 4 votes vote down vote up
@RequestStreamMapping(value = "/requestStream", mimeType = "application/json")
public Flux<Integer> adder(Flux<Integer> input){
	return input.map(integer -> integer+1);
}
 
Example 12
Source File: TaxiController.java    From Spring-Boot-2.0-Projects with MIT License 4 votes vote down vote up
@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()));
}
 
Example 13
Source File: ContextFunctionCatalogAutoConfigurationTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Foo> apply(Flux<String> flux) {
	return flux.map(foo -> new Foo(value() + ": " + foo.toUpperCase()));
}
 
Example 14
Source File: ReactiveTargetResolver.java    From promregator with Apache License 2.0 4 votes vote down vote up
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 15
Source File: ContextFunctionCatalogInitializerTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Foo> apply(Flux<String> flux) {
	return flux.map(foo -> new Foo(value() + ": " + foo.toUpperCase()));
}
 
Example 16
Source File: FunctionTypeTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Bar> apply(Flux<Foo> t) {
	return t.map(f -> new Bar());
}
 
Example 17
Source File: ReactiveTestServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<String> requestGlobals(Flux<String> actions) {
    return actions.map(text -> "received: " + text);
}
 
Example 18
Source File: FluxFunction.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<O> apply(Flux<I> input) {
	return input.map(value -> this.getTarget().apply(value));
}
 
Example 19
Source File: Exclaimer.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<String> apply(Flux<String> words) {
	return words.map(word -> word + "!!!");
}
 
Example 20
Source File: FunctionTypeTests.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
@Override
public Flux<Message<Bar>> apply(Flux<Message<Foo>> t) {
	return t.map(f -> MessageBuilder.withPayload(new Bar())
			.copyHeadersIfAbsent(f.getHeaders()).build());
}