Example usage for com.google.common.collect MapDifference entriesOnlyOnRight

List of usage examples for com.google.common.collect MapDifference entriesOnlyOnRight

Introduction

In this page you can find the example usage for com.google.common.collect MapDifference entriesOnlyOnRight.

Prototype

Map<K, V> entriesOnlyOnRight();

Source Link

Document

Returns an unmodifiable map containing the entries from the right map whose keys are not present in the left map.

Usage

From source file:org.apache.fluo.recipes.core.map.it.DocumentObserver.java

private static Map<String, Long> calculateChanges(Map<String, Long> newCounts, Map<String, Long> currCounts) {
    Map<String, Long> changes = new HashMap<>();

    // guava Maps class
    MapDifference<String, Long> diffs = Maps.difference(currCounts, newCounts);

    // compute the diffs for words that changed
    changes.putAll(//from  ww w  .  j av  a2s.  com
            Maps.transformValues(diffs.entriesDiffering(), vDiff -> vDiff.rightValue() - vDiff.leftValue()));

    // add all new words
    changes.putAll(diffs.entriesOnlyOnRight());

    // subtract all words no longer present
    changes.putAll(Maps.transformValues(diffs.entriesOnlyOnLeft(), l -> l * -1));

    return changes;
}

From source file:org.apache.cassandra.db.DefsTables.java

private static Set<String> mergeKeyspaces(Map<DecoratedKey, ColumnFamily> before,
        Map<DecoratedKey, ColumnFamily> after) {
    List<Row> created = new ArrayList<>();
    List<String> altered = new ArrayList<>();
    Set<String> dropped = new HashSet<>();

    /*/*  w w w. ja  va  2  s . c o  m*/
     * - we don't care about entriesOnlyOnLeft() or entriesInCommon(), because only the changes are of interest to us
     * - of all entriesOnlyOnRight(), we only care about ones that have live columns; it's possible to have a ColumnFamily
     *   there that only has the top-level deletion, if:
     *      a) a pushed DROP KEYSPACE change for a keyspace hadn't ever made it to this node in the first place
     *      b) a pulled dropped keyspace that got dropped before it could find a way to this node
     * - of entriesDiffering(), we don't care about the scenario where both pre and post-values have zero live columns:
     *   that means that a keyspace had been recreated and dropped, and the recreated keyspace had never found a way
     *   to this node
     */
    MapDifference<DecoratedKey, ColumnFamily> diff = Maps.difference(before, after);

    for (Map.Entry<DecoratedKey, ColumnFamily> entry : diff.entriesOnlyOnRight().entrySet())
        if (entry.getValue().getColumnCount() > 0)
            created.add(new Row(entry.getKey(), entry.getValue()));

    for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering()
            .entrySet()) {
        String keyspaceName = AsciiType.instance.compose(entry.getKey().key);

        ColumnFamily pre = entry.getValue().leftValue();
        ColumnFamily post = entry.getValue().rightValue();

        if (pre.getColumnCount() > 0 && post.getColumnCount() > 0)
            altered.add(keyspaceName);
        else if (pre.getColumnCount() > 0)
            dropped.add(keyspaceName);
        else if (post.getColumnCount() > 0) // a (re)created keyspace
            created.add(new Row(entry.getKey(), post));
    }

    for (Row row : created)
        addKeyspace(KSMetaData.fromSchema(row, Collections.<CFMetaData>emptyList()));
    for (String name : altered)
        updateKeyspace(name);
    return dropped;
}

From source file:org.apache.cassandra.db.DefsTables.java

private static void mergeColumnFamilies(Map<DecoratedKey, ColumnFamily> before,
        Map<DecoratedKey, ColumnFamily> after) {
    List<CFMetaData> created = new ArrayList<>();
    List<CFMetaData> altered = new ArrayList<>();
    List<CFMetaData> dropped = new ArrayList<>();

    MapDifference<DecoratedKey, ColumnFamily> diff = Maps.difference(before, after);

    for (Map.Entry<DecoratedKey, ColumnFamily> entry : diff.entriesOnlyOnRight().entrySet())
        if (entry.getValue().getColumnCount() > 0)
            created.addAll(/*  w w w  .j  a va 2s . c o  m*/
                    KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), entry.getValue())).values());

    for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering()
            .entrySet()) {
        String keyspaceName = AsciiType.instance.compose(entry.getKey().key);

        ColumnFamily pre = entry.getValue().leftValue();
        ColumnFamily post = entry.getValue().rightValue();

        if (pre.getColumnCount() > 0 && post.getColumnCount() > 0) {
            MapDifference<String, CFMetaData> delta = Maps.difference(
                    Schema.instance.getKSMetaData(keyspaceName).cfMetaData(),
                    KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), post)));

            dropped.addAll(delta.entriesOnlyOnLeft().values());
            created.addAll(delta.entriesOnlyOnRight().values());
            Iterables.addAll(altered, Iterables.transform(delta.entriesDiffering().values(),
                    new Function<MapDifference.ValueDifference<CFMetaData>, CFMetaData>() {
                        public CFMetaData apply(MapDifference.ValueDifference<CFMetaData> pair) {
                            return pair.rightValue();
                        }
                    }));
        } else if (pre.getColumnCount() > 0) {
            dropped.addAll(Schema.instance.getKSMetaData(keyspaceName).cfMetaData().values());
        } else if (post.getColumnCount() > 0) {
            created.addAll(KSMetaData.deserializeColumnFamilies(new Row(entry.getKey(), post)).values());
        }
    }

    for (CFMetaData cfm : created)
        addColumnFamily(cfm);
    for (CFMetaData cfm : altered)
        updateColumnFamily(cfm.ksName, cfm.cfName);
    for (CFMetaData cfm : dropped)
        dropColumnFamily(cfm.ksName, cfm.cfName);
}

From source file:com.cenrise.test.azkaban.PropsUtils.java

/**
 * @return the difference between oldProps and newProps.
 *//*  w w  w  .j  av a2 s.c om*/
public static String getPropertyDiff(Props oldProps, Props newProps) {

    final StringBuilder builder = new StringBuilder("");

    // oldProps can not be null during the below comparison process.
    if (oldProps == null) {
        oldProps = new Props();
    }

    if (newProps == null) {
        newProps = new Props();
    }

    final MapDifference<String, String> md = Maps.difference(toStringMap(oldProps, false),
            toStringMap(newProps, false));

    final Map<String, String> newlyCreatedProperty = md.entriesOnlyOnRight();
    if (newlyCreatedProperty != null && newlyCreatedProperty.size() > 0) {
        builder.append("Newly created Properties: ");
        newlyCreatedProperty.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v + "], ");
        });
        builder.append("\n");
    }

    final Map<String, String> deletedProperty = md.entriesOnlyOnLeft();
    if (deletedProperty != null && deletedProperty.size() > 0) {
        builder.append("Deleted Properties: ");
        deletedProperty.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v + "], ");
        });
        builder.append("\n");
    }

    final Map<String, MapDifference.ValueDifference<String>> diffProperties = md.entriesDiffering();
    if (diffProperties != null && diffProperties.size() > 0) {
        builder.append("Modified Properties: ");
        diffProperties.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v.leftValue() + "-->" + v.rightValue() + "], ");
        });
    }
    return builder.toString();
}

From source file:azkaban.utils.PropsUtils.java

/**
 * @param oldProps//from w ww .j  a  va  2 s  .c  om
 * @param newProps
 * @return the difference between oldProps and newProps.
 */
public static String getPropertyDiff(Props oldProps, Props newProps) {

    StringBuilder builder = new StringBuilder("");

    MapDifference<String, String> md = Maps.difference(toStringMap(oldProps, false),
            toStringMap(newProps, false));

    Map<String, String> newlyCreatedProperty = md.entriesOnlyOnRight();
    if (newlyCreatedProperty != null && newlyCreatedProperty.size() > 0) {
        builder.append("Newly created Properties: ");
        newlyCreatedProperty.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v + "], ");
        });
        builder.append("\n");
    }

    Map<String, String> deletedProperty = md.entriesOnlyOnLeft();
    if (deletedProperty != null && deletedProperty.size() > 0) {
        builder.append("Deleted Properties: ");
        deletedProperty.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v + "], ");
        });
        builder.append("\n");
    }

    Map<String, MapDifference.ValueDifference<String>> diffProperties = md.entriesDiffering();
    if (diffProperties != null && diffProperties.size() > 0) {
        builder.append("Modified Properties: ");
        diffProperties.forEach((k, v) -> {
            builder.append("[ " + k + ", " + v.leftValue() + "-->" + v.rightValue() + "], ");
        });
    }
    return builder.toString();
}

From source file:org.openengsb.core.util.ConfigUtils.java

/**
 * apply the differences to the given map (3-way-merge)
 *
 * @throws MergeException if the changes cannot be applied because of merge-conflicts
 *///from   w w w  .j  a  v a2  s .c o m
public static <K, V> Map<K, V> updateMap(final Map<K, V> original, MapDifference<K, V> diff)
        throws MergeException {
    Map<K, V> result = new HashMap<K, V>(original);
    if (diff.areEqual()) {
        return result;
    }
    for (Entry<K, V> entry : diff.entriesOnlyOnLeft().entrySet()) {
        V originalValue = original.get(entry.getKey());
        if (ObjectUtils.equals(originalValue, entry.getValue())) {
            result.remove(entry.getKey());
        }
    }
    for (Entry<K, V> entry : diff.entriesOnlyOnRight().entrySet()) {
        K key = entry.getKey();
        if (original.containsKey(key)) {
            if (ObjectUtils.notEqual(original.get(key), entry.getValue())) {
                throw new MergeException(
                        String.format("tried to introduce a new value, but it was already there: %s (%s,%s)",
                                key, original.get(key), entry.getValue()));
            }
        }
        result.put(entry.getKey(), entry.getValue());
    }
    for (Entry<K, ValueDifference<V>> entry : diff.entriesDiffering().entrySet()) {
        K key = entry.getKey();
        V originalValue = original.get(entry.getKey());
        if (ObjectUtils.equals(originalValue, entry.getValue().leftValue())) {
            // Map changed in diff only
            result.put(key, entry.getValue().rightValue());
        } else if (ObjectUtils.equals(originalValue, entry.getValue().rightValue())) {
            // Diff would change value to value already in original Map
            result.put(key, originalValue);
        } else {
            // Merge conflict, got 3 different Values
            String errorMessage = String.format(
                    "Changes could not be applied, because original value differes from left-side of the"
                            + "MapDifference: %s (%s,%s)",
                    entry.getKey(), original.get(entry.getKey()), entry.getValue());
            throw new MergeException(errorMessage);
        }
    }
    return result;
}

From source file:co.mitro.core.util.ParallelPhantomLoginMain.java

static synchronized final void addFlattenedSiteData(String key, Map<String, String> data) {
    newData.put(key, data);//from   w w  w.j av  a 2 s .  co m
    if (oldData.containsKey(key)) {
        MapDifference<String, String> differences = Maps.difference(data, oldData.get(key));
        if (differences.areEqual()) {
            safePrintln("data for " + key + " has not changed.");
            return;
        } else {
            safePrintln("data for " + key + " differs:");
            for (String s : differences.entriesOnlyOnLeft().keySet()) {
                safePrintln("\tNew key " + s);
            }
            for (String s : differences.entriesOnlyOnRight().keySet()) {
                safePrintln("\tMissing key " + s);
            }
            for (String s : differences.entriesDiffering().keySet()) {
                safePrintln("\tKey[" + key + "]" + " old:" + differences.entriesDiffering().get(s).rightValue()
                        + " new:" + differences.entriesDiffering().get(s).leftValue());
            }
        }
    } else {
        safePrintln("no old data for " + key);
    }
}

From source file:org.apache.aurora.scheduler.updater.JobDiff.java

private static JobDiff computeUnscoped(Map<Integer, ITaskConfig> currentState, IJobKey job,
        Map<Integer, ITaskConfig> proposedState) {

    requireNonNull(job);//from  w  ww . j  a  va2  s. c  om
    requireNonNull(proposedState);

    MapDifference<Integer, ITaskConfig> diff = Maps.difference(currentState, proposedState);

    Map<Integer, ITaskConfig> removedInstances = ImmutableMap.<Integer, ITaskConfig>builder()
            .putAll(diff.entriesOnlyOnLeft())
            .putAll(Maps.transformValues(diff.entriesDiffering(), JobDiff.leftValue())).build();

    Set<Integer> addedInstances = ImmutableSet.<Integer>builder().addAll(diff.entriesOnlyOnRight().keySet())
            .addAll(diff.entriesDiffering().keySet()).build();

    return new JobDiff(removedInstances, addedInstances, ImmutableMap.copyOf(diff.entriesInCommon()));
}

From source file:org.sonarsource.sonarlint.core.container.connected.update.check.ModuleStorageUpdateChecker.java

private static void checkForQualityProfilesUpdates(DefaultStorageUpdateCheckResult result,
        ModuleConfiguration serverModuleConfiguration, ModuleConfiguration storageModuleConfiguration) {
    MapDifference<String, String> qProfileDiff = Maps.difference(
            storageModuleConfiguration.getQprofilePerLanguageMap(),
            serverModuleConfiguration.getQprofilePerLanguageMap());
    if (!qProfileDiff.areEqual()) {
        for (Map.Entry<String, String> entry : qProfileDiff.entriesOnlyOnLeft().entrySet()) {
            LOG.debug("Quality profile for language '{}' removed", entry.getKey());
        }//from  ww w. j av a 2s.  co  m
        for (Map.Entry<String, String> entry : qProfileDiff.entriesOnlyOnRight().entrySet()) {
            LOG.debug("Quality profile for language '{}' added with value '{}'", entry.getKey(),
                    entry.getValue());
        }
        for (Map.Entry<String, ValueDifference<String>> entry : qProfileDiff.entriesDiffering().entrySet()) {
            LOG.debug("Quality profile for language '{}' changed from '{}' to '{}'", entry.getKey(),
                    entry.getValue().leftValue(), entry.getValue().rightValue());
        }
        // Don't report update when QP removed since this is harmless for the analysis
        if (!qProfileDiff.entriesOnlyOnRight().isEmpty() || !qProfileDiff.entriesDiffering().isEmpty()) {
            result.appendToChangelog("Quality profiles configuration changed");
        }
    }
}

From source file:org.sonarsource.sonarlint.core.container.connected.update.check.ModuleStorageUpdateChecker.java

private static void checkForSettingsUpdates(DefaultStorageUpdateCheckResult result,
        ModuleConfiguration serverModuleConfiguration, ModuleConfiguration storageModuleConfiguration) {
    MapDifference<String, String> propDiff = Maps.difference(
            GlobalSettingsUpdateChecker.filter(storageModuleConfiguration.getPropertiesMap()),
            GlobalSettingsUpdateChecker.filter(serverModuleConfiguration.getPropertiesMap()));
    if (!propDiff.areEqual()) {
        result.appendToChangelog("Project settings updated");
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnLeft().entrySet()) {
            LOG.debug("Property '{}' removed", entry.getKey());
        }//from w  w  w .java2  s.c o m
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnRight().entrySet()) {
            LOG.debug("Property '{}' added with value '{}'", entry.getKey(),
                    GlobalSettingsUpdateChecker.formatValue(entry.getKey(), entry.getValue()));
        }
        for (Map.Entry<String, ValueDifference<String>> entry : propDiff.entriesDiffering().entrySet()) {
            LOG.debug("Value of property '{}' changed from '{}' to '{}'", entry.getKey(),
                    GlobalSettingsUpdateChecker.formatLeftDiff(entry.getKey(), entry.getValue().leftValue(),
                            entry.getValue().rightValue()),
                    GlobalSettingsUpdateChecker.formatRightDiff(entry.getKey(), entry.getValue().leftValue(),
                            entry.getValue().rightValue()));
        }
    }
}