io.grpc.okhttp.OkHttpChannelBuilder Java Examples

The following examples show how to use io.grpc.okhttp.OkHttpChannelBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TesterOkHttpChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
public static ManagedChannel build(
    String host,
    int port,
    @Nullable String serverHostOverride,
    boolean useTls,
    @Nullable InputStream testCa) {
  ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
      .maxInboundMessageSize(16 * 1024 * 1024);
  if (serverHostOverride != null) {
    // Force the hostname to match the cert the server uses.
    channelBuilder.overrideAuthority(serverHostOverride);
  }
  if (useTls) {
    try {
      ((OkHttpChannelBuilder) channelBuilder).useTransportSecurity();
      ((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(getSslSocketFactory(testCa));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  } else {
    channelBuilder.usePlaintext();
  }
  return channelBuilder.build();
}
 
Example #2
Source File: Utils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #3
Source File: Http2OkHttpTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private OkHttpChannelBuilder createChannelBuilder() {
  int port = ((InetSocketAddress) getListenAddress()).getPort();
  OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", port)
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .connectionSpec(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
          .cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
          .build())
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, port));
  try {
    builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
        TestUtils.loadCert("ca.pem")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  // Disable the default census stats interceptor, use testing interceptor instead.
  io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
  return builder.intercept(createCensusStatsClientInterceptor());
}
 
Example #4
Source File: TesterOkHttpChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
public static ManagedChannel build(
    String host,
    int port,
    @Nullable String serverHostOverride,
    boolean useTls,
    @Nullable InputStream testCa) {
  ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
      .maxInboundMessageSize(16 * 1024 * 1024);
  if (serverHostOverride != null) {
    // Force the hostname to match the cert the server uses.
    channelBuilder.overrideAuthority(serverHostOverride);
  }
  if (useTls) {
    try {
      ((OkHttpChannelBuilder) channelBuilder).useTransportSecurity();
      ((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(getSslSocketFactory(testCa));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  } else {
    channelBuilder.usePlaintext();
  }
  return channelBuilder.build();
}
 
Example #5
Source File: StrictModeHelloworldActivity.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected String doInBackground(String... params) {
  String host = params[0];
  String message = params[1];
  String portStr = params[2];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel =
        OkHttpChannelBuilder.forAddress(host, port)
            .transportExecutor(new NetworkTaggingExecutor(0xFDD))
            .usePlaintext()
            .build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply = stub.sayHello(request);
    return reply.getMessage();
  } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}
 
Example #6
Source File: ArmeriaGrpcServerInteropTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
    try {
        final int port = server.httpsPort();
        return OkHttpChannelBuilder
                .forAddress("localhost", port)
                .useTransportSecurity()
                .maxInboundMessageSize(16 * 1024 * 1024)
                .connectionSpec(ConnectionSpec.MODERN_TLS)
                .overrideAuthority("example.com:" + port)
                .sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
                        Platform.get().getProvider(), ssc.certificateFile()))
                .build();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #7
Source File: ExampleUnitTest.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGRPC() {
    final String SERVER_ADDRESS = "192.168.43.169";
    final int PORT = 8080;

    ManagedChannel channel = OkHttpChannelBuilder.forAddress(SERVER_ADDRESS, PORT)
            .usePlaintext()
            .build();

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

    HelloRequest helloRequest = HelloRequest.newBuilder()
            .setName("Shuza")
            .setAge(20)
            .setSentiment(Sentiment.HAPPY)
            .build();

    HelloResponse helloResponse = stub.greeting(helloRequest);

    System.out.println("Result :    " + helloResponse.getGreeting());
    assertEquals("Hello there, Shuza", helloResponse.getGreeting());
}
 
Example #8
Source File: LndConnection.java    From zap-android with MIT License 6 votes vote down vote up
private void generateChannelAndStubs() {
    String host = mConnectionConfig.getHost();
    int port = mConnectionConfig.getPort();

    // Channels are expensive to create. We want to create it once and then reuse it on all our requests.
    if (mSSLFactory == null) {
        // BTCPay
        mSecureChannel = OkHttpChannelBuilder
                .forAddress(host, port)
                .build();

    } else {
        mSecureChannel = OkHttpChannelBuilder
                .forAddress(host, port)
                .sslSocketFactory(mSSLFactory)
                .build();
    }

    mLndLightningService = new RemoteLndLightningService(mSecureChannel, mMacaroon);
    mLndWalletUnlockerService = new RemoteLndWalletUnlockerService(mSecureChannel, mMacaroon);
}
 
Example #9
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #10
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private OkHttpChannelBuilder createChannelBuilder() {
  OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", getPort())
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .connectionSpec(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
          .cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
          .build())
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, getPort()));
  io.grpc.internal.TestingAccessor.setStatsImplementation(
      builder, createClientCensusStatsModule());
  try {
    builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
        TestUtils.loadCert("ca.pem")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return builder;
}
 
Example #11
Source File: OkHttpClientInteropServlet.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  assertEquals(
      "jdk7 required",
      "1.7",
      System.getProperty("java.specification.version"));
  assertEquals(
      "Can not run in dev servers because they lack org.conscrypt.OpenSSLProvider support",
      "Production",
      System.getProperty("com.google.appengine.runtime.environment"));
  ManagedChannelBuilder<?> builder =
      ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
          .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
  assertTrue(builder instanceof OkHttpChannelBuilder);
  return builder.build();
}
 
Example #12
Source File: TlsOkHttpChannelGenerator.java    From capillary with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ManagedChannel} to the given host and port with the given TLS
 * certificates.
 */
static ManagedChannel generate(String host, int port, InputStream certStream) throws IOException {
  OkHttpChannelBuilder channelBuilder = OkHttpChannelBuilder.forAddress(host, port);
  try {
    SSLSocketFactory sslSocketFactory = getSslSocketFactory(certStream);
    channelBuilder.sslSocketFactory(sslSocketFactory);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return channelBuilder.build();
}
 
Example #13
Source File: Service.java    From africastalking-android with MIT License 5 votes vote down vote up
static ManagedChannel getChannel(String host, int port) {
    OkHttpChannelBuilder channelBuilder;

    if (DISABLE_TLS) {
        channelBuilder = OkHttpChannelBuilder
                .forAddress(host, port)
                .usePlaintext(true);
    } else {
        channelBuilder = OkHttpChannelBuilder
                .forAddress(host, port);
    }

    return channelBuilder.build();
}
 
Example #14
Source File: SimpleBenchmarkBase.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Setup
public void start() throws Exception {
    setUp();
    okhttpChannel = OkHttpChannelBuilder.forAddress("127.0.0.1", port())
                                        .usePlaintext()
                                        .directExecutor()
                                        .build();
    githubApiOkhttpClient = GithubServiceGrpc.newBlockingStub(okhttpChannel);
    githubApiOkhttpFutureClient = GithubServiceGrpc.newFutureStub(okhttpChannel);
}
 
Example #15
Source File: ReconnectTestClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void runTest() throws Exception {
  try {
    controlChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverControlPort)
        .negotiationType(NegotiationType.PLAINTEXT).build();
    controlStub = ReconnectServiceGrpc.newBlockingStub(controlChannel);
    if (useOkhttp) {
      retryChannel =
          OkHttpChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
              .useTransportSecurity()
              .build();
    } else {
      retryChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
          .negotiationType(NegotiationType.TLS).build();
    }
    retryStub = ReconnectServiceGrpc.newBlockingStub(retryChannel);
    controlStub.start(Empty.getDefaultInstance());

    long startTimeStamp = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTimeStamp) < TEST_TIME_MS) {
      try {
        retryStub.start(Empty.getDefaultInstance());
      } catch (StatusRuntimeException expected) {
        // Make CheckStyle happy.
      }
      Thread.sleep(50);
    }
    ReconnectInfo info = controlStub.stop(Empty.getDefaultInstance());
    assertTrue(info.getPassed());
  } finally {
    controlChannel.shutdownNow();
    retryChannel.shutdownNow();
  }
}
 
Example #16
Source File: ReconnectTestClient.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private void runTest() throws Exception {
  try {
    controlChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverControlPort)
        .negotiationType(NegotiationType.PLAINTEXT).build();
    controlStub = ReconnectServiceGrpc.newBlockingStub(controlChannel);
    if (useOkhttp) {
      retryChannel =
          OkHttpChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
              .useTransportSecurity()
              .build();
    } else {
      retryChannel = NettyChannelBuilder.forAddress("127.0.0.1", serverRetryPort)
          .negotiationType(NegotiationType.TLS).build();
    }
    retryStub = ReconnectServiceGrpc.newBlockingStub(retryChannel);
    controlStub.start(Empty.getDefaultInstance());

    long startTimeStamp = System.currentTimeMillis();
    while ((System.currentTimeMillis() - startTimeStamp) < TEST_TIME_MS) {
      try {
        retryStub.start(Empty.getDefaultInstance());
      } catch (StatusRuntimeException expected) {
        // Make CheckStyle happy.
      }
      Thread.sleep(50);
    }
    ReconnectInfo info = controlStub.stop(Empty.getDefaultInstance());
    assertTrue(info.getPassed());
  } finally {
    controlChannel.shutdownNow();
    retryChannel.shutdownNow();
  }
}
 
Example #17
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void fromBuilderConstructor() {
  OkHttpChannelBuilder wrappedBuilder = OkHttpChannelBuilder.forTarget("target");
  AndroidChannelBuilder androidBuilder = AndroidChannelBuilder.fromBuilder(wrappedBuilder);
  assertThat(androidBuilder.delegate()).isSameAs(wrappedBuilder);
}
 
Example #18
Source File: TestServiceClient.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  if (customCredentialsType != null
      && customCredentialsType.equals("google_default_credentials")) {
    return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (useAlts) {
    return AltsChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  AbstractManagedChannelImplBuilder<?> builder;
  if (!useOkHttp) {
    SslContext sslContext = null;
    if (useTestCa) {
      try {
        sslContext = GrpcSslContexts.forClient().trustManager(
                TestUtils.loadCert("ca.pem")).build();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
    NettyChannelBuilder nettyBuilder =
        NettyChannelBuilder.forAddress(serverHost, serverPort)
            .flowControlWindow(65 * 1024)
            .negotiationType(useTls ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
            .sslContext(sslContext);
    if (serverHostOverride != null) {
      nettyBuilder.overrideAuthority(serverHostOverride);
    }
    if (fullStreamDecompression) {
      nettyBuilder.enableFullStreamDecompression();
    }
    builder = nettyBuilder;
  } else {
    OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
    if (serverHostOverride != null) {
      // Force the hostname to match the cert the server uses.
      okBuilder.overrideAuthority(
          GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
    }
    if (useTls) {
      try {
        SSLSocketFactory factory = useTestCa
            ? TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
                TestUtils.loadCert("ca.pem"))
            : (SSLSocketFactory) SSLSocketFactory.getDefault();
        okBuilder.sslSocketFactory(factory);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else {
      okBuilder.usePlaintext();
    }
    if (fullStreamDecompression) {
      okBuilder.enableFullStreamDecompression();
    }
    builder = okBuilder;
  }
  io.grpc.internal.TestingAccessor.setStatsImplementation(
      builder, createClientCensusStatsModule());
  return builder.build();
}
 
Example #19
Source File: TestServiceClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  if (customCredentialsType != null
      && customCredentialsType.equals("google_default_credentials")) {
    return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (customCredentialsType != null
      && customCredentialsType.equals("compute_engine_channel_creds")) {
    return ComputeEngineChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (useAlts) {
    return AltsChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  AbstractManagedChannelImplBuilder<?> builder;
  if (!useOkHttp) {
    SslContext sslContext = null;
    if (useTestCa) {
      try {
        sslContext = GrpcSslContexts.forClient().trustManager(
                TestUtils.loadCert("ca.pem")).build();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
    NettyChannelBuilder nettyBuilder =
        NettyChannelBuilder.forAddress(serverHost, serverPort)
            .flowControlWindow(65 * 1024)
            .negotiationType(useTls ? NegotiationType.TLS :
              (useH2cUpgrade ? NegotiationType.PLAINTEXT_UPGRADE : NegotiationType.PLAINTEXT))
            .sslContext(sslContext);
    if (serverHostOverride != null) {
      nettyBuilder.overrideAuthority(serverHostOverride);
    }
    if (fullStreamDecompression) {
      nettyBuilder.enableFullStreamDecompression();
    }
    builder = nettyBuilder;
  } else {
    OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
    if (serverHostOverride != null) {
      // Force the hostname to match the cert the server uses.
      okBuilder.overrideAuthority(
          GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
    }
    if (useTls) {
      if (useTestCa) {
        try {
          SSLSocketFactory factory = TestUtils.newSslSocketFactoryForCa(
              Platform.get().getProvider(), TestUtils.loadCert("ca.pem"));
          okBuilder.sslSocketFactory(factory);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    } else {
      okBuilder.usePlaintext();
    }
    if (fullStreamDecompression) {
      okBuilder.enableFullStreamDecompression();
    }
    builder = okBuilder;
  }
  // Disable the default census stats interceptor, use testing interceptor instead.
  io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
  return builder.intercept(createCensusStatsClientInterceptor()).build();
}
 
Example #20
Source File: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void usingBuilderConstructor() {
  OkHttpChannelBuilder wrappedBuilder = OkHttpChannelBuilder.forTarget("target");
  AndroidChannelBuilder androidBuilder = AndroidChannelBuilder.usingBuilder(wrappedBuilder);
  assertThat(androidBuilder.delegate()).isSameInstanceAs(wrappedBuilder);
}