下面列出了怎么用com.google.common.collect.ImmutableListMultimap的API类实例代码及写法,或者点击链接到github查看源代码。
@Override public ImmutableList<String> determinePropertyOrder() throws IOException {
Reader sourceReader;
try {
sourceReader = readerProvider.call();
} catch (Exception e) {
return ImmutableList.of();
}
try {
String packageName = TypeSimplifier.packageNameOf(type);
String className = type.getQualifiedName().toString();
AbstractMethodExtractor extractor = new AbstractMethodExtractor();
JavaTokenizer tokenizer = new JavaTokenizer(sourceReader);
ImmutableListMultimap<String, String> methodOrders =
extractor.abstractMethods(tokenizer, packageName);
return methodOrders.get(className);
} finally {
sourceReader.close();
}
}
@Override
public void visitChangesWithAnyLabel(Revision start, ImmutableCollection<String> labels,
ChangesLabelVisitor visitor) throws RepoException, ValidationException {
for (ProcessedChange processedChange : Lists.reverse(processed)) {
VisitResult result =
visitor.visit(
new Change<>(
processedChange.getOriginRef(),
processedChange.getAuthor(),
processedChange.getChangesSummary(),
processedChange.getTimestamp(),
ImmutableListMultimap.of()),
ImmutableMap.copyOf(labels
.stream()
.collect(Collectors.toMap(
Function.identity(), e -> processedChange.getOriginRef().asString()))));
if (result == VisitResult.TERMINATE) {
return;
}
}
}
@Test
public void writeHeadersShouldSendHeaders() throws Exception {
Metadata headers = new Metadata();
ListMultimap<CharSequence, CharSequence> expectedHeaders =
ImmutableListMultimap.copyOf(Utils.convertServerHeaders(headers));
stream().writeHeaders(headers);
ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap =
ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true));
SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue();
assertThat(sendHeaders.stream()).isSameAs(stream.transportState());
assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
.containsExactlyEntriesIn(expectedHeaders);
assertThat(sendHeaders.endOfStream()).isFalse();
}
private void process(Writer<GitRevision> writer, DummyRevision ref)
throws ValidationException, RepoException, IOException {
TransformResult result = TransformResults.of(workdir, ref);
Changes changes = new Changes(
ImmutableList.of(
new Change<>(ref, new Author("foo", "[email protected]"), "message",
ZonedDateTime.now(ZoneOffset.UTC), ImmutableListMultimap.of("my_label", "12345")),
new Change<>(ref, new Author("foo", "[email protected]"), "message",
ZonedDateTime.now(ZoneOffset.UTC), ImmutableListMultimap.of("my_label", "6789"))),
ImmutableList.of());
result = result.withChanges(changes);
ImmutableList<DestinationEffect> destinationResult =
writer.write(result, destinationFiles, console);
assertThat(destinationResult).hasSize(1);
assertThat(destinationResult.get(0).getErrors()).isEmpty();
assertThat(destinationResult.get(0).getType()).isEqualTo(Type.CREATED);
assertThat(destinationResult.get(0).getDestinationRef().getType()).isEqualTo("commit");
assertThat(destinationResult.get(0).getDestinationRef().getId()).matches("[0-9a-f]{40}");
}
@Test
public void testResourceOffers_canHandleOffersWithMixedRoles() throws InvalidProtocolBufferException {
cleanState("someOtherRole");
Protos.Offer offer = createOffer(slaves[0]);
scheduler.resourceOffers(driver, newArrayList(offer));
Collection<Protos.TaskInfo> launchedTasks = driver.launchTasks()._2;
assertThat(launchedTasks).isNotEmpty();
Protos.TaskInfo launchedTask = launchedTasks.iterator().next();
List<Protos.Resource> resources = launchedTask.getResourcesList();
ImmutableListMultimap<String, Protos.Resource> resourceMap = FluentIterable.from(resources)
.index(resourceByName());
Protos.Resource cpus = resourceMap.get("cpus").get(0);
assertThat(cpus.getRole()).isEqualTo("*");
assertThat(cpus.getScalar().getValue()).isEqualTo(0.1);
Protos.Resource mem = resourceMap.get("mem").get(0);
assertThat(mem.getRole()).isEqualTo("*");
assertThat(mem.getScalar().getValue()).isEqualTo(32.0);
}
private void addLabelOutput(
Attribute attribute,
Label label,
EventHandler eventHandler,
ImmutableList.Builder<OutputFile> outputFilesBuilder,
ImmutableListMultimap.Builder<String, OutputFile> outputFileMapBuilder,
boolean performChecks)
throws LabelSyntaxException {
if (performChecks) {
if (!label.getPackageIdentifier().equals(pkg.getPackageIdentifier())) {
throw new IllegalStateException("Label for attribute " + attribute
+ " should refer to '" + pkg.getName()
+ "' but instead refers to '" + label.getPackageFragment()
+ "' (label '" + label.getName() + "')");
}
if (label.getName().equals(".")) {
throw new LabelSyntaxException("output file name can't be equal '.'");
}
}
OutputFile outputFile = addOutputFile(label, eventHandler, outputFilesBuilder);
outputFileMapBuilder.put(attribute.getName(), outputFile);
}
private HttpRequestFactory getHttpRequestFactory(
@Nullable UserPassword userPassword, ImmutableListMultimap<String, String> headers) {
return httpTransport.createRequestFactory(
request -> {
request.setConnectTimeout((int) Duration.ofMinutes(1).toMillis());
request.setReadTimeout((int) Duration.ofMinutes(1).toMillis());
HttpHeaders httpHeaders = new HttpHeaders();
if (userPassword != null) {
httpHeaders.setBasicAuthentication(userPassword.getUsername(),
userPassword.getPassword_BeCareful());
}
for (Map.Entry<String, Collection<String>> header : headers.asMap().entrySet()) {
httpHeaders.put(header.getKey(), header.getValue());
}
request.setHeaders(httpHeaders);
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
}
@Test
public void testFormatDependencyPaths_threePathsForA() {
ImmutableListMultimap<ClassPathEntry, DependencyPath> tree =
ImmutableListMultimap.of(
jarA, dependencyPath_A, jarA, dependencyPath_B_A, jarA, dependencyPath_A_B_A);
ClassPathResult classPathResult = new ClassPathResult(tree, ImmutableSet.of());
String actual = classPathResult.formatDependencyPaths(ImmutableList.of(jarA));
assertEquals(
"com.google:a:1 is at:\n"
+ " com.google:a:1 (compile)\n"
+ " and 2 other dependency paths.\n",
actual);
}
/**
* Resolve a reference
*
* @throws CannotResolveRevisionException if it cannot resolve the reference
*/
GitRevision resolveReferenceWithContext(String reference, @Nullable String contextRef,
String url)
throws RepoException, CannotResolveRevisionException {
// Nothing needs to be resolved, since it is a complete SHA-1. But we
// check that the reference exists.
if (GitRevision.COMPLETE_SHA1_PATTERN.matcher(reference).matches()) {
if (checkSha1Exists(reference)) {
return new GitRevision(this, reference);
}
throw new CannotResolveRevisionException(
"Cannot find '" + reference + "' object in the repository");
}
return new GitRevision(this, parseRef(reference), /*reviewReference=*/null, contextRef,
ImmutableListMultimap.of(), url);
}
private boolean hashesMatch(
FileHashLoader fileHashLoader,
SourcePathResolverAdapter resolver,
ImmutableListMultimap<String, SourcePath> universe,
int[] hashIndices)
throws IOException {
for (int hashIndex : hashIndices) {
Pair<Integer, HashCode> hashEntry = hashes.get(hashIndex);
String input = inputs.get(hashEntry.getFirst());
ImmutableList<SourcePath> candidates = universe.get(input);
if (candidates.isEmpty()) {
return false;
}
HashCode onDiskHeaderHash;
try {
onDiskHeaderHash = hashSourcePathGroup(fileHashLoader, resolver, candidates);
} catch (NoSuchFileException e) {
return false;
}
HashCode inputHash = hashEntry.getSecond();
if (!inputHash.equals(onDiskHeaderHash)) {
return false;
}
}
return true;
}
private Multimap<String, String> params(String query) {
final ImmutableListMultimap.Builder<String, String> queryParams = ImmutableListMultimap.builder();
if (! Strings.isNullOrEmpty(query)) {
for (String pair : SPLITTER.split(query)) {
final int index = pair.indexOf('=');
if (index > 0) {
final String key = pair.substring(0, index);
final String value = pair.substring(index + 1);
queryParams.put(key, value);
} else {
queryParams.put(pair, "");
}
}
}
return queryParams.build();
}
@Override public ImmutableList<String> determinePropertyOrder() throws IOException {
Reader sourceReader;
try {
sourceReader = readerProvider.call();
} catch (Exception e) {
return ImmutableList.of();
}
try {
String packageName = TypeSimplifier.packageNameOf(type);
String className = type.getQualifiedName().toString();
AbstractMethodExtractor extractor = new AbstractMethodExtractor();
JavaTokenizer tokenizer = new JavaTokenizer(sourceReader);
ImmutableListMultimap<String, String> methodOrders =
extractor.abstractMethods(tokenizer, packageName);
return methodOrders.get(className);
} finally {
sourceReader.close();
}
}
@Test
public void testNotFlattening()
{
tester().assertThat(new MergeIntersect())
.on(p -> {
Symbol a = p.symbol("a");
Symbol b = p.symbol("b");
Symbol c = p.symbol("c");
return p.intersect(
ImmutableListMultimap.<Symbol, Symbol>builder()
.put(c, a)
.put(c, b)
.build(),
ImmutableList.of(p.values(1, a), p.values(1, b)));
})
.doesNotFire();
}
public ClassPathResult(
ListMultimap<ClassPathEntry, DependencyPath> dependencyPaths,
Iterable<UnresolvableArtifactProblem> artifactProblems) {
this.dependencyPaths = ImmutableListMultimap.copyOf(dependencyPaths);
this.classPath = ImmutableList.copyOf(dependencyPaths.keySet());
this.artifactProblems = ImmutableList.copyOf(artifactProblems);
}
ProtoRegistry build() {
ImmutableListMultimap<String, TypeModification> modificationsMap =
ImmutableListMultimap.copyOf(
this.typeModifications.stream()
.map(
modification ->
new SimpleImmutableEntry<>(modification.getTypeName(), modification))
.collect(Collectors.toList()));
final BiMap<String, GraphQLType> mapping = HashBiMap.create();
GraphQLInterfaceType nodeInterface =
new Relay()
.nodeInterface(
env -> {
Relay.ResolvedGlobalId resolvedGlobalId =
new Relay().fromGlobalId(env.getArguments().get("id").toString());
return (GraphQLObjectType) mapping.get(resolvedGlobalId.getType());
});
mapping.putAll(
modifyTypes(
getMap(fileDescriptors, descriptors, enumDescriptors, nodeInterface, schemaOptions),
modificationsMap));
return new ProtoRegistry(mapping, nodeInterface);
}
@Test public void how_to_concisely_group_multimap_entries() {
Stream<Multimap<Integer, String>> numbers = Stream.of(
ImmutableListMultimap.of(1, "one", 2, "two"),
ImmutableListMultimap.of(1, "uno", 2, "dos"));
Map<Integer, List<String>> numberTranslations = numbers
.collect(groupingValuesFrom(Multimap::entries))
.toMap();
assertThat(numberTranslations)
.containsExactly(1, asList("one", "uno"), 2, asList("two", "dos"));
}
@Test
public void test_toImmutableListMultimap_key() {
List<String> list = Arrays.asList("a", "ab", "b", "bb", "c", "a");
ImmutableListMultimap<Integer, String> test = list.stream()
.collect(Guavate.toImmutableListMultimap(s -> s.length()));
ImmutableListMultimap<Object, Object> expected = ImmutableListMultimap.builder()
.put(1, "a").put(2, "ab").put(1, "b").put(2, "bb").put(1, "c").put(1, "a").build();
assertThat(test).isEqualTo(expected);
}
private static ClassPathResult buildClassPathResult(DependencyResolutionResult result)
throws EnforcerRuleException {
// The root node must have the project's JAR file
DependencyNode root = result.getDependencyGraph();
File rootFile = root.getArtifact().getFile();
if (rootFile == null) {
throw new EnforcerRuleException("The root project artifact is not associated with a file.");
}
List<Dependency> unresolvedDependencies = result.getUnresolvedDependencies();
Set<Artifact> unresolvedArtifacts =
unresolvedDependencies.stream().map(Dependency::getArtifact).collect(toImmutableSet());
DependencyGraph dependencyGraph = DependencyGraph.from(root);
ImmutableListMultimap.Builder<ClassPathEntry, DependencyPath> builder =
ImmutableListMultimap.builder();
ImmutableList.Builder<UnresolvableArtifactProblem> problems = ImmutableList.builder();
for (DependencyPath path : dependencyGraph.list()) {
Artifact artifact = path.getLeaf();
if (unresolvedArtifacts.contains(artifact)) {
problems.add(new UnresolvableArtifactProblem(artifact));
} else {
builder.put(new ClassPathEntry(artifact), path);
}
}
return new ClassPathResult(builder.build(), problems.build());
}
private static ImmutableListMultimap<String, String> getCompatibleJavacOptions(
RuleContext ruleContext) {
ImmutableListMultimap.Builder<String, String> result = ImmutableListMultimap.builder();
for (Map.Entry<String, List<String>> entry :
ruleContext.attributes().get("compatible_javacopts", Type.STRING_LIST_DICT).entrySet()) {
result.putAll(entry.getKey(), JavaHelper.tokenizeJavaOptions(entry.getValue()));
}
return result.build();
}
@Test
public void postOrder_tree_connectedRoots() {
Walker<String> walker =
DataType.TREE.newWalker(
ImmutableListMultimap.of("foo", "bar", "bar", "dog", "zoo", "dog", "zoo", "cat"));
assertThat(walker.postOrderFrom("foo", "zoo"))
.containsExactly("dog", "bar", "foo", "cat", "dog", "zoo")
.inOrder();
}
@Test
public void testGroupBy(){
List<UserEntity> all = LangUtils.newArrayList();
List<UserEntity> aa = createSameNameUserList("aa", 3);
List<UserEntity> bb = createSameNameUserList("bb", 1);
List<UserEntity> cc = createSameNameUserList("cc", 2);
all.addAll(aa);
all.addAll(bb);
all.addAll(cc);
ImmutableListMultimap<String, UserEntity> groups = Multimaps.index(all, new Function<UserEntity, String>() {
@Override
public String apply(UserEntity input) {
return input.getUserName();
}
});
System.out.println("groups:" + groups);
Assert.assertEquals(3, groups.get("aa").size());
Assert.assertEquals(1, groups.get("bb").size());
Assert.assertEquals(2, groups.get("cc").size());
Map<String, List<UserEntity>> userGroup = all.stream().collect(Collectors.groupingBy(u->u.getUserName()));
System.out.println("userGroup:" + userGroup);
Assert.assertEquals(3, userGroup.get("aa").size());
Assert.assertEquals(1, userGroup.get("bb").size());
Assert.assertEquals(2, userGroup.get("cc").size());
}
private JsonObject generateActualJsonWithFullName(String fn, String cursor) {
metricSearchType = SearchType.BY_FULL_NAME;
action.fnParam = Optional.of(fn);
if (cursor == null) {
action.parameterMap = ImmutableListMultimap.of("fn", fn);
action.cursorTokenParam = Optional.empty();
} else {
action.parameterMap = ImmutableListMultimap.of("fn", fn, "cursor", cursor);
action.cursorTokenParam = Optional.of(cursor);
}
action.run();
return parseJsonObject(response.getPayload());
}
@Override
public ImmutableList<ModuleSplit> merge(ImmutableCollection<ModuleSplit> moduleSplits) {
checkArgument(
moduleSplits.stream().map(ModuleSplit::getVariantTargeting).distinct().count() == 1,
"SameTargetingMerger doesn't support merging splits from different variants.");
ImmutableList.Builder<ModuleSplit> result = ImmutableList.builder();
ImmutableListMultimap<ApkTargeting, ModuleSplit> splitsByTargeting =
Multimaps.index(moduleSplits, ModuleSplit::getApkTargeting);
for (ApkTargeting targeting : splitsByTargeting.keySet()) {
result.add(mergeSplits(splitsByTargeting.get(targeting)));
}
return result.build();
}
final ImmutableListMultimap<ExecutableElement, AnnotationMirror> propertyMethodAnnotationMap(
TypeElement type, ImmutableSet<ExecutableElement> propertyMethods) {
ImmutableListMultimap.Builder<ExecutableElement, AnnotationMirror> builder =
ImmutableListMultimap.builder();
for (ExecutableElement propertyMethod : propertyMethods) {
builder.putAll(propertyMethod, propertyMethodAnnotations(type, propertyMethod));
}
return builder.build();
}
@Test
public void topologicalOrder_dag() {
Graph<String> graph = toDirectedGraph(
ImmutableListMultimap.of("foo", "baz", "foo", "bar", "bar", "zoo", "baz", "zoo"));
assertThat(topologicalOrder(graph, "foo"))
.containsExactly("foo", "bar", "baz", "zoo")
.inOrder();
}
@Test
public void topologicalOrder_oneUndirectedEdge() {
Graph<String> graph = toUndirectedGraph(ImmutableListMultimap.of("foo", "bar"));
CyclicGraphException thrown =
assertThrows(CyclicGraphException.class, () -> topologicalOrder(graph, "foo"));
assertThat(thrown.cyclicPath()).containsExactly("foo", "bar", "foo").inOrder();
}
private ReadResponseImpl(
boolean success, ImmutableList<PiEntity> entities,
ImmutableListMultimap<Class<? extends PiEntity>, PiEntity> typeToEntities,
String explanation, Throwable throwable) {
this.success = success;
this.entities = entities;
this.typeToEntities = typeToEntities;
this.explanation = explanation;
this.throwable = throwable;
}
private static ImmutableListMultimap<Environment, SourceFile> loadBuiltinExterns() {
ImmutableListMultimap.Builder<Environment, SourceFile> externs =
ImmutableListMultimap.builder();
for (Environment environment : Environment.values()) {
try {
externs.putAll(environment, AbstractCommandLineRunner.getBuiltinExterns(environment));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return externs.build();
}
@Test
public void clear() throws Exception {
multiMap.putAll(ImmutableListMultimap.of(
"first", new TestEntity("1", "v1"),
"second", new TestEntity("2", "v2"),
"second", new TestEntity("3", "v3")
));
assertThat(multiMap.asMap()).isNotEmpty();
multiMap.clear();
assertThat(multiMap.asMap()).isEmpty();
}
public AlterIndexStatement(NamedTableNode indexTableNode, String dataTableName, boolean ifExists, PIndexState indexState, boolean isRebuildAll, boolean async, ListMultimap<String,Pair<String,Object>> props) {
super(indexTableNode,0);
this.dataTableName = dataTableName;
this.ifExists = ifExists;
this.indexState = indexState;
this.async = async;
this.isRebuildAll = isRebuildAll;
this.props= props==null ? ImmutableListMultimap.<String,Pair<String,Object>>of() : props;
}