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.jfrog.hudson.plugins.artifactory.util.ExtractorUtils.java

private static void addEnvVars(Map<String, String> env, AbstractBuild<?, ?> build,
        ArtifactoryClientConfiguration configuration, IncludesExcludes envVarsPatterns) {
    IncludeExcludePatterns patterns = new IncludeExcludePatterns(envVarsPatterns.getIncludePatterns(),
            envVarsPatterns.getExcludePatterns());

    // Add only the Hudson specific environment variables
    MapDifference<String, String> envDifference = Maps.difference(env, System.getenv());
    Map<String, String> filteredEnvDifference = envDifference.entriesOnlyOnLeft();
    configuration.info.addBuildVariables(filteredEnvDifference, patterns);

    // Add Hudson build variables
    Map<String, String> buildVariables = build.getBuildVariables();
    MapDifference<String, String> buildVarDifference = Maps.difference(buildVariables, System.getenv());
    Map<String, String> filteredBuildVarDifferences = buildVarDifference.entriesOnlyOnLeft();
    configuration.info.addBuildVariables(filteredBuildVarDifferences, patterns);

    // Write all the deploy (matrix params) properties.
    configuration.fillFromProperties(buildVariables, patterns);
    for (Map.Entry<String, String> entry : buildVariables.entrySet()) {
        if (entry.getKey().startsWith(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX)) {
            configuration.publisher.addMatrixParam(entry.getKey(), entry.getValue());
        }//from  ww w.  jav  a 2s . c o  m
    }
}

From source file:com.eucalyptus.bootstrap.Databases.java

private static void runDbStateChange(Function<String, Runnable> runnableFunction) {
    Logs.extreme().info("DB STATE CHANGE: " + runnableFunction);
    try {/*from   w w w  .  j ava  2 s . co m*/
        Logs.extreme().info("Attempting to acquire db state lock: " + runnableFunction);
        if (canHas.writeLock().tryLock(5, TimeUnit.MINUTES)) {

            try {
                Logs.extreme().info("Acquired db state lock: " + runnableFunction);
                Map<Runnable, Future<Runnable>> runnables = Maps.newHashMap();
                for (final String ctx : listDatabases()) {
                    Runnable run = runnableFunction.apply(ctx);
                    runnables.put(run, ExecuteRunnable.INSTANCE.apply(run));
                }
                Map<Runnable, Future<Runnable>> succeeded = Futures.waitAll(runnables);
                MapDifference<Runnable, Future<Runnable>> failed = Maps.difference(runnables, succeeded);
                StringBuilder builder = new StringBuilder();
                builder.append(Joiner.on("\nSUCCESS: ").join(succeeded.keySet()));
                builder.append(Joiner.on("\nFAILED:  ").join(failed.entriesOnlyOnLeft().keySet()));
                Logs.extreme().debug(builder.toString());
                if (!failed.entriesOnlyOnLeft().isEmpty()) {
                    throw Exceptions.toUndeclared(builder.toString());
                }
            } finally {
                canHas.writeLock().unlock();
            }
        } else {
            throw new LockTimeoutException("DB STATE CHANGE ABORTED (failed to get lock): " + runnableFunction);
        }
    } catch (RuntimeException ex) {
        LOG.error(ex);
        Logs.extreme().error(ex, ex);
        throw ex;
    } catch (InterruptedException ex) {
        Exceptions.maybeInterrupted(ex);
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:com.fixedorgo.neuron.NeoFuzzyNeuron.java

@Override
public boolean equals(Object obj) {
    return obj instanceof NeoFuzzyNeuron
            && Maps.difference(synapses, NeoFuzzyNeuron.class.cast(obj).synapses).areEqual();
}

From source file:com.twitter.distributedlog.client.routing.ConsistentHashRoutingService.java

@Override
protected synchronized void performServerSetChange(ImmutableSet<DLSocketAddress> serviceInstances) {
    Set<SocketAddress> joinedList = new HashSet<SocketAddress>();
    Set<SocketAddress> removedList = new HashSet<SocketAddress>();

    Map<Integer, SocketAddress> newMap = new HashMap<Integer, SocketAddress>();
    synchronized (shardId2Address) {
        for (DLSocketAddress serviceInstance : serviceInstances) {
            if (serviceInstance.getShard() >= 0) {
                newMap.put(serviceInstance.getShard(), serviceInstance.getSocketAddress());
            } else {
                Integer shard = address2ShardId.get(serviceInstance.getSocketAddress());
                if (null == shard) {
                    // Assign a random negative shardId
                    int shardId;
                    do {
                        shardId = Math.min(-1, (int) (Math.random() * Integer.MIN_VALUE));
                    } while (null != shardId2Address.get(shardId));
                    shard = shardId;/* ww w  . j  a  va2 s  .c om*/
                }
                newMap.put(shard, serviceInstance.getSocketAddress());
            }
        }
    }

    Map<Integer, SocketAddress> left;
    synchronized (shardId2Address) {
        MapDifference<Integer, SocketAddress> difference = Maps.difference(shardId2Address, newMap);
        left = difference.entriesOnlyOnLeft();
        for (Integer shard : left.keySet()) {
            if (shard >= 0) {
                SocketAddress host = shardId2Address.get(shard);
                if (null != host) {
                    // we don't remove those hosts that just disappered on serverset proactively,
                    // since it might be just because serverset become flaky
                    // address2ShardId.remove(host);
                    // circle.remove(shard, host);
                    logger.info("Shard {} ({}) left temporarily.", shard, host);
                }
            } else {
                // shard id is negative - they are resolved from finagle name, which instances don't have shard id
                // in this case, if they are removed from serverset, we removed them directly
                SocketAddress host = left.get(shard);
                if (null != host) {
                    removeHostInternal(host, Optional.<Throwable>absent());
                    removedList.add(host);
                }
            }
        }
        // we need to find if any shards are replacing old shards
        for (Integer shard : newMap.keySet()) {
            SocketAddress oldHost = shardId2Address.get(shard);
            SocketAddress newHost = newMap.get(shard);
            if (!newHost.equals(oldHost)) {
                join(shard, newHost, removedList);
                joinedList.add(newHost);
            }
        }
    }

    for (SocketAddress addr : removedList) {
        for (RoutingListener listener : listeners) {
            listener.onServerLeft(addr);
        }
    }

    for (SocketAddress addr : joinedList) {
        for (RoutingListener listener : listeners) {
            listener.onServerJoin(addr);
        }
    }
}

From source file:org.apache.distributedlog.client.routing.ConsistentHashRoutingService.java

@Override
protected synchronized void performServerSetChange(ImmutableSet<DLSocketAddress> serviceInstances) {
    Set<SocketAddress> joinedList = new HashSet<SocketAddress>();
    Set<SocketAddress> removedList = new HashSet<SocketAddress>();

    Map<Integer, SocketAddress> newMap = new HashMap<Integer, SocketAddress>();
    synchronized (shardId2Address) {
        for (DLSocketAddress serviceInstance : serviceInstances) {
            if (serviceInstance.getShard() >= 0) {
                newMap.put(serviceInstance.getShard(), serviceInstance.getSocketAddress());
            } else {
                Integer shard = address2ShardId.get(serviceInstance.getSocketAddress());
                if (null == shard) {
                    // Assign a random negative shardId
                    int shardId;
                    do {
                        shardId = Math.min(-1, (int) (Math.random() * Integer.MIN_VALUE));
                    } while (null != shardId2Address.get(shardId));
                    shard = shardId;//  w w w. ja va  2  s  .c om
                }
                newMap.put(shard, serviceInstance.getSocketAddress());
            }
        }
    }

    Map<Integer, SocketAddress> left;
    synchronized (shardId2Address) {
        MapDifference<Integer, SocketAddress> difference = Maps.difference(shardId2Address, newMap);
        left = difference.entriesOnlyOnLeft();
        for (Map.Entry<Integer, SocketAddress> shardEntry : left.entrySet()) {
            int shard = shardEntry.getKey();
            if (shard >= 0) {
                SocketAddress host = shardId2Address.get(shard);
                if (null != host) {
                    // we don't remove those hosts that just disappered on serverset proactively,
                    // since it might be just because serverset become flaky
                    // address2ShardId.remove(host);
                    // circle.remove(shard, host);
                    logger.info("Shard {} ({}) left temporarily.", shard, host);
                }
            } else {
                // shard id is negative - they are resolved from finagle name, which instances don't have shard id
                // in this case, if they are removed from serverset, we removed them directly
                SocketAddress host = shardEntry.getValue();
                if (null != host) {
                    removeHostInternal(host, Optional.<Throwable>absent());
                    removedList.add(host);
                }
            }
        }
        // we need to find if any shards are replacing old shards
        for (Map.Entry<Integer, SocketAddress> shard : newMap.entrySet()) {
            SocketAddress oldHost = shardId2Address.get(shard.getKey());
            SocketAddress newHost = shard.getValue();
            if (!newHost.equals(oldHost)) {
                join(shard.getKey(), newHost, removedList);
                joinedList.add(newHost);
            }
        }
    }

    for (SocketAddress addr : removedList) {
        for (RoutingListener listener : listeners) {
            listener.onServerLeft(addr);
        }
    }

    for (SocketAddress addr : joinedList) {
        for (RoutingListener listener : listeners) {
            listener.onServerJoin(addr);
        }
    }
}

From source file:eu.numberfour.n4js.ui.preferences.AbstractN4JSPreferencePage.java

/**
 * @param originalSettings//w  w  w.  j  a v a2 s. c o m
 *            the settings before applying the values of the form page
 * @param currentSettings
 *            the settings after collecting the values of the form page
 * @return a map keyed by the preference store key (e.g. outlet.es5.autobuilding for compiler (resp. output
 *         configuration) with name 'es5' and property 'autobuilding') containing old and new value. Only keys whose
 *         values has been changed are included.
 */
private Map<String, ValueDifference<String>> getPreferenceChanges(Map<String, String> originalSettings,
        Map<String, String> currentSettings) {
    MapDifference<String, String> mapDifference = Maps.difference(currentSettings, originalSettings);
    return mapDifference.entriesDiffering();
}

From source file:io.fabric8.api.Profiles.java

/**
 * Get the diff string of two profiles//from w  w w .  j a va  2  s . com
 */
public static String getProfileDifference(Profile leftProfile, Profile rightProfile) {
    IllegalArgumentAssertion.assertNotNull(leftProfile, "leftProfile");
    IllegalArgumentAssertion.assertNotNull(rightProfile, "rightProfile");
    if (leftProfile.equals(rightProfile)) {
        return "ProfileDiff [ver=" + leftProfile.getVersion() + ",id=" + leftProfile.getId() + "] - equals";
    } else {
        StringBuilder builder = new StringBuilder(
                "ProfileDiff [ver=" + leftProfile.getVersion() + ",id=" + leftProfile.getId() + "] vs. [ver="
                        + rightProfile.getVersion() + ",id=" + rightProfile.getId() + "]");
        MapDifference<String, String> attributeDiff = Maps.difference(leftProfile.getAttributes(),
                rightProfile.getAttributes());
        SetView<String> leftOnlyPids = Sets.difference(leftProfile.getConfigurations().keySet(),
                rightProfile.getConfigurations().keySet());
        SetView<String> rightOnlyPids = Sets.difference(rightProfile.getConfigurations().keySet(),
                leftProfile.getConfigurations().keySet());
        SetView<String> commonPids = Sets.union(leftProfile.getConfigurations().keySet(),
                rightProfile.getConfigurations().keySet());
        SetView<String> leftOnlyFiles = Sets.difference(leftProfile.getFileConfigurations().keySet(),
                rightProfile.getFileConfigurations().keySet());
        SetView<String> rightOnlyFiles = Sets.difference(rightProfile.getFileConfigurations().keySet(),
                leftProfile.getFileConfigurations().keySet());
        builder.append("\nAttributes");
        builder.append("\n  " + attributeDiff);
        builder.append("\nConfigurations");
        builder.append("\n  left only: " + leftOnlyPids);
        for (String pid : leftOnlyPids) {
            builder.append("\n  " + pid);
            Map<String, String> config = new TreeMap<>(leftProfile.getConfiguration(pid));
            for (Entry<String, String> citem : config.entrySet()) {
                builder.append("\n    " + citem.getKey() + " = " + citem.getValue());
            }
        }
        builder.append("\n  right only: " + rightOnlyPids);
        for (String pid : rightOnlyPids) {
            builder.append("\n  " + pid);
            Map<String, String> config = new TreeMap<>(rightProfile.getConfiguration(pid));
            for (Entry<String, String> citem : config.entrySet()) {
                builder.append("\n    " + citem.getKey() + " = " + citem.getValue());
            }
        }
        for (String pid : commonPids) {
            Map<String, String> leftConfig = leftProfile.getConfiguration(pid);
            Map<String, String> rightConfig = rightProfile.getConfiguration(pid);
            if (!leftConfig.equals(rightConfig)) {
                builder.append("\n  " + pid + ": " + Maps.difference(leftConfig, rightConfig));
            }
        }
        builder.append("\nFiles");
        builder.append("\n  left only: " + leftOnlyFiles);
        builder.append("\n  right only: " + rightOnlyFiles);
        return builder.toString();
    }
}

From source file:org.apache.stratos.cloud.controller.publisher.CartridgeInstanceDataPublisherTask.java

private static void populateNewlyAddedOrStateChangedNodes(Map<String, String> newMap) {

    MapDifference<String, String> diff = Maps.difference(newMap,
            FasterLookUpDataHolder.getInstance().getNodeIdToStatusMap());

    // adding newly added nodes
    Map<String, String> newlyAddedNodes = diff.entriesOnlyOnLeft();

    for (Iterator<?> it = newlyAddedNodes.entrySet().iterator(); it.hasNext();) {
        @SuppressWarnings("unchecked")
        Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
        String key = entry.getKey();
        String val = entry.getValue();
        ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);

        log.debug("------ Node id: " + key + " --- node status: " + val + " -------- ctxt: " + ctxt);

        if (ctxt != null && key != null && val != null) {
            // bundle the data to be published
            bundleData(key, val, ctxt);
        }/* w ww.j a  v  a2  s . com*/

    }

    // adding nodes with state changes
    Map<String, ValueDifference<String>> stateChangedNodes = diff.entriesDiffering();

    for (Iterator<?> it = stateChangedNodes.entrySet().iterator(); it.hasNext();) {
        @SuppressWarnings("unchecked")
        Map.Entry<String, ValueDifference<String>> entry = (Map.Entry<String, ValueDifference<String>>) it
                .next();

        String key = entry.getKey();
        String newState = entry.getValue().leftValue();
        ServiceContext ctxt = FasterLookUpDataHolder.getInstance().getServiceContext(key);

        log.debug("------- Node id: " + key + " --- node status: " + newState + " -------- ctxt: " + ctxt);

        if (ctxt != null && key != null && newState != null) {
            // bundle the data to be published
            bundleData(key, newState, ctxt);
        }

    }

}

From source file:org.apache.cassandra.schema.LegacySchemaTables.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<>();

    /*/*from  www .j a v  a 2 s  . c  om*/
     * - 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().hasColumns())
            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().getKey());

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

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

    for (Row row : created)
        Schema.instance.addKeyspace(createKeyspaceFromSchemaPartition(row));
    for (String name : altered)
        Schema.instance.updateKeyspace(name);
    return dropped;
}

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 ww.  jav a2  s  .  c o m
    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);
}