Example usage for java.util Set forEach

List of usage examples for java.util Set forEach

Introduction

In this page you can find the example usage for java.util Set forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:org.apache.bookkeeper.statelib.impl.kv.RocksdbKVStore.java

private void closeIters() {
    Set<KVIterator> iterators;
    synchronized (kvIters) {
        iterators = Sets.newHashSet(kvIters);
    }//  w ww  .ja v  a  2  s .  c  o  m
    iterators.forEach(KVIterator::close);
}

From source file:se.uu.it.cs.recsys.dataloader.impl.NormalizedCourseSelectionLoader.java

private void loadToDB(Map.Entry<String, Set<String>> singleSutdentSelection) {
    Integer studentId = Integer.valueOf(singleSutdentSelection.getKey());

    singleSutdentSelection.getValue().forEach(courseCode -> {
        Set<CourseNormalization> courseNormalizationSet = this.courseNormalizationRepository
                .findByFromEarlierCode(courseCode);

        if (courseNormalizationSet == null || courseNormalizationSet.isEmpty()) {

            Integer courseId = this.courseRepository.findByCodeAndTaughtYearAndStartPeriod(courseCode,
                    FixedValueForPreviousYears.COURSE_TAUGHT_YEAR.shortValue(),
                    FixedValueForPreviousYears.COURSE_START_PERIOD.shortValue()).getAutoGenId();

            this.courseSelectionNormalizedRepository.save(new CourseSelectionNormalized(studentId, courseId));

        } else {//  w  w w.  ja  va  2s. c  o m

            courseNormalizationSet.forEach(courseNormalization -> {
                String toCode = courseNormalization.getCourseNormalizationPK().getToLaterCode();

                Set<Course> courseSetWithTargetCode = this.courseRepository.findByCode(toCode);

                // same course code can have two courseId, for both past and future
                if (courseSetWithTargetCode != null) {
                    courseSetWithTargetCode.forEach(course -> {
                        // normalize course selection record to plan year
                        if (!course.getTaughtYear()
                                .equals(FixedValueForPreviousYears.COURSE_TAUGHT_YEAR.shortValue())) {
                            this.courseSelectionNormalizedRepository
                                    .save(new CourseSelectionNormalized(studentId, course.getAutoGenId()));
                        }
                    });
                }
            });

        }

    });
}

From source file:org.finra.herd.service.impl.IndexSearchServiceImpl.java

/**
 * Validates a set of search match fields. This method also trims and lowers the match fields.
 *
 * @param match the search match fields to be validated
 *//*from w ww .ja v  a2  s. co m*/
private void validateSearchMatchFields(Set<String> match) {
    // Create a local copy of the match fields set so that we can stream it to modify the match fields set
    Set<String> localCopy = new HashSet<>(match);

    // Clear the match set
    match.clear();

    // Add to the match set field the strings both trimmed and lower cased and filter out empty and null strings
    localCopy.stream().filter(StringUtils::isNotBlank).map(String::trim).map(String::toLowerCase)
            .forEachOrdered(match::add);

    // Validate the field names
    match.forEach(field -> Assert.isTrue(getValidSearchMatchFields().contains(field),
            String.format("Search match field \"%s\" is not supported.", field)));
}

From source file:ai.susi.mind.SusiMind.java

/**
 * This is the core principle of creativity: being able to match a given input
 * with problem-solving knowledge./*ww  w .j av  a  2  s. c  om*/
 * This method finds ideas (with a query instantiated skills) for a given query.
 * The skills are selected using a scoring system and pattern matching with the query.
 * Not only the most recent user query is considered for skill selection but also
 * previously requested queries and their answers to be able to set new skill selections
 * in the context of the previous conversation.
 * @param query the user input
 * @param previous_argument the latest conversation with the same user
 * @param maxcount the maximum number of ideas to return
 * @return an ordered list of ideas, first idea should be considered first.
 */
public List<SusiIdea> creativity(String query, SusiThought latest_thought, int maxcount) {
    // tokenize query to have hint for idea collection
    final List<SusiIdea> ideas = new ArrayList<>();
    this.reader.tokenizeSentence(query).forEach(token -> {
        Set<SusiSkill> skill_for_category = this.skilltrigger.get(token.categorized);
        Set<SusiSkill> skill_for_original = token.original.equals(token.categorized) ? null
                : this.skilltrigger.get(token.original);
        Set<SusiSkill> r = new HashSet<>();
        if (skill_for_category != null)
            r.addAll(skill_for_category);
        if (skill_for_original != null)
            r.addAll(skill_for_original);
        r.forEach(skill -> ideas.add(new SusiIdea(skill).setIntent(token)));
    });

    for (SusiIdea idea : ideas)
        DAO.log("idea.phrase-1: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // add catchall skills always (those are the 'bad ideas')
    Collection<SusiSkill> ca = this.skilltrigger.get(SusiSkill.CATCHALL_KEY);
    if (ca != null)
        ca.forEach(skill -> ideas.add(new SusiIdea(skill)));

    // create list of all ideas that might apply
    TreeMap<Long, List<SusiIdea>> scored = new TreeMap<>();
    AtomicLong count = new AtomicLong(0);
    ideas.forEach(idea -> {
        int score = idea.getSkill().getScore().score;
        long orderkey = Long.MAX_VALUE - ((long) score) * 1000L + count.incrementAndGet();
        List<SusiIdea> r = scored.get(orderkey);
        if (r == null) {
            r = new ArrayList<>();
            scored.put(orderkey, r);
        }
        r.add(idea);
    });

    // make a sorted list of all ideas
    ideas.clear();
    scored.values().forEach(r -> ideas.addAll(r));

    for (SusiIdea idea : ideas)
        DAO.log("idea.phrase-2: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());

    // test ideas and collect those which match up to maxcount
    List<SusiIdea> plausibleIdeas = new ArrayList<>(Math.min(10, maxcount));
    for (SusiIdea idea : ideas) {
        SusiSkill skill = idea.getSkill();
        Collection<Matcher> m = skill.matcher(query);
        if (m.isEmpty())
            continue;
        // TODO: evaluate leading SEE flow commands right here as well
        plausibleIdeas.add(idea);
        if (plausibleIdeas.size() >= maxcount)
            break;
    }

    for (SusiIdea idea : plausibleIdeas) {
        DAO.log("idea.phrase-3: score=" + idea.getSkill().getScore().score + " : "
                + idea.getSkill().getPhrases().toString() + " " + idea.getSkill().getActionsClone());
        DAO.log("idea.phrase-3:   log=" + idea.getSkill().getScore().log);
    }

    return plausibleIdeas;
}

From source file:org.commonjava.indy.folo.ctl.FoloAdminController.java

private Set<TrackedContentEntry> recalculateEntrySet(final Set<TrackedContentEntry> entries, final String id,
        final AtomicBoolean failed) throws IndyWorkflowException {
    if (entries == null) {
        return null;
    }/*w  w w .jav a 2 s. c om*/

    DrainingExecutorCompletionService<TrackedContentEntry> recalculateService = new DrainingExecutorCompletionService<>(
            recalculationExecutor);

    detectOverloadVoid(() -> entries.forEach(entry -> recalculateService.submit(() -> {
        try {
            return recalculate(entry);
        } catch (IndyWorkflowException e) {
            logger.error(String.format("Tracking record: %s : Failed to recalculate: %s/%s (%s). Reason: %s",
                    id, entry.getStoreKey(), entry.getPath(), entry.getEffect(), e.getMessage()), e);

            failed.set(true);
        }
        return null;
    })));

    Set<TrackedContentEntry> result = new HashSet<>();
    try {
        recalculateService.drain(entry -> {
            if (entry != null) {
                result.add(entry);
            }
        });
    } catch (InterruptedException | ExecutionException e) {
        logger.error("Failed to recalculate metadata for Folo tracked content entries in: " + id, e);
        failed.set(true);
    }

    return result;
}

From source file:alfio.manager.SpecialPriceManager.java

public boolean sendCodeToAssignee(List<SendCodeModification> input, String eventName, int categoryId,
        String username) {//from   w ww .  j a v a2  s. c  o m
    final Event event = eventManager.getSingleEvent(eventName, username);
    final Organization organization = eventManager.loadOrganizer(event, username);
    Set<SendCodeModification> set = new LinkedHashSet<>(input);
    checkCodeAssignment(set, categoryId, event, username);
    Validate.isTrue(set.stream().allMatch(IS_CODE_PRESENT),
            "There are missing codes. Please check input file.");
    List<ContentLanguage> eventLanguages = i18nManager.getEventLanguages(event.getLocales());
    Validate.isTrue(!eventLanguages.isEmpty(),
            "No locales have been defined for the event. Please check the configuration");
    ContentLanguage defaultLocale = eventLanguages.contains(ContentLanguage.ENGLISH) ? ContentLanguage.ENGLISH
            : eventLanguages.get(0);
    set.forEach(m -> {
        Locale locale = Locale.forLanguageTag(StringUtils.defaultString(StringUtils.trimToNull(m.getLanguage()),
                defaultLocale.getLanguage()));
        Map<String, Object> model = TemplateResource.prepareModelForSendReservedCode(organization, event, m,
                eventManager.getEventUrl(event));
        notificationManager.sendSimpleEmail(event, m.getEmail(),
                messageSource.getMessage("email-code.subject", new Object[] { event.getDisplayName() }, locale),
                () -> templateManager.renderTemplate(event, TemplateResource.SEND_RESERVED_CODE, model,
                        locale));
        int marked = specialPriceRepository.markAsSent(ZonedDateTime.now(event.getZoneId()),
                m.getAssignee().trim(), m.getEmail().trim(), m.getCode().trim());
        Validate.isTrue(marked == 1, "Expected exactly one row updated, got " + marked);
    });
    return true;
}

From source file:org.duniter.elasticsearch.user.service.UserService.java

public String joinNamesFromPubkeys(Set<String> pubkeys, String separator, boolean minify) {
    Preconditions.checkNotNull(pubkeys);
    Preconditions.checkNotNull(separator);
    Preconditions.checkArgument(pubkeys.size() > 0);
    if (pubkeys.size() == 1) {
        String pubkey = pubkeys.iterator().next();
        String title = getProfileTitle(pubkey);
        return title != null ? title : (minify ? ModelUtils.minifyPubkey(pubkey) : pubkey);
    }//from   www .ja  v  a2s . c  o m

    Map<String, String> profileTitles = getProfileTitles(pubkeys);
    StringBuilder sb = new StringBuilder();
    pubkeys.forEach((pubkey) -> {
        String title = profileTitles != null ? profileTitles.get(pubkey) : null;
        sb.append(separator);
        sb.append(title != null ? title : (minify ? ModelUtils.minifyPubkey(pubkey) : pubkey));
    });

    return sb.substring(separator.length());
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void applyMultiVariablesToMap(Map<String, String> variables, Map<String, List<String>> target) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);

    Map<String, List<String>> newValues = new HashMap<>();
    Set removeSet = new HashSet<>();

    target.forEach((paramName, paramValues) -> {
        StringProperty paramNameProperty = new SimpleStringProperty(paramName);
        variableTokens.forEach((String originalName) -> {
            String[] variableNameParts = originalName.split("\\|");
            String variableName = variableNameParts[0];
            String variableNameMatchPattern = Pattern.quote("${" + originalName + "}");
            String val = variables.get(variableName);
            if (val == null) {
                val = "";
            }//from ww  w .j a v a2 s  .c om
            String variableValue = Matcher.quoteReplacement(val);
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            removeSet.add(paramNameProperty.get());
            removeSet.add(paramName);
            if (newValues.get(paramNameProperty.get()) == null) {
                newValues.put(paramNameProperty.get(), new ArrayList<>(paramValues.size()));
            }
            if (newValues.get(newParamName) == null) {
                newValues.put(newParamName, new ArrayList<>(paramValues.size()));
            }
            List<String> newParamValues = newValues.get(paramNameProperty.get());
            for (int i = 0; i < paramValues.size(); i++) {
                String newParamValue = newParamValues != null && newParamValues.size() > i
                        && newParamValues.get(i) != null ? newParamValues.get(i) : paramValues.get(i);

                // fix for removing JCR values (setting them to an empty
                // string deletes them from the JCR)
                if (null == newParamValue) {
                    newParamValue = "";
                }

                newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
                if (newParamName.contains("/") && newParamValue.equals("@" + newParamName)) {
                    // The upload name should actually be the file name, not the full path of the file.
                    removeSet.add(newParamName);
                    newValues.remove(newParamName);
                    newParamName = newParamName.substring(newParamName.lastIndexOf("/") + 1);
                    newValues.put(newParamName, newParamValues);
                }
                if (newValues.get(newParamName).size() == i) {
                    newValues.get(newParamName).add(newParamValue);
                } else {
                    newValues.get(newParamName).set(i, newParamValue);
                }
            }
            if (!paramNameProperty.get().equals(newParamName)) {
                newValues.remove(paramNameProperty.get());
            }
            paramNameProperty.set(newParamName);
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:io.gravitee.management.service.impl.ApiServiceImpl.java

@Override
public void delete(String apiName) {
    ApiEntity api = findById(apiName);//from w w  w. j  a  v a 2 s  . c  o m
    try {
        LOGGER.debug("Delete API {}", apiName);

        if (api.getState() == Lifecycle.State.STARTED) {
            throw new ApiRunningStateException(apiName);
        } else {
            Set<ApiKey> keys = apiKeyRepository.findByApi(apiName);
            keys.forEach(apiKey -> {
                try {
                    apiKeyRepository.delete(apiKey.getKey());
                } catch (TechnicalException e) {
                    LOGGER.error("An error occurs while deleting API Key {}", apiKey.getKey(), e);
                }
            });

            Set<EventEntity> events = eventService.findByApi(apiName);
            events.forEach(event -> {
                eventService.delete(event.getId());
            });

            apiRepository.delete(apiName);
        }
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to delete API {}", apiName, ex);
        throw new TechnicalManagementException("An error occurs while trying to delete API " + apiName, ex);
    }
}

From source file:org.onosproject.provider.te.topology.TeTopologyRestconfProvider.java

private void connectDevices() {

    RestconfServerConfig cfg = cfgService.getConfig(appId, RestconfServerConfig.class);
    try {/*from  ww w .  ja v  a 2 s.  com*/
        if (cfg != null && cfg.getDevicesAddresses() != null) {
            //Precomputing the devices to be removed
            Set<RestSBDevice> toBeRemoved = new HashSet<>(restconfClient.getDevices().values());
            toBeRemoved.removeAll(cfg.getDevicesAddresses());
            //Adding new devices
            for (RestSBDevice device : cfg.getDevicesAddresses()) {
                device.setActive(false);
                restconfClient.addDevice(device);
                deviceAdded(device);
            }

            //Removing devices not wanted anymore
            toBeRemoved.forEach(device -> deviceRemoved(device.deviceId()));
        }
    } catch (ConfigException e) {
        log.error("Configuration error {}", e);
    }

    // Discover the topology from RESTCONF server
    addedDevices.forEach(this::retrieveTopology);
    addedDevices.clear();
}