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

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

Introduction

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

Prototype

Map<K, V> entriesOnlyOnLeft();

Source Link

Document

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

Usage

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

private void refreshLeaderBoard() {
    try {//  w  ww  .j  a v  a 2  s  . c o 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: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 va2 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: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();//from   w ww  .  j ava 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 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();/*from   w w w.  jav  a 2 s. 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 BuildDiffBean(buildA, buildB, entries);
}

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.
 *//* ww  w . j  a va 2 s  .  c  o m*/
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.level28.android.moca.sync.SessionHelper.java

/**
 * Perform session synchronization between local SQLite database and TMA-1
 * sessions API.// w  w  w.ja v a  2s . 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: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()) {//w w  w.j a  va 2 s . c om
        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();
}

From source file:co.cask.cdap.internal.app.store.DefaultStore.java

@Override
public List<ProgramSpecification> getDeletedProgramSpecifications(final Id.Application id,
        ApplicationSpecification appSpec) {

    ApplicationMeta existing = txnl/*  w ww. j a v a2  s  . c  om*/
            .executeUnchecked(new TransactionExecutor.Function<AppMds, ApplicationMeta>() {
                @Override
                public ApplicationMeta apply(AppMds mds) throws Exception {
                    return mds.apps.getApplication(id.getNamespaceId(), id.getId());
                }
            });

    List<ProgramSpecification> deletedProgramSpecs = Lists.newArrayList();

    if (existing != null) {
        ApplicationSpecification existingAppSpec = existing.getSpec();

        ImmutableMap<String, ProgramSpecification> existingSpec = new ImmutableMap.Builder<String, ProgramSpecification>()
                .putAll(existingAppSpec.getMapReduce()).putAll(existingAppSpec.getSpark())
                .putAll(existingAppSpec.getWorkflows()).putAll(existingAppSpec.getFlows())
                .putAll(existingAppSpec.getServices()).putAll(existingAppSpec.getWorkers()).build();

        ImmutableMap<String, ProgramSpecification> newSpec = new ImmutableMap.Builder<String, ProgramSpecification>()
                .putAll(appSpec.getMapReduce()).putAll(appSpec.getSpark()).putAll(appSpec.getWorkflows())
                .putAll(appSpec.getFlows()).putAll(appSpec.getServices()).putAll(appSpec.getWorkers()).build();

        MapDifference<String, ProgramSpecification> mapDiff = Maps.difference(existingSpec, newSpec);
        deletedProgramSpecs.addAll(mapDiff.entriesOnlyOnLeft().values());
    }

    return deletedProgramSpecs;
}

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  av a 2  s. c  o m
 * @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:com.excilys.ebi.gatling.recorder.ui.component.RunningFrame.java

private void processRequest(ResponseReceivedEvent event) {

    HttpRequest request = event.getRequest();

    URI uri = null;/*  w w w  .  j a  va2 s  .  com*/
    try {
        uri = new URI(request.getUri());
    } catch (URISyntaxException ex) {
        logger.error("Can't create URI from request uri (" + request.getUri() + ")" + ex.getStackTrace());
    }

    events.addElement(request.getMethod() + " | " + request.getUri());
    executedEvents.ensureIndexIsVisible(events.getSize() - 1);

    int id = ++numberOfRequests;
    event.setId(id);

    /* URLs */
    if (urlBase == null) {
        protocol = uri.getScheme();
        host = uri.getHost();
        port = uri.getPort();
        urlBase = protocol + "://" + host;
        urlBaseString = "PROTOCOL + \"://\" + HOST";
        if (port != -1) {
            urlBase += ":" + port;
            urlBaseString += " + \":\" + PORT";
        }
    }

    String requestUrlBase = uri.getScheme() + "://" + uri.getHost();
    if (uri.getPort() != -1)
        requestUrlBase += ":" + uri.getPort();
    if (requestUrlBase.equals(urlBase))
        event.setWithUrlBase(true);
    else
        urls.put("url_" + id, requestUrlBase + uri.getPath());

    String headerAuthorization = event.getRequest().getHeader("Authorization");
    request.removeHeader("Authorization");
    if (headerAuthorization != null) {
        if (basicAuth == null) {
            // Split on " " and take 2nd group (Basic credentialsInBase64==)
            String credentials = new String(Base64.decodeBase64(headerAuthorization.split(" ")[1].getBytes()));
            basicAuth = new BasicAuth(requestUrlBase, credentials.split(":")[0], credentials.split(":")[1]);
            event.setBasicAuth(basicAuth);
        } else {
            if (requestUrlBase.equals(basicAuth.getUrlBase()))
                event.setBasicAuth(basicAuth);
            else
                basicAuth = null;
        }
    }

    /* Headers */
    Map<String, String> requestHeaders = new TreeMap<String, String>();
    for (Entry<String, String> entry : request.getHeaders())
        requestHeaders.put(entry.getKey(), entry.getValue());
    requestHeaders.remove("Cookie");

    int bestChoice = 0;
    String headerKey = EMPTY;
    MapDifference<String, String> diff;
    Map<String, String> fullHeaders = new TreeMap<String, String>();
    boolean containsHeaders = false;

    if (headers.size() > 0) {
        for (Entry<String, Map<String, String>> header : headers.entrySet()) {

            fullHeaders = new TreeMap<String, String>(header.getValue());
            containsHeaders = false;

            if (header.getValue().containsKey("headers")) {
                fullHeaders.putAll(headers.get(header.getValue().get("headers")));
                fullHeaders.remove("headers");
                containsHeaders = true;
            }

            diff = Maps.difference(fullHeaders, requestHeaders);
            logger.debug(diff.toString());
            if (diff.areEqual()) {
                headerKey = header.getKey();
                bestChoice = 1;
                break;
            } else if (diff.entriesOnlyOnLeft().size() == 0 && diff.entriesDiffering().size() == 0
                    && !containsHeaders) {
                // header are included in requestHeaders
                headerKey = header.getKey();
                bestChoice = 2;
            } else if (bestChoice > 2 && diff.entriesOnlyOnRight().size() == 0
                    && diff.entriesDiffering().size() == 0 && !containsHeaders) {
                // requestHeaders are included in header
                headerKey = header.getKey();
                bestChoice = 3;
            }
        }
    }

    switch (bestChoice) {
    case 1:
        event.setHeadersId(headerKey);
        break;
    case 2:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm2 = new TreeMap<String, String>(diff.entriesOnlyOnRight());
        headers.put("headers_" + id, tm2);
        headers.get("headers_" + id).put("headers", headerKey);
        event.setHeadersId("headers_" + id);
        break;
    case 3:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm3 = new TreeMap<String, String>(diff.entriesInCommon());
        headers.put("headers_" + id, tm3);
        event.setHeadersId("headers_" + id);
        headers.remove(headerKey);
        tm3 = new TreeMap<String, String>(diff.entriesOnlyOnLeft());
        headers.put(headerKey, tm3);
        headers.get(headerKey).put("headers", "headers_" + id);
        break;
    default:
        headers.put("headers_" + id, requestHeaders);
        event.setHeadersId("headers_" + id);
    }

    /* Add check if status is not in 20X */
    if ((event.getResponse().getStatus().getCode() < 200) || (event.getResponse().getStatus().getCode() > 210))
        event.setWithCheck(true);

    /* Params */
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    event.getRequestParams().putAll((decoder.getParameters()));

    /* Content */
    if (request.getContent().capacity() > 0) {
        String content = new String(request.getContent().array());
        // We check if it's a form validation and so we extract post params
        if ("application/x-www-form-urlencoded".equals(request.getHeader("Content-Type"))) {
            decoder = new QueryStringDecoder("http://localhost/?" + content);
            event.getRequestParams().putAll(decoder.getParameters());
        } else {
            event.setWithBody(true);
            dumpRequestBody(id, content);
        }
    }

    listEvents.add(event);
}