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.guvnor.ala.build.maven.util.RepositoryVisitor.java

public RepositoryVisitor(final Path projectPath, final String _projectRoot, final boolean cleanTempDir) {
    this.root = makeTempRootDirectory(_projectRoot, cleanTempDir);

    try {// ww w.  j ava2  s  .  c o m
        if (_projectRoot != null && !_projectRoot.equals("")) {
            loadIndex(root.getAbsolutePath());
        }
        visitPaths(root, Files.newDirectoryStream(projectPath));
        if (oldIdentityHash != null) {
            MapDifference<String, String> difference = Maps.difference(oldIdentityHash, identityHash);
            Map<String, String> deletedFiles = difference.entriesOnlyOnLeft();
            for (String path : deletedFiles.keySet()) {
                boolean deleted = new File(
                        root.getAbsolutePath().replace(projectPath.toString(), "") + "/" + path).delete();
                System.out.println("Deleted: " + root.getAbsolutePath().replace(projectPath.toString(), "")
                        + "/" + path + " -> " + deleted);
            }
        }
        storeIndex(root.getAbsolutePath());
    } catch (IOException | NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

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

public void checkForUpdates(DefaultStorageUpdateCheckResult result, List<SonarAnalyzer> pluginList) {
    PluginReferences serverPluginReferences = pluginReferenceDownloader.fetchPlugins(pluginList);
    PluginReferences storagePluginReferences = storageManager.readPluginReferencesFromStorage();
    Map<String, String> serverPluginHashes = serverPluginReferences.getReferenceList().stream()
            .collect(Collectors.toMap(PluginReference::getKey, PluginReference::getHash));
    Map<String, String> storagePluginHashes = storagePluginReferences.getReferenceList().stream()
            .collect(Collectors.toMap(PluginReference::getKey, PluginReference::getHash));
    MapDifference<String, String> pluginDiff = Maps.difference(storagePluginHashes, serverPluginHashes);
    if (!pluginDiff.areEqual()) {
        for (Map.Entry<String, String> entry : pluginDiff.entriesOnlyOnLeft().entrySet()) {
            result.appendToChangelog(String.format("Plugin '%s' removed", entry.getKey()));
        }/*from   w  w w  .  j  a v a  2s  .  com*/
        for (Map.Entry<String, String> entry : pluginDiff.entriesOnlyOnRight().entrySet()) {
            result.appendToChangelog("Plugin '" + entry.getKey() + "' added");
        }
        for (Map.Entry<String, ValueDifference<String>> entry : pluginDiff.entriesDiffering().entrySet()) {
            result.appendToChangelog("Plugin '" + entry.getKey() + "' updated");
        }
    }
}

From source file:org.jivesoftware.smackx.omemo.OmemoManagerSetupHelper.java

public static void trustAllIdentitiesWithTests(OmemoManager alice, OmemoManager bob)
        throws InterruptedException, SmackException.NotConnectedException, SmackException.NotLoggedInException,
        SmackException.NoResponseException, CannotEstablishOmemoSessionException, CorruptedOmemoKeyException,
        XMPPException.XMPPErrorException, PubSubException.NotALeafNodeException {
    alice.requestDeviceListUpdateFor(bob.getOwnJid());
    HashMap<OmemoDevice, OmemoFingerprint> fps1 = alice.getActiveFingerprints(bob.getOwnJid());

    assertFalse(fps1.isEmpty());//w w  w  .  j  ava 2s .  c o m
    assertAllDevicesAreUndecided(alice, fps1);
    assertAllDevicesAreUntrusted(alice, fps1);

    trustAllIdentities(alice, bob);

    HashMap<OmemoDevice, OmemoFingerprint> fps2 = alice.getActiveFingerprints(bob.getOwnJid());
    assertEquals(fps1.size(), fps2.size());
    assertTrue(Maps.difference(fps1, fps2).areEqual());

    assertAllDevicesAreDecided(alice, fps2);
    assertAllDevicesAreTrusted(alice, fps2);
}

From source file:org.opendaylight.controller.filtervalve.cors.jaxb.Filter.java

public synchronized void initialize(String fileName, Optional<Filter> maybeTemplate) {
    checkState(initialized == false, "Already initialized");
    logger.trace("Initializing filter {} : {}", filterName, filterClass);
    for (InitParam initParam : initParams) {
        initParam.inititialize();/*from ww  w. j a v a 2  s  .c  o  m*/
    }
    if (maybeTemplate.isPresent()) {
        // merge non conflicting init params
        Filter template = maybeTemplate.get();
        checkArgument(template.isTemplate);
        Map<String, InitParam> templateParams = template.getInitParamsMap();
        Map<String, InitParam> currentParams = getInitParamsMap();
        // add values of template that are not present in current
        MapDifference<String, InitParam> difference = Maps.difference(templateParams, currentParams);
        for (Entry<String, InitParam> templateUnique : difference.entriesOnlyOnLeft().entrySet()) {
            initParams.add(templateUnique.getValue());
        }
        // merge filterClass
        if (filterClass == null) {
            filterClass = template.filterClass;
        } else if (Objects.equals(filterClass, template.filterClass) == false) {
            logger.error(
                    "Conflict detected in filter-class of {} defined in {}, template class {}, child class {}",
                    filterName, fileName, template.filterClass, filterClass);
            throw new IllegalStateException("Conflict detected in template/filter filter-class definitions,"
                    + " filter name: " + filterName + " in file " + fileName);
        }
    }
    initParams = Collections.unmodifiableList(new ArrayList<>(initParams));
    Class<?> clazz;
    try {
        clazz = Class.forName(filterClass);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Cannot instantiate class defined in filter " + filterName + " in file " + fileName, e);
    }
    try {
        actualFilter = (javax.servlet.Filter) clazz.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException(
                "Cannot instantiate class defined in filter " + filterName + " in file " + fileName, e);
    }
    logger.trace("Initializing {} with following init-params:{}", filterName, getInitParams());
    try {
        actualFilter.init(this);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot initialize filter " + filterName + " in file " + fileName, e);
    }
    initialized = true;
}

From source file:com.cloudera.nav.sdk.model.entities.UDPChangeSet.java

/**
 * Replace existing properties with specified properties
 * @param properties// w  w  w. j a v  a2  s  . co  m
 */
public void setProperties(Map<String, String> properties) {
    if (properties == null) {
        overrideProperties = null;
    } else {
        removeProperties.removeAll(properties.keySet());
        newProperties = Maps.newHashMap(Maps.difference(newProperties, properties).entriesOnlyOnLeft());
        overrideProperties = Maps.newHashMap(properties);
    }
}

From source file:org.wso2.carbon.governance.comparator.wsdl.WSDLDeclarationComparator.java

private boolean detectDeclarationChange(Definition base, Definition changed) {

    // 1. Check Namespaces
    Map<String, String> baseNamespaces = base.getNamespaces();
    Map<String, String> changedNamespaces = changed.getNamespaces();
    MapDifference<String, String> mapDiff = Maps.difference(baseNamespaces, changedNamespaces);
    if (!mapDiff.areEqual()) {
        return true;
    }//from  w w w . ja v a  2s .c om

    // 2. Check QNames
    if (isNotEqualAndNotNull(base.getQName(), changed.getQName())) {
        return true;
    }

    // 3. Check TNS
    if (isNotEqualAndNotNull(base.getTargetNamespace(), changed.getTargetNamespace())) {
        return true;
    }

    // 4. Check documentation
    if (isNotEqualAndNotNull(base.getDocumentationElement(), changed.getDocumentationElement())) {
        return true;
    }

    // 4. Check baseURI
    //TODO It seems comparing baseURI is not correct, check again.
    //        if (isNotEqualAndNotNull(base.getDocumentBaseURI(), changed.getDocumentBaseURI())) {
    //            return true;
    //        }

    return false;

}

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

/**
 * Perform session synchronization between local SQLite database and TMA-1
 * sessions API.// w ww. j ava2s. 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.sonarsource.sonarlint.core.container.connected.update.check.GlobalSettingsUpdateChecker.java

public void checkForUpdates(String serverVersion, DefaultStorageUpdateCheckResult result) {
    GlobalProperties serverGlobalProperties = globalPropertiesDownloader.fetchGlobalSettings(serverVersion);
    GlobalProperties storageGlobalProperties = storageManager.readGlobalPropertiesFromStorage();
    MapDifference<String, String> propDiff = Maps.difference(filter(storageGlobalProperties.getPropertiesMap()),
            filter(serverGlobalProperties.getPropertiesMap()));
    if (!propDiff.areEqual()) {
        result.appendToChangelog("Global settings updated");
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnLeft().entrySet()) {
            LOG.debug("Property '{}' removed", entry.getKey());
        }//from  w  ww  .jav  a  2 s . c  om
        for (Map.Entry<String, String> entry : propDiff.entriesOnlyOnRight().entrySet()) {
            LOG.debug("Property '{}' added with value '{}'", entry.getKey(),
                    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(),
                    formatLeftDiff(entry.getKey(), entry.getValue().leftValue(), entry.getValue().rightValue()),
                    formatRightDiff(entry.getKey(), entry.getValue().leftValue(),
                            entry.getValue().rightValue()));
        }
    }
}

From source file:org.opendaylight.sxp.controller.listeners.sublisteners.MasterDatabaseListener.java

private void getChanges(DataObjectModification<MasterDatabase> c, List<MasterDatabaseBinding> removed,
        List<MasterDatabaseBinding> added) {
    Map<IpPrefix, MasterDatabaseBinding> before = c.getDataBefore() == null
            || c.getDataBefore().getMasterDatabaseBinding() == null
                    ? new HashMap<>()
                    : c.getDataBefore().getMasterDatabaseBinding().stream().filter(this::isLocalBinding)
                            .collect(Collectors.toMap(SxpBindingFields::getIpPrefix, Function.identity())),
            after = c.getDataAfter() == null || c.getDataAfter().getMasterDatabaseBinding() == null
                    ? new HashMap<>()
                    : c.getDataAfter().getMasterDatabaseBinding().stream().filter(this::isLocalBinding)
                            .collect(Collectors.toMap(SxpBindingFields::getIpPrefix, Function.identity()));
    MapDifference<IpPrefix, MasterDatabaseBinding> databaseDifference = Maps.difference(before, after);
    removed.addAll(databaseDifference.entriesOnlyOnLeft().values());
    added.addAll(databaseDifference.entriesOnlyOnRight().values());

    databaseDifference.entriesDiffering().forEach((p, d) -> {
        removed.add(d.leftValue());//  w  w  w .j a  va  2  s  .  c  o m
        added.add(d.rightValue());
    });
}

From source file:com.thinkbiganalytics.metadata.rest.model.nifi.NiFiFlowCacheSync.java

public Map<String, NiFiFlowCacheConnectionData> getConnectionIdToConnectionUpdatedSinceLastSync(
        Map<String, NiFiFlowCacheConnectionData> connectionDataMap) {
    MapDifference<String, NiFiFlowCacheConnectionData> diff = Maps
            .difference(snapshot.getConnectionIdToConnection(), connectionDataMap);
    return diff.entriesOnlyOnRight();
}