Example usage for java.util.function Consumer accept

List of usage examples for java.util.function Consumer accept

Introduction

In this page you can find the example usage for java.util.function Consumer accept.

Prototype

void accept(T t);

Source Link

Document

Performs this operation on the given argument.

Usage

From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java

@Override
public List<InformationPreviewItem> loadModel(Consumer<List<InformationPreviewItem>> furtherProcessing) {
    List<Class<? extends Information<?>>> classes = new ArrayList<>(
            Arrays.asList(TextInfo.class, ChartInfo.class, UmlDiagramInfo.class));
    if (loadingHint.getType() != null) {
        classes.clear();//from   w  w  w  . j  a  v a  2  s .  com
        classes.add(loadingHint.getType());
    }
    String name = "%" + StringUtils.replace(loadingHint.getName(), "*", "%") + "%";
    List<String> tags = loadingHint.getTags();
    Category category = loadingHint.getCategory();

    List<InformationPreviewItem> retval = PersistentWork.read(em -> {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        List<InformationPreviewItem> items = new ArrayList<>();

        for (Class<? extends Information<?>> clazz : classes) {
            List<InformationPreviewItem> results = getResults(name, tags, category, em, builder, clazz);
            results.forEach(r -> r.setType(clazz));
            items.addAll(results);
        }
        furtherProcessing.accept(items);
        return items;
    });

    return retval;
}

From source file:net.dv8tion.jda.handle.EntityBuilder.java

public Guild createGuildFirstPass(JSONObject guild, Consumer<Guild> secondPassCallback) {
    String id = guild.getString("id");
    GuildImpl guildObj = ((GuildImpl) api.getGuildMap().get(id));
    if (guildObj == null) {
        guildObj = new GuildImpl(api, id);
        api.getGuildMap().put(id, guildObj);
    }/*  w  ww . j av  a 2  s. c om*/
    if (guild.has("unavailable") && guild.getBoolean("unavailable")) {
        guildObj.setAvailable(false);
        if (secondPassCallback != null) {
            secondPassCallback.accept(guildObj);
        }
        GuildLock.get(api).lock(id);
        return guildObj;
    }
    guildObj.setAvailable(true).setIconId(guild.isNull("icon") ? null : guild.getString("icon"))
            .setRegion(Region.fromKey(guild.getString("region"))).setName(guild.getString("name"))
            .setAfkTimeout(guild.getInt("afk_timeout"))
            .setAfkChannelId(guild.isNull("afk_channel_id") ? null : guild.getString("afk_channel_id"))
            .setVerificationLevel(Guild.VerificationLevel.fromKey(guild.getInt("verification_level")));

    JSONArray roles = guild.getJSONArray("roles");
    for (int i = 0; i < roles.length(); i++) {
        Role role = createRole(roles.getJSONObject(i), guildObj.getId());
        guildObj.getRolesMap().put(role.getId(), role);
        if (role.getId().equals(guildObj.getId()))
            guildObj.setPublicRole(role);
    }
    if (guild.has("emojis")) {
        JSONArray emojiArr = guild.getJSONArray("emojis");
        for (int i = 0; i < emojiArr.length(); i++) {
            JSONObject obj = emojiArr.getJSONObject(i);
            String emojID = obj.getString("id");
            Emote emote = api.getEmoteById(emojID);
            if (emote == null)
                emote = new EmoteImpl(obj.getString("name"), emojID);
            api.getEmoteMap().putIfAbsent(emojID, emote);
            guildObj.getEmoteMap().put(emojID, emote);
            ((EmoteImpl) emote).addGuild(guildObj);
        }
    } else
        JDAImpl.LOG.warn("Guild Didn't have field called 'emojis'. Identifier: " + guildObj.getId());

    if (guild.has("members")) {
        JSONArray members = guild.getJSONArray("members");
        createGuildMemberPass(guildObj, members);
    }

    User owner = api.getUserById(guild.getString("owner_id"));
    if (owner != null)
        guildObj.setOwner(owner);

    if (guild.has("presences")) {
        JSONArray presences = guild.getJSONArray("presences");
        for (int i = 0; i < presences.length(); i++) {
            JSONObject presence = presences.getJSONObject(i);
            UserImpl user = ((UserImpl) api.getUserMap().get(presence.getJSONObject("user").getString("id")));
            if (user == null) {
                //corresponding user to presence not found... ignoring
                continue;
            }
            Game presenceGame = null;
            if (!presence.isNull("game") && !presence.getJSONObject("game").isNull("name")) {
                presenceGame = new GameImpl(presence.getJSONObject("game").get("name").toString(),
                        presence.getJSONObject("game").isNull("url") ? null
                                : presence.getJSONObject("game").get("url").toString(),
                        presence.getJSONObject("game").isNull("type") ? Game.GameType.DEFAULT
                                : Game.GameType.fromKey((int) presence.getJSONObject("game").get("type")));
            }
            user.setCurrentGame(presenceGame)
                    .setOnlineStatus(OnlineStatus.fromKey(presence.getString("status")));
        }
    }

    if (guild.has("channels")) {
        JSONArray channels = guild.getJSONArray("channels");

        for (int i = 0; i < channels.length(); i++) {
            JSONObject channel = channels.getJSONObject(i);
            ChannelType type = ChannelType.fromId(channel.getInt("type"));
            if (type == ChannelType.TEXT) {
                TextChannel newChannel = createTextChannel(channel, guildObj.getId());
                if (newChannel.getId().equals(guildObj.getId()))
                    guildObj.setPublicChannel(newChannel);
            } else if (type == ChannelType.VOICE) {
                createVoiceChannel(channel, guildObj.getId());
            } else
                JDAImpl.LOG.fatal(
                        "Received a channel for a guild that isn't a text or voice channel. JSON: " + channel);
        }
    }

    if (guild.has("voice_states")) {
        JSONArray voiceStates = guild.getJSONArray("voice_states");
        for (int i = 0; i < voiceStates.length(); i++) {
            JSONObject voiceState = voiceStates.getJSONObject(i);
            User user = api.getUserById(voiceState.getString("user_id"));
            if (user == null) {
                //voice-status of offline user -> ignore
                continue;
            }

            try {
                VoiceStatus voiceStatus = createVoiceStatus(voiceState, guildObj, user);
                ((VoiceChannelImpl) voiceStatus.getChannel()).getUsersModifiable().add(user);
            } catch (IllegalArgumentException ignored) {
                //Ignore this: weird behaviour of Discord itself gives us presences to vc that were deleted
            }
        }
    }

    //We allow Guild creation without second pass for when JDA itself creates a NEW Guild. We won't need
    // to worry about there being a lack of offline Users because there wont be -any users or, at the very
    // most, the only User will be the JDA user that just created the new Guild.
    //This fall through is used by JDAImpl.createGuild(String, Region).
    if (secondPassCallback != null && guild.has("large") && guild.getBoolean("large")) {
        HashMap<String, JSONObject> cachedGuildJsons = cachedJdaGuildJsons.get(api);
        HashMap<String, Consumer<Guild>> cachedGuildCallbacks = cachedJdaGuildCallbacks.get(api);
        cachedGuildJsons.put(id, guild);
        cachedGuildCallbacks.put(id, secondPassCallback);
        GuildMembersChunkHandler.setExpectedGuildMembers(api, id, guild.getInt("member_count"));
        if (api.getClient().isReady()) {
            JSONObject obj = new JSONObject().put("op", 8).put("d",
                    new JSONObject().put("guild_id", id).put("query", "").put("limit", 0));
            api.getClient().send(obj.toString());
        } else {
            new ReadyHandler(api, 0).onGuildNeedsMembers(guildObj);
        }
        GuildLock.get(api).lock(id);
        return null;//Nothing should be using the return of this method besides JDAImpl.createGuild(String, Region)
    }

    JSONArray channels = guild.getJSONArray("channels");
    createGuildChannelPass(guildObj, channels);

    if (secondPassCallback != null) {
        secondPassCallback.accept(guildObj);
        GuildLock.get(api).unlock(guildObj.getId());
        return null;//Nothing should be using the return of this method besides JDAImpl.createGuild(String, Region)
    }

    GuildLock.get(api).unlock(guildObj.getId());
    return guildObj;
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private void validateSSLConfigurationIsReloaded(Settings settings, Environment env,
        Consumer<SSLContext> preChecks, Runnable modificationFunction, Consumer<SSLContext> postChecks)
        throws Exception {

    final CountDownLatch reloadLatch = new CountDownLatch(1);
    final SSLService sslService = new SSLService(settings, env);
    final SSLConfiguration config = sslService.sslConfiguration(Settings.EMPTY);
    new SSLConfigurationReloader(settings, env, sslService, resourceWatcherService) {
        @Override//from w w w  . j  ava2 s. co m
        void reloadSSLContext(SSLConfiguration configuration) {
            super.reloadSSLContext(configuration);
            reloadLatch.countDown();
        }
    };
    // Baseline checks
    preChecks.accept(sslService.sslContextHolder(config).sslContext());

    assertEquals("nothing should have called reload", 1, reloadLatch.getCount());

    // modify
    modificationFunction.run();
    reloadLatch.await();
    // checks after reload
    postChecks.accept(sslService.sslContextHolder(config).sslContext());
}

From source file:org.apache.hadoop.hbase.client.AsyncSingleRequestRpcRetryingCaller.java

private void onError(Throwable error, Supplier<String> errMsg, Consumer<Throwable> updateCachedLocation) {
    error = translateException(error);/*  ww w  .  java 2s .c o m*/
    if (tries > startLogErrorsCnt) {
        LOG.warn(errMsg.get(), error);
    }
    RetriesExhaustedException.ThrowableWithExtraContext qt = new RetriesExhaustedException.ThrowableWithExtraContext(
            error, EnvironmentEdgeManager.currentTime(), "");
    exceptions.add(qt);
    if (error instanceof DoNotRetryIOException || tries >= maxAttempts) {
        completeExceptionally();
        return;
    }
    long delayNs;
    if (operationTimeoutNs > 0) {
        long maxDelayNs = operationTimeoutNs - (System.nanoTime() - startNs);
        if (maxDelayNs <= 0) {
            completeExceptionally();
            return;
        }
        delayNs = Math.min(maxDelayNs, getPauseTime(pauseNs, tries - 1));
    } else {
        delayNs = getPauseTime(pauseNs, tries - 1);
    }
    updateCachedLocation.accept(error);
    tries++;
    retryTimer.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            // always restart from beginning.
            locateThenCall();
        }
    }, delayNs, TimeUnit.NANOSECONDS);
}

From source file:com.github.erchu.beancp.DeclarativeMapImpl.java

@Override
public <T> DeclarativeMap<S, D> bindConstant(final T constantValue, final Consumer<T> toMember,
        final BindingOption<S, D, T>... options) {
    notNull(toMember, "toMember");

    if (mode == MapMode.CONFIGURATION) {
        if (_afterMapExecuted) {
            throw new MapperConfigurationException(INVALID_STATEMENT_ORDER_MESSAGE);
        }//from  www .ja va 2s.  c o m

        _bindBindConstantOrMapExecuted = true;
    }

    if (mode == MapMode.CONFIGURATION) {
        for (BindingOption<S, D, T> i : options) {
            if (i.getNullSubstitution() != null) {
                throw new MapperConfigurationException(
                        "Null substitution option not allowed for bindConstant.");
            }
        }
    }

    if (mode == MapMode.EXECUTION) {
        boolean map = shouldBeMapped(options);

        if (map) {
            toMember.accept(constantValue);
        }
    }

    return this;
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

private void startAndCreateCallbackHandlerService(String systemContainerName,
        BiConsumer<AbstractCallbackServiceHandler.CallbackServiceHandlerState, Boolean> actualCallback,
        Consumer<ServiceTaskCallback> caller) {
    if (actualCallback == null) {
        caller.accept(ServiceTaskCallback.createEmpty());
        return;//from  ww w. ja  va2  s .co m
    }
    String callbackLink = ManagementUriParts.REQUEST_CALLBACK_HANDLER_TASKS + UUID.randomUUID().toString();
    AbstractCallbackServiceHandler.CallbackServiceHandlerState body = new AbstractCallbackServiceHandler.CallbackServiceHandlerState();
    body.documentSelfLink = callbackLink;
    body.customProperties = new HashMap<>();
    body.customProperties.put(SYSTEM_CONTAINER_NAME, systemContainerName);
    URI callbackUri = UriUtils.buildUri(getHost(), callbackLink);

    Operation startPost = Operation.createPost(callbackUri).setBody(body).setCompletion((o, e) -> {
        if (e != null) {
            logSevere("Failure creating callback handler. Error %s", Utils.toString(e));
            return;
        }
        caller.accept(ServiceTaskCallback.create(callbackUri.toString()));
    });

    SystemContainerOperationCallbackHandler service = new SystemContainerOperationCallbackHandler(
            actualCallback);
    service.setCompletionCallback(() -> getHost().stopService(service));
    getHost().startService(startPost, service);
}

From source file:com.vmware.photon.controller.deployer.xenon.util.VibUtils.java

public static Runnable removeVibs(HostService.State hostState, Service service,
        Consumer<Throwable> completion) {

    return new Runnable() {

        @Override/*w  w w.j  av a 2s  .  c om*/
        public void run() {
            try {
                DeployerContext deployerContext = HostUtils.getDeployerContext(service);
                for (String vibName : deployerContext.getVibUninstallOrder()) {
                    ServiceUtils.logInfo(service, "Uninstalling vib [%s] from host [%s]", vibName,
                            hostState.hostAddress);
                    List<String> command = Arrays.asList("./" + DELETE_VIB_SCRIPT_NAME, hostState.hostAddress,
                            hostState.userName, hostState.password, vibName);

                    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
                            DELETE_VIB_SCRIPT_NAME + "-" + hostState.hostAddress + "-"
                                    + UUID.randomUUID().toString() + ".log");

                    ScriptRunner scriptRunner = new ScriptRunner.Builder(command,
                            deployerContext.getScriptTimeoutSec())
                                    .directory(deployerContext.getScriptDirectory())
                                    .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile))
                                    .redirectErrorStream(true).build();

                    int scriptReturnCode = scriptRunner.call();

                    if (scriptReturnCode != 0) {
                        ServiceUtils.logSevere(service,
                                DELETE_VIB_SCRIPT_NAME + " returned " + scriptReturnCode);
                        ServiceUtils.logSevere(service,
                                "Script output: " + FileUtils.readFileToString(scriptLogFile));
                        throw new IllegalStateException("Installing VIB file " + vibName + " to host "
                                + hostState.hostAddress + " failed with exit code " + scriptReturnCode);
                    }
                }
            } catch (Throwable t) {
                completion.accept(t);
            }
            completion.accept(null);
        }

    };
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

private void createDiscoveredContainers(List<ContainerState> containerStates, Consumer<Throwable> callback) {
    if (containerStates.isEmpty()) {
        callback.accept(null);
    } else {//w  ww .j  a  v  a  2 s. c om
        AtomicInteger counter = new AtomicInteger(containerStates.size());
        for (ContainerState containerState : containerStates) {
            if (containerState.names == null || containerState.names.isEmpty()) {
                logInfo("Names not set for container: %s", containerState.documentSelfLink);
                if (counter.decrementAndGet() == 0) {
                    callback.accept(null);
                }
                continue;
            }
            // check again if the container state already exists by names. This is needed in
            // cluster mode not to create container states that we already have
            Operation operation = Operation.createGet(this,
                    UriUtils.buildUriPath(ContainerFactoryService.SELF_LINK, containerState.names.get(0)))
                    .setCompletion((o, ex) -> {
                        if (o.getStatusCode() == Operation.STATUS_CODE_NOT_FOUND) {
                            createDiscoveredContainer(callback, counter, containerState);
                        } else if (ex != null) {
                            logSevere("Failed to get container %s : %s", containerState.names, ex.getMessage());
                            callback.accept(ex);
                        } else {
                            if (counter.decrementAndGet() == 0) {
                                callback.accept(null);
                            }
                        }

                    });
            sendRequest(operation);
        }

    }
}

From source file:org.icgc.dcc.portal.repository.FileRepository.java

private SearchResponse searchFileCentric(Consumer<SearchRequestBuilder> queryCustomizer, String[] fields) {
    val size = 5000;

    return searchFileCentric("Preparing data table export", request -> {
        request.setSearchType(SCAN).setSize(size).setScroll(KEEP_ALIVE).addFields(fields);

        queryCustomizer.accept(request);
    });/*  w  ww  . java2s .  co m*/
}

From source file:com.github.erchu.beancp.DeclarativeMapImpl.java

@Override
public <T> DeclarativeMap<S, D> bind(final Supplier<T> fromFunction, final Consumer<T> toMember,
        final BindingOption<S, D, T>... options) {
    notNull(fromFunction, "fromFunction");
    notNull(toMember, "toMember");

    if (mode == MapMode.CONFIGURATION) {
        if (_afterMapExecuted) {
            throw new MapperConfigurationException(INVALID_STATEMENT_ORDER_MESSAGE);
        }/*from ww w.  ja v  a  2 s  . c om*/

        _bindBindConstantOrMapExecuted = true;
    }

    if (mode == MapMode.EXECUTION) {
        boolean map = shouldBeMapped(options);

        if (map) {
            T getValue = fromFunction.get();

            if (getValue == null) {
                for (BindingOption<S, D, T> i : options) {
                    if (i.getNullSubstitution() != null) {
                        getValue = i.getNullSubstitution();
                        break;
                    }
                }
            }

            toMember.accept(getValue);
        }
    }

    return this;
}