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

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

Introduction

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

Prototype

public static <K, V> SortedMapDifference<K, V> difference(SortedMap<K, ? extends V> left,
        Map<? extends K, ? extends V> right) 

Source Link

Document

Computes the difference between two sorted maps, using the comparator of the left map, or Ordering.natural() if the left map uses the natural ordering of its elements.

Usage

From source file:org.apache.cassandra.schema.LegacySchemaTables.java

private static void mergeTables(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().hasColumns())
            created.addAll(createTablesFromTablesPartition(new Row(entry.getKey(), entry.getValue())).values());

    for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering()
            .entrySet()) {/*from   w w w. java  2  s.c o m*/
        String keyspaceName = AsciiType.instance.compose(entry.getKey().getKey());

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

        if (pre.hasColumns() && post.hasColumns()) {
            MapDifference<String, CFMetaData> delta = Maps.difference(
                    Schema.instance.getKSMetaData(keyspaceName).cfMetaData(),
                    createTablesFromTablesPartition(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.hasColumns()) {
            dropped.addAll(Schema.instance.getKSMetaData(keyspaceName).cfMetaData().values());
        } else if (post.hasColumns()) {
            created.addAll(createTablesFromTablesPartition(new Row(entry.getKey(), post)).values());
        }
    }

    for (CFMetaData cfm : created)
        Schema.instance.addTable(cfm);
    for (CFMetaData cfm : altered)
        Schema.instance.updateTable(cfm.ksName, cfm.cfName);
    for (CFMetaData cfm : dropped)
        Schema.instance.dropTable(cfm.ksName, cfm.cfName);
}

From source file:org.apache.cassandra.schema.SchemaKeyspace.java

public static Mutation.SimpleBuilder makeUpdateTableMutation(KeyspaceMetadata keyspace, CFMetaData oldTable,
        CFMetaData newTable, long timestamp) {
    Mutation.SimpleBuilder builder = makeCreateKeyspaceMutation(keyspace.name, keyspace.params, timestamp);

    addTableToSchemaMutation(newTable, false, builder);

    MapDifference<ByteBuffer, ColumnDefinition> columnDiff = Maps.difference(oldTable.getColumnMetadata(),
            newTable.getColumnMetadata());

    // columns that are no longer needed
    for (ColumnDefinition column : columnDiff.entriesOnlyOnLeft().values())
        dropColumnFromSchemaMutation(oldTable, column, builder);

    // newly added columns
    for (ColumnDefinition column : columnDiff.entriesOnlyOnRight().values())
        addColumnToSchemaMutation(newTable, column, builder);

    // old columns with updated attributes
    for (ByteBuffer name : columnDiff.entriesDiffering().keySet())
        addColumnToSchemaMutation(newTable, newTable.getColumnDefinition(name), builder);

    // dropped columns
    MapDifference<ByteBuffer, CFMetaData.DroppedColumn> droppedColumnDiff = Maps
            .difference(oldTable.getDroppedColumns(), newTable.getDroppedColumns());

    // newly dropped columns
    for (CFMetaData.DroppedColumn column : droppedColumnDiff.entriesOnlyOnRight().values())
        addDroppedColumnToSchemaMutation(newTable, column, builder);

    // columns added then dropped again
    for (ByteBuffer name : droppedColumnDiff.entriesDiffering().keySet())
        addDroppedColumnToSchemaMutation(newTable, newTable.getDroppedColumns().get(name), builder);

    MapDifference<String, TriggerMetadata> triggerDiff = triggersDiff(oldTable.getTriggers(),
            newTable.getTriggers());/*from   ww  w  .ja  v  a 2  s  . c  o  m*/

    // dropped triggers
    for (TriggerMetadata trigger : triggerDiff.entriesOnlyOnLeft().values())
        dropTriggerFromSchemaMutation(oldTable, trigger, builder);

    // newly created triggers
    for (TriggerMetadata trigger : triggerDiff.entriesOnlyOnRight().values())
        addTriggerToSchemaMutation(newTable, trigger, builder);

    MapDifference<String, IndexMetadata> indexesDiff = indexesDiff(oldTable.getIndexes(),
            newTable.getIndexes());

    // dropped indexes
    for (IndexMetadata index : indexesDiff.entriesOnlyOnLeft().values())
        dropIndexFromSchemaMutation(oldTable, index, builder);

    // newly created indexes
    for (IndexMetadata index : indexesDiff.entriesOnlyOnRight().values())
        addIndexToSchemaMutation(newTable, index, builder);

    // updated indexes need to be updated
    for (MapDifference.ValueDifference<IndexMetadata> diff : indexesDiff.entriesDiffering().values())
        addUpdatedIndexToSchemaMutation(newTable, diff.rightValue(), builder);

    return builder;
}

From source file:org.apache.hive.hcatalog.api.HCatTable.java

/**
 * Helper method to compare 2 Map instances, for equivalence.
 * @param lhs First map to be compared.//from   w  ww  .jav a 2s  .  c o  m
 * @param rhs Second map to be compared.
 * @return true, if the 2 Maps contain the same entries.
 */
private static boolean equivalent(Map<String, String> lhs, Map<String, String> rhs) {
    return lhs.size() == rhs.size() && Maps.difference(lhs, rhs).areEqual();
}

From source file:org.apache.cassandra.schema.LegacySchemaTables.java

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

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

    // New keyspace with types
    for (Map.Entry<DecoratedKey, ColumnFamily> entry : diff.entriesOnlyOnRight().entrySet())
        if (entry.getValue().hasColumns())
            created.addAll(createTypesFromPartition(new Row(entry.getKey(), entry.getValue())).values());

    for (Map.Entry<DecoratedKey, MapDifference.ValueDifference<ColumnFamily>> entry : diff.entriesDiffering()
            .entrySet()) {//w w w  . j  a  v  a  2 s .c o  m
        String keyspaceName = AsciiType.instance.compose(entry.getKey().getKey());

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

        if (pre.hasColumns() && post.hasColumns()) {
            MapDifference<ByteBuffer, UserType> delta = Maps.difference(
                    Schema.instance.getKSMetaData(keyspaceName).userTypes.getAllTypes(),
                    createTypesFromPartition(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<UserType>, UserType>() {
                        public UserType apply(MapDifference.ValueDifference<UserType> pair) {
                            return pair.rightValue();
                        }
                    }));
        } else if (pre.hasColumns()) {
            dropped.addAll(Schema.instance.getKSMetaData(keyspaceName).userTypes.getAllTypes().values());
        } else if (post.hasColumns()) {
            created.addAll(createTypesFromPartition(new Row(entry.getKey(), post)).values());
        }
    }

    for (UserType type : created)
        Schema.instance.addType(type);
    for (UserType type : altered)
        Schema.instance.updateType(type);
    for (UserType type : dropped)
        Schema.instance.dropType(type);
}

From source file:com.blackducksoftware.bdio.io.Specification.java

/**
 * Returns a modified version of this specification whose term definitions can be used to map an older version of
 * the specification into a newer version.
 *//*w w w.  ja v  a2 s .  c o  m*/
public Map<String, TermDefinition> importDefinitions() {
    MapDifference<String, TermDefinition> diff = Maps.difference(asTermDefinitions(),
            latest().asTermDefinitions());
    if (diff.areEqual()) {
        return asTermDefinitions();
    } else {
        // Use the resolver from the latest version of the specification to generate term definitions
        ImportResolver resolver = latest().importResolver();
        Map<String, TermDefinition> termDefinitions = new LinkedHashMap<>();

        // Entries on the right did not exist when the current version of the specification was
        // released, therefore we can ignore them in our reconstructed definitions

        // All common entries are unchanged between both versions of the specification
        termDefinitions.putAll(diff.entriesInCommon());

        // Entries which have the same alias but different IRIs have been "re-mapped"; typically
        // (but not always) we want the alias to point to the latest IRI
        for (Entry<String, ValueDifference<TermDefinition>> e : diff.entriesDiffering().entrySet()) {
            String alias = e.getKey();
            termDefinitions.put(alias,
                    resolver.changed(alias, e.getValue().leftValue(), e.getValue().rightValue()));
        }

        // Entries on the left have been removed or renamed (their alias changed). We must delegate
        // to the import resolver to decide what do here.
        for (Entry<String, TermDefinition> e : diff.entriesOnlyOnLeft().entrySet()) {
            String alias = e.getKey();
            termDefinitions.put(alias, resolver.removed(alias, e.getValue()));
        }

        return termDefinitions;
    }
}

From source file:org.eclipse.xtext.ui.preferences.OptionsConfigurationBlock.java

public Map<String, ValueDifference<String>> getPreferenceChanges() {
    Map<String, String> currentSettings = Maps.newHashMapWithExpectedSize(keys.length);
    for (String key : keys) {
        currentSettings.put(key, preferenceStore.getString(key));
    }/*from   w  ww  .  jav  a 2 s. c om*/
    MapDifference<String, String> mapDifference = Maps.difference(currentSettings, originalSettings);
    Map<String, ValueDifference<String>> entriesDiffering = mapDifference.entriesDiffering();
    return entriesDiffering;
}

From source file:org.apache.cassandra.schema.SchemaKeyspace.java

private static MapDifference<String, IndexMetadata> indexesDiff(Indexes before, Indexes after) {
    Map<String, IndexMetadata> beforeMap = new HashMap<>();
    before.forEach(i -> beforeMap.put(i.name, i));

    Map<String, IndexMetadata> afterMap = new HashMap<>();
    after.forEach(i -> afterMap.put(i.name, i));

    return Maps.difference(beforeMap, afterMap);
}

From source file:org.apache.cassandra.schema.SchemaKeyspace.java

private static MapDifference<String, TriggerMetadata> triggersDiff(Triggers before, Triggers after) {
    Map<String, TriggerMetadata> beforeMap = new HashMap<>();
    before.forEach(t -> beforeMap.put(t.name, t));

    Map<String, TriggerMetadata> afterMap = new HashMap<>();
    after.forEach(t -> afterMap.put(t.name, t));

    return Maps.difference(beforeMap, afterMap);
}

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

private void refreshLeaderBoard() {
    try {/* w  w  w . j  a  va  2  s.  c om*/
        Map<String, Leadership> newLeaderBoard = Maps.newHashMap();
        leaderMap.entrySet().forEach(entry -> {
            String path = entry.getKey();
            Versioned<NodeId> leader = entry.getValue();
            Leadership leadership = new Leadership(path, leader.value(), leader.version(),
                    leader.creationTime());
            newLeaderBoard.put(path, leadership);
        });

        // first take snapshot of current leader board.
        Map<String, Leadership> currentLeaderBoard = ImmutableMap.copyOf(leaderBoard);

        MapDifference<String, Leadership> diff = Maps.difference(currentLeaderBoard, newLeaderBoard);

        // evict stale leaders
        diff.entriesOnlyOnLeft().forEach((path, leadership) -> {
            log.debug("Evicting {} from leaderboard. It is no longer active leader.", leadership);
            onLeadershipEvent(new LeadershipEvent(LeadershipEvent.Type.LEADER_BOOTED, leadership));
        });

        // add missing leaders
        diff.entriesOnlyOnRight().forEach((path, leadership) -> {
            log.debug("Adding {} to leaderboard. It is now the active leader.", leadership);
            onLeadershipEvent(new LeadershipEvent(LeadershipEvent.Type.LEADER_ELECTED, leadership));
        });

        // add updated leaders
        diff.entriesDiffering().forEach((path, difference) -> {
            Leadership current = difference.leftValue();
            Leadership updated = difference.rightValue();
            if (current.epoch() < updated.epoch()) {
                log.debug("Updated {} in leaderboard.", updated);
                onLeadershipEvent(new LeadershipEvent(LeadershipEvent.Type.LEADER_ELECTED, updated));
            }
        });
    } catch (Exception e) {
        log.debug("Failed to refresh leader board", e);
    }
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.Util.java

/**
 * Given two sets of matches find out the differences
 * TODO: Probably useful for others. Place somewhere else. The discovery-api module is an option but it forces to have guava as a dependency, do we want to?
 *
 * @param inputMatches//from w  w  w  . ja v a  2  s  .co m
 * @param inputMatchesAlt
 */
public static void compareResults(Map<URL, MatchResult> inputMatches, Map<URL, MatchResult> inputMatchesAlt) {

    MapDifference<URL, MatchResult> diff = Maps.difference(inputMatches, inputMatchesAlt);
    System.out.println("Comparing Match Results Maps");

    Map<URL, MatchResult> common = diff.entriesInCommon();
    System.out.println("Entries in common");
    showMapDetails(common);

    Map<URL, MatchResult> onlyLeft = diff.entriesOnlyOnLeft();
    System.out.println("Entries only in the left map");
    showMapDetails(common);

    Map<URL, MatchResult> onlyRight = diff.entriesOnlyOnRight();
    System.out.println("Entries only in the right map");
    showMapDetails(common);

    Map<URL, ValueDifference<MatchResult>> diffValues = diff.entriesDiffering();
    System.out.println("Differing values");
    for (Entry<URL, ValueDifference<MatchResult>> entry : diffValues.entrySet()) {
        MatchResult resultLeft = entry.getValue().leftValue();
        MatchResult resultRight = entry.getValue().rightValue();

        System.out.println("Match " + entry.getKey().toString());
        System.out.println("Left value details: ");
        System.out.println("Match explanation: " + resultLeft.getExplanation());

        System.out.println("Right value details: ");
        System.out.println("Match explanation: " + resultRight.getExplanation());
    }

}