Java 类io.grpc.Channel 实例源码

项目:saluki    文件:AbstractClientInvocation.java   
private Object unaryCall(GrpcRequest request, Channel channel) {
  String serviceName = request.getServiceName();
  String methodName = request.getMethodName();
  GrpcURL refUrl = request.getRefUrl();
  Integer retryOption = this.buildRetryOption(methodName, refUrl);
  GrpcUnaryClientCall clientCall = GrpcUnaryClientCall.create(channel, retryOption, refUrl);
  GrpcHystrixCommand hystrixCommand = null;
  Boolean isEnableFallback = this.buildFallbackOption(methodName, refUrl);
  switch (request.getCallType()) {
    case Constants.RPCTYPE_ASYNC:
      hystrixCommand = new GrpcFutureUnaryCommand(serviceName, methodName, isEnableFallback);
      break;
    case Constants.RPCTYPE_BLOCKING:
      hystrixCommand = new GrpcBlockingUnaryCommand(serviceName, methodName, isEnableFallback);
      break;
    default:
      hystrixCommand = new GrpcFutureUnaryCommand(serviceName, methodName, isEnableFallback);
      break;
  }
  hystrixCommand.setClientCall(clientCall);
  hystrixCommand.setRequest(request);
  hystrixCommand.setClientServerMonitor(monitor);
  return hystrixCommand.execute();

}
项目:GoogleAssistantSDK    文件:SpeechService.java   
@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);
        }
    };
}
项目:grpc-java-contrib    文件:TimeClient.java   
public static void main(String[] args) throws Exception {
    String host = args[0];
    int port = Integer.parseInt(args[1]);

    String abstractName = "mesh://timeService";

    // Open a channel to the server
    Channel channel = ManagedChannelBuilder
            .forTarget(abstractName)
            .nameResolverFactory(StaticResolver.factory(new InetSocketAddress(host, port)))
            .usePlaintext(true)
            .build();

    // Create a CompletableFuture-based stub
    TimeServiceGrpc8.TimeServiceCompletableFutureStub stub = TimeServiceGrpc8.newCompletableFutureStub(channel);

    // Call the service
    CompletableFuture<TimeReply> completableFuture = stub.getTime(Empty.getDefaultInstance());
    TimeReply timeReply = completableFuture.get();

    // Convert to JDK8 types
    Instant now = MoreTimestamps.toInstantUtc(timeReply.getTime());
    System.out.println("The time is " + now);
}
项目:grpc-java-contrib    文件:CompletableFutureStubTest.java   
@Test
public void AbstractStubFeaturesShouldPropagate() throws Exception {
    com.google.common.base.Preconditions.checkArgument(true);
    Channel channel = InProcessChannelBuilder.forName("ignore").build();
    com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub stub = com.salesforce.jprotoc.GreeterGrpc8
                    .newCompletableFutureStub(channel)
                    .withCompression("bz2")
                    .withMaxInboundMessageSize(42);

    Field innerStubField = com.salesforce.jprotoc.GreeterGrpc8.GreeterCompletableFutureStub.class.getDeclaredField("innerStub");
    innerStubField.setAccessible(true);
    com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub innerStub = (com.salesforce.jprotoc.GreeterGrpc.GreeterFutureStub) innerStubField.get(stub);

    assertEquals("bz2", stub.getCallOptions().getCompressor());
    assertEquals(new Integer(42), stub.getCallOptions().getMaxInboundMessageSize());

    assertEquals("bz2", innerStub.getCallOptions().getCompressor());
    assertEquals(new Integer(42), innerStub.getCallOptions().getMaxInboundMessageSize());

    assertEquals(stub.getCallOptions().toString(), innerStub.getCallOptions().toString());
}
项目:black-mirror    文件:SpeechService.java   
@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);
        }
    };
}
项目:dble    文件:AlarmAppender.java   
/**
 * if the config is rollback the config of dbleAppender should be rollback too
 */
public static void rollbackConfig() {
    if (stub == null && (grpcUrlOld == null && "".equals(grpcUrlOld))) {
        grpcUrl = grpcUrlOld;
        serverId = serverIdOld;
        alertComponentId = alertComponentIdOld;
        port = portOld;
        grpcUrl = grpcUrlOld;
        grpcLevel = grpcLevelOld;
        return;
    } else {
        grpcUrl = grpcUrlOld;
        serverId = serverIdOld;
        alertComponentId = alertComponentIdOld;
        port = portOld;
        grpcUrl = grpcUrlOld;
        try {
            Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build();
            stub = UcoreGrpc.newBlockingStub(channel);
        } catch (Exception e) {
            return;
        }
    }
}
项目:bazel-buildfarm    文件:ByteStreamUploader.java   
/**
 * Creates a new instance.
 *
 * @param instanceName the instance name to be prepended to resource name of the {@code Write}
 *     call. See the {@code ByteStream} service definition for details
 * @param channel the {@link io.grpc.Channel} to use for calls
 * @param callCredentials the credentials to use for authentication. May be {@code null}, in which
 *     case no authentication is performed
 * @param callTimeoutSecs the timeout in seconds after which a {@code Write} gRPC call must be
 *     complete. The timeout resets between retries
 * @param retrier the {@link Retrier} whose backoff strategy to use for retry timings.
 * @param retryService the executor service to schedule retries on. It's the responsibility of the
 *     caller to properly shutdown the service after use. Users should avoid shutting down the
 *     service before {@link #shutdown()} has been called
 */
public ByteStreamUploader(
    @Nullable String instanceName,
    Channel channel,
    @Nullable CallCredentials callCredentials,
    long callTimeoutSecs,
    Retrier retrier,
    ListeningScheduledExecutorService retryService) {
  checkArgument(callTimeoutSecs > 0, "callTimeoutSecs must be gt 0.");

  this.instanceName = instanceName;
  this.channel = channel;
  this.callCredentials = callCredentials;
  this.callTimeoutSecs = callTimeoutSecs;
  this.retrier = retrier;
  this.retryService = retryService;
}
项目:Saiy-PS    文件:GoogleCredentialsInterceptor.java   
@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);
        }
    };
}
项目:polyglot    文件:ChannelFactory.java   
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;
}
项目:jetcd    文件:ClientConnectionManager.java   
/**
 * get token from etcd with name and password.
 *
 * @param channel channel to etcd
 * @param username auth name
 * @param password auth password
 * @return authResp
 */
private ListenableFuture<AuthenticateResponse> authenticate(
    Channel channel, ByteSequence username, ByteSequence password) {

  ByteString user = byteStringFromByteSequence(username);
  ByteString pass = byteStringFromByteSequence(password);

  checkArgument(!user.isEmpty(), "username can not be empty.");
  checkArgument(!pass.isEmpty(), "password can not be empty.");

  return AuthGrpc.newFutureStub(channel).authenticate(
      AuthenticateRequest.newBuilder()
          .setNameBytes(user)
          .setPasswordBytes(pass)
          .build()
  );
}
项目:jetcd    文件:ClientConnectionManager.java   
/**
 * get token with ClientBuilder.
 *
 * @return the auth token
 * @throws com.coreos.jetcd.exception.EtcdException a exception indicates failure reason.
 */
private Optional<String> generateToken(Channel channel) {

  if (builder.user() != null && builder.password() != null) {
    try {
      return Optional.of(
          authenticate(channel, builder.user(), builder.password()).get().getToken()
      );
    } catch (InterruptedException ite) {
      throw handleInterrupt(ite);
    } catch (ExecutionException exee) {
      throw toEtcdException(exee);
    }
  }
  return Optional.empty();
}
项目:jetcd    文件:ClientConnectionManager.java   
@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);
    }
  };
}
项目:bohpien-hsm-service    文件:DigestTest.java   
@BeforeClass
public void beforeClass() throws IOException, DuplicateSessionException {
    /* create and start service */
    final int port = 8080;
    final ServiceRunner service = new ServiceRunner.Builder()
            .setSessionProvider(sessionProvider)
            .setPort(port)
            .build();
    thread = new Thread(service);
    thread.start();

    /* create client */
    final Channel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port)
            .usePlaintext(true).build();
    client = DigestServiceGrpc.newBlockingStub(channel);

    /* register session id */
    sessionId = sessionProvider.createSession(userId);
}
项目:fabric-java    文件:MemberServiceImpl.java   
public MemberServiceImpl(String host, int port, Crypto crypto) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(port);

    InetAddress address = null;
    try {
        address = InetAddress.getByName(host);
    } catch (UnknownHostException e) {
        logger.error("Create member service failed by unknown host exception", e);
        Throwables.propagate(e);
    }

    final Channel channel = NettyChannelBuilder
            .forAddress(new InetSocketAddress(address, port))
            .negotiationType(NegotiationType.PLAINTEXT)
            .build();

    initializeStubs(channel);
    this.crypto = crypto;
}
项目:android-docs-samples    文件:SpeechService.java   
@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);
        }
    };
}
项目:thingsboard    文件:RpcSessionActor.java   
private void initSession(RpcSessionCreateRequestMsg msg) {
    log.info("[{}] Initializing session", context().self());
    ServerAddress remoteServer = msg.getRemoteAddress();
    listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self());
    if (msg.getRemoteAddress() == null) {
        // Server session
        session = new GrpcSession(listener);
        session.setOutputStream(msg.getResponseObserver());
        session.initInputStream();
        session.initOutputStream();
        systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream());
    } else {
        // Client session
        Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort()).usePlaintext(true).build();
        session = new GrpcSession(remoteServer, listener);
        session.initInputStream();

        ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel);
        StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub.handlePluginMsgs(session.getInputStream());

        session.setOutputStream(outputStream);
        session.initOutputStream();
        outputStream.onNext(toConnectMsg());
    }
}
项目:cloud-bigtable-client    文件:UnaryCallRetryInterceptor.java   
public UnaryCallRetryInterceptor(
    Channel delegate,
    ScheduledExecutorService executorService,
    Set<MethodDescriptor<?, ?>> retriableMethods,
    int initialBackoffMillis,
    double backoffMultiplier,
    int maxElapsedBackoffMillis) {
  this(
      delegate,
      executorService,
      Maps.asMap(retriableMethods, new Function<MethodDescriptor<?, ?>, Predicate<?>>() {
        @Override
        public Predicate<Object> apply(MethodDescriptor<?, ?> methodDescriptor) {
          return Predicates.alwaysTrue();
        }
      }),
      initialBackoffMillis,
      backoffMultiplier,
      maxElapsedBackoffMillis);
}
项目:cloud-bigtable-client    文件:BigtableChannels.java   
/**
 * Given a channel, create a CloseableChannel that invokces onClientClose when the close
 * method is invoked.
 */
private static CloseableChannel createCloseableChannel(
    final Channel channel, final ClientCloseHandler onClientClose) {
  return new CloseableChannel() {
    @Override
    public void close() throws IOException {
      onClientClose.close();
    }

    @Override
    public <ReqT, RespT> Call<ReqT, RespT> newCall(
        MethodDescriptor<ReqT, RespT> methodDescriptor) {
      return channel.newCall(methodDescriptor);
    }
  };
}
项目:java-docs-samples    文件:HelloWorldClient.java   
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) {
  LOGGER.info("Intercepted " + method.getFullMethodName());
  ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);

  call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      if (apiKey != null && !apiKey.isEmpty()) {
        LOGGER.info("Attaching API Key: " + apiKey);
        headers.put(API_KEY_HEADER, apiKey);
      }
      super.start(responseListener, headers);
    }
  };
  return call;
}
项目:java-docs-samples    文件:BookstoreClient.java   
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) {
  LOGGER.info("Intercepted " + method.getFullMethodName());
  ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);

  call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      if (apiKey != null && !apiKey.isEmpty()) {
        LOGGER.info("Attaching API Key: " + apiKey);
        headers.put(API_KEY_HEADER, apiKey);
      }
      if (authToken != null && !authToken.isEmpty()) {
        System.out.println("Attaching auth token");
        headers.put(AUTHORIZATION_HEADER, "Bearer " + authToken);
      }
      super.start(responseListener, headers);
    }
  };
  return call;
}
项目:abelana    文件:AbelanaClient.java   
/**
 * Initializes a connection to the gRPC server.
 * @return a boolean indicating the success.
 */
private boolean initServerConnection() {
    if(!mConnected) {
        mInterceptor = new AuthHeaderClientInterceptor(
                getUserIdToken());
        try {
            mChannelImpl = OkHttpChannelBuilder
                    .forAddress(AndroidConstants.HOST,
                            AndroidConstants.PORT)
                    .build();
            Channel mOriginChannel = ClientInterceptors
                    .intercept(mChannelImpl, mInterceptor);
            mBlockingStub = AbelanaGrpc.newBlockingStub(mOriginChannel);
            mConnected = true;
        } catch (RuntimeException e) {
            mConnected = false;
        }
    }
    return mConnected;
}
项目:bazel    文件:GrpcRemoteCache.java   
@VisibleForTesting
public GrpcRemoteCache(
    Channel channel,
    CallCredentials credentials,
    RemoteOptions options,
    RemoteRetrier retrier,
    DigestUtil digestUtil) {
  super(digestUtil);
  this.options = options;
  this.credentials = credentials;
  this.channel = channel;
  this.retrier = retrier;

  uploader = new ByteStreamUploader(options.remoteInstanceName, channel, credentials,
      options.remoteTimeout, retrier, retryScheduler);
}
项目:bazel    文件:ByteStreamUploader.java   
/**
 * Creates a new instance.
 *
 * @param instanceName the instance name to be prepended to resource name of the {@code Write}
 *     call. See the {@code ByteStream} service definition for details
 * @param channel the {@link io.grpc.Channel} to use for calls
 * @param callCredentials the credentials to use for authentication. May be {@code null}, in which
 *     case no authentication is performed
 * @param callTimeoutSecs the timeout in seconds after which a {@code Write} gRPC call must be
 *     complete. The timeout resets between retries
 * @param retrier the {@link RemoteRetrier} whose backoff strategy to use for retry timings.
 * @param retryService the executor service to schedule retries on. It's the responsibility of the
 *     caller to properly shutdown the service after use. Users should avoid shutting down the
 *     service before {@link #shutdown()} has been called
 */
public ByteStreamUploader(
    @Nullable String instanceName,
    Channel channel,
    @Nullable CallCredentials callCredentials,
    long callTimeoutSecs,
    RemoteRetrier retrier,
    ListeningScheduledExecutorService retryService) {
  checkArgument(callTimeoutSecs > 0, "callTimeoutSecs must be gt 0.");

  this.instanceName = instanceName;
  this.channel = channel;
  this.callCredentials = callCredentials;
  this.callTimeoutSecs = callTimeoutSecs;
  this.retrier = retrier;
  this.retryService = retryService;
}
项目:grpc-java    文件:ClientAuthInterceptor.java   
/**
 * Generate a JWT-specific service URI. The URI is simply an identifier with enough information
 * for a service to know that the JWT was intended for it. The URI will commonly be verified with
 * a simple string equality check.
 */
private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException {
  String authority = channel.authority();
  if (authority == null) {
    throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException();
  }
  // Always use HTTPS, by definition.
  final String scheme = "https";
  final int defaultPort = 443;
  String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName());
  URI uri;
  try {
    uri = new URI(scheme, authority, path, null, null);
  } catch (URISyntaxException e) {
    throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth")
        .withCause(e).asException();
  }
  // The default port must not be present. Alternative ports should be present.
  if (uri.getPort() == defaultPort) {
    uri = removePort(uri);
  }
  return uri;
}
项目:grpc-java    文件:AsyncClient.java   
private List<Histogram> doBenchmark(SimpleRequest req,
                                    List<? extends Channel> channels,
                                    long endTime) throws Exception {
  // Initiate the concurrent calls
  List<Future<Histogram>> futures =
      new ArrayList<Future<Histogram>>(config.outstandingRpcsPerChannel);
  for (int i = 0; i < config.channels; i++) {
    for (int j = 0; j < config.outstandingRpcsPerChannel; j++) {
      Channel channel = channels.get(i);
      futures.add(doRpcs(channel, req, endTime));
    }
  }
  // Wait for completion
  List<Histogram> histograms = new ArrayList<Histogram>(futures.size());
  for (Future<Histogram> future : futures) {
    histograms.add(future.get());
  }
  return histograms;
}
项目:grpc-java    文件:BinaryLogProvider.java   
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method,
    CallOptions callOptions,
    Channel next) {
  ClientInterceptor binlogInterceptor = getClientInterceptor(method.getFullMethodName());
  if (binlogInterceptor == null) {
    return next.newCall(method, callOptions);
  } else {
    return InternalClientInterceptors
        .wrapClientInterceptor(
            binlogInterceptor,
            IDENTITY_MARSHALLER,
            IDENTITY_MARSHALLER)
        .interceptCall(method, callOptions, next);
  }
}
项目:grpc-java    文件:CensusStatsModule.java   
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  // New RPCs on client-side inherit the tag context from the current Context.
  TagContext parentCtx = tagger.getCurrentTagContext();
  final ClientCallTracer tracerFactory =
      newClientCallTracer(parentCtx, method.getFullMethodName(),
          recordStartedRpcs, recordFinishedRpcs);
  ClientCall<ReqT, RespT> call =
      next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory));
  return new SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      delegate().start(
          new SimpleForwardingClientCallListener<RespT>(responseListener) {
            @Override
            public void onClose(Status status, Metadata trailers) {
              tracerFactory.callEnded(status);
              super.onClose(status, trailers);
            }
          },
          headers);
    }
  };
}
项目:grpc-java    文件:CensusTracingModule.java   
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  // New RPCs on client-side inherit the tracing context from the current Context.
  // Safe usage of the unsafe trace API because CONTEXT_SPAN_KEY.get() returns the same value
  // as Tracer.getCurrentSpan() except when no value available when the return value is null
  // for the direct access and BlankSpan when Tracer API is used.
  final ClientCallTracer tracerFactory = newClientCallTracer(CONTEXT_SPAN_KEY.get(), method);
  ClientCall<ReqT, RespT> call =
      next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory));
  return new SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      delegate().start(
          new SimpleForwardingClientCallListener<RespT>(responseListener) {
            @Override
            public void onClose(io.grpc.Status status, Metadata trailers) {
              tracerFactory.callEnded(status);
              super.onClose(status, trailers);
            }
          },
          headers);
    }
  };
}
项目:grpc-java    文件:BinaryLogProviderTest.java   
@Test
public void wrapChannel_methodDescriptor() throws Exception {
  final AtomicReference<MethodDescriptor<?, ?>> methodRef =
      new AtomicReference<MethodDescriptor<?, ?>>();
  Channel channel = new Channel() {
    @Override
    public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
        MethodDescriptor<RequestT, ResponseT> method, CallOptions callOptions) {
      methodRef.set(method);
      return new NoopClientCall<RequestT, ResponseT>();
    }

    @Override
    public String authority() {
      throw new UnsupportedOperationException();
    }
  };
  Channel wChannel = binlogProvider.wrapChannel(channel);
  ClientCall<String, Integer> ignoredClientCall = wChannel.newCall(method, CallOptions.DEFAULT);
  validateWrappedMethod(methodRef.get());
}
项目:grpc-mate    文件:EchoServiceTest.java   
@Before
public void setUp() throws Exception {
  faker = new Faker();
  Injector injector = Guice.createInjector();
  EchoService echoService = injector.getInstance(EchoService.class);
  ServiceInterceptor serviceInterceptor = injector.getInstance(ServiceInterceptor.class);
  CallerInterceptor callerInterceptor = injector.getInstance(CallerInterceptor.class);

  grpcServerRule.getServiceRegistry().addService(ServerInterceptors.intercept(echoService, serviceInterceptor));
  Channel channel = ClientInterceptors.intercept(
      grpcServerRule.getChannel(),
      callerInterceptor);
  stub = EchoServiceGrpc.newBlockingStub(channel);
}
项目:saluki    文件:GrpcStubClient.java   
@SuppressWarnings("unchecked")
@Override
public AbstractStub getGrpcClient(ChannelCall channelPool, int callType, int callTimeout) {
  String stubClassName = GrpcStubClient.this.getStubClassName();
  Channel channel = null;
  if (StringUtils.contains(stubClassName, "$")) {
    try {
      String parentName = StringUtils.substringBefore(stubClassName, "$");
      Class<?> clzz = ReflectUtils.name2class(parentName);
      Method method;
      switch (callType) {
        case Constants.RPCTYPE_ASYNC:
          method = clzz.getMethod("newFutureStub", io.grpc.Channel.class);
          break;
        case Constants.RPCTYPE_BLOCKING:
          method = clzz.getMethod("newBlockingStub", io.grpc.Channel.class);
          break;
        default:
          method = clzz.getMethod("newFutureStub", io.grpc.Channel.class);
          break;
      }
      channel = channelPool.getChannel(refUrl);
      AbstractStub stubInstance = (AbstractStub) method.invoke(null, channel);
      return stubInstance;
    } catch (Exception e) {
      throw new IllegalArgumentException(
          "stub definition not correct,do not edit proto generat file", e);
    }
  } else {
    throw new IllegalArgumentException(
        "stub definition not correct,do not edit proto generat file");
  }
}
项目:saluki    文件:AbstractClientInvocation.java   
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  if (ReflectUtils.isToStringMethod(method)) {
    return AbstractClientInvocation.this.toString();
  } else {
    GrpcRequest request = this.buildGrpcRequest(method, args);
    requstValidator.doValidate(request);
    MethodType methodType = request.getMethodType();
    Channel channel = request.getChannel();
    try {
      switch (methodType) {
        case UNARY:
          return unaryCall(request, channel);
        case CLIENT_STREAMING:
          return streamCall(request, channel);
        case SERVER_STREAMING:
          return streamCall(request, channel);
        case BIDI_STREAMING:
          return streamCall(request, channel);
        default:
          RpcServiceException rpcFramwork =
              new RpcServiceException(RpcErrorMsgConstant.SERVICE_UNFOUND);
          throw rpcFramwork;
      }
    } finally {
      Object remote = GrpcCallOptions.getAffinity(request.getRefUrl())
          .get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY);
      log.debug(String.format("Service: %s  Method: %s  RemoteAddress: %s",
          request.getServiceName(), request.getMethodName(), String.valueOf(remote)));
    }
  }
}
项目:factcast    文件:GrpcFactStore0Test.java   
@Test
public void testConstruction() throws Exception {
    expectNPE(() -> new GrpcFactStore((AddressChannelFactory) null));
    expectNPE(() -> new GrpcFactStore((Channel) null));
    expectNPE(() -> new GrpcFactStore(mock(RemoteFactStoreBlockingStub.class), null));
    expectNPE(() -> new GrpcFactStore(null, mock(RemoteFactStoreStub.class)));
    expectNPE(() -> new GrpcFactStore(null, null));
}
项目:grpc-java-contrib    文件:Jdk8GeneratorStructureTest.java   
@Test
public void GeneratedClassHasCompletableFutureStubMethod() throws Exception {
    Class<?> clazz = Class.forName("com.salesforce.jprotoc.GreeterGrpc8");
    Method stubMethod = clazz.getMethod("newCompletableFutureStub", Channel.class);
    assertNotNull(stubMethod);
    assertTrue(Modifier.isPublic(stubMethod.getModifiers()));
    assertTrue(Modifier.isStatic(stubMethod.getModifiers()));
}
项目:seldon-core    文件:SeldonClientExample.java   
/** Construct client for accessing RouteGuide server using the existing channel. */
public SeldonClientExample(ManagedChannelBuilder<?> channelBuilder) {
 ClientInterceptor interceptor = new HeaderClientInterceptor();
  channel = channelBuilder.build();
  Channel interceptChannel = ClientInterceptors.intercept(channel, interceptor);
  blockingStub = SeldonGrpc.newBlockingStub(interceptChannel);
  asyncStub = SeldonGrpc.newStub(interceptChannel);
}
项目:athena    文件:DeviceProviderServiceClientProxy.java   
DeviceProviderServiceClientProxy(DeviceProvider provider, Channel channel) {
    super(provider);
    this.channel = channel;

    DeviceProviderRegistryRpcStub stub = DeviceProviderRegistryRpcGrpc.newStub(channel);
    log.debug("Calling RPC register({}) against {}", provider.id(), channel.authority());
    devProvService = stub.register(new DeviceProviderClientProxy(provider));

    // send initialize message
    DeviceProviderServiceMsg.Builder builder = DeviceProviderServiceMsg.newBuilder();
    builder.setRegisterProvider(builder.getRegisterProviderBuilder()
                                .setProviderScheme(provider.id().scheme())
                                .build());
    devProvService.onNext(builder.build());
}
项目:dble    文件:AlarmAppender.java   
/**
 * refresh config of alarm address and re create the stub
 */
public static void refreshConfig() {
    try {
        AlarmConfig config = DbleServer.getInstance().getConfig().getAlarm();
        if (config != null) {
            //put the old config into  _old
            grpcUrlOld = grpcUrl;
            serverIdOld = serverId;
            alertComponentIdOld = alertComponentId;
            portOld = port;
            grpcUrlOld = grpcUrl;
            grpcLevelOld = grpcLevel;

            grpcLevel = Integer.parseInt(config.getLevel());
            serverId = config.getServerId();
            port = Integer.parseInt(config.getPort());
            grpcUrl = config.getUrl();
            alertComponentId = config.getComponentId();
            if (port != portOld || !grpcUrlOld.equals(grpcUrl)) {
                Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel);
            }
        } else {
            stub = null;
        }
    } catch (Exception e) {
        //config not ready yeat
        return;
    }
}
项目:bazel-buildfarm    文件:ByteStreamUploader.java   
AsyncUpload(
    Channel channel,
    CallCredentials callCredentials,
    long callTimeoutSecs,
    String instanceName,
    Chunker chunker,
    Listener listener) {
  this.channel = channel;
  this.callCredentials = callCredentials;
  this.callTimeoutSecs = callTimeoutSecs;
  this.instanceName = instanceName;
  this.chunker = chunker;
  this.listener = listener;
}
项目:iotplatform    文件:RpcSessionActor.java   
private void initSession(RpcSessionCreateRequestMsg msg) {
  log.info("[{}] Initializing session", context().self());
  ServerAddress remoteServer = msg.getRemoteAddress();
  listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self());
  if (msg.getRemoteAddress() == null) {
    // Server session
    session = new GrpcSession(listener);
    session.setOutputStream(msg.getResponseObserver());
    session.initInputStream();
    session.initOutputStream();
    systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream());
  } else {
    // Client session
    Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort())
        .usePlaintext(true).build();
    session = new GrpcSession(remoteServer, listener);
    session.initInputStream();

    ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel);
    StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub
        .handlePluginMsgs(session.getInputStream());

    session.setOutputStream(outputStream);
    session.initOutputStream();
    outputStream.onNext(toConnectMsg());
  }
}
项目:book_ldrtc    文件:CustomHeaderClient.java   
/**
 * A custom client.
 */
private CustomHeaderClient(String host, int port) {
  originChannel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext(true)
      .build();
  ClientInterceptor interceptor = new HeaderClientInterceptor();
  Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}