diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 99705fa63..bac301924 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -22,7 +22,9 @@ jobs:
bazel:
runs-on: ubuntu-latest
- container: gcr.io/gapic-images/googleapis-bazel:20210105
+ # Not using a container. The ubuntu-latest has Bazel 4.2 installed as of
+ # November 2021. gRPC 1.42 requires Bazel 4.
+ # https://github.com/grpc/grpc-java/pull/7598
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v1
@@ -53,7 +55,10 @@ jobs:
echo "The old one will disappear after 7 days."
- name: Run bazel tests
- run: bazel --batch test //... --noshow_progress --test_output=errors
+ run: |
+ which bazel
+ bazel --version
+ bazel --batch test //... --noshow_progress --test_output=errors
- uses: actions/upload-artifact@v2
if: ${{ failure() }}
diff --git a/.gitignore b/.gitignore
index e41705477..5687543f8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,6 @@
bin
build
.gradle
-tmp_gh-pages
tmp_docs
bazel-*
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0515a8ff6..313d9ec99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,21 @@
# Changelog
+### [2.7.1](https://www.github.com/googleapis/gax-java/compare/v2.7.0...v2.7.1) (2021-12-02)
+
+
+### Bug Fixes
+
+* fix gRPC code conversion ([#1555](https://www.github.com/googleapis/gax-java/issues/1555)) ([09b99d5](https://www.github.com/googleapis/gax-java/commit/09b99d591497b44c3c25b1a54abb0f1cb69d7376))
+* pass error message when creating ApiException ([#1556](https://www.github.com/googleapis/gax-java/issues/1556)) ([918ae41](https://www.github.com/googleapis/gax-java/commit/918ae419f84ad5721638ca10eca992333e9f7c3d))
+* revert generics syntax change in MockHttpService test utility ([#1574](https://www.github.com/googleapis/gax-java/issues/1574)) ([b629488](https://www.github.com/googleapis/gax-java/commit/b629488ffc7d68158158d9197695158f97229c7b))
+* update exception mapping on HTTP error responses ([#1570](https://www.github.com/googleapis/gax-java/issues/1570)) ([8a170d1](https://www.github.com/googleapis/gax-java/commit/8a170d19b42e9b13d4c69dcfbe531d4d4ca69c90))
+
+
+### Dependencies
+
+* update grpc to 1.42.1 ([#1559](https://www.github.com/googleapis/gax-java/issues/1559)) ([92b7632](https://www.github.com/googleapis/gax-java/commit/92b76325d54604c98c798c489b3a963fdf21a75c))
+* upgrade protobuf to 3.19.1 ([#1571](https://www.github.com/googleapis/gax-java/issues/1571)) ([7b354e7](https://www.github.com/googleapis/gax-java/commit/7b354e73b8ce49008bed51076afb255ca5dc68e4))
+
## [2.7.0](https://www.github.com/googleapis/gax-java/compare/v2.6.0...v2.7.0) (2021-11-03)
diff --git a/README.md b/README.md
index 0813b4d4d..d56f177a4 100644
--- a/README.md
+++ b/README.md
@@ -29,27 +29,27 @@ If you are using Maven, add this to your pom.xml file
com.google.api
gax
- 2.7.0
+ 2.7.1
com.google.api
gax-grpc
- 2.7.0
+ 2.7.1
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.api:gax:2.7.0',
- 'com.google.api:gax-grpc:2.7.0'
+compile 'com.google.api:gax:2.7.1',
+ 'com.google.api:gax-grpc:2.7.1'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.api" % "gax" % "2.7.0"
-libraryDependencies += "com.google.api" % "gax-grpc" % "2.7.0"
+libraryDependencies += "com.google.api" % "gax" % "2.7.1"
+libraryDependencies += "com.google.api" % "gax-grpc" % "2.7.1"
```
[//]: # ({x-version-update-end})
diff --git a/WORKSPACE b/WORKSPACE
index d3a451a95..9c65d85e8 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -12,7 +12,31 @@ load("//:repositories.bzl", "com_google_api_gax_java_repositories")
com_google_api_gax_java_repositories()
-load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
+load("@com_google_protobuf//:protobuf_deps.bzl",
+ "PROTOBUF_MAVEN_ARTIFACTS", "protobuf_deps")
+
+# From protobuf 3.19, protobuf project started to provide
+# PROTOBUF_MAVEN_ARTIFACTS variable so that the Bazel users can resolve their
+# dependencies through maven_install.
+# https://github.com/protocolbuffers/protobuf/issues/9132
+RULES_JVM_EXTERNAL_TAG = "4.2"
+RULES_JVM_EXTERNAL_SHA = "cd1a77b7b02e8e008439ca76fd34f5b07aecb8c752961f9640dea15e9e5ba1ca"
+http_archive(
+ name = "rules_jvm_external",
+ strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
+ sha256 = RULES_JVM_EXTERNAL_SHA,
+ url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
+)
+
+load("@rules_jvm_external//:defs.bzl", "maven_install")
+
+maven_install(
+ artifacts = PROTOBUF_MAVEN_ARTIFACTS,
+ generate_compat_repositories = True,
+ repositories = [
+ "https://repo.maven.apache.org/maven2/",
+ ],
+)
protobuf_deps()
diff --git a/benchmark/README.md b/benchmark/README.md
deleted file mode 100644
index e5dd9709c..000000000
--- a/benchmark/README.md
+++ /dev/null
@@ -1,18 +0,0 @@
-Benchmarking
-============
-
-This sub-project contains micro-benchmarks for commonly used GAX functionalities.
-
-To run all of the benchmarks:
-```
-# Run from project root directory
-./gradlew benchmark:jmh
-```
-
-
-To run a benchmark, run the following command
-```
-# Run from project root directory
-./gradlew benchmark:jmh -Pinclude="com.google.api.gax.grpc.CallableBenchmark"
-```
-substituting any benchmark class for `com.google.api.gax.grpc.CallableBenchmark`.
diff --git a/benchmark/build.gradle b/benchmark/build.gradle
deleted file mode 100644
index 6384e15fb..000000000
--- a/benchmark/build.gradle
+++ /dev/null
@@ -1,18 +0,0 @@
-plugins {
- id 'me.champeau.gradle.jmh' version '0.5.3'
-}
-
-project.version = "0.77.0" // {x-version-update:benchmark:current}
-
-dependencies {
- implementation project(':gax')
- implementation project(':gax-grpc')
- implementation "io.grpc:grpc-netty:${libraries['version.io_grpc']}"
- implementation 'com.google.api.grpc:grpc-google-cloud-bigtable-v2:2.2.0'
- implementation 'com.google.api.grpc:grpc-google-cloud-pubsub-v1:1.96.7'
-}
-
-// Allow command line to target specific test
-if (project.hasProperty('include')) {
- jmh.include = [project.include]
-}
diff --git a/benchmark/src/jmh/java/com/google/api/gax/grpc/CallableBenchmark.java b/benchmark/src/jmh/java/com/google/api/gax/grpc/CallableBenchmark.java
deleted file mode 100644
index 91159f472..000000000
--- a/benchmark/src/jmh/java/com/google/api/gax/grpc/CallableBenchmark.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright 2017 Google LLC
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google LLC nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-package com.google.api.gax.grpc;
-
-import com.google.api.core.ApiFuture;
-import com.google.api.core.ApiFutures;
-import com.google.api.gax.retrying.RetrySettings;
-import com.google.api.gax.rpc.ApiCallContext;
-import com.google.api.gax.rpc.Callables;
-import com.google.api.gax.rpc.ClientContext;
-import com.google.api.gax.rpc.StatusCode;
-import com.google.api.gax.rpc.UnaryCallSettings;
-import com.google.api.gax.rpc.UnaryCallable;
-import com.google.common.collect.ImmutableList;
-import com.google.protobuf.ByteString;
-import com.google.pubsub.v1.PublishRequest;
-import com.google.pubsub.v1.PubsubMessage;
-import com.google.pubsub.v1.TopicName;
-import java.io.ByteArrayOutputStream;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import org.openjdk.jmh.annotations.Benchmark;
-import org.openjdk.jmh.annotations.BenchmarkMode;
-import org.openjdk.jmh.annotations.Fork;
-import org.openjdk.jmh.annotations.Measurement;
-import org.openjdk.jmh.annotations.Mode;
-import org.openjdk.jmh.annotations.OutputTimeUnit;
-import org.openjdk.jmh.annotations.Param;
-import org.openjdk.jmh.annotations.Scope;
-import org.openjdk.jmh.annotations.State;
-import org.openjdk.jmh.annotations.Warmup;
-import org.openjdk.jmh.infra.Blackhole;
-import org.threeten.bp.Duration;
-
-@Fork(value = 1)
-@BenchmarkMode(Mode.Throughput)
-@Warmup(iterations = 10)
-@Measurement(iterations = 20)
-@State(Scope.Benchmark)
-@OutputTimeUnit(TimeUnit.MILLISECONDS)
-public class CallableBenchmark {
- private static final String TOPIC_NAME_STRING = TopicName.format("my-project", "my-topic");
- private static final UnaryCallable RETURN_ONE_CALLABLE =
- new UnaryCallable() {
- @Override
- public ApiFuture futureCall(PublishRequest request, ApiCallContext context) {
- return ApiFutures.immediateFuture(1);
- }
- };
- private static final RetrySettings RETRY_SETTINGS =
- RetrySettings.newBuilder()
- .setTotalTimeout(Duration.ofSeconds(1))
- .setInitialRetryDelay(Duration.ofSeconds(1))
- .setRetryDelayMultiplier(1.2)
- .setMaxRetryDelay(Duration.ofSeconds(1))
- .setInitialRpcTimeout(Duration.ofSeconds(1))
- .setRpcTimeoutMultiplier(1.2)
- .setMaxRpcTimeout(Duration.ofSeconds(1))
- .build();
- private static final UnaryCallSettings callSettings =
- UnaryCallSettings.newUnaryCallSettingsBuilder()
- .setRetrySettings(RETRY_SETTINGS)
- .setRetryableCodes(StatusCode.Code.UNAVAILABLE)
- .build();
- private static final UnaryCallable ONE_UNARY_CALLABLE =
- Callables.retrying(
- RETURN_ONE_CALLABLE,
- callSettings,
- ClientContext.newBuilder()
- .setDefaultCallContext(GrpcCallContext.createDefault())
- .build());
- private static final List MESSAGES = createMessages();
-
- private static final int MESSAGES_NUM = 100;
-
- private static List createMessages() {
- ImmutableList.Builder messages = ImmutableList.builder();
- for (int i = 0; i < MESSAGES_NUM; i++) {
- messages.add(
- PubsubMessage.newBuilder()
- .setData(ByteString.copyFromUtf8(String.format("test-message-%d", i)))
- .build());
- }
- return messages.build();
- }
-
- private void serialize(int numMessages, Blackhole blackhole) throws Exception {
- PublishRequest request =
- PublishRequest.newBuilder()
- .setTopic(TOPIC_NAME_STRING)
- .addAllMessages(MESSAGES.subList(0, numMessages))
- .build();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- request.writeTo(out);
- blackhole.consume(out.size());
- }
-
- @State(Scope.Benchmark)
- public static class SerializeParams {
- @Param({"1", "10", "100"})
- public int numMessages;
- }
-
- @Benchmark
- public void timeSerialize(SerializeParams serializeParams, Blackhole blackhole) throws Exception {
- serialize(serializeParams.numMessages, blackhole);
- }
-
- @Benchmark
- public void timeRequest(Blackhole blackhole) {
- Integer result =
- ONE_UNARY_CALLABLE.call(PublishRequest.newBuilder().setTopic(TOPIC_NAME_STRING).build());
-
- blackhole.consume(result);
- }
-}
diff --git a/benchmark/src/jmh/java/com/google/api/gax/grpc/FakeBigtableService.java b/benchmark/src/jmh/java/com/google/api/gax/grpc/FakeBigtableService.java
deleted file mode 100644
index bfd736dd0..000000000
--- a/benchmark/src/jmh/java/com/google/api/gax/grpc/FakeBigtableService.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2018 Google LLC
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google LLC nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-package com.google.api.gax.grpc;
-
-import com.google.bigtable.v2.BigtableGrpc;
-import com.google.bigtable.v2.ReadRowsRequest;
-import com.google.bigtable.v2.ReadRowsResponse;
-import com.google.bigtable.v2.ReadRowsResponse.CellChunk;
-import com.google.common.collect.AbstractIterator;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.StringValue;
-import io.grpc.stub.ServerCallStreamObserver;
-import io.grpc.stub.StreamObserver;
-import java.util.Iterator;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Fake implementation of the bigtable service. It is meant to aid in benchmarking client code by
- * generating fake responses.
- */
-public class FakeBigtableService extends BigtableGrpc.BigtableImplBase {
- /**
- * Generates a stream of responses as fast as it can. The number of responses is controlled by
- * {@link ReadRowsRequest#getRowsLimit()}.
- */
- @Override
- public void readRows(ReadRowsRequest request, StreamObserver responseObserver) {
- long numRows = Long.MAX_VALUE;
- if (request.getRowsLimit() > 0) {
- numRows = request.getRowsLimit();
- }
-
- final AtomicBoolean done = new AtomicBoolean();
-
- final Iterator source = new ReadRowsGenerator(numRows);
- final ServerCallStreamObserver target =
- (ServerCallStreamObserver) responseObserver;
-
- target.setOnReadyHandler(
- new Runnable() {
- @Override
- public void run() {
- while (target.isReady() && source.hasNext()) {
- target.onNext(source.next());
- }
- if (!source.hasNext() && done.compareAndSet(false, true)) {
- target.onCompleted();
- }
- }
- });
- }
-
- private static class ReadRowsGenerator extends AbstractIterator {
- private final long numResponses;
- private long numSent;
-
- ReadRowsGenerator(long numResponses) {
- this.numResponses = numResponses;
- }
-
- @Override
- protected ReadRowsResponse computeNext() {
- if (numSent < numResponses) {
- return buildResponse(numSent++);
- }
- return endOfData();
- }
-
- private ReadRowsResponse buildResponse(long i) {
- return ReadRowsResponse.newBuilder()
- .addChunks(
- CellChunk.newBuilder()
- .setRowKey(ByteString.copyFromUtf8(String.format("user%07d", i)))
- .setFamilyName(StringValue.newBuilder().setValue("cf").build())
- .setTimestampMicros(1_000)
- .setValue(ByteString.copyFromUtf8(String.format("user%07d", i)))
- .setCommitRow(true)
- .build())
- .build();
- }
- }
-}
diff --git a/benchmark/src/jmh/java/com/google/api/gax/grpc/ServerStreamingCallableBenchmark.java b/benchmark/src/jmh/java/com/google/api/gax/grpc/ServerStreamingCallableBenchmark.java
deleted file mode 100644
index b37379055..000000000
--- a/benchmark/src/jmh/java/com/google/api/gax/grpc/ServerStreamingCallableBenchmark.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * Copyright 2018 Google LLC
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google LLC nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-package com.google.api.gax.grpc;
-
-import com.google.api.core.CurrentMillisClock;
-import com.google.api.gax.retrying.RetrySettings;
-import com.google.api.gax.rpc.ClientContext;
-import com.google.api.gax.rpc.RequestParamsExtractor;
-import com.google.api.gax.rpc.ResponseObserver;
-import com.google.api.gax.rpc.ServerStream;
-import com.google.api.gax.rpc.ServerStreamingCallSettings;
-import com.google.api.gax.rpc.ServerStreamingCallable;
-import com.google.api.gax.rpc.StatusCode.Code;
-import com.google.api.gax.rpc.StreamController;
-import com.google.bigtable.v2.BigtableGrpc;
-import com.google.bigtable.v2.ReadRowsRequest;
-import com.google.bigtable.v2.ReadRowsResponse;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.SettableFuture;
-import io.grpc.CallOptions;
-import io.grpc.ClientCall;
-import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.Metadata;
-import io.grpc.Server;
-import io.grpc.ServerBuilder;
-import io.grpc.Status;
-import io.grpc.stub.ClientCallStreamObserver;
-import io.grpc.stub.ClientCalls;
-import io.grpc.stub.ClientResponseObserver;
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import org.openjdk.jmh.annotations.Benchmark;
-import org.openjdk.jmh.annotations.BenchmarkMode;
-import org.openjdk.jmh.annotations.Fork;
-import org.openjdk.jmh.annotations.Measurement;
-import org.openjdk.jmh.annotations.Mode;
-import org.openjdk.jmh.annotations.OperationsPerInvocation;
-import org.openjdk.jmh.annotations.OutputTimeUnit;
-import org.openjdk.jmh.annotations.Param;
-import org.openjdk.jmh.annotations.Scope;
-import org.openjdk.jmh.annotations.Setup;
-import org.openjdk.jmh.annotations.State;
-import org.openjdk.jmh.annotations.TearDown;
-import org.openjdk.jmh.annotations.Warmup;
-import org.openjdk.jmh.infra.BenchmarkParams;
-import org.openjdk.jmh.infra.Blackhole;
-import org.threeten.bp.Duration;
-
-/**
- * This benchmark tests the performance of gax's {@link ServerStreamingCallable}s relative to the
- * raw GRPC interfaces. It uses {@link FakeBigtableService} to generate the stream. The number of
- * responses per stream is controlled by {@code OperationsPerInvocation}.
- */
-@Fork(value = 1)
-@BenchmarkMode(Mode.Throughput)
-@Warmup(iterations = 5)
-@Measurement(iterations = 5)
-@State(Scope.Benchmark)
-@OperationsPerInvocation(100_000)
-@OutputTimeUnit(TimeUnit.SECONDS)
-public class ServerStreamingCallableBenchmark {
- private static final Logger LOG =
- Logger.getLogger(ServerStreamingCallableBenchmark.class.getName());
-
- @State(Scope.Benchmark)
- public static class AsyncSettings {
- @Param({"true", "false"})
- private boolean autoFlowControl = true;
- }
-
- private ScheduledExecutorService executor;
- private Server fakeServer;
- private ManagedChannel grpcChannel;
- private ClientContext clientContext;
- private ReadRowsRequest request;
-
- private ServerStreamingCallable directCallable;
- private ServerStreamingCallable baseCallable;
- private BigtableGrpc.BigtableStub stub;
-
- @Setup
- public void setup(BenchmarkParams benchmarkParams) throws IOException {
- executor = Executors.newScheduledThreadPool(4);
-
- final int availablePort;
- try (ServerSocket ss = new ServerSocket(0)) {
- availablePort = ss.getLocalPort();
- }
- fakeServer =
- ServerBuilder.forPort(availablePort).addService(new FakeBigtableService()).build().start();
-
- grpcChannel =
- ManagedChannelBuilder.forAddress("localhost", availablePort).usePlaintext().build();
-
- clientContext =
- ClientContext.newBuilder()
- .setExecutor(executor)
- .setClock(CurrentMillisClock.getDefaultClock())
- .setDefaultCallContext(
- GrpcCallContext.of(
- grpcChannel, CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.HOURS)))
- .setTransportChannel(GrpcTransportChannel.create(grpcChannel))
- .build();
-
- request =
- ReadRowsRequest.newBuilder().setRowsLimit(benchmarkParams.getOpsPerInvocation()).build();
-
- // Stub
- stub = BigtableGrpc.newStub(grpcChannel);
-
- // Direct Callable
- directCallable = new GrpcDirectServerStreamingCallable<>(BigtableGrpc.getReadRowsMethod());
-
- // Base Callable (direct + params extractor + exceptions + retries)
- GrpcCallSettings grpcCallSettings =
- GrpcCallSettings.newBuilder()
- .setMethodDescriptor(BigtableGrpc.getReadRowsMethod())
- .setParamsExtractor(new FakeRequestParamsExtractor())
- .build();
-
- ServerStreamingCallSettings callSettings =
- ServerStreamingCallSettings.newBuilder()
- .setRetryableCodes(Code.UNAVAILABLE)
- .setRetrySettings(
- RetrySettings.newBuilder()
- .setMaxAttempts(10)
- .setJittered(true)
- .setTotalTimeout(Duration.ofHours(1))
- .setInitialRetryDelay(Duration.ofMillis(5))
- .setRetryDelayMultiplier(2)
- .setMaxRetryDelay(Duration.ofMinutes(1))
- .setInitialRpcTimeout(Duration.ofHours(1))
- .setRpcTimeoutMultiplier(1)
- .setMaxRpcTimeout(Duration.ofHours(1))
- .build())
- .setIdleTimeout(Duration.ofSeconds(1))
- .build();
-
- baseCallable =
- GrpcCallableFactory.createServerStreamingCallable(
- grpcCallSettings, callSettings, clientContext);
- }
-
- @TearDown
- public void teardown() {
- try {
- grpcChannel.shutdown();
- if (!grpcChannel.awaitTermination(10, TimeUnit.SECONDS)) {
- throw new TimeoutException();
- }
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to close the grpc channel", e);
- }
-
- try {
- fakeServer.shutdown();
- if (!fakeServer.awaitTermination(10, TimeUnit.SECONDS)) {
- throw new TimeoutException();
- }
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to shutdown the fake server", e);
- }
-
- try {
- executor.shutdown();
- if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
- throw new TimeoutException();
- }
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Failed to shutdown the the executor", e);
- }
- }
-
- // ClientCall.Listener baseline
- @Benchmark
- public void asyncGrpcListener(AsyncSettings asyncSettings, Blackhole blackhole) throws Exception {
- ClientCall clientCall =
- grpcChannel.newCall(BigtableGrpc.getReadRowsMethod(), CallOptions.DEFAULT);
-
- GrpcClientCallListener listener =
- new GrpcClientCallListener(clientCall, asyncSettings.autoFlowControl, blackhole);
- clientCall.start(listener, new Metadata());
- clientCall.sendMessage(request);
- clientCall.halfClose();
-
- if (asyncSettings.autoFlowControl) {
- clientCall.request(Integer.MAX_VALUE);
- } else {
- clientCall.request(1);
- }
-
- listener.awaitCompletion();
- }
-
- // grpc-stub baseline
- @Benchmark
- public void asyncGrpcObserver(AsyncSettings asyncSettings, Blackhole blackhole) throws Exception {
- GrpcStreamingObserver observer =
- new GrpcStreamingObserver(asyncSettings.autoFlowControl, blackhole);
- stub.readRows(request, observer);
- observer.awaitCompletion();
- }
-
- @Benchmark
- public void syncGrpcIterator(Blackhole blackhole) {
- Iterator iterator =
- ClientCalls.blockingServerStreamingCall(
- grpcChannel, BigtableGrpc.getReadRowsMethod(), CallOptions.DEFAULT, request);
-
- while (iterator.hasNext()) {
- ReadRowsResponse response = iterator.next();
- blackhole.consume(response);
- }
- }
-
- // DirectCallable
- @Benchmark
- public void asyncDirectServerStreamingCallable(AsyncSettings asyncSettings, Blackhole blackhole)
- throws Exception {
- GaxResponseObserver responseObserver =
- new GaxResponseObserver(asyncSettings.autoFlowControl, blackhole);
- directCallable.call(request, responseObserver, clientContext.getDefaultCallContext());
- responseObserver.awaitCompletion();
- }
-
- @Benchmark
- public void syncDirectServerStreamingCallable(Blackhole blackhole) {
- ServerStream results =
- directCallable.call(request, clientContext.getDefaultCallContext());
- for (ReadRowsResponse result : results) {
- blackhole.consume(result);
- }
- }
-
- // BaseCallable
- @Benchmark
- public void asyncBaseServerStreamingCallable(AsyncSettings asyncSettings, Blackhole blackhole)
- throws Exception {
- GaxResponseObserver responseObserver =
- new GaxResponseObserver(asyncSettings.autoFlowControl, blackhole);
- baseCallable.call(request, responseObserver);
- responseObserver.awaitCompletion();
- }
-
- @Benchmark
- public void syncBaseServerStreamingCallable(Blackhole blackhole) {
- ServerStream results = baseCallable.call(request);
- for (ReadRowsResponse result : results) {
- blackhole.consume(result);
- }
- }
-
- // Helpers
- private static class FakeRequestParamsExtractor
- implements RequestParamsExtractor {
- @Override
- public Map extract(ReadRowsRequest request) {
- return ImmutableMap.of("table_name", request.getTableName());
- }
- }
-
- static class GrpcClientCallListener extends ClientCall.Listener {
- private final SettableFuture future = SettableFuture.create();
- private final ClientCall clientCall;
- private final boolean autoFlowControl;
- private final Blackhole blackhole;
-
- GrpcClientCallListener(
- ClientCall clientCall,
- boolean autoFlowControl,
- Blackhole blackhole) {
- this.clientCall = clientCall;
- this.autoFlowControl = autoFlowControl;
- this.blackhole = blackhole;
- }
-
- void awaitCompletion() throws InterruptedException, ExecutionException, TimeoutException {
- future.get(1, TimeUnit.MINUTES);
- }
-
- @Override
- public void onMessage(ReadRowsResponse message) {
- blackhole.consume(message);
- if (!autoFlowControl) {
- clientCall.request(1);
- }
- }
-
- @Override
- public void onClose(Status status, Metadata trailers) {
- if (status.isOk()) {
- future.set(null);
- } else {
- future.setException(status.asRuntimeException(trailers));
- }
- }
- }
-
- static class GrpcStreamingObserver
- implements ClientResponseObserver {
- private final SettableFuture future = SettableFuture.create();
- private final boolean autoFlowControl;
- private final Blackhole blackhole;
- private ClientCallStreamObserver inner;
-
- public GrpcStreamingObserver(boolean autoFlowControl, Blackhole blackhole) {
- this.autoFlowControl = autoFlowControl;
- this.blackhole = blackhole;
- }
-
- void awaitCompletion() throws InterruptedException, ExecutionException, TimeoutException {
- future.get(1, TimeUnit.HOURS);
- }
-
- @Override
- public void beforeStart(ClientCallStreamObserver observer) {
- if (!autoFlowControl) {
- observer.disableAutoInboundFlowControl();
- }
- this.inner = observer;
- }
-
- @Override
- public void onNext(ReadRowsResponse msg) {
- blackhole.consume(msg);
- if (!autoFlowControl) {
- inner.request(1);
- }
- }
-
- @Override
- public void onError(Throwable throwable) {
- future.setException(throwable);
- }
-
- @Override
- public void onCompleted() {
- future.set(null);
- }
- }
-
- static class GaxResponseObserver implements ResponseObserver {
- private final SettableFuture future = SettableFuture.create();
- private final boolean autoFlowControl;
- private final Blackhole blackhole;
- private StreamController controller;
-
- GaxResponseObserver(boolean autoFlowControl, Blackhole blackhole) {
- this.autoFlowControl = autoFlowControl;
- this.blackhole = blackhole;
- }
-
- void awaitCompletion() throws InterruptedException, ExecutionException, TimeoutException {
- future.get(1, TimeUnit.HOURS);
- }
-
- @Override
- public void onStart(StreamController controller) {
- this.controller = controller;
- if (!autoFlowControl) {
- controller.disableAutoInboundFlowControl();
- controller.request(1);
- }
- }
-
- @Override
- public void onResponse(ReadRowsResponse response) {
- blackhole.consume(response);
- if (!autoFlowControl) {
- controller.request(1);
- }
- }
-
- @Override
- public void onError(Throwable t) {
- future.setException(t);
- }
-
- @Override
- public void onComplete() {
- future.set(null);
- }
- }
-}
diff --git a/build.gradle b/build.gradle
index 849b52e46..703a82a6e 100644
--- a/build.gradle
+++ b/build.gradle
@@ -4,23 +4,20 @@ plugins {
id 'java'
id 'io.github.gradle-nexus.publish-plugin' version '1.1.0'
- id 'com.diffplug.eclipse.apt' version '3.33.1' apply false
+ id 'com.diffplug.eclipse.apt' version '3.33.2' apply false
id 'com.dorongold.task-tree' version '2.1.0' apply false
- id 'com.github.johnrengelman.shadow' version '6.1.0' apply false
- id 'com.github.sherter.google-java-format' version '0.8' apply false
+ id 'com.github.johnrengelman.shadow' version '7.1.0' apply false
+ id 'com.github.sherter.google-java-format' version '0.9' apply false
}
// TODO: Populate this from dependencies.properties version property (for proper Gradle-Bazel sync)
-project.version = "2.7.0" // {x-version-update:gax:current}
+project.version = "2.7.1" // {x-version-update:gax:current}
allprojects {
group = 'com.google.api'
}
-// Project names not used for release
-def nonReleaseProjects = ['benchmark']
// Project names not using the default publication configuration
-def noDefaultPublications = ['benchmark', 'gax-bom']
def nonJavaProjects = ['gax-bom']
ext {
@@ -75,6 +72,7 @@ configure(javaProjects) {
// Formatting tasks
// ================
googleJavaFormat {
+ toolVersion '1.7'
exclude '.apt_generated*/**'
exclude 'bin/**'
exclude 'build/**'
@@ -128,8 +126,8 @@ configure(javaProjects) {
jacoco.toolVersion = '0.8.5'
jacocoTestReport {
reports {
- xml.enabled true
- html.enabled true
+ xml.required = true
+ html.required = true
}
afterEvaluate {
getClassDirectories().setFrom files(classDirectories.files.collect {
@@ -152,13 +150,13 @@ configure(javaProjects) {
javadoc.options {
encoding = 'UTF-8'
- links 'https://docs.oracle.com/javase/7/docs/api/'
+ links 'https://docs.oracle.com/javase/8/docs/api/'
if (JavaVersion.current().isJava8Compatible()) {
addStringOption('Xdoclint:all,-missing', '-quiet')
}
if (JavaVersion.current().isJava11Compatible()) {
- addStringOption('-release', '7')
+ addStringOption('-release', '8')
}
}
@@ -218,7 +216,7 @@ configure(javaProjects) {
}
def normalReleasableProjects = subprojects.findAll {
- !nonReleaseProjects.contains(it.name) && !noDefaultPublications.contains(it.name)
+ !nonJavaProjects.contains(it.name)
}
configure(normalReleasableProjects) {
apply plugin: 'maven-publish'
@@ -284,7 +282,7 @@ configure(normalReleasableProjects) {
// ./gradlew gax-httpjson:checkJavaLinkage
dependsOn project.getTasksByName('publishMavenJavaPublicationToMavenLocal', true)
classpath = configurations.linkageChecker
- main = 'com.google.cloud.tools.opensource.classpath.LinkageCheckerMain'
+ mainClass = 'com.google.cloud.tools.opensource.classpath.LinkageCheckerMain'
def arguments = ['-a', "com.google.api:${project.name}:${project.version}"]
if (project.name == 'gax-grpc') {
@@ -335,102 +333,9 @@ task javadocCombinedV3(type: Javadoc) {
}
clean {
- delete 'tmp_gh-pages/'
delete 'tmp_docs/'
}
-// Release
-// =======
-
-task checkOutGhPages {
- doLast {
- exec {
- commandLine 'git', 'clone', '--branch', 'gh-pages',
- '--single-branch', 'git@github.com:googleapis/gax-java.git', 'tmp_gh-pages'
- }
- }
-}
-
-task copyFilesToGhPages {
- dependsOn 'checkOutGhPages'
- dependsOn 'javadocCombined'
- doLast {
- def newSiteDirPath = 'tmp_gh-pages/' + project.version + '/apidocs/'
- new File(newSiteDirPath).mkdirs()
- copy {
- from 'tmp_docs'
- into newSiteDirPath
- }
- copy {
- from 'README.md'
- into 'tmp_gh-pages'
- rename { filename -> filename.replace 'README', 'index' }
- }
- delete('tmp_gh-pages/latest/')
- def latestDirPath = 'tmp_gh-pages/latest/apidocs/'
- new File(latestDirPath).mkdirs()
- copy {
- from 'tmp_docs'
- into latestDirPath
- }
- }
-}
-
-task createApiDocsRedirect {
- dependsOn 'copyFilesToGhPages'
- doLast {
- def template = new File('templates/apidocs_index.html.template').text
- def outputContent = template.replace('{{siteVersion}}', project.version)
- new File('tmp_gh-pages/apidocs/index.html').write(outputContent)
- }
-}
-
-task publishDocs {
- dependsOn 'closeAndReleaseSonatypeStagingRepository'
- doLast {
- exec {
- workingDir './tmp_gh-pages'
- commandLine 'git', 'add', '.'
- }
- exec {
- workingDir './tmp_gh-pages'
- commandLine 'git', 'commit', '-m', 'Release docs for ' + project.version
- }
- exec {
- workingDir './tmp_gh-pages'
- commandLine 'git', 'push'
- }
- }
-}
-
-// 1. Updates samples/pom.xml
-// 2. Updates README.md
-// 3. Regenerates the gh-pages branch under tmp_gh-pages
-// 4. Stages the artifact on Sonatype
-task stageRelease {
- dependsOn 'createApiDocsRedirect'
- doLast {
- exec {
- // We need to spawn a new gradle build process in order to upload appropriately
- // More details: http://stackoverflow.com/questions/31614735/gradle-uploadarchives-artificats-namespace-when-depending-on-a-plugin
- commandLine './gradlew', 'publish'
- }
- }
-}
-
-// 1. Closes and releases the artifact on Sonatype
-// 2. Commits and pushes the new docs
-// 3. Remove tmp_gh-pages
-// Note: This task assumes that the 'stage_release' task has been completed.
-task finalizeRelease {
- dependsOn publishDocs
- doLast {
- exec {
- commandLine 'rm', '-r', 'tmp_gh-pages'
- }
- }
-}
-
// Linkage Monitor searches for pom.xml but gax-java uses Gradle. Alternatively Linkage Monitor
// reads linkage-monitor-artifacts.txt to get list of artifacts.
// https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/Linkage-Monitor#linkage-monitor-artifactstxt
diff --git a/dependencies.properties b/dependencies.properties
index 10e4b6086..305d003a1 100644
--- a/dependencies.properties
+++ b/dependencies.properties
@@ -8,24 +8,24 @@
# Versions of oneself
# {x-version-update-start:gax:current}
-version.gax=2.7.0
+version.gax=2.7.1
# {x-version-update-end}
# {x-version-update-start:gax:current}
-version.gax_grpc=2.7.0
+version.gax_grpc=2.7.1
# {x-version-update-end}
# {x-version-update-start:gax:current}
-version.gax_bom=2.7.0
+version.gax_bom=2.7.1
# {x-version-update-end}
# {x-version-update-start:gax-httpjson:current}
-version.gax_httpjson=0.92.0
+version.gax_httpjson=0.92.1
# {x-version-update-end}
# Versions for dependencies which actual artifacts differ between Bazel and Gradle.
# Gradle build depends on prebuilt maven artifacts, while Bazel build depends on Bazel workspaces
# with the sources.
-version.com_google_protobuf=3.18.1
+version.com_google_protobuf=3.19.1
version.google_java_format=1.1
-version.io_grpc=1.41.0
+version.io_grpc=1.42.1
# Maven artifacts.
# Note, the actual name of each property matters (bazel build scripts depend on it).
diff --git a/gax-bom/build.gradle b/gax-bom/build.gradle
index 272a09121..85a728d61 100644
--- a/gax-bom/build.gradle
+++ b/gax-bom/build.gradle
@@ -5,7 +5,7 @@ plugins {
archivesBaseName = 'gax-bom'
-project.version = "2.7.0" // {x-version-update:gax-bom:current}
+project.version = "2.7.1" // {x-version-update:gax-bom:current}
def mavenJavaDir = "$buildDir/publications/mavenJava"
def mavenJavaBomOutputFile = file(mavenJavaDir + '/pom-default.xml')
diff --git a/gax-bom/pom.xml b/gax-bom/pom.xml
index d83a4fcfc..a744ed93b 100644
--- a/gax-bom/pom.xml
+++ b/gax-bom/pom.xml
@@ -3,7 +3,7 @@
4.0.0
com.google.api
gax-bom
- 2.7.0
+ 2.7.1
pom
GAX (Google Api eXtensions) for Java
Google Api eXtensions for Java
@@ -33,34 +33,34 @@
com.google.api
gax
- 2.7.0
+ 2.7.1
com.google.api
gax
- 2.7.0
+ 2.7.1
testlib
com.google.api
gax-grpc
- 2.7.0
+ 2.7.1
com.google.api
gax-grpc
- 2.7.0
+ 2.7.1
testlib
com.google.api
gax-httpjson
- 0.92.0
+ 0.92.1
com.google.api
gax-httpjson
- 0.92.0
+ 0.92.1
testlib
diff --git a/gax-grpc/build.gradle b/gax-grpc/build.gradle
index faa7912b6..11b2de195 100644
--- a/gax-grpc/build.gradle
+++ b/gax-grpc/build.gradle
@@ -1,7 +1,7 @@
archivesBaseName = 'gax-grpc'
// TODO: Populate this from dependencies.properties version property (for proper Gradle-Bazel sync)
-project.version = "2.7.0" // {x-version-update:gax-grpc:current}
+project.version = "2.7.1" // {x-version-update:gax-grpc:current}
dependencies {
api(project(':gax'),
diff --git a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java
index d3fdd990e..22dc53c24 100644
--- a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java
+++ b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java
@@ -185,16 +185,16 @@ public GrpcCallContext withTimeout(@Nullable Duration timeout) {
}
return new GrpcCallContext(
- this.channel,
- this.callOptions,
+ channel,
+ callOptions,
timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
@Nullable
@@ -211,16 +211,16 @@ public GrpcCallContext withStreamWaitTimeout(@Nullable Duration streamWaitTimeou
}
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
+ channel,
+ callOptions,
+ timeout,
streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
@Override
@@ -231,31 +231,31 @@ public GrpcCallContext withStreamIdleTimeout(@Nullable Duration streamIdleTimeou
}
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
@BetaApi("The surface for channel affinity is not stable yet and may change in the future.")
public GrpcCallContext withChannelAffinity(@Nullable Integer affinity) {
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
affinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
@BetaApi("The surface for extra headers is not stable yet and may change in the future.")
@@ -265,55 +265,55 @@ public GrpcCallContext withExtraHeaders(Map> extraHeaders)
ImmutableMap> newExtraHeaders =
Headers.mergeHeaders(this.extraHeaders, extraHeaders);
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
newExtraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ options,
+ retrySettings,
+ retryableCodes);
}
@Override
public RetrySettings getRetrySettings() {
- return this.retrySettings;
+ return retrySettings;
}
@Override
public GrpcCallContext withRetrySettings(RetrySettings retrySettings) {
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
retrySettings,
- this.retryableCodes);
+ retryableCodes);
}
@Override
public Set getRetryableCodes() {
- return this.retryableCodes;
+ return retryableCodes;
}
@Override
public GrpcCallContext withRetryableCodes(Set retryableCodes) {
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
retryableCodes);
}
@@ -331,56 +331,56 @@ public ApiCallContext merge(ApiCallContext inputCallContext) {
Channel newChannel = grpcCallContext.channel;
if (newChannel == null) {
- newChannel = this.channel;
+ newChannel = channel;
}
Deadline newDeadline = grpcCallContext.callOptions.getDeadline();
if (newDeadline == null) {
- newDeadline = this.callOptions.getDeadline();
+ newDeadline = callOptions.getDeadline();
}
CallCredentials newCallCredentials = grpcCallContext.callOptions.getCredentials();
if (newCallCredentials == null) {
- newCallCredentials = this.callOptions.getCredentials();
+ newCallCredentials = callOptions.getCredentials();
}
ApiTracer newTracer = grpcCallContext.callOptions.getOption(TRACER_KEY);
if (newTracer == null) {
- newTracer = this.callOptions.getOption(TRACER_KEY);
+ newTracer = callOptions.getOption(TRACER_KEY);
}
Duration newTimeout = grpcCallContext.timeout;
if (newTimeout == null) {
- newTimeout = this.timeout;
+ newTimeout = timeout;
}
Duration newStreamWaitTimeout = grpcCallContext.streamWaitTimeout;
if (newStreamWaitTimeout == null) {
- newStreamWaitTimeout = this.streamWaitTimeout;
+ newStreamWaitTimeout = streamWaitTimeout;
}
Duration newStreamIdleTimeout = grpcCallContext.streamIdleTimeout;
if (newStreamIdleTimeout == null) {
- newStreamIdleTimeout = this.streamIdleTimeout;
+ newStreamIdleTimeout = streamIdleTimeout;
}
Integer newChannelAffinity = grpcCallContext.channelAffinity;
if (newChannelAffinity == null) {
- newChannelAffinity = this.channelAffinity;
+ newChannelAffinity = channelAffinity;
}
RetrySettings newRetrySettings = grpcCallContext.retrySettings;
if (newRetrySettings == null) {
- newRetrySettings = this.retrySettings;
+ newRetrySettings = retrySettings;
}
Set newRetryableCodes = grpcCallContext.retryableCodes;
if (newRetryableCodes == null) {
- newRetryableCodes = this.retryableCodes;
+ newRetryableCodes = retryableCodes;
}
ImmutableMap> newExtraHeaders =
- Headers.mergeHeaders(this.extraHeaders, grpcCallContext.extraHeaders);
+ Headers.mergeHeaders(extraHeaders, grpcCallContext.extraHeaders);
ApiCallContextOptions newOptions = options.merge(grpcCallContext.options);
@@ -422,6 +422,7 @@ public CallOptions getCallOptions() {
*
* @see ApiCallContext#withStreamWaitTimeout(Duration)
*/
+ @Override
@BetaApi("The surface for streaming is not stable yet and may change in the future.")
@Nullable
public Duration getStreamWaitTimeout() {
@@ -433,6 +434,7 @@ public Duration getStreamWaitTimeout() {
*
* @see ApiCallContext#withStreamIdleTimeout(Duration)
*/
+ @Override
@BetaApi("The surface for streaming is not stable yet and may change in the future.")
@Nullable
public Duration getStreamIdleTimeout() {
@@ -450,37 +452,37 @@ public Integer getChannelAffinity() {
@BetaApi("The surface for extra headers is not stable yet and may change in the future.")
@Override
public Map> getExtraHeaders() {
- return this.extraHeaders;
+ return extraHeaders;
}
/** Returns a new instance with the channel set to the given channel. */
public GrpcCallContext withChannel(Channel newChannel) {
return new GrpcCallContext(
newChannel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
/** Returns a new instance with the call options set to the given call options. */
public GrpcCallContext withCallOptions(CallOptions newCallOptions) {
return new GrpcCallContext(
- this.channel,
+ channel,
newCallOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
- this.options,
- this.retrySettings,
- this.retryableCodes);
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
+ options,
+ retrySettings,
+ retryableCodes);
}
public GrpcCallContext withRequestParamsDynamicHeaderOption(String requestParams) {
@@ -513,16 +515,16 @@ public GrpcCallContext withTracer(@Nonnull ApiTracer tracer) {
public GrpcCallContext withOption(Key key, T value) {
ApiCallContextOptions newOptions = options.withOption(key, value);
return new GrpcCallContext(
- this.channel,
- this.callOptions,
- this.timeout,
- this.streamWaitTimeout,
- this.streamIdleTimeout,
- this.channelAffinity,
- this.extraHeaders,
+ channel,
+ callOptions,
+ timeout,
+ streamWaitTimeout,
+ streamIdleTimeout,
+ channelAffinity,
+ extraHeaders,
newOptions,
- this.retrySettings,
- this.retryableCodes);
+ retrySettings,
+ retryableCodes);
}
/** {@inheritDoc} */
@@ -556,21 +558,21 @@ public boolean equals(Object o) {
}
GrpcCallContext that = (GrpcCallContext) o;
- return Objects.equals(this.channel, that.channel)
- && Objects.equals(this.callOptions, that.callOptions)
- && Objects.equals(this.timeout, that.timeout)
- && Objects.equals(this.streamWaitTimeout, that.streamWaitTimeout)
- && Objects.equals(this.streamIdleTimeout, that.streamIdleTimeout)
- && Objects.equals(this.channelAffinity, that.channelAffinity)
- && Objects.equals(this.extraHeaders, that.extraHeaders)
- && Objects.equals(this.options, that.options)
- && Objects.equals(this.retrySettings, that.retrySettings)
- && Objects.equals(this.retryableCodes, that.retryableCodes);
+ return Objects.equals(channel, that.channel)
+ && Objects.equals(callOptions, that.callOptions)
+ && Objects.equals(timeout, that.timeout)
+ && Objects.equals(streamWaitTimeout, that.streamWaitTimeout)
+ && Objects.equals(streamIdleTimeout, that.streamIdleTimeout)
+ && Objects.equals(channelAffinity, that.channelAffinity)
+ && Objects.equals(extraHeaders, that.extraHeaders)
+ && Objects.equals(options, that.options)
+ && Objects.equals(retrySettings, that.retrySettings)
+ && Objects.equals(retryableCodes, that.retryableCodes);
}
Metadata getMetadata() {
Metadata metadata = new Metadata();
- for (Map.Entry> header : this.extraHeaders.entrySet()) {
+ for (Map.Entry> header : extraHeaders.entrySet()) {
String headerKey = header.getKey();
for (String headerValue : header.getValue()) {
metadata.put(Metadata.Key.of(headerKey, Metadata.ASCII_STRING_MARSHALLER), headerValue);
diff --git a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallSettings.java b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallSettings.java
index 739b480a8..177dde6ed 100644
--- a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallSettings.java
+++ b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallSettings.java
@@ -40,7 +40,7 @@ public class GrpcCallSettings {
private final RequestParamsExtractor paramsExtractor;
private final boolean alwaysAwaitTrailers;
- private GrpcCallSettings(Builder builder) {
+ private GrpcCallSettings(Builder builder) {
this.methodDescriptor = builder.methodDescriptor;
this.paramsExtractor = builder.paramsExtractor;
this.alwaysAwaitTrailers = builder.shouldAwaitTrailers;
diff --git a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptor.java b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptor.java
index e405336c2..c3940f4db 100644
--- a/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptor.java
+++ b/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcMetadataHandlerInterceptor.java
@@ -33,7 +33,6 @@
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
-import io.grpc.ClientCall.Listener;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
diff --git a/gax-grpc/src/main/java/com/google/longrunning/OperationsSettings.java b/gax-grpc/src/main/java/com/google/longrunning/OperationsSettings.java
index 507711f47..16035fc6f 100644
--- a/gax-grpc/src/main/java/com/google/longrunning/OperationsSettings.java
+++ b/gax-grpc/src/main/java/com/google/longrunning/OperationsSettings.java
@@ -29,8 +29,6 @@
*/
package com.google.longrunning;
-import static com.google.longrunning.OperationsClient.ListOperationsPagedResponse;
-
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
@@ -40,6 +38,7 @@
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.UnaryCallSettings;
+import com.google.longrunning.OperationsClient.ListOperationsPagedResponse;
import com.google.longrunning.stub.OperationsStubSettings;
import com.google.protobuf.Empty;
import java.io.IOException;
@@ -103,6 +102,7 @@ public static Builder newBuilder(ClientContext clientContext) {
}
/** Returns a builder containing all the values of this settings class. */
+ @Override
public Builder toBuilder() {
return new Builder(this);
}
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java
index f566ca074..26a6b925f 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/CallOptionsUtilTest.java
@@ -41,7 +41,7 @@
public class CallOptionsUtilTest {
@Test
- public void testPutAndGetDynamicHeaderOption() throws Exception {
+ public void testPutAndGetDynamicHeaderOption() {
String encodedRequestParams = "param1=value¶m2.param3=value23";
CallOptions options =
CallOptionsUtil.putRequestParamsDynamicHeaderOption(
@@ -54,7 +54,7 @@ public void testPutAndGetDynamicHeaderOption() throws Exception {
}
@Test
- public void testPutAndGetDynamicHeaderOptionEmpty() throws Exception {
+ public void testPutAndGetDynamicHeaderOptionEmpty() {
CallOptions options =
CallOptionsUtil.putRequestParamsDynamicHeaderOption(CallOptions.DEFAULT, "");
assertSame(CallOptions.DEFAULT, options);
@@ -63,7 +63,7 @@ public void testPutAndGetDynamicHeaderOptionEmpty() throws Exception {
}
@Test(expected = NullPointerException.class)
- public void testPutAndGetHeaderOptionNull() throws Exception {
+ public void testPutAndGetHeaderOptionNull() {
CallOptionsUtil.putRequestParamsDynamicHeaderOption(CallOptions.DEFAULT, null);
}
}
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java
index a660ca1c6..d6ae65202 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/ChannelPoolTest.java
@@ -180,23 +180,21 @@ public void channelPrimerShouldCallPoolConstruction() throws IOException {
// Test channelPrimer is called periodically, if there's an executorService
@Test
- public void channelPrimerIsCalledPeriodically() throws IOException, InterruptedException {
+ public void channelPrimerIsCalledPeriodically() throws IOException {
ChannelPrimer mockChannelPrimer = Mockito.mock(ChannelPrimer.class);
ManagedChannel channel1 = Mockito.mock(RefreshingManagedChannel.class);
ManagedChannel channel2 = Mockito.mock(RefreshingManagedChannel.class);
ManagedChannel channel3 = Mockito.mock(RefreshingManagedChannel.class);
- final List channelRefreshers = new ArrayList<>();
+ List channelRefreshers = new ArrayList<>();
ScheduledExecutorService scheduledExecutorService =
Mockito.mock(ScheduledExecutorService.class);
- Answer extractChannelRefresher =
- new Answer() {
- public Object answer(InvocationOnMock invocation) {
- channelRefreshers.add((Runnable) invocation.getArgument(0));
- return Mockito.mock(ScheduledFuture.class);
- }
+ Answer> extractChannelRefresher =
+ invocation -> {
+ channelRefreshers.add((Runnable) invocation.getArgument(0));
+ return Mockito.mock(ScheduledFuture.class);
};
Mockito.doAnswer(extractChannelRefresher)
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java
index 163f43d1c..2ebe93b7f 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcCallableFactoryTest.java
@@ -88,7 +88,7 @@ public void tearDown() {
}
@Test
- public void createServerStreamingCallableRetryableExceptions() throws Exception {
+ public void createServerStreamingCallableRetryableExceptions() {
GrpcCallSettings grpcCallSettings =
GrpcCallSettings.create(FakeServiceGrpc.METHOD_STREAMING_RECOGNIZE_ERROR);
@@ -147,7 +147,7 @@ public void createServerStreamingCallableRetryableExceptions() throws Exception
@Test
public void testGetSpanName() {
@SuppressWarnings("unchecked")
- MethodDescriptor descriptor =
+ MethodDescriptor, ?> descriptor =
MethodDescriptor.newBuilder()
.setType(MethodType.SERVER_STREAMING)
.setFullMethodName("google.bigtable.v2.Bigtable/ReadRows")
@@ -162,7 +162,7 @@ public void testGetSpanName() {
@Test
public void testGetSpanNameUnqualified() {
@SuppressWarnings("unchecked")
- MethodDescriptor descriptor =
+ MethodDescriptor, ?> descriptor =
MethodDescriptor.newBuilder()
.setType(MethodType.SERVER_STREAMING)
.setFullMethodName("UnqualifiedService/ReadRows")
@@ -180,7 +180,7 @@ public void testGetSpanNameInvalid() {
for (String invalidName : invalidNames) {
@SuppressWarnings("unchecked")
- MethodDescriptor descriptor =
+ MethodDescriptor, ?> descriptor =
MethodDescriptor.newBuilder()
.setType(MethodType.SERVER_STREAMING)
.setFullMethodName(invalidName)
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java
index 9722f8634..ef0d58ce9 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcClientCallsTest.java
@@ -53,8 +53,6 @@
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.threeten.bp.Duration;
public class GrpcClientCallsTest {
@@ -105,22 +103,19 @@ public void testExtraHeaders() {
@SuppressWarnings("unchecked")
ClientCall.Listener mockListener = Mockito.mock(ClientCall.Listener.class);
- @SuppressWarnings("unchecked")
Channel mockChannel = Mockito.mock(ManagedChannel.class);
Mockito.doAnswer(
- new Answer() {
- public Void answer(InvocationOnMock invocation) {
- Metadata clientCallHeaders = (Metadata) invocation.getArguments()[1];
- Metadata.Key key1 =
- Metadata.Key.of("header-key-1", Metadata.ASCII_STRING_MARSHALLER);
- Metadata.Key key2 =
- Metadata.Key.of("header-key-2", Metadata.ASCII_STRING_MARSHALLER);
- assertThat(clientCallHeaders.getAll(key1))
- .containsExactly("header-value-11", "header-value-12");
- assertThat(clientCallHeaders.getAll(key2)).containsExactly("header-value-21");
- return null;
- }
+ invocation -> {
+ Metadata clientCallHeaders = (Metadata) invocation.getArguments()[1];
+ Metadata.Key key1 =
+ Metadata.Key.of("header-key-1", Metadata.ASCII_STRING_MARSHALLER);
+ Metadata.Key key2 =
+ Metadata.Key.of("header-key-2", Metadata.ASCII_STRING_MARSHALLER);
+ assertThat(clientCallHeaders.getAll(key1))
+ .containsExactly("header-value-11", "header-value-12");
+ assertThat(clientCallHeaders.getAll(key2)).containsExactly("header-value-21");
+ return null;
})
.when(mockClientCall)
.start(Mockito.>any(), Mockito.any());
@@ -143,7 +138,6 @@ public void testTimeoutToDeadlineConversion() {
@SuppressWarnings("unchecked")
ClientCall.Listener mockListener = Mockito.mock(ClientCall.Listener.class);
- @SuppressWarnings("unchecked")
Channel mockChannel = Mockito.mock(ManagedChannel.class);
ArgumentCaptor capturedCallOptions = ArgumentCaptor.forClass(CallOptions.class);
@@ -175,7 +169,6 @@ public void testTimeoutAfterDeadline() {
@SuppressWarnings("unchecked")
ClientCall.Listener mockListener = Mockito.mock(ClientCall.Listener.class);
- @SuppressWarnings("unchecked")
Channel mockChannel = Mockito.mock(ManagedChannel.class);
ArgumentCaptor capturedCallOptions = ArgumentCaptor.forClass(CallOptions.class);
@@ -209,7 +202,6 @@ public void testTimeoutBeforeDeadline() {
@SuppressWarnings("unchecked")
ClientCall.Listener mockListener = Mockito.mock(ClientCall.Listener.class);
- @SuppressWarnings("unchecked")
Channel mockChannel = Mockito.mock(ManagedChannel.class);
ArgumentCaptor capturedCallOptions = ArgumentCaptor.forClass(CallOptions.class);
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java
index fa5a41fbd..335a70966 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectServerStreamingCallableTest.java
@@ -129,7 +129,7 @@ public void testBadContext() {
}
@Test
- public void testServerStreamingStart() throws Exception {
+ public void testServerStreamingStart() {
CountDownLatch latch = new CountDownLatch(1);
MoneyObserver moneyObserver = new MoneyObserver(true, latch);
@@ -240,7 +240,7 @@ protected void onCompleteImpl() {
}
@Test
- public void testBlockingServerStreaming() throws Exception {
+ public void testBlockingServerStreaming() {
Color request = Color.newBuilder().setRed(0.5f).build();
ServerStream response = streamingCallable.call(request);
List responseData = Lists.newArrayList(response);
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java
index 733f4d02d..95d4550b0 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcDirectStreamingCallableTest.java
@@ -141,7 +141,6 @@ public void testBidiStreamingClientError() throws Exception {
GrpcDirectServerStreamingCallableTest.MoneyObserver moneyObserver =
new GrpcDirectServerStreamingCallableTest.MoneyObserver(true, latch);
- Color request = Color.newBuilder().setRed(0.5f).build();
ClientStream stream = streamingCallable.splitCall(moneyObserver);
Throwable clientError = new StatusRuntimeException(Status.CANCELLED);
stream.closeSendWithError(clientError);
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java
index 8f259e8c3..80b041a37 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcResponseMetadataTest.java
@@ -147,7 +147,7 @@ public void tearDown() {
}
@Test
- public void testResponseMetadataUnaryCall() throws Exception {
+ public void testResponseMetadataUnaryCall() {
GrpcCallSettings grpcCallSettings =
GrpcCallSettings.create(FakeServiceGrpc.METHOD_RECOGNIZE);
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java
index 9cd1aaa89..456d4e73b 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/GrpcTransportDescriptorTest.java
@@ -58,7 +58,7 @@ public class GrpcTransportDescriptorTest {
private static boolean IS_RETRYABLE = true;
@Test
- public void translateException_StatusException_noRetry() throws Exception {
+ public void translateException_StatusException_noRetry() {
Throwable originalException = new StatusException(Status.INVALID_ARGUMENT);
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(
@@ -73,7 +73,7 @@ public void translateException_StatusException_noRetry() throws Exception {
}
@Test
- public void translateException_StatusException_withRetry() throws Exception {
+ public void translateException_StatusException_withRetry() {
Throwable originalException = new StatusException(Status.UNAVAILABLE);
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(
@@ -88,7 +88,7 @@ public void translateException_StatusException_withRetry() throws Exception {
}
@Test
- public void translateException_StatusRuntimeException_noRetry() throws Exception {
+ public void translateException_StatusRuntimeException_noRetry() {
Throwable originalException = new StatusRuntimeException(Status.INVALID_ARGUMENT);
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(
@@ -103,7 +103,7 @@ public void translateException_StatusRuntimeException_noRetry() throws Exception
}
@Test
- public void translateException_StatusRuntimeException_withRetry() throws Exception {
+ public void translateException_StatusRuntimeException_withRetry() {
Throwable originalException = new StatusRuntimeException(Status.UNAVAILABLE);
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(
@@ -118,7 +118,7 @@ public void translateException_StatusRuntimeException_withRetry() throws Excepti
}
@Test
- public void translateException_cancelled() throws Exception {
+ public void translateException_cancelled() {
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(inactiveCallable(), Collections.emptySet());
ApiFuture result = exceptionCallable.futureCall(0);
@@ -129,7 +129,7 @@ public void translateException_cancelled() throws Exception {
}
@Test
- public void translateException_ApiException() throws Exception {
+ public void translateException_ApiException() {
Throwable originalException = new RuntimeException("stuff went wrong");
Throwable apiException =
new DataLossException(
@@ -147,7 +147,7 @@ public void translateException_ApiException() throws Exception {
}
@Test
- public void translateException_RuntimeException() throws Exception {
+ public void translateException_RuntimeException() {
Throwable originalException = new RuntimeException("stuff went wrong");
GrpcExceptionCallable exceptionCallable =
new GrpcExceptionCallable<>(
@@ -180,8 +180,7 @@ public ApiFuture futureCall(Integer request, ApiCallContext context) {
}
public void assertInnerExceptionIsInstanceOf(
- Throwable thrownException, Class> clazz, boolean retryable, Throwable originalException)
- throws Exception {
+ Throwable thrownException, Class> clazz, boolean retryable, Throwable originalException) {
Truth.assertThat(thrownException).isInstanceOf(clazz);
ApiException apiException = (ApiException) thrownException;
Truth.assertThat(apiException.isRetryable()).isEqualTo(retryable);
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java
index ed01d241e..a3f88d554 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProviderTest.java
@@ -232,10 +232,10 @@ public void testChannelConfigurator() throws IOException {
ApiFunction channelConfigurator =
Mockito.mock(ApiFunction.class);
- ArgumentCaptor channelBuilderCaptor =
+ ArgumentCaptor> channelBuilderCaptor =
ArgumentCaptor.forClass(ManagedChannelBuilder.class);
- ManagedChannelBuilder swappedBuilder = Mockito.mock(ManagedChannelBuilder.class);
+ ManagedChannelBuilder> swappedBuilder = Mockito.mock(ManagedChannelBuilder.class);
ManagedChannel fakeChannel = Mockito.mock(ManagedChannel.class);
Mockito.when(swappedBuilder.build()).thenReturn(fakeChannel);
@@ -327,13 +327,10 @@ public void testWithDirectPathDisabled() throws IOException {
executor.shutdown();
ApiFunction channelConfigurator =
- new ApiFunction() {
- @Override
- public ManagedChannelBuilder apply(ManagedChannelBuilder channelBuilder) {
- // Clients without setting attemptDirectPath flag will not attempt DirectPath
- assertThat(channelBuilder instanceof ComputeEngineChannelBuilder).isFalse();
- return channelBuilder;
- }
+ channelBuilder -> {
+ // Clients without setting attemptDirectPath flag will not attempt DirectPath
+ assertThat(channelBuilder instanceof ComputeEngineChannelBuilder).isFalse();
+ return channelBuilder;
};
TransportChannelProvider provider =
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java
index d8eba05a2..5ac43f141 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/ProtoOperationTransformersTest.java
@@ -29,11 +29,13 @@
*/
package com.google.api.gax.grpc;
+import static org.junit.Assert.assertThrows;
+
import com.google.api.gax.grpc.ProtoOperationTransformers.MetadataTransformer;
import com.google.api.gax.grpc.ProtoOperationTransformers.ResponseTransformer;
import com.google.api.gax.longrunning.OperationSnapshot;
-import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.UnavailableException;
+import com.google.api.gax.rpc.UnknownException;
import com.google.common.truth.Truth;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
@@ -41,7 +43,6 @@
import com.google.type.Color;
import com.google.type.Money;
import io.grpc.Status.Code;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -66,14 +67,11 @@ public void testAnyResponseTransformer_exception() {
OperationSnapshot operationSnapshot =
GrpcOperationSnapshot.create(
Operation.newBuilder().setResponse(Any.pack(inputMoney)).setError(status).build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("ResponseTransformer should have thrown an exception");
- } catch (UnavailableException expected) {
- Truth.assertThat(expected)
- .hasMessageThat()
- .contains("failed with status = GrpcStatusCode{transportCode=UNAVAILABLE}");
- }
+ Exception exception =
+ assertThrows(UnavailableException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception)
+ .hasMessageThat()
+ .contains("failed with status = GrpcStatusCode{transportCode=UNAVAILABLE}");
}
@Test
@@ -86,12 +84,9 @@ public void testAnyResponseTransformer_mismatchedTypes() {
.setResponse(Any.pack(Color.getDefaultInstance()))
.setError(status)
.build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("ResponseTransformer should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).hasMessageThat().contains("Failed to unpack object");
- }
+ Exception exception =
+ assertThrows(UnknownException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception).hasMessageThat().contains("encountered a problem unpacking it");
}
@Test
@@ -114,11 +109,8 @@ public void testAnyMetadataTransformer_mismatchedTypes() {
.setMetadata(Any.pack(Color.getDefaultInstance()))
.setError(status)
.build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("MetadataTransformer should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).hasMessageThat().contains("Failed to unpack object");
- }
+ Exception exception =
+ assertThrows(UnknownException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception).hasMessageThat().contains("encountered a problem unpacking it");
}
}
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/RefreshingManagedChannelTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/RefreshingManagedChannelTest.java
index ece24086a..b56070bf3 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/RefreshingManagedChannelTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/RefreshingManagedChannelTest.java
@@ -52,7 +52,6 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@RunWith(JUnit4.class)
@@ -65,13 +64,11 @@ public void channelRefreshShouldSwapChannels() throws IOException {
// mock executor service to capture the runnable scheduled so we can invoke it when we want to
ScheduledExecutorService scheduledExecutorService =
Mockito.mock(ScheduledExecutorService.class);
- final List channelRefreshers = new ArrayList<>();
- Answer extractChannelRefresher =
- new Answer() {
- public Object answer(InvocationOnMock invocation) {
- channelRefreshers.add((Runnable) invocation.getArgument(0));
- return null;
- }
+ List channelRefreshers = new ArrayList<>();
+ Answer> extractChannelRefresher =
+ invocation -> {
+ channelRefreshers.add((Runnable) invocation.getArgument(0));
+ return null;
};
Mockito.doAnswer(extractChannelRefresher)
@@ -104,39 +101,33 @@ public Object answer(InvocationOnMock invocation) {
@Test
public void randomizeTest() throws IOException, InterruptedException, ExecutionException {
int channelCount = 10;
- final ManagedChannel[] underlyingChannels = new ManagedChannel[channelCount];
- final Random r = new Random();
+ ManagedChannel[] underlyingChannels = new ManagedChannel[channelCount];
+ Random r = new Random();
for (int i = 0; i < channelCount; i++) {
- final ManagedChannel mockManagedChannel = Mockito.mock(ManagedChannel.class);
+ ManagedChannel mockManagedChannel = Mockito.mock(ManagedChannel.class);
underlyingChannels[i] = mockManagedChannel;
- final Answer waitAndSendMessage =
- new Answer() {
- @Override
- public Object answer(InvocationOnMock invocation) throws Throwable {
- // add a little time to sleep so calls don't always complete right away
- TimeUnit.MICROSECONDS.sleep(r.nextInt(1000));
- // when sending message on the call, the channel cannot be shutdown
- Mockito.verify(mockManagedChannel, Mockito.never()).shutdown();
- return invocation.callRealMethod();
- }
+ Answer> waitAndSendMessage =
+ invocation -> {
+ // add a little time to sleep so calls don't always complete right away
+ TimeUnit.MICROSECONDS.sleep(r.nextInt(1000));
+ // when sending message on the call, the channel cannot be shutdown
+ Mockito.verify(mockManagedChannel, Mockito.never()).shutdown();
+ return invocation.callRealMethod();
};
- Answer createNewCall =
- new Answer() {
- @Override
- public Object answer(InvocationOnMock invocation) throws Throwable {
- // create a new client call for every new call to the underlying channel
- MockClientCall mockClientCall = new MockClientCall<>(1, Status.OK);
- MockClientCall spyClientCall = Mockito.spy(mockClientCall);
-
- // spy into clientCall to verify that the channel is not shutdown
- Mockito.doAnswer(waitAndSendMessage)
- .when(spyClientCall)
- .sendMessage(Mockito.anyString());
-
- return spyClientCall;
- }
+ Answer> createNewCall =
+ invocation -> {
+ // create a new client call for every new call to the underlying channel
+ MockClientCall mockClientCall = new MockClientCall<>(1, Status.OK);
+ MockClientCall spyClientCall = Mockito.spy(mockClientCall);
+
+ // spy into clientCall to verify that the channel is not shutdown
+ Mockito.doAnswer(waitAndSendMessage)
+ .when(spyClientCall)
+ .sendMessage(Mockito.anyString());
+
+ return spyClientCall;
};
// return a new mocked client call when requesting new call on the channel
@@ -147,15 +138,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
}
// mock executor service to capture the runnable scheduled so we can invoke it when we want to
- final List channelRefreshers = new ArrayList<>();
+ List channelRefreshers = new ArrayList<>();
ScheduledExecutorService scheduledExecutorService =
Mockito.mock(ScheduledExecutorService.class);
- Answer extractChannelRefresher =
- new Answer() {
- public Object answer(InvocationOnMock invocation) {
- channelRefreshers.add((Runnable) invocation.getArgument(0));
- return null;
- }
+ Answer> extractChannelRefresher =
+ invocation -> {
+ channelRefreshers.add((Runnable) invocation.getArgument(0));
+ return null;
};
Mockito.doAnswer(extractChannelRefresher)
.when(scheduledExecutorService)
@@ -163,7 +152,7 @@ public Object answer(InvocationOnMock invocation) {
Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS));
FakeChannelFactory channelFactory = new FakeChannelFactory(Arrays.asList(underlyingChannels));
- final ManagedChannel refreshingManagedChannel =
+ ManagedChannel refreshingManagedChannel =
new RefreshingManagedChannel(channelFactory, scheduledExecutorService);
// send a bunch of request to RefreshingManagedChannel, executor needs more than 1 thread to
@@ -178,18 +167,15 @@ public Object answer(InvocationOnMock invocation) {
int whenToRefresh = r.nextInt(requestCount);
for (int j = 0; j < requestCount; j++) {
Runnable createNewCall =
- new Runnable() {
- @Override
- public void run() {
- // create a new call and send message on refreshingManagedChannel
- ClientCall call =
- refreshingManagedChannel.newCall(
- FakeMethodDescriptor.create(), CallOptions.DEFAULT);
- @SuppressWarnings("unchecked")
- ClientCall.Listener listener = Mockito.mock(ClientCall.Listener.class);
- call.start(listener, new Metadata());
- call.sendMessage("message");
- }
+ () -> {
+ // create a new call and send message on refreshingManagedChannel
+ ClientCall call =
+ refreshingManagedChannel.newCall(
+ FakeMethodDescriptor.create(), CallOptions.DEFAULT);
+ @SuppressWarnings("unchecked")
+ ClientCall.Listener listener = Mockito.mock(ClientCall.Listener.class);
+ call.start(listener, new Metadata());
+ call.sendMessage("message");
};
futures.add(executor.submit(createNewCall));
// at the randomly chosen point, refresh the channel
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/SafeShutdownManagedChannelTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/SafeShutdownManagedChannelTest.java
index ed5659b1f..91b16dcbf 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/SafeShutdownManagedChannelTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/SafeShutdownManagedChannelTest.java
@@ -40,7 +40,6 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@RunWith(JUnit4.class)
@@ -61,13 +60,10 @@ public void callShouldCompleteAfterCreation() {
Mockito.>any(), Mockito.any(CallOptions.class)))
.thenReturn(spyClientCall);
- Answer verifyChannelNotShutdown =
- new Answer() {
- @Override
- public Object answer(InvocationOnMock invocation) throws Throwable {
- Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
- return invocation.callRealMethod();
- }
+ Answer> verifyChannelNotShutdown =
+ invocation -> {
+ Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
+ return invocation.callRealMethod();
};
// verify that underlying channel is not shutdown when clientCall is still sending message
@@ -108,13 +104,10 @@ public void callShouldCompleteAfterStarted() {
Mockito.>any(), Mockito.any(CallOptions.class)))
.thenReturn(spyClientCall);
- Answer verifyChannelNotShutdown =
- new Answer() {
- @Override
- public Object answer(InvocationOnMock invocation) throws Throwable {
- Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
- return invocation.callRealMethod();
- }
+ Answer> verifyChannelNotShutdown =
+ invocation -> {
+ Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
+ return invocation.callRealMethod();
};
// verify that underlying channel is not shutdown when clientCall is still sending message
@@ -154,13 +147,10 @@ public void channelShouldShutdown() {
Mockito.>any(), Mockito.any(CallOptions.class)))
.thenReturn(spyClientCall);
- Answer verifyChannelNotShutdown =
- new Answer() {
- @Override
- public Object answer(InvocationOnMock invocation) throws Throwable {
- Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
- return invocation.callRealMethod();
- }
+ Answer> verifyChannelNotShutdown =
+ invocation -> {
+ Mockito.verify(underlyingChannel, Mockito.never()).shutdown();
+ return invocation.callRealMethod();
};
// verify that underlying channel is not shutdown when clientCall is still sending message
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java
index f40716d4f..e24e36c68 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/SettingsTest.java
@@ -170,16 +170,17 @@ public static Builder newBuilder() {
return Builder.createDefault();
}
+ @Override
public Builder toBuilder() {
return new Builder(this);
}
- private FakeStubSettings(Builder settingsBuilder) throws IOException {
+ private FakeStubSettings(Builder settingsBuilder) {
super(settingsBuilder);
- this.fakeMethodSimple = settingsBuilder.fakeMethodSimple().build();
- this.fakePagedMethod = settingsBuilder.fakePagedMethod().build();
- this.fakeMethodBatching = settingsBuilder.fakeMethodBatching().build();
+ fakeMethodSimple = settingsBuilder.fakeMethodSimple().build();
+ fakePagedMethod = settingsBuilder.fakePagedMethod().build();
+ fakeMethodBatching = settingsBuilder.fakeMethodBatching().build();
}
private static class Builder extends StubSettings.Builder {
@@ -318,24 +319,24 @@ public void channelCustomCredentialScopes() throws IOException {
// ====
@Test
- public void callSettingsToBuilder() throws IOException {
- UnaryCallSettings.Builder builderA = UnaryCallSettings.newUnaryCallSettingsBuilder();
- UnaryCallSettings settingsA = builderA.build();
- UnaryCallSettings.Builder builderB = settingsA.toBuilder();
- UnaryCallSettings settingsB = builderB.build();
+ public void callSettingsToBuilder() {
+ UnaryCallSettings.Builder, ?> builderA = UnaryCallSettings.newUnaryCallSettingsBuilder();
+ UnaryCallSettings, ?> settingsA = builderA.build();
+ UnaryCallSettings.Builder, ?> builderB = settingsA.toBuilder();
+ UnaryCallSettings, ?> settingsB = builderB.build();
assertEquals(settingsA, settingsB);
}
@Test
- public void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() throws IOException {
+ public void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() {
UnaryCallSettings.Builder builder =
UnaryCallSettings.newUnaryCallSettingsBuilder();
builder.build();
}
@Test
- public void callSettingsBuildFromTimeoutNoRetries() throws IOException {
+ public void callSettingsBuildFromTimeoutNoRetries() {
Duration timeout = Duration.ofMillis(60000);
UnaryCallSettings.Builder builderA =
diff --git a/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java b/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java
index 8a4df4244..3b0d8ebc5 100644
--- a/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java
+++ b/gax-grpc/src/test/java/com/google/api/gax/grpc/TimeoutTest.java
@@ -32,12 +32,10 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.times;
-import com.google.api.core.ApiFuture;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.RequestParamsExtractor;
-import com.google.api.gax.rpc.ServerStream;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.StatusCode;
@@ -365,7 +363,7 @@ private CallOptions setupUnaryCallable(
ClientContext.newBuilder().setDefaultCallContext(context).build());
try {
- ApiFuture future = callable.futureCall("Is your refrigerator running?");
+ callable.futureCall("Is your refrigerator running?");
} catch (ApiException e) {
}
@@ -426,7 +424,7 @@ private CallOptions setupServerStreamingCallable(
ClientContext.newBuilder().setDefaultCallContext(context).build());
try {
- ServerStream stream = callable.call("Is your refrigerator running?");
+ callable.call("Is your refrigerator running?");
} catch (ApiException e) {
}
diff --git a/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java b/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java
index aa335e91c..0c5eaa302 100644
--- a/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java
+++ b/gax-grpc/src/test/java/com/google/longrunning/OperationsClientTest.java
@@ -29,14 +29,13 @@
*/
package com.google.longrunning;
-import static com.google.longrunning.OperationsClient.ListOperationsPagedResponse;
-
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.common.collect.Lists;
+import com.google.longrunning.OperationsClient.ListOperationsPagedResponse;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Duration;
import com.google.protobuf.Empty;
@@ -84,7 +83,7 @@ public void setUp() throws IOException {
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
client.close();
}
diff --git a/gax-httpjson/build.gradle b/gax-httpjson/build.gradle
index 863f3bd65..0212433ab 100644
--- a/gax-httpjson/build.gradle
+++ b/gax-httpjson/build.gradle
@@ -1,7 +1,7 @@
archivesBaseName = 'gax-httpjson'
// TODO: Populate this from dependencies.properties version property (for proper Gradle-Bazel sync)
-project.version = "0.92.0" // {x-version-update:gax-httpjson:current}
+project.version = "0.92.1" // {x-version-update:gax-httpjson:current}
dependencies {
api(project(':gax'),
diff --git a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonExceptionCallable.java b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonExceptionCallable.java
index c2ec8c19e..14be14332 100644
--- a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonExceptionCallable.java
+++ b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonExceptionCallable.java
@@ -95,16 +95,13 @@ public void onSuccess(ResponseT r) {
public void onFailure(Throwable throwable) {
if (throwable instanceof HttpResponseException) {
HttpResponseException e = (HttpResponseException) throwable;
- StatusCode.Code statusCode =
- HttpJsonStatusCode.httpStatusToStatusCode(e.getStatusCode(), e.getMessage());
- boolean canRetry = retryableCodes.contains(statusCode);
+ StatusCode statusCode = HttpJsonStatusCode.of(e.getStatusCode());
+ boolean canRetry = retryableCodes.contains(statusCode.getCode());
String message = e.getStatusMessage();
ApiException newException =
message == null
- ? ApiExceptionFactory.createException(
- throwable, HttpJsonStatusCode.of(statusCode), canRetry)
- : ApiExceptionFactory.createException(
- message, throwable, HttpJsonStatusCode.of(statusCode), canRetry);
+ ? ApiExceptionFactory.createException(throwable, statusCode, canRetry)
+ : ApiExceptionFactory.createException(message, throwable, statusCode, canRetry);
super.setException(newException);
} else if (throwable instanceof CancellationException && cancelled) {
// this just circled around, so ignore.
diff --git a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshot.java b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshot.java
index 97cb55dfb..471cff04d 100644
--- a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshot.java
+++ b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshot.java
@@ -138,10 +138,9 @@ public Builder setResponse(Object response) {
return this;
}
- public Builder setError(int errorCode, String errorMessage) {
+ public Builder setError(int httpStatus, String errorMessage) {
this.errorCode =
- HttpJsonStatusCode.of(
- errorCode == 0 ? Code.OK.getHttpStatusCode() : errorCode, errorMessage);
+ httpStatus == 0 ? HttpJsonStatusCode.of(Code.OK) : HttpJsonStatusCode.of(httpStatus);
this.errorMessage = errorMessage;
return this;
}
diff --git a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonStatusCode.java b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonStatusCode.java
index db5e2a93a..617496eb5 100644
--- a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonStatusCode.java
+++ b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonStatusCode.java
@@ -32,36 +32,29 @@
import com.google.api.core.BetaApi;
import com.google.api.core.InternalExtensionOnly;
import com.google.api.gax.rpc.StatusCode;
-import com.google.common.base.Strings;
import java.util.Objects;
/** A failure code specific to an HTTP call. */
@BetaApi
@InternalExtensionOnly
public class HttpJsonStatusCode implements StatusCode {
- static final String FAILED_PRECONDITION = "FAILED_PRECONDITION";
- static final String OUT_OF_RANGE = "OUT_OF_RANGE";
- static final String ALREADY_EXISTS = "ALREADY_EXISTS";
- static final String DATA_LOSS = "DATA_LOSS";
- static final String UNKNOWN = "UNKNOWN";
-
private final int httpStatus;
- private final StatusCode.Code statusCode;
+ private final Code statusCode;
/** Creates a new instance with the given status code. */
- public static HttpJsonStatusCode of(int httpStatus, String errorMessage) {
- return new HttpJsonStatusCode(httpStatus, httpStatusToStatusCode(httpStatus, errorMessage));
+ public static HttpJsonStatusCode of(int httpStatus) {
+ return new HttpJsonStatusCode(httpStatus, httpStatusToStatusCode(httpStatus));
}
- public static HttpJsonStatusCode of(StatusCode.Code statusCode) {
+ public static HttpJsonStatusCode of(Code statusCode) {
return new HttpJsonStatusCode(statusCode.getHttpStatusCode(), statusCode);
}
public static HttpJsonStatusCode of(com.google.rpc.Code rpcCode) {
- return new HttpJsonStatusCode(rpcCode.getNumber(), rpcCodeToStatusCode(rpcCode));
+ return HttpJsonStatusCode.of(rpcCodeToStatusCode(rpcCode));
}
- static StatusCode.Code rpcCodeToStatusCode(com.google.rpc.Code rpcCode) {
+ static Code rpcCodeToStatusCode(com.google.rpc.Code rpcCode) {
switch (rpcCode) {
case OK:
return Code.OK;
@@ -102,60 +95,47 @@ static StatusCode.Code rpcCodeToStatusCode(com.google.rpc.Code rpcCode) {
}
}
- static StatusCode.Code httpStatusToStatusCode(int httpStatus, String errorMessage) {
- String causeMessage = Strings.nullToEmpty(errorMessage).toUpperCase();
- switch (httpStatus) {
- case 200:
- return Code.OK;
- case 400:
- if (causeMessage.contains(OUT_OF_RANGE)) {
- return Code.OUT_OF_RANGE;
- } else if (causeMessage.contains(FAILED_PRECONDITION)) {
- return Code.FAILED_PRECONDITION;
- } else {
+ static Code httpStatusToStatusCode(int httpStatus) {
+ if (200 <= httpStatus && httpStatus < 300) {
+ return Code.OK;
+ } else if (400 <= httpStatus && httpStatus < 500) {
+ switch (httpStatus) {
+ case 400:
return Code.INVALID_ARGUMENT;
- }
- case 401:
- return Code.UNAUTHENTICATED;
- case 403:
- return Code.PERMISSION_DENIED;
- case 404:
- return Code.NOT_FOUND;
- case 409:
- if (causeMessage.contains(ALREADY_EXISTS)) {
- return Code.ALREADY_EXISTS;
- } else {
+ case 401:
+ return Code.UNAUTHENTICATED;
+ case 403:
+ return Code.PERMISSION_DENIED;
+ case 404:
+ return Code.NOT_FOUND;
+ case 409:
return Code.ABORTED;
- }
- case 411:
- throw new IllegalStateException(
- "411 status code received (Content-Length header not given.) Please file a bug against https://github.com/googleapis/gax-java/\n"
- + httpStatus);
- case 429:
- return Code.RESOURCE_EXHAUSTED;
- case 499:
- return Code.CANCELLED;
- case 500:
- if (causeMessage.contains(DATA_LOSS)) {
- return Code.DATA_LOSS;
- } else if (causeMessage.contains(UNKNOWN)) {
- return Code.UNKNOWN;
- } else {
+ case 416:
+ return Code.OUT_OF_RANGE;
+ case 429:
+ return Code.RESOURCE_EXHAUSTED;
+ case 499:
+ return Code.CANCELLED;
+ default:
+ return Code.FAILED_PRECONDITION;
+ }
+ } else if (500 <= httpStatus && httpStatus < 600) {
+ switch (httpStatus) {
+ case 501:
+ return Code.UNIMPLEMENTED;
+ case 503:
+ return Code.UNAVAILABLE;
+ case 504:
+ return Code.DEADLINE_EXCEEDED;
+ default:
return Code.INTERNAL;
- }
- case 501:
- return Code.UNIMPLEMENTED;
- case 503:
- return Code.UNAVAILABLE;
- case 504:
- return Code.DEADLINE_EXCEEDED;
- default:
- throw new IllegalArgumentException("Unrecognized http status code: " + httpStatus);
+ }
}
+ return Code.UNKNOWN;
}
@Override
- public StatusCode.Code getCode() {
+ public Code getCode() {
return statusCode;
}
@@ -165,8 +145,8 @@ public Integer getTransportCode() {
return httpStatus;
}
- private HttpJsonStatusCode(int code, StatusCode.Code statusCode) {
- this.httpStatus = code;
+ private HttpJsonStatusCode(int httpStatus, Code statusCode) {
+ this.httpStatus = httpStatus;
this.statusCode = statusCode;
}
diff --git a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java
index 250d0a47f..f3a7ffd6c 100644
--- a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java
+++ b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpRequestRunnable.java
@@ -43,7 +43,6 @@
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.api.core.SettableApiFuture;
-import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.auth.Credentials;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auto.value.AutoValue;
@@ -189,12 +188,6 @@ public void run() {
try {
HttpRequest httpRequest = createHttpRequest();
HttpResponse httpResponse = httpRequest.execute();
- if (!httpResponse.isSuccessStatusCode()) {
- ApiExceptionFactory.createException(
- null,
- HttpJsonStatusCode.of(httpResponse.getStatusCode(), httpResponse.getStatusMessage()),
- false);
- }
if (getApiMethodDescriptor().getResponseParser() != null) {
ResponseT response =
@@ -213,7 +206,7 @@ public void run() {
static Builder newBuilder() {
return new AutoValue_HttpRequestRunnable.Builder()
- .setHeaderEnhancers(new LinkedList());
+ .setHeaderEnhancers(new LinkedList<>());
}
@AutoValue.Builder
diff --git a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java
index ccc9ae2c9..dd9cfb54a 100644
--- a/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java
+++ b/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java
@@ -29,25 +29,20 @@
*/
package com.google.api.gax.httpjson.longrunning.stub;
-import static com.google.api.gax.httpjson.longrunning.OperationsClient.ListOperationsPagedResponse;
-
import com.google.api.client.http.HttpMethods;
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
-import com.google.api.gax.httpjson.FieldsExtractor;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonLongRunningClient;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshot;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
-import com.google.api.gax.httpjson.OperationSnapshotFactory;
-import com.google.api.gax.httpjson.PollingRequestFactory;
import com.google.api.gax.httpjson.ProtoMessageRequestFormatter;
import com.google.api.gax.httpjson.ProtoMessageResponseParser;
import com.google.api.gax.httpjson.ProtoRestSerializer;
-import com.google.api.gax.longrunning.OperationSnapshot;
+import com.google.api.gax.httpjson.longrunning.OperationsClient.ListOperationsPagedResponse;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.LongRunningClient;
import com.google.api.gax.rpc.UnaryCallable;
@@ -83,37 +78,24 @@ public class HttpJsonOperationsStub extends OperationsStub {
ProtoMessageRequestFormatter.newBuilder()
.setPath(
"/v1/{name=operations}",
- new FieldsExtractor>() {
- @Override
- public Map extract(ListOperationsRequest request) {
- Map fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- serializer.putPathParam(fields, "name", request.getName());
- return fields;
- }
+ request -> {
+ Map fields = new HashMap<>();
+ ProtoRestSerializer serializer =
+ ProtoRestSerializer.create();
+ serializer.putPathParam(fields, "name", request.getName());
+ return fields;
})
.setQueryParamsExtractor(
- new FieldsExtractor>>() {
- @Override
- public Map> extract(
- ListOperationsRequest request) {
- Map> fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- serializer.putQueryParam(fields, "filter", request.getFilter());
- serializer.putQueryParam(fields, "pageSize", request.getPageSize());
- serializer.putQueryParam(fields, "pageToken", request.getPageToken());
- return fields;
- }
- })
- .setRequestBodyExtractor(
- new FieldsExtractor() {
- @Override
- public String extract(ListOperationsRequest request) {
- return null;
- }
+ request -> {
+ Map> fields = new HashMap<>();
+ ProtoRestSerializer serializer =
+ ProtoRestSerializer.create();
+ serializer.putQueryParam(fields, "filter", request.getFilter());
+ serializer.putQueryParam(fields, "pageSize", request.getPageSize());
+ serializer.putQueryParam(fields, "pageToken", request.getPageToken());
+ return fields;
})
+ .setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.newBuilder()
@@ -130,53 +112,25 @@ public String extract(ListOperationsRequest request) {
ProtoMessageRequestFormatter.newBuilder()
.setPath(
"/v1/{name=operations/**}",
- new FieldsExtractor>() {
- @Override
- public Map extract(GetOperationRequest request) {
- Map fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- serializer.putPathParam(fields, "name", request.getName());
- return fields;
- }
- })
- .setQueryParamsExtractor(
- new FieldsExtractor>>() {
- @Override
- public Map> extract(GetOperationRequest request) {
- Map> fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- return fields;
- }
- })
- .setRequestBodyExtractor(
- new FieldsExtractor() {
- @Override
- public String extract(GetOperationRequest request) {
- return null;
- }
+ request -> {
+ Map fields = new HashMap<>();
+ ProtoRestSerializer serializer =
+ ProtoRestSerializer.create();
+ serializer.putPathParam(fields, "name", request.getName());
+ return fields;
})
+ .setQueryParamsExtractor(request -> new HashMap<>())
+ .setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.build())
.setOperationSnapshotFactory(
- new OperationSnapshotFactory() {
- @Override
- public OperationSnapshot create(
- GetOperationRequest request, Operation response) {
- return HttpJsonOperationSnapshot.create(response);
- }
- })
+ (request, response) -> HttpJsonOperationSnapshot.create(response))
.setPollingRequestFactory(
- new PollingRequestFactory() {
- @Override
- public GetOperationRequest create(String compoundOperationId) {
- return GetOperationRequest.newBuilder().setName(compoundOperationId).build();
- }
- })
+ compoundOperationId ->
+ GetOperationRequest.newBuilder().setName(compoundOperationId).build())
.build();
private static final ApiMethodDescriptor
@@ -188,34 +142,15 @@ public GetOperationRequest create(String compoundOperationId) {
ProtoMessageRequestFormatter.newBuilder()
.setPath(
"/v1/{name=operations/**}",
- new FieldsExtractor>() {
- @Override
- public Map extract(DeleteOperationRequest request) {
- Map fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- serializer.putPathParam(fields, "name", request.getName());
- return fields;
- }
- })
- .setQueryParamsExtractor(
- new FieldsExtractor>>() {
- @Override
- public Map> extract(
- DeleteOperationRequest request) {
- Map> fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- return fields;
- }
- })
- .setRequestBodyExtractor(
- new FieldsExtractor() {
- @Override
- public String extract(DeleteOperationRequest request) {
- return null;
- }
+ request -> {
+ Map fields = new HashMap<>();
+ ProtoRestSerializer serializer =
+ ProtoRestSerializer.create();
+ serializer.putPathParam(fields, "name", request.getName());
+ return fields;
})
+ .setQueryParamsExtractor(request -> new HashMap<>())
+ .setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.newBuilder()
@@ -232,34 +167,15 @@ public String extract(DeleteOperationRequest request) {
ProtoMessageRequestFormatter.newBuilder()
.setPath(
"/v1/{name=operations/**}:cancel",
- new FieldsExtractor>() {
- @Override
- public Map extract(CancelOperationRequest request) {
- Map fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- serializer.putPathParam(fields, "name", request.getName());
- return fields;
- }
- })
- .setQueryParamsExtractor(
- new FieldsExtractor>>() {
- @Override
- public Map> extract(
- CancelOperationRequest request) {
- Map> fields = new HashMap<>();
- ProtoRestSerializer serializer =
- ProtoRestSerializer.create();
- return fields;
- }
- })
- .setRequestBodyExtractor(
- new FieldsExtractor() {
- @Override
- public String extract(CancelOperationRequest request) {
- return null;
- }
+ request -> {
+ Map fields = new HashMap<>();
+ ProtoRestSerializer serializer =
+ ProtoRestSerializer.create();
+ serializer.putPathParam(fields, "name", request.getName());
+ return fields;
})
+ .setQueryParamsExtractor(request -> new HashMap<>())
+ .setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.newBuilder()
@@ -355,30 +271,29 @@ protected HttpJsonOperationsStub(
.setTypeRegistry(typeRegistry)
.build();
- this.listOperationsCallable =
+ listOperationsCallable =
callableFactory.createUnaryCallable(
listOperationsTransportSettings, settings.listOperationsSettings(), clientContext);
- this.listOperationsPagedCallable =
+ listOperationsPagedCallable =
callableFactory.createPagedCallable(
listOperationsTransportSettings, settings.listOperationsSettings(), clientContext);
- this.getOperationCallable =
+ getOperationCallable =
callableFactory.createUnaryCallable(
getOperationTransportSettings, settings.getOperationSettings(), clientContext);
- this.deleteOperationCallable =
+ deleteOperationCallable =
callableFactory.createUnaryCallable(
deleteOperationTransportSettings, settings.deleteOperationSettings(), clientContext);
- this.cancelOperationCallable =
+ cancelOperationCallable =
callableFactory.createUnaryCallable(
cancelOperationTransportSettings, settings.cancelOperationSettings(), clientContext);
- this.longRunningClient =
- new HttpJsonLongRunningClient(
+ longRunningClient =
+ new HttpJsonLongRunningClient<>(
getOperationCallable,
getOperationMethodDescriptor.getOperationSnapshotFactory(),
getOperationMethodDescriptor.getPollingRequestFactory());
- this.backgroundResources =
- new BackgroundResourceAggregation(clientContext.getBackgroundResources());
+ backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
@InternalApi
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ApiMessageOperationTransformersTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ApiMessageOperationTransformersTest.java
index edf0f56ce..d498e56c5 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ApiMessageOperationTransformersTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ApiMessageOperationTransformersTest.java
@@ -54,7 +54,7 @@ public void testResponseTransformer() {
ResponseTransformer transformer = ResponseTransformer.create(EmptyMessage.class);
EmptyMessage emptyResponse = EmptyMessage.getDefaultInstance();
- FakeMetadataMessage metadata = new FakeMetadataMessage(Status.PENDING, Code.OK);
+ FakeMetadataMessage> metadata = new FakeMetadataMessage<>(Status.PENDING, Code.OK);
OperationSnapshot operationSnapshot =
new OperationSnapshotImpl(
new FakeOperationMessage<>("Pending; no response method", emptyResponse, metadata));
@@ -66,7 +66,7 @@ public void testResponseTransformer() {
public void testResponseTransformer_exception() {
ResponseTransformer transformer = ResponseTransformer.create(EmptyMessage.class);
EmptyMessage emptyResponse = EmptyMessage.getDefaultInstance();
- FakeMetadataMessage metadata = new FakeMetadataMessage(Status.PENDING, Code.UNAVAILABLE);
+ FakeMetadataMessage> metadata = new FakeMetadataMessage<>(Status.PENDING, Code.UNAVAILABLE);
OperationSnapshot operationSnapshot =
new OperationSnapshotImpl(
new FakeOperationMessage<>("Unavailable; no response method", emptyResponse, metadata));
@@ -81,7 +81,7 @@ public void testResponseTransformer_exception() {
@Test
public void testResponseTransformer_mismatchedTypes() {
ResponseTransformer transformer = ResponseTransformer.create(EmptyMessage.class);
- FakeMetadataMessage metadata = new FakeMetadataMessage(Status.PENDING, Code.OK);
+ FakeMetadataMessage> metadata = new FakeMetadataMessage<>(Status.PENDING, Code.OK);
ApiMessage bananaResponse =
new FakeApiMessage(ImmutableMap.of("name", "banana"), null, null);
OperationSnapshot operationSnapshot =
@@ -100,8 +100,9 @@ public void testMetadataTransformer() {
MetadataTransformer transformer =
MetadataTransformer.create(FakeMetadataMessage.class);
EmptyMessage returnType = EmptyMessage.getDefaultInstance();
- FakeMetadataMessage metadataMessage = new FakeMetadataMessage(Status.PENDING, Code.OK);
- FakeOperationMessage operation = new FakeOperationMessage<>("foo", returnType, metadataMessage);
+ FakeMetadataMessage> metadataMessage = new FakeMetadataMessage<>(Status.PENDING, Code.OK);
+ FakeOperationMessage, ?> operation =
+ new FakeOperationMessage<>("foo", returnType, metadataMessage);
OperationSnapshot operationSnapshot = new OperationSnapshotImpl(operation);
Truth.assertThat(transformer.apply(operationSnapshot)).isEqualTo(metadataMessage);
}
@@ -110,10 +111,10 @@ public void testMetadataTransformer() {
public void testMetadataTransformer_mismatchedTypes() {
MetadataTransformer transformer =
MetadataTransformer.create(FakeOperationMessage.class);
- FakeMetadataMessage metadataMessage = new FakeMetadataMessage(Status.PENDING, Code.OK);
+ FakeMetadataMessage> metadataMessage = new FakeMetadataMessage<>(Status.PENDING, Code.OK);
ApiMessage bananaResponse =
new FakeApiMessage(ImmutableMap.of("name", "banana"), null, null);
- FakeOperationMessage metadata =
+ FakeOperationMessage, ?> metadata =
new FakeOperationMessage<>("No response method", bananaResponse, metadataMessage);
OperationSnapshot operationSnapshot = new OperationSnapshotImpl(metadata);
try {
@@ -139,6 +140,7 @@ public FakeMetadataMessage(Status status, Code code) {
this.code = code;
}
+ @Override
public Object getFieldValue(String fieldName) {
if ("status".equals(fieldName)) {
return status;
@@ -149,10 +151,12 @@ public Object getFieldValue(String fieldName) {
return null;
}
+ @Override
public List getFieldMask() {
return null;
}
+ @Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@@ -172,6 +176,7 @@ public FakeOperationMessage(String name, ResponseT responseT, MetadataT metadata
this.metadata = metadata;
}
+ @Override
public Object getFieldValue(String fieldName) {
if ("name".equals(fieldName)) {
return name;
@@ -185,10 +190,12 @@ public Object getFieldValue(String fieldName) {
return null;
}
+ @Override
public List getFieldMask() {
return null;
}
+ @Override
public ResponseT getApiMessageRequestBody() {
return responseT;
}
@@ -196,9 +203,9 @@ public ResponseT getApiMessageRequestBody() {
private static class OperationSnapshotImpl implements OperationSnapshot {
- private final FakeOperationMessage operation;
+ private final FakeOperationMessage, ?> operation;
- public OperationSnapshotImpl(FakeOperationMessage operation) {
+ public OperationSnapshotImpl(FakeOperationMessage, ?> operation) {
this.operation = operation;
}
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java
index 9efa4cd7a..4d0785f24 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonCallableFactoryTest.java
@@ -55,7 +55,7 @@ public void testGetSpanName() {
for (Entry entry : validNames.entrySet()) {
@SuppressWarnings("unchecked")
- ApiMethodDescriptor descriptor =
+ ApiMethodDescriptor, ?> descriptor =
ApiMethodDescriptor.newBuilder()
.setFullMethodName(entry.getKey())
.setHttpMethod(HttpMethods.POST)
@@ -74,7 +74,7 @@ public void testGetSpanNameInvalid() {
for (String invalidName : invalidNames) {
@SuppressWarnings("unchecked")
- ApiMethodDescriptor descriptor =
+ ApiMethodDescriptor, ?> descriptor =
ApiMethodDescriptor.newBuilder()
.setFullMethodName(invalidName)
.setHttpMethod(HttpMethods.POST)
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshotTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshotTest.java
index 20561fe17..6ff331c2c 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshotTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonOperationSnapshotTest.java
@@ -67,7 +67,7 @@ public void newBuilderTestWithError() {
.build();
assertEquals(testOperationSnapshot.getErrorMessage(), "Forbidden");
- assertEquals(testOperationSnapshot.getErrorCode(), HttpJsonStatusCode.of(403, "Forbidden"));
+ assertEquals(testOperationSnapshot.getErrorCode(), HttpJsonStatusCode.of(403));
assertTrue(testOperationSnapshot.isDone());
}
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonStatusCodeTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonStatusCodeTest.java
index 7117026e8..7c7664c3b 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonStatusCodeTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonStatusCodeTest.java
@@ -29,12 +29,10 @@
*/
package com.google.api.gax.httpjson;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
-import com.google.api.gax.rpc.StatusCode;
-import java.util.Arrays;
+import com.google.api.gax.rpc.StatusCode.Code;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
@@ -43,9 +41,9 @@ public class HttpJsonStatusCodeTest {
@Test
public void rpcCodeToStatusCodeTest() {
- Set allCodes = new HashSet<>();
+ Set allCodes = new HashSet<>();
for (com.google.rpc.Code rpcCode : com.google.rpc.Code.values()) {
- StatusCode.Code statusCode;
+ Code statusCode;
try {
statusCode = HttpJsonStatusCode.rpcCodeToStatusCode(rpcCode);
} catch (IllegalArgumentException e) {
@@ -55,77 +53,39 @@ public void rpcCodeToStatusCodeTest() {
continue;
}
- assertNotNull(statusCode);
+ assertThat(statusCode).isNotNull();
allCodes.add(statusCode);
}
- assertEquals(allCodes, new HashSet<>(Arrays.asList(StatusCode.Code.values())));
+ assertThat(Code.values()).asList().containsExactlyElementsIn(allCodes);
}
@Test
public void httpStatusToStatusCodeTest() {
- // The HTTP status code conversion logic is currently in the process of being standardized,
- // the tested logic may change in nearest future.
- final String defaultMessage = "anything";
- assertEquals(
- StatusCode.Code.OK, HttpJsonStatusCode.httpStatusToStatusCode(200, defaultMessage));
- assertEquals(
- StatusCode.Code.OUT_OF_RANGE,
- HttpJsonStatusCode.httpStatusToStatusCode(400, HttpJsonStatusCode.OUT_OF_RANGE));
- assertEquals(
- StatusCode.Code.FAILED_PRECONDITION,
- HttpJsonStatusCode.httpStatusToStatusCode(400, HttpJsonStatusCode.FAILED_PRECONDITION));
- assertEquals(
- StatusCode.Code.INVALID_ARGUMENT,
- HttpJsonStatusCode.httpStatusToStatusCode(400, defaultMessage));
- assertEquals(
- StatusCode.Code.UNAUTHENTICATED,
- HttpJsonStatusCode.httpStatusToStatusCode(401, defaultMessage));
- assertEquals(
- StatusCode.Code.PERMISSION_DENIED,
- HttpJsonStatusCode.httpStatusToStatusCode(403, defaultMessage));
- assertEquals(
- StatusCode.Code.NOT_FOUND, HttpJsonStatusCode.httpStatusToStatusCode(404, defaultMessage));
- assertEquals(
- StatusCode.Code.ALREADY_EXISTS,
- HttpJsonStatusCode.httpStatusToStatusCode(409, HttpJsonStatusCode.ALREADY_EXISTS));
- assertEquals(
- StatusCode.Code.ABORTED, HttpJsonStatusCode.httpStatusToStatusCode(409, defaultMessage));
- assertEquals(
- StatusCode.Code.RESOURCE_EXHAUSTED,
- HttpJsonStatusCode.httpStatusToStatusCode(429, defaultMessage));
- assertEquals(
- StatusCode.Code.CANCELLED, HttpJsonStatusCode.httpStatusToStatusCode(499, defaultMessage));
- assertEquals(
- StatusCode.Code.DATA_LOSS,
- HttpJsonStatusCode.httpStatusToStatusCode(500, HttpJsonStatusCode.DATA_LOSS));
- assertEquals(
- StatusCode.Code.UNKNOWN,
- HttpJsonStatusCode.httpStatusToStatusCode(500, HttpJsonStatusCode.UNKNOWN));
- assertEquals(
- StatusCode.Code.INTERNAL, HttpJsonStatusCode.httpStatusToStatusCode(500, defaultMessage));
- assertEquals(
- StatusCode.Code.UNIMPLEMENTED,
- HttpJsonStatusCode.httpStatusToStatusCode(501, defaultMessage));
- assertEquals(
- StatusCode.Code.UNAVAILABLE,
- HttpJsonStatusCode.httpStatusToStatusCode(503, defaultMessage));
- assertEquals(
- StatusCode.Code.DEADLINE_EXCEEDED,
- HttpJsonStatusCode.httpStatusToStatusCode(504, defaultMessage));
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(200)).isEqualTo(Code.OK);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(201)).isEqualTo(Code.OK);
- try {
- HttpJsonStatusCode.httpStatusToStatusCode(411, defaultMessage);
- fail();
- } catch (IllegalStateException e) {
- // expected
- }
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(400)).isEqualTo(Code.INVALID_ARGUMENT);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(401)).isEqualTo(Code.UNAUTHENTICATED);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(403)).isEqualTo(Code.PERMISSION_DENIED);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(404)).isEqualTo(Code.NOT_FOUND);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(409)).isEqualTo(Code.ABORTED);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(416)).isEqualTo(Code.OUT_OF_RANGE);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(429)).isEqualTo(Code.RESOURCE_EXHAUSTED);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(499)).isEqualTo(Code.CANCELLED);
- try {
- HttpJsonStatusCode.httpStatusToStatusCode(666, defaultMessage);
- fail();
- } catch (IllegalArgumentException e) {
- // expected
- }
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(405)).isEqualTo(Code.FAILED_PRECONDITION);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(408)).isEqualTo(Code.FAILED_PRECONDITION);
+
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(500)).isEqualTo(Code.INTERNAL);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(501)).isEqualTo(Code.UNIMPLEMENTED);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(502)).isEqualTo(Code.INTERNAL);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(503)).isEqualTo(Code.UNAVAILABLE);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(504)).isEqualTo(Code.DEADLINE_EXCEEDED);
+
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(100)).isEqualTo(Code.UNKNOWN);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(300)).isEqualTo(Code.UNKNOWN);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(302)).isEqualTo(Code.UNKNOWN);
+ assertThat(HttpJsonStatusCode.httpStatusToStatusCode(600)).isEqualTo(Code.UNKNOWN);
}
}
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ProtoOperationTransformersTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ProtoOperationTransformersTest.java
index 549b386dc..38685f17b 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ProtoOperationTransformersTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/ProtoOperationTransformersTest.java
@@ -29,11 +29,13 @@
*/
package com.google.api.gax.httpjson;
+import static org.junit.Assert.assertThrows;
+
import com.google.api.gax.httpjson.ProtoOperationTransformers.MetadataTransformer;
import com.google.api.gax.httpjson.ProtoOperationTransformers.ResponseTransformer;
import com.google.api.gax.longrunning.OperationSnapshot;
-import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.UnavailableException;
+import com.google.api.gax.rpc.UnknownException;
import com.google.common.truth.Truth;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
@@ -41,7 +43,6 @@
import com.google.rpc.Status;
import com.google.type.Color;
import com.google.type.Money;
-import org.junit.Assert;
import org.junit.Test;
public class ProtoOperationTransformersTest {
@@ -94,14 +95,12 @@ public void testAnyResponseTransformer_exception() {
OperationSnapshot operationSnapshot =
HttpJsonOperationSnapshot.create(
Operation.newBuilder().setResponse(Any.pack(inputMoney)).setError(status).build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("ResponseTransformer should have thrown an exception");
- } catch (UnavailableException expected) {
- Truth.assertThat(expected)
- .hasMessageThat()
- .contains("failed with status = HttpJsonStatusCode{statusCode=UNAVAILABLE}");
- }
+
+ Exception exception =
+ assertThrows(UnavailableException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception)
+ .hasMessageThat()
+ .contains("failed with status = HttpJsonStatusCode{statusCode=UNAVAILABLE}");
}
@Test
@@ -114,12 +113,9 @@ public void testAnyResponseTransformer_mismatchedTypes() {
.setResponse(Any.pack(Color.getDefaultInstance()))
.setError(status)
.build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("ResponseTransformer should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).hasMessageThat().contains("Failed to unpack object");
- }
+ Exception exception =
+ assertThrows(UnknownException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception).hasMessageThat().contains("encountered a problem unpacking it");
}
@Test
@@ -142,11 +138,8 @@ public void testAnyMetadataTransformer_mismatchedTypes() {
.setMetadata(Any.pack(Color.getDefaultInstance()))
.setError(status)
.build());
- try {
- transformer.apply(operationSnapshot);
- Assert.fail("MetadataTransformer should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).hasMessageThat().contains("Failed to unpack object");
- }
+ Exception exception =
+ assertThrows(UnknownException.class, () -> transformer.apply(operationSnapshot));
+ Truth.assertThat(exception).hasMessageThat().contains("encountered a problem unpacking it");
}
}
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java
index c6a68b661..d03d7e57f 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/RetryingTest.java
@@ -29,6 +29,8 @@
*/
package com.google.api.gax.httpjson;
+import static org.junit.Assert.assertThrows;
+
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpStatusCodes;
@@ -53,7 +55,6 @@
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.Set;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -65,17 +66,13 @@
public class RetryingTest {
@SuppressWarnings("unchecked")
- private UnaryCallable callInt = Mockito.mock(UnaryCallable.class);
+ private final UnaryCallable callInt = Mockito.mock(UnaryCallable.class);
private RecordingScheduler executor;
private FakeApiClock fakeClock;
private ClientContext clientContext;
- private static int STATUS_SERVER_ERROR = 500;
- private static int STATUS_DEADLINE_EXCEEDED = 504;
- private static int STATUS_FAILED_PRECONDITION = 400;
-
- private static String DEADLINE_EXCEEDED = "DEADLINE_EXCEEDED";
+ private static final int HTTP_CODE_PRECONDITION_FAILED = 412;
private HttpResponseException HTTP_SERVICE_UNAVAILABLE_EXCEPTION =
new HttpResponseException.Builder(
@@ -112,17 +109,13 @@ public void teardown() {
executor.shutdownNow();
}
- static ApiFuture immediateFailedFuture(Throwable t) {
- return ApiFutures.immediateFailedFuture(t);
- }
-
@Test
public void retry() {
ImmutableSet retryable = ImmutableSet.of(Code.UNAVAILABLE);
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
.thenReturn(ApiFutures.immediateFuture(2));
UnaryCallSettings callSettings =
@@ -132,7 +125,7 @@ public void retry() {
Truth.assertThat(callable.call(1)).isEqualTo(2);
}
- @Test(expected = ApiException.class)
+ @Test
public void retryTotalTimeoutExceeded() {
ImmutableSet retryable = ImmutableSet.of(Code.UNAVAILABLE);
HttpResponseException httpResponseException =
@@ -148,7 +141,7 @@ public void retryTotalTimeoutExceeded() {
HttpJsonStatusCode.of(Code.FAILED_PRECONDITION),
false);
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(apiException))
+ .thenReturn(ApiFutures.immediateFailedFuture(apiException))
.thenReturn(ApiFutures.immediateFuture(2));
RetrySettings retrySettings =
@@ -160,30 +153,30 @@ public void retryTotalTimeoutExceeded() {
UnaryCallSettings callSettings = createSettings(retryable, retrySettings);
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- callable.call(1);
+ assertThrows(ApiException.class, () -> callable.call(1));
}
- @Test(expected = ApiException.class)
+ @Test
public void retryMaxAttemptsExceeded() {
ImmutableSet retryable = ImmutableSet.of(Code.UNAVAILABLE);
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
.thenReturn(ApiFutures.immediateFuture(2));
RetrySettings retrySettings = FAST_RETRY_SETTINGS.toBuilder().setMaxAttempts(2).build();
UnaryCallSettings callSettings = createSettings(retryable, retrySettings);
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- callable.call(1);
+ assertThrows(ApiException.class, () -> callable.call(1));
}
@Test
public void retryWithinMaxAttempts() {
ImmutableSet retryable = ImmutableSet.of(Code.UNAVAILABLE);
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
- .thenReturn(RetryingTest.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
+ .thenReturn(ApiFutures.immediateFailedFuture(HTTP_SERVICE_UNAVAILABLE_EXCEPTION))
.thenReturn(ApiFutures.immediateFuture(2));
RetrySettings retrySettings = FAST_RETRY_SETTINGS.toBuilder().setMaxAttempts(3).build();
@@ -199,13 +192,14 @@ public void retryOnStatusUnknown() {
ImmutableSet retryable = ImmutableSet.of(Code.UNKNOWN);
HttpResponseException throwable =
new HttpResponseException.Builder(
- STATUS_SERVER_ERROR, "server unavailable", new HttpHeaders())
- .setMessage("UNKNOWN")
+ HttpStatusCodes.STATUS_CODE_TEMPORARY_REDIRECT,
+ "temporary redirect",
+ new HttpHeaders())
.build();
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable))
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable))
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable))
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable))
.thenReturn(ApiFutures.immediateFuture(2));
UnaryCallSettings callSettings =
createSettings(retryable, FAST_RETRY_SETTINGS);
@@ -219,24 +213,21 @@ public void retryOnUnexpectedException() {
ImmutableSet retryable = ImmutableSet.of(Code.UNKNOWN);
Throwable throwable = new RuntimeException("foobar");
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable));
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable));
UnaryCallSettings callSettings =
createSettings(retryable, FAST_RETRY_SETTINGS);
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- try {
- callable.call(1);
- Assert.fail("Callable should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).hasCauseThat().isSameInstanceAs(throwable);
- }
+ ApiException exception = assertThrows(ApiException.class, () -> callable.call(1));
+ Truth.assertThat(exception).hasCauseThat().isSameInstanceAs(throwable);
}
@Test
public void retryNoRecover() {
ImmutableSet retryable = ImmutableSet.of(Code.UNAVAILABLE);
HttpResponseException httpResponseException =
- new HttpResponseException.Builder(STATUS_FAILED_PRECONDITION, "foobar", new HttpHeaders())
+ new HttpResponseException.Builder(
+ HTTP_CODE_PRECONDITION_FAILED, "foobar", new HttpHeaders())
.build();
ApiException apiException =
ApiExceptionFactory.createException(
@@ -245,18 +236,14 @@ public void retryNoRecover() {
HttpJsonStatusCode.of(Code.FAILED_PRECONDITION),
false);
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(apiException))
+ .thenReturn(ApiFutures.immediateFailedFuture(apiException))
.thenReturn(ApiFutures.immediateFuture(2));
UnaryCallSettings callSettings =
createSettings(retryable, FAST_RETRY_SETTINGS);
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- try {
- callable.call(1);
- Assert.fail("Callable should have thrown an exception");
- } catch (ApiException expected) {
- Truth.assertThat(expected).isSameInstanceAs(apiException);
- }
+ ApiException exception = assertThrows(ApiException.class, () -> callable.call(1));
+ Truth.assertThat(exception).isSameInstanceAs(apiException);
}
@Test
@@ -267,7 +254,7 @@ public void retryKeepFailing() {
HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE, "Unavailable", new HttpHeaders())
.build();
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable));
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable));
UnaryCallSettings callSettings =
createSettings(retryable, FAST_RETRY_SETTINGS);
UnaryCallable callable =
@@ -275,13 +262,10 @@ public void retryKeepFailing() {
// Need to advance time inside the call.
ApiFuture future = callable.futureCall(1);
- try {
- Futures.getUnchecked(future);
- Assert.fail("Callable should have thrown an exception");
- } catch (UncheckedExecutionException expected) {
- Truth.assertThat(expected).hasCauseThat().isInstanceOf(ApiException.class);
- Truth.assertThat(expected).hasCauseThat().hasMessageThat().contains("Unavailable");
- }
+ UncheckedExecutionException exception =
+ assertThrows(UncheckedExecutionException.class, () -> Futures.getUnchecked(future));
+ Truth.assertThat(exception).hasCauseThat().isInstanceOf(ApiException.class);
+ Truth.assertThat(exception).hasCauseThat().hasMessageThat().contains("Unavailable");
}
@Test
@@ -302,46 +286,37 @@ public void testKnownStatusCode() {
+ "}";
HttpResponseException throwable =
new HttpResponseException.Builder(
- STATUS_FAILED_PRECONDITION,
- HttpJsonStatusCode.FAILED_PRECONDITION,
- new HttpHeaders())
+ HTTP_CODE_PRECONDITION_FAILED, "precondition failed", new HttpHeaders())
.setMessage(throwableMessage)
.build();
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(throwable));
+ .thenReturn(ApiFutures.immediateFailedFuture(throwable));
UnaryCallSettings callSettings =
UnaryCallSettings.newUnaryCallSettingsBuilder()
.setRetryableCodes(retryable)
.build();
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- try {
- callable.call(1);
- Assert.fail("Callable should have thrown an exception");
- } catch (FailedPreconditionException expected) {
- Truth.assertThat(((HttpJsonStatusCode) expected.getStatusCode()).getTransportCode())
- .isEqualTo(STATUS_FAILED_PRECONDITION);
- Truth.assertThat(expected.getMessage()).contains(HttpJsonStatusCode.FAILED_PRECONDITION);
- }
+ ApiException exception =
+ assertThrows(FailedPreconditionException.class, () -> callable.call(1));
+ Truth.assertThat(exception.getStatusCode().getTransportCode())
+ .isEqualTo(HTTP_CODE_PRECONDITION_FAILED);
+ Truth.assertThat(exception).hasMessageThat().contains("precondition failed");
}
@Test
public void testUnknownStatusCode() {
ImmutableSet retryable = ImmutableSet.of();
Mockito.when(callInt.futureCall((Integer) Mockito.any(), (ApiCallContext) Mockito.any()))
- .thenReturn(RetryingTest.immediateFailedFuture(new RuntimeException("unknown")));
+ .thenReturn(ApiFutures.immediateFailedFuture(new RuntimeException("unknown")));
UnaryCallSettings callSettings =
UnaryCallSettings.newUnaryCallSettingsBuilder()
.setRetryableCodes(retryable)
.build();
UnaryCallable callable =
HttpJsonCallableFactory.createUnaryCallable(callInt, callSettings, clientContext);
- try {
- callable.call(1);
- Assert.fail("Callable should have thrown an exception");
- } catch (UnknownException expected) {
- Truth.assertThat(expected.getMessage()).isEqualTo("java.lang.RuntimeException: unknown");
- }
+ UnknownException exception = assertThrows(UnknownException.class, () -> callable.call(1));
+ Truth.assertThat(exception).hasMessageThat().isEqualTo("java.lang.RuntimeException: unknown");
}
public static UnaryCallSettings createSettings(
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/OperationsClientTest.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/OperationsClientTest.java
index 96a8ac740..1240ba742 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/OperationsClientTest.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/OperationsClientTest.java
@@ -29,10 +29,9 @@
*/
package com.google.api.gax.httpjson.longrunning;
-import static com.google.api.gax.httpjson.longrunning.OperationsClient.ListOperationsPagedResponse;
-
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
+import com.google.api.gax.httpjson.longrunning.OperationsClient.ListOperationsPagedResponse;
import com.google.api.gax.httpjson.longrunning.stub.HttpJsonOperationsStub;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
@@ -52,7 +51,6 @@
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
-import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -81,16 +79,13 @@ public static void stopServer() {
client.close();
}
- @Before
- public void setUp() {}
-
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
mockService.reset();
}
@Test
- public void listOperationsTest() throws Exception {
+ public void listOperationsTest() {
Operation responsesElement = Operation.newBuilder().build();
ListOperationsResponse expectedResponse =
ListOperationsResponse.newBuilder()
@@ -125,7 +120,7 @@ public void listOperationsTest() throws Exception {
}
@Test
- public void listOperationsExceptionTest() throws Exception {
+ public void listOperationsExceptionTest() {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
@@ -142,7 +137,7 @@ public void listOperationsExceptionTest() throws Exception {
}
@Test
- public void getOperationTest() throws Exception {
+ public void getOperationTest() {
Operation expectedResponse =
Operation.newBuilder()
.setName("operations/hey1")
@@ -172,7 +167,7 @@ public void getOperationTest() throws Exception {
}
@Test
- public void getOperationExceptionTest() throws Exception {
+ public void getOperationExceptionTest() {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
@@ -188,7 +183,7 @@ public void getOperationExceptionTest() throws Exception {
}
@Test
- public void deleteOperationTest() throws Exception {
+ public void deleteOperationTest() {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
@@ -212,7 +207,7 @@ public void deleteOperationTest() throws Exception {
}
@Test
- public void deleteOperationExceptionTest() throws Exception {
+ public void deleteOperationExceptionTest() {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
@@ -228,7 +223,7 @@ public void deleteOperationExceptionTest() throws Exception {
}
@Test
- public void cancelOperationTest() throws Exception {
+ public void cancelOperationTest() {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
@@ -252,7 +247,7 @@ public void cancelOperationTest() throws Exception {
}
@Test
- public void cancelOperationExceptionTest() throws Exception {
+ public void cancelOperationExceptionTest() {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
diff --git a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java
index 68f6fa6b8..e6fb4d586 100644
--- a/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java
+++ b/gax-httpjson/src/test/java/com/google/api/gax/httpjson/testing/MockHttpService.java
@@ -68,7 +68,7 @@ public final class MockHttpService extends MockHttpTransport {
*/
public MockHttpService(List serviceMethodDescriptors, String pathPrefix) {
this.serviceMethodDescriptors = ImmutableList.copyOf(serviceMethodDescriptors);
- this.endpoint = pathPrefix;
+ endpoint = pathPrefix;
}
@Override
diff --git a/gax/build.gradle b/gax/build.gradle
index ae94e1a05..3e3a1f41e 100644
--- a/gax/build.gradle
+++ b/gax/build.gradle
@@ -1,7 +1,7 @@
archivesBaseName = "gax"
// TODO: Populate this from dependencies.properties version property (for proper Gradle-Bazel sync)
-project.version = "2.7.0" // {x-version-update:gax:current}
+project.version = "2.7.1" // {x-version-update:gax:current}
dependencies {
api(libraries['maven.com_google_api_api_common'],
diff --git a/gax/src/main/java/com/google/api/gax/rpc/ApiExceptionFactory.java b/gax/src/main/java/com/google/api/gax/rpc/ApiExceptionFactory.java
index d1b787e85..9820b751e 100644
--- a/gax/src/main/java/com/google/api/gax/rpc/ApiExceptionFactory.java
+++ b/gax/src/main/java/com/google/api/gax/rpc/ApiExceptionFactory.java
@@ -43,8 +43,6 @@ public static ApiException createException(
return new CancelledException(cause, statusCode, retryable);
case NOT_FOUND:
return new NotFoundException(cause, statusCode, retryable);
- case UNKNOWN:
- return new UnknownException(cause, statusCode, retryable);
case INVALID_ARGUMENT:
return new InvalidArgumentException(cause, statusCode, retryable);
case DEADLINE_EXCEEDED:
@@ -72,6 +70,7 @@ public static ApiException createException(
case UNAUTHENTICATED:
return new UnauthenticatedException(cause, statusCode, retryable);
+ case UNKNOWN: // Fall through.
default:
return new UnknownException(cause, statusCode, retryable);
}
@@ -84,8 +83,6 @@ public static ApiException createException(
return new CancelledException(message, cause, statusCode, retryable);
case NOT_FOUND:
return new NotFoundException(message, cause, statusCode, retryable);
- case UNKNOWN:
- return new UnknownException(message, cause, statusCode, retryable);
case INVALID_ARGUMENT:
return new InvalidArgumentException(message, cause, statusCode, retryable);
case DEADLINE_EXCEEDED:
@@ -113,8 +110,9 @@ public static ApiException createException(
case UNAUTHENTICATED:
return new UnauthenticatedException(message, cause, statusCode, retryable);
+ case UNKNOWN: // Fall through.
default:
- return new UnknownException(cause, statusCode, retryable);
+ return new UnknownException(message, cause, statusCode, retryable);
}
}
}
diff --git a/gax/src/main/java/com/google/api/gax/rpc/internal/ApiCallContextOptions.java b/gax/src/main/java/com/google/api/gax/rpc/internal/ApiCallContextOptions.java
index daf64679c..a0873f309 100644
--- a/gax/src/main/java/com/google/api/gax/rpc/internal/ApiCallContextOptions.java
+++ b/gax/src/main/java/com/google/api/gax/rpc/internal/ApiCallContextOptions.java
@@ -57,7 +57,7 @@ public static ApiCallContextOptions getDefaultOptions() {
public ApiCallContextOptions withOption(Key key, T value) {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(value);
- ImmutableMap.Builder builder = ImmutableMap.builder();
+ ImmutableMap.Builder