Java Code Examples for java.util.concurrent.CompletionStage#thenApply()

The following examples show how to use java.util.concurrent.CompletionStage#thenApply() . 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
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Callable<CompletionStage<ResponseEntity<?>>> process(@Valid @RequestBody PerformPaymentRequest request) {

    LOG.debug("Request {}", request);

    return () -> {
        LOG.debug("Callable...");

        PerformPayment performPayment = PerformPayment.commandOf(
                new CustomerId(request.getCustomerId()),
                PaymentIntent.valueOf(request.getPaymentIntent()),
                PaymentMethod.valueOf(request.getPaymentMethod()),
                request.getTransaction());

        CompletionStage<Either<CommandFailure, Tuple2<PaymentId, PaymentStatus>>> promise = paymentProcessManager.process(performPayment);
        return promise.thenApply(acceptOrReject -> acceptOrReject.fold(
                reject -> ResponseEntity.badRequest().body(reject),
                accept -> ResponseEntity.accepted().body(new PerformPaymentResponse(accept._1.id, accept._2.name()))
        ));
    };


}
 
Example 2
Source Project: java-async-util   File: Combinators.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T, A, R> CompletionStage<R> collectImpl(
    final Iterator<? extends CompletionStage<T>> it,
    final Collector<? super T, A, R> collector) {

  CompletionStage<A> acc = StageSupport.completedStage(collector.supplier().get());
  final BiConsumer<A, ? super T> accFun = collector.accumulator();

  while (it.hasNext()) {
    /*
     * each additional combination step runs only after all previous steps have completed
     */
    acc = acc.thenCombine(it.next(), (a, t) -> {
      accFun.accept(a, t);
      return a;
    });
  }
  return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)
      ? (CompletionStage<R>) acc
      : acc.thenApply(collector.finisher());

}
 
Example 3
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Iterable<Object>> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Iterable<Object>>> context) {
    CompletionStage<? extends Iterable<?>> future;
    if (context.hasAnnotation(Query.class)) {
        PreparedQuery<?, ?> preparedQuery = prepareQuery(methodKey, context);
        future = asyncDatastoreOperations.findAll(preparedQuery);

    } else {
        future = asyncDatastoreOperations.findAll(getPagedQuery(context));
    }
    return future.thenApply((Function<Iterable<?>, Iterable<Object>>) iterable -> {
        Argument<CompletionStage<Iterable<Object>>> targetType = context.getReturnType().asArgument();
        Argument<?> argument = targetType.getFirstTypeVariable().orElse(Argument.listOf(Object.class));
        Iterable<Object> result = (Iterable<Object>) ConversionService.SHARED.convert(
                iterable,
                argument
        ).orElse(null);
        return result == null ? Collections.emptyList() : result;
    });
}
 
Example 4
@Override
public CompletionStage<SearchResults> search(String query) {
    query = query.replace("$Artifact", toFqn()); // simplify usage
    CompletionStage<RestResponse> results = getCache().query(query);
    return results.thenApply(r -> {
        try {
            int status = r.getStatus();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IoBufferedInputStream rbis = new IoBufferedInputStream(r.getBodyAsStream(), (bytes, count) -> {
                baos.write(bytes, 0, count);
            });
            // Infinispan Search impl details!!
            JsonNode tree = mapper.readTree(rbis);
            int totalResults = tree.get("total_results").asInt();
            ArrayNode hits = (ArrayNode) tree.get("hits");
            List<Search.Artifact> artifacts = new ArrayList<>();
            for (int i = 0; i < hits.size(); i++) {
                JsonNode jsonNode = hits.get(i);
                Search.Artifact.Builder builder = Search.Artifact.newBuilder();
                String json = jsonNode.get("hit").toString();
                Search.Artifact artifact = ProtoUtil.fromJson(builder, json, true);
                artifacts.add(artifact);
            }
            return new RestSearchResults(status, totalResults, artifacts);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    });
}
 
Example 5
@ApiAction
public CompletionStage<Result> getOrderById( @Min(1) @Max(5)Long orderId) throws Exception {
    CompletionStage<Order> stage = imp.getOrderById(orderId).thenApply(obj -> { 
        if (configuration.getBoolean("useOutputBeanValidation")) {
            OpenAPIUtils.validate(obj);
        }
        return obj;
    });
    stage.thenApply(obj -> {
        JsonNode result = mapper.valueToTree(obj);
        return ok(result);
    });
}
 
Example 6
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenApply(context -> {
        final UiSchema schema = newUiSchema(context);
        schema.setWidget("toggle");
        return context;
    });
}
 
Example 7
@Override
public CompletionStage<VersionMetaData> createArtifactVersion(String artifactId, ArtifactType xRegistryArtifactType, InputStream data) {
    CompletionStage<VersionMetaData> cs = getDelegate().createArtifactVersion(artifactId, xRegistryArtifactType, data);
    return cs.thenApply(vmd -> {
        Map<Integer, VersionMetaData> map = vmds.computeIfAbsent(artifactId, id -> new ConcurrentHashMap<>());
        map.put(vmd.getVersion(), vmd);
        return vmd;
    });
}
 
Example 8
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenApply(context -> {
        final UiSchema schema = newUiSchema(context);
        schema.setWidget("textarea");
        return context;
    });
}
 
Example 9
private static CompletionStage<BeamFnApi.RegisterResponse> getRegisterResponse(
    CompletionStage<InstructionResponse> responseFuture) {
  return responseFuture.thenApply(
      response -> {
        switch (response.getResponseCase()) {
          case REGISTER:
            return response.getRegister();
          default:
            throw new IllegalStateException(
                String.format(
                    "SDK harness returned wrong kind of response to RegisterRequest: %s",
                    TextFormat.printToString(response)));
        }
      });
}
 
Example 10
@SuppressWarnings("unchecked")
@Override
public CompletionStage<Object> intercept(RepositoryMethodKey methodKey, MethodInvocationContext<T, CompletionStage<Object>> context) {
    PreparedQuery<Object, Object> preparedQuery = (PreparedQuery<Object, Object>) prepareQuery(methodKey, context);
    CompletionStage<Object> future = asyncDatastoreOperations.findOne(preparedQuery);
    Argument<?> type = context.getReturnType().asArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
    return future.thenApply(o -> {
        if (!type.getType().isInstance(o)) {
            return ConversionService.SHARED.convert(o, type)
                    .orElseThrow(() -> new IllegalStateException("Unexpected return type: " + o));
        }
        return o;
    });
}
 
Example 11
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenApply(context -> {
        jsonSchema.setType("string");
        if (context.getProperty().getValidation() == null
                || context.getProperty().getValidation().getEnumValues() == null) {
            jsonSchema.setEnumValues(emptyList());
        } else {
            jsonSchema.setEnumValues(context.getProperty().getValidation().getEnumValues());
        }
        return context;
    });
}
 
Example 12
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenApply(context -> {
        final UiSchema schema = newUiSchema(context);
        initDatePicker(context, schema);
        return context;
    });
}
 
Example 13
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenApply(context -> {
        final UiSchema schema = newUiSchema(context);
        final String codeLang = context.getProperty().getMetadata().get("ui::code::value");
        schema.setWidget("code");
        schema.setOptions(singletonMap("language", codeLang));
        return context;
    });

}
 
Example 14
@ApiAction
public CompletionStage<Result> findPetsByTags() throws Exception {
    String[] tagsArray = request().queryString().get("tags");
    if (tagsArray == null) {
        throw new IllegalArgumentException("'tags' parameter is required");
    }
    List<String> tagsList = OpenAPIUtils.parametersToList("csv", tagsArray);
    List<String> tags = new ArrayList<>();
    for (String curParam : tagsList) {
        if (!curParam.isEmpty()) {
            //noinspection UseBulkOperation
            tags.add(curParam);
        }
    }
    CompletionStage<List<Pet>> stage = imp.findPetsByTags(tags).thenApply(obj -> { 
        if (configuration.getBoolean("useOutputBeanValidation")) {
            for (Pet curItem : obj) {
                OpenAPIUtils.validate(curItem);
            }
        }
        return obj;
    });
    stage.thenApply(obj -> {
        JsonNode result = mapper.valueToTree(obj);
        return ok(result);
    });
}
 
Example 15
@ApiAction
public CompletionStage<Result> getPetById(Long petId) throws Exception {
    CompletionStage<Pet> stage = imp.getPetById(petId).thenApply(obj -> { 
        if (configuration.getBoolean("useOutputBeanValidation")) {
            OpenAPIUtils.validate(obj);
        }
        return obj;
    });
    stage.thenApply(obj -> {
        JsonNode result = mapper.valueToTree(obj);
        return ok(result);
    });
}
 
Example 16
/**
 * Return null if the argument is an "unsaved" entity (ie. one with no existing database row), or the
 * input argument otherwise.  This is how Hibernate avoids foreign key constraint violations.
 *
 * @param value An entity attribute value
 * @param propertyName An entity attribute name
 * @param type An entity attribute type
 *
 * @return {@code null} if the argument is an unsaved entity; otherwise return the argument.
 */
private CompletionStage<Object> nullifyTransientReferences(Object value, String propertyName, Type type) {
	final CompletionStage<Object> result;
	if ( value == null ) {
		return null;
	}
	else if ( type.isEntityType() ) {
		final EntityType entityType = (EntityType) type;
		if ( entityType.isOneToOne() ) {
			return null;
		}
		else {
			// if we're dealing with a lazy property, it may need to be
			// initialized to determine if the value is nullifiable
			CompletionStage<Object> fetcher;
			if ( isDelete
					&& value == LazyPropertyInitializer.UNFETCHED_PROPERTY
					&& !session.getPersistenceContextInternal().isNullifiableEntityKeysEmpty() ) {
				throw new UnsupportedOperationException("lazy property initialization not supported");
//				fetcher = ( (LazyPropertyInitializer) persister ).initializeLazyProperty( propertyName, self, session );
			}
			else {
				fetcher = CompletionStages.completedFuture( value );
			}
			result = fetcher.thenCompose( fetchedValue -> {
				if ( fetchedValue == null ) {
					// The uninitialized value was initialized to null
					return CompletionStages.nullFuture();
				}
				else {
					// If the value is not nullifiable, make sure that the
					// possibly initialized value is returned.
					return isNullifiable( entityType.getAssociatedEntityName(), fetchedValue )
							.thenApply( trans -> trans ? null : fetchedValue );
				}
			} );
		}
	}
	else if ( type.isAnyType() ) {
		result = isNullifiable( null, value ).thenApply( trans -> trans  ? null : value );
	}
	else if ( type.isComponentType() ) {
		final CompositeType actype = (CompositeType) type;
		final Object[] values = actype.getPropertyValues( value, session );
		CompletionStage<Void> nullifier = nullifyTransientReferences(
				propertyName,
				values,
				actype.getSubtypes(),
				actype.getPropertyNames()
		);
		if ( nullifier == null ) {
			return null;
		}
		else {
			result = nullifier.thenAccept( v -> actype.setPropertyValues( value, values, EntityMode.POJO ) )
					.thenApply( v -> value );
		}
	}
	else {
		return null;
	}

	return result.thenApply( returnedValue -> {
		trackDirt( value, propertyName, returnedValue );
		return returnedValue;
	} );
}
 
Example 17
Source Project: component-runtime   File: Responses.java    License: Apache License 2.0 4 votes vote down vote up
public static CompletionStage<Response> decorate(final CompletionStage<Response> source) {
    return source.thenApply(Responses::decorate);
}
 
Example 18
@Incoming("in")
@Outgoing("out")
public CompletionStage<Message<String>> processMessageCS(Message<Integer> in) {
    CompletionStage<String> cs = invokeService(in.getPayload());
    return cs.thenApply(in::withPayload);
}
 
Example 19
Source Project: immutables   File: AsyncFetcherDelegate.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public CompletionStage<Optional<T>> oneOrNone() {
  CompletionStage<List<T>> future = Publishers.toListFuture(fetcher.oneOrNone());
  return future.thenApply(list -> list.isEmpty() ? Optional.empty() : Optional.ofNullable(list.get(0)));
}
 
Example 20
Source Project: java-async-util   File: StageSupport.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Performs a function with an asynchronously acquired {@link AutoCloseable auto closeable},
 * ensuring that the resource is {@link AutoCloseable#close() closed} after the function runs.
 * Similar to a try-with-resources block, the resource will be closed even if {@code fn} throws an
 * exception.
 *
 * <p>
 * The returned stage will complete exceptionally in the following scenarios
 *
 * <ol>
 * <li>{@code resource} completes exceptionally
 * <li>{@code fn} throws an exception
 * <li>{@link AutoCloseable#close()} throws an exception
 * </ol>
 *
 * Of these cases, only 2 and 3 can happen simultaneously - in this case, the exception thrown by
 * close will be added to the exception from {@code fn} as a suppressed exception. If
 * {@link AutoCloseable#close()} throws a non-runtime exception, it will be wrapped in a
 * {@link CompletionException}.
 *
 * @param resource a {@link CompletionStage} that completes with an {@link AutoCloseable}
 * @param fn an function to perform that uses result of {@code resource} to produce a value
 * @param <T> the result type of {@code fn}
 * @param <R> the {@link AutoCloseable} resource type
 * @return a {@link CompletionStage} that completes with the result of {@code fn} or completes
 *         exceptionally
 */
public static <T, R extends AutoCloseable> CompletionStage<T> tryWith(
    final CompletionStage<R> resource,
    final Function<? super R, ? extends T> fn) {
  return resource.thenApply(r -> {
    try {
      try (R rtemp = r) {
        return fn.apply(r);
      }
    } catch (final RuntimeException rte) {
      throw rte;
    } catch (final Throwable ex) {
      throw new CompletionException(ex);
    }
  });
}