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:com.google.devtools.build.android.resources.FieldInitializers.java

public Iterable<Entry<ResourceType, Map<String, FieldInitializer>>> filter(FieldInitializers fieldsToWrite) {
    Map<ResourceType, Map<String, FieldInitializer>> initializersToWrite = new EnumMap<>(ResourceType.class);

    for (Entry<ResourceType, Map<String, FieldInitializer>> entry : fieldsToWrite.initializers.entrySet()) {
        if (initializers.containsKey(entry.getKey())) {
            final Map<String, FieldInitializer> valueFields = initializers.get(entry.getKey());
            final ImmutableMap.Builder<String, FieldInitializer> fields = ImmutableSortedMap.naturalOrder();
            // Resource type may be missing if resource overriding eliminates resources at the binary
            // level, which were originally present at the library level.
            for (String fieldName : Sets.intersection(entry.getValue().keySet(), valueFields.keySet())) {
                fields.put(fieldName, valueFields.get(fieldName));
            }//from ww w. jav a  2  s  .c  o m
            initializersToWrite.put(entry.getKey(), fields.build());
        }
    }

    return initializersToWrite.entrySet();
}

From source file:prm4j.indexing.model.ParametricPropertyModel.java

private void initialize() {
    final Set<Tuple<Set<Parameter<?>>, Set<Parameter<?>>>> updates = getParametricProperty().getUpdates();
    for (BaseEvent baseEvent : getParametricProperty().getSpec().getBaseEvents()) {
        final Set<Parameter<?>> parameterSet = baseEvent.getParameters();
        for (Set<Parameter<?>> enablingParameterSet : toReverseTopologicalOrdering(
                getParametricProperty().getEnableParameterSets().get(baseEvent))) {
            /*/*  ww w .  j a  va 2s .c om*/
             * the empty parameter set {} can be filtered. No parameter set can contain less elements, so there can
             * be no maxArgs = (X -> {}). And a joindata = (e -> ( {} -> {} )) makes no sense either. The same with
             * chaining from {} to {} and updates.
             */
            if (!enablingParameterSet.equals(EMPTY_PARAMETER_SET)
                    && !isSubsetEq(parameterSet, enablingParameterSet)) {
                if (isSuperset(parameterSet, enablingParameterSet)) {
                    maxArgs.put(baseEvent, enablingParameterSet);
                } else {
                    final Set<Parameter<?>> compatibleSubset = Sets.intersection(parameterSet,
                            enablingParameterSet);
                    final Tuple<Set<Parameter<?>>, Set<Parameter<?>>> tuple = tuple(compatibleSubset,
                            enablingParameterSet);
                    joinArgs.put(baseEvent, tuple);
                    updateChainingArgs.put(enablingParameterSet, tuple);
                    if (updates.contains(tuple)) {
                        monitorSetSpecs.put(compatibleSubset, tuple(enablingParameterSet, true));
                    } else {
                        monitorSetSpecs.put(compatibleSubset, tuple(enablingParameterSet, false));
                    }
                }
            }
        }
    }
    for (Tuple<Set<Parameter<?>>, Set<Parameter<?>>> tuple : updates) {
        if (!monitorSetSpecs.containsEntry(tuple._1(), tuple(tuple._2(), true))) {
            updateChainingArgs.put(tuple._2(), tuple(tuple._1(), EMPTY_PARAMETER_SET));
            monitorSetSpecs.put(tuple._1(), tuple(EMPTY_PARAMETER_SET, true));
        }
    }
}

From source file:org.eclipse.sirius.business.internal.session.danalysis.MovidaSupport.java

void registryChanged(final org.eclipse.sirius.business.internal.movida.registry.ViewpointRegistry registry,
        Set<URI> removed, Set<URI> added, Set<URI> changed) {
    TransactionalEditingDomain transactionalEditingDomain = session.getTransactionalEditingDomain();
    Set<URI> selected = Sets.newHashSet(
            Iterables.transform(session.getSelectedViewpoints(false), new Function<Viewpoint, URI>() {
                public URI apply(Viewpoint from) {
                    return new ViewpointQuery(from).getViewpointURI().get();
                }/* w ww. j  a  va2s.c  o m*/
            }));
    final SetView<URI> unavailable = Sets.intersection(selected, removed);
    if (!unavailable.isEmpty()) {
        deselectMissingViewpoints(unavailable);
    }
    Set<URI> resourcesLoaded = vsmResources;
    Set<URI> resourcesRequired = new VSMResolver(registry).resolve(selected);
    Set<URI> resourcesChanged = Sets
            .newHashSet(Iterables.transform(Sets.intersection(changed, selected), new Function<URI, URI>() {
                public URI apply(URI logicalURI) {
                    return registry.getProvider(logicalURI).get();
                };
            }));
    for (URI uri : Sets.difference(resourcesLoaded, resourcesRequired)) {
        // The resource was loaded but is not required anymore.
        // Unload & remove.
        Resource vsm = transactionalEditingDomain.getResourceSet().getResource(uri, false);
        new ViewpointResourceOperations(vsm).unloadAndResetProxyURIs();
        transactionalEditingDomain.getResourceSet().getResources().remove(vsm);
    }
    for (URI uri : resourcesChanged) {
        // The resource is loaded and still required, but its content
        // has changed: unload it.
        Resource vsm = transactionalEditingDomain.getResourceSet().getResource(uri, false);
        if (vsm != null) {
            new ViewpointResourceOperations(vsm).unloadAndResetProxyURIs();
        }
    }
    for (URI uri : Sets.difference(resourcesRequired, resourcesLoaded)) {
        transactionalEditingDomain.getResourceSet().getResource(uri, true);
    }
    for (DAnalysis analysis : session.allAnalyses()) {
        EcoreUtil.resolveAll(analysis);
    }
    vsmResources = resourcesRequired;
    transactionalEditingDomain.getCommandStack().execute(new RecordingCommand(transactionalEditingDomain) {
        @Override
        protected void doExecute() {
            for (DView view : session.getSelectedViews()) {
                for (DRepresentation representation : view.getAllRepresentations()) {
                    DialectManager.INSTANCE.refreshEffectiveRepresentationDescription(representation,
                            new NullProgressMonitor());
                }
            }
        }
    });
}

From source file:tech.beshu.ror.acl.blocks.rules.impl.GroupsAsyncRule.java

@Override
public CompletableFuture<RuleExitResult> match(__old_RequestContext rc) {

    // All configured groups in a block's group rule, contextualized
    Set<String> resolvedGroups = settings.getGroups().stream().map(g -> g.getValue(rc))
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toSet());

    List<UserSettings> userSettingsToCheck = settings.getUsersSettings();

    // Filter the userSettings to leave only the ones which include the current group
    // #TODO move to proper use of optional
    final String preferredGroup = rc.getLoggedInUser().isPresent()
            ? rc.getLoggedInUser().get().resolveCurrentGroup(rc.getHeaders()).orElse(null)
            : new LoggedUser("x").resolveCurrentGroup(rc.getHeaders()).orElse(null);

    // Exclude userSettings that don't contain groups in this groupRule
    userSettingsToCheck = userSettingsToCheck.stream()
            .filter(us -> !Sets.intersection(us.getGroups(), resolvedGroups).isEmpty())
            .collect(Collectors.toList());

    if (!Strings.isNullOrEmpty(preferredGroup)) {
        if (!resolvedGroups.contains(preferredGroup)) {
            return CompletableFuture.completedFuture(NO_MATCH);
        }/*from  w ww  .  j  a  va  2s  . co m*/
    }

    if (userSettingsToCheck.isEmpty()) {
        return CompletableFuture.completedFuture(NO_MATCH);
    }

    // Check remaining userSettings for matching auth
    return FuturesSequencer.runInSeqUntilConditionIsUndone(

            // Iterator of users which match at least one group in this block's group rule
            userSettingsToCheck.iterator(),

            // Asynchronously map for each userSetting, return MATCH when we authenticated the first user
            uSettings -> {
                if (!Strings.isNullOrEmpty(preferredGroup) && !uSettings.getGroups().contains(preferredGroup)) {
                    return CompletableFuture.completedFuture(NO_MATCH);
                }
                return users.get(uSettings.getUsername()).getAuthKeyRule().match(rc).exceptionally(e -> {
                    e.printStackTrace();
                    return NO_MATCH;
                }).thenApply(rExitRes -> {
                    if (!rExitRes.isMatch()) {
                        return rExitRes;
                    }
                    if (!rc.getLoggedInUser().filter(lu -> uSettings.getUsername().equals(lu.getId()))
                            .isPresent()) {
                        // User is authenticated, but was not declared as "username"
                        return NO_MATCH;
                    }
                    return rExitRes;
                });
            },

            // Boolean decision (true = break loop)
            (uSettings, ruleExit) -> {

                if (!ruleExit.isMatch() && rc.getLoggedInUser().isPresent()) {
                    return false;
                }

                // Now that we have a user, and we know this is a match, we can populate the headers.
                if (ruleExit.isMatch()) {
                    rc.getLoggedInUser().ifPresent(lu -> {
                        User u = users.get(lu.getId());
                        if (u != null) {
                            lu.addAvailableGroups(u.getGroups());
                            Optional<String> cu = lu.resolveCurrentGroup(rc.getHeaders());
                            if (!cu.isPresent() && ruleExit.isMatch()) {
                                lu.setCurrentGroup(resolvedGroups.iterator().next());
                            }
                        }
                    });
                }
                return ruleExit.isMatch();
            },

            // If never true..
            nothing -> NO_MATCH).exceptionally(e -> {
                e.printStackTrace();
                throw new CompletionException(e);
            });

}

From source file:com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.helpers.CGraphSelector.java

/**
 * Function which handles the selection of nodes in a path finding scenario. The function performs
 * four BFS runs: BFS 1 searches for all successors of the start nodes. BFS 2 searches for all
 * predecessors of the end nodes. BFS 2 searches for all predecessors of the start nodes. BFS 4
 * searches for all successors of the end nodes.
 * /*from ww  w.ja va  2  s .  co  m*/
 * These four BFS runs are used in two sets: Set 1 is intersect of nodes reached through (BFS 1,
 * BFS 2). Set 2 is intersect of nodes reached through (BFS 3, BFS 4).
 * 
 * Therefore Set 1 represents all nodes on paths if the set of start nodes contains parents of the
 * newly selected node and Set 2 represents all nodes on paths if the set of start nodes contains
 * child nodes of the newly selected node.
 * 
 * 
 * @param graph The graph in which the selection takes place.
 * @param alreadySelectedNodes The List of nodes already selected.
 * @param newlySelectedNode The node which is newly selected.
 */
@SuppressWarnings("unchecked")
public static <NodeType extends ZyGraphNode<?>> void selectPath(final AbstractZyGraph<NodeType, ?> graph,
        final ArrayList<NodeType> alreadySelectedNodes, final NodeType newlySelectedNode) {
    final Function<NodeType, Node> function = new Function<NodeType, Node>() {
        @Override
        public Node apply(final NodeType input) {
            return input.getNode();
        }
    };

    final Collection<Node> foo = Collections2.transform(alreadySelectedNodes, function);

    final NodeList startNodes = new NodeList(foo.iterator());
    final NodeList endNodes = new NodeList(newlySelectedNode.getNode());

    final Set<Node> startSuccSet = new HashSet<Node>();
    final NodeList[] nodeListsStartSucc = Bfs.getLayers(graph.getGraph(), startNodes, Bfs.DIRECTION_SUCCESSOR,
            graph.getGraph().createNodeMap(), 0);
    for (final NodeList nodeList : nodeListsStartSucc) {
        startSuccSet.addAll(nodeList);
    }
    final Set<Node> endPredSet = new HashSet<Node>();
    final NodeList[] nodeListsEndPred = Bfs.getLayers(graph.getGraph(), endNodes, Bfs.DIRECTION_PREDECESSOR,
            graph.getGraph().createNodeMap(), 0);
    for (final NodeList nodeList : nodeListsEndPred) {
        endPredSet.addAll(nodeList);
    }

    final SetView<Node> startBeforeEndSetView = Sets.intersection(startSuccSet, endPredSet);
    if (!startBeforeEndSetView.isEmpty()) {
        for (final Node node : startBeforeEndSetView) {
            graph.getGraph().setSelected(node, true);
        }
    }

    final Set<Node> startPredSet = new HashSet<Node>();
    final NodeList[] nodeListsStartPred = Bfs.getLayers(graph.getGraph(), startNodes, Bfs.DIRECTION_PREDECESSOR,
            graph.getGraph().createNodeMap(), 0);
    for (final NodeList nodeList : nodeListsStartPred) {
        startPredSet.addAll(nodeList);
    }

    final Set<Node> endSuccSet = new HashSet<Node>();
    final NodeList[] nodeListsEndSucc = Bfs.getLayers(graph.getGraph(), endNodes, Bfs.DIRECTION_SUCCESSOR,
            graph.getGraph().createNodeMap(), 0);
    for (final NodeList nodeList : nodeListsEndSucc) {
        endSuccSet.addAll(nodeList);
    }

    final SetView<Node> endBeforeStartSetView = Sets.intersection(startPredSet, endSuccSet);
    if (!endBeforeStartSetView.isEmpty()) {
        for (final Node node : endBeforeStartSetView) {
            graph.getGraph().setSelected(node, true);
        }
    }
}

From source file:org.apache.accumulo.tserver.compaction.CompactionPlan.java

/**
 * Validate compaction plan./*  w  w  w.  ja  v  a2  s . c  o m*/
 *
 * @param allFiles
 *          All possible files
 * @throws IllegalStateException
 *           thrown when validation fails.
 */
public final void validate(Set<FileRef> allFiles) {
    Set<FileRef> inputSet = new HashSet<FileRef>(inputFiles);
    Set<FileRef> deleteSet = new HashSet<FileRef>(deleteFiles);

    if (!allFiles.containsAll(inputSet)) {
        inputSet.removeAll(allFiles);
        throw new IllegalStateException("plan inputs contains files not in allFiles " + inputSet);
    }

    if (!allFiles.containsAll(deleteSet)) {
        deleteSet.removeAll(allFiles);
        throw new IllegalStateException("plan deletes contains files not in allFiles " + deleteSet);
    }

    if (!Collections.disjoint(inputSet, deleteSet)) {
        throw new IllegalStateException("plan contains overlap in inputFiles and deleteFiles "
                + Sets.intersection(inputSet, deleteSet));
    }
}

From source file:org.caleydo.view.relationshipexplorer.ui.collection.AEntityCollection.java

@Override
public void setSelectedItems(Set<Object> elementIDs) {
    this.selectedElementIDs = new HashSet<>(Sets.intersection(elementIDs, allElementIDs));
    // notifySelectionUpdate(updateSource);
}

From source file:com.github.rinde.rinsim.central.SolverValidator.java

/**
 * Validates the inputs for {@link Solver#solve(GlobalStateObject)} method. If
 * the input is not correct an {@link IllegalArgumentException} is thrown.
 * @param state The state to validate.//from w  w  w  .j a v a  2  s  .c om
 * @return The state.
 */
public static GlobalStateObject validateInputs(GlobalStateObject state) {
    checkArgument(state.getTime() >= 0, "Time must be >= 0, is %s.", state.getTime());
    checkArgument(!state.getVehicles().isEmpty(), "At least one vehicle must be present.");

    final Set<Parcel> inventoryParcels = newHashSet();
    final boolean routeIsPresent = state.getVehicles().get(0).getRoute().isPresent();
    final Set<Parcel> allParcels = newHashSet();
    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject vs = state.getVehicles().get(i);
        checkArgument(vs.getRoute().isPresent() == routeIsPresent,
                "Either a route should be present for all vehicles, or no route "
                        + "should be present for all vehicles.");
        if (vs.getRoute().isPresent()) {
            for (final Parcel p : vs.getRoute().get()) {
                checkArgument(!allParcels.contains(p),
                        "Found parcel which is already present in the route of another "
                                + "vehicle. %s is found in vehicle %s.",
                        p, i);
            }
            allParcels.addAll(vs.getRoute().get());
        }
    }

    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject vs = state.getVehicles().get(i);

        checkArgument(vs.getRemainingServiceTime() >= 0, "Remaining service time must be >= 0, is %s.",
                vs.getRemainingServiceTime());
        final Set<Parcel> intersection = Sets.intersection(state.getAvailableParcels(), vs.getContents());
        checkArgument(intersection.isEmpty(),
                "Parcels can not be available AND in the inventory of a vehicle, " + "found: %s.",
                intersection);
        final Set<Parcel> inventoryIntersection = Sets.intersection(inventoryParcels, vs.getContents());
        checkArgument(inventoryIntersection.isEmpty(),
                "Parcels can not be in the inventory of two vehicles at the same " + "time, found: %s.",
                inventoryIntersection);
        inventoryParcels.addAll(vs.getContents());

        // if the destination parcel is not available, it must be in the
        // cargo of the vehicle
        if (vs.getDestination().isPresent()) {
            final boolean isAvailable = state.getAvailableParcels().contains(vs.getDestination().get());
            final boolean isInCargo = vs.getContents().contains(vs.getDestination().get());
            checkArgument(isAvailable != isInCargo,
                    "Destination must be either available (%s) or in the current "
                            + "vehicle's cargo (%s), but not both (i.e. XOR). Destination: "
                            + "%s, vehicle: %s (out of %s), remaining service time: %s.",
                    isAvailable, isInCargo, vs.getDestination(), i, state.getVehicles().size(),
                    vs.getRemainingServiceTime());
        }

        if (vs.getRoute().isPresent()) {
            checkRoute(vs, i);
        }
    }
    return state;
}

From source file:com.b2international.index.revision.DefaultRevisionIndex.java

@Override
public <T> T read(final String branchPath, final RevisionIndexRead<T> read) {
    if (RevisionIndex.isBaseRefPath(branchPath)) {
        final String branchPathWithoutBaseRef = branchPath.substring(0, branchPath.length() - 1);
        if (RevisionBranch.MAIN_PATH.equals(branchPathWithoutBaseRef)) {
            throw new IllegalArgumentException("Cannot query base of MAIN branch");
        }/*from www. j a  va 2  s  . c  om*/
        final RevisionBranch parent = getParentBranch(branchPathWithoutBaseRef);
        final RevisionBranch branch = getBranch(branchPathWithoutBaseRef);
        final Set<Integer> commonPath = Sets.intersection(branch.segments(), parent.segments());
        final RevisionBranch baseOfBranch = new RevisionBranch(parent.path(),
                Ordering.natural().max(commonPath), commonPath);
        return read(baseOfBranch, read);
    } else if (RevisionIndex.isRevRangePath(branchPath)) {
        final String[] branches = RevisionIndex.getRevisionRangePaths(branchPath);
        final String basePath = branches[0];
        final String comparePath = branches[1];
        final RevisionBranch base = getBranch(basePath);
        final RevisionBranch compare = getBranch(comparePath);
        final Set<Integer> compareSegments = Sets.difference(compare.segments(), base.segments());
        return read(new RevisionBranch(comparePath, compare.segmentId(), compareSegments), read);
    } else {
        return read(getBranch(branchPath), read);
    }
}

From source file:com.facebook.buck.android.relinker.RelinkerRule.java

private static String getVersionScript(Set<String> needed, Set<String> provided) {
    Set<String> keep = new ImmutableSet.Builder<String>().addAll(Sets.intersection(needed, provided))
            .addAll(Sets.filter(provided, s -> {
                if (s.contains("JNI_OnLoad")) {
                    return true;
                }/* w  ww  . j  a  va 2s . com*/
                if (s.contains("Java_")) {
                    return true;
                }
                return false;
            })).build();
    String res = "{\n";
    if (!keep.isEmpty()) {
        res += "global:\n";
    }
    for (String s : keep) {
        res += "  " + s + ";\n";
    }
    res += "local: *;\n};\n";
    return res;
}