Java Code Examples for java.util.Collection#containsAll()

The following examples show how to use java.util.Collection#containsAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultWebSocketManager.java    From onedev with MIT License 7 votes vote down vote up
@Override
public void observe(BasePage page) {
	String sessionId = page.getSession().getId();
	if (sessionId != null) {
		Map<IKey, Collection<String>> sessionPages = registeredObservables.get(sessionId);
		if (sessionPages == null) {
			sessionPages = new ConcurrentHashMap<>();
			registeredObservables.put(sessionId, sessionPages);
		}
		IKey pageKey = new PageIdKey(page.getPageId());
		Collection<String> observables = page.findWebSocketObservables();
		Collection<String> prevObservables = sessionPages.put(pageKey, observables);
		if (prevObservables != null && !prevObservables.containsAll(observables)) {
			IWebSocketConnection connection = connectionRegistry.getConnection(application, sessionId, pageKey);
			if (connection != null)
				notifyPastObservables(connection);
		}
	}
}
 
Example 2
Source File: TmfFilteredXYChartViewer.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Update the chart depending on the selected entries.
 *
 * @param entries
 *            Counters to display on the chart
 */
@Override
public void handleCheckStateChangedEvent(Collection<ITmfTreeViewerEntry> entries) {
    cancelUpdate();

    Iterable<TmfGenericTreeEntry> counterEntries = Iterables.filter(entries, TmfGenericTreeEntry.class);
    Collection<@NonNull Long> selectedIds = Sets.newHashSet(Iterables.transform(counterEntries, e -> e.getModel().getId()));
    if (!selectedIds.containsAll(fSelectedIds)) {
        clearContent();
    }
    fSelectedIds = selectedIds;
    // Update the styles as well
    BaseXYPresentationProvider presProvider = getPresentationProvider2();
    for (ITmfTreeViewerEntry entry : entries) {
        if (entry instanceof TmfGenericTreeEntry) {
            TmfGenericTreeEntry<TmfTreeDataModel> genericEntry = (TmfGenericTreeEntry<TmfTreeDataModel>) entry;
            TmfTreeDataModel model = genericEntry.getModel();
            OutputElementStyle style = model.getStyle();
            if (style != null) {
                presProvider.setStyle(model.getId(), style);
            }
        }
    }

    updateContent();
}
 
Example 3
Source File: CollectionCompareTests.java    From java_in_examples with Apache License 2.0 6 votes vote down vote up
private static void testContainsAll() {
    Collection<String> collection1 = Lists.newArrayList("a1", "a2", "a3", "a1");
    Collection<String> collection2 = Lists.newArrayList("a1", "a2", "a3", "a1");
    Iterable<String> iterable1 = collection1;
    Iterable<String> iterable2 = collection2;
    MutableCollection<String> mutableCollection1 = FastList.newListWith("a1", "a2", "a3", "a1");
    MutableCollection<String> mutableCollection2 = FastList.newListWith("a1", "a2", "a3", "a1");

    // Проверить полное соответствие двух коллекций
    boolean jdk =  collection1.containsAll(collection2); // c помощью JDK
    boolean guava = Iterables.elementsEqual(iterable1, iterable2); // с помощью guava
    boolean apache = CollectionUtils.containsAll(collection1, collection2);  // c помощью Apache
    boolean gs = mutableCollection1.containsAll(mutableCollection2); // c помощью GS

    System.out.println("containsAll = " + jdk + ":" + guava + ":" + apache + ":" + gs); // напечатает containsAll = true:true:true:true
}
 
Example 4
Source File: BgpPeer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public synchronized Boolean containsEqualConfiguration(final Neighbor neighbor) {
    if (this.currentConfiguration == null) {
        return false;
    }
    final AfiSafis actAfiSafi = this.currentConfiguration.getAfiSafis();
    final AfiSafis extAfiSafi = neighbor.getAfiSafis();
    final Collection<AfiSafi> actualSafi = actAfiSafi != null ? actAfiSafi.nonnullAfiSafi().values()
            : Collections.emptyList();
    final Collection<AfiSafi> extSafi = extAfiSafi != null ? extAfiSafi.nonnullAfiSafi().values()
            : Collections.emptyList();
    return actualSafi.containsAll(extSafi) && extSafi.containsAll(actualSafi)
            && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
            && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
            && Objects.equals(this.currentConfiguration.getAddPaths(), neighbor.getAddPaths())
            && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
            && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
            && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
            && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
            && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
            && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
            && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
            && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
            && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
            && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
}
 
Example 5
Source File: WithinScopeDecider.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Override
public boolean ok(ScopedIF scoped) { 
  if (context == null || context.isEmpty())
    return false;
  Collection<TopicIF> objscope = scoped.getScope();
  if (objscope.containsAll(context))
    return true;
  return false;
}
 
Example 6
Source File: ReplicationUtils.java    From hbase with Apache License 2.0 5 votes vote down vote up
private static boolean isCollectionEqual(Collection<String> c1, Collection<String> c2) {
  if (c1 == null) {
    return c2 == null;
  }
  if (c2 == null) {
    return false;
  }
  return c1.size() == c2.size() && c1.containsAll(c2);
}
 
Example 7
Source File: Utils.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
public boolean checkEqualCollection(Collection<?> injectedProperties,
      Collection<?> portletResponseProperties) {
   if (injectedProperties.equals(portletResponseProperties)) {
      return true;
   }
   if (injectedProperties.containsAll(portletResponseProperties)
         && portletResponseProperties.containsAll(injectedProperties)) {
      return true;
   }
   return false;
}
 
Example 8
Source File: CollectionStringContainAllComparator.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public boolean test(Collection<String> src, Collection<String> another) {
    if (CollectionUtils.isEmpty(src)) {
        return false;
    }
    if (CollectionUtils.isEmpty(another)) {
        return false;
    }

    return src.containsAll(another);
}
 
Example 9
Source File: ColumnNameSet.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);

    if (!c.containsAll(this)) {
        throw new UnsupportedOperationException();
    }

    return false;
}
 
Example 10
Source File: DataResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if a given anomaly passes the dimension filters {@code filters}, or
 * {@code false} otherwise. If {@code filters} contains multiple values for the same dimension
 * key, ANY match will pass the filter.
 *
 * @param anomaly anomaly to filter
 * @param filters dimension filter multimap
 * @return {@code true} if anomaly passed the filters, {@code false} otherwise
 */
static boolean applyAnomalyFilters(MergedAnomalyResultDTO anomaly, Multimap<String, String> filters) {
  Multimap<String, String> anomalyFilter = AnomaliesResource.generateFilterSetForTimeSeriesQuery(anomaly);
  for (String filterKey : filters.keySet()) {
    if (!anomalyFilter.containsKey(filterKey))
      return false;

    Collection<String> filterValues = filters.get(filterKey);
    if (!filterValues.containsAll(anomalyFilter.get(filterKey)))
      return false;
  }
  return true;
}
 
Example 11
Source File: StringUtil.java    From ranger with Apache License 2.0 5 votes vote down vote up
public static boolean equals(Collection<String> set1, Collection<String> set2) {
	boolean ret = false;

	if(set1 == null) {
		ret = set2 == null;
	} else if(set2 == null) {
		ret = false;
	} else if(set1.size() == set2.size()) {
		ret = set1.containsAll(set2);
	}

	return ret;
}
 
Example 12
Source File: Relation.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Invoked after construction for setting the table identified by {@link #catalog}, {@link #schema}
 * and {@link #table} names. Shall be invoked exactly once.
 *
 * @param  search       the other table containing the primary key ({@link Direction#IMPORT})
 *                      or the foreigner key ({@link Direction#EXPORT}) of this relation.
 * @param  primaryKeys  the primary key columns of the relation. May be the primary key columns of this table
 *                      or the primary key columns of the other table, depending on {@link Direction}.
 * @param  direction    {@code this.direction} (see comment in field declarations).
 */
final void setSearchTable(final Analyzer analyzer, final Table search, final String[] primaryKeys,
                          final Direction direction) throws DataStoreException
{
    /*
     * Sanity check (could be assertion): name of the given table must match
     * the name expected by this relation. This check below should never fail.
     */
    final boolean isDefined = (searchTable != null);
    if (isDefined || !equals(search.name)) {
        throw new InternalDataStoreException(isDefined ? analyzer.internalError() : super.toString());
    }
    /*
     * Store the specified table and verify if this relation
     * contains all columns required by the primary key.
     */
    searchTable = search;
    final Collection<String> referenced;        // Primary key components referenced by this relation.
    switch (direction) {
        case IMPORT: referenced = columns.keySet(); break;
        case EXPORT: referenced = columns.values(); break;
        default: throw new AssertionError(direction);
    }
    useFullKey = referenced.containsAll(Arrays.asList(primaryKeys));
    if (useFullKey && columns.size() >= 2) {
        /*
         * Sort the columns in the order expected by the primary key.  This is required because we need
         * a consistent order in the cache provided by Table.instanceForPrimaryKeys() even if different
         * relations declare different column order in their foreigner key. Note that the 'columns' map
         * is unmodifiable if its size is less than 2, and modifiable otherwise.
         */
        final Map<String,String> copy = new HashMap<>(columns);
        columns.clear();
        for (String key : primaryKeys) {
            String value = key;
            switch (direction) {
                case IMPORT: {                                      // Primary keys are 'columns' keys.
                    value = copy.remove(key);
                    break;
                }
                case EXPORT: {                                      // Primary keys are 'columns' values.
                    key = null;
                    for (final Iterator<Map.Entry<String,String>> it = copy.entrySet().iterator(); it.hasNext();) {
                        final Map.Entry<String,String> e = it.next();
                        if (value.equals(e.getValue())) {
                            key = e.getKey();
                            it.remove();
                            break;
                        }
                    }
                    break;
                }
            }
            if (key == null || value == null || columns.put(key, value) != null) {
                throw new InternalDataStoreException(analyzer.internalError());
            }
        }
        if (!copy.isEmpty()) {
            throw new DataStoreContentException(Resources.forLocale(analyzer.locale)
                        .getString(Resources.Keys.MalformedForeignerKey_2, freeText,
                                   CollectionsExt.first(copy.keySet())));
        }
    }
}
 
Example 13
Source File: AbstractPrimaryKeyJoinColumnResolver.java    From rice with Educational Community License v2.0 4 votes vote down vote up
protected final List<Expression> getJoinColumns(String enclosingClass, String fieldName, String mappedClass) {
    final ObjectReferenceDescriptor ord = OjbUtil.findObjectReferenceDescriptor(mappedClass, fieldName,
            descriptorRepositories);
    final List<Expression> joinColumns = new ArrayList<Expression>();

    if (foundDescriptor(ord)) {

        final Collection<String> fks = getForeignKeys(ord);
        if (fks == null || fks.isEmpty()) {
            LOG.error(ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass) + " field has a reference descriptor for " + fieldName
                    + " but does not have any foreign keys configured");
            return null;
        }

        final Collection<String> pks = OjbUtil.getPrimaryKeyNames(mappedClass, descriptorRepositories);

        if (pks.size() == fks.size() && pks.containsAll(fks) && !pks.isEmpty()) {

            final ClassDescriptor cd = OjbUtil.findClassDescriptor(mappedClass, descriptorRepositories);
            final ClassDescriptor icd;

            final String itemClassName = getItemClass(ord);
            if (StringUtils.isBlank(itemClassName)) {
                LOG.error(ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass) + " field has a reference descriptor for " + fieldName
                        + " but does not class name attribute");
                return null;
            } else {
                icd = OjbUtil.findClassDescriptor(itemClassName, descriptorRepositories);
            }

            final FieldDescriptor[] pfds = cd.getPkFields();
            final FieldDescriptor[] ipfds = icd.getPkFields();
            for (int i = 0; i < pfds.length; i++) {
                final List<MemberValuePair> pairs = new ArrayList<MemberValuePair>();
                pairs.add(new MemberValuePair("name", new StringLiteralExpr(pfds[i].getColumnName())));
                pairs.add(new MemberValuePair("referencedColumnName", new StringLiteralExpr(ipfds[i].getColumnName())));
                joinColumns.add(new NormalAnnotationExpr(new NameExpr("PrimaryKeyJoinColumn"), pairs));
            }

            if (isCascadeDelete(ord)) {
                LOG.error(ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass) + " field has a reference descriptor set to cascade delete but JPA does not support that configuration with primary key join columns.");
            }
            if (isCascadePersist(ord)) {
                LOG.error(ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass) + " field has a reference descriptor set to cascade persist but JPA does not support that configuration with primary key join columns.");
            }
        }
    }
    return joinColumns;
}
 
Example 14
Source File: ListItem.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected void captureAccess(ParameterParser params, String index) 
{
	String access_mode = params.getString("access_mode" + index);
	
	if(access_mode == null || AccessMode.GROUPED.toString().equals(access_mode))
	{
		// we inherit more than one group and must check whether group access changes at this item
		String[] access_groups = params.getStrings("access_groups" + index);
		
		SortedSet<String> new_groups = new TreeSet<String>();
		if(access_groups != null)
		{
			new_groups.addAll(Arrays.asList(access_groups));
		}
		SortedSet<String> new_group_refs = convertToRefs(new_groups);
		
		Collection inh_grps = getInheritedGroupRefs();
		boolean groups_are_inherited = (new_group_refs.size() == inh_grps.size()) && inh_grps.containsAll(new_group_refs);
		
		if(groups_are_inherited)
		{
			new_groups.clear();
			setGroupsById(new_groups);
			setAccessMode(AccessMode.INHERITED);
		}
		else
		{
			setGroupsById(new_groups);
			setAccessMode(AccessMode.GROUPED);
		}
		
		setPubview(false);
	}
	else if(ResourcesAction.PUBLIC_ACCESS.equals(access_mode))
	{
		if(! isPubviewInherited())
		{
			setPubview(true);
			setAccessMode(AccessMode.INHERITED);
		}
	}
	else if(AccessMode.INHERITED.toString().equals(access_mode))
	{
		captureAccessRoles(params, index);
		setAccessMode(AccessMode.INHERITED);
		this.groups.clear();
	}
}
 
Example 15
Source File: StaticAnalysisTests.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void assertEquals(TypeFlow actual, Object... expected) {
    Collection<?> actualTypes = actual.getTypes();
    if (actualTypes.size() != expected.length || !actualTypes.containsAll(Arrays.asList(expected))) {
        Assert.fail(actualTypes + " != " + Arrays.asList(expected));
    }
}
 
Example 16
Source File: BSONStructureTask.java    From workcraft with MIT License 4 votes vote down vote up
private Map<Condition, String> phaseTask3(ONGroup upperGroup) {
    Map<Condition, String> result = new HashMap<>();

    for (Condition c : upperGroup.getConditions()) {
        Condition pre = null;
        Collection<Phase> phases = getAllPhases().get(c);

        if (!getRelationAlg().getPrePNCondition(c).isEmpty()) {
            pre = getRelationAlg().getPrePNCondition(c).iterator().next();
        }

        if (pre != null) {
            Collection<Phase> prePhases = getAllPhases().get(pre);
            Collection<Condition> preMax = getBSONAlg().getMaximalPhase(prePhases);
            System.out.println("premax+" + net.toString(preMax));

            for (Phase phase : phases) {
                boolean match = false;
                Collection<Condition> min = getBSONAlg().getMinimalPhase(phase);
                System.out.println("min+" + net.toString(min));
                if (preMax.containsAll(min)) {
                    match = true;
                }

                if (!match) {
                    match = true;
                    ONGroup lowGroup = net.getGroup(phase.iterator().next());
                    boolean containFinal = false;

                    if (!min.containsAll(getRelationAlg().getONInitial(lowGroup))) {
                        match = false;
                    }
                    for (ONGroup group : getBSONAlg().getLowerGroups(pre)) {
                        if (preMax.containsAll(getRelationAlg().getONFinal(group))) {
                            containFinal = true;
                            break;
                        }
                    }
                    if (!containFinal) {
                        match = false;
                    }
                }

                if (!match) {
                    String ref = net.getNodeReference(c);
                    String ref2 = net.getNodeReference(pre);
                    result.put(c, "Disjoint phases between " + ref + " and " + ref2);
                }
            }
        }
    }
    return result;
}
 
Example 17
Source File: DBTable.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean equals(Object obj) {
    boolean result = false;

    // Check for reflexivity first.
    if (this == obj) {
        return true;
    }
    if (!(obj instanceof DBTable)) {
        return false;
    }

    result = super.equals(obj);

    if (!result) {
        return result;
    }

    // Check for castability (also deals with null obj)
    if (obj instanceof DBTable) {
        DBTable aTable = (DBTable) obj;
        String aTableName = aTable.getName();
        Map<String, DBColumn> aTableColumns = aTable.getColumns();
        DBPrimaryKey aTablePK = aTable.primaryKey;
        List<DBForeignKey> aTableFKs = aTable.getForeignKeys();

        result &= (aTableName != null && name != null && name.equals(aTableName));
        if (columns != null && aTableColumns != null) {
            Set<String> objCols = aTableColumns.keySet();
            Set<String> myCols = columns.keySet();

            // Must be identical (no subsetting), hence the pair of tests.
            result &= myCols.containsAll(objCols) && objCols.containsAll(myCols);
        } else if (!(columns == null && aTableColumns == null)) {
            result = false;
        }

        result &= (primaryKey != null) ? primaryKey.equals(aTablePK) : aTablePK == null;
        if (foreignKeys != null && aTableFKs != null) {
            Collection<DBForeignKey> myFKs = foreignKeys.values();
            // Must be identical (no subsetting), hence the pair of tests.
            result &= myFKs.containsAll(aTableFKs) && aTableFKs.containsAll(myFKs);
        } else if (!(foreignKeys == null && aTableFKs == null)) {
            result = false;
        }
    }
    return result;
}
 
Example 18
Source File: P.java    From winter with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean invoke(Collection<T> in) {
	return in.containsAll(value);
}
 
Example 19
Source File: VplsConfigManager.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the VPLS configuration from network configuration.
 * Checks difference between new configuration and old configuration.
 */
private synchronized void reloadConfiguration() {
    VplsAppConfig vplsAppConfig = configService.getConfig(appId, VplsAppConfig.class);

    if (vplsAppConfig == null) {
        log.warn(CONFIG_NULL);

        // If the config is null, removes all VPLS.
        vpls.removeAllVpls();
        return;
    }

    // If there exists a update time in the configuration; it means the
    // configuration was pushed by VPLS store; ignore this configuration.
    long updateTime = vplsAppConfig.updateTime();
    if (updateTime != -1L) {
        return;
    }

    Collection<VplsData> oldVplses = vpls.getAllVpls();
    Collection<VplsData> newVplses;

    // Generates collection of new VPLSs
    newVplses = vplsAppConfig.vplss().stream()
            .map(vplsConfig -> {
                Set<Interface> interfaces = vplsConfig.ifaces().stream()
                        .map(this::getInterfaceByName)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());
                VplsData vplsData = VplsData.of(vplsConfig.name(), vplsConfig.encap());
                vplsData.addInterfaces(interfaces);
                return vplsData;
            }).collect(Collectors.toSet());

    if (newVplses.containsAll(oldVplses) && oldVplses.containsAll(newVplses)) {
        // no update, ignore
        return;
    }

    // To add or update
    newVplses.forEach(newVplsData -> {
        boolean vplsExists = false;
        for (VplsData oldVplsData : oldVplses) {
            if (oldVplsData.name().equals(newVplsData.name())) {
                vplsExists = true;

                // VPLS exists; but need to be updated.
                if (!oldVplsData.equals(newVplsData)) {
                    // Update VPLS
                    Set<Interface> newInterfaces = newVplsData.interfaces();
                    Set<Interface> oldInterfaces = oldVplsData.interfaces();

                    Set<Interface> ifaceToAdd = newInterfaces.stream()
                            .filter(iface -> !oldInterfaces.contains(iface))
                            .collect(Collectors.toSet());

                    Set<Interface> ifaceToRem = oldInterfaces.stream()
                            .filter(iface -> !newInterfaces.contains(iface))
                            .collect(Collectors.toSet());

                    vpls.addInterfaces(oldVplsData, ifaceToAdd);
                    vpls.removeInterfaces(oldVplsData, ifaceToRem);
                    vpls.setEncapsulationType(oldVplsData, newVplsData.encapsulationType());
                }
            }
        }
        // VPLS not exist; add new VPLS
        if (!vplsExists) {
            vpls.createVpls(newVplsData.name(), newVplsData.encapsulationType());
            vpls.addInterfaces(newVplsData, newVplsData.interfaces());
        }
    });

    // VPLS not exists in old VPLS configuration; remove it.
    Set<VplsData> vplsToRemove = Sets.newHashSet();
    oldVplses.forEach(oldVpls -> {
        Set<String> newVplsNames = newVplses.stream()
                .map(VplsData::name)
                .collect(Collectors.toSet());

        if (!newVplsNames.contains(oldVpls.name())) {
            // To avoid ConcurrentModificationException; do remove after this
            // iteration.
            vplsToRemove.add(oldVpls);
        }
    });
    vplsToRemove.forEach(vpls::removeVpls);
}
 
Example 20
Source File: IdToken.java    From google-oauth-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Returns whether the audience in the payload contains only client IDs that are trusted as
 * specified in step 2 of <a
 * href="http://openid.net/specs/openid-connect-basic-1_0-27.html#id.token.validation">ID Token
 * Validation</a>.
 *
 * @param trustedClientIds list of trusted client IDs
 */
public final boolean verifyAudience(Collection<String> trustedClientIds) {
  Collection<String> audience = getPayload().getAudienceAsList();
  if (audience.isEmpty()) {
    return false;
  }
  return trustedClientIds.containsAll(audience);
}