当前位置: 首页>>代码示例>>Java>>正文


Java Metadata.get方法代码示例

本文整理汇总了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);
  }
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:21,代码来源:HeaderServerInterceptor.java

示例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);
    }
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:23,代码来源:MetadataConverter.java

示例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);
	}
}
 
开发者ID:SeldonIO,项目名称:seldon-server,代码行数:26,代码来源:ExternalRpcServer.java

示例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);
}
 
开发者ID:apache,项目名称:incubator-skywalking,代码行数:27,代码来源:ServerCallOnReadyInterceptor.java

示例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);
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:21,代码来源:CensusStatsModule.java

示例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");
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:22,代码来源:Http2ClientStreamTransportState.java

示例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);
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:27,代码来源:ClientCallImplTest.java

示例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);
}
 
开发者ID:aksalj,项目名称:africastalking-java,代码行数:11,代码来源:Server.java

示例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);
}
 
开发者ID:salesforce,项目名称:grpc-java-contrib,代码行数:12,代码来源:MoreMetadataTest.java

示例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);
}
 
开发者ID:salesforce,项目名称:grpc-java-contrib,代码行数:14,代码来源:MoreMetadataTest.java

示例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");
}
 
开发者ID:salesforce,项目名称:grpc-java-contrib,代码行数:14,代码来源:MoreMetadataTest.java

示例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);
  }
 
开发者ID:SeldonIO,项目名称:seldon-core,代码行数:30,代码来源:HeaderServerInterceptor.java

示例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());
  }
}
 
开发者ID:benson-git,项目名称:ibole-microservice,代码行数:28,代码来源:ClientErrorHandler.java

示例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));
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:9,代码来源:MetadataConverterShould.java

示例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);
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:11,代码来源:TracingMetadataUtils.java


注:本文中的io.grpc.Metadata.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。