Example usage for java.util List removeIf

List of usage examples for java.util List removeIf

Introduction

In this page you can find the example usage for java.util List removeIf.

Prototype

default boolean removeIf(Predicate<? super E> filter) 

Source Link

Document

Removes all of the elements of this collection that satisfy the given predicate.

Usage

From source file:org.artifactory.maven.index.MavenIndexerServiceImpl.java

/**
 * Returns a filtered list of virtual repositories based on the excluded repository list
 *
 * @param includedRepositories List of repositories to index
 * @return List of virtual repositories to index
 *///from  www. jav  a  2  s. c  o m
private List<VirtualRepo> getVirtualRepos(@Nonnull Set<? extends RepoDescriptor> includedRepositories) {
    List<VirtualRepo> virtualRepositories = repositoryService.getVirtualRepositories();
    List<VirtualRepo> virtualRepositoriesCopy = new ArrayList<>(virtualRepositories);
    virtualRepositoriesCopy.removeIf(virtualRepo -> {
        boolean isFilterGlobalRepo = VirtualRepoDescriptor.GLOBAL_VIRTUAL_REPO_KEY.equals(virtualRepo.getKey())
                && ConstantValues.disableGlobalRepoAccess.getBoolean();

        boolean isIncluded = includedRepositories.stream().map(RepoDescriptor::getKey)
                .collect(Collectors.toList()).contains(virtualRepo.getKey());

        return isFilterGlobalRepo || !isIncluded;
    });

    return virtualRepositoriesCopy;
}

From source file:org.wso2.is.portal.user.client.api.ChallengeQuestionManagerClientServiceImpl.java

@Override
public void deleteChallengeQuestionForUser(String userUniqueId, String questionId, String questionSetId)
        throws IdentityRecoveryException, IdentityStoreException, UserNotFoundException, UserPortalUIException {

    if (challengeQuestionManager == null || realmService == null) {
        throw new IdentityRecoveryException("Challenge question manager or Realm service is not available.");
    }/*from w  w w  . j  a va2  s  .co m*/
    int minNumOfSecurityQuestions = challengeQuestionManager.getMinimumNoOfChallengeQuestionsToAnswer();
    User user = realmService.getIdentityStore().getUser(userUniqueId);

    List<UserChallengeAnswer> existingAnswers = challengeQuestionManager
            .getChallengeAnswersOfUser(userUniqueId);
    if (minNumOfSecurityQuestions < existingAnswers.size()) {
        existingAnswers.removeIf(answer -> StringUtils.equals(answer.getQuestion().getQuestionId(), questionId)
                && StringUtils.equals(answer.getQuestion().getQuestionSetId(),
                        new String(Base64.getDecoder().decode(questionSetId.getBytes(StandardCharsets.UTF_8)),
                                StandardCharsets.UTF_8)));
        challengeQuestionManager.setChallengesOfUser(user, existingAnswers);
    } else {
        String error = "Cannot delete security question. You need to have at least" + minNumOfSecurityQuestions
                + "security questions";
        throw new UserPortalUIException(error);
    }
}

From source file:org.flowable.decision.DecisionAnalysisService.java

@Scheduled(initialDelay = 1000, fixedDelay = 30000)
public void analyze() {

    LOGGER.info("Starting decision analysis ...");

    // Hardcoded process definition for demo, but obviouysly can be parameterized
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
            .processDefinitionKey("loan").latestVersion().singleResult();
    if (processDefinition == null) {
        LOGGER.info("No process definition found. No analysis done.");
        return;//  w  ww.ja  v  a2  s . co m
    }
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());

    /*
            
    1) Look for pattern: user tasks with form + exclusive gateway + sequenceflows with form outcomes
            
    2) Calculate all paths from that user task to the start + gather the variables (form fields) along those paths
            
    3) Hand over to Spark ML
            
    */

    // Step (1)
    LOGGER.info("Analyzing process definition " + processDefinition.getId());
    List<UserTask> matchingUserTasks = findUserTasksMatchingPattern(bpmnModel);

    // For demo, only show 'Loan Review' task
    matchingUserTasks.removeIf(userTask -> "Loan Review".equals(userTask.getName()));

    // Step (2) 
    Map<String, List<String>> outcomesMap = new HashMap<>(); // userTask.id -> outcomes
    Map<String, Map<String, List<String>>> possibleValueCounts // userTask.id -> {variable, distinct_values_count}
            = determinePossibleVariablesForUserTasks(processDefinition, matchingUserTasks, outcomesMap);

    // Step (3)
    submitSparkAppsForTasks(processDefinition, outcomesMap, matchingUserTasks, possibleValueCounts);
}

From source file:org.fao.geonet.api.groups.GroupsApi.java

/**
 * Retrieves a user's groups.//www.j  ava  2s.c  om
 *
 * @param includingSystemGroups if true, also returns the system groups ('GUEST', 'intranet',
 *                              'all')
 * @param all                   if true returns all the groups, even those the user doesn't
 *                              belongs to
 */
private List<Group> getGroups(UserSession session, Profile profile, boolean includingSystemGroups, boolean all)
        throws SQLException {
    ApplicationContext applicationContext = ApplicationContextHolder.get();
    final GroupRepository groupRepository = applicationContext.getBean(GroupRepository.class);
    final UserGroupRepository userGroupRepository = applicationContext.getBean(UserGroupRepository.class);
    final Sort sort = SortUtils.createSort(Group_.id);

    if (all || !session.isAuthenticated() || Profile.Administrator == session.getProfile()) {
        if (includingSystemGroups) {
            return groupRepository.findAll(null, sort);
        } else {
            return groupRepository.findAll(Specifications.not(GroupSpecs.isReserved()), sort);
        }
    } else {
        Specifications<UserGroup> spec = Specifications
                .where(UserGroupSpecs.hasUserId(session.getUserIdAsInt()));
        // you're no Administrator
        // retrieve your groups
        if (profile != null) {
            spec = spec.and(UserGroupSpecs.hasProfile(profile));
        }
        Set<Integer> ids = new HashSet<Integer>(userGroupRepository.findGroupIds(spec));

        // include system groups if requested (used in harvesters)
        if (includingSystemGroups) {
            // these DB keys of system groups are hardcoded !
            for (ReservedGroup reservedGroup : ReservedGroup.values()) {
                ids.add(reservedGroup.getId());
            }
        }

        // retrieve all groups and filter to only user one
        List<Group> groups = groupRepository.findAll(null, sort);
        groups.removeIf(g -> !ids.contains(g.getId()));
        return groups;
    }
}

From source file:org.artifactory.maven.index.MavenIndexerServiceImpl.java

private List<RealRepo> getNonVirtualRepositoriesToIndex(
        @Nullable Set<? extends RepoDescriptor> includedRepositories) {
    List<RealRepo> indexedRepos = repositoryService.getLocalAndRemoteRepositories();
    if (includedRepositories != null) {
        indexedRepos.removeIf(realRepo -> !includedRepositories.contains(realRepo.getDescriptor()));
    }//  ww w .j  ava  2s  . c  om
    return indexedRepos;
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

protected void rewriteXML(Document doc, List<Rule> rules, boolean failOnUnmatchedRule,
        boolean onlyUnmatchedRules) throws Exception {
    for (Rule r : rules) {
        if (onlyUnmatchedRules && r.matched) {
            continue;
        }//from  w  w  w.java 2s.c  om

        final List<Node> nodes = evaluateXPath(r.xpath, doc);

        if (debugEnabled) {
            debug("RULE MATCHED " + nodes.size() + " nodes: " + r);
        }
        if (nodes.size() > 0) {
            r.matched = true;
        }

        for (Node child : nodes) {
            r.apply(doc, child);
        }
    }

    final List<Rule> unmatched = new ArrayList<>(rules);
    unmatched.removeIf(r -> r.matched);

    if (failOnUnmatchedRule && !unmatched.isEmpty()) {
        unmatched.forEach(r -> System.err.println("ERROR: Unmatched rule " + r));
        throw new RuntimeException("One or more rules were not matched");
    }
}

From source file:org.languagetool.rules.spelling.SpellingCheckRule.java

/**
 * Remove prohibited words from suggestions.
 * @since 2.8//from   w  ww .  j a  v  a 2 s. c  o m
 */
protected void filterSuggestions(List<String> suggestions) {
    suggestions.removeIf(suggestion -> isProhibited(suggestion));
    filterDupes(suggestions);
}

From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationDownloader.java

private List<ConfigurationLocation> getLocations(ConfigurationSource source) {
    List<ConfigurationLocation> result = new ArrayList<>();
    List<ConfigurationLocation> randomized = new ArrayList<>();

    preferLastSuccessLocation(source, result);

    randomized.addAll(source.getLocations());
    Collections.shuffle(randomized);
    result.addAll(randomized);/*  www  . ja  v a  2  s  .co m*/

    result.removeIf(Objects::isNull);

    return result;
}

From source file:com.thoughtworks.go.server.service.MagicalMaterialAndMaterialConfigConversionTest.java

@Test
public void failIfNewTypeOfMaterialIsNotAddedInTheAboveTest() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);/*from www . j  a v a2s  . com*/
    provider.addIncludeFilter(new AssignableTypeFilter(MaterialConfig.class));
    Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com/thoughtworks");
    List<Class> reflectionsSubTypesOf = candidateComponents.stream()
            .map(beanDefinition -> beanDefinition.getBeanClassName()).map(s -> {
                try {
                    return Class.forName(s);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());

    reflectionsSubTypesOf.removeIf(this::isNotAConcrete_NonTest_MaterialConfigImplementation);

    List<Class> allExpectedMaterialConfigImplementations = allMaterialConfigsWhichAreDataPointsInThisTest();

    assertThatAllMaterialConfigsInCodeAreTestedHere(reflectionsSubTypesOf,
            allExpectedMaterialConfigImplementations);
}

From source file:eu.esdihumboldt.hale.io.gml.reader.internal.wfs.WfsBackedGmlInstanceCollection.java

/**
 * Create a GML instance collection based on the given WFS source.
 * //  ww  w . jav  a2  s  .co m
 * @param source the source
 * @param sourceSchema the source schema
 * @param restrictToFeatures if only instances that are GML features shall
 *            be loaded
 * @param ignoreRoot if the root element should be ignored for creating
 *            instances even if it is recognized as an allowed instance type
 * @param strict if associating elements with properties should be done
 *            strictly according to the schema, otherwise a fall-back is
 *            used trying to populate values also on invalid property paths
 * @param ignoreNamespaces if parsing of the XML instances should allow
 *            types and properties with namespaces that differ from those
 *            defined in the schema
 * @param crsProvider CRS provider in case no CRS is specified, may be
 *            <code>null</code>
 * @param provider the I/O provider to get values
 * @param featuresPerRequest Number of features to retrieve at most with one
 *            WFS GetFeature request, or {@value #UNLIMITED} to disable
 *            pagination
 * @throws URISyntaxException thrown if the WFS request URL cannot be
 *             generated from the source location URI
 */
public WfsBackedGmlInstanceCollection(LocatableInputSupplier<? extends InputStream> source,
        TypeIndex sourceSchema, boolean restrictToFeatures, boolean ignoreRoot, boolean strict,
        boolean ignoreNamespaces, CRSProvider crsProvider, IOProvider provider, int featuresPerRequest)
        throws URISyntaxException {

    this.sourceSchema = sourceSchema;
    this.restrictToFeatures = restrictToFeatures;
    this.ignoreRoot = ignoreRoot;
    this.strict = strict;
    this.crsProvider = crsProvider;
    this.ignoreNamespaces = ignoreNamespaces;
    this.ioProvider = provider;

    this.primordialUri = source.getLocation();

    // Build base URI from original location by removing STARTINDEX and
    // MAXFEATURES/COUNT parameters if present
    URIBuilder builder = new URIBuilder(primordialUri);
    builder.getQueryParams()
            .forEach(qp -> primordialQueryParams.put(qp.getName().toUpperCase(), qp.getValue()));

    wfsVersion = primordialQueryParams.get("VERSION");
    if (wfsVersion == null || wfsVersion.isEmpty()) {
        throw new IllegalArgumentException("WFS URL must contain VERSION parameter");
    }

    List<NameValuePair> params = builder.getQueryParams();
    params.removeIf(nvp -> nvp.getName().equalsIgnoreCase("STARTINDEX"));
    params.removeIf(nvp -> nvp.getName().equalsIgnoreCase(getMaxFeaturesParameterName(wfsVersion)));
    builder.clearParameters();
    builder.addParameters(params);
    this.baseUri = builder.build();

    // If a MAXFEATURES/COUNT parameter is present in the primordial URI,
    // set maxNumberOfFeatures accordingly
    if (primordialQueryParams.containsKey(getMaxFeaturesParameterName(wfsVersion))) {
        // Allow possible NumberFormatException to be thrown up to prevent
        // unintended retrieval of too many features
        maxNumberOfFeatures = Integer
                .parseInt(primordialQueryParams.get(getMaxFeaturesParameterName(wfsVersion)));

        if (maxNumberOfFeatures < 0) {
            throw new IllegalArgumentException(
                    MessageFormat.format("Parameter \"{0}\" must be a non-negative integer.",
                            getMaxFeaturesParameterName(wfsVersion)));
        }
    }

    // Use primordial URI and issue "hits" request to check if the WFS will
    // return anything at all
    int hits;
    try {
        hits = requestHits(primordialUri);
    } catch (WFSException e) {
        log.debug(MessageFormat.format("Failed to perform hits query (REQUESTTYPE=hits): {0}", e.getMessage()),
                e);
        hits = UNKNOWN_SIZE;
    }

    switch (wfsVersion) {
    case "1.1.0":
        // The "numberOfFeatures" reported by a 1.1.0 WFS may be smaller
        // than the actual number of features matches by the query if the
        // number of features returned per query is limited on the server
        // side. Therefore do not rely on it as a size information here.
        this.size = UNKNOWN_SIZE;
        break;
    case "2.0.0":
    case "2.0.2":
        // The "numberMatched" reported by a 2.0.0/2.0.2 WFS should be
        // number of features matched by the query. If hits equals
        // UNKNOWN_SIZE then size is also set to that value
        this.size = isLimited() ? Math.min(maxNumberOfFeatures, hits) : hits;
        break;
    default:
        this.size = UNKNOWN_SIZE;
    }

    if (featuresPerRequest != UNLIMITED && featuresPerRequest <= 0) {
        throw new IllegalArgumentException(MessageFormat.format(
                "featuresPerRequest must be a positive integer or {0} to disable pagination", UNLIMITED));
    }
    this.featuresPerRequest = featuresPerRequest;
}