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:se.sics.caracaldb.global.DefaultPolicy.java

private void getHostActions(LUTWorkingBuffer lut, ImmutableSortedMap<Integer, Address> failIds,
        ImmutableSortedMap<Integer, Address> joinIds) {
    SortedMapDifference<Integer, Address> idDiff = Maps.difference(failIds, joinIds);
    SortedMap<Integer, Address> nullableIds = idDiff.entriesOnlyOnLeft();
    for (Entry<Integer, Address> e : nullableIds.entrySet()) {
        lut.removeHost(e.getKey());//from w w w. j a  v  a2  s . co m
    }
    for (Entry<Integer, Address> e : joinIds.entrySet()) {
        lut.putHost(e.getKey(), e.getValue());
    }
}

From source file:com.facebook.buck.rules.ActionGraphCache.java

/**
 * Compares the cached ActionGraph with a newly generated from the targetGraph. The comparison
 * is done by generating and comparing content agnostic RuleKeys. In case of mismatch, the
 * mismatching BuildRules are printed and the building process is stopped.
 * @param eventBus Buck's event bus./* w ww  . j a va  2s.c  o  m*/
 * @param lastActionGraphAndResolver The cached version of the graph that gets compared.
 * @param targetGraph Used to generate the actionGraph that gets compared with lastActionGraph.
 */
private void compareActionGraphs(final BuckEventBus eventBus,
        final ActionGraphAndResolver lastActionGraphAndResolver, final TargetGraph targetGraph,
        final int keySeed) {
    try (SimplePerfEvent.Scope scope = SimplePerfEvent.scope(eventBus,
            PerfEventId.of("ActionGraphCacheCheck"))) {
        // We check that the lastActionGraph is not null because it's possible we had a
        // invalidateCache() between the scheduling and the execution of this task.
        LOG.info("ActionGraph integrity check spawned.");
        Pair<TargetGraph, ActionGraphAndResolver> newActionGraph = new Pair<TargetGraph, ActionGraphAndResolver>(
                targetGraph,
                createActionGraph(eventBus, new DefaultTargetNodeToBuildRuleTransformer(), targetGraph));

        Map<BuildRule, RuleKey> lastActionGraphRuleKeys = getRuleKeysFromBuildRules(
                lastActionGraphAndResolver.getActionGraph().getNodes(),
                lastActionGraphAndResolver.getResolver(), keySeed);
        Map<BuildRule, RuleKey> newActionGraphRuleKeys = getRuleKeysFromBuildRules(
                newActionGraph.getSecond().getActionGraph().getNodes(),
                newActionGraph.getSecond().getResolver(), keySeed);

        if (!lastActionGraphRuleKeys.equals(newActionGraphRuleKeys)) {
            invalidateCache();
            String mismatchInfo = "RuleKeys of cached and new ActionGraph don't match:\n";
            MapDifference<BuildRule, RuleKey> mismatchedRules = Maps.difference(lastActionGraphRuleKeys,
                    newActionGraphRuleKeys);
            mismatchInfo += "Number of nodes in common/differing: " + mismatchedRules.entriesInCommon().size()
                    + "/" + mismatchedRules.entriesDiffering().size() + "\n"
                    + "Entries only in the cached ActionGraph: " + mismatchedRules.entriesOnlyOnLeft().size()
                    + "Entries only in the newly created ActionGraph: "
                    + mismatchedRules.entriesOnlyOnRight().size() + "The rules that did not match:\n";
            mismatchInfo += mismatchedRules.entriesDiffering().keySet().toString();
            LOG.error(mismatchInfo);
            throw new RuntimeException(mismatchInfo);
        }
    }
}

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  ww .  ja  v  a2 s  . 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.facebook.buck.parser.DaemonicCellState.java

Optional<MapDifference<String, String>> invalidateIfEnvHasChanged(Cell cell, Path buildFile) {
    try (AutoCloseableLock writeLock = rawAndComputedNodesLock.writeLock()) {
        // Invalidate if env vars have changed.
        ImmutableMap<String, Optional<String>> usedEnv = buildFileEnv.get(buildFile);
        if (usedEnv == null) {
            this.cell = cell;
            return Optional.empty();
        }// w  w  w  .j  a  va2s .  co  m
        for (Map.Entry<String, Optional<String>> ent : usedEnv.entrySet()) {
            Optional<String> value = Optional
                    .ofNullable(cell.getBuckConfig().getEnvironment().get(ent.getKey()));
            if (!value.equals(ent.getValue())) {
                invalidatePath(buildFile);
                this.cell = cell;
                return Optional.of(Maps.difference(
                        value.map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of()),
                        ent.getValue().map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of())));
            }
        }
        return Optional.empty();
    }
}

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

/**
 * @return the difference between oldProps and newProps.
 *//*from   w ww  .  ja  v a2  s. co  m*/
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:org.opentestsystem.authoring.testauth.service.impl.FileGroupServiceImpl.java

@Override
public SearchResponse<FileGroup> searchPsychometricRecordFileGroupsByVersion(
        final Map<String, String[]> parameterMap) {

    final SearchResponse<PublishingRecord> publishingRecordResponse = this.publishingRecordService
            .searchPublishingRecords(getPublishingRecordSearchParams(parameterMap));

    for (final PublishingRecord publishingRecord : publishingRecordResponse.getSearchResults()) {
        final PsychometricRecord psychometricRecord = getPsychometricRecordByPublishingRecordId(
                publishingRecord.getId());
        if (psychometricRecord != null) {
            final Map<String, String[]> updatedParams = Maps.newHashMap();
            updatedParams.putAll(Maps.difference(parameterMap, updatedParams).entriesOnlyOnLeft());
            updatedParams.put("psychometricRecordId", new String[] { psychometricRecord.getId() });
            updatedParams.remove("assessmentId");
            updatedParams.remove("version");
            return searchFileGroups(updatedParams);
        }//from  w w w  . jav  a 2 s .c  o  m
    }
    return searchFileGroups(
            ImmutableMap.of("psychometricRecordId", new String[] { "invalid-psychometric-id" }));
}

From source file:azkaban.utils.PropsUtils.java

/**
 * @param oldProps/*from w ww .  ja  v a  2s  .  com*/
 * @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.apache.ambari.server.upgrade.AbstractUpgradeCatalog.java

protected void updateConfigurationPropertiesForCluster(Cluster cluster, String configType,
        Map<String, String> properties, boolean updateIfExists, boolean createNewConfigType)
        throws AmbariException {
    AmbariManagementController controller = injector.getInstance(AmbariManagementController.class);
    String newTag = "version" + System.currentTimeMillis();

    if (properties != null) {
        Map<String, Config> all = cluster.getConfigsByType(configType);
        if (all == null || !all.containsKey(newTag) || properties.size() > 0) {
            Map<String, String> oldConfigProperties;
            Config oldConfig = cluster.getDesiredConfigByType(configType);

            if (oldConfig == null && !createNewConfigType) {
                LOG.info("Config " + configType + " not found. Assuming service not installed. "
                        + "Skipping configuration properties update");
                return;
            } else if (oldConfig == null) {
                oldConfigProperties = new HashMap<String, String>();
                newTag = "version1";
            } else {
                oldConfigProperties = oldConfig.getProperties();
            }/*from   w w  w . ja  v  a  2s. c  o  m*/

            Map<String, String> mergedProperties = mergeProperties(oldConfigProperties, properties,
                    updateIfExists);

            if (!Maps.difference(oldConfigProperties, mergedProperties).areEqual()) {
                LOG.info("Applying configuration with tag '{}' to " + "cluster '{}'", newTag,
                        cluster.getClusterName());

                ConfigurationRequest cr = new ConfigurationRequest();
                cr.setClusterName(cluster.getClusterName());
                cr.setVersionTag(newTag);
                cr.setType(configType);
                cr.setProperties(mergedProperties);
                controller.createConfiguration(cr);

                Config baseConfig = cluster.getConfig(cr.getType(), cr.getVersionTag());
                if (baseConfig != null) {
                    String authName = AUTHENTICATED_USER_NAME;

                    if (cluster.addDesiredConfig(authName, Collections.singleton(baseConfig)) != null) {
                        String oldConfigString = (oldConfig != null) ? " from='" + oldConfig.getTag() + "'"
                                : "";
                        LOG.info("cluster '" + cluster.getClusterName() + "' " + "changed by: '" + authName
                                + "'; " + "type='" + baseConfig.getType() + "' " + "tag='" + baseConfig.getTag()
                                + "'" + oldConfigString);
                    }
                }
            } else {
                LOG.info("No changes detected to config " + configType
                        + ". Skipping configuration properties update");
            }
        }
    }
}

From source file:com.facebook.buck.core.model.actiongraph.computation.ActionGraphProvider.java

/**
 * Compares the cached ActionGraph with a newly generated from the targetGraph. The comparison is
 * done by generating and comparing content agnostic RuleKeys. In case of mismatch, the
 * mismatching BuildRules are printed and the building process is stopped.
 *
 * @param lastActionGraphAndBuilder The cached version of the graph that gets compared.
 * @param targetGraph Used to generate the actionGraph that gets compared with lastActionGraph.
 * @param fieldLoader//w  w  w . j  ava2 s . c o m
 * @param ruleKeyLogger The logger to use (if any) when computing the new action graph
 */
private void compareActionGraphs(ActionGraphAndBuilder lastActionGraphAndBuilder,
        TargetNodeToBuildRuleTransformer transformer, TargetGraph targetGraph, RuleKeyFieldLoader fieldLoader,
        Optional<ThriftRuleKeyLogger> ruleKeyLogger) {
    try (SimplePerfEvent.Scope scope = SimplePerfEvent.scope(eventBus,
            PerfEventId.of("ActionGraphCacheCheck"))) {
        // We check that the lastActionGraph is not null because it's possible we had a
        // invalidateCache() between the scheduling and the execution of this task.
        LOG.info("ActionGraph integrity check spawned.");
        ActionGraphAndBuilder newActionGraph = createActionGraph(transformer, targetGraph,
                IncrementalActionGraphMode.DISABLED);

        Map<BuildRule, RuleKey> lastActionGraphRuleKeys = getRuleKeysFromBuildRules(
                lastActionGraphAndBuilder.getActionGraph().getNodes(),
                lastActionGraphAndBuilder.getActionGraphBuilder(), fieldLoader,
                Optional.empty() /* Only log once, and only for the new graph */);
        Map<BuildRule, RuleKey> newActionGraphRuleKeys = getRuleKeysFromBuildRules(
                newActionGraph.getActionGraph().getNodes(), newActionGraph.getActionGraphBuilder(), fieldLoader,
                ruleKeyLogger);

        if (!lastActionGraphRuleKeys.equals(newActionGraphRuleKeys)) {
            actionGraphCache.invalidateCache();
            String mismatchInfo = "RuleKeys of cached and new ActionGraph don't match:\n";
            MapDifference<BuildRule, RuleKey> mismatchedRules = Maps.difference(lastActionGraphRuleKeys,
                    newActionGraphRuleKeys);
            mismatchInfo += "Number of nodes in common/differing: " + mismatchedRules.entriesInCommon().size()
                    + "/" + mismatchedRules.entriesDiffering().size() + "\n"
                    + "Entries only in the cached ActionGraph: " + mismatchedRules.entriesOnlyOnLeft().size()
                    + "Entries only in the newly created ActionGraph: "
                    + mismatchedRules.entriesOnlyOnRight().size() + "The rules that did not match:\n";
            mismatchInfo += mismatchedRules.entriesDiffering().keySet().toString();
            LOG.error(mismatchInfo);
            throw new RuntimeException(mismatchInfo);
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport.java

/**
 * Performs verification of the given files.
 * @param checker {@link Checker} instance
 * @param processedFiles files to process.
 * @param expectedViolations a map of expected violations per files.
 * @throws Exception if exception occurs during verification process.
 *//*w  w w .  j  a  v  a  2  s . c om*/
protected final void verify(Checker checker, File[] processedFiles,
        Map<String, List<String>> expectedViolations) throws Exception {
    stream.flush();
    final List<File> theFiles = new ArrayList<>();
    Collections.addAll(theFiles, processedFiles);
    final int errs = checker.process(theFiles);

    // process each of the lines
    final Map<String, List<String>> actualViolations = getActualViolations(errs);
    final Map<String, List<String>> realExpectedViolations = Maps.filterValues(expectedViolations,
            input -> !input.isEmpty());
    final MapDifference<String, List<String>> violationDifferences = Maps.difference(realExpectedViolations,
            actualViolations);

    final Map<String, List<String>> missingViolations = violationDifferences.entriesOnlyOnLeft();
    final Map<String, List<String>> unexpectedViolations = violationDifferences.entriesOnlyOnRight();
    final Map<String, MapDifference.ValueDifference<List<String>>> differingViolations = violationDifferences
            .entriesDiffering();

    final StringBuilder message = new StringBuilder(256);
    if (!missingViolations.isEmpty()) {
        message.append("missing violations: ").append(missingViolations);
    }
    if (!unexpectedViolations.isEmpty()) {
        if (message.length() > 0) {
            message.append('\n');
        }
        message.append("unexpected violations: ").append(unexpectedViolations);
    }
    if (!differingViolations.isEmpty()) {
        if (message.length() > 0) {
            message.append('\n');
        }
        message.append("differing violations: ").append(differingViolations);
    }

    assertTrue(message.toString(),
            missingViolations.isEmpty() && unexpectedViolations.isEmpty() && differingViolations.isEmpty());

    checker.destroy();
}