本文整理汇总了Java中io.grpc.internal.GrpcUtil类的典型用法代码示例。如果您正苦于以下问题:Java GrpcUtil类的具体用法?Java GrpcUtil怎么用?Java GrpcUtil使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
GrpcUtil类属于io.grpc.internal包,在下文中一共展示了GrpcUtil类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: newNameResolver
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Nullable
@Override
public NameResolver newNameResolver(URI targetUri, Attributes params) {
if (SCHEME.equals(targetUri.getScheme())) {
String targetPath = Preconditions.checkNotNull(targetUri.getPath(), "targetPath");
Preconditions.checkArgument(targetPath.startsWith("/"),
"the path component (%s) of the target (%s) must start with '/'", targetPath, targetUri);
String[] parts = targetPath.split("/");
if (parts.length != 4) {
throw new IllegalArgumentException("Must be formatted like kubernetes:///{namespace}/{service}/{port}");
}
try {
int port = Integer.valueOf(parts[3]);
return new KubernetesNameResolver(parts[1], parts[2], port, params, GrpcUtil.TIMER_SERVICE,
GrpcUtil.SHARED_CHANNEL_EXECUTOR);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unable to parse port number", e);
}
} else {
return null;
}
}
示例2: CronetClientTransport
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
CronetClientTransport(
StreamBuilderFactory streamFactory,
InetSocketAddress address,
String authority,
@Nullable String userAgent,
Executor executor,
int maxMessageSize,
boolean alwaysUsePut,
TransportTracer transportTracer) {
this.address = Preconditions.checkNotNull(address, "address");
this.authority = authority;
this.userAgent = GrpcUtil.getGrpcUserAgent("cronet", userAgent);
this.maxMessageSize = maxMessageSize;
this.alwaysUsePut = alwaysUsePut;
this.executor = Preconditions.checkNotNull(executor, "executor");
this.streamFactory = Preconditions.checkNotNull(streamFactory, "streamFactory");
this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
}
示例3: setGrpcHeaders
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
private void setGrpcHeaders(BidirectionalStream.Builder builder) {
// Psuedo-headers are set by cronet.
// All non-pseudo headers must come after pseudo headers.
// TODO(ericgribkoff): remove this and set it on CronetEngine after crbug.com/588204 gets fixed.
builder.addHeader(USER_AGENT_KEY.name(), userAgent);
builder.addHeader(CONTENT_TYPE_KEY.name(), GrpcUtil.CONTENT_TYPE_GRPC);
builder.addHeader("te", GrpcUtil.TE_TRAILERS);
// Now add any application-provided headers.
// TODO(ericgribkoff): make a String-based version to avoid unnecessary conversion between
// String and byte array.
byte[][] serializedHeaders = TransportFrameUtil.toHttp2Headers(headers);
for (int i = 0; i < serializedHeaders.length; i += 2) {
String key = new String(serializedHeaders[i], Charset.forName("UTF-8"));
// TODO(ericgribkoff): log an error or throw an exception
if (isApplicationHeader(key)) {
String value = new String(serializedHeaders[i + 1], Charset.forName("UTF-8"));
builder.addHeader(key, value);
}
}
}
示例4: goAway
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Override
public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
if (errorCode == ErrorCode.ENHANCE_YOUR_CALM) {
String data = debugData.utf8();
log.log(Level.WARNING, String.format(
"%s: Received GOAWAY with ENHANCE_YOUR_CALM. Debug data: %s", this, data));
if ("too_many_pings".equals(data)) {
tooManyPingsRunnable.run();
}
}
Status status = GrpcUtil.Http2Error.statusForCode(errorCode.httpCode)
.augmentDescription("Received Goaway");
if (debugData.size() > 0) {
// If a debug message was provided, use it.
status = status.augmentDescription(debugData.utf8());
}
startGoAway(lastGoodStreamId, null, status);
}
示例5: getNameResolverParams
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Override
protected Attributes getNameResolverParams() {
int defaultPort;
switch (negotiationType) {
case PLAINTEXT:
defaultPort = GrpcUtil.DEFAULT_PORT_PLAINTEXT;
break;
case TLS:
defaultPort = GrpcUtil.DEFAULT_PORT_SSL;
break;
default:
throw new AssertionError(negotiationType + " not handled");
}
return Attributes.newBuilder()
.set(NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build();
}
示例6: addDefaultUserAgent
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Test
public void addDefaultUserAgent() throws Exception {
initTransport();
MockStreamListener listener = new MockStreamListener();
OkHttpClientStream stream =
clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
stream.start(listener);
Header userAgentHeader = new Header(GrpcUtil.USER_AGENT_KEY.name(),
GrpcUtil.getGrpcUserAgent("okhttp", null));
List<Header> expectedHeaders = Arrays.asList(SCHEME_HEADER, METHOD_HEADER,
new Header(Header.TARGET_AUTHORITY, "notarealauthority:80"),
new Header(Header.TARGET_PATH, "/" + method.getFullMethodName()),
userAgentHeader, CONTENT_TYPE_HEADER, TE_HEADER);
verify(frameWriter, timeout(TIME_OUT_MS))
.synStream(eq(false), eq(false), eq(3), eq(0), eq(expectedHeaders));
getStream(3).cancel(Status.CANCELLED);
shutdownAndVerify();
}
示例7: overrideDefaultUserAgent
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Test
public void overrideDefaultUserAgent() throws Exception {
startTransport(3, null, true, DEFAULT_MAX_MESSAGE_SIZE, "fakeUserAgent");
MockStreamListener listener = new MockStreamListener();
OkHttpClientStream stream =
clientTransport.newStream(method, new Metadata(), CallOptions.DEFAULT);
stream.start(listener);
List<Header> expectedHeaders = Arrays.asList(SCHEME_HEADER, METHOD_HEADER,
new Header(Header.TARGET_AUTHORITY, "notarealauthority:80"),
new Header(Header.TARGET_PATH, "/" + method.getFullMethodName()),
new Header(GrpcUtil.USER_AGENT_KEY.name(),
GrpcUtil.getGrpcUserAgent("okhttp", "fakeUserAgent")),
CONTENT_TYPE_HEADER, TE_HEADER);
verify(frameWriter, timeout(TIME_OUT_MS))
.synStream(eq(false), eq(false), eq(3), eq(0), eq(expectedHeaders));
getStream(3).cancel(Status.CANCELLED);
shutdownAndVerify();
}
示例8: start_headerFieldOrder
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Test
public void start_headerFieldOrder() {
Metadata metaData = new Metadata();
metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application");
stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport,
flowController, lock, MAX_MESSAGE_SIZE, "localhost", "good-application",
StatsTraceContext.NOOP, transportTracer);
stream.start(new BaseClientStreamListener());
stream.transportState().start(3);
verify(frameWriter).synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
assertThat(headersCaptor.getValue()).containsExactly(
Headers.SCHEME_HEADER,
Headers.METHOD_HEADER,
new Header(Header.TARGET_AUTHORITY, "localhost"),
new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()),
new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"),
Headers.CONTENT_TYPE_HEADER,
Headers.TE_HEADER)
.inOrder();
}
示例9: createChannelBuilder
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
private OkHttpChannelBuilder createChannelBuilder() {
OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", getPort())
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.connectionSpec(new ConnectionSpec.Builder(OkHttpChannelBuilder.DEFAULT_CONNECTION_SPEC)
.cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
.tlsVersions(ConnectionSpec.MODERN_TLS.tlsVersions().toArray(new TlsVersion[0]))
.build())
.overrideAuthority(GrpcUtil.authorityFromHostAndPort(
TestUtils.TEST_SERVER_HOST, getPort()));
io.grpc.internal.TestingAccessor.setStatsImplementation(
builder, createClientCensusStatsModule());
try {
builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
TestUtils.loadCert("ca.pem")));
} catch (Exception e) {
throw new RuntimeException(e);
}
return builder;
}
示例10: wrongHostNameFailHostnameVerification
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Test
public void wrongHostNameFailHostnameVerification() throws Exception {
ManagedChannel channel = createChannelBuilder()
.overrideAuthority(GrpcUtil.authorityFromHostAndPort(
BAD_HOSTNAME, getPort()))
.build();
TestServiceGrpc.TestServiceBlockingStub blockingStub =
TestServiceGrpc.newBlockingStub(channel);
Throwable actualThrown = null;
try {
blockingStub.emptyCall(Empty.getDefaultInstance());
} catch (Throwable t) {
actualThrown = t;
}
assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
Throwable cause = Throwables.getRootCause(actualThrown);
assertTrue(
"Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
channel.shutdown();
}
示例11: hostnameVerifierWithBadHostname
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Test
public void hostnameVerifierWithBadHostname() throws Exception {
ManagedChannel channel = createChannelBuilder()
.overrideAuthority(GrpcUtil.authorityFromHostAndPort(
BAD_HOSTNAME, getPort()))
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
TestServiceGrpc.TestServiceBlockingStub blockingStub =
TestServiceGrpc.newBlockingStub(channel);
blockingStub.emptyCall(Empty.getDefaultInstance());
channel.shutdown();
}
示例12: tls
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
/**
* Returns a {@link ProtocolNegotiator} that ensures the pipeline is set up so that TLS will
* be negotiated, the {@code handler} is added and writes to the {@link io.netty.channel.Channel}
* may happen immediately, even before the TLS Handshake is complete.
*/
public static ProtocolNegotiator tls(SslContext sslContext, String authority) {
Preconditions.checkNotNull(sslContext, "sslContext");
URI uri = GrpcUtil.authorityToUri(Preconditions.checkNotNull(authority, "authority"));
String host;
int port;
if (uri.getHost() != null) {
host = uri.getHost();
port = uri.getPort();
} else {
/*
* Implementation note: We pick -1 as the port here rather than deriving it from the original
* socket address. The SSL engine doens't use this port number when contacting the remote
* server, but rather it is used for other things like SSL Session caching. When an invalid
* authority is provided (like "bad_cert"), picking the original port and passing it in would
* mean that the port might used under the assumption that it was correct. By using -1 here,
* it forces the SSL implementation to treat it as invalid.
*/
host = authority;
port = -1;
}
return new TlsNegotiator(sslContext, host, port);
}
示例13: NettyClientTransport
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
NettyClientTransport(
SocketAddress address, Class<? extends Channel> channelType,
Map<ChannelOption<?>, ?> channelOptions, EventLoopGroup group,
ProtocolNegotiator negotiator, int flowControlWindow, int maxMessageSize,
int maxHeaderListSize, long keepAliveTimeNanos, long keepAliveTimeoutNanos,
boolean keepAliveWithoutCalls, String authority, @Nullable String userAgent,
Runnable tooManyPingsRunnable, TransportTracer transportTracer) {
this.negotiator = Preconditions.checkNotNull(negotiator, "negotiator");
this.address = Preconditions.checkNotNull(address, "address");
this.group = Preconditions.checkNotNull(group, "group");
this.channelType = Preconditions.checkNotNull(channelType, "channelType");
this.channelOptions = Preconditions.checkNotNull(channelOptions, "channelOptions");
this.flowControlWindow = flowControlWindow;
this.maxMessageSize = maxMessageSize;
this.maxHeaderListSize = maxHeaderListSize;
this.keepAliveTimeNanos = keepAliveTimeNanos;
this.keepAliveTimeoutNanos = keepAliveTimeoutNanos;
this.keepAliveWithoutCalls = keepAliveWithoutCalls;
this.authority = new AsciiString(authority);
this.userAgent = new AsciiString(GrpcUtil.getGrpcUserAgent("netty", userAgent));
this.tooManyPingsRunnable =
Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
this.transportTracer = Preconditions.checkNotNull(transportTracer, "transportTracer");
}
示例14: convertClientHeaders
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
public static Http2Headers convertClientHeaders(Metadata headers,
AsciiString scheme,
AsciiString defaultPath,
AsciiString authority,
AsciiString method,
AsciiString userAgent) {
Preconditions.checkNotNull(defaultPath, "defaultPath");
Preconditions.checkNotNull(authority, "authority");
Preconditions.checkNotNull(method, "method");
// Discard any application supplied duplicates of the reserved headers
headers.discardAll(CONTENT_TYPE_KEY);
headers.discardAll(GrpcUtil.TE_HEADER);
headers.discardAll(GrpcUtil.USER_AGENT_KEY);
return GrpcHttp2OutboundHeaders.clientRequestHeaders(
toHttp2Headers(headers),
authority,
defaultPath,
method,
scheme,
userAgent);
}
示例15: getNameResolverParams
import io.grpc.internal.GrpcUtil; //导入依赖的package包/类
@Override
@CheckReturnValue
protected Attributes getNameResolverParams() {
int defaultPort;
switch (negotiationType) {
case PLAINTEXT:
case PLAINTEXT_UPGRADE:
defaultPort = GrpcUtil.DEFAULT_PORT_PLAINTEXT;
break;
case TLS:
defaultPort = GrpcUtil.DEFAULT_PORT_SSL;
break;
default:
throw new AssertionError(negotiationType + " not handled");
}
return Attributes.newBuilder()
.set(NameResolver.Factory.PARAMS_DEFAULT_PORT, defaultPort).build();
}