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:com.facebook.buck.parser.DaemonicParserState.java

private synchronized void invalidateIfBuckConfigOrEnvHasChanged(Cell cell, Path buildFile) {
    try (AutoCloseableLock readLock = cellStateLock.readLock()) {
        DaemonicCellState state = cellPathToDaemonicState.get(cell.getRoot());
        if (state == null) {
            return;
        }//  w  w w  .  ja  va 2  s . co  m
        // Invalidates and also keeps the state cell up-to-date
        state.invalidateIfBuckConfigHasChanged(cell, buildFile);
        Optional<MapDifference<String, String>> envDiff = state.invalidateIfEnvHasChanged(cell, buildFile);
        if (envDiff.isPresent()) {
            MapDifference<String, String> diff = envDiff.get();
            LOG.warn("Invalidating cache on environment change (%s)", diff);
            Set<String> environmentChanges = new HashSet<>();
            environmentChanges.addAll(diff.entriesOnlyOnLeft().keySet());
            environmentChanges.addAll(diff.entriesOnlyOnRight().keySet());
            environmentChanges.addAll(diff.entriesDiffering().keySet());
            cacheInvalidatedByEnvironmentVariableChangeCounter.addAll(environmentChanges);
            broadcastEventListener.broadcast(ParsingEvent.environmentalChange(environmentChanges.toString()));
        }
    }
}

From source file:org.apache.abdera2.activities.extra.Extra.java

/**
 * Two ASObject's are considered equivalent in identity if 
 * they share the same objectType and id property
 * values. Note: This implementation does not yet take 
 * the downstreamDuplicates and upstreamDuplicates properties
 * into account when determining equivalence.
 *///www  . j  a  v  a2 s  . c  om
public static <X extends ASObject> Equivalence<X> identity() {
    return new Equivalence<X>() {
        protected boolean doEquivalent(X a, X b) {
            Selector<Map.Entry<String, Object>> filter = ASBase.withFields("id", "alias", "objectType",
                    "displayName");
            Map<String, Object> map1 = Maps.transformEntries(a.toMap(filter), lower_val);
            Map<String, Object> map2 = Maps.transformEntries(b.toMap(filter), lower_val);
            MapDifference<String, Object> diff = Maps.difference(map1, map2);
            return ((diff.entriesInCommon().containsKey("alias") || diff.entriesInCommon().containsKey("id")
                    || diff.entriesInCommon().containsKey("displayName"))
                    && !diff.entriesDiffering().containsKey("objectType")
                    && !diff.entriesDiffering().containsKey("id") && !diff.entriesOnlyOnLeft().containsKey("id")
                    && !diff.entriesOnlyOnRight().containsKey("id"));
        }

        protected int doHash(ASObject t) {
            return MoreFunctions.genHashCode(1, t.getId(), t.getProperty("alias"), t.getObjectType());
        }
    };
}

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

public static synchronized void mergeSchema(Collection<Mutation> mutations) {
    // only compare the keyspaces affected by this set of schema mutations
    Set<String> affectedKeyspaces = mutations.stream().map(m -> UTF8Type.instance.compose(m.key().getKey()))
            .collect(Collectors.toSet());

    // fetch the current state of schema for the affected keyspaces only
    Keyspaces before = Schema.instance.getKeyspaces(affectedKeyspaces);

    // apply the schema mutations and flush
    mutations.forEach(Mutation::apply);//from   w  w w.ja  v a2s.  c  o  m
    if (FLUSH_SCHEMA_TABLES)
        flush();

    // fetch the new state of schema from schema tables (not applied to Schema.instance yet)
    Keyspaces after = fetchKeyspacesOnly(affectedKeyspaces);

    // deal with the diff
    MapDifference<String, KeyspaceMetadata> keyspacesDiff = before.diff(after);

    // dropped keyspaces
    for (KeyspaceMetadata keyspace : keyspacesDiff.entriesOnlyOnLeft().values()) {
        keyspace.functions.udas().forEach(Schema.instance::dropAggregate);
        keyspace.functions.udfs().forEach(Schema.instance::dropFunction);
        keyspace.views.forEach(v -> Schema.instance.dropView(v.ksName, v.viewName));
        keyspace.tables.forEach(t -> Schema.instance.dropTable(t.ksName, t.cfName));
        keyspace.types.forEach(Schema.instance::dropType);
        Schema.instance.dropKeyspace(keyspace.name);
    }

    // new keyspaces
    for (KeyspaceMetadata keyspace : keyspacesDiff.entriesOnlyOnRight().values()) {
        Schema.instance.addKeyspace(KeyspaceMetadata.create(keyspace.name, keyspace.params));
        keyspace.types.forEach(Schema.instance::addType);
        keyspace.tables.forEach(Schema.instance::addTable);
        keyspace.views.forEach(Schema.instance::addView);
        keyspace.functions.udfs().forEach(Schema.instance::addFunction);
        keyspace.functions.udas().forEach(Schema.instance::addAggregate);
    }

    // updated keyspaces
    for (Map.Entry<String, MapDifference.ValueDifference<KeyspaceMetadata>> diff : keyspacesDiff
            .entriesDiffering().entrySet())
        updateKeyspace(diff.getKey(), diff.getValue().leftValue(), diff.getValue().rightValue());
}

From source file:com.sam.moca.cluster.manager.simulator.ClusterTestUtils.java

/**
 * Make sure that cache contents are the same. If not, generate a nice
 * message telling what went wrong.//from  w  w  w.  j  a  v a 2s  . c om
 * @param cacheName
 * @param compareAgainstMap the map that serves as the "correct" map
 * @param nodeCacheContents the map that could be wrong that we are checking
 */
void assertMapContentsEqual(String cacheName, final Map<Object, Object> compareAgainstMap,
        final Map<Object, Object> nodeCacheContents) {
    final StringBuilder err = new StringBuilder();
    if (!compareAgainstMap.equals(nodeCacheContents)) {
        err.append("DIFFERENT CACHE CONTENTS FOR CACHE " + cacheName + "! ");
        final MapDifference<Object, Object> d = Maps.difference(nodeCacheContents, compareAgainstMap);

        final Map<Object, Object> onlyLeft = d.entriesOnlyOnRight();
        if (onlyLeft.size() > 0) {
            err.append("MAP SHOULD HAVE INCLUDED: {");
            for (Map.Entry<Object, Object> entry : onlyLeft.entrySet()) {
                err.append("[" + entry.getKey() + "|" + entry.getValue() + "]");
            }
            err.append("} ");
        }

        final Map<Object, Object> onlyRight = d.entriesOnlyOnLeft();
        if (onlyRight.size() > 0) {
            err.append("MAP INCLUDED EXTRA: {");
            for (Map.Entry<Object, Object> entry : onlyRight.entrySet()) {
                err.append("[" + entry.getKey() + "|" + entry.getValue() + "]");
            }
            err.append("} ");
        }

        final Map<Object, ValueDifference<Object>> diff = d.entriesDiffering();
        if (diff.size() > 0) {
            for (Map.Entry<Object, ValueDifference<Object>> e : diff.entrySet()) {
                err.append("KEY {" + e.getKey() + "} HAD INCORRECT VALUE: {" + e.getValue().rightValue()
                        + "}, expected {" + e.getValue().leftValue() + "} ");
            }
        }

        if (err.length() > 0) {
            writeLineWithDate(err.toString());
            throw new AssertionError(err.toString());
        }
    }
}

From source file:org.level28.android.moca.sync.SessionHelper.java

/**
 * Perform session synchronization between local SQLite database and TMA-1
 * sessions API./*w  w  w.  jav  a  2  s .c  om*/
 */
List<ContentProviderOperation> synchronizeSessions() throws IOException, JsonDeserializerException {
    final ArrayList<ContentProviderOperation> sessionsBatch = Lists.newArrayList();

    // Get a snapshot of all sessions stored in the database
    final Map<String, Session> localSessions = getSessionsSnapshot();
    // Ask the TMA-1 server for updated session data
    final Map<String, Session> remoteSessions = getRemoteSessions();

    if (!remoteSessions.isEmpty()) {
        // Perform the update only if we got a non-empty reply from the
        // TMA-1 server
        final MapDifference<String, Session> diff = Maps.difference(localSessions, remoteSessions);

        // @formatter:off
        /*
         * Now diff contains a nice "patch" that should be transformed into a
         * batch of ContentProviderOperation.
         *
         * Namely:
         *  diff.entriesDiffering()   -> entries that should be updated with new values
         *  diff.entriesOnlyOnLeft()  -> entries that should be removed
         *  diff.entriesOnlyOnRight() -> entries that should be added
         */
        // @formatter:on
        sessionsBatch.addAll(createUpdateOps(diff.entriesDiffering()));
        sessionsBatch.addAll(createDeleteOps(diff.entriesOnlyOnLeft()));
        sessionsBatch.addAll(createInsertOps(diff.entriesOnlyOnRight()));
    }

    return sessionsBatch;
}

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

private void refreshLeaderBoard() {
    try {/*  w ww.  j a v  a2s. co  m*/
        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:org.apache.cassandra.schema.LegacySchemaTables.java

public static Mutation makeUpdateTableMutation(KSMetaData keyspace, CFMetaData oldTable, CFMetaData newTable,
        long timestamp, boolean fromThrift) {
    Mutation mutation = makeCreateKeyspaceMutation(keyspace, timestamp, false);

    addTableToSchemaMutation(newTable, timestamp, false, mutation);

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

    // columns that are no longer needed
    for (ColumnDefinition column : columnDiff.entriesOnlyOnLeft().values()) {
        // Thrift only knows about the REGULAR ColumnDefinition type, so don't consider other type
        // are being deleted just because they are not here.
        if (fromThrift && column.kind != ColumnDefinition.Kind.REGULAR)
            continue;

        dropColumnFromSchemaMutation(oldTable, column, timestamp, mutation);
    }/*from  w  w  w . j a  v  a  2 s.c  om*/

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

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

    MapDifference<String, TriggerDefinition> triggerDiff = Maps.difference(oldTable.getTriggers(),
            newTable.getTriggers());

    // dropped triggers
    for (TriggerDefinition trigger : triggerDiff.entriesOnlyOnLeft().values())
        dropTriggerFromSchemaMutation(oldTable, trigger, timestamp, mutation);

    // newly created triggers
    for (TriggerDefinition trigger : triggerDiff.entriesOnlyOnRight().values())
        addTriggerToSchemaMutation(newTable, trigger, timestamp, mutation);

    return mutation;
}

From source file:jetbrains.buildServer.agentsDiff.BuildAgentsDiffCalculator.java

public BuildAgentsDiffBean calculateDiff(BuildAgentEx agentA, BuildAgentEx agentB) {
    final Map<String, String> configParamsA = agentA.getAvailableParameters();
    final Map<String, String> configParamsB = agentB.getAvailableParameters();

    final List<BuildAgentsDiffEntry> entries = new LinkedList<BuildAgentsDiffEntry>();

    final MapDifference<String, String> mapDifference = Maps.difference(configParamsA, configParamsB);
    if (!mapDifference.areEqual()) {
        final Map<String, MapDifference.ValueDifference<String>> stringValueDifferenceMap = mapDifference
                .entriesDiffering();/* ww  w .ja va 2s  .  com*/
        for (String key : stringValueDifferenceMap.keySet()) {
            final MapDifference.ValueDifference<String> stringValueDifference = stringValueDifferenceMap
                    .get(key);
            entries.add(new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_VALUE, key,
                    stringValueDifference.leftValue(), stringValueDifference.rightValue()));
        }

        Map<String, String> map = mapDifference.entriesOnlyOnLeft();
        for (String key : map.keySet()) {
            entries.add(
                    new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_NAME, key, map.get(key), null));
        }

        map = mapDifference.entriesOnlyOnRight();
        for (String key : map.keySet()) {
            entries.add(
                    new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_NAME, key, null, map.get(key)));
        }
    }
    Collections.sort(entries, new Comparator<BuildAgentsDiffEntry>() {
        public int compare(BuildAgentsDiffEntry o1, BuildAgentsDiffEntry o2) {
            return o1.getPropertyName().compareToIgnoreCase(o2.getPropertyName());
        }
    });
    return new BuildAgentsDiffBean(agentA, agentB, entries);
}

From source file:jetbrains.buildServer.agentsDiff.BuildDiffCalculator.java

public BuildDiffBean calculateDiff(SBuild buildA, SBuild buildB) {
    final Map<String, String> configParamsA = buildA.getBuildOwnParameters();
    final Map<String, String> configParamsB = buildB.getBuildOwnParameters();

    final List<BuildAgentsDiffEntry> entries = new LinkedList<BuildAgentsDiffEntry>();

    final MapDifference<String, String> mapDifference = Maps.difference(configParamsA, configParamsB);
    if (!mapDifference.areEqual()) {
        final Map<String, MapDifference.ValueDifference<String>> stringValueDifferenceMap = mapDifference
                .entriesDiffering();// w  ww  .j  a  v  a 2 s .c o m
        for (String key : stringValueDifferenceMap.keySet()) {
            final MapDifference.ValueDifference<String> stringValueDifference = stringValueDifferenceMap
                    .get(key);
            entries.add(new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_VALUE, key,
                    stringValueDifference.leftValue(), stringValueDifference.rightValue()));
        }

        Map<String, String> map = mapDifference.entriesOnlyOnLeft();
        for (String key : map.keySet()) {
            entries.add(
                    new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_NAME, key, map.get(key), null));
        }

        map = mapDifference.entriesOnlyOnRight();
        for (String key : map.keySet()) {
            entries.add(
                    new BuildAgentsDiffEntry(BuildAgentsDiffEntryType.PARAMETER_NAME, key, null, map.get(key)));
        }
    }
    Collections.sort(entries, new Comparator<BuildAgentsDiffEntry>() {
        public int compare(BuildAgentsDiffEntry o1, BuildAgentsDiffEntry o2) {
            return o1.getPropertyName().compareToIgnoreCase(o2.getPropertyName());
        }
    });
    return new BuildDiffBean(buildA, buildB, entries);
}

From source file:be.solidx.hot.shows.AbstractWebSocket.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<Options, Handler<CLOSURE>> refreshSocket(WebSocket<CLOSURE, MAP> updatedWebSocket) {
    MapDifference<Options, Handler<CLOSURE>> diff = Maps.difference(socketHandlerAdapterMap,
            updatedWebSocket.getSocketHandlerAdapterMap());
    for (Entry<Options, ValueDifference<Handler<CLOSURE>>> differingEntry : diff.entriesDiffering()
            .entrySet()) {//from  w  ww  .j a va  2  s  .  com
        AbstractWebSocketHandler<CLOSURE> newHandler = (AbstractWebSocketHandler) differingEntry.getValue()
                .rightValue();
        AbstractWebSocketHandler<CLOSURE> currentHandler = (AbstractWebSocketHandler) differingEntry.getValue()
                .leftValue();
        currentHandler.getSocketHandlerAdapter().updateClosures(newHandler.socketHandlerAdapter.connectClosure,
                newHandler.socketHandlerAdapter.abstractConnection.messageClosure,
                newHandler.socketHandlerAdapter.abstractConnection.closeClosure);
    }
    for (Entry<Options, Handler<CLOSURE>> entry : diff.entriesOnlyOnLeft().entrySet()) {
        AbstractWebSocketHandler<CLOSURE> currentHandler = (AbstractWebSocketHandler) entry.getValue();
        currentHandler.closed = true;
    }
    socketHandlerAdapterMap.putAll(diff.entriesOnlyOnRight());
    return diff.entriesOnlyOnRight();
}