本文整理匯總了Java中io.grpc.Metadata.get方法的典型用法代碼示例。如果您正苦於以下問題:Java Metadata.get方法的具體用法?Java Metadata.get怎麽用?Java Metadata.get使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類io.grpc.Metadata
的用法示例。
在下文中一共展示了Metadata.get方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: copyMetadataToThreadLocal
import io.grpc.Metadata; //導入方法依賴的package包/類
private void copyMetadataToThreadLocal(Metadata headers) {
String attachments = headers.get(GrpcUtil.GRPC_CONTEXT_ATTACHMENTS);
String values = headers.get(GrpcUtil.GRPC_CONTEXT_VALUES);
try {
if (attachments != null) {
Map<String, String> attachmentsMap =
SerializerUtil.fromJson(attachments, new TypeToken<Map<String, String>>() {}.getType());
RpcContext.getContext().setAttachments(attachmentsMap);
}
if (values != null) {
Map<String, Object> valuesMap =
SerializerUtil.fromJson(values, new TypeToken<Map<String, Object>>() {}.getType());
for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
RpcContext.getContext().set(entry.getKey(), entry.getValue());
}
}
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
}
示例2: toError
import io.grpc.Metadata; //導入方法依賴的package包/類
/**
* Returns the {@link Error} extracted from the {@link Metadata}.
*
* @param metadata the metadata to convert
* @return the error extracted from the metadata or {@code Optional.absent()}
* if there is no error.
*/
public static Optional<Error> toError(Metadata metadata) {
checkNotNull(metadata);
final byte[] bytes = metadata.get(KEY);
if (bytes == null) {
return Optional.absent();
}
try {
final Error error = Error.parseFrom(bytes);
return Optional.of(error);
} catch (InvalidProtocolBufferException e) {
throw Exceptions.illegalStateWithCauseOf(e);
}
}
示例3: interceptCall
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,ServerCallHandler<ReqT, RespT> next) {
logger.info("Call intercepted "+headers.toString());
String token = headers.get(authKey);
if (StringUtils.notEmpty(token))
{
try
{
logger.info("Token "+token);
ConsumerBean consumer = resourceServer.validateResourceFromToken(token);
logger.info("Setting call to client "+consumer.getShort_name());
return new SeldonServerCallListener<ReqT>(next.startCall(call, headers),consumer.getShort_name(),this);
}
catch (APIException e)
{
logger.warn("API exception on getting token ",e);
return next.startCall(call, headers);
}
}
else
{
logger.warn("Empty token ignoring call");
return next.startCall(call, headers);
}
}
示例4: beforeMethod
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
MethodInterceptResult result) throws Throwable {
GRPCDynamicFields cachedObjects = (GRPCDynamicFields)objInst.getSkyWalkingDynamicField();
Metadata headers = cachedObjects.getMetadata();
Map<String, String> headerMap = new HashMap<String, String>();
for (String key : headers.keys()) {
if (!key.endsWith(Metadata.BINARY_HEADER_SUFFIX)) {
String value = headers.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER));
headerMap.put(key, value);
}
}
ContextCarrier contextCarrier = new ContextCarrier();
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
String contextValue = headerMap.get(next.getHeadKey());
if (!StringUtil.isEmpty(contextValue)) {
next.setHeadValue(contextValue);
}
}
final AbstractSpan span = ContextManager.createEntrySpan(cachedObjects.getRequestMethodName() + (cachedObjects.getMethodType() != MethodDescriptor.MethodType.UNARY ? STREAM_CALL_OPERATION_NAME_SUFFIX : BLOCK_CALL_OPERATION_NAME_SUFFIX), contextCarrier);
span.setComponent(ComponentsDefine.GRPC);
}
示例5: newServerStreamTracer
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) {
TagContext parentCtx = headers.get(statsHeader);
if (parentCtx == null) {
parentCtx = tagger.empty();
}
parentCtx =
tagger
.toBuilder(parentCtx)
.put(RpcMeasureConstants.RPC_METHOD, TagValue.create(fullMethodName))
.build();
return new ServerTracer(
CensusStatsModule.this,
fullMethodName,
parentCtx,
stopwatchSupplier,
tagger,
recordStartedRpcs,
recordFinishedRpcs);
}
示例6: statusFromTrailers
import io.grpc.Metadata; //導入方法依賴的package包/類
/**
* Extract the response status from trailers.
*/
private Status statusFromTrailers(Metadata trailers) {
Status status = trailers.get(InternalStatus.CODE_KEY);
if (status != null) {
return status.withDescription(trailers.get(InternalStatus.MESSAGE_KEY));
}
// No status; something is broken. Try to provide a resonanable error.
if (headersReceived) {
return Status.UNKNOWN.withDescription("missing GRPC status in response");
}
Integer httpStatus = trailers.get(HTTP2_STATUS);
if (httpStatus != null) {
status = GrpcUtil.httpStatusToGrpcStatus(httpStatus);
} else {
status = Status.INTERNAL.withDescription("missing HTTP status code");
}
return status.augmentDescription(
"missing GRPC status, inferred error from HTTP status code");
}
示例7: contextDeadlineShouldBePropagatedInMetadata
import io.grpc.Metadata; //導入方法依賴的package包/類
@Test
public void contextDeadlineShouldBePropagatedInMetadata() {
long deadlineNanos = TimeUnit.SECONDS.toNanos(1);
Context context = Context.current().withDeadlineAfter(deadlineNanos, TimeUnit.NANOSECONDS,
deadlineCancellationExecutor);
context.attach();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
method,
MoreExecutors.directExecutor(),
baseCallOptions,
provider,
deadlineCancellationExecutor,
channelCallTracer);
Metadata headers = new Metadata();
call.start(callListener, headers);
assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
Long timeout = headers.get(GrpcUtil.TIMEOUT_KEY);
assertNotNull(timeout);
long deltaNanos = TimeUnit.MILLISECONDS.toNanos(400);
assertTimeoutBetween(timeout, deadlineNanos - deltaNanos, deadlineNanos);
}
示例8: interceptCall
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
String clientId = headers.get(CLIENT_ID_HEADER_KEY);
if (clientId == null || !authenticator.authenticate(clientId)) {
call.close(Status.UNAUTHENTICATED.withDescription("Invalid or unknown client: " + clientId), headers);
return NOOP_LISTENER;
}
Context context = Context.current().withValue(CLIENT_ID_CONTEXT_KEY, clientId);
return Contexts.interceptCall(context, call, headers, next);
}
示例9: changeMetadataKeyType
import io.grpc.Metadata; //導入方法依賴的package包/類
@Test
public void changeMetadataKeyType() {
Metadata.Key<String> stringKey = Metadata.Key.of("key", Metadata.ASCII_STRING_MARSHALLER);
Metadata.Key<Long> longKey = Metadata.Key.of("key", MoreMetadata.LONG_MARSHALLER);
Metadata metadata = new Metadata();
metadata.put(stringKey, "12345");
Long bool = metadata.get(longKey);
assertThat(bool).isEqualTo(12345);
}
示例10: rawJsonToTypedJson
import io.grpc.Metadata; //導入方法依賴的package包/類
@Test
public void rawJsonToTypedJson() {
Metadata.Key<String> stringKey = Metadata.Key.of("key", Metadata.ASCII_STRING_MARSHALLER);
Metadata.Key<Bar> barKey = Metadata.Key.of("key", MoreMetadata.JSON_MARSHALLER(Bar.class));
Metadata metadata = new Metadata();
metadata.put(stringKey, "{'cheese': 'swiss', 'age': 42}");
Bar bar = metadata.get(barKey);
assertThat(bar).isNotNull();
assertThat(bar.cheese).isEqualTo("swiss");
assertThat(bar.age).isEqualTo(42);
}
示例11: rawBytesToTypedProto
import io.grpc.Metadata; //導入方法依賴的package包/類
@Test
public void rawBytesToTypedProto() {
Metadata.Key<byte[]> byteKey = Metadata.Key.of("key-bin", Metadata.BINARY_BYTE_MARSHALLER);
Metadata.Key<HelloRequest> protoKey = Metadata.Key.of("key-bin", MoreMetadata.PROTOBUF_MARSHALLER(HelloRequest.class));
HelloRequest request = HelloRequest.newBuilder().setName("World").build();
Metadata metadata = new Metadata();
metadata.put(byteKey, request.toByteArray());
HelloRequest request2 = metadata.get(protoKey);
assertThat(request2).isNotNull();
assertThat(request2.getName()).isEqualTo("World");
}
示例12: interceptCall
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
final Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
String token = requestHeaders.get(authKey);
String principal = null;
if (StringUtils.isEmpty(token))
{
logger.warn("Failed to find token");
}
else
{
Map<String,String> tokenParams = new HashMap<>();
tokenParams.put(OAuth2AccessToken.ACCESS_TOKEN,token);
OAuth2AccessToken otoken = DefaultOAuth2AccessToken.valueOf(tokenParams);
OAuth2Authentication auth = server.getTokenStore().readAuthentication(otoken);
if (auth != null && auth.isAuthenticated())
{
logger.debug("Principal:"+auth.getPrincipal());
principal = auth.getPrincipal().toString();
}
else
{
logger.warn("Failed to authenticate token "+token);
}
}
return new MessagePrincipalListener<ReqT>(next.startCall(call, requestHeaders),principal,server);
}
示例13: toErrorReporter
import io.grpc.Metadata; //導入方法依賴的package包/類
private static ErrorReporter toErrorReporter(Exception ex) {
Metadata trailers = Status.trailersFromThrowable(ex);
ErrorDetails errorDetails = trailers.get(errorDetailsKey);
Status status = Status.fromThrowable(ex);
Throwable throwable = null;
if(errorDetails.getDetailedMessageList().size() > 0){
throwable = new Throwable(errorDetails.getDetailedMessage(0));
}
switch (status.getCode()) {
case FAILED_PRECONDITION:
return ErrorReporter.FUNCTION.withCause(throwable)
.withSpecificErrorCode(errorDetails.getSpecificCode())
.withSpecificErrorMsg(errorDetails.getSpecificMessage());
case UNAVAILABLE:
return ErrorReporter.UNAVAILABLE.withCause(throwable)
.withSpecificErrorCode(errorDetails.getSpecificCode())
.withSpecificErrorMsg(errorDetails.getSpecificMessage());
case INTERNAL:
return ErrorReporter.INTERNAL.withCause(throwable)
.withSpecificErrorCode(errorDetails.getSpecificCode())
.withSpecificErrorMsg(errorDetails.getSpecificMessage());
default:
return ErrorReporter.UNKNOWN.withCause(throwable)
.withSpecificErrorCode(errorDetails.getSpecificCode())
.withSpecificErrorMsg(errorDetails.getSpecificMessage());
}
}
示例14: return_metadata_containing_error
import io.grpc.Metadata; //導入方法依賴的package包/類
@SuppressWarnings("ConstantConditions") // A part of the test.
@Test
public void return_metadata_containing_error() throws InvalidProtocolBufferException {
final Error error = Error.getDefaultInstance();
final Metadata metadata = MetadataConverter.toMetadata(error);
final byte[] bytes = metadata.get(MetadataConverter.KEY);
assertEquals(error, Error.parseFrom(bytes));
}
示例15: interceptCall
import io.grpc.Metadata; //導入方法依賴的package包/類
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
RequestMetadata meta = headers.get(METADATA_KEY);
if (meta == null) {
throw new IllegalStateException("RequestMetadata not received from the client.");
}
Context ctx = Context.current().withValue(CONTEXT_KEY, meta);
return Contexts.interceptCall(ctx, call, headers, next);
}