下面列出了com.google.common.collect.ImmutableListMultimap#copyOf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void writeMessageShouldSendResponse() throws Exception {
ListMultimap<CharSequence, CharSequence> expectedHeaders =
ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
.status(Utils.STATUS_OK)
.set(Utils.CONTENT_TYPE_HEADER, Utils.CONTENT_TYPE_GRPC));
stream.writeHeaders(new Metadata());
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();
byte[] msg = smallMessage();
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
verify(writeQueue).enqueue(
eq(new SendGrpcFrameCommand(stream.transportState(), messageFrame(MESSAGE), false)),
eq(true));
}
@Test
public void closeBeforeClientHalfCloseShouldSucceed() throws Exception {
ListMultimap<CharSequence, CharSequence> expectedHeaders =
ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
.status(new AsciiString("200"))
.set(new AsciiString("content-type"), new AsciiString("application/grpc"))
.set(new AsciiString("grpc-status"), new AsciiString("0")));
stream().close(Status.OK, new Metadata());
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()).isTrue();
verifyZeroInteractions(serverListener);
// Sending complete. Listener gets closed()
stream().transportState().complete();
verify(serverListener).closed(Status.OK);
assertNull("no message expected", listenerMessageQueue.poll());
}
public SpringChannelHandler(final List<OnConnectMethodInvoker> onConnectCallbacks,
final List<OnMessageMethodInvoker> onMessageCallbacks) {
this.onConnectCallbacks = onConnectCallbacks;
this.onMessageCallbacks = onMessageCallbacks;
final Multimap<Class<?>, OnMessageMethodInvoker> onMessageInvokers = ArrayListMultimap.create();
final Set<? extends Class<?>> messageBodyTypes = onMessageCallbacks.stream()
.map(OnMessageMethodInvoker::getMessageBodyType)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
messageBodyTypes.forEach(mbt -> {
onMessageCallbacks.forEach(invoker -> {
final Class<?> messageBodyType = invoker.getMessageBodyType();
if ((messageBodyType == null) || mbt.isAssignableFrom(messageBodyType)) {
onMessageInvokers.put(mbt, invoker);
}
});
});
typedCallbackMap = ImmutableListMultimap.copyOf(onMessageInvokers);
typedCallbackClasses = typedCallbackMap.keySet();
}
@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()).isSameInstanceAs(stream.transportState());
assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
.containsExactlyEntriesIn(expectedHeaders);
assertThat(sendHeaders.endOfStream()).isFalse();
}
@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
ListMultimap<CharSequence, CharSequence> expectedHeaders =
ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
.status(new AsciiString("200"))
.set(new AsciiString("content-type"), new AsciiString("application/grpc"))
.set(new AsciiString("grpc-status"), new AsciiString("0")));
// Client half-closes. Listener gets halfClosed()
stream().transportState()
.inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);
verify(serverListener).halfClosed();
// Server closes. Status sent
stream().close(Status.OK, trailers);
assertNull("no message expected", listenerMessageQueue.poll());
ArgumentCaptor<SendResponseHeadersCommand> cmdCap =
ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
SendResponseHeadersCommand cmd = cmdCap.getValue();
assertThat(cmd.stream()).isSameAs(stream.transportState());
assertThat(ImmutableListMultimap.copyOf(cmd.headers()))
.containsExactlyEntriesIn(expectedHeaders);
assertThat(cmd.endOfStream()).isTrue();
// Sending and receiving complete. Listener gets closed()
stream().transportState().complete();
verify(serverListener).closed(Status.OK);
assertNull("no message expected", listenerMessageQueue.poll());
}
@Test
public void getRequestSentThroughHeader() {
// Creating a GET method
MethodDescriptor<?, ?> descriptor = MethodDescriptor.<Void, Void>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("testService/test")
.setRequestMarshaller(marshaller)
.setResponseMarshaller(marshaller)
.setIdempotent(true)
.setSafe(true)
.build();
NettyClientStream stream = new NettyClientStream(
new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
descriptor,
new Metadata(),
channel,
AsciiString.of("localhost"),
AsciiString.of("http"),
AsciiString.of("agent"),
StatsTraceContext.NOOP,
transportTracer,
CallOptions.DEFAULT);
stream.start(listener);
stream.transportState().setId(STREAM_ID);
stream.transportState().setHttp2Stream(http2Stream);
byte[] msg = smallMessage();
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
stream.halfClose();
ArgumentCaptor<CreateStreamCommand> cmdCap = ArgumentCaptor.forClass(CreateStreamCommand.class);
verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
ImmutableListMultimap<CharSequence, CharSequence> headers =
ImmutableListMultimap.copyOf(cmdCap.getValue().headers());
assertThat(headers).containsEntry(AsciiString.of(":method"), Utils.HTTP_GET_METHOD);
assertThat(headers)
.containsEntry(
AsciiString.of(":path"),
AsciiString.of("/testService/test?" + BaseEncoding.base64().encode(msg)));
}
@JsonCreator
protected SetOperationNode(
@JsonProperty("id") PlanNodeId id,
@JsonProperty("sources") List<PlanNode> sources,
@JsonProperty("outputToInputs") ListMultimap<Symbol, Symbol> outputToInputs,
@JsonProperty("outputs") List<Symbol> outputs)
{
super(id);
requireNonNull(sources, "sources is null");
checkArgument(!sources.isEmpty(), "Must have at least one source");
requireNonNull(outputToInputs, "outputToInputs is null");
requireNonNull(outputs, "outputs is null");
this.sources = ImmutableList.copyOf(sources);
this.outputToInputs = ImmutableListMultimap.copyOf(outputToInputs);
this.outputs = ImmutableList.copyOf(outputs);
for (Collection<Symbol> inputs : this.outputToInputs.asMap().values()) {
checkArgument(inputs.size() == this.sources.size(), "Every source needs to map its symbols to an output %s operation symbol", this.getClass().getSimpleName());
}
// Make sure each source positionally corresponds to their Symbol values in the Multimap
for (int i = 0; i < sources.size(); i++) {
for (Collection<Symbol> expectedInputs : this.outputToInputs.asMap().values()) {
checkArgument(sources.get(i).getOutputSymbols().contains(Iterables.get(expectedInputs, i)), "Source does not provide required symbols");
}
}
}
@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
ListMultimap<CharSequence, CharSequence> expectedHeaders =
ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
.status(new AsciiString("200"))
.set(new AsciiString("content-type"), new AsciiString("application/grpc"))
.set(new AsciiString("grpc-status"), new AsciiString("0")));
// Client half-closes. Listener gets halfClosed()
stream().transportState()
.inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);
verify(serverListener).halfClosed();
// Server closes. Status sent
stream().close(Status.OK, trailers);
assertNull("no message expected", listenerMessageQueue.poll());
ArgumentCaptor<SendResponseHeadersCommand> cmdCap =
ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
SendResponseHeadersCommand cmd = cmdCap.getValue();
assertThat(cmd.stream()).isSameInstanceAs(stream.transportState());
assertThat(ImmutableListMultimap.copyOf(cmd.headers()))
.containsExactlyEntriesIn(expectedHeaders);
assertThat(cmd.endOfStream()).isTrue();
// Sending and receiving complete. Listener gets closed()
stream().transportState().complete();
verify(serverListener).closed(Status.OK);
assertNull("no message expected", listenerMessageQueue.poll());
}
private static ImmutableListMultimap<String, String> parseParties(XmlElement root) {
ListMultimap<String, String> parties = ArrayListMultimap.create();
for (XmlElement child : root.getChildren("party")) {
parties.putAll(child.getAttribute(ID), findPartyIds(child));
}
return ImmutableListMultimap.copyOf(parties);
}
protected <T extends DataObject> T get(final Class<T> type, final String endpoint, final Platform platform, final Map<String, String> parameters,
final String rateLimiterName) {
final RequestContext<T> context = new RequestContext<>(type, endpoint, platform,
parameters == null ? null : ImmutableListMultimap.copyOf(parameters.entrySet()),
rateLimiterName);
return get(context);
}
/**
* Loads file containing unary rules
*/
public static ListMultimap<Category, UnaryRule> loadUnaryRules(final File file) throws IOException {
final Multimap<Category, UnaryRule> result = HashMultimap.create();
final Lexicon lexicon = new DefaultLexicon();
for (String line : Util.readFile(file)) {
// Allow comments.
if (line.startsWith("#")) {
continue;
}
line = line.trim();
if (line.isEmpty()) {
continue;
}
final String[] fields = line.split("\\s+");
if (fields.length != 2 && fields.length != 3) {
throw new Error("Expected 2 categories (and optional logical form) on line in UnaryRule file: " + line);
}
final String from = fields[0];
final String to = fields[1];
final Category cat = Category.make(Category.valueOf(to), Slash.FWD, Category.valueOf(from));
Logic logic;
if (fields.length == 3) {
logic = LogicParser.fromString(fields[2], cat);
} else {
logic = lexicon.getEntry(null, "NULL", cat, Coindexation.fromString(to + "/" + from, -1));
}
result.put(Category.valueOf(from), new UnaryRule(result.size(), from, to, logic));
}
return ImmutableListMultimap.copyOf(result);
}
protected <T extends CoreData> T get(final Class<T> type, final String endpoint, final Map<String, String> parameters) {
final RequestContext<T> context = new RequestContext<>(type, endpoint, parameters == null ? null : ImmutableListMultimap.copyOf(parameters.entrySet()));
return get(context);
}
private ImmutableMap<CxxPreprocessAndCompile, SourcePath> requireCxxObjects(
BuildTarget target,
ProjectFilesystem projectFilesystem,
ActionGraphBuilder graphBuilder,
CellPathResolver cellRoots,
CxxPlatform cxxPlatform,
CxxPythonExtensionDescriptionArg args,
ImmutableSet<BuildRule> deps) {
StringWithMacrosConverter macrosConverter =
CxxDescriptionEnhancer.getStringWithMacrosArgsConverter(
target, cellRoots, graphBuilder, cxxPlatform);
// Extract all C/C++ sources from the constructor arg.
ImmutableMap<String, CxxSource> srcs =
CxxDescriptionEnhancer.parseCxxSources(target, graphBuilder, cxxPlatform, args);
ImmutableMap<Path, SourcePath> headers =
CxxDescriptionEnhancer.parseHeaders(
target, graphBuilder, projectFilesystem, Optional.of(cxxPlatform), args);
// Setup the header symlink tree and combine all the preprocessor input from this rule
// and all dependencies.
HeaderSymlinkTree headerSymlinkTree =
CxxDescriptionEnhancer.requireHeaderSymlinkTree(
target,
projectFilesystem,
graphBuilder,
cxxPlatform,
headers,
HeaderVisibility.PRIVATE,
true);
ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput =
CxxDescriptionEnhancer.collectCxxPreprocessorInput(
target,
cxxPlatform,
graphBuilder,
deps,
ImmutableListMultimap.copyOf(
Multimaps.transformValues(
CxxFlags.getLanguageFlagsWithMacros(
args.getPreprocessorFlags(),
args.getPlatformPreprocessorFlags(),
args.getLangPreprocessorFlags(),
args.getLangPlatformPreprocessorFlags(),
cxxPlatform),
macrosConverter::convert)),
ImmutableList.of(headerSymlinkTree),
ImmutableSet.of(),
CxxPreprocessables.getTransitiveCxxPreprocessorInputFromDeps(
cxxPlatform, graphBuilder, deps),
args.getRawHeaders(),
args.getIncludeDirectories(),
projectFilesystem);
// Generate rule to build the object files.
ImmutableMultimap<CxxSource.Type, Arg> compilerFlags =
ImmutableListMultimap.copyOf(
Multimaps.transformValues(
CxxFlags.getLanguageFlagsWithMacros(
args.getCompilerFlags(),
args.getPlatformCompilerFlags(),
args.getLangCompilerFlags(),
args.getLangPlatformCompilerFlags(),
cxxPlatform),
macrosConverter::convert));
CxxSourceRuleFactory factory =
CxxSourceRuleFactory.of(
projectFilesystem,
target,
graphBuilder,
graphBuilder.getSourcePathResolver(),
cxxBuckConfig,
cxxPlatform,
cxxPreprocessorInput,
compilerFlags,
args.getPrefixHeader(),
args.getPrecompiledHeader(),
PicType.PIC);
return factory.requirePreprocessAndCompileRules(srcs);
}
DuplicateConstraintException(
ListMultimap<ConstraintSettingInfo, ConstraintValueInfo> duplicateConstraints) {
super(formatError(duplicateConstraints));
this.duplicateConstraints = ImmutableListMultimap.copyOf(duplicateConstraints);
}
public DesugarRule build() {
checkInjectableClassLiterals();
checkInjectableAsmNodes();
checkInjectableMethodHandles();
checkInjectableJarEntries();
if (maxNumOfTransformations > 0) {
checkJVMOptions();
if (bootClassPathEntries.isEmpty()
&& !customCommandOptions.containsKey("allow_empty_bootclasspath")) {
addBootClassPathEntries(Paths.get(androidRuntimeJarJvmFlagValue));
}
addClasspathEntries(Paths.get(jacocoAgentJarJvmFlagValue));
}
ImmutableList.Builder<SourceCompilationUnit> sourceCompilationUnits = ImmutableList.builder();
if (!sourceInputs.isEmpty()) {
try {
Path runtimeCompiledJar = Files.createTempFile("runtime_compiled_", ".jar");
sourceCompilationUnits.add(
new SourceCompilationUnit(
ToolProvider.getSystemJavaCompiler(),
ImmutableList.copyOf(javacOptions),
ImmutableList.copyOf(sourceInputs),
runtimeCompiledJar));
addInputs(runtimeCompiledJar);
} catch (IOException e) {
errorMessenger.addError(
"Failed to access the output jar location for compilation: %s\n%s", sourceInputs, e);
}
}
RuntimeEntityResolver runtimeEntityResolver =
new RuntimeEntityResolver(
testInstanceLookup,
workingJavaPackage,
maxNumOfTransformations,
ImmutableList.copyOf(inputs),
ImmutableList.copyOf(classPathEntries),
ImmutableList.copyOf(bootClassPathEntries),
ImmutableListMultimap.copyOf(customCommandOptions));
if (errorMessenger.containsAnyError()) {
throw new IllegalStateException(
String.format(
"Invalid Desugar configurations:\n%s\n",
String.join("\n", errorMessenger.getAllMessages())));
}
return new DesugarRule(
testInstance,
testInstanceLookup,
ImmutableList.<Field>builder()
.addAll(injectableClassLiterals)
.addAll(injectableAsmNodes)
.addAll(injectableMethodHandles)
.addAll(injectableJarEntries)
.build(),
sourceCompilationUnits.build(),
runtimeEntityResolver);
}
private RuleIndex(ListMultimap<Class<?>, Rule<?>> rulesByRootType)
{
this.rulesByRootType = ImmutableListMultimap.copyOf(rulesByRootType);
}
@Test
public void getRequestSentThroughHeader() {
// Creating a GET method
MethodDescriptor<?, ?> descriptor = MethodDescriptor.<Void, Void>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("testService/test")
.setRequestMarshaller(marshaller)
.setResponseMarshaller(marshaller)
.setIdempotent(true)
.setSafe(true)
.build();
NettyClientStream stream = new NettyClientStream(
new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
descriptor,
new Metadata(),
channel,
AsciiString.of("localhost"),
AsciiString.of("http"),
AsciiString.of("agent"),
StatsTraceContext.NOOP,
transportTracer,
CallOptions.DEFAULT,
true);
stream.start(listener);
stream.transportState().setId(STREAM_ID);
stream.transportState().setHttp2Stream(http2Stream);
byte[] msg = smallMessage();
stream.writeMessage(new ByteArrayInputStream(msg));
stream.flush();
stream.halfClose();
ArgumentCaptor<CreateStreamCommand> cmdCap = ArgumentCaptor.forClass(CreateStreamCommand.class);
verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
ImmutableListMultimap<CharSequence, CharSequence> headers =
ImmutableListMultimap.copyOf(cmdCap.getValue().headers());
assertThat(headers).containsEntry(AsciiString.of(":method"), Utils.HTTP_GET_METHOD);
assertThat(headers)
.containsEntry(
AsciiString.of(":path"),
AsciiString.of("/testService/test?" + BaseEncoding.base64().encode(msg)));
}
public SchemaOrgTypeImpl(
Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) {
super(properties);
this.reverseMap = ImmutableListMultimap.copyOf(reverseMap);
}
protected <T extends DataObject> T get(final Class<T> type, final String endpoint, final Platform platform, final Map<String, String> parameters) {
final RequestContext<T> context = new RequestContext<>(type, endpoint, platform,
parameters == null ? null : ImmutableListMultimap.copyOf(parameters.entrySet()), null);
return get(context);
}
public HttpQueryParams immutableCopy()
{
return new HttpQueryParams(ImmutableListMultimap.copyOf(delegate));
}