Example usage for com.google.common.collect Sets intersection

List of usage examples for com.google.common.collect Sets intersection

Introduction

In this page you can find the example usage for com.google.common.collect Sets intersection.

Prototype

public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) 

Source Link

Document

Returns an unmodifiable view of the intersection of two sets.

Usage

From source file:xml.entity.visitor.ReplaceVisitor.java

@Override
public final void leaveChild(final ImmutableElement element) {
    if (!ImmutableElements.isInternal().apply(element)) {
        return;/*from  ww w . j a va 2 s  . c o m*/
    }
    // test if replacements for children exist
    final SetView<ImmutableElement> intersection = Sets.intersection(Sets.newHashSet(element.children()),
            this.replace.keySet());
    if (intersection.isEmpty()) {
        // always set root to the last node left
        if (this.replace.containsKey(element)) {
            // if the root node has been replaced
            this.root = this.replace.get(element);
            logger.debug("replace root: {}, with: {}", element, this.root);
        } else {
            // if the node is unmodified
            this.root = element;
        }
    } else {
        // replace children
        final Builder<ImmutableElement> builder = ImmutableList.builder();
        for (final ImmutableElement e : element.children()) {
            if (this.replace.containsKey(e)) {
                final ImmutableElement repacement = this.replace.remove(e);
                logger.debug("replace: {}, with: {}", e, repacement);
                if (repacement == null) {
                    // skip
                } else {
                    builder.add(repacement);
                }
            } else {
                builder.add(e);
            }
        }
        final ImmutableElement internalElement = factory.createNode(element.name(), builder.build());
        replace(element, internalElement);
        this.root = internalElement;
    }
}

From source file:com.linecorp.armeria.server.http.dynamic.DynamicHttpFunctionEntry.java

/**
 * Returns whether it's mapping overlaps with given {@link DynamicHttpFunctionEntry} instance.
 *///w  ww.j  a v  a  2s  . c  om
boolean overlaps(DynamicHttpFunctionEntry entry) {
    return !Sets.intersection(methods, entry.methods).isEmpty()
            && path.skeleton().equals(entry.path.skeleton());
}

From source file:org.dllearner.utilities.Helper.java

public static <T> Set<T> intersectionTuple(Set<T> set, SortedSetTuple<T> tuple) {
    Set<T> ret = Sets.intersection(set, tuple.getPosSet());
    ret.retainAll(tuple.getNegSet());/* ww  w.  j  a va  2s.  c o  m*/
    return ret;
}

From source file:com.wrmsr.wava.core.unit.Module.java

public Module(Name name, Memory memory, Table table, Set<Signature> declaredSignatures,
        Map<Name, Import> imports, Map<Name, Export> exports, Map<Name, Function> functions) {
    this.name = requireNonNull(name);
    this.memory = requireNonNull(memory);
    this.table = table;
    this.declaredSignatures = ImmutableSet.copyOf(declaredSignatures);
    this.imports = ImmutableMap.copyOf(imports);
    this.exports = ImmutableMap.copyOf(exports);
    this.functions = ImmutableMap.copyOf(functions);
    checkArgument(Sets.intersection(imports.keySet(), functions.keySet()).isEmpty());
    checkArgument(imports.entrySet().stream().allMatch(e -> e.getKey().equals(e.getValue().getName())));
    checkArgument(exports.entrySet().stream().allMatch(e -> e.getKey().equals(e.getValue().getName())));
    checkArgument(functions.entrySet().stream().allMatch(e -> e.getKey().equals(e.getValue().getName())));
}

From source file:org.elasticsearch.test.cache.recycler.MockBigArrays.java

public static void ensureAllArraysAreReleased() throws Exception {
    final Map<Object, Object> masterCopy = Maps.newHashMap(ACQUIRED_ARRAYS);
    if (!masterCopy.isEmpty()) {
        // not empty, we might be executing on a shared cluster that keeps on obtaining
        // and releasing arrays, lets make sure that after a reasonable timeout, all master
        // copy (snapshot) have been released
        boolean success = ElasticsearchTestCase.awaitBusy(new Predicate<Object>() {
            @Override/*w  ww .  j a  v  a 2s .co m*/
            public boolean apply(Object input) {
                return Sets.intersection(masterCopy.keySet(), ACQUIRED_ARRAYS.keySet()).isEmpty();
            }
        });
        if (!success) {
            masterCopy.keySet().retainAll(ACQUIRED_ARRAYS.keySet());
            ACQUIRED_ARRAYS.keySet().removeAll(masterCopy.keySet()); // remove all existing master copy we will report on
            if (!masterCopy.isEmpty()) {
                final Object cause = masterCopy.entrySet().iterator().next().getValue();
                throw new RuntimeException(masterCopy.size() + " arrays have not been released",
                        cause instanceof Throwable ? (Throwable) cause : null);
            }
        }
    }
    for (final BigArrays bigArrays : INSTANCES) {
        // BigArrays are used on the network layer and the cluster is shared across tests so nodes might still be talking to
        // each other a bit after the test finished, wait a bit for things to stabilize if so
        final boolean sizeIsZero = ElasticsearchTestCase.awaitBusy(new Predicate<Object>() {
            @Override
            public boolean apply(Object input) {
                return bigArrays.sizeInBytes() == 0;
            }
        });
        if (!sizeIsZero) {
            final long sizeInBytes = bigArrays.sizeInBytes();
            if (sizeInBytes != 0) {
                throw new AssertionError("Expected 0 bytes, got " + sizeInBytes);
            }
        }
    }
}

From source file:org.apache.storm.daemon.GrouperFactory.java

public static LoadAwareCustomStreamGrouping mkGrouper(WorkerTopologyContext context, String componentId,
        String streamId, Fields outFields, Grouping thriftGrouping, List<Integer> unsortedTargetTasks,
        Map<String, Object> topoConf) {
    List<Integer> targetTasks = Ordering.natural().sortedCopy(unsortedTargetTasks);
    final boolean isNotLoadAware = (null != topoConf.get(Config.TOPOLOGY_DISABLE_LOADAWARE_MESSAGING)
            && (boolean) topoConf.get(Config.TOPOLOGY_DISABLE_LOADAWARE_MESSAGING));
    CustomStreamGrouping result = null;/*from w  ww.  j  a v  a2 s.  c o  m*/
    switch (Thrift.groupingType(thriftGrouping)) {
    case FIELDS:
        if (Thrift.isGlobalGrouping(thriftGrouping)) {
            result = new GlobalGrouper();
        } else {
            result = new FieldsGrouper(outFields, thriftGrouping);
        }
        break;
    case SHUFFLE:
        if (isNotLoadAware) {
            result = new ShuffleGrouping();
        } else {
            result = new LoadAwareShuffleGrouping();
        }
        break;
    case ALL:
        result = new AllGrouper();
        break;
    case LOCAL_OR_SHUFFLE:
        // Prefer local tasks as target tasks if possible
        Set<Integer> sameTasks = Sets.intersection(Sets.newHashSet(targetTasks),
                Sets.newHashSet(context.getThisWorkerTasks()));
        targetTasks = (sameTasks.isEmpty()) ? targetTasks : new ArrayList<>(sameTasks);
        if (isNotLoadAware) {
            result = new ShuffleGrouping();
        } else {
            result = new LoadAwareShuffleGrouping();
        }
        break;
    case NONE:
        result = new NoneGrouper();
        break;
    case CUSTOM_OBJECT:
        result = (CustomStreamGrouping) Thrift.instantiateJavaObject(thriftGrouping.get_custom_object());
        break;
    case CUSTOM_SERIALIZED:
        result = Utils.javaDeserialize(thriftGrouping.get_custom_serialized(), CustomStreamGrouping.class);
        break;
    case DIRECT:
        result = DIRECT;
        break;
    default:
        result = null;
        break;
    }

    if (null != result) {
        result.prepare(context, new GlobalStreamId(componentId, streamId), targetTasks);
    }

    if (result instanceof LoadAwareCustomStreamGrouping) {
        return (LoadAwareCustomStreamGrouping) result;
    } else {
        return new BasicLoadAwareCustomStreamGrouping(result);
    }
}

From source file:com.getbase.android.schema.MigrationsHelper.java

public void performMigrations(SQLiteDatabase db, TableMigration... migrations) {
    for (TableMigration migration : migrations) {
        final String tempTable = "tmp_" + tempTableIndex++;
        db.execSQL("ALTER TABLE " + migration.tableName + " RENAME TO " + tempTable);
        ImmutableSet<String> oldColumns = getColumns(db, tempTable);

        db.execSQL(migration.createTableStatement);
        final String tempNewTable = "tmp_" + tempTableIndex++;
        db.execSQL("ALTER TABLE " + migration.tableName + " RENAME TO " + tempNewTable);
        ImmutableSet<String> newColumns = getColumns(db, tempNewTable);

        db.execSQL("ALTER TABLE " + tempNewTable + " RENAME TO " + migration.tableName);

        Set<String> commonColumns = Sets.intersection(oldColumns, newColumns);
        Set<String> droppedColumns = Sets.difference(oldColumns, newColumns);
        if (!droppedColumns.isEmpty()) {
            Log.w(TAG, "Dropping columns " + Joiner.on(",").join(droppedColumns) + " during migration of "
                    + migration.tableName);
        }/*from w w w. j a v  a 2 s .  co m*/

        Set<String> addedColumns = Sets.difference(Sets.difference(newColumns, oldColumns),
                migration.mappings.keySet());
        if (!addedColumns.isEmpty()) {
            Log.w(TAG, "Will try to add new columns " + Joiner.on(",").join(addedColumns)
                    + " during migration of " + migration.tableName);
        }

        SetView<String> unmappedColumns = Sets.difference(commonColumns, migration.mappings.keySet());
        String insertColumnsString = Joiner.on(",")
                .join(Iterables.concat(unmappedColumns, migration.mappings.keySet()));
        String selectColumnsString = Joiner.on(",")
                .join(Iterables.concat(unmappedColumns, migration.mappings.values()));

        db.execSQL("INSERT INTO " + migration.tableName + "(" + insertColumnsString + ") SELECT "
                + selectColumnsString + " FROM " + tempTable);
        db.execSQL("DROP TABLE " + tempTable);
    }
}

From source file:ai.grakn.graql.internal.query.analytics.ClusterQueryImpl.java

@Override
public T execute() {
    LOGGER.info("ConnectedComponentsVertexProgram is called");
    initSubGraph();//  ww w  . j  ava2 s . c  o m
    if (!selectedTypesHaveInstance())
        return (T) Collections.emptyMap();

    ComputerResult result;
    GraknComputer computer = getGraphComputer();

    if (members) {
        if (persist) {
            if (!Sets.intersection(subTypeNames, analyticsElements).isEmpty()) {
                throw new IllegalStateException(
                        ErrorMessage.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(this.getClass().toString()));
            }
            mutateResourceOntology(connectedComponent, ResourceType.DataType.STRING);
            waitOnMutateResourceOntology(connectedComponent);
            result = computer.compute(new ConnectedComponentVertexProgram(subTypeNames, keySpace),
                    new ClusterMemberMapReduce(subTypeNames, ConnectedComponentVertexProgram.CLUSTER_LABEL));
        } else {
            result = computer.compute(new ConnectedComponentVertexProgram(subTypeNames),
                    new ClusterMemberMapReduce(subTypeNames, ConnectedComponentVertexProgram.CLUSTER_LABEL));
        }
    } else {
        if (persist) {
            if (!Sets.intersection(subTypeNames, analyticsElements).isEmpty()) {
                throw new IllegalStateException(
                        ErrorMessage.ILLEGAL_ARGUMENT_EXCEPTION.getMessage(this.getClass().toString()));
            }
            mutateResourceOntology(connectedComponent, ResourceType.DataType.STRING);
            waitOnMutateResourceOntology(connectedComponent);
            result = computer.compute(new ConnectedComponentVertexProgram(subTypeNames, keySpace),
                    new ClusterSizeMapReduce(subTypeNames, ConnectedComponentVertexProgram.CLUSTER_LABEL));
        } else {
            result = computer.compute(new ConnectedComponentVertexProgram(subTypeNames),
                    new ClusterSizeMapReduce(subTypeNames, ConnectedComponentVertexProgram.CLUSTER_LABEL));
        }
    }
    LOGGER.info("ConnectedComponentsVertexProgram is done");
    return (T) result.memory().get(GraknMapReduce.MAP_REDUCE_MEMORY_KEY);
}

From source file:org.wso2.carbon.governance.comparator.wsdl.WSDLPortComparator.java

protected void comparePorts(Definition base, Definition changed, DefaultComparison comparison) {
    DefaultComparison.DefaultSection section = null;
    Set<QName> commonKeys = Sets.intersection(base.getAllServices().keySet(),
            changed.getAllServices().keySet());
    if (commonKeys.size() > 0) {
        for (QName service : commonKeys) {
            Map<QName, Port> basePorts = base.getService(service).getPorts();
            Map<QName, Port> changedPorts = changed.getService(service).getPorts();
            MapDifference<QName, Port> mapDiff = Maps.difference(basePorts, changedPorts);

            if (!mapDiff.areEqual()) {
                Map<QName, Port> additions = mapDiff.entriesOnlyOnRight();
                if (section == null && additions.size() > 0) {
                    section = comparison.newSection();
                }//from  w w w .  j  a  va2s . c  o  m
                processAdditions(section, additions, changed);

                Map<QName, Port> removals = mapDiff.entriesOnlyOnLeft();
                if (section == null && removals.size() > 0) {
                    section = comparison.newSection();
                }
                processRemovals(section, removals, base);

                Map<QName, MapDifference.ValueDifference<Port>> changes = mapDiff.entriesDiffering();
                section = processChanges(section, comparison, changes, base, changed);
            }
        }
    }

    if (section != null) {
        comparison.addSection(ComparatorConstants.WSDL_PORTS, section);
    }
}

From source file:com.b2international.commons.hierarchy.Hierarchy.java

public void addAll(Iterable<M> members) {
    Preconditions.checkArgument(members != null, "Members to add must not be null");
    Set<M> membersToAdd = Sets.newHashSet(members);
    Set<M> actualMembers = doGetAllMembers();
    boolean notContainAny = Sets.intersection(actualMembers, membersToAdd).isEmpty();
    Preconditions.checkArgument(notContainAny,
            "Members to add most not contain any member that is already present in hierarchy");

    topLevelMembers.addAll(membersToAdd);
}