Skip to content

Commit e9746f8

Browse files
authored
fix: make use of ImmutableMap.Builder#buildOrThrow graceful (#2159)
`buildOrThrow` was added in guava 31.0, and while we specify a min version >= 31.0, sometimes our library is used in environments that set different guava version (usually due to platform pinned versions). We do not strictly need this method, as it has the same behavior of `ImmutableMap.Builder#build()` but with a more clear name (`ImmutableMap.Builder` never allowed duplicate keys). Manually tested, but creating a separate project that did the following in its maven config: ``` <dependencyManagement> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>24.0-jre</version> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-storage-bom</artifactId> <version>2.26.1-SNAPSHOT</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-storage</artifactId> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </exclusion> </exclusions> </dependency> </dependencies> ``` Then issuing any RPC.
1 parent a7ac773 commit e9746f8

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

google-cloud-storage/src/main/java/com/google/cloud/storage/UnifiedOpts.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2086,6 +2086,21 @@ public String toString() {
20862086
*/
20872087
@SuppressWarnings("unchecked")
20882088
static final class Opts<T extends Opt> {
2089+
private static final Function<ImmutableMap.Builder<?, ?>, ImmutableMap<?, ?>> mapBuild;
2090+
2091+
static {
2092+
Function<ImmutableMap.Builder<?, ?>, ImmutableMap<?, ?>> tmp;
2093+
// buildOrThrow was added in guava 31.0
2094+
// if it fails, fallback to the older build() method instead.
2095+
// The behavior was the same, but the new name makes the behavior clear
2096+
try {
2097+
ImmutableMap.builder().buildOrThrow();
2098+
tmp = ImmutableMap.Builder::buildOrThrow;
2099+
} catch (NoSuchMethodError e) {
2100+
tmp = ImmutableMap.Builder::build;
2101+
}
2102+
mapBuild = tmp;
2103+
}
20892104

20902105
private final ImmutableList<T> opts;
20912106

@@ -2172,7 +2187,7 @@ Opts<T> projectAsSource() {
21722187
ImmutableMap<StorageRpc.Option, ?> getRpcOptions() {
21732188
ImmutableMap.Builder<StorageRpc.Option, Object> builder =
21742189
rpcOptionMapper().apply(ImmutableMap.builder());
2175-
return builder.buildOrThrow();
2190+
return (ImmutableMap<StorageRpc.Option, ?>) mapBuild.apply(builder);
21762191
}
21772192

21782193
Mapper<GrpcCallContext> grpcMetadataMapper() {

0 commit comments

Comments
 (0)