From 8d1678eef5a774b449ba3f268ba4555dd2238b6c Mon Sep 17 00:00:00 2001 From: Mikayla Thompson Date: Wed, 15 Jan 2025 14:55:42 -0700 Subject: [PATCH] Sonarqube Fix - Ensure optional is present before `get` (#1233) * Ensure optional is present before `get` * Add specific exception when instantiating a client fails Signed-off-by: Mikayla Thompson --- .../bulkload/common/OpenSearchClientFactory.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/RFS/src/main/java/org/opensearch/migrations/bulkload/common/OpenSearchClientFactory.java b/RFS/src/main/java/org/opensearch/migrations/bulkload/common/OpenSearchClientFactory.java index ec9639823..8aa77c3bf 100644 --- a/RFS/src/main/java/org/opensearch/migrations/bulkload/common/OpenSearchClientFactory.java +++ b/RFS/src/main/java/org/opensearch/migrations/bulkload/common/OpenSearchClientFactory.java @@ -46,7 +46,7 @@ public OpenSearchClient determineVersionAndCreate() { return clientClass.getConstructor(ConnectionContext.class, Version.class) .newInstance(connectionContext, version); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException("Failed to instantiate OpenSearchClient", e); + throw new ClientInstantiationException("Failed to instantiate OpenSearchClient", e); } } @@ -59,7 +59,7 @@ public OpenSearchClient determineVersionAndCreate(RestClient restClient, FailedR return clientClass.getConstructor(RestClient.class, FailedRequestsLogger.class, Version.class) .newInstance(restClient, failedRequestsLogger, version); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException("Failed to instantiate OpenSearchClient", e); + throw new ClientInstantiationException("Failed to instantiate OpenSearchClient", e); } } @@ -191,9 +191,7 @@ private Mono getVersionFromNodes(HttpResponse resp) { if (foundVersions.isEmpty()) { return Mono.error(new OpenSearchClient.OperationFailed("Unable to find any version numbers", resp)); - } - - if (foundVersions.size() == 1) { + } else if (foundVersions.size() == 1) { return Mono.just(foundVersions.stream().findFirst().get()); } @@ -209,5 +207,10 @@ private Flavor getLikelyOpenSearchFlavor() { return client.getConnectionContext().isAwsSpecificAuthentication() ? Flavor.AMAZON_MANAGED_OPENSEARCH : Flavor.OPENSEARCH; } + public static class ClientInstantiationException extends RuntimeException { + public ClientInstantiationException(String message, Exception cause) { + super(message, cause); + } + } }