Java Code Examples for io.grpc.ManagedChannel

The following are top voted examples for showing how to use io.grpc.ManagedChannel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JungleTree   File: PluginGrpcServer.java   View source code 8 votes vote down vote up
public void connectPlugin(String host, int port) {
    ManagedChannel channel = NettyChannelBuilder.forAddress(host, port)
            .negotiationType(NegotiationType.PLAINTEXT) // TODO: gRPC encryption
            .keepAliveTime(1, TimeUnit.MINUTES)
            .keepAliveTimeout(5, TimeUnit.SECONDS)
            .directExecutor()
            .channelType(EpollSocketChannel.class)
            .eventLoopGroup(new EpollEventLoopGroup())
            .build();

    PluginManagerGrpc.PluginManagerBlockingStub blocking = PluginManagerGrpc.newBlockingStub(channel);
    PluginManagerGrpc.PluginManagerStub async = PluginManagerGrpc.newStub(channel);

    ServiceConnection connection = ServiceConnection.builder()
            .channel(channel)
            .blockingStub(blocking)
            .asyncStub(async)
            .build();

    this.pluginConnections.put(PLUGIN_MANAGER, connection);
}
 
Example 2
Project: africastalking-java   File: ATServerTest.java   View source code 8 votes vote down vote up
@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));
                                }
                            }
                        });
                
            }
        });
}
 
Example 3
Project: grpc-samples-java   File: GreeterClient.java   View source code 7 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

        // Create a channel
        ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT)
                .usePlaintext(true)
                .build();

        // Create a blocking stub with the channel
        GreetingServiceGrpc.GreetingServiceBlockingStub stub = 
                GreetingServiceGrpc.newBlockingStub(channel);

        // Create a request
        HelloRequest request = HelloRequest.newBuilder()
                .setName("Mete - on Java")
                .setAge(34)
                .setSentiment(Sentiment.HAPPY)
                .build();

        // Send the request using the stub
        System.out.println("GreeterClient sending request");
        HelloResponse helloResponse = stub.greeting(request);

        System.out.println("GreeterClient received response: " + helloResponse.getGreeting());

        //channel.shutdown();
    }
 
Example 4
Project: utils-java   File: GenomicsChannel.java   View source code 7 votes vote down vote up
private static ManagedChannel getGenomicsManagedChannel(List<ClientInterceptor> interceptors)
    throws SSLException {
  // Java 8's implementation of GCM ciphers is extremely slow. Therefore we disable
  // them here.
  List<String> defaultCiphers = GrpcSslContexts.forClient().ciphers(null).build().cipherSuites();
  List<String> performantCiphers = new ArrayList<>();
  for (String cipher : defaultCiphers) {
    if (!cipher.contains("GCM")) {
      performantCiphers.add(cipher);
    }
  }

  return NettyChannelBuilder.forAddress(GENOMICS_ENDPOINT, 443)
      .negotiationType(NegotiationType.TLS)
      .sslContext(GrpcSslContexts.forClient().ciphers(performantCiphers).build())
      .intercept(interceptors)
      .build();
}
 
Example 5
Project: africastalking-android   File: Service.java   View source code 6 votes vote down vote up
protected ClientTokenResponse fetchToken(String host, int port) throws IOException {

        if (LOGGING) { LOGGER.log("Fetching token..."); }

        ManagedChannel channel = getChannel(host, port);
        SdkServerServiceBlockingStub stub = addClientIdentification(SdkServerServiceGrpc.newBlockingStub(channel));
        ClientTokenRequest req = ClientTokenRequest.newBuilder().build();
        ClientTokenResponse token = stub.getToken(req);

        if (LOGGING) {
            LOGGER.log(
                "\n\nToken: %s\nUsername: %s\nEnvironment: %s\nExpires: %s\n\n",
                token.getToken(),
                token.getUsername(),
                token.getEnvironment(),
                String.valueOf(token.getExpiration()));
        }
        return token;
    }
 
Example 6
Project: incubator-servicecomb-saga   File: GrpcClientMessageSender.java   View source code 6 votes vote down vote up
public GrpcClientMessageSender(
    String address,
    ManagedChannel channel,
    MessageSerializer serializer,
    MessageDeserializer deserializer,
    ServiceConfig serviceConfig,
    Function<MessageSender, Runnable> errorHandlerFactory,
    MessageHandler handler) {
  this.target = address;
  this.asyncEventService = TxEventServiceGrpc.newStub(channel);
  this.blockingEventService = TxEventServiceGrpc.newBlockingStub(channel);
  this.serializer = serializer;

  this.compensateStreamObserver = new GrpcCompensateStreamObserver(handler, errorHandlerFactory.apply(this), deserializer);
  this.serviceConfig = serviceConfig(serviceConfig.serviceName(), serviceConfig.instanceId());
}
 
Example 7
Project: haystack-client-java   File: GRPCAgentClient.java   View source code 6 votes vote down vote up
public GRPCAgentClient build() {

            ManagedChannel managedChannel = channel;

            if (managedChannel == null) {
                managedChannel = NettyChannelBuilder.forAddress(host, port)
                    .keepAliveTime(keepAliveTimeMS, TimeUnit.MILLISECONDS)
                    .keepAliveTimeout(keepAliveTimeoutMS, TimeUnit.MILLISECONDS)
                    .keepAliveWithoutCalls(keepAliveWithoutCalls)
                    .negotiationType(negotiationType)
                    .build();
            }

            SpanAgentStub stub = SpanAgentGrpc.newStub(managedChannel);

            return new GRPCAgentClient(format, managedChannel, stub, observer, shutdownTimeoutMS);
        }
 
Example 8
Project: vertx-zero   File: RpcSslTool.java   View source code 6 votes vote down vote up
/**
 * @param vertx  Vert.x instance
 * @param config configuration
 * @return ManagedChannel
 */
public static ManagedChannel getChannel(final Vertx vertx,
                                        final JsonObject config) {
    final String rpcHost = config.getString(Key.HOST);
    final Integer rpcPort = config.getInteger(Key.PORT);
    LOGGER.info(Info.CLIENT_RPC, rpcHost, String.valueOf(rpcPort));
    final VertxChannelBuilder builder =
            VertxChannelBuilder
                    .forAddress(vertx, rpcHost, rpcPort);
    Fn.safeSemi(null != config.getValue(Key.SSL), LOGGER,
            () -> {
                final JsonObject sslConfig = config.getJsonObject(Key.SSL);
                if (null != sslConfig && !sslConfig.isEmpty()) {
                    final Object type = sslConfig.getValue("type");
                    final CertType certType = null == type ?
                            CertType.PEM : Types.fromStr(CertType.class, type.toString());
                    final TrustPipe<JsonObject> pipe = TrustPipe.get(certType);
                    // Enable SSL
                    builder.useSsl(pipe.parse(sslConfig));
                } else {
                    builder.usePlaintext(true);
                }
            });
    return builder.build();
}
 
Example 9
Project: vertx-zero   File: UnitySpear.java   View source code 6 votes vote down vote up
@Override
public Future<Envelop> send(
        final Vertx vertx,
        final IpcData data) {
    // Channel
    final ManagedChannel channel = RpcSslTool.getChannel(vertx, data);
    final UnityServiceGrpc.UnityServiceVertxStub stub
            = UnityServiceGrpc.newVertxStub(channel);
    // Request
    final IpcRequest request = DataEncap.in(data);
    // Call and return to future
    final Future<Envelop> handler = Future.future();
    stub.unityCall(request, response ->
            // Reply
            RpcRepdor.create(getClass()).reply(handler, response));
    return handler;
}
 
Example 10
Project: google-assistant-java-demo   File: AssistantClient.java   View source code 6 votes vote down vote up
public AssistantClient(OAuthCredentials oAuthCredentials, AssistantConf assistantConf, DeviceModel deviceModel,
                       Device device) {

    this.assistantConf = assistantConf;
    this.deviceModel = deviceModel;
    this.device = device;
    this.currentConversationState = ByteString.EMPTY;

    // Create a channel to the test service.
    ManagedChannel channel = ManagedChannelBuilder.forAddress(assistantConf.getAssistantApiEndpoint(), 443)
            .build();

    // Create a stub with credential
    embeddedAssistantStub = EmbeddedAssistantGrpc.newStub(channel);

    updateCredentials(oAuthCredentials);
}
 
Example 11
Project: microservice-skeleton   File: GreeterServiceConsumer.java   View source code 6 votes vote down vote up
public void greet(String name, String message) {

        if (discoveryClient == null) {
            logger.info("Discovery client is null");
        } else {
            logger.info("Discovery client is not null");
            try {
                List<ServiceInstance> servers = discoveryClient.getInstances("service-account");

                for (ServiceInstance server : servers) {
                    String hostName = server.getHost();
                    int gRpcPort = Integer.parseInt(server.getMetadata().get("grpc.port"));
                    logger.info("=====>> " + hostName + " ---- " + gRpcPort);

                    final ManagedChannel channel = ManagedChannelBuilder.forAddress(hostName, gRpcPort)
                            .usePlaintext(true)
                            .build();
                    final GreetingGrpc.GreetingFutureStub stub = GreetingGrpc.newFutureStub(channel);

                    stub.sayHi(HelloRequest.newBuilder().setName(name).setMessage(message).build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
Example 12
Project: GoogleAssistantSDK   File: SpeechService.java   View source code 6 votes vote down vote up
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
 
Example 13
Project: GoogleAssistantSDK   File: SpeechService.java   View source code 6 votes vote down vote up
private void fetchAccessToken() {


        ManagedChannel channel = ManagedChannelBuilder.forTarget(HOSTNAME).build();
        try {
            mApi = EmbeddedAssistantGrpc.newStub(channel)
                    .withCallCredentials(MoreCallCredentials.from(
                            Credentials_.fromResource(getApplicationContext(), R.raw.credentials)
                    ));
        } catch (IOException|JSONException e) {
            Log.e(TAG, "error creating assistant service:", e);
        }

        for (Listener listener : mListeners) {
            listener. onCredentioalSuccess();

        }

    }
 
Example 14
Project: tikv-client-lib-java   File: PDClient.java   View source code 6 votes vote down vote up
private boolean createLeaderWrapper(String leaderUrlStr) {
  try {
    URL tURL = new URL(leaderUrlStr);
    HostAndPort newLeader = HostAndPort.fromParts(tURL.getHost(), tURL.getPort());
    leaderUrlStr = newLeader.toString();
    if (leaderWrapper != null && leaderUrlStr.equals(leaderWrapper.getLeaderInfo())) {
      return true;
    }

    // create new Leader
    ManagedChannel clientChannel = session.getChannel(leaderUrlStr);
    leaderWrapper =
      new LeaderWrapper(
          leaderUrlStr,
          PDGrpc.newBlockingStub(clientChannel),
          PDGrpc.newStub(clientChannel),
          System.nanoTime());
  } catch (MalformedURLException e) {
    logger.error("Error updating leader.", e);
    return false;
  }
  logger.info(String.format("Switched to new leader: %s", leaderWrapper));
  return true;
}
 
Example 15
Project: tikv-client-lib-java   File: RegionStoreClient.java   View source code 6 votes vote down vote up
public static RegionStoreClient create(
    TiRegion region, Store store, TiSession session) {
  RegionStoreClient client;
  String addressStr = store.getAddress();
  if (logger.isDebugEnabled()) {
    logger.debug(String.format("Create region store client on address %s", addressStr));
  }
  ManagedChannel channel = session.getChannel(addressStr);

  TikvBlockingStub blockingStub = TikvGrpc.newBlockingStub(channel);

  TikvStub asyncStub = TikvGrpc.newStub(channel);
  client =
      new RegionStoreClient(region, session, blockingStub, asyncStub);
  return client;
}
 
Example 16
Project: tikv-client-lib-java   File: TiSession.java   View source code 6 votes vote down vote up
public synchronized ManagedChannel getChannel(String addressStr) {
  ManagedChannel channel = connPool.get(addressStr);
  if (channel == null) {
    HostAndPort address;
    try {
      address = HostAndPort.fromString(addressStr);
    } catch (Exception e) {
      throw new IllegalArgumentException("failed to form address");
    }

    // Channel should be lazy without actual connection until first call
    // So a coarse grain lock is ok here
    channel = ManagedChannelBuilder.forAddress(address.getHostText(), address.getPort())
        .maxInboundMessageSize(conf.getMaxFrameSize())
        .usePlaintext(true)
        .idleTimeout(60, TimeUnit.SECONDS)
        .build();
    connPool.put(addressStr, channel);
  }
  return channel;
}
 
Example 17
Project: ms-grpc   File: GreetTest.java   View source code 6 votes vote down vote up
@Test
public void getMessage(){
    ManagedChannel channel = ManagedChannelBuilder
            .forAddress("127.0.0.1",50051)
            .usePlaintext(true)
            .build();
    GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName("gggg").build();
    HelloReply response;
    blockingStub.sayHello(request);

    try {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: grpc-java-contrib   File: CompletableFutureEndToEndTest.java   View source code 6 votes vote down vote up
@Test
public void serverRunsAndRespondsCorrectly() throws ExecutionException,
        IOException,
        InterruptedException,
        TimeoutException {
    final String name = UUID.randomUUID().toString();

    Server server = ServerBuilder.forPort(9999)
            .addService(new GreeterImpl())
            .build();

    server.start();

    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
            .usePlaintext(true)
            .build();

    GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel);

    CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());

    await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name));

    channel.shutdown();
    channel.awaitTermination(1, TimeUnit.MINUTES);
    channel.shutdownNow();

    server.shutdown();
    server.awaitTermination(1, TimeUnit.MINUTES);
    server.shutdownNow();
}
 
Example 19
Project: seldon-core   File: SeldonGrpcServer.java   View source code 6 votes vote down vote up
/**
 * Using the principal from authorization return a client gRPC channel to connect to the engine running the prediction graph.
 * @return ManagedChannel
 */
public ManagedChannel getChannel() {
    final String principal = getPrincipal();
    if (principal == null )
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_GRPC_NO_PRINCIPAL_FOUND,"");
    }

    final DeploymentSpec deploymentSpec = deploymentStore.getDeployment(principal);
    if (deploymentSpec == null)
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_NO_RUNNING_DEPLOYMENT,"Principal is "+principal);
    }
    
    ManagedChannel channel = channelStore.get(principal);
    if (channel == null)
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_GRPC_NO_GRPC_CHANNEL_FOUND,"Principal is "+principal);
    }
    return channel;
}
 
Example 20
Project: dockerized-microservices   File: PasswordsServiceClient.java   View source code 6 votes vote down vote up
/**
 * A client to call the GRPC find password service
 * @param param Query
 * @return Map of the GRPC service response
 */
public PasswordsResponseDto findPasswordMatches(String param) {
    ManagedChannel managedChannel = passwordsServiceManagedChannelSupplier.get();
    FindPasswordsQuery query = FindPasswordsQuery.newBuilder()
            .setQuery(param).build();

    FindPasswordsResponse response = PasswordsServiceGrpc
            .newBlockingStub(managedChannel)
            .withDeadlineAfter(grpcTimeout, TimeUnit.MILLISECONDS)
            .withInterceptors(interceptor)
            .findPasswords(query);

    PasswordsResponseDto.PasswordsResponseDtoBuilder responseDtoBuilder = PasswordsResponseDto.builder()
            .totalMatches(response.getNumOfMatches());

    if(!CollectionUtils.isEmpty(response.getMatchesList())) {
        responseDtoBuilder.matches(response.getMatchesList());
    }
    else {
        responseDtoBuilder.matches(Collections.emptyList());
    }

    return responseDtoBuilder.build();
}
 
Example 21
Project: black-mirror   File: SpeechService.java   View source code 6 votes vote down vote up
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
 
Example 22
Project: black-mirror   File: SpeechService.java   View source code 6 votes vote down vote up
@Override
protected void onPostExecute(AccessToken accessToken) {
    mAccessTokenTask = null;
    final ManagedChannel channel = new OkHttpChannelProvider()
            .builderForAddress(HOSTNAME, PORT)
            .nameResolverFactory(new DnsNameResolverProvider())
            .intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
                    .createScoped(SCOPE)))
            .build();
    mApi = SpeechGrpc.newStub(channel);

    // Schedule access token refresh before it expires
    if (mHandler != null) {
        mHandler.postDelayed(mFetchAccessTokenRunnable,
                Math.max(accessToken.getExpirationTime().getTime()
                        - System.currentTimeMillis()
                        - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
    }
}
 
Example 23
Project: grpcx   File: ChannelFactory.java   View source code 6 votes vote down vote up
public static ManagedChannel getChannel(String serviceName)
{
	HostInfo hostInfo=LoadBalance.getHostInfo(serviceName);
	if(hostInfo==null)
		return null;
	synchronized (ChannelFactory.class) {
		if(serviceChannels.get(hostInfo)!=null)
		{
			return serviceChannels.get(hostInfo);
		}
		else 
		{
			ManagedChannel channel=ManagedChannelBuilder.forAddress(hostInfo.getIp(), Integer.valueOf(hostInfo.getPort()))
					.usePlaintext(true)
					.build();
			serviceChannels.put(hostInfo, channel);
			return channel;
		}
	}
	
}
 
Example 24
Project: grpcx   File: ChannelFactory.java   View source code 6 votes vote down vote up
public static void shutDownChannel(HostInfo hostInfo)
{
	ManagedChannel channel=serviceChannels.get(hostInfo);
	try {
		if(channel!=null&&!channel.isShutdown())
		{
			channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
		}
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	finally {
		serviceChannels.remove(hostInfo);
	}
}
 
Example 25
Project: jetcd   File: ClientConnectionManager.java   View source code 6 votes vote down vote up
<T extends AbstractStub<T>, R> CompletableFuture<R> withNewChannel(
    String endpoint,
    Function<ManagedChannel, T> stubCustomizer,
    Function<T, CompletableFuture<R>> stubConsumer) {

  final ManagedChannel channel = defaultChannelBuilder()
      .nameResolverFactory(
          forEndpoints(
              Optional.ofNullable(builder.authority()).orElse("etcd"),
              Collections.singleton(endpoint),
              Optional.ofNullable(builder.uriResolverLoader())
                  .orElseGet(URIResolverLoader::defaultLoader)
          )
      ).build();

  try {
    T stub = stubCustomizer.apply(channel);

    return stubConsumer.apply(stub).whenComplete(
        (r, t) -> channel.shutdown()
    );
  } catch (Exception e) {
    channel.shutdown();
    throw EtcdExceptionFactory.toEtcdException(e);
  }
}
 
Example 26
Project: grpc-java-by-example   File: SimpleEchoClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException, UnknownHostException {
  String host = System.getenv("ECHO_SERVICE_HOST");
  String port = System.getenv("ECHO_SERVICE_PORT");
  final ManagedChannel channel = ManagedChannelBuilder.forAddress(host, Integer.valueOf(port))
      .usePlaintext(true)
      .build();

  final String self = InetAddress.getLocalHost().getHostName();

  ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
  for (int i = 0; i < THREADS; i++) {
    EchoServiceGrpc.EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(channel);
    executorService.submit(() -> {
      while (true) {
        EchoResponse response = stub.echo(EchoRequest.newBuilder()
            .setMessage(self + ": " + Thread.currentThread().getName())
            .build());
        System.out.println(response.getFrom() + " echoed");

        Thread.sleep(RANDOM.nextInt(700));
      }
    });
  }
}
 
Example 27
Project: grpc-java-by-example   File: MyGrpcClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
      .usePlaintext(true)
      .build();

  GreetingServiceGrpc.GreetingServiceBlockingStub stub =
      GreetingServiceGrpc.newBlockingStub(channel);

  HelloResponse helloResponse = stub.greeting(
      HelloRequest.newBuilder()
          .setName("Ray")
          .setAge(18)
          .setSentiment(Sentiment.HAPPY)
          .build());

  System.out.println(helloResponse);

  channel.shutdown();
}
 
Example 28
Project: java-app-sdk   File: AsyncDiscovery.java   View source code 6 votes vote down vote up
/**
 * Build an AsyncDiscovery wrapper from Host and Port
 *
 * @param _host The server host
 * @param _port The server port
 * @return An Observable stream containing the newly built AsyncDiscovery wrapper
 */
public static Observable<AsyncDiscovery> from(String _host, int _port) {
    return Observable
            .create((Subscriber<? super AsyncDiscovery> t) -> {
                try {
                    ManagedChannel ch = ManagedChannelBuilder
                            .forAddress(_host, _port)
                            .usePlaintext(true)
                            .build();
                    DiscoveryGrpc.DiscoveryFutureStub stub1 = DiscoveryGrpc.newFutureStub(ch);
                    t.onNext(new AsyncDiscovery(stub1));
                    t.onCompleted();
                } catch (Exception ex) {
                    t.onError(ex);
                }
            });
}
 
Example 29
Project: fabric-sdk-java   File: OrdererClient.java   View source code 6 votes vote down vote up
synchronized void shutdown(boolean force) {

        if (shutdown) {
            return;
        }
        shutdown = true;
        ManagedChannel lchannel = managedChannel;
        managedChannel = null;
        if (lchannel == null) {
            return;
        }
        if (force) {
            lchannel.shutdownNow();
        } else {
            boolean isTerminated = false;

            try {
                isTerminated = lchannel.shutdown().awaitTermination(3, TimeUnit.SECONDS);
            } catch (Exception e) {
                logger.debug(e); //best effort
            }
            if (!isTerminated) {
                lchannel.shutdownNow();
            }
        }
    }
 
Example 30
Project: android-docs-samples   File: SpeechService.java   View source code 6 votes vote down vote up
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
 
Example 31
Project: android-docs-samples   File: SpeechService.java   View source code 6 votes vote down vote up
@Override
protected void onPostExecute(AccessToken accessToken) {
    mAccessTokenTask = null;
    final ManagedChannel channel = new OkHttpChannelProvider()
            .builderForAddress(HOSTNAME, PORT)
            .nameResolverFactory(new DnsNameResolverProvider())
            .intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
                    .createScoped(SCOPE)))
            .build();
    mApi = SpeechGrpc.newStub(channel);

    // Schedule access token refresh before it expires
    if (mHandler != null) {
        mHandler.postDelayed(mFetchAccessTokenRunnable,
                Math.max(accessToken.getExpirationTime().getTime()
                        - System.currentTimeMillis()
                        - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
    }
}
 
Example 32
Project: undercarriage   File: HelloWorldGrpcApplicationTests.java   View source code 6 votes vote down vote up
@Test
public void sayHelloEndpointReturnsExpectedResponse() {
    final String name = UUID.randomUUID().toString();

    final ManagedChannel channel = ManagedChannelBuilder
            .forAddress("localhost", applicationTestRule.application().port())
            .usePlaintext(true)
            .build();

    final GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);

    HelloRequest request = HelloRequest.newBuilder()
            .setName(name)
            .build();

    HelloResponse response = blockingStub.sayHello(request);

    assertThat(response.getMessage()).isEqualTo("Hello " + name);
}
 
Example 33
Project: beam   File: BeamFnControlClient.java   View source code 6 votes vote down vote up
public BeamFnControlClient(
    Endpoints.ApiServiceDescriptor apiServiceDescriptor,
    Function<Endpoints.ApiServiceDescriptor, ManagedChannel> channelFactory,
    BiFunction<
            StreamObserverClientFactory<InstructionRequest, BeamFnApi.InstructionResponse>,
            StreamObserver<BeamFnApi.InstructionRequest>,
            StreamObserver<BeamFnApi.InstructionResponse>>
        streamObserverFactory,
    EnumMap<
            BeamFnApi.InstructionRequest.RequestCase,
            ThrowingFunction<BeamFnApi.InstructionRequest, BeamFnApi.InstructionResponse.Builder>>
        handlers) {
  this.bufferedInstructions = new LinkedBlockingDeque<>();
  this.outboundObserver = streamObserverFactory.apply(
      BeamFnControlGrpc.newStub(channelFactory.apply(apiServiceDescriptor))::control,
      new InboundObserver());
  this.handlers = handlers;
  this.onFinish = new CompletableFuture<>();
}
 
Example 34
Project: beam   File: PubsubGrpcClient.java   View source code 6 votes vote down vote up
@Override
public PubsubClient newClient(
    @Nullable String timestampAttribute, @Nullable String idAttribute, PubsubOptions options)
    throws IOException {
  ManagedChannel channel = NettyChannelBuilder
      .forAddress(PUBSUB_ADDRESS, PUBSUB_PORT)
      .negotiationType(NegotiationType.TLS)
      .sslContext(GrpcSslContexts.forClient().ciphers(null).build())
      .build();

  return new PubsubGrpcClient(timestampAttribute,
                              idAttribute,
                              DEFAULT_TIMEOUT_S,
                              channel,
                              options.getGcpCredential());
}
 
Example 35
Project: dropwizard-grpc   File: GrpcServerTests.java   View source code 6 votes vote down vote up
@Test
public void createsPlainTextServer() throws Exception {
    final DropwizardTestSupport<TestConfiguration> testSupport =
            new DropwizardTestSupport<>(TestApplication.class, resourceFilePath("grpc-test-config.yaml"));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createPlaintextChannel(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        final GetPersonResponse resp =
                client.getPerson(GetPersonRequest.newBuilder().setName(TEST_PERSON_NAME).build());
        assertEquals(TEST_PERSON_NAME, resp.getPerson().getName());
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
 
Example 36
Project: dropwizard-grpc   File: GrpcServerTests.java   View source code 6 votes vote down vote up
@Test
public void createsServerWithTls() throws Exception {
    final DropwizardTestSupport<TestConfiguration> testSupport = new DropwizardTestSupport<>(TestApplication.class,
        resourceFilePath("grpc-test-config.yaml"), Optional.empty(),
        ConfigOverride.config("grpcServer.certChainFile", getURIForResource("cert/server.crt")),
        ConfigOverride.config("grpcServer.privateKeyFile", getURIForResource("cert/server.key")));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createClientChannelForEncryptedServer(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        final GetPersonResponse resp =
                client.getPerson(GetPersonRequest.newBuilder().setName(TEST_PERSON_NAME).build());
        assertEquals(TEST_PERSON_NAME, resp.getPerson().getName());
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
 
Example 37
Project: dropwizard-grpc   File: GrpcServerTests.java   View source code 6 votes vote down vote up
@Test
public void grpcServerGetsStopped() {
    final DropwizardTestSupport<TestConfiguration> testSupport =
            new DropwizardTestSupport<>(TestApplication.class, resourceFilePath("grpc-test-config.yaml"));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createPlaintextChannel(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        testSupport.after();

        try {
            // this should fail as the server is now stopped
            client.getPerson(GetPersonRequest.newBuilder().setName("blah").build());
            fail("Request should have failed.");
        } catch (final Exception e) {
            assertEquals(StatusRuntimeException.class, e.getClass());
            assertEquals(Code.UNAVAILABLE, ((StatusRuntimeException) e).getStatus().getCode());
        }
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
 
Example 38
Project: jahhan   File: GrpcProtocol.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected <T> T doRefer(Class<T> type, URL url) throws JahhanException {
	String name = type.getName();
	final ManagedChannel channel = ManagedChannelBuilder.forAddress(url.getHost(), url.getPort()).usePlaintext(true)
			.build();
	try {
		String substring = name.substring(name.lastIndexOf(".") + 1,
				name.indexOf(BaseConfiguration.INTERFACE_SUFFIX));
		String grpcImplName;
		if (name.startsWith(BaseConfiguration.SERVICE_PATH)) {
			grpcImplName = BaseConfiguration.SERVICE_PATH + packageName + substring + "GrpcInvoker";
		} else if (name.startsWith(BaseConfiguration.FRAMEWORK_PATH)) {
			grpcImplName =BaseConfiguration.FRAMEWORK_PATH + packageName + substring + "GrpcInvoker";
		} else {
			grpcImplName = "com" + packageName + substring + "GrpcInvoker";
		}
		Class<?> grpcImplClass = Class.forName(grpcImplName);
		GrpcAbstractInvoker newInstance = (GrpcAbstractInvoker) BaseContext.CTX.getInjector().getInstance(grpcImplClass);
		newInstance.setChannel(channel);
		return (T) newInstance;
	} catch (Exception e) {
		throw new JahhanException(e.getMessage(), e);
	}
}
 
Example 39
Project: armeria   File: ArmeriaGrpcServerInteropTest.java   View source code 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
    try {
        final int port = server.getPort();
        return OkHttpChannelBuilder
                .forAddress("localhost", port)
                .negotiationType(NegotiationType.TLS)
                .maxInboundMessageSize(16 * 1024 * 1024)
                .connectionSpec(ConnectionSpec.MODERN_TLS)
                .overrideAuthority("example.com:" + port)
                .sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
                        Platform.get().getProvider(), ssc.certificate()))
                .build();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 40
Project: incubator-skywalking   File: JVMMetricServiceHandlerTestCase.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 11800).usePlaintext(true).build();
    JVMMetricsServiceGrpc.JVMMetricsServiceBlockingStub blockingStub = JVMMetricsServiceGrpc.newBlockingStub(channel);

    JVMMetrics.Builder builder = JVMMetrics.newBuilder();
    builder.setApplicationInstanceId(2);

    JVMMetric.Builder metricBuilder = JVMMetric.newBuilder();
    metricBuilder.setTime(System.currentTimeMillis());

    buildCPUMetric(metricBuilder);
    buildGCMetric(metricBuilder);
    buildMemoryMetric(metricBuilder);
    buildMemoryPoolMetric(metricBuilder);

    builder.addMetrics(metricBuilder.build());

    blockingStub.collect(builder.build());
}