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.oscarehr.admin.traceability.TraceabilityReportProcessor.java

@Override
public String call() throws Exception {
    ClinicDAO dao = SpringUtils.getBean(ClinicDAO.class);
    Clinic clinic = dao.getClinic();/*  w w  w .j a v  a  2  s .c o  m*/
    String clinicName = clinic.getClinicName();
    String originDate = null;
    String gitSHA = null;
    clinicName = (clinicName == null) ? "" : clinicName;
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    PrintWriter pw = new PrintWriter(outputStream);
    List<FileItem> items = upload.parseRequest(request);
    for (FileItem diskFileItem : items) {
        GZIPInputStream gzip = new GZIPInputStream(diskFileItem.getInputStream());
        ObjectInputStream ios = new ObjectInputStream(gzip);
        @SuppressWarnings("unchecked")
        Map<String, String> sourceMap = (Map<String, String>) ios.readObject();
        originDate = sourceMap.get("origin_date");
        originDate = (originDate == null) ? "n/a" : originDate;
        sourceMap.remove("origin_date");
        gitSHA = sourceMap.get("git_sha");
        gitSHA = (gitSHA == null) ? "n/a" : gitSHA;
        sourceMap.remove("origin_date");
        sourceMap.remove("git_sha");
        // build local 'trace' 
        Map<String, String> targetMap = GenerateTraceabilityUtil.buildTraceMap(request);
        // find the difference between incoming and local 'trace'
        MapDifference<String, String> diff = Maps.difference(sourceMap, targetMap);
        // modified, for the same keys
        Map<String, MapDifference.ValueDifference<String>> differing = diff.entriesDiffering();

        pw.write("---------------------------------------------------------------------------------------");
        pw.write(newLine);
        pw.write("----------------------------TRACEABILITY REPORT----------------------------------------");
        pw.write(newLine);
        pw.write("---------------------------------------------------------------------------------------");
        pw.write(newLine);
        pw.write(newLine);
        pw.write("Started: " + new java.util.Date());
        pw.write(newLine);
        pw.write(newLine);
        pw.write("Trace Generated On Date: " + originDate);
        pw.write(newLine);
        pw.write("Clinic Name: " + clinicName);
        pw.write(newLine);
        pw.write("Git SHA: " + gitSHA);
        pw.write(newLine);
        pw.write(newLine);
        pw.write("Changed:");
        pw.write(newLine);
        pw.write("-----------------------------------------");
        pw.write(newLine);
        pw.write(newLine);
        for (Map.Entry<String, MapDifference.ValueDifference<String>> entry : differing.entrySet()) {
            String key = entry.getKey();
            pw.write(key);
            pw.write(newLine);
            pw.write(newLine);
        }
        //to check equality
        //boolean mapsEqual = diff.areEqual();

        pw.write(newLine);
        pw.write("Removed:");
        pw.write(newLine);
        pw.write("-----------------------------------------");
        pw.write(newLine);
        pw.write(newLine);
        Map<String, String> left_ = diff.entriesOnlyOnLeft();
        for (Map.Entry<String, String> entry : left_.entrySet()) {
            String key = entry.getKey();
            pw.write(key);
            pw.write(newLine);
        }

        pw.write(newLine);
        pw.write("Added:");
        pw.write(newLine);
        pw.write("-----------------------------------------");
        pw.write(newLine);
        pw.write(newLine);
        Map<String, String> right_ = diff.entriesOnlyOnRight();
        for (Map.Entry<String, String> entry : right_.entrySet()) {
            String key = entry.getKey();
            pw.write(key);
            pw.write(newLine);
        }

        pw.write(newLine);
        pw.write("Unchanged:");
        pw.write(newLine);
        pw.write("-----------------------------------------");
        pw.write(newLine);
        pw.write(newLine);
        Map<String, String> common = diff.entriesInCommon();
        for (Map.Entry<String, String> entry : common.entrySet()) {
            String key = entry.getKey();
            pw.write(key);
            pw.write(newLine);
        }

        pw.write("Finished: " + new java.util.Date());
        pw.write(newLine);
        pw.write("---------------------------------------------------------------------------------------");
        pw.write(newLine);
        pw.write("--------------------------------END OF REPORT------------------------------------------");
        pw.write(newLine);
        pw.write("---------------------------------------------------------------------------------------");
        pw.write(newLine);
        pw.flush();
        pw.close();
        break;
    }
    return getClass().getName();
}

From source file:org.sonarsource.sonarlint.core.container.connected.update.check.ModuleStorageUpdateChecker.java

private static void checkForSettingsUpdates(DefaultStorageUpdateCheckResult result,
        ModuleConfiguration serverModuleConfiguration, ModuleConfiguration storageModuleConfiguration) {
    MapDifference<String, String> propDiff = Maps.difference(
            GlobalSettingsUpdateChecker.filter(storageModuleConfiguration.getPropertiesMap()),
            GlobalSettingsUpdateChecker.filter(serverModuleConfiguration.getPropertiesMap()));
    if (!propDiff.areEqual()) {
        result.appendToChangelog("Project settings updated");
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnLeft().entrySet()) {
            LOG.debug("Property '{}' removed", entry.getKey());
        }/*w ww .java  2  s . c o  m*/
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnRight().entrySet()) {
            LOG.debug("Property '{}' added with value '{}'", entry.getKey(),
                    GlobalSettingsUpdateChecker.formatValue(entry.getKey(), entry.getValue()));
        }
        for (Map.Entry<String, ValueDifference<String>> entry : propDiff.entriesDiffering().entrySet()) {
            LOG.debug("Value of property '{}' changed from '{}' to '{}'", entry.getKey(),
                    GlobalSettingsUpdateChecker.formatLeftDiff(entry.getKey(), entry.getValue().leftValue(),
                            entry.getValue().rightValue()),
                    GlobalSettingsUpdateChecker.formatRightDiff(entry.getKey(), entry.getValue().leftValue(),
                            entry.getValue().rightValue()));
        }
    }
}

From source file:org.apache.aurora.scheduler.updater.JobDiff.java

private static JobDiff computeUnscoped(Map<Integer, ITaskConfig> currentState, IJobKey job,
        Map<Integer, ITaskConfig> proposedState) {

    requireNonNull(job);/*w  w w.j av a 2  s . c  om*/
    requireNonNull(proposedState);

    MapDifference<Integer, ITaskConfig> diff = Maps.difference(currentState, proposedState);

    Map<Integer, ITaskConfig> removedInstances = ImmutableMap.<Integer, ITaskConfig>builder()
            .putAll(diff.entriesOnlyOnLeft())
            .putAll(Maps.transformValues(diff.entriesDiffering(), JobDiff.leftValue())).build();

    Set<Integer> addedInstances = ImmutableSet.<Integer>builder().addAll(diff.entriesOnlyOnRight().keySet())
            .addAll(diff.entriesDiffering().keySet()).build();

    return new JobDiff(removedInstances, addedInstances, ImmutableMap.copyOf(diff.entriesInCommon()));
}

From source file:com.technophobia.webdriver.substeps.impl.AbstractWebDriverSubStepImplementations.java

protected boolean elementHasExpectedAttributes(final WebElement e,
        final Map<String, String> expectedAttributes) {
    final Map<String, String> actualValues = new HashMap<String, String>();

    for (final String key : expectedAttributes.keySet()) {
        final String elementVal = e.getAttribute(key);

        // if no attribute will this throw an exception or just return
        // null ??
        actualValues.put(key, elementVal);

    }// w  ww.  j a  v a  2 s  .co m

    final MapDifference<String, String> difference = Maps.difference(expectedAttributes, actualValues);
    return difference.areEqual();
}

From source file:gobblin.configuration.State.java

/**
 * Populates this instance with properties of the other instance.
 *
 * @param otherState the other {@link State} instance
 *//*w w  w  .java2 s. co  m*/
public void addAll(State otherState) {
    Properties diffCommonProps = new Properties();
    diffCommonProps
            .putAll(Maps.difference(this.commonProperties, otherState.commonProperties).entriesOnlyOnRight());
    addAll(diffCommonProps);
    addAll(otherState.specProperties);
}

From source file:com.alibaba.jstorm.config.SupervisorRefreshConfig.java

@Override
public void run() {
    try {/*from  w w w. j  av a2  s .  co m*/
        if (!enableSync) {
            return;
        }

        if (this.nimbusClientWrapper == null) {
            this.nimbusClientWrapper = new NimbusClientWrapper();
            try {
                this.nimbusClientWrapper.init(this.stormConf);
            } catch (Exception ex) {
                LOG.error("init nimbus client wrapper error, maybe nimbus is not alive.");
            }
        }

        String nimbusYaml = JStormUtils.trimEnd(yarnConfigBlacklist
                .filterConfigIfNecessary(this.nimbusClientWrapper.getClient().getStormRawConf()));
        Map nimbusConf = LoadConf.loadYamlFromString(nimbusYaml);

        if (nimbusYaml != null && !this.supervisorConf.equals(nimbusConf)) {
            Map newConf = LoadConf.loadYamlFromString(nimbusYaml);
            if (newConf == null) {
                LOG.error("received invalid storm.yaml, skip...");
            } else {
                MapDifference<?, ?> diff = Maps.difference(this.supervisorConf, nimbusConf);
                LOG.debug("conf diff, left only:{}, right only:{}", diff.entriesOnlyOnLeft(),
                        diff.entriesOnlyOnRight());
                LOG.debug("received nimbus config update, new config:\n{}", nimbusYaml);
                this.stormYaml = nimbusYaml;

                // append yarn config
                nimbusYaml = JStormUtils.trimEnd(nimbusYaml + "\n" + retainedYarnConfig);

                // backup config & overwrite current storm.yaml
                RefreshableComponents.refresh(newConf);
                LoadConf.backupAndOverwriteStormYaml(nimbusYaml);
            }
        }
    } catch (Exception ex) {
        LOG.error("failed to get nimbus conf, maybe nimbus is not alive.");
        this.nimbusClientWrapper.reconnect();
    }
}

From source file:org.terasology.combat.systems.HitDetectionSystem.java

private synchronized void processHits(float delta) {

    //Periodic//from w w  w.j  a v  a 2 s. c om
    HashMap<EntityRef, Float> removeMap = Maps.newHashMap();
    for (Map.Entry<EntityRef, Float> entry : context.getPeriodic().entrySet()) {
        Float test = entry.getValue();
        test = test - delta;
        entry.setValue(test);
        if (test <= 0) {
            removeMap.put(entry.getKey(), test);
            entry = null;
        }
    }
    context.setPeriodic(Maps.newHashMap(Maps.difference(context.getPeriodic(), removeMap).entriesOnlyOnLeft()));
    //PeriodicPer Entity
    Set<Map.Entry<EntityRef, HashMap<EntityRef, Float>>> entries = context.getPeriodicPerEntity().entrySet();
    for (Map.Entry<EntityRef, HashMap<EntityRef, Float>> entry : entries) {
        Set<Map.Entry<EntityRef, Float>> subEntries = entry.getValue().entrySet();
        if (entry != null && entry.getKey().exists()) {
            for (Map.Entry<EntityRef, Float> entryTemp : subEntries) {
                if (entryTemp != null && (entryTemp.getKey().exists())) {
                    Float test = entryTemp.getValue();
                    test = test - delta;
                    entryTemp.setValue(test);
                    if (test <= 0) {
                        entryTemp = null;//Eintrag entfernern
                    }
                }
            }
        } else {
            entry = null;//Eintrag entfernern
        }
    }
}

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

/**
 * @param originalSettings//from   w  ww  .java2s. c om
 *            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);
    Map<String, ValueDifference<String>> entriesDiffering = mapDifference.entriesDiffering();
    return entriesDiffering;
}

From source file:org.cgiar.ccafs.marlo.utils.HistoryComparator.java

private List<HistoryDifference> compareHistory(String jsonNew, String jsonOlder, String subFix) {
    List<HistoryDifference> myDifferences = new ArrayList<>();
    Gson g = new Gson();
    Type mapType = new TypeToken<Map<String, Object>>() {
    }.getType();//from   w  w  w .  ja va 2  s .  c  o m

    JSONObject jsonObjNew = new JSONObject(jsonNew);

    JSONObject jsonObjOld = new JSONObject(jsonOlder);

    this.removeJSONField(jsonObjNew, "activeSince");
    this.removeJSONField(jsonObjOld, "activeSince");
    this.removeJSONField(jsonObjNew, "modifiedBy");
    this.removeJSONField(jsonObjOld, "modifiedBy");
    this.removeJSONField(jsonObjNew, "modificationJustification");
    this.removeJSONField(jsonObjOld, "modificationJustification");
    String subFixStr[] = subFix.split("\\.");
    for (String string : subFixStr) {
        this.removeJSONField(jsonObjNew, string);
        this.removeJSONField(jsonObjOld, string);
    }

    Map<String, Object> firstMap = g.fromJson(jsonObjNew.toString(), mapType);
    Map<String, Object> secondMap = g.fromJson(jsonObjOld.toString(), mapType);
    MapDifference<String, Object> comparable = Maps.difference(firstMap, secondMap);
    Map<String, ValueDifference<Object>> diferences = comparable.entriesDiffering();
    Map<String, Object> diferencesLeft = comparable.entriesOnlyOnLeft();
    diferences.forEach((k, v) -> myDifferences.add(new HistoryDifference(UUID.randomUUID().toString(), k, false,
            v.rightValue().toString(), v.leftValue().toString())));
    diferencesLeft.forEach((k, v) -> new HistoryDifference(UUID.randomUUID().toString(), k, true, "", ""));
    return myDifferences;
}

From source file:com.nearinfinity.honeycomb.mysql.Util.java

/**
 * Retrieve from a list of indices which ones have been changed.
 *
 * @param indices    Table indices/*  www . ja  v a2  s. co m*/
 * @param oldRecords Old MySQL row
 * @param newRecords New MySQL row
 * @return List of changed indices
 */
public static ImmutableList<IndexSchema> getChangedIndices(Collection<IndexSchema> indices,
        Map<String, ByteBuffer> oldRecords, Map<String, ByteBuffer> newRecords) {
    if (indices.isEmpty()) {
        return ImmutableList.of();
    }

    MapDifference<String, ByteBuffer> diff = Maps.difference(oldRecords, newRecords);

    Set<String> changedColumns = Sets.difference(Sets.union(newRecords.keySet(), oldRecords.keySet()),
            diff.entriesInCommon().keySet());

    ImmutableList.Builder<IndexSchema> changedIndices = ImmutableList.builder();

    for (IndexSchema index : indices) {
        Set<String> indexColumns = ImmutableSet.copyOf(index.getColumns());
        if (!Sets.intersection(changedColumns, indexColumns).isEmpty()) {
            changedIndices.add(index);
        }
    }

    return changedIndices.build();
}