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:org.caleydo.view.tourguide.impl.PAGEAlgorithm.java

@Override
protected float computePValueImpl(Set<Integer> geneSet, IProgressMonitor monitor) {
    float z = compute(geneSet, monitor);
    if (Float.isNaN(z))
        return Float.NaN;
    int m = Sets.intersection(foldChanges.keySet(), geneSet).size();
    if (m == 0)//from   ww w.j  ava 2  s  .  co  m
        return Float.NaN;
    TDistributionImpl t = new TDistributionImpl(m);
    float pValue = (float) t.density(z);
    return pValue;
}

From source file:org.ow2.play.governance.platform.user.service.PermissionCheck.java

/**
 * Get all the user resources and check if the input one is available with the given mode.
 *
 * @param user/*  w  w  w .j a  va 2 s. c  o  m*/
 * @param resource resource URI
 * @param mode mode URI
 * @return
 */
@Override
public boolean checkMode(String user, String resource, String mode) {
    // TODO : we should be able to do it in one mongodb query

    // load the user just one time instead of calling checkGroup N times...
    User u = null;
    try {
        u = userService.getUser(user);
    } catch (UserException e) {
        // logger
        e.printStackTrace();
    }

    return Sets.intersection(getGroupsForResourceInMode(resource, mode),
            Sets.newHashSet(Collections2.transform(u.groups, new Function<Resource, String>() {
                @Override
                public String apply(Resource input) {
                    System.out.println(input);
                    return input.uri + "#" + input.name;
                }
            }))).size() > 0;

}

From source file:com.querydsl.mongodb.MongodbSerializer.java

@SuppressWarnings("unchecked")
@Override/*from ww w . jav  a2s.  co  m*/
public Object visit(Operation<?> expr, Void context) {
    Operator op = expr.getOperator();
    if (op == Ops.EQ) {
        if (expr.getArg(0) instanceof Operation) {
            Operation<?> lhs = (Operation<?>) expr.getArg(0);
            if (lhs.getOperator() == Ops.COL_SIZE || lhs.getOperator() == Ops.ARRAY_SIZE) {
                return asDBObject(asDBKey(lhs, 0), asDBObject("$size", asDBValue(expr, 1)));
            } else {
                throw new UnsupportedOperationException("Illegal operation " + expr);
            }
        } else if (expr.getArg(0) instanceof Path) {
            Path<?> path = (Path<?>) expr.getArg(0);
            Constant<?> constant = (Constant<?>) expr.getArg(1);
            return asDBObject(asDBKey(expr, 0), convert(path, constant));
        }
    } else if (op == Ops.STRING_IS_EMPTY) {
        return asDBObject(asDBKey(expr, 0), "");

    } else if (op == Ops.AND) {
        BSONObject lhs = (BSONObject) handle(expr.getArg(0));
        BSONObject rhs = (BSONObject) handle(expr.getArg(1));
        if (Sets.intersection(lhs.keySet(), rhs.keySet()).isEmpty()) {
            lhs.putAll(rhs);
            return lhs;
        } else {
            BasicDBList list = new BasicDBList();
            list.add(handle(expr.getArg(0)));
            list.add(handle(expr.getArg(1)));
            return asDBObject("$and", list);
        }

    } else if (op == Ops.NOT) {
        //Handle the not's child
        Operation<?> subOperation = (Operation<?>) expr.getArg(0);
        Operator subOp = subOperation.getOperator();
        if (subOp == Ops.IN) {
            return visit(ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0),
                    subOperation.getArg(1)), context);
        } else {
            BasicDBObject arg = (BasicDBObject) handle(expr.getArg(0));
            return negate(arg);
        }

    } else if (op == Ops.OR) {
        BasicDBList list = new BasicDBList();
        list.add(handle(expr.getArg(0)));
        list.add(handle(expr.getArg(1)));
        return asDBObject("$or", list);

    } else if (op == Ops.NE) {
        Path<?> path = (Path<?>) expr.getArg(0);
        Constant<?> constant = (Constant<?>) expr.getArg(1);
        return asDBObject(asDBKey(expr, 0), asDBObject("$ne", convert(path, constant)));

    } else if (op == Ops.STARTS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1)));

    } else if (op == Ops.STARTS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.ENDS_WITH) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$"));

    } else if (op == Ops.ENDS_WITH_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.EQ_IGNORE_CASE) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.STRING_CONTAINS) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*"));

    } else if (op == Ops.STRING_CONTAINS_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.MATCHES) {
        return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString()));

    } else if (op == Ops.MATCHES_IC) {
        return asDBObject(asDBKey(expr, 0),
                Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE));

    } else if (op == Ops.LIKE) {
        String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
        return asDBObject(asDBKey(expr, 0), Pattern.compile(regex));

    } else if (op == Ops.BETWEEN) {
        BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1));
        value.append("$lte", asDBValue(expr, 2));
        return asDBObject(asDBKey(expr, 0), value);

    } else if (op == Ops.IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            @SuppressWarnings("unchecked") //guarded by previous check
            Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$in", values.toArray()));
        } else {
            Path<?> path = (Path<?>) expr.getArg(exprIndex);
            Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            return asDBObject(asDBKey(expr, exprIndex), convert(path, constant));
        }

    } else if (op == Ops.NOT_IN) {
        int constIndex = 0;
        int exprIndex = 1;
        if (expr.getArg(1) instanceof Constant<?>) {
            constIndex = 1;
            exprIndex = 0;
        }
        if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
            @SuppressWarnings("unchecked") //guarded by previous check
            Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$nin", values.toArray()));
        } else {
            Path<?> path = (Path<?>) expr.getArg(exprIndex);
            Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
            return asDBObject(asDBKey(expr, exprIndex), asDBObject("$ne", convert(path, constant)));
        }

    } else if (op == Ops.COL_IS_EMPTY) {
        BasicDBList list = new BasicDBList();
        list.add(asDBObject(asDBKey(expr, 0), new BasicDBList()));
        list.add(asDBObject(asDBKey(expr, 0), asDBObject("$exists", false)));
        return asDBObject("$or", list);

    } else if (op == Ops.LT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lt", asDBValue(expr, 1)));

    } else if (op == Ops.GT) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gt", asDBValue(expr, 1)));

    } else if (op == Ops.LOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$lte", asDBValue(expr, 1)));

    } else if (op == Ops.GOE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$gte", asDBValue(expr, 1)));

    } else if (op == Ops.IS_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", false));

    } else if (op == Ops.IS_NOT_NULL) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$exists", true));

    } else if (op == Ops.CONTAINS_KEY) {
        Path<?> path = (Path<?>) expr.getArg(0);
        Expression<?> key = expr.getArg(1);
        return asDBObject(visit(path, context) + "." + key.toString(), asDBObject("$exists", true));

    } else if (op == MongodbOps.NEAR) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1)));

    } else if (op == MongodbOps.NEAR_SPHERE) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$nearSphere", asDBValue(expr, 1)));

    } else if (op == MongodbOps.ELEM_MATCH) {
        return asDBObject(asDBKey(expr, 0), asDBObject("$elemMatch", asDBValue(expr, 1)));
    }

    throw new UnsupportedOperationException("Illegal operation " + expr);
}

From source file:de.bund.bfr.knime.openkrise.util.network.ToKnimeNetworkNodeModel.java

/**
 * {@inheritDoc}/*  w  w  w  .  j  av a 2s  .  c  o m*/
 */
@Override
protected PortObject[] executeInternal(PortObject[] inObjects, ExecutionContext exec) throws Exception {
    BufferedDataTable nodeTable = (BufferedDataTable) inObjects[0];
    BufferedDataTable edgeTable = (BufferedDataTable) inObjects[1];
    NodePropertySchema nodeSchema = new NodePropertySchema(TracingUtils.getTableColumns(nodeTable.getSpec()),
            TracingColumns.ID);
    EdgePropertySchema edgeSchema = new EdgePropertySchema(TracingUtils.getTableColumns(edgeTable.getSpec()),
            TracingColumns.ID, TracingColumns.FROM, TracingColumns.TO);
    Map<String, GraphNode> nodes = TracingUtils.readGraphNodes(nodeTable, nodeSchema);
    Set<RowKey> skippedEdgeRows = new LinkedHashSet<>();
    Map<String, Edge<GraphNode>> edges = CanvasUtils
            .getElementsById(TracingUtils.readEdges(edgeTable, edgeSchema, nodes, skippedEdgeRows));

    for (RowKey key : skippedEdgeRows) {
        setWarningMessage("Delivery Table: Row " + key.getString() + " skipped");
    }

    if (!addPrefix.getBooleanValue() && !Sets.intersection(nodes.keySet(), edges.keySet()).isEmpty()) {
        throw new Exception(
                "Some stations and deliveries are using the same IDs. Therefore you must enable \"Add Prefix to Node and Edge IDs\".");
    }

    KPartiteGraph<PersistentObject, Partition> net = GraphFactory.createNet(NET_ID, NET_URI);
    String nodeIdPrefix = addPrefix.getBooleanValue() ? "Node:" : "";
    String edgeIdPrefix = addPrefix.getBooleanValue() ? "Edge:" : "";

    net.defineFeature(StandardFeature.IS_TARGET);

    for (Edge<GraphNode> e : edges.values()) {
        PersistentObject from = net.createNode(nodeIdPrefix + e.getFrom().getId());
        PersistentObject to = net.createNode(nodeIdPrefix + e.getTo().getId());
        PersistentObject edge = net.createEdge(edgeIdPrefix + e.getId(), from, to);

        net.addFeature(new EndObject(to, edge), StandardFeature.IS_TARGET.getName(), Boolean.TRUE);
    }

    return new PortObject[] { new GraphPortObject<>(net) };
}

From source file:com.facebook.buck.tools.consistency.RuleKeyDiffer.java

private void printDiff(ParsedRuleKeyFile originalFile, RuleKeyNode originalRuleKey, ParsedRuleKeyFile newFile,
        RuleKeyNode newRuleKey, int visitId) throws MaxDifferencesException, GraphTraversalException {
    if (originalRuleKey.ruleKey.key.equals(newRuleKey.ruleKey.key)) {
        return;//w  w  w .j  av  a2 s.  c  o  m
    }

    if (originalRuleKey.lastVisitId == visitId && newRuleKey.lastVisitId == visitId) {
        return;
    }

    originalRuleKey.lastVisitId = visitId;
    newRuleKey.lastVisitId = visitId;

    Set<String> originalRuleKeyProperties = originalRuleKey.ruleKey.values.keySet();
    Set<String> newRuleKeyProperties = newRuleKey.ruleKey.values.keySet();
    Set<String> onlyInOriginalKey = Sets.difference(originalRuleKeyProperties, newRuleKeyProperties);
    Set<String> onlyInNewKey = Sets.difference(newRuleKeyProperties, originalRuleKeyProperties);
    Set<String> inBoth = Sets.intersection(originalRuleKeyProperties, newRuleKeyProperties);

    String target = RuleKeyDiffPrinter.getRuleKeyName(originalFile, originalRuleKey.ruleKey);

    try (TargetScope targetScope = printer.addTarget(target, originalRuleKey.ruleKey.key,
            newRuleKey.ruleKey.key)) {
        try (PropertyScope rootProperty = targetScope.addProperty("")) {
            for (String key : onlyInOriginalKey) {
                try (PropertyScope propertyScope = rootProperty.addNestedProperty(key)) {
                    propertyScope.removed(originalFile, originalRuleKey.ruleKey.values.get(key));
                }
            }
            for (String key : onlyInNewKey) {
                try (PropertyScope propertyScope = rootProperty.addNestedProperty(key)) {
                    propertyScope.added(newFile, newRuleKey.ruleKey.values.get(key));
                }
            }
            for (String key : inBoth) {
                try (PropertyScope propertyScope = rootProperty.addNestedProperty(key)) {
                    printDiff(propertyScope, originalFile, originalRuleKey.ruleKey.values.get(key), newFile,
                            newRuleKey.ruleKey.values.get(key));
                }
            }
        }
    } catch (MaxDifferencesException e) {
        throw e;
    } catch (Exception e) {
        throw new GraphTraversalException(e, "Unexpected error while traversing rule key graph");
    }
}

From source file:org.apache.aurora.scheduler.AcceptedOffer.java

private static List<Resource> allocateRangeType(List<Resource.Builder> from, Set<Integer> valueSet)
        throws Resources.InsufficientResourcesException {

    Set<Integer> leftOver = Sets.newHashSet(valueSet);
    ImmutableList.Builder<Resource> result = ImmutableList.<Resource>builder();
    for (Resource.Builder r : from) {
        Set<Integer> fromResource = Sets.newHashSet(Iterables
                .concat(Iterables.transform(r.getRanges().getRangeList(), Resources.RANGE_TO_MEMBERS)));
        Set<Integer> available = Sets.newHashSet(Sets.intersection(leftOver, fromResource));
        if (available.isEmpty()) {
            continue;
        }/*  www .  j a  v a 2s . c  om*/
        Resource newResource = makeMesosRangeResource(r.build(), available);
        result.add(newResource);
        leftOver.removeAll(available);
        if (leftOver.isEmpty()) {
            break;
        }
    }
    if (!leftOver.isEmpty()) {
        // NOTE: this will not happen as long as Veto logic from TaskAssigner.maybeAssign is
        // consistent.
        // Maybe we should consider implementing resource veto with this class to ensure that.
        throw new Resources.InsufficientResourcesException(
                "Insufficient resource for range type when allocating from offer");
    }
    return result.build();
}

From source file:org.calrissian.accumulorecipes.commons.support.qfd.planner.visitors.CalculateShardsVisitor.java

private Set<String> getShards(ParentNode node) {

    /**//from w ww  .j ava  2 s .  c  o m
     * First, we grab all shards for all subtrees (until we reach the leaves).
     */
    Set<Set<String>> resultShards = new HashSet<Set<String>>();
    for (Node child : node.children()) {
        if (child instanceof AndNode || child instanceof OrNode)
            resultShards.add(getShards((ParentNode) child));
        else if (child instanceof Leaf) {
            Set<String> childShards = getShards((Leaf) child);
            resultShards.add(childShards);
        }
    }

    Set<String> combinedSet = null;

    /**
     * We want to intersect the shards for all AND queries since the query will only return true for
     * shards that will all make the tree return true.
     */

    // if the parent is an AndNode, we need to intersect keysToShards
    if (node instanceof AndNode) {
        for (Set<String> curShards : resultShards) {
            if (combinedSet == null)
                combinedSet = curShards;
            else {
                Set<String> intersected = Sets.intersection(combinedSet, curShards);
                combinedSet = new HashSet<String>(intersected);
            }
        }

        /**
         * For OR nodes, we can just union the shards together because any one of the shards
         * will make the tree return true.
         */

    } else {
        for (Set<String> curShards : resultShards) {
            if (combinedSet == null)
                combinedSet = Sets.newHashSet();
            combinedSet.addAll(curShards);
        }
    }

    return (combinedSet != null ? combinedSet : Sets.<String>newHashSet());
}

From source file:org.sonar.batch.source.ZeroCoverageSensor.java

private boolean isCoverageMeasuresAlreadyDefined(InputFile f) {
    Set<String> metricKeys = newHashSet(
            transform(measureCache.byComponentKey(f.key()), new MeasureToMetricKey()));
    Function<Metric, String> metricToKey = new MetricToKey();
    Set<String> allCoverageMetricKeys = newHashSet(
            concat(transform(CoverageType.UNIT.allMetrics(), metricToKey),
                    transform(CoverageType.IT.allMetrics(), metricToKey),
                    transform(CoverageType.OVERALL.allMetrics(), metricToKey)));
    return !Sets.intersection(metricKeys, allCoverageMetricKeys).isEmpty();
}

From source file:org.apache.sentry.provider.db.generic.service.thrift.SearchProviderBackend.java

@Override
public ImmutableSet<String> getRoles(Set<String> groups, ActiveRoleSet roleSet) {
    if (!initialized) {
        throw new IllegalStateException("SearchProviderBackend has not been properly initialized");
    }/*w w w .  j a v  a  2  s  . c om*/
    SearchPolicyServiceClient client = null;
    try {
        Set<TSentryRole> tRoles = Sets.newHashSet();
        client = getClient();
        //get the roles according to group
        for (String group : groups) {
            tRoles.addAll(client.listRolesByGroupName(subject.getName(), group));
        }
        Set<String> roles = Sets.newHashSet();
        for (TSentryRole tRole : tRoles) {
            roles.add(tRole.getRoleName());
        }
        return ImmutableSet.copyOf(roleSet.isAll() ? roles : Sets.intersection(roles, roleSet.getRoles()));
    } catch (SentryUserException e) {
        String msg = "Unable to obtain roles from server: " + e.getMessage();
        LOGGER.error(msg, e);
    } catch (Exception e) {
        String msg = "Unable to obtain client:" + e.getMessage();
        LOGGER.error(msg, e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return ImmutableSet.of();
}

From source file:c5db.interfaces.replication.QuorumConfiguration.java

private static <T> boolean setComprisesMajorityOfAnotherSet(Set<T> sourceSet, Set<T> destinationSet) {
    return Sets.intersection(sourceSet, destinationSet)
            .size() >= calculateNumericalMajority(destinationSet.size());
}