Example usage for java.util.concurrent CompletableFuture thenApply

List of usage examples for java.util.concurrent CompletableFuture thenApply

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture thenApply.

Prototype

public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn) 

Source Link

Usage

From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java

/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) 
 * @author Alex/* w ww.  j a v  a 2  s  . c  om*/
 */
@SuppressWarnings("unchecked")
public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate,
        final Optional<QueryComponent<T>> extra_query,
        final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform,
        final Map<String, BiFunction<Object, Object[], Object>> interceptors,
        final Optional<BiFunction<Object, Object[], Object>> default_interceptor) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());

            // First off, apply the extra term to any relevant args:
            final Object[] args_with_extra_query_pretransform = query_transform.map(q -> {
                return (null != args) ? Arrays.stream(args)
                        .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                ? q.apply((QueryComponent<T>) o)
                                : o)
                        .collect(Collectors.toList()).toArray() : args;
            }).orElse(args);

            final Object[] args_with_extra_query = extra_query.map(q -> {
                return (null != args_with_extra_query_pretransform)
                        ? Arrays.stream(args_with_extra_query_pretransform)
                                .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                        ? CrudUtils.allOf((QueryComponent<T>) o, q)
                                        : o)
                                .collect(Collectors.toList()).toArray()
                        : args_with_extra_query_pretransform;
            }).orElse(args_with_extra_query_pretransform);

            // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId
            final Object o = Lambdas.get(() -> {
                final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz)
                        ? (SingleQueryComponent<T>) CrudUtils.allOf()
                        : CrudUtils.allOf(clazz);

                try {
                    if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec
                        return delegate.countObjectsBySpec(extra_query.get());
                    } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query
                        if (1 == args.length) {
                            return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(),
                                    base_query.when(JsonUtils._ID, args[0])));
                        } else {
                            return delegate.getObjectBySpec(
                                    CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                    (List<String>) args[1], (Boolean) args[2]);
                        }
                    } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) {
                        CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get());
                        return l.thenApply(ll -> ll > 0);
                    } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query
                        return delegate.deleteObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])));
                    } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query
                        return delegate.updateObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                Optional.empty(), (UpdateComponent<T>) args[1]);
                    } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        Optional<QueryComponent<JsonNode>> json_extra_query = extra_query
                                .map(qc -> qc.toJson());
                        return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query,
                                Optional.empty(), interceptors, default_interceptor);
                    } else { // wrap any CrudService types
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        return (null != o_internal)
                                && ICrudService.class.isAssignableFrom(o_internal.getClass())
                                        ? intercept(clazz, (ICrudService<T>) o_internal, extra_query,
                                                Optional.empty(), interceptors, default_interceptor)
                                        : o_internal;
                    }
                } catch (IllegalAccessException ee) {
                    throw new RuntimeException(ee);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getCause().getMessage(), e);
                }
            });

            return interceptors
                    .getOrDefault(m.getName(),
                            default_interceptor.orElse(CrudServiceUtils::identityInterceptor))
                    .apply(o, args_with_extra_query);
        }
    };

    return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass())
            ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(),
                    new Class[] { ICrudService.IReadOnlyCrudService.class }, handler)
            : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(),
                    new Class[] { ICrudService.class }, handler);
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java

/** Update a bucket based on a new V1 source
 * @param key//  w  w w.j  a va  2 s  .  c om
 * @param bucket_mgmt
 * @param underlying_bucket_status_mgmt
 * @param source_db
 * @return
 */
@SuppressWarnings("unchecked")
protected static ManagementFuture<Supplier<Object>> updateBucket(final String key,
        final IManagementCrudService<DataBucketBean> bucket_mgmt,
        final IManagementCrudService<DataBucketStatusBean> underlying_bucket_status_mgmt,
        final ICrudService<JsonNode> source_db) {
    _logger.info(ErrorUtils.get("Source {0} was modified, updating bucket", key));

    // Get the full source from V1
    // .. and from V2: the existing bucket and the existing status

    // OK first off, we're immediately going to update the bucket's modified time
    // since otherwise if the update fails then we'll get stuck updating it every iteration...
    // (ie this is the reason we set isApproved:false in the create case)
    //(this ugliness just handles the test case already running on the underlying service)
    final ICrudService<DataBucketBean> underlying_bucket_db = bucket_mgmt
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.empty()).orElse(bucket_mgmt);

    underlying_bucket_db.updateObjectById(getBucketIdFromV1SourceKey(key),
            CrudUtils.update(DataBucketBean.class).set(DataBucketBean::modified, new Date()));

    final SingleQueryComponent<JsonNode> v1_query = CrudUtils.allOf().when("key", key);
    final CompletableFuture<Optional<JsonNode>> f_v1_source = source_db.getObjectBySpec(v1_query);

    return FutureUtils.denestManagementFuture(
            f_v1_source.<ManagementFuture<Supplier<Object>>>thenApply(Lambdas.wrap_u(v1_source -> {
                // Once we have all the queries back, get some more information
                final boolean is_now_suspended = safeJsonGet("searchCycle_secs", v1_source.get()).asInt(1) < 0;
                final DataBucketBean new_object = getBucketFromV1Source(v1_source.get());

                // (Update status in underlying status store so don't trip a spurious harvest call)
                CompletableFuture<?> update = underlying_bucket_status_mgmt.updateObjectById(
                        getBucketIdFromV1SourceKey(key), CrudUtils.update(DataBucketStatusBean.class)
                                .set(DataBucketStatusBean::suspended, is_now_suspended));

                // Then update the management db

                return FutureUtils.denestManagementFuture(
                        update.thenApply(__ -> bucket_mgmt.storeObject(new_object, true)));
            })).exceptionally(e -> {
                return FutureUtils
                        .<Supplier<Object>>createManagementFuture(
                                FutureUtils.returnError(new RuntimeException(e)),
                                CompletableFuture.completedFuture(Arrays.asList(new BasicMessageBean(new Date(),
                                        false, "IkanowV1SyncService_Buckets", "updateBucket", null,
                                        ErrorUtils.getLongForm("{0}", e), null))));
            }));
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.SteamUser.java

public CompletableFuture<List<SteamBanStatus>> getPlayerBans(Long... steamIds) {
    CompletableFuture<JsonObject> json = sendRequest(new GetPlayerBans(VERSION_1, steamIds));
    return json.thenApply(root -> {
        JsonArray players = root.getAsJsonArray("players");
        Type type = new TypeToken<List<SteamBanStatus>>() {
        }.getType();/*w ww.java2s . co m*/
        return builder().fromJson(players, type);
    });
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.SteamUser.java

public CompletableFuture<List<SteamGroupId>> getUserGroupList(long steamId) {
    CompletableFuture<JsonObject> json = sendRequest(new GetUserGroupList(VERSION_1, steamId));
    return json.thenApply((JsonObject root) -> {
        JsonArray groups = root.getAsJsonObject("response").getAsJsonArray("groups");
        Type type = new TypeToken<List<SteamGroupId>>() {
        }.getType();/*from  w  w w  . j  a va2  s.c  om*/
        return builder().fromJson(groups, type);
    });
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.SteamUser.java

public CompletableFuture<List<SteamPlayerProfile>> getPlayerProfiles(Long... steamIds) {
    CompletableFuture<JsonObject> json = sendRequest(new GetPlayerSummaries(VERSION_2, steamIds));
    return json.thenApply(root -> {
        JsonArray players = root.getAsJsonObject("response").getAsJsonArray("players");
        Type type = new TypeToken<List<SteamPlayerProfile>>() {
        }.getType();/*from   w w w .j a v a 2 s.  co m*/
        if (players != null) {
            return builder().fromJson(players, type);
        }
        return null;
    });
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.SteamUser.java

public CompletableFuture<List<SteamFriend>> getFriendList(long steamId, String relationship) {
    CompletableFuture<JsonObject> json = sendRequest(new GetFriendList(VERSION_1, steamId, relationship));
    return json.thenApply(root -> {
        JsonArray friendsList = root.getAsJsonObject("friendslist").getAsJsonArray("friends");
        Type type = new TypeToken<List<SteamFriend>>() {
        }.getType();/*from  w  w  w .  j  av  a  2 s.com*/
        return builder().fromJson(friendsList, type);
    });
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.interfaces.SteamUser.java

public CompletableFuture<Long> getSteamIdFromVanityUrl(String urlPath, VanityUrlType type) {
    CompletableFuture<JsonObject> json = sendRequest(new ResolveVanityURL(VERSION_1, urlPath, type));
    return json.thenApply(root -> {
        JsonObject response = root.getAsJsonObject("response");
        int success = response.getAsJsonPrimitive("success").getAsInt();
        if (success == 1) {
            String steamId = response.getAsJsonPrimitive("steamid").getAsString();
            if (!StringUtils.isEmpty(steamId) && StringUtils.isNumeric(steamId)) {
                return Long.valueOf(steamId);
            }// w  ww. j  a  v a2  s.c  o  m
        }
        return null;
    });
}

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private CompletableFuture<Optional<DecodedImage>> imageDataFromResponse(int imageIndex, IndexMap indexMap,
        CompletableFuture<ResponseEntity<byte[]>> response) {
    return response.thenApply(bytes -> decompressImage(imageIndex, indexMap, bytes));
}

From source file:pt.isel.mpd.monitrgw.webapi.MonitrApiAsyncNio.java

public CompletableFuture<MonitrStockAnalysisDtoData> GetStockAnalysis(String stockSymbol) {
    CompletableFuture<MonitrStockAnalysisDto> stockAnalysis = callMonitrAction(MonitrStockAnalysisDto.class,
            "/v2/symbol/mentions?apikey=%s&symbol=%s&startDay=0&endDay=1", MONITR_API_KEY, stockSymbol);
    return stockAnalysis.thenApply(saDto -> saDto.analysis.get(0));
}

From source file:de.ks.file.FileStore.java

public CompletableFuture<FileReference> getReference(File file) {
    if (!file.exists()) {
        throw new IllegalArgumentException("File " + file + " does not exist");
    }/*w  w w. j  av a  2 s  .c  om*/
    CompletableFuture<String> md5Sum = CompletableFuture.supplyAsync(() -> getMd5(file), executorService);

    return md5Sum.thenApply(md5 -> resolveReference(md5, file));
}