當前位置: 首頁>>代碼示例>>Java>>正文


Java Metadata類代碼示例

本文整理匯總了Java中io.grpc.Metadata的典型用法代碼示例。如果您正苦於以下問題:Java Metadata類的具體用法?Java Metadata怎麽用?Java Metadata使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Metadata類屬於io.grpc包,在下文中一共展示了Metadata類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: startServer

import io.grpc.Metadata; //導入依賴的package包/類
@BeforeClass
public static void startServer() throws IOException {
    AfricasTalking.initialize(Fixtures.USERNAME, Fixtures.API_KEY);
    server = new Server(new Authenticator() {
        @Override
        public boolean authenticate(String client) {
            return client.compareToIgnoreCase(TEST_CLIENT_ID) == 0;
        }
    });
    server.addSipCredentials("test", "secret", "sip://at.dev");
    server.start(certFile, privateKeyFile, TEST_PORT);
    
    ManagedChannel ch = NettyChannelBuilder.forAddress("localhost", TEST_PORT)
        .sslContext(GrpcSslContexts.forClient().trustManager(certFile).build())
        .build();

        
    client = SdkServerServiceGrpc.newBlockingStub(ch)
        .withCallCredentials(new CallCredentials(){
            @Override
            public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor,
                    final MetadataApplier applier) {
                        appExecutor.execute(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    Metadata headers = new Metadata();
                                    Metadata.Key<String> clientIdKey = Metadata.Key.of("X-Client-Id", Metadata.ASCII_STRING_MARSHALLER);
                                    headers.put(clientIdKey, TEST_CLIENT_ID);
                                    applier.apply(headers);
                                } catch(Throwable ex) {
                                    applier.fail(Status.UNAUTHENTICATED.withCause(ex));
                                }
                            }
                        });
                
            }
        });
}
 
開發者ID:aksalj,項目名稱:africastalking-java,代碼行數:40,代碼來源:ATServerTest.java

示例2: metadataInterceptor

import io.grpc.Metadata; //導入依賴的package包/類
private ClientInterceptor metadataInterceptor() {
  ClientInterceptor interceptor = new ClientInterceptor() {
    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        final io.grpc.MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {
      return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
        @Override
        protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
            throws StatusException {
          for (ConfigProto.CallMetadataEntry entry : callConfiguration.getMetadataList()) {
            Metadata.Key<String> key = Metadata.Key.of(entry.getName(), Metadata.ASCII_STRING_MARSHALLER);
            headers.put(key, entry.getValue());
          }
          delegate().start(responseListener, headers);
        }
      };
    }
  };

  return interceptor;
}
 
開發者ID:grpc-ecosystem,項目名稱:polyglot,代碼行數:22,代碼來源:ChannelFactory.java

示例3: 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

示例4: copyThreadLocalToMetadata

import io.grpc.Metadata; //導入依賴的package包/類
private void copyThreadLocalToMetadata(Metadata headers) {
  Map<String, String> attachments = RpcContext.getContext().getAttachments();
  Map<String, Object> values = RpcContext.getContext().get();
  try {
    if (!attachments.isEmpty()) {
      headers.put(GrpcUtil.GRPC_CONTEXT_ATTACHMENTS, SerializerUtil.toJson(attachments));
    }
    if (!values.isEmpty()) {
      headers.put(GrpcUtil.GRPC_CONTEXT_VALUES, SerializerUtil.toJson(values));
    }
  } catch (Throwable e) {
    log.error(e.getMessage(), e);
  } finally {
    RpcContext.removeContext();
  }
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:17,代碼來源:HeaderClientInterceptor.java

示例5: statusError

import io.grpc.Metadata; //導入依賴的package包/類
private void statusError(Status status, Metadata trailers) {
  if (enabledRetry) {
    final NameResolverNotify nameResolverNotify = this.createNameResolverNotify();
    boolean retryHaveDone = this.retryHaveDone();
    if (retryHaveDone) {
      completionFuture.setException(status.asRuntimeException(trailers));
    } else {
      nameResolverNotify.refreshChannel();
      scheduleRetryService.execute(this);
      SocketAddress remoteAddress =
          (SocketAddress) callOptions.getOption(GrpcCallOptions.CALLOPTIONS_CUSTOME_KEY)
              .get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY);
      logger.error(String.format("Retrying failed call. Failure #%d,Failure Server: %s",
          currentRetries.get(), String.valueOf(remoteAddress)));
      currentRetries.getAndIncrement();
    }
  } else {
    completionFuture.setException(status.asRuntimeException(trailers));
  }

}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:22,代碼來源:FailOverUnaryFuture.java

示例6: interceptCall

import io.grpc.Metadata; //導入依賴的package包/類
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        Metadata headers,
        ServerCallHandler<ReqT, RespT> next) {
    if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(key,
                "anonymousUser", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));

        log.debug("Populated SecurityContextHolder with anonymous token: {}",
                SecurityContextHolder.getContext().getAuthentication());
    } else {
        log.debug("SecurityContextHolder not populated with anonymous token, as it already contained: {}",
                SecurityContextHolder.getContext().getAuthentication());
    }

    return next.startCall(call, headers);
}
 
開發者ID:revinate,項目名稱:grpc-spring-security-demo,代碼行數:19,代碼來源:AnonymousAuthenticationInterceptor.java

示例7: interceptCall

import io.grpc.Metadata; //導入依賴的package包/類
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
        final Channel next) {
    return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
            next.newCall(method, callOptions)) {
        @Override
        protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
                throws StatusException {
            Metadata cachedSaved;
            URI uri = serviceUri(next, method);
            synchronized (this) {
                Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                if (mLastMetadata == null || mLastMetadata != latestMetadata) {
                    mLastMetadata = latestMetadata;
                    mCached = toHeaders(mLastMetadata);
                }
                cachedSaved = mCached;
            }
            headers.merge(cachedSaved);
            delegate().start(responseListener, headers);
        }
    };
}
 
開發者ID:hsavaliya,項目名稱:GoogleAssistantSDK,代碼行數:25,代碼來源:SpeechService.java

示例8: JSON_MARSHALLER

import io.grpc.Metadata; //導入依賴的package包/類
/**
 * A metadata marshaller that encodes objects as JSON using the google-gson library.
 *
 * <p>All non-ascii characters are unicode escaped to comply with {@code AsciiMarshaller}'s character range
 * requirements.
 *
 * @param clazz the type to serialize
 * @param <T>
 */
public static final <T> Metadata.AsciiMarshaller<T> JSON_MARSHALLER(Class<T> clazz) {
    return new Metadata.AsciiMarshaller<T>() {
        TypeToken<T> typeToken = TypeToken.of(clazz);
        private Gson gson = new Gson();

        @Override
        public String toAsciiString(T value) {
            try {
                try (StringWriter sw = new StringWriter()) {
                    gson.toJson(value, typeToken.getType(), new UnicodeEscapingAsciiWriter(sw));
                    return sw.toString();
                }
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        public T parseAsciiString(String serialized) {
            return gson.fromJson(serialized, typeToken.getType());
        }
    };
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:33,代碼來源:MoreMetadata.java

示例9: PROTOBUF_MARSHALLER

import io.grpc.Metadata; //導入依賴的package包/類
/**
 * A metadata marshaller that encodes objects as protobuf according to their proto IDL specification.
 *
 * @param clazz the type to serialize
 * @param <T>
 */
public static <T extends GeneratedMessageV3> Metadata.BinaryMarshaller<T> PROTOBUF_MARSHALLER(Class<T> clazz) {
    try {
        Method defaultInstance = clazz.getMethod("getDefaultInstance");
        GeneratedMessageV3 instance = (GeneratedMessageV3) defaultInstance.invoke(null);

        return new Metadata.BinaryMarshaller<T>() {
            @Override
            public byte[] toBytes(T value) {
                return value.toByteArray();
            }

            @SuppressWarnings("unchecked")
            @Override
            public T parseBytes(byte[] serialized) {
                try {
                    return (T) instance.getParserForType().parseFrom(serialized);
                } catch (InvalidProtocolBufferException ipbe) {
                    throw new IllegalArgumentException(ipbe);
                }
            }
        };
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    }
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:32,代碼來源:MoreMetadata.java

示例10: interceptorShouldFreezeContext

import io.grpc.Metadata; //導入依賴的package包/類
@Test
public void interceptorShouldFreezeContext() {
    TestService svc = new TestService();

    // Plumbing
    serverRule.getServiceRegistry().addService(ServerInterceptors.interceptForward(svc,
            new AmbientContextServerInterceptor("ctx-"),
            new AmbientContextFreezeServerInterceptor()));
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc
            .newBlockingStub(serverRule.getChannel())
            .withInterceptors(new AmbientContextClientInterceptor("ctx-"));

    // Test
    Metadata.Key<String> key = Metadata.Key.of("ctx-k", Metadata.ASCII_STRING_MARSHALLER);
    AmbientContext.initialize(Context.current()).run(() -> {
        AmbientContext.current().put(key, "value");
        stub.sayHello(HelloRequest.newBuilder().setName("World").build());
    });

    assertThat(svc.frozen).isTrue();
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:22,代碼來源:AmbientContextFreezeInterceptorTest.java

示例11: jsonMarshallerRoundtrip

import io.grpc.Metadata; //導入依賴的package包/類
@Test
public void jsonMarshallerRoundtrip() {
    Foo foo = new Foo();
    foo.country = "France";
    List<Bar> bars = new ArrayList<>();
    Bar bar1 = new Bar();
    bar1.cheese = "Brë";
    bar1.age = 2;
    bars.add(bar1);
    Bar bar2 = new Bar();
    bar2.cheese = "Guda<>'";
    bar2.age = 4;
    bars.add(bar2);
    foo.bars = bars;

    Metadata.AsciiMarshaller<Foo> marshaller = MoreMetadata.JSON_MARSHALLER(Foo.class);
    String str = marshaller.toAsciiString(foo);
    assertThat(str).doesNotContain("ë");

    Foo foo2 = marshaller.parseAsciiString(str);
    assertThat(foo2).isEqualTo(foo);
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:23,代碼來源:MoreMetadataTest.java

示例12: interceptCall

import io.grpc.Metadata; //導入依賴的package包/類
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method,
                                                           CallOptions callOptions, final Channel next) {
    return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
            next.newCall(method, callOptions)) {
        @Override
        protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
                throws StatusException {

            Metadata cachedSaved;
            URI uri = serviceUri(next, method);
            synchronized (GoogleCredentialsInterceptor.this) {
                Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                if (mLastMetadata == null || mLastMetadata != latestMetadata) {
                    mLastMetadata = latestMetadata;
                    mCached = toHeaders(mLastMetadata);
                }
                cachedSaved = mCached;
            }
            headers.merge(cachedSaved);
            delegate().start(responseListener, headers);
        }
    };
}
 
開發者ID:brandall76,項目名稱:Saiy-PS,代碼行數:25,代碼來源:GoogleCredentialsInterceptor.java

示例13: interceptCall

import io.grpc.Metadata; //導入依賴的package包/類
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      getToken(next).ifPresent(t -> headers.put(TOKEN, t));
      super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {
        @Override
        public void onClose(Status status, Metadata trailers) {
          if (isInvalidTokenError(status)) {
            try {
              refreshToken(next);
            } catch (Exception e) {
              // don't throw any error here.
              // rpc will retry on expired auth token.
            }
          }
          super.onClose(status, trailers);
        }
      }, headers);
    }
  };
}
 
開發者ID:coreos,項目名稱:jetcd,代碼行數:25,代碼來源:ClientConnectionManager.java

示例14: newCall

import io.grpc.Metadata; //導入依賴的package包/類
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT>
    newCall(MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) {
  final Context timerContext = timer.time();
  final AtomicBoolean decremented = new AtomicBoolean(false);
  return new CheckedForwardingClientCall<ReqT, RespT>(delegate.newCall(methodDescriptor, callOptions)) {
    @Override
    protected void checkedStart(ClientCall.Listener<RespT> responseListener, Metadata headers)
        throws Exception {
      ClientCall.Listener<RespT> timingListener = wrap(responseListener, timerContext, decremented);
      getStats().ACTIVE_RPC_COUNTER.inc();
      getStats().RPC_METER.mark();
      delegate().start(timingListener, headers);
    }

    @Override
    public void cancel(String message, Throwable cause) {
      if (!decremented.getAndSet(true)) {
        getStats().ACTIVE_RPC_COUNTER.dec();
      }
      super.cancel(message, cause);
    }
  };
}
 
開發者ID:benson-git,項目名稱:ibole-microservice,代碼行數:25,代碼來源:ChannelPool.java

示例15: toException

import io.grpc.Metadata; //導入依賴的package包/類
private static Exception toException(ErrorReporter errorReport) {
  Metadata trailers = new Metadata();
  trailers.put(errorDetailsKey, errorReport.toErrorDetails());
  switch (errorReport.getGeneralCode()) {
    case FUNCTION:
      return Status.FAILED_PRECONDITION.withCause(errorReport.getCause())
          .withDescription(errorReport.getSpecificErrorMsg()).asException(trailers);
    case UNAVAILABLE:
      return Status.UNAVAILABLE.withCause(errorReport.getCause())
          .withDescription(errorReport.getSpecificErrorMsg()).asRuntimeException(trailers);
    case INTERNAL:
      return Status.INTERNAL.withCause(errorReport.getCause())
          .withDescription(errorReport.getSpecificErrorMsg()).asRuntimeException(trailers);
    default:
      return Status.UNKNOWN.withCause(errorReport.getCause())
          .withDescription(errorReport.getSpecificErrorMsg()).asRuntimeException(trailers);
  }
}
 
開發者ID:benson-git,項目名稱:ibole-microservice,代碼行數:19,代碼來源:ServerErrorHandler.java


注:本文中的io.grpc.Metadata類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。