com.google.common.collect.MapDifference.ValueDifference#com.google.common.collect.MapDifference源码实例Demo

下面列出了com.google.common.collect.MapDifference.ValueDifference#com.google.common.collect.MapDifference 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: kylin-on-parquet-v2   文件: Coordinator.java
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;
}
 
@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);
}
 
源代码3 项目: onedev   文件: DefaultMembershipManager.java
@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));		
}
 
源代码4 项目: soundwave   文件: JsonCompareUtilTest.java
@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());
}
 
源代码5 项目: selenium-jupiter   文件: SelenoidConfigTest.java
@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());
}
 
@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();
}
 
@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;
}
 
源代码8 项目: datacollector   文件: CDCJdbcRunnable.java
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;
}
 
源代码9 项目: caffeine   文件: EvictionTest.java
@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);
  });
}
 
源代码10 项目: jpmml-evaluator   文件: Conflict.java
@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();
}
 
源代码11 项目: tutorials   文件: HashMapComparisonUnitTest.java
@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());
}
 
源代码12 项目: tutorials   文件: HashMapComparisonUnitTest.java
@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"));
}
 
源代码13 项目: tutorials   文件: HashMapComparisonUnitTest.java
@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"));
}
 
源代码14 项目: tutorials   文件: HashMapComparisonUnitTest.java
@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());
}
 
源代码15 项目: attic-aurora   文件: JobDiff.java
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()));
}
 
源代码16 项目: denominator   文件: GeoResourceRecordSetCommands.java
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);
  }
}
 
源代码17 项目: qconfig   文件: PropertiesChangedManager.java
synchronized void addPropertiesListener(MapConfig.PropertiesChangeListener listener) {
    Preconditions.checkNotNull(listener);
    if (!config.equals(Collections.EMPTY_MAP)) {
        PropertiesChange change = new PropertiesChange(config, ImmutableMap.<String, String>of(), ImmutableMap.<String, MapDifference.ValueDifference<String>>of(), ImmutableMap.<String, String>of());
        if (change.hasChange()) {
            triggerPropertiesChange(listener, change);
        }
    }
    propertiesChangeListeners.add(listener);
}
 
源代码18 项目: onedev   文件: DefaultSshKeyManager.java
@Transactional
  @Override
  public void syncSshKeys(User user, Collection<String> sshKeys) {
  	Map<String, SshKey> syncMap = new HashMap<>();
  	for (String content: sshKeys) {
  		try {
  			PublicKey pubEntry = SshKeyUtils.decodeSshPublicKey(content);
  	        String digest = KeyUtils.getFingerPrint(SshKey.DIGEST_FORMAT, pubEntry);
  			
  	        SshKey sshKey = new SshKey();
  	        sshKey.setDigest(digest);
  	        sshKey.setContent(content);
  	        sshKey.setOwner(user);
  	        sshKey.setDate(new Date());
  	        syncMap.put(content, sshKey);
  		} catch (IOException | GeneralSecurityException e) {
  			logger.error("Error parsing SSH key", e);
  		}
  	}

  	Map<String, SshKey> currentMap = new HashMap<>();
user.getSshKeys().forEach(sshKey -> currentMap.put(sshKey.getContent(), sshKey));

MapDifference<String, SshKey> diff = Maps.difference(currentMap, syncMap);

diff.entriesOnlyOnLeft().values().forEach(sshKey -> delete(sshKey));

diff.entriesOnlyOnRight().values().forEach(sshKey -> {
	if (findByDigest(sshKey.getDigest()) == null) 
		save(sshKey);	
	else 
		logger.warn("SSH key is already in use (digest: {})", sshKey.getDigest());
});

  }
 
源代码19 项目: airsonic   文件: JWTAuthenticationProvider.java
private static boolean roughlyEqual(String expectedRaw, String requestedPathRaw) {
    LOG.debug("Comparing expected [{}] vs requested [{}]", expectedRaw, requestedPathRaw);
    if (StringUtils.isEmpty(expectedRaw)) {
        LOG.debug("False: empty expected");
        return false;
    }
    try {
        UriComponents expected = UriComponentsBuilder.fromUriString(expectedRaw).build();
        UriComponents requested = UriComponentsBuilder.fromUriString(requestedPathRaw).build();

        if (!Objects.equals(expected.getPath(), requested.getPath())) {
            LOG.debug("False: expected path [{}] does not match requested path [{}]",
                    expected.getPath(), requested.getPath());
            return false;
        }

        MapDifference<String, List<String>> difference = Maps.difference(expected.getQueryParams(),
                requested.getQueryParams());

        if (!difference.entriesDiffering().isEmpty() ||
                !difference.entriesOnlyOnLeft().isEmpty() ||
                difference.entriesOnlyOnRight().size() != 1 ||
                difference.entriesOnlyOnRight().get(JWTSecurityService.JWT_PARAM_NAME) == null) {
            LOG.debug("False: expected query params [{}] do not match requested query params [{}]", expected.getQueryParams(), requested.getQueryParams());
            return false;
        }

    } catch (Exception e) {
        LOG.warn("Exception encountered while comparing paths", e);
        return false;
    }
    return true;
}
 
源代码20 项目: syndesis   文件: AbstractResourceUpdateHandler.java
protected List<LeveledMessage> computePropertiesDiffMessages(
    Supplier<LeveledMessage.Builder> supplier, Map<String, ConfigurationProperty> left, Map<String, ConfigurationProperty> right) {

    final List<LeveledMessage> messages = new ArrayList<>();
    final MapDifference<String, ConfigurationProperty> diff = Maps.difference(left, right);

    for (Map.Entry<String, MapDifference.ValueDifference<ConfigurationProperty>> entry: diff.entriesDiffering().entrySet()) {
        final MapDifference.ValueDifference<ConfigurationProperty> value = entry.getValue();
        final ConfigurationProperty leftValue = value.leftValue();
        final ConfigurationProperty rightValue = value.rightValue();

        // Special handling because of dynamic metadata
        if (!equals(leftValue, rightValue)) {
            messages.add(
                supplier.get()
                    .level(LeveledMessage.Level.INFO)
                    .code(LeveledMessage.Code.SYNDESIS001).build()
            );

            break;
        }
    }

    if (!diff.entriesOnlyOnLeft().isEmpty() || !diff.entriesOnlyOnRight().isEmpty()) {
        messages.add(
            supplier.get()
                .level(LeveledMessage.Level.WARN)
                .code(LeveledMessage.Code.SYNDESIS002).build()
        );
    }

    return messages;
}
 
源代码21 项目: styx   文件: AbstractRegistry.java
protected static <T extends Identifiable> Changes<T> changes(Iterable<T> newResources, Iterable<T> currentResources) {
    Map<Id, T> newIdsToResource = mapById(newResources);
    Map<Id, T> currentIdsToResource = mapById(currentResources);

    MapDifference<Id, T> diff = difference(newIdsToResource, currentIdsToResource);

    Map<Id, MapDifference.ValueDifference<T>> diffs = diff.entriesDiffering();
    return new Changes.Builder<T>()
            .added(diff.entriesOnlyOnLeft().values())
            .removed(diff.entriesOnlyOnRight().values())
            .updated(filterKeys(newIdsToResource, diffs::containsKey).values())
            .build();
}
 
源代码22 项目: Mycat2   文件: CollectionUtil.java
public static void safeUpdateByUpdateOrder(Map t, Map updateInfo) {
    MapDifference difference = Maps.difference(updateInfo, t);
    Map commonMap = difference.entriesInCommon();//求交集,交集为可以持续提供服务的数据源
    t.putAll(commonMap);
    Map entriesOnlyOnLeft = difference.entriesOnlyOnLeft();//两个map,左边有,右边没有的entry,为需要移除的数据源
    for (Object s : entriesOnlyOnLeft.keySet()) {
        t.remove(s);
    }
    t.putAll(updateInfo);
}
 
源代码23 项目: Recaf   文件: RemappingTest.java
private void testSame(MappingImpl toCompare, Path mapping) {
	try {
		// Both of these files outline the same data, just in different formats
		Mappings mappingsSimple = MappingImpl.SIMPLE.create(methodMapFile, workspace);
		Mappings mappingsProguard = toCompare.create(mapping, workspace);
		// So their parsed values should be the same.
		MapDifference<String, String> difference =
				Maps.difference(mappingsSimple.getMappings(), mappingsProguard.getMappings());
		assertTrue(difference.areEqual());
	} catch(IOException ex) {
		fail(ex);
	}
}
 
@Override
public String get() {
  try (Writer w = new StringWriter()) {
    try (BufferedWriter writer = new BufferedWriter(w)) {
      writer.append(String.format("Map for actual.%s() does not match expected.%s().", this.method, this.method));
      writer.newLine();
      Map<?, ? extends MapDifference.ValueDifference<?>> differences = mapDifference.entriesDiffering();
      if (!differences.isEmpty()) {
        writer.append("Keys with Differences");
        writer.newLine();
        for (Map.Entry<?, ? extends MapDifference.ValueDifference<?>> kvp : differences.entrySet()) {
          writer.append("  ");
          writer.append(kvp.getKey().toString());
          writer.newLine();

          writer.append("    expected:");
          writer.append(kvp.getValue().leftValue().toString());
          writer.newLine();

          writer.append("    actual:");
          writer.append(kvp.getValue().rightValue().toString());
          writer.newLine();
        }
      }

      Map<?, ?> entries = mapDifference.entriesOnlyOnLeft();
      writeEntries(writer, "Only in expected map", entries);

      Map<?, ?> onlyInActual = mapDifference.entriesOnlyOnRight();
      writeEntries(writer, "Only in actual map", onlyInActual);
    }
    return w.toString();
  } catch (IOException ex) {
    throw new IllegalStateException(ex);
  }
}
 
static void assertMap(Map<String, ?> expected, Map<String, ?> actual, String message) {
  if (null == expected && null == actual) {
    return;
  }

  String prefix = Strings.isNullOrEmpty(message) ? "" : message + ": ";
  assertNotNull(expected, prefix + "expected cannot be null");
  assertNotNull(actual, prefix + "actual cannot be null");
  MapDifference<String, ?> mapDifference = Maps.difference(expected, actual);
  assertTrue(mapDifference.areEqual(), new MapDifferenceSupplier(mapDifference, prefix));
}
 
源代码26 项目: connect-utils   文件: GenericAssertions.java
@Override
public String get() {
  try (Writer w = new StringWriter()) {
    try (BufferedWriter writer = new BufferedWriter(w)) {
      writer.append(String.format("Map for actual.%s() does not match expected.%s().", this.method, this.method));
      writer.newLine();
      Map<?, ? extends MapDifference.ValueDifference<?>> differences = mapDifference.entriesDiffering();
      if (!differences.isEmpty()) {
        writer.append("Keys with Differences");
        writer.newLine();
        for (Map.Entry<?, ? extends MapDifference.ValueDifference<?>> kvp : differences.entrySet()) {
          writer.append("  ");
          writer.append(kvp.getKey().toString());
          writer.newLine();

          writer.append("    expected:");
          writer.append(kvp.getValue().leftValue().toString());
          writer.newLine();

          writer.append("    actual:");
          writer.append(kvp.getValue().rightValue().toString());
          writer.newLine();
        }
      }

      Map<?, ?> entries = mapDifference.entriesOnlyOnLeft();
      writeEntries(writer, "Only in expected map", entries);

      Map<?, ?> onlyInActual = mapDifference.entriesOnlyOnRight();
      writeEntries(writer, "Only in actual map", onlyInActual);
    }
    return w.toString();
  } catch (IOException ex) {
    throw new IllegalStateException(ex);
  }
}
 
源代码27 项目: connect-utils   文件: GenericAssertions.java
public static void assertMap(Map<String, ?> expected, Map<String, ?> actual, String message) {
  if (null == expected && null == actual) {
    return;
  }

  String prefix = Strings.isNullOrEmpty(message) ? "" : message + ": ";
  assertNotNull(expected, prefix + "expected cannot be null");
  assertNotNull(actual, prefix + "actual cannot be null");
  MapDifference<String, ?> mapDifference = Maps.difference(expected, actual);
  assertTrue(mapDifference.areEqual(), new MapDifferenceSupplier(mapDifference, prefix));
}
 
源代码28 项目: connect-utils   文件: GenericAssertions.java
@Override
public String get() {
  try (Writer w = new StringWriter()) {
    try (BufferedWriter writer = new BufferedWriter(w)) {
      writer.append(String.format("Map for actual.%s() does not match expected.%s().", this.method, this.method));
      writer.newLine();
      Map<?, ? extends MapDifference.ValueDifference<?>> differences = mapDifference.entriesDiffering();
      if (!differences.isEmpty()) {
        writer.append("Keys with Differences");
        writer.newLine();
        for (Map.Entry<?, ? extends MapDifference.ValueDifference<?>> kvp : differences.entrySet()) {
          writer.append("  ");
          writer.append(kvp.getKey().toString());
          writer.newLine();

          writer.append("    expected:");
          writer.append(kvp.getValue().leftValue().toString());
          writer.newLine();

          writer.append("    actual:");
          writer.append(kvp.getValue().rightValue().toString());
          writer.newLine();
        }
      }

      Map<?, ?> entries = mapDifference.entriesOnlyOnLeft();
      writeEntries(writer, "Only in expected map", entries);

      Map<?, ?> onlyInActual = mapDifference.entriesOnlyOnRight();
      writeEntries(writer, "Only in actual map", onlyInActual);
    }
    return w.toString();
  } catch (IOException ex) {
    throw new IllegalStateException(ex);
  }
}
 
源代码29 项目: connect-utils   文件: GenericAssertions.java
public static void assertMap(Map<String, ?> expected, Map<String, ?> actual, String message) {
  if (null == expected && null == actual) {
    return;
  }

  String prefix = Strings.isNullOrEmpty(message) ? "" : message + ": ";
  assertNotNull(expected, prefix + "expected cannot be null");
  assertNotNull(actual, prefix + "actual cannot be null");
  MapDifference<String, ?> mapDifference = Maps.difference(expected, actual);
  assertTrue(mapDifference.areEqual(), new MapDifferenceSupplier(mapDifference, prefix));
}
 
源代码30 项目: metacat   文件: DirectSqlDatabase.java
/**
 * Updates the database object.
 * @param databaseInfo database object
 */
public void update(final DatabaseInfo databaseInfo) {
    log.debug("Start: Database update using direct sql for {}", databaseInfo.getName());
    final long start = registry.clock().wallTime();
    try {
        final Long databaseId = getDatabaseId(databaseInfo.getName());
        final DatabaseInfo existingDatabaseInfo = getDatabaseById(databaseId, databaseInfo.getName());
        final Map<String, String> newMetadata = databaseInfo.getMetadata() == null ? Maps.newHashMap()
            : databaseInfo.getMetadata();
        final MapDifference<String, String> diff = Maps.difference(existingDatabaseInfo.getMetadata(), newMetadata);
        insertDatabaseParams(databaseId, diff.entriesOnlyOnRight());
        final Map<String, String> updateParams = diff.entriesDiffering().entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, s -> s.getValue().rightValue()));
        updateDatabaseParams(databaseId, updateParams);
        final String uri =
            Strings.isNullOrEmpty(databaseInfo.getUri()) ? existingDatabaseInfo.getUri() : databaseInfo.getUri();
        final String newOwner = getOwner(databaseInfo.getAudit());
        final String owner =
            Strings.isNullOrEmpty(newOwner) ? newOwner : existingDatabaseInfo.getAudit().getCreatedBy();
        jdbcTemplate.update(SQL.UPDATE_DATABASE, new SqlParameterValue(Types.VARCHAR, uri),
            new SqlParameterValue(Types.VARCHAR, owner),
            new SqlParameterValue(Types.BIGINT, databaseId));
    } finally {
        this.fastServiceMetric.recordTimer(
            HiveMetrics.TagAlterDatabase.getMetricName(), registry.clock().wallTime() - start);
        log.debug("End: Database update using direct sql for {}", databaseInfo.getName());
    }
}