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

The following examples show how to use reactor.core.publisher.Mono#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
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
/**
 * 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 Project: james-project   File: HybridBlobStore.java    License: 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
@PostMapping("/mono")
public Mono<Person> transformMono(@RequestBody Mono<Person> personFuture) {
	return personFuture.map(person -> new Person(person.getName().toUpperCase()));
}
 
Example 5
@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 6
@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 7
@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 8
@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 9
Source Project: java-sdk   File: DaprHttpClient.java    License: 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 10
Source Project: tutorials   File: ClientRestController.java    License: MIT License 5 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 11
Source Project: tutorials   File: ClientRestController.java    License: 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 12
@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 13
@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 14
@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
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));
		});
	}
 
Example 16
Source Project: staccato   File: ItemsFilterProcessor.java    License: 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 17
Source Project: crnk-framework   File: CrnkVertxHandler.java    License: 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 18
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 19
@Override
public Mono<Message> oneToOne(Mono<Message> request) {
    return request.map(this::maybeExplode);
}
 
Example 20
Source Project: armeria   File: HelloServiceImpl.java    License: 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())));
}