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

The following examples show how to use reactor.core.publisher.Mono#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: InstanceExchangeFilterFunctions.java    From spring-boot-admin with Apache License 2.0 9 votes vote down vote up
public static InstanceExchangeFilterFunction convertLegacyEndpoints(List<LegacyEndpointConverter> converters) {
	return (instance, request, next) -> {
		Mono<ClientResponse> clientResponse = next.exchange(request);

		Optional<Object> endpoint = request.attribute(ATTRIBUTE_ENDPOINT);
		if (!endpoint.isPresent()) {
			return clientResponse;
		}

		for (LegacyEndpointConverter converter : converters) {
			if (converter.canConvert(endpoint.get())) {
				return clientResponse.map((response) -> {
					if (isLegacyResponse(response)) {
						return convertLegacyResponse(converter, response);
					}
					return response;
				});
			}
		}
		return clientResponse;
	};
}
 
Example 2
Source File: ReactiveLifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 8 votes vote down vote up
/**
 * Performs a token refresh. Creates a new token if no token was obtained before. If a
 * token was obtained before, it uses self-renewal to renew the current token.
 * Client-side errors (like permission denied) indicate the token cannot be renewed
 * because it's expired or simply not found.
 * @return the {@link VaultToken} if the refresh was successful or a new token was
 * obtained. {@link Mono#empty()} if a new the token expired or
 * {@link Mono#error(Throwable)} if refresh failed.
 */
public Mono<VaultToken> renewToken() {

	this.logger.info("Renewing token");

	Mono<TokenWrapper> tokenWrapper = this.token.get();

	if (tokenWrapper == TERMINATED) {
		return tokenWrapper.map(TokenWrapper::getToken);
	}

	if (tokenWrapper == EMPTY) {
		return getVaultToken();
	}

	return tokenWrapper.flatMap(this::doRenewToken).map(TokenWrapper::getToken);
}
 
Example 3
Source File: HybridBlobStore.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mono<BlobStore> selectBlobStore(StoragePolicy storagePolicy, Mono<Boolean> largeData) {
    switch (storagePolicy) {
        case LOW_COST:
            return Mono.just(lowCostBlobStore);
        case SIZE_BASED:
            return largeData.map(isLarge -> {
                if (isLarge) {
                    return lowCostBlobStore;
                }
                return highPerformanceBlobStore;
            });
        case HIGH_PERFORMANCE:
            return Mono.just(highPerformanceBlobStore);
        default:
            throw new RuntimeException("Unknown storage policy: " + storagePolicy);
    }
}
 
Example 4
Source File: ClientRestController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/auth-code")
Mono<String> useOauthWithAuthCode() {
    Mono<String> retrievedResource = webClient.get()
        .uri(RESOURCE_URI)
        .retrieve()
        .bodyToMono(String.class);
    return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string);
}
 
Example 5
Source File: RequestMappingMessageConversionIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@PostMapping("/mono")
public Mono<Person> transformMono(@RequestBody Mono<Person> personFuture) {
	return personFuture.map(person -> new Person(person.getName().toUpperCase()));
}
 
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: RedissonReactiveClusterKeyCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ByteBuffer> randomKey(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<byte[]> m = executorService.reactive(() -> {
        return executorService.readRandomAsync(entry, ByteArrayCodec.INSTANCE, RedisCommands.RANDOM_KEY);
    });
    return m.map(v -> ByteBuffer.wrap(v));
}
 
Example 8
Source File: RedissonReactiveKeyCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Duration> idletime(ByteBuffer key) {
    Assert.notNull(key, "Key must not be null!");

    byte[] keyBuf = toByteArray(key);
    Mono<Long> m = read(keyBuf, StringCodec.INSTANCE, OBJECT_IDLETIME, keyBuf);
    return m.map(Duration::ofSeconds);
}
 
Example 9
Source File: RedissonReactiveClusterKeyCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ByteBuffer> randomKey(RedisClusterNode node) {
    MasterSlaveEntry entry = getEntry(node);
    Mono<byte[]> m = executorService.reactive(() -> {
        return executorService.readRandomAsync(entry, ByteArrayCodec.INSTANCE, RedisCommands.RANDOM_KEY);
    });
    return m.map(v -> ByteBuffer.wrap(v));
}
 
Example 10
Source File: RedissonReactiveClusterKeyCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<List<ByteBuffer>> keys(RedisClusterNode node, ByteBuffer pattern) {
    Mono<List<String>> m = executorService.reactive(() -> {
        return (RFuture<List<String>>)(Object) executorService.readAllAsync(StringCodec.INSTANCE, RedisCommands.KEYS, toByteArray(pattern));
    });
    return m.map(v -> v.stream().map(t -> ByteBuffer.wrap(t.getBytes(CharsetUtil.UTF_8))).collect(Collectors.toList()));
}
 
Example 11
Source File: DaprHttpClient.java    From java-sdk with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Mono<byte[]> invokeActorMethod(String actorType, String actorId, String methodName, byte[] jsonPayload) {
  String url = String.format(Constants.ACTOR_METHOD_RELATIVE_URL_FORMAT, actorType, actorId, methodName);
  Mono<DaprHttp.Response> responseMono =
        this.client.invokeApi(DaprHttp.HttpMethods.POST.name(), url, null, jsonPayload, null);
  return responseMono.map(r -> r.getBody());
}
 
Example 12
Source File: ClientRestController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/auth-code-no-client")
Mono<String> useOauthWithNoClient() {
    // This call will fail, since we don't have the client properly set for this webClient
    Mono<String> retrievedResource = otherWebClient.get()
        .uri(RESOURCE_URI)
        .retrieve()
        .bodyToMono(String.class);
    return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string);
}
 
Example 13
Source File: Main.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Mono<GreeterOuterClass.HelloResponse> sayHello(Mono<GreeterOuterClass.HelloRequest> request) {
    return request.map(req -> 
        GreeterOuterClass.HelloResponse.newBuilder()
        .addMessage("Hello " + req.getName())
        .addMessage("Aloha " + req.getName())
        .addMessage("Howdy " + req.getName())
        .build()
    );
}
 
Example 14
Source File: RedissonReactiveClusterKeyCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<List<ByteBuffer>> keys(RedisClusterNode node, ByteBuffer pattern) {
    Mono<List<String>> m = executorService.reactive(() -> {
        return (RFuture<List<String>>)(Object) executorService.readAllAsync(StringCodec.INSTANCE, RedisCommands.KEYS, toByteArray(pattern));
    });
    return m.map(v -> v.stream().map(t -> ByteBuffer.wrap(t.getBytes(CharsetUtil.UTF_8))).collect(Collectors.toList()));
}
 
Example 15
Source File: HelloServiceImpl.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Sends a {@link HelloReply} immediately when receiving a request.
 */
@Override
public Mono<HelloReply> hello(Mono<HelloRequest> request) {
    return request.map(it -> buildReply(toMessage(it.getName())));
}
 
Example 16
Source File: FusedTckService.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Mono<Message> oneToOne(Mono<Message> request) {
    return request.map(this::maybeExplode);
}
 
Example 17
Source File: CfBlueGreenStage2Delegate.java    From ya-cf-app-gradle-plugin with Apache License 2.0 4 votes vote down vote up
public Mono<Void> runStage2(Project project, CloudFoundryOperations cfOperations,
                            CfProperties cfProperties) {
    
    String greenNameString = cfProperties.name() + "-green";
    Mono<String> greenRouteMono = CfRouteUtil.getTempRoute(cfOperations, cfProperties, "green");

    CfProperties greenName = ImmutableCfProperties.copyOf(cfProperties)
        .withName(greenNameString);

    Mono<CfProperties> greenNameAndRouteMono = greenRouteMono.map(greenRoute -> ImmutableCfProperties.copyOf(cfProperties)
        .withName(greenNameString)
        .withHost(null)
        .withDomain(null)
        .withRoutes(Collections.singletonList(greenRoute)));

    CfProperties blueName = ImmutableCfProperties.copyOf(cfProperties)
        .withName(cfProperties.name() + "-blue");

    Mono<Optional<ApplicationDetail>> backupAppMono = appDetailsDelegate
        .getAppDetails(cfOperations, blueName);

    Mono<Optional<ApplicationDetail>> existingAppMono = appDetailsDelegate
        .getAppDetails(cfOperations, cfProperties);

    Mono<Void> bgResult = Mono.zip(backupAppMono, existingAppMono, greenNameAndRouteMono, greenRouteMono)
        .flatMap(function((backupApp, existingApp, greenNameAndRoute, greenRouteString) -> {
            LOGGER.lifecycle(
                "Running Blue Green Deploy - after deploying a 'green' app. App '{}' with route '{}'",
                cfProperties.name(),
                greenRouteString);
            return
                (backupApp.isPresent() ?
                    deleteAppDelegate.deleteApp(cfOperations, blueName) : Mono.empty())
                    .thenMany(mapRouteDelegate.mapRoute(cfOperations, greenName))
                    .thenMany(existingApp.isPresent() ?
                        unMapRouteDelegate.unmapRoute(cfOperations, cfProperties) :
                        Mono.empty())
                    .thenMany(unMapRouteDelegate.unmapRoute(cfOperations, greenNameAndRoute))
                    .then(existingApp.isPresent() ?
                        renameAppDelegate
                            .renameApp(cfOperations, cfProperties, blueName) :
                        Mono.empty())
                    .then(renameAppDelegate
                        .renameApp(cfOperations, greenName, cfProperties))
                    .then(
                        existingApp.isPresent() ?
                            appStopDelegate.stopApp(cfOperations, blueName) :
                            Mono.empty());
        }));

    return bgResult;
}
 
Example 18
Source File: CrnkVertxHandler.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private Mono<HttpServerRequest> processRequest(HttpRequestContext context, HttpServerRequest serverRequest) {
    RequestDispatcher requestDispatcher = boot.getRequestDispatcher();

    long startTime = System.currentTimeMillis();
    LOGGER.debug("setting up request");

    try {
        Optional<Result<HttpResponse>> optResponse = requestDispatcher.process(context);

        if (optResponse.isPresent()) {
            MonoResult<HttpResponse> response = (MonoResult<HttpResponse>) optResponse.get();

            Mono<HttpResponse> mono = response.getMono();


            return mono.map(it -> {
                HttpServerResponse httpResponse = serverRequest.response();
                LOGGER.debug("delivering response {}", httpResponse);
                httpResponse.setStatusCode(it.getStatusCode());
                it.getHeaders().forEach((key, value) -> httpResponse.putHeader(key, value));
                if (it.getBody() != null) {
                    Buffer bodyBuffer = Buffer.newInstance(io.vertx.core.buffer.Buffer.buffer(it.getBody()));
                    httpResponse.end(bodyBuffer);
                } else {
                    httpResponse.end();
                }
                return serverRequest;
            });
        } else {
            serverRequest.response().setStatusCode(HttpStatus.NOT_FOUND_404);
            serverRequest.response().end();
            return Mono.just(serverRequest);
        }

    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        long endTime = System.currentTimeMillis();
        LOGGER.debug("prepared request in in {}ms", endTime - startTime);
    }
}
 
Example 19
Source File: ItemsFilterProcessor.java    From staccato with Apache License 2.0 4 votes vote down vote up
public Mono<ItemCollection> searchItemCollectionMono(Mono<ItemCollection> itemCollectionMono, SearchRequest request) {
    return (null == searchFilters) ? itemCollectionMono : itemCollectionMono.map(ic ->
            searchItemCollectionFunction.apply(ic, request));
}
 
Example 20
Source File: ReactiveLifecycleAwareSessionManager.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
private static Mono<VaultToken> augmentWithSelfLookup(WebClient webClient, VaultToken token) {

		Mono<Map<String, Object>> data = lookupSelf(webClient, token);

		return data.map(it -> {

			Boolean renewable = (Boolean) it.get("renewable");
			Number ttl = (Number) it.get("ttl");

			if (renewable != null && renewable) {
				return LoginToken.renewable(token.toCharArray(), LoginTokenAdapter.getLeaseDuration(ttl));
			}

			return LoginToken.of(token.toCharArray(), LoginTokenAdapter.getLeaseDuration(ttl));
		});
	}