Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

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

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:io.fabric8.elasticsearch.plugin.kibana.KibanaSeed.java

public void setDashboards(final OpenshiftRequestContext context, Client client, String kibanaVersion,
        final String projectPrefix) {

    LOGGER.debug("Begin setDashboards:  projectPrefix '{}' for user '{}' projects '{}' kibanaIndex '{}'",
            projectPrefix, context.getUser(), context.getProjects(), context.getKibanaIndex());

    // We want to seed the Kibana user index initially
    // since the logic from Kibana has changed to create before this plugin
    // starts.../*from w  ww .j  a  v a 2s.  c om*/
    boolean changed = initialSeedKibanaIndex(context, client);

    // GET .../.kibana/index-pattern/_search?pretty=true&fields=
    // compare results to projects; handle any deltas (create, delete?)

    Set<String> indexPatterns = getProjectNamesFromIndexes(context, client, projectPrefix);
    LOGGER.debug("Found '{}' Index patterns for user", indexPatterns.size());

    Set<String> projects = new HashSet<>(context.getProjects());
    List<String> filteredProjects = new ArrayList<String>(filterProjectsWithIndices(projectPrefix, projects));
    LOGGER.debug("projects for '{}' that have existing indexes: '{}'", context.getUser(), filteredProjects);

    addAliasToAllProjects(context, filteredProjects);
    Collections.sort(filteredProjects);

    // If none have been set yet
    if (indexPatterns.isEmpty()) {
        create(context.getKibanaIndex(), filteredProjects, true, client, kibanaVersion, projectPrefix,
                indexPatterns);
        changed = true;
    } else {

        List<String> common = new ArrayList<String>(indexPatterns);

        common.retainAll(filteredProjects);

        filteredProjects.removeAll(common);
        indexPatterns.removeAll(common);

        // if we aren't a cluster-admin, make sure we're deleting the
        // ADMIN_ALIAS_NAME
        if (!context.isOperationsUser()) {
            LOGGER.debug("user is not a cluster admin, ensure they don't keep/have the admin alias pattern");
            indexPatterns.add(ADMIN_ALIAS_NAME);
        }

        // check if we're going to be adding or removing any projects
        if (!filteredProjects.isEmpty() || !indexPatterns.isEmpty()) {
            changed = true;
        }

        // for any to create (remaining in projects) call createIndices, createSearchmapping?, create dashboard
        create(context.getKibanaIndex(), filteredProjects, false, client, kibanaVersion, projectPrefix,
                indexPatterns);

        // cull any that are in ES but not in OS (remaining in indexPatterns)
        remove(context.getKibanaIndex(), indexPatterns, client, projectPrefix);

        common.addAll(filteredProjects);
        Collections.sort(common);
        // Set default index to first index in common if we removed the default
        String defaultIndex = getDefaultIndex(context, client, kibanaVersion, projectPrefix);

        LOGGER.debug("Checking if index patterns '{}' contain default index '{}'", indexPatterns, defaultIndex);

        if (indexPatterns.contains(defaultIndex) || StringUtils.isEmpty(defaultIndex)) {
            LOGGER.debug("'{}' does contain '{}' and common size is {}", indexPatterns, defaultIndex,
                    common.size());
            if (!common.isEmpty()) {
                setDefaultIndex(context.getKibanaIndex(), common.get(0), client, kibanaVersion, projectPrefix);
            }
        }
    }

    if (changed) {
        refreshKibanaUser(context.getKibanaIndex(), client);
    }
}

From source file:org.andstatus.app.timeline.TimelineSelector.java

private void removeDuplicates(List<TimelineListViewItem> timelines) {
    Map<String, TimelineListViewItem> unique = new HashMap<>();
    boolean removeSomething = false;
    for (TimelineListViewItem viewItem : timelines) {
        String key = viewItem.timelineTitle.toString();
        if (unique.containsKey(key)) {
            removeSomething = true;/*from  w ww  .ja  v a  2  s.  c om*/
        } else {
            unique.put(key, viewItem);
        }
    }
    if (removeSomething) {
        timelines.retainAll(unique.values());
    }
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

public static VtepConfigSchema validateForUpdateVtepSchema(String schemaName, List<BigInteger> lstDpnsForAdd,
        List<BigInteger> lstDpnsForDelete, IITMProvider itmProvider) {
    Preconditions.checkArgument(StringUtils.isNotBlank(schemaName));
    if ((lstDpnsForAdd == null || lstDpnsForAdd.isEmpty())
            && (lstDpnsForDelete == null || lstDpnsForDelete.isEmpty())) {
        Preconditions.checkArgument(false,
                "DPN ID list for add | delete is null or empty in schema " + schemaName);
    }/*w ww. j ava 2  s  .c  om*/
    VtepConfigSchema schema = itmProvider.getVtepConfigSchema(schemaName);
    if (schema == null) {
        Preconditions.checkArgument(false, "Specified VTEP Schema [" + schemaName + "] doesn't exists!");
    }
    List<BigInteger> existingDpnIds = getDpnIdList(schema.getDpnIds());
    if (isNotEmpty(lstDpnsForAdd)) {
        //  if (isNotEmpty(existingDpnIds)) {
        List<BigInteger> lstAlreadyExistingDpns = new ArrayList<>(existingDpnIds);
        lstAlreadyExistingDpns.retainAll(lstDpnsForAdd);
        Preconditions.checkArgument(lstAlreadyExistingDpns.isEmpty(),
                "DPN ID's " + lstAlreadyExistingDpns + " already exists in VTEP schema [" + schemaName + "]");
        //    }
        if (schema.getTunnelType().equals(TunnelTypeGre.class)) {
            validateForSingleGreTep(schema.getSchemaName(), lstDpnsForAdd,
                    itmProvider.getAllVtepConfigSchemas());
        }
    }
    if (isNotEmpty(lstDpnsForDelete)) {
        if (existingDpnIds == null || existingDpnIds.isEmpty()) {
            String builder = "DPN ID's " + lstDpnsForDelete + " specified for delete from VTEP schema ["
                    + schemaName + "] are not configured in the schema.";
            Preconditions.checkArgument(false, builder);
        } else if (!existingDpnIds.containsAll(lstDpnsForDelete)) {
            List<BigInteger> lstConflictingDpns = new ArrayList<>(lstDpnsForDelete);
            lstConflictingDpns.removeAll(existingDpnIds);
            String builder = "DPN ID's " + lstConflictingDpns + " specified for delete from VTEP schema ["
                    + schemaName + "] are not configured in the schema.";
            Preconditions.checkArgument(false, builder);
        }
    }
    return schema;
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

private static void validateForSingleGreTep(String schemaName, List<BigInteger> lstDpnsForAdd,
        List<VtepConfigSchema> existingSchemas) {
    for (VtepConfigSchema existingSchema : emptyIfNull(existingSchemas)) {
        if (TunnelTypeGre.class.equals(existingSchema.getTunnelType())
                && !StringUtils.equalsIgnoreCase(schemaName, existingSchema.getSchemaName())) {
            List<BigInteger> lstConflictingDpns = new ArrayList<>(getDpnIdList(existingSchema.getDpnIds()));
            lstConflictingDpns.retainAll(emptyIfNull(lstDpnsForAdd));
            if (!lstConflictingDpns.isEmpty()) {
                String errMsg = "DPN's " + lstConflictingDpns
                        + " already configured with GRE TEP. Mutiple GRE TEP's on a single DPN are not allowed.";
                Preconditions.checkArgument(false, errMsg);
            }//from   ww w  . j av  a 2 s .  co m
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimGroupMembershipManager.java

@Override
public List<ScimGroupMember> updateOrAddMembers(String groupId, List<ScimGroupMember> members)
        throws ScimResourceNotFoundException {
    List<ScimGroupMember> currentMembers = getMembers(groupId, null, false);
    logger.debug("current-members: " + currentMembers + ", in request: " + members);

    List<ScimGroupMember> currentMembersToRemove = new ArrayList<>(currentMembers);
    currentMembersToRemove.removeAll(members);
    logger.debug("removing members: " + currentMembersToRemove);
    for (ScimGroupMember member : currentMembersToRemove) {
        removeMemberById(groupId, member.getMemberId());
    }//from  w  w  w  . j  a  va  2  s  .  c o  m

    List<ScimGroupMember> newMembersToAdd = new ArrayList<>(members);
    newMembersToAdd.removeAll(currentMembers);
    logger.debug("adding new members: " + newMembersToAdd);
    for (ScimGroupMember member : newMembersToAdd) {
        addMember(groupId, member);
    }

    List<ScimGroupMember> membersToUpdate = new ArrayList<>(members);
    membersToUpdate.retainAll(currentMembers);
    logger.debug("updating members: " + membersToUpdate);
    for (ScimGroupMember member : membersToUpdate) {
        updateMember(groupId, member);
    }

    return getMembers(groupId, null, false);
}

From source file:opennlp.tools.jsmlearning.FeatureSpaceCoverageProcessor.java

public boolean ruleCoversCase(Map<String, String> attr_value, String[] line) {
    boolean soFarCovers = true;
    for (String attr : attributes) {
        int attrIndex = getIdForAttributeName(attr);
        String rule = attr_value.get(attr);
        if (rule == null)
            continue; // no constraint
        rule = rule.toLowerCase().replace("\"", "").replace(",  ", ",").replace(", ", ",");
        String vCase = line[attrIndex].toLowerCase().replace("\"", "").replace(",  ", ",").replace(", ", ",");
        if (vCase == null) {// rule for this attribute exists but case has no value
            soFarCovers = false;//from   ww  w .  j  a  va  2s. co  m
            return false;
        }

        String valArrCaseStr = StringUtils.substringBetween(vCase, "{", "}");
        String valArrRuleStr = StringUtils.substringBetween(rule, "{", "}");
        if (valArrCaseStr == null || valArrRuleStr == null) { // we assume single value, not an array of values
            if (!vCase.equals(rule)) {
                soFarCovers = false;
                return false;
            }
        } else {
            String[] valArrCase = valArrCaseStr.split(",");
            String[] valArrRule = valArrRuleStr.split(",");
            List<String> valListCase = new ArrayList<String>(Arrays.asList(valArrCase));
            List<String> valListRule = new ArrayList<String>(Arrays.asList(valArrRule));

            int ruleSize = valListRule.size();
            //System.out.println(valListRule);
            //System.out.println(valListCase);

            // rule members are subset of case
            valListRule.retainAll(valListCase);

            //System.out.println(valListRule);

            if (ruleSize != valListRule.size()) {
                soFarCovers = false;
                return false;
            }

        }
    }
    return soFarCovers;
}

From source file:com.ichi2.anki.tests.libanki.ImportTest.java

public void testApkg() throws IOException {
    List<String> expected;
    List<String> actual;

    Collection tmp = Shared.getEmptyCol(getContext());
    String apkg = Shared.getTestFilePath(getContext(), "media.apkg");
    Importer imp = new AnkiPackageImporter(tmp, apkg);
    expected = Arrays.asList();/*from   w  w  w. ja  va 2  s  . c o m*/
    actual = Arrays.asList(new File(tmp.getMedia().dir()).list());
    actual.retainAll(expected);
    assertEquals(actual.size(), expected.size());
    imp.run();
    expected = Arrays.asList("foo.wav");
    actual = Arrays.asList(new File(tmp.getMedia().dir()).list());
    actual.retainAll(expected);
    assertEquals(expected.size(), actual.size());
    // import again should be idempotent in terms of media
    tmp.remCards(Utils.arrayList2array(tmp.getDb().queryColumn(Long.class, "select id from cards", 0)));
    imp = new AnkiPackageImporter(tmp, apkg);
    imp.run();
    expected = Arrays.asList("foo.wav");
    actual = Arrays.asList(new File(tmp.getMedia().dir()).list());
    actual.retainAll(expected);
    assertEquals(actual.size(), expected.size());
    // but if the local file has different data, it will rename
    tmp.remCards(Utils.arrayList2array(tmp.getDb().queryColumn(Long.class, "select id from cards", 0)));
    FileOutputStream os;
    os = new FileOutputStream(new File(tmp.getMedia().dir(), "foo.wav"), false);
    os.write("xyz".getBytes());
    os.close();
    imp = new AnkiPackageImporter(tmp, apkg);
    imp.run();
    assertTrue(new File(tmp.getMedia().dir()).list().length == 2);
}

From source file:com.github.alexfalappa.nbspringboot.navigator.MappedElementExtractor.java

@Override
public List visitClass(final ClassTree node, final Void p) {
    final List<MappedElement> mappedElements = new ArrayList<>();
    if (canceled || node == null) {
        return mappedElements;
    }/*from   w  w w. j  a va  2s  .  c om*/
    final Element clazz = trees.getElement(new TreePath(rootPath, node));
    if (clazz == null || (clazz.getAnnotation(Controller.class) == null
            && clazz.getAnnotation(RestController.class) == null)) {
        return mappedElements;
    }
    final RequestMapping parentRequestMapping = clazz.getAnnotation(RequestMapping.class);
    final Map<String, List<RequestMethod>> parentUrls = extractTypeLevelMappings(parentRequestMapping);
    for (Element enclosedElement : clazz.getEnclosedElements()) {
        if (enclosedElement.getKind() != ElementKind.METHOD) {
            continue;
        }
        final Map<String, List<RequestMethod>> elementUrls = new TreeMap<>();
        final RequestMapping requestMapping = enclosedElement.getAnnotation(RequestMapping.class);
        if (requestMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(requestMapping.value(), requestMapping.path()),
                    requestMapping.method());
        }
        final DeleteMapping deleteMapping = enclosedElement.getAnnotation(DeleteMapping.class);
        if (deleteMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(deleteMapping.value(), deleteMapping.path()),
                    new RequestMethod[] { RequestMethod.DELETE });
        }
        final GetMapping getMapping = enclosedElement.getAnnotation(GetMapping.class);
        if (getMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(getMapping.value(), getMapping.path()),
                    new RequestMethod[] { RequestMethod.GET });
        }
        final PatchMapping patchMapping = enclosedElement.getAnnotation(PatchMapping.class);
        if (patchMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(patchMapping.value(), patchMapping.path()),
                    new RequestMethod[] { RequestMethod.PATCH });
        }
        final PostMapping postMapping = enclosedElement.getAnnotation(PostMapping.class);
        if (postMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(postMapping.value(), postMapping.path()),
                    new RequestMethod[] { RequestMethod.POST });
        }
        final PutMapping putMapping = enclosedElement.getAnnotation(PutMapping.class);
        if (putMapping != null) {
            extractMethodLevelMappings(elementUrls, concatValues(putMapping.value(), putMapping.path()),
                    new RequestMethod[] { RequestMethod.PUT });
        }

        for (Map.Entry<String, List<RequestMethod>> methodLevelMapping : elementUrls.entrySet()) {
            for (Map.Entry<String, List<RequestMethod>> typeLevelMapping : parentUrls.entrySet()) {
                final String url = pathMatcher.combine(typeLevelMapping.getKey(), methodLevelMapping.getKey());

                final List<RequestMethod> effectiveMethods = new ArrayList<>();
                if (methodLevelMapping.getValue().isEmpty()) {
                    effectiveMethods.add(null);
                }
                effectiveMethods.addAll(methodLevelMapping.getValue());
                if (!typeLevelMapping.getValue().isEmpty()) {
                    effectiveMethods.retainAll(typeLevelMapping.getValue());
                }

                for (RequestMethod effectiveMethod : effectiveMethods) {
                    mappedElements
                            .add(new MappedElement(this.fileObject, enclosedElement, url, effectiveMethod));
                }
            }
        }
    }
    return mappedElements;
}

From source file:com.floragunn.searchguard.ssl.SSLTest.java

@Test
public void testAvailCiphers() throws Exception {
    final SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(null, null, null);
    final SSLEngine engine = serverContext.createSSLEngine();
    final List<String> jdkSupportedCiphers = new ArrayList<>(Arrays.asList(engine.getSupportedCipherSuites()));
    jdkSupportedCiphers.retainAll(SSLConfigConstants.getSecureSSLCiphers(Settings.EMPTY, false));
    engine.setEnabledCipherSuites(jdkSupportedCiphers.toArray(new String[0]));

    final List<String> jdkEnabledCiphers = Arrays.asList(engine.getEnabledCipherSuites());
    // example/*from   w w  w  .  j  av a2s  .c  om*/
    // TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    // TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA
    System.out.println("JDK enabled ciphers: " + jdkEnabledCiphers);
    Assert.assertTrue(jdkEnabledCiphers.size() > 0);
}

From source file:opennlp.tools.parse_thicket.opinion_processor.LinguisticPhraseManager.java

public List<String> formStandardizedTopic() {
    Set<ParseTreeChunk> keys = entry_group.keySet();
    for (ParseTreeChunk k : keys) {
        List<ParseTreeChunk> lingPhrases = entry_group.get(k);
        for (int i = 0; i < lingPhrases.size(); i++)
            for (int j = i + 1; j < lingPhrases.size(); j++) {
                ParseTreeChunk chI = lingPhrases.get(i);
                ParseTreeChunk chJ = lingPhrases.get(j);
                List<String> lemmas = new ArrayList<String>(chI.getLemmas());
                lemmas.retainAll(chJ.getLemmas());
                if (lemmas.size() < 2)
                    continue;
                String buf = "";
                List<String> candTopicLst = new ArrayList<String>();
                for (String w : lemmas) {
                    if (w.length() < MIN_LENGTH_OF_WORD_TO_CONSIDER)
                        continue;
                    if (!StringUtils.isAlpha(w))
                        continue;
                    // find POS of w
                    boolean bAccept = false;
                    for (int iw = 0; iw < chI.getLemmas().size(); iw++) {
                        if (w.equals(chI.getLemmas().get(iw))) {
                            if (chI.getPOSs().get(iw).startsWith("NN") || chI.getPOSs().get(iw).startsWith("JJ")
                                    || chI.getPOSs().get(iw).startsWith("VB"))
                                bAccept = true;
                        }//from w  w w .  j  a  v a2 s  .c o m
                    }
                    if (bAccept) {
                        // buf+=w+" ";
                        String ws = substituteSynonym(w);
                        candTopicLst.add(ws);
                    }
                }
                // remove duplicates like 'new new house'
                // candTopicLst = new ArrayList<String>(new
                // HashSet<String>(candTopicLst));
                for (String w : candTopicLst) {
                    buf += w + " ";
                }

                buf = buf.trim();
                if (buf.indexOf(' ') < 0)
                    continue;

                if (!standardizedTopics.contains(buf)) {
                    standardizedTopics.add(buf);
                    std_group.put(buf, lingPhrases);
                }
            }
    }
    cleanUpStandardizedTopics();

    return standardizedTopics;
}