com.google.common.collect.MapDifference Java Examples

The following examples show how to use com.google.common.collect.MapDifference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HashMapComparisonUnitTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() {
    Map<String, String> asia1 = new HashMap<String, String>();
    asia1.put("Japan", "Tokyo");
    asia1.put("South Korea", "Seoul");
    asia1.put("India", "New Delhi");

    Map<String, String> asia2 = new HashMap<String, String>();
    asia2.put("Japan", "Tokyo");
    asia2.put("China", "Beijing");
    asia2.put("India", "Delhi");

    MapDifference<String, String> diff = Maps.difference(asia1, asia2);
    Map<String, ValueDifference<String>> entriesDiffering = diff.entriesDiffering();
    
    assertFalse(diff.areEqual());
    assertEquals(1, entriesDiffering.size());
    assertThat(entriesDiffering, hasKey("India"));
    assertEquals("New Delhi", entriesDiffering.get("India").leftValue());
    assertEquals("Delhi", entriesDiffering.get("India").rightValue());
}
 
Example #2
Source File: MapDifferenceSupplier.java    From kafka-connect-solr with Apache License 2.0 6 votes vote down vote up
@Override
public String get() {
  StringBuilder builder = new StringBuilder();
  if (!difference.entriesDiffering().isEmpty()) {
    builder.append("Differing:\n");
    for (Map.Entry<String, MapDifference.ValueDifference<SolrInputField>> diff : difference.entriesDiffering().entrySet()) {
      builder.append("  ");
      builder.append(diff.getKey());
      builder.append('\n');
      builder.append("  left  : ");
      builder.append(diff.getValue().leftValue());
      builder.append('\n');
      builder.append("  right : ");
      builder.append(diff.getValue().rightValue());
      builder.append('\n');
    }
  }

  return builder.toString();
}
 
Example #3
Source File: DefaultMembershipManager.java    From onedev with MIT License 6 votes vote down vote up
@Override
public void syncMemberships(User user, Collection<String> groupNames) {
   	Map<String, Membership> syncMap = new HashMap<>();
   	for (String groupName: groupNames) {
   		Group group = groupManager.find(groupName);
   		if (group == null) {
   			logger.warn("Unable to find group: " + groupName);
   		} else {
   			Membership membership = new Membership();
   			membership.setGroup(group);
   			membership.setUser(user);
   			syncMap.put(groupName, membership);
   		}
   	}

   	Map<String, Membership> currentMap = new HashMap<>();
	user.getMemberships().forEach(membership -> 
			currentMap.put(membership.getGroup().getName(), membership));
	
	MapDifference<String, Membership> diff = Maps.difference(currentMap, syncMap);
	
	diff.entriesOnlyOnLeft().values().forEach(membership -> delete(membership));
	diff.entriesOnlyOnRight().values().forEach(membership -> save(membership));		
}
 
Example #4
Source File: HashMapComparisonUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() {
    Equivalence<String[]> eq = new Equivalence<String[]>() {
        @Override
        protected boolean doEquivalent(String[] a, String[] b) {
            return Arrays.equals(a, b);
        }

        @Override
        protected int doHash(String[] value) {
            return value.hashCode();
        }
    };

    MapDifference<String, String[]> diff = Maps.difference(asiaCity1, asiaCity2, eq);
    assertTrue(diff.areEqual());
    
    diff = Maps.difference(asiaCity1, asiaCity3, eq);
    assertFalse(diff.areEqual());
}
 
Example #5
Source File: ReceiverClusterManager.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@NotAtomicAndNotIdempotent
void reassignCubeImpl(String cubeName, CubeAssignment preAssignments, CubeAssignment newAssignments) {
    logger.info("start cube reBalance, cube:{}, previous assignments:{}, new assignments:{}", cubeName,
            preAssignments, newAssignments);
    if (newAssignments.equals(preAssignments)) {
        logger.info("the new assignment is the same as the previous assignment, do nothing for this reassignment");
        return;
    }
    CubeInstance cubeInstance = getCoordinator().getCubeManager().getCube(cubeName);
    doReassignWithoutCommit(cubeInstance, preAssignments, newAssignments);

    // add empty partitions to the removed replica sets, means that there's still data in the replica set, but no new data will be consumed.
    MapDifference<Integer, List<Partition>> assignDiff = Maps.difference(preAssignments.getAssignments(),
            newAssignments.getAssignments());
    Map<Integer, List<Partition>> removedAssign = assignDiff.entriesOnlyOnLeft();
    for (Integer removedReplicaSet : removedAssign.keySet()) {
        newAssignments.addAssignment(removedReplicaSet, Lists.<Partition> newArrayList());
    }

    logger.info("Commit reassign {} transaction.", cubeName);
    getCoordinator().getStreamMetadataStore().saveNewCubeAssignment(newAssignments);
    AssignmentsCache.getInstance().clearCubeCache(cubeName);
}
 
Example #6
Source File: Coordinator.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private CubeAssignment reassignCubeImpl(String cubeName, CubeAssignment preAssignments,
        CubeAssignment newAssignments) {
    logger.info("start cube reBalance, cube:{}, previous assignments:{}, new assignments:{}", cubeName,
            preAssignments, newAssignments);
    if (newAssignments.equals(preAssignments)) {
        logger.info("the new assignment is the same as the previous assignment, do nothing for this reassignment");
        return newAssignments;
    }
    CubeInstance cubeInstance = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()).getCube(cubeName);
    doReassign(cubeInstance, preAssignments, newAssignments);
    MapDifference<Integer, List<Partition>> assignDiff = Maps.difference(preAssignments.getAssignments(),
            newAssignments.getAssignments());

    // add empty partitions to the removed replica sets, means that there's still data in the replica set, but no new data will be consumed.
    Map<Integer, List<Partition>> removedAssign = assignDiff.entriesOnlyOnLeft();
    for (Integer removedReplicaSet : removedAssign.keySet()) {
        newAssignments.addAssignment(removedReplicaSet, Lists.<Partition> newArrayList());
    }
    streamMetadataStore.saveNewCubeAssignment(newAssignments);
    AssignmentsCache.getInstance().clearCubeCache(cubeName);
    return newAssignments;
}
 
Example #7
Source File: GeoResourceRecordSetCommands.java    From denominator with Apache License 2.0 6 votes vote down vote up
static void validateRegions(Map<String, Collection<String>> regionsToAdd,
                            Map<String, Collection<String>> supportedRegions) {
  MapDifference<String, Collection<String>>
      comparison =
      Maps.difference(regionsToAdd, supportedRegions);
  checkArgument(comparison.entriesOnlyOnLeft().isEmpty(), "unsupported regions: %s", comparison
      .entriesOnlyOnLeft().keySet());
  for (Entry<String, Collection<String>> entry : regionsToAdd.entrySet()) {
    ImmutableSet<String> toAdd = ImmutableSet.copyOf(entry.getValue());
    SetView<String> intersection = Sets.intersection(toAdd,
                                                     ImmutableSet.copyOf(
                                                         supportedRegions.get(entry.getKey())));
    SetView<String> unsupported = Sets.difference(toAdd, intersection);
    checkArgument(unsupported.isEmpty(), "unsupported territories in %s:", entry.getKey(),
                  unsupported);
  }
}
 
Example #8
Source File: JobDiff.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
private static JobDiff computeUnscoped(
    Map<Integer, ITaskConfig> currentState,
    IJobKey job,
    Map<Integer, ITaskConfig> proposedState) {

  requireNonNull(job);
  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()));
}
 
Example #9
Source File: HashMapComparisonUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() {
    Map<String, String> asia1 = new HashMap<String, String>();
    asia1.put("Japan", "Tokyo");
    asia1.put("South Korea", "Seoul");
    asia1.put("India", "New Delhi");

    Map<String, String> asia2 = new HashMap<String, String>();
    asia2.put("Japan", "Tokyo");
    asia2.put("China", "Beijing");
    asia2.put("India", "Delhi");

    MapDifference<String, String> diff = Maps.difference(asia1, asia2);
    Map<String, String> entriesInCommon = diff.entriesInCommon();

    assertEquals(1, entriesInCommon.size());
    assertThat(entriesInCommon, hasEntry("Japan", "Tokyo"));
}
 
Example #10
Source File: Conflict.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String toString(){
	ToStringHelper helper = new ToStringHelper(this)
		.add("id", getId())
		.add("arguments", getArguments());

	MapDifference<FieldName, ?> difference = getDifference();
	if(difference != null){
		helper.add("difference", getDifference());
	}

	Exception exception = getException();
	if(exception != null){
		helper.add("exception", exception);
	}

	return helper.toString();
}
 
Example #11
Source File: SelenoidConfigTest.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
void testBrowserConfig() throws IOException {
    String browsersJsonFromProperties = selenoidConfig
            .getBrowsersJsonAsString();

    String expectedBrowsersJson = IOUtils.toString(
            this.getClass().getResourceAsStream("/browsers-test.json"),
            defaultCharset());

    Gson gson = new Gson();
    Type mapType = new TypeToken<Map<String, Object>>() {
    }.getType();
    Map<String, Object> browserMap = gson
            .fromJson(browsersJsonFromProperties, mapType);
    Map<String, Object> expectedBrowserMap = gson
            .fromJson(expectedBrowsersJson, mapType);
    MapDifference<String, Object> difference = difference(browserMap,
            expectedBrowserMap);
    log.debug("{}", difference);
    assertTrue(difference.areEqual());
}
 
Example #12
Source File: EvictionTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, population = Population.FULL,
    maximumSize = { Maximum.ZERO, Maximum.ONE, Maximum.FULL },
    weigher = {CacheWeigher.DEFAULT, CacheWeigher.TEN})
public void evict(Cache<Integer, Integer> cache, CacheContext context,
    Eviction<Integer, Integer> eviction) {
  cache.putAll(context.absent());
  if (eviction.isWeighted()) {
    assertThat(eviction.weightedSize().getAsLong(), is(context.maximumWeight()));
  } else {
    assertThat(cache.estimatedSize(), is(context.maximumSize()));
  }
  int count = context.absentKeys().size();
  assertThat(context, hasEvictionCount(count));
  assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.SIZE));

  verifyWriter(context, (verifier, writer) -> {
    Map<Integer, Integer> all = new HashMap<>(context.original());
    all.putAll(context.absent());
    MapDifference<Integer, Integer> diff = Maps.difference(all, cache.asMap());
    verifier.deletedAll(diff.entriesOnlyOnLeft(), RemovalCause.SIZE);
  });
}
 
Example #13
Source File: CDCJdbcRunnable.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private boolean getDiff(String captureInstanceName, Map<String, Integer> sourceTableColumnInfo, Map<String, Integer> cdcTableColumnInfo) {
  MapDifference<String, Integer> diff = Maps.difference(sourceTableColumnInfo, cdcTableColumnInfo);

  if (!diff.areEqual()) {
    if (LOG.isTraceEnabled()) {
      LOG.trace(
          "Detected drift for table {} - new columns: {}, drop columns: {}",
          captureInstanceName,
          StringUtils.join(diff.entriesOnlyOnLeft().keySet(), ","),
          StringUtils.join(diff.entriesOnlyOnRight().keySet(), ",")
      );
    }
    return true;
  }

  return false;
}
 
Example #14
Source File: HashMapComparisonUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() {
    Map<String, String> asia1 = new HashMap<String, String>();
    asia1.put("Japan", "Tokyo");
    asia1.put("South Korea", "Seoul");
    asia1.put("India", "New Delhi");

    Map<String, String> asia2 = new HashMap<String, String>();
    asia2.put("Japan", "Tokyo");
    asia2.put("China", "Beijing");
    asia2.put("India", "Delhi");

    MapDifference<String, String> diff = Maps.difference(asia1, asia2);
    Map<String, String> entriesOnlyOnRight = diff.entriesOnlyOnRight();
    Map<String, String> entriesOnlyOnLeft = diff.entriesOnlyOnLeft();

    assertEquals(1, entriesOnlyOnRight.size());
    assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing"));
    assertEquals(1, entriesOnlyOnLeft.size());
    assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul"));
}
 
Example #15
Source File: SolrInputFieldEquivalence.java    From kafka-connect-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean doEquivalent(SolrInputField o1, SolrInputField o2) {
  if (o1.getValue() instanceof SolrInputDocument) {
    if (!(o2.getValue() instanceof SolrInputDocument)) {
      return false;
    }
    final MapDifference<String, SolrInputField> difference = Maps.difference(
        (SolrInputDocument) o1.getValue(),
        (SolrInputDocument) o2.getValue(),
        this
    );
    if (!difference.areEqual()) {
      return false;
    }
  } else {
    if (o1.getValue() != o2.getValue()) {
      return false;
    }
  }
  return true;
}
 
Example #16
Source File: JsonCompareUtilTest.java    From soundwave with Apache License 2.0 6 votes vote down vote up
@Test
public void TestDiff() {
  HashMap<String, Object> map1 = new HashMap<>();
  HashMap<String, Object> map2 = new HashMap<>();
  map1.put("bbbb", "cccc");
  map1.put("xxx", "aaa");
  map2.put("xxx", "aa");
  map2.put("cccc", "bbbb");
  map1.put("dict", ImmutableMap.builder().put("a", 1).put("b", 2)
      .put("em", ImmutableMap.builder().put("c", 3).build()).build());
  map2.put("dict", ImmutableMap.builder().put("a", 1).put("b", 3)
      .put("em", ImmutableMap.builder().put("c", 4).put("d", 5).build()).build());
  MapDifference diff = Maps.difference(map1, map2);
  Map diffMap = new HashMap();
  JsonCompareUtil.getDetailsDiff(map1, map2, diffMap, "");
  Assert.assertTrue(diffMap.containsKey("bbbb"));
  Assert.assertTrue(diffMap.containsKey("xxx"));
  Assert.assertTrue(diffMap.containsKey("cccc"));
  Assert.assertTrue(diffMap.containsKey("dict.b"));
  Assert.assertTrue(diffMap.containsKey("dict.em.c"));
  Assert.assertTrue(diffMap.containsKey("dict.em.d"));
  Assert.assertEquals(6, diffMap.size());
}
 
Example #17
Source File: GrokParserTest.java    From metron with Apache License 2.0 5 votes vote down vote up
public boolean compare(JSONObject expected, JSONObject actual) {
  MapDifference mapDifferences = Maps.difference(expected, actual);
  if (mapDifferences.entriesOnlyOnLeft().size() > 0) {
    fail("Expected JSON has extra parameters: " + mapDifferences.entriesOnlyOnLeft());
  }
  if (mapDifferences.entriesOnlyOnRight().size() > 0) {
    fail("Actual JSON has extra parameters: " + mapDifferences.entriesOnlyOnRight());
  }
  Map actualDifferences = new HashMap();
  if (mapDifferences.entriesDiffering().size() > 0) {
    Map differences = Collections.unmodifiableMap(mapDifferences.entriesDiffering());
    for (Object key : differences.keySet()) {
      Object expectedValueObject = expected.get(key);
      Object actualValueObject = actual.get(key);
      if (expectedValueObject instanceof Long || expectedValueObject instanceof Integer) {
        Long expectedValue = Long.parseLong(expectedValueObject.toString());
        Long actualValue = Long.parseLong(actualValueObject.toString());
        if (!expectedValue.equals(actualValue)) {
          actualDifferences.put(key, differences.get(key));
        }
      } else {
        actualDifferences.put(key, differences.get(key));
      }
    }
  }
  if (actualDifferences.size() > 0) {
    fail("Expected and Actual JSON values don't match: " + actualDifferences);
  }
  return true;
}
 
Example #18
Source File: MapDifferenceExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void entries_only_on_right() {

	MapDifference<Integer, Student> mapDifference = Maps.difference(
			geometryClass, gymClass);

	Map<Integer, Student> studentsOnTheRight = mapDifference
			.entriesOnlyOnRight();

	logger.info(studentsOnTheRight);

	assertThat(studentsOnTheRight, hasKey(new Integer(478)));
	assertThat(studentsOnTheRight, hasKey(new Integer(937)));
}
 
Example #19
Source File: DaemonicCellState.java    From buck with Apache License 2.0 5 votes vote down vote up
Optional<MapDifference<String, String>> invalidateIfEnvHasChanged(Cell cell, AbsPath buildFile) {
  // Invalidate if env vars have changed.
  ImmutableMap<String, Optional<String>> usedEnv;
  try (AutoCloseableLock readLock = cachesLock.readLock()) {
    usedEnv = buildFileEnv.get(buildFile);
  }
  if (usedEnv == null) {
    this.cell.set(cell);
    return Optional.empty();
  }
  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())) {
      LOG.verbose("invalidating for env change: %s (%s != %s)", buildFile, value, ent.getValue());
      invalidatePath(buildFile);
      this.cell.set(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();
}
 
Example #20
Source File: GoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
static <K, V> void assertMapsEqual(
    Map<K, V> expected, Map<K, V> result, Equivalence<V> valueEquivalence) {
  MapDifference<K, V> diff = Maps.difference(expected, result, valueEquivalence);
  if (!diff.areEqual()) {
    fail(
        String.format(
            "Maps differ. Entries differing: %s%nMissing entries: %s%nExtra entries: %s%n",
            diff.entriesDiffering(), diff.entriesOnlyOnLeft(), diff.entriesOnlyOnRight()));
  }
}
 
Example #21
Source File: MapDifferenceExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void entries_only_on_left() {

	MapDifference<Integer, Student> mapDifference = Maps.difference(
			geometryClass, gymClass);

	Map<Integer, Student> studentsOnLeft = mapDifference
			.entriesOnlyOnLeft();

	logger.info(studentsOnLeft);

	assertThat(studentsOnLeft, hasKey(new Integer(456)));
	assertThat(studentsOnLeft, hasKey(new Integer(912)));
}
 
Example #22
Source File: OptionsConfigurationBlock.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public Map<String, ValueDifference<String>> getPreferenceChanges() {
	Map<String, String> currentSettings = Maps.newHashMapWithExpectedSize(keys.length);
	for (String key : keys) {
		currentSettings.put(key, preferenceStore.getString(key));
	}
	MapDifference<String, String> mapDifference = Maps.difference(currentSettings, originalSettings);
	Map<String, ValueDifference<String>> entriesDiffering = mapDifference.entriesDiffering();
	return entriesDiffering;
}
 
Example #23
Source File: ConfigureNameIdAction.java    From oxTrust with MIT License 5 votes vote down vote up
public Map<String, String> getAvailableNamedIds(NameIdConfig config) {
	MapDifference<String, String> diff = Maps.difference(availableNamedIds, usedNamedIds);
	Map<String, String> value = diff.entriesOnlyOnLeft();
	Map<String, String> result = Maps.newHashMap(value);
	if (config.getNameIdType() != null) {
		result.put(config.getNameIdType(), config.getNameIdType());
	}
	return result;
}
 
Example #24
Source File: ClaimsListShard.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static final void loadAndCompareCloudSqlList(ClaimsListShard datastoreList) {
  Optional<ClaimsList> maybeCloudSqlList = ClaimsListDao.getLatestRevision();
  if (maybeCloudSqlList.isPresent()) {
    ClaimsList cloudSqlList = maybeCloudSqlList.get();
    MapDifference<String, String> diff =
        Maps.difference(datastoreList.labelsToKeys, cloudSqlList.getLabelsToKeys());
    if (!diff.areEqual()) {
      if (diff.entriesDiffering().size() > 10) {
        logger.atWarning().log(
            String.format(
                "Unequal claims lists detected, Cloud SQL list with revision id %d has %d"
                    + " different records than the current Datastore list.",
                cloudSqlList.getRevisionId(), diff.entriesDiffering().size()));
      } else {
        StringBuilder diffMessage = new StringBuilder("Unequal claims lists detected:\n");
        diff.entriesDiffering().entrySet().stream()
            .forEach(
                entry -> {
                  String label = entry.getKey();
                  ValueDifference<String> valueDiff = entry.getValue();
                  diffMessage.append(
                      String.format(
                          "Domain label %s has key %s in Datastore and key %s in Cloud"
                              + " SQL.\n",
                          label, valueDiff.leftValue(), valueDiff.rightValue()));
                });
        logger.atWarning().log(diffMessage.toString());
      }
    }
  } else {
    logger.atWarning().log("Claims list in Cloud SQL is empty.");
  }
}
 
Example #25
Source File: DummyRevision.java    From copybara with Apache License 2.0 5 votes vote down vote up
private Set<String> computeChangedFiles() {
  Map<String, String> pathToContent = readAllFiles(changesBase);
  Map<String, String> previousContent = previousPath == null
      ? ImmutableMap.of()
      : readAllFiles(previousPath);

  MapDifference<String, String> diff = Maps.difference(pathToContent, previousContent);

  return ImmutableSet.<String>builder()
      .addAll(diff.entriesOnlyOnLeft().keySet())
      .addAll(diff.entriesOnlyOnRight().keySet())
      .addAll(diff.entriesDiffering().keySet())
      .build();
}
 
Example #26
Source File: FetchResult.java    From copybara with Apache License 2.0 5 votes vote down vote up
FetchResult(ImmutableMap<String, GitRevision> before,
    ImmutableMap<String, GitRevision> after) {
  MapDifference<String, GitRevision> diff = Maps.difference(before, after);
  deleted = ImmutableMap.copyOf(diff.entriesOnlyOnLeft());
  inserted = ImmutableMap.copyOf(diff.entriesOnlyOnRight());
  updated = ImmutableMap.copyOf(diff.entriesDiffering().entrySet().stream()
      .collect(Collectors.toMap(
          Map.Entry::getKey,
          v -> new RefUpdate(v.getValue().leftValue(), v.getValue().rightValue()))));
}
 
Example #27
Source File: BaseQueueServiceTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Because of an Ostrich bug the BaseQueueService methods have been copied to DedupQueueService.java.
 * Verify that this copy has been done correctly and the 3 interfaces are identical.
 */
@Test
public void testDedupQueueApisMatch() {
    MapDifference<List<Object>, Method> diff = Maps.difference(
            getDeclaredPublicMethodMap(BaseQueueService.class),
            getDeclaredPublicMethodMap(DedupQueueService.class));

    assertTrue(diff.entriesOnlyOnLeft().isEmpty(), "In BaseQueueService but not in DedupQueueService: " + diff.entriesOnlyOnLeft().values());
    assertTrue(diff.entriesOnlyOnRight().isEmpty(), "In DedupQueueService but not in BaseQueueService: " + diff.entriesOnlyOnRight().values());
}
 
Example #28
Source File: BaseQueueServiceTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * Because of an Ostrich bug the BaseQueueService methods have been copied to QueueService.java.
 * Verify that this copy has been done correctly and the 3 interfaces are identical.
 */
@Test
public void testQueueApisMatch() {
    MapDifference<List<Object>, Method> diff = Maps.difference(
            getDeclaredPublicMethodMap(BaseQueueService.class),
            getDeclaredPublicMethodMap(QueueService.class));

    assertTrue(diff.entriesOnlyOnLeft().isEmpty(), "In BaseQueueService but not in QueueService: " + diff.entriesOnlyOnLeft().values());
    assertTrue(diff.entriesOnlyOnRight().isEmpty(), "In QueueService but not in BaseQueueService: " + diff.entriesOnlyOnRight().values());
}
 
Example #29
Source File: DaemonicParserState.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean invalidateIfBuckConfigOrEnvHasChanged(
    Cell cell, AbsPath buildFile, BuckEventBus eventBus) {
  try (AutoCloseableLock readLock = cellStateLock.readLock()) {
    DaemonicCellState state = cellPathToDaemonicState.get(cell.getRoot());
    if (state == null) {
      return false;
    }

    // Keep track of any invalidations.
    boolean hasInvalidated = false;

    // Currently, if `.buckconfig` settings change, we restart the entire daemon, meaning checking
    // for `.buckconfig`-based invalidations is redundant. (see
    // {@link com.facebook.buck.cli.DaemonLifecycleManager#getDaemon} for where we restart the
    // daemon and {@link com.facebook.buck.config.BuckConfig's static initializer for the
    // whitelist of fields.

    // Invalidate based on env vars.
    Optional<MapDifference<String, String>> envDiff =
        state.invalidateIfEnvHasChanged(cell, buildFile);
    if (envDiff.isPresent()) {
      hasInvalidated = true;
      MapDifference<String, String> diff = envDiff.get();
      LOG.info("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);
      eventBus.post(ParsingEvent.environmentalChange(environmentChanges.toString()));
    }

    return hasInvalidated;
  }
}
 
Example #30
Source File: RemoteConnectionInstanceWorkflow.java    From ecs-cf-service-broker with Apache License 2.0 5 votes vote down vote up
private void validateSettings(ServiceInstance remoteInstance, ServiceDefinitionProxy serviceDef, PlanProxy plan,
                              Map<String, Object> parameters) {
    Map<String, Object> settings = new HashMap<>();
    settings.putAll(parameters);
    settings.putAll(plan.getServiceSettings());
    settings.putAll(serviceDef.getServiceSettings());

    Map<String, MapDifference.ValueDifference<Object>> settingsDiff =
            Maps.difference(settings, remoteInstance.getServiceSettings()).entriesDiffering();
    if (! settingsDiff.isEmpty())
        throw new ServiceBrokerException("service definition must match between local and remote instances");

}