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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the difference of two sets.

Usage

From source file:com.bodybuilding.argos.discovery.AbstractClusterDiscovery.java

/**
 * Construct AbstractClusterDiscovery that calls {@link #getCurrentClusters()} on the specified interval
 * @param interval//from   w w w  .j  a va 2 s .c o m
 * @param timeUnit
 */
public AbstractClusterDiscovery(long interval, TimeUnit timeUnit) {
    this.updateIntervalMs = timeUnit.toMillis(interval);

    clusterObservable = observeUpdateClusters().retry().flatMap(clusterList -> {
        List<Cluster> updates = Lists.newArrayList();
        clusterList.stream().forEach(c -> {
            // update our tracked clusters for any new or downed clusters
            if (trackedClusters.containsKey(c.getName()) && !c.isActive()) {
                trackedClusters.remove(c.getName());
                updates.add(c);
            } else if (c.isActive() && !trackedClusters.containsKey(c.getName())) {
                trackedClusters.put(c.getName(), c);
                updates.add(c);
            }
        });
        // find clusters not returned from the latest update
        Set<String> discoveredClusters = clusterList.stream().map(Cluster::getName).collect(Collectors.toSet());
        Sets.SetView<String> missingClusterNames = Sets.difference(trackedClusters.keySet(),
                discoveredClusters);
        missingClusterNames.stream().forEach(name -> {
            Cluster c = trackedClusters.get(name);
            updates.add(new Cluster(c.getName(), c.getUrl(), false));
            trackedClusters.remove(c.getName());
        });

        return Observable.from(updates);
    })
            // we want to clear the list when all subscribers are unsubscribed.
            .doOnUnsubscribe(trackedClusters::clear);
}

From source file:see.reactive.impl.AbstractOrderedSignal.java

private void updateDependencies(Set<? extends AbstractOrderedSignal<?>> dependencies) {
    Set<? extends AbstractOrderedSignal<?>> toAdd = copyOf(Sets.difference(dependencies, this.dependencies));
    Set<? extends AbstractOrderedSignal<?>> toRemove = copyOf(Sets.difference(this.dependencies, dependencies));

    for (AbstractOrderedSignal<?> signal : toAdd) {
        addDependency(signal);/*ww  w .j ava 2  s . co  m*/
    }

    for (AbstractOrderedSignal<?> signal : toRemove) {
        removeDependency(signal);
    }
    this.level = getMaxLevel(dependencies);
}

From source file:modules.ChromeCLIMonitorModule.java

@Override
public void processOut(String extractNative) {
    HashSet<String> res = new HashSet<String>();
    String lines[] = extractNative.split("\\r?\\n");
    for (int n = 0; n < lines.length; n++) {
        if (lines[n].startsWith("["))
            res.add(lines[n].substring(lines[n].indexOf(' ') + 1));
    }//  www. java  2 s  . c  o  m
    if (prev != null) {
        for (String o : Sets.difference(prev, res)) {
            disappear(o);
        }
        for (String o : Sets.difference(res, prev)) {
            appear(o);
        }
    } else {
        for (String o : res) {
            appear(o);
        }
    }
    prev = res;
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.ManyClientPoolingContainer.java

public synchronized void setNewHosts(CassandraKeyValueServiceConfig config) {
    String keyspace = config.keyspace();
    int poolSize = config.poolSize();
    boolean isSsl = config.ssl();
    int socketTimeoutMillis = config.socketTimeoutMillis();
    int socketQueryTimeoutMillis = config.socketQueryTimeoutMillis();

    Set<InetSocketAddress> toRemove = Sets.difference(containerMap.keySet(), config.servers()).immutableCopy();
    Set<InetSocketAddress> toAdd = Sets.difference(config.servers(), containerMap.keySet()).immutableCopy();
    for (InetSocketAddress addr : toRemove) {
        PoolingContainer<Client> pool = containerMap.remove(addr);
        Preconditions.checkNotNull(pool);
        log.warn("Shutting down client pool for {}", addr);
        pool.shutdownPooling();//from   ww  w . j  a  va  2  s . c o  m
    }

    if (!toAdd.isEmpty()) {
        CassandraVerifier.sanityCheckRingConsistency(Sets.union(containerMap.keySet(), toAdd), keyspace, isSsl,
                safetyDisabled, socketTimeoutMillis, socketQueryTimeoutMillis);
    }

    for (InetSocketAddress addr : toAdd) {
        if (isShutdown) {
            log.warn("client Pool is shutdown, cannot add hosts:{}", toAdd);
            break;
        }
        PoolingContainer<Client> newPool = createPool(addr, keyspace, poolSize, isSsl, socketTimeoutMillis,
                socketQueryTimeoutMillis);
        containerMap.put(addr, newPool);
        log.info("Created pool {} for host {}", newPool, addr);
    }
    containers = ImmutableList.copyOf(containerMap.values());
}

From source file:com.google.gerrit.server.git.GarbageCollection.java

public GarbageCollectionResult run(List<Project.NameKey> projectNames, PrintWriter writer) {
    GarbageCollectionResult result = new GarbageCollectionResult();
    Set<Project.NameKey> projectsToGc = gcQueue.addAll(projectNames);
    for (Project.NameKey projectName : Sets.difference(Sets.newHashSet(projectNames), projectsToGc)) {
        result.addError(new GarbageCollectionResult.Error(
                GarbageCollectionResult.Error.Type.GC_ALREADY_SCHEDULED, projectName));
    }/* ww w .j  a  va  2  s. co m*/
    for (Project.NameKey p : projectsToGc) {
        Repository repo = null;
        try {
            repo = repoManager.openRepository(p);
            logGcConfiguration(p, repo);
            print(writer, "collecting garbage for \"" + p + "\":\n");
            GarbageCollectCommand gc = Git.wrap(repo).gc();
            logGcInfo(p, "before:", gc.getStatistics());
            gc.setProgressMonitor(
                    writer != null ? new TextProgressMonitor(writer) : NullProgressMonitor.INSTANCE);
            Properties statistics = gc.call();
            logGcInfo(p, "after: ", statistics);
            print(writer, "done.\n\n");
        } catch (RepositoryNotFoundException e) {
            logGcError(writer, p, e);
            result.addError(new GarbageCollectionResult.Error(
                    GarbageCollectionResult.Error.Type.REPOSITORY_NOT_FOUND, p));
        } catch (IOException e) {
            logGcError(writer, p, e);
            result.addError(new GarbageCollectionResult.Error(GarbageCollectionResult.Error.Type.GC_FAILED, p));
        } catch (GitAPIException e) {
            logGcError(writer, p, e);
            result.addError(new GarbageCollectionResult.Error(GarbageCollectionResult.Error.Type.GC_FAILED, p));
        } catch (JGitInternalException e) {
            logGcError(writer, p, e);
            result.addError(new GarbageCollectionResult.Error(GarbageCollectionResult.Error.Type.GC_FAILED, p));
        } finally {
            if (repo != null) {
                repo.close();
            }
            gcQueue.gcFinished(p);
        }
    }
    return result;
}

From source file:com.facebook.buck.testutil.JsonMatcher.java

/**
 * Static method which tries to match 2 JsonNode objects recursively.
 *
 * @param path:        Path to start matching the objects from.
 * @param expected:    First JsonNode.//  ww  w. j a va2  s  .c  o m
 * @param actual:      Second JsonNode.
 * @param description: The Description to be appended to.
 * @return true if the 2 objects match, false otherwise.
 */
private static boolean matchJsonObjects(String path, JsonNode expected, JsonNode actual,
        Description description) {
    if (expected != null && actual != null && expected.isObject()) {
        if (!actual.isObject()) {
            description.appendText(String.format("the JsonNodeType is not OBJECT at path [%s]", path));
            return false;
        }
        HashSet<String> expectedFields = Sets.newHashSet(expected.fieldNames());
        HashSet<String> actualFields = Sets.newHashSet(actual.fieldNames());

        for (String field : expectedFields) {
            if (!actualFields.contains(field)) {
                description.appendText(String.format("expecting field [%s] at path [%s]", field, path));
                return false;
            }
            if (!matchJsonObjects(path + "/" + field, expected.get(field), actual.get(field), description)) {
                return false;
            }
        }
        if (!Sets.newHashSet().equals(Sets.difference(actualFields, expectedFields))) {
            description.appendText(String.format("found unexpected fields %s at path [%s]",
                    Sets.difference(actualFields, expectedFields).toString(), path));
            return false;
        }
    }
    if (!expected.equals(actual)) {
        description.appendText(String.format("mismatch at path [%s]", path));
        return false;
    }
    return true;
}

From source file:org.opendaylight.netconf.impl.NetconfServerSessionNegotiatorFactory.java

private static ImmutableSet<String> validateBaseCapabilities(final Set<String> baseCapabilities) {
    // Check base capabilities to be supported by the server
    final Sets.SetView<String> unknownBaseCaps = Sets.difference(baseCapabilities, DEFAULT_BASE_CAPABILITIES);
    Preconditions.checkArgument(unknownBaseCaps.isEmpty(),
            "Base capabilities that will be supported by netconf server have to be subset of %s, unknown base capabilities: %s",
            DEFAULT_BASE_CAPABILITIES, unknownBaseCaps);

    final ImmutableSet.Builder<String> b = ImmutableSet.builder();
    b.addAll(baseCapabilities);//from  w  w  w. j  a  v  a  2 s . co  m
    // Base 1.0 capability is supported by default
    b.add(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0);
    return b.build();
}

From source file:org.apache.james.mailbox.maildir.user.MaildirSubscriptionMapper.java

@Override
public void delete(Subscription subscription) throws SubscriptionException {
    // TODO: we need some kind of file locking here
    Set<String> subscriptionNames = readSubscriptionsForUser(subscription.getUser());
    Set<String> newSubscriptions = Sets.difference(subscriptionNames,
            ImmutableSet.of(subscription.getMailbox()));
    boolean changed = subscriptionNames.size() != newSubscriptions.size();
    if (changed) {
        try {//w  w w.j a va2 s. c  o  m
            writeSubscriptions(new File(store.userRoot(subscription.getUser())), newSubscriptions);
        } catch (IOException e) {
            throw new SubscriptionException(e);
        }
    }
}

From source file:no.ssb.vtl.script.operations.FoldOperation.java

/**
 * Checks that all of the given columns are present in the structure.
 *
 * @throws IllegalArgumentException if one or more columns are missing.
 *//* www.  j a  v  a2  s.co  m*/
private static void checkContainsColumns(DataStructure structure, ImmutableSet<String> columns) {
    Set<String> structureColumns = ImmutableSet.copyOf(structure.keySet());
    checkArgument(structureColumns.containsAll(columns), "the element(s) [%s] were not found",
            Sets.difference(columns, structureColumns));
}

From source file:org.sosy_lab.cpachecker.cpa.invariants.InvariantsMergeOperator.java

@Override
public AbstractState merge(AbstractState pState1, AbstractState pState2, Precision pPrecision)
        throws CPAException, InterruptedException {
    InvariantsState state1 = (InvariantsState) pState1;
    InvariantsState state2 = (InvariantsState) pState2;
    InvariantsPrecision precision = (InvariantsPrecision) pPrecision;
    boolean isMergeAllowed = isMergeAllowed(state1, state2, precision);
    AbstractionState abstractionState1 = state1.determineAbstractionState(precision);
    AbstractionState abstractionState2 = state2.determineAbstractionState(precision);
    Set<String> wideningTargets = abstractionState1.determineWideningTargets(abstractionState2);
    Set<InvariantsFormula<CompoundInterval>> wideningHints = Sets.union(abstractionState1.getWideningHints(),
            abstractionState2.getWideningHints());
    state1 = state1.widen(state2, precision, wideningTargets, wideningHints);
    if (state1 != pState1
            && definitelyImplies(state2, reduceToGivenVariables(reduceToInterestingVariables(state1, precision),
                    Sets.difference(state1.getEnvironment().keySet(), wideningTargets)))) {
        isMergeAllowed = true;//from www  .  jav  a2  s .c  o  m
    }
    InvariantsState result = state2;
    if (isMergeAllowed) {
        result = state1.join(state2, precision);
    }
    return result;
}