diff --git a/CHANGELOG.md b/CHANGELOG.md index 80c6804c11a0b..35010e89292b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Add subdirectory-aware store module with recovery support ([#19132](https://github.com/opensearch-project/OpenSearch/pull/19132)) ### Changed +- Refactor `if-else` chains to use `Java 17 pattern matching switch expressions`(([#18965](https://github.com/opensearch-project/OpenSearch/pull/18965)) - Add CompletionStage variants to methods in the Client Interface and default to ActionListener impl ([#18998](https://github.com/opensearch-project/OpenSearch/pull/18998)) - IllegalArgumentException when scroll ID references a node not found in Cluster ([#19031](https://github.com/opensearch-project/OpenSearch/pull/19031)) - Adding ScriptedAvg class to painless spi to allowlist usage from plugins ([#19006](https://github.com/opensearch-project/OpenSearch/pull/19006)) diff --git a/libs/common/src/main/java/org/opensearch/common/Numbers.java b/libs/common/src/main/java/org/opensearch/common/Numbers.java index d5a364a4a934e..6392884dff28b 100644 --- a/libs/common/src/main/java/org/opensearch/common/Numbers.java +++ b/libs/common/src/main/java/org/opensearch/common/Numbers.java @@ -83,44 +83,60 @@ public static boolean isValidDouble(double value) { * stored value cannot be converted to a long that stores the exact same * value. */ public static long toLongExact(Number n) { - if (n instanceof Byte || n instanceof Short || n instanceof Integer || n instanceof Long) { - return n.longValue(); - } else if (n instanceof Float || n instanceof Double) { - double d = n.doubleValue(); - if (d != Math.round(d)) { - throw new IllegalArgumentException(n + " is not an integer value"); + return switch (n) { + case Byte b -> b.longValue(); + case Short s -> s.longValue(); + case Integer i -> i.longValue(); + case Long l -> l; + case Float f -> { + double d = f.doubleValue(); + if (d != Math.round(d)) { + throw new IllegalArgumentException(f + " is not an integer value"); + } + yield f.longValue(); } - return n.longValue(); - } else if (n instanceof BigDecimal) { - return ((BigDecimal) n).toBigIntegerExact().longValueExact(); - } else if (n instanceof BigInteger) { - return ((BigInteger) n).longValueExact(); - } else { - throw new IllegalArgumentException( + case Double d -> { + if (d != Math.round(d)) { + throw new IllegalArgumentException(d + " is not an integer value"); + } + yield d.longValue(); + } + case BigDecimal bd -> bd.toBigIntegerExact().longValueExact(); + case BigInteger bi -> bi.longValueExact(); + default -> throw new IllegalArgumentException( "Cannot check whether [" + n + "] of class [" + n.getClass().getName() + "] is actually a long" ); - } + }; } /** Return the {@link BigInteger} that {@code n} stores, or throws an exception if the * stored value cannot be converted to a {@link BigInteger} that stores the exact same * value. */ public static BigInteger toBigIntegerExact(Number n) { - if (n instanceof Byte || n instanceof Short || n instanceof Integer || n instanceof Long) { - return BigInteger.valueOf(n.longValue()); - } else if (n instanceof Float || n instanceof Double) { - double d = n.doubleValue(); - if (d != Math.round(d)) { - throw new IllegalArgumentException(n + " is not an integer value"); + return switch (n) { + case Byte b -> BigInteger.valueOf(b.longValue()); + case Short s -> BigInteger.valueOf(s.longValue()); + case Integer i -> BigInteger.valueOf(i.longValue()); + case Long l -> BigInteger.valueOf(l.longValue()); + case Float f -> { + double d = f.doubleValue(); + if (d != Math.round(d)) { + throw new IllegalArgumentException(f + " is not an integer value"); + } + yield BigInteger.valueOf(f.longValue()); } - return BigInteger.valueOf(n.longValue()); - } else if (n instanceof BigDecimal) { - return ((BigDecimal) n).toBigIntegerExact(); - } else if (n instanceof BigInteger) { - return ((BigInteger) n); - } else { - throw new IllegalArgumentException("Cannot convert [" + n + "] of class [" + n.getClass().getName() + "] to a BigInteger"); - } + case Double d -> { + if (d != Math.round(d)) { + throw new IllegalArgumentException(d + " is not an integer value"); + } + yield BigInteger.valueOf(d.longValue()); + } + case BigDecimal bd -> bd.toBigIntegerExact(); + case BigInteger bi -> bi; + default -> throw new IllegalArgumentException( + "Cannot convert [" + n + "] of class [" + n.getClass().getName() + "] to a BigInteger" + ); + }; } /** Return the unsigned long (as {@link BigInteger}) that {@code n} stores, or throws an exception if the diff --git a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java index c795dadf671be..765cd1cbdc960 100644 --- a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java +++ b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java @@ -112,53 +112,40 @@ private ErrorMessages() { private ExceptionsHelper() {} public static RuntimeException convertToRuntime(Exception e) { - if (e instanceof RuntimeException) { - return (RuntimeException) e; - } - return new OpenSearchException(e); + return switch (e) { + case RuntimeException re -> re; + default -> new OpenSearchException(e); + }; } public static OpenSearchException convertToOpenSearchException(Exception e) { - if (e instanceof OpenSearchException) { - return (OpenSearchException) e; - } - return new OpenSearchException(e); + return switch (e) { + case OpenSearchException oe -> oe; + default -> new OpenSearchException(e); + }; } public static RestStatus status(Throwable t) { - if (t != null) { - if (t instanceof OpenSearchException) { - return ((OpenSearchException) t).status(); - } else if (t instanceof IllegalArgumentException) { - return RestStatus.BAD_REQUEST; - } else if (t instanceof InputCoercionException) { - return RestStatus.BAD_REQUEST; - } else if (t instanceof JsonParseException) { - return RestStatus.BAD_REQUEST; - } else if (t instanceof OpenSearchRejectedExecutionException) { - return RestStatus.TOO_MANY_REQUESTS; - } else if (t instanceof NotXContentException) { - return RestStatus.BAD_REQUEST; - } - } - return RestStatus.INTERNAL_SERVER_ERROR; + return switch (t) { + case OpenSearchException ose -> ose.status(); + case IllegalArgumentException ignored -> RestStatus.BAD_REQUEST; + case InputCoercionException ignored -> RestStatus.BAD_REQUEST; + case JsonParseException ignored -> RestStatus.BAD_REQUEST; + case NotXContentException ignored -> RestStatus.BAD_REQUEST; + case OpenSearchRejectedExecutionException ignored -> RestStatus.TOO_MANY_REQUESTS; + case null, default -> RestStatus.INTERNAL_SERVER_ERROR; + }; } public static String summaryMessage(Throwable t) { - if (t != null) { - if (t instanceof OpenSearchException) { - return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]"; - } else if (t instanceof IllegalArgumentException) { - return ErrorMessages.INVALID_ARGUMENT; - } else if (t instanceof InputCoercionException) { - return ErrorMessages.JSON_COERCION_FAILED; - } else if (t instanceof JsonParseException) { - return ErrorMessages.JSON_PARSE_FAILED; - } else if (t instanceof OpenSearchRejectedExecutionException) { - return ErrorMessages.TOO_MANY_REQUESTS; - } - } - return ErrorMessages.INTERNAL_FAILURE; + return switch (t) { + case OpenSearchException ose -> getExceptionSimpleClassName(t) + "[" + ose.getMessage() + "]"; + case IllegalArgumentException ignored -> ErrorMessages.INVALID_ARGUMENT; + case InputCoercionException ignored -> ErrorMessages.JSON_COERCION_FAILED; + case JsonParseException ignored -> ErrorMessages.JSON_PARSE_FAILED; + case OpenSearchRejectedExecutionException ignored -> ErrorMessages.TOO_MANY_REQUESTS; + case null, default -> "Internal failure"; + }; } public static Throwable unwrapCause(Throwable t) { diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java index 6b60e7448cd03..a28d2d930d30a 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java +++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java @@ -63,11 +63,10 @@ public interface BytesReference extends Comparable, ToXContentFr static BytesReference bytes(XContentBuilder xContentBuilder) { xContentBuilder.close(); OutputStream stream = xContentBuilder.getOutputStream(); - if (stream instanceof ByteArrayOutputStream) { - return new BytesArray(((ByteArrayOutputStream) stream).toByteArray()); - } else { - return ((BytesStream) stream).bytes(); - } + return switch (stream) { + case ByteArrayOutputStream baos -> new BytesArray(baos.toByteArray()); + default -> ((BytesStream) stream).bytes(); + }; } /** diff --git a/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java b/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java index c7b9bee3cbf4d..e123aafd399be 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java +++ b/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java @@ -169,24 +169,16 @@ private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Set booleanArrayAppend(sbuf, boolArr); + case byte[] byteArr -> byteArrayAppend(sbuf, byteArr); + case char[] charArr -> charArrayAppend(sbuf, charArr); + case short[] shortArr -> shortArrayAppend(sbuf, shortArr); + case int[] intArr -> intArrayAppend(sbuf, intArr); + case long[] longArr -> longArrayAppend(sbuf, longArr); + case float[] floatArr -> floatArrayAppend(sbuf, floatArr); + case double[] doubleArr -> doubleArrayAppend(sbuf, doubleArr); + default -> objectArrayAppend(sbuf, (Object[]) o, seen); } } } diff --git a/libs/nio/src/main/java/org/opensearch/nio/NioSelectorGroup.java b/libs/nio/src/main/java/org/opensearch/nio/NioSelectorGroup.java index 47ba253a1bd61..e2c8489f1168a 100644 --- a/libs/nio/src/main/java/org/opensearch/nio/NioSelectorGroup.java +++ b/libs/nio/src/main/java/org/opensearch/nio/NioSelectorGroup.java @@ -183,10 +183,9 @@ private static void startSelectors(Iterable selectors, ThreadFactor Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted while waiting for selector to start.", e); } catch (ExecutionException e) { - if (e.getCause() instanceof RuntimeException) { - throw (RuntimeException) e.getCause(); - } else { - throw new RuntimeException("Exception during selector start.", e); + switch (e.getCause()) { + case RuntimeException re -> throw re; + default -> throw new RuntimeException("Exception during selector start.", e); } } } diff --git a/libs/nio/src/main/java/org/opensearch/nio/SocketChannelContext.java b/libs/nio/src/main/java/org/opensearch/nio/SocketChannelContext.java index 530aa1d86afc7..29b4c29b01f3b 100644 --- a/libs/nio/src/main/java/org/opensearch/nio/SocketChannelContext.java +++ b/libs/nio/src/main/java/org/opensearch/nio/SocketChannelContext.java @@ -142,12 +142,10 @@ public boolean connect() throws IOException { return true; } else if (connectContext.isCompletedExceptionally()) { Exception exception = connectException; - if (exception == null) { - throw new AssertionError("Should have received connection exception"); - } else if (exception instanceof IOException) { - throw (IOException) exception; - } else { - throw (RuntimeException) exception; + switch (exception) { + case null -> throw new AssertionError("Should have received connection exception"); + case IOException ioException -> throw ioException; + default -> throw (RuntimeException) exception; } } diff --git a/server/src/main/java/org/opensearch/action/DocWriteRequest.java b/server/src/main/java/org/opensearch/action/DocWriteRequest.java index e887af898527e..5335c52074ed2 100644 --- a/server/src/main/java/org/opensearch/action/DocWriteRequest.java +++ b/server/src/main/java/org/opensearch/action/DocWriteRequest.java @@ -263,33 +263,39 @@ static ActionRequestValidationException validateDocIdLength(String id, ActionReq /** write a document write (index/delete/update) request*/ static void writeDocumentRequest(StreamOutput out, DocWriteRequest request) throws IOException { - if (request instanceof IndexRequest) { - out.writeByte((byte) 0); - ((IndexRequest) request).writeTo(out); - } else if (request instanceof DeleteRequest) { - out.writeByte((byte) 1); - ((DeleteRequest) request).writeTo(out); - } else if (request instanceof UpdateRequest) { - out.writeByte((byte) 2); - ((UpdateRequest) request).writeTo(out); - } else { - throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]"); + switch (request) { + case IndexRequest indexRequest -> { + out.writeByte((byte) 0); + indexRequest.writeTo(out); + } + case DeleteRequest deleteRequest -> { + out.writeByte((byte) 1); + deleteRequest.writeTo(out); + } + case UpdateRequest updateRequest -> { + out.writeByte((byte) 2); + updateRequest.writeTo(out); + } + default -> throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]"); } } /** write a document write (index/delete/update) request without shard id*/ static void writeDocumentRequestThin(StreamOutput out, DocWriteRequest request) throws IOException { - if (request instanceof IndexRequest) { - out.writeByte((byte) 0); - ((IndexRequest) request).writeThin(out); - } else if (request instanceof DeleteRequest) { - out.writeByte((byte) 1); - ((DeleteRequest) request).writeThin(out); - } else if (request instanceof UpdateRequest) { - out.writeByte((byte) 2); - ((UpdateRequest) request).writeThin(out); - } else { - throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]"); + switch (request) { + case IndexRequest indexRequest -> { + out.writeByte((byte) 0); + indexRequest.writeThin(out); + } + case DeleteRequest deleteRequest -> { + out.writeByte((byte) 1); + deleteRequest.writeThin(out); + } + case UpdateRequest updateRequest -> { + out.writeByte((byte) 2); + updateRequest.writeThin(out); + } + default -> throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]"); } } diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java index 51521a1d129c8..e43fb2854be91 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java @@ -630,14 +630,11 @@ public void writeThin(StreamOutput out) throws IOException { } private void writeResponseType(StreamOutput out) throws IOException { - if (response instanceof IndexResponse) { - out.writeByte((byte) 0); - } else if (response instanceof DeleteResponse) { - out.writeByte((byte) 1); - } else if (response instanceof UpdateResponse) { - out.writeByte((byte) 3); // make 3 instead of 2, because 2 is already in use for 'no responses' - } else { - throw new IllegalStateException("Unexpected response type found [" + response.getClass() + "]"); + switch (response) { + case IndexResponse ignored -> out.writeByte((byte) 0); + case DeleteResponse ignored -> out.writeByte((byte) 1); + case UpdateResponse ignored -> out.writeByte((byte) 3); // make 3 instead of 2, because 2 is already in use for 'no responses' + default -> throw new IllegalStateException("Unexpected response type found [" + response.getClass() + "]"); } } } diff --git a/server/src/main/java/org/opensearch/index/search/NestedHelper.java b/server/src/main/java/org/opensearch/index/search/NestedHelper.java index fd8527924083a..047d05cf7ac1c 100644 --- a/server/src/main/java/org/opensearch/index/search/NestedHelper.java +++ b/server/src/main/java/org/opensearch/index/search/NestedHelper.java @@ -63,52 +63,35 @@ public NestedHelper(MapperService mapperService) { /** Returns true if the given query might match nested documents. */ public boolean mightMatchNestedDocs(Query query) { - if (query instanceof ConstantScoreQuery) { - return mightMatchNestedDocs(((ConstantScoreQuery) query).getQuery()); - } else if (query instanceof BoostQuery) { - return mightMatchNestedDocs(((BoostQuery) query).getQuery()); - } else if (query instanceof MatchAllDocsQuery) { - return true; - } else if (query instanceof MatchNoDocsQuery) { - return false; - } else if (query instanceof TermQuery) { - // We only handle term(s) queries and range queries, which should already - // cover a high majority of use-cases - return mightMatchNestedDocs(((TermQuery) query).getTerm().field()); - } else if (query instanceof TermInSetQuery) { - final TermInSetQuery termInSetQuery = (TermInSetQuery) query; - if (termInSetQuery.getTermsCount() > 0) { - return mightMatchNestedDocs(termInSetQuery.getField()); - } else { - return false; - } - } else if (query instanceof PointRangeQuery) { - return mightMatchNestedDocs(((PointRangeQuery) query).getField()); - } else if (query instanceof IndexOrDocValuesQuery) { - return mightMatchNestedDocs(((IndexOrDocValuesQuery) query).getIndexQuery()); - } else if (query instanceof ApproximateScoreQuery) { - return mightMatchNestedDocs(((ApproximateScoreQuery) query).getOriginalQuery()); - } else if (query instanceof BooleanQuery) { - final BooleanQuery bq = (BooleanQuery) query; - final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired); - if (hasRequiredClauses) { - return bq.clauses() - .stream() - .filter(BooleanClause::isRequired) - .map(BooleanClause::query) - .allMatch(this::mightMatchNestedDocs); - } else { - return bq.clauses() - .stream() - .filter(c -> c.occur() == Occur.SHOULD) - .map(BooleanClause::query) - .anyMatch(this::mightMatchNestedDocs); + return switch (query) { + case ConstantScoreQuery csq -> mightMatchNestedDocs(csq.getQuery()); + case BoostQuery bq -> mightMatchNestedDocs(bq.getQuery()); + case MatchAllDocsQuery ignored -> true; + case MatchNoDocsQuery ignored -> false; + case TermQuery tq -> mightMatchNestedDocs(tq.getTerm().field()); + case TermInSetQuery tisq -> tisq.getTermsCount() > 0 && mightMatchNestedDocs(tisq.getField()); + case PointRangeQuery prq -> mightMatchNestedDocs(prq.getField()); + case IndexOrDocValuesQuery iorvq -> mightMatchNestedDocs(iorvq.getIndexQuery()); + case ApproximateScoreQuery asq -> mightMatchNestedDocs(asq.getOriginalQuery()); + case BooleanQuery bq -> { + final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired); + if (hasRequiredClauses) { + yield bq.clauses() + .stream() + .filter(BooleanClause::isRequired) + .map(BooleanClause::query) + .allMatch(this::mightMatchNestedDocs); + } else { + yield bq.clauses() + .stream() + .filter(c -> c.occur() == Occur.SHOULD) + .map(BooleanClause::query) + .anyMatch(this::mightMatchNestedDocs); + } } - } else if (query instanceof OpenSearchToParentBlockJoinQuery) { - return ((OpenSearchToParentBlockJoinQuery) query).getPath() != null; - } else { - return true; - } + case OpenSearchToParentBlockJoinQuery opbq -> opbq.getPath() != null; + case null, default -> true; + }; } /** Returns true if a query on the given field might match nested documents. */ @@ -137,48 +120,34 @@ boolean mightMatchNestedDocs(String field) { /** Returns true if the given query might match parent documents or documents * that are nested under a different path. */ public boolean mightMatchNonNestedDocs(Query query, String nestedPath) { - if (query instanceof ConstantScoreQuery) { - return mightMatchNonNestedDocs(((ConstantScoreQuery) query).getQuery(), nestedPath); - } else if (query instanceof BoostQuery) { - return mightMatchNonNestedDocs(((BoostQuery) query).getQuery(), nestedPath); - } else if (query instanceof MatchAllDocsQuery) { - return true; - } else if (query instanceof MatchNoDocsQuery) { - return false; - } else if (query instanceof TermQuery) { - return mightMatchNonNestedDocs(((TermQuery) query).getTerm().field(), nestedPath); - } else if (query instanceof TermInSetQuery) { - final TermInSetQuery termInSetQuery = (TermInSetQuery) query; - if (termInSetQuery.getTermsCount() > 0) { - return mightMatchNonNestedDocs(termInSetQuery.getField(), nestedPath); - } else { - return false; - } - } else if (query instanceof PointRangeQuery) { - return mightMatchNonNestedDocs(((PointRangeQuery) query).getField(), nestedPath); - } else if (query instanceof IndexOrDocValuesQuery) { - return mightMatchNonNestedDocs(((IndexOrDocValuesQuery) query).getIndexQuery(), nestedPath); - } else if (query instanceof ApproximateScoreQuery) { - return mightMatchNonNestedDocs(((ApproximateScoreQuery) query).getOriginalQuery(), nestedPath); - } else if (query instanceof BooleanQuery) { - final BooleanQuery bq = (BooleanQuery) query; - final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired); - if (hasRequiredClauses) { - return bq.clauses() - .stream() - .filter(BooleanClause::isRequired) - .map(BooleanClause::query) - .allMatch(q -> mightMatchNonNestedDocs(q, nestedPath)); - } else { - return bq.clauses() - .stream() - .filter(c -> c.occur() == Occur.SHOULD) - .map(BooleanClause::query) - .anyMatch(q -> mightMatchNonNestedDocs(q, nestedPath)); + return switch (query) { + case ConstantScoreQuery csq -> mightMatchNonNestedDocs(csq.getQuery(), nestedPath); + case BoostQuery bq -> mightMatchNonNestedDocs(bq.getQuery(), nestedPath); + case MatchAllDocsQuery ignored -> true; + case MatchNoDocsQuery ignored -> false; + case TermQuery tq -> mightMatchNonNestedDocs(tq.getTerm().field(), nestedPath); + case TermInSetQuery tisq -> tisq.getTermsCount() > 0 && mightMatchNonNestedDocs(tisq.getField(), nestedPath); + case PointRangeQuery prq -> mightMatchNonNestedDocs(prq.getField(), nestedPath); + case IndexOrDocValuesQuery iorvq -> mightMatchNonNestedDocs(iorvq.getIndexQuery(), nestedPath); + case ApproximateScoreQuery asq -> mightMatchNonNestedDocs(asq.getOriginalQuery(), nestedPath); + case BooleanQuery bq -> { + final boolean hasRequiredClauses = bq.clauses().stream().anyMatch(BooleanClause::isRequired); + if (hasRequiredClauses) { + yield bq.clauses() + .stream() + .filter(BooleanClause::isRequired) + .map(BooleanClause::query) + .allMatch(q -> mightMatchNonNestedDocs(q, nestedPath)); + } else { + yield bq.clauses() + .stream() + .filter(c -> c.occur() == Occur.SHOULD) + .map(BooleanClause::query) + .anyMatch(q -> mightMatchNonNestedDocs(q, nestedPath)); + } } - } else { - return true; - } + case null, default -> true; + }; } /** Returns true if a query on the given field might match parent documents diff --git a/server/src/main/java/org/opensearch/ingest/ValueSource.java b/server/src/main/java/org/opensearch/ingest/ValueSource.java index 3463fb0f83b26..f7e3e34c35955 100644 --- a/server/src/main/java/org/opensearch/ingest/ValueSource.java +++ b/server/src/main/java/org/opensearch/ingest/ValueSource.java @@ -65,40 +65,42 @@ public interface ValueSource { Object copyAndResolve(Map model); static ValueSource wrap(Object value, ScriptService scriptService) { - - if (value instanceof Map) { - @SuppressWarnings("unchecked") - Map mapValue = (Map) value; - Map valueTypeMap = new HashMap<>(mapValue.size()); - for (Map.Entry entry : mapValue.entrySet()) { - valueTypeMap.put(wrap(entry.getKey(), scriptService), wrap(entry.getValue(), scriptService)); + return switch (value) { + case Map mapValue -> { + @SuppressWarnings("unchecked") + Map castedMap = (Map) mapValue; + Map valueTypeMap = new HashMap<>(castedMap.size()); + for (Map.Entry entry : castedMap.entrySet()) { + valueTypeMap.put(wrap(entry.getKey(), scriptService), wrap(entry.getValue(), scriptService)); + } + yield new MapValue(valueTypeMap); } - return new MapValue(valueTypeMap); - } else if (value instanceof List) { - @SuppressWarnings("unchecked") - List listValue = (List) value; - List valueSourceList = new ArrayList<>(listValue.size()); - for (Object item : listValue) { - valueSourceList.add(wrap(item, scriptService)); + case List listValue -> { + @SuppressWarnings("unchecked") + List castedList = (List) listValue; + List valueSourceList = new ArrayList<>(castedList.size()); + for (Object item : castedList) { + valueSourceList.add(wrap(item, scriptService)); + } + yield new ListValue(valueSourceList); } - return new ListValue(valueSourceList); - } else if (value == null || value instanceof Number || value instanceof Boolean) { - return new ObjectValue(value); - } else if (value instanceof byte[]) { - return new ByteValue((byte[]) value); - } else if (value instanceof String) { - // This check is here because the DEFAULT_TEMPLATE_LANG(mustache) is not - // installed for use by REST tests. `value` will not be - // modified if templating is not available - if (scriptService.isLangSupported(DEFAULT_TEMPLATE_LANG) && ((String) value).contains("{{")) { - Script script = new Script(ScriptType.INLINE, DEFAULT_TEMPLATE_LANG, (String) value, Collections.emptyMap()); - return new TemplatedValue(scriptService.compile(script, TemplateScript.CONTEXT)); - } else { - return new ObjectValue(value); + case byte[] byteArray -> new ByteValue(byteArray); + case String stringValue -> { + // This check is here because the DEFAULT_TEMPLATE_LANG(mustache) is not + // installed for use by REST tests. `value` will not be + // modified if templating is not available + if (scriptService.isLangSupported(DEFAULT_TEMPLATE_LANG) && stringValue.contains("{{")) { + Script script = new Script(ScriptType.INLINE, DEFAULT_TEMPLATE_LANG, stringValue, Collections.emptyMap()); + yield new TemplatedValue(scriptService.compile(script, TemplateScript.CONTEXT)); + } else { + yield new ObjectValue(stringValue); + } } - } else { - throw new IllegalArgumentException("unexpected value type [" + value.getClass() + "]"); - } + case null -> new ObjectValue(null); + case Number number -> new ObjectValue(number); + case Boolean bool -> new ObjectValue(bool); + default -> throw new IllegalArgumentException("unexpected value type [" + value.getClass() + "]"); + }; } /** diff --git a/server/src/main/java/org/opensearch/search/SearchSortValuesAndFormats.java b/server/src/main/java/org/opensearch/search/SearchSortValuesAndFormats.java index f9174e92b79e8..fb2592b494f24 100644 --- a/server/src/main/java/org/opensearch/search/SearchSortValuesAndFormats.java +++ b/server/src/main/java/org/opensearch/search/SearchSortValuesAndFormats.java @@ -61,24 +61,22 @@ public SearchSortValuesAndFormats(Object[] rawSortValues, DocValueFormat[] sortV this.formattedSortValues = Arrays.copyOf(rawSortValues, rawSortValues.length); for (int i = 0; i < rawSortValues.length; ++i) { Object sortValue = rawSortValues[i]; - if (sortValue instanceof BytesRef) { - this.formattedSortValues[i] = sortValueFormats[i].format((BytesRef) sortValue); - } else if (sortValue instanceof Long) { - this.formattedSortValues[i] = sortValueFormats[i].format((long) sortValue); - } else if (sortValue instanceof BigInteger) { - this.formattedSortValues[i] = sortValueFormats[i].format((BigInteger) sortValue); - } else if (sortValue instanceof Double) { - this.formattedSortValues[i] = sortValueFormats[i].format((double) sortValue); - } else if (sortValue instanceof Float || sortValue instanceof Integer) { - // sort by _score or _doc - this.formattedSortValues[i] = sortValue; - } else { - assert sortValue == null : "Sort values must be a BytesRef, Long, Integer, Double or Float, but got " - + sortValue.getClass() - + ": " - + sortValue; - this.formattedSortValues[i] = sortValue; - } + this.formattedSortValues[i] = switch (sortValue) { + case BytesRef bytesRef -> sortValueFormats[i].format(bytesRef); + case Long longValue -> sortValueFormats[i].format(longValue); + case BigInteger bigInteger -> sortValueFormats[i].format(bigInteger); + case Double doubleValue -> sortValueFormats[i].format(doubleValue); + case Float ignored -> sortValue; + case Integer ignored -> sortValue; // sort by _score or _doc + case null -> sortValue; + default -> { + assert false : "Sort values must be a BytesRef, Long, Integer, Double or Float, but got " + + sortValue.getClass() + + ": " + + sortValue; + yield sortValue; + } + }; } }