diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java b/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java index 94ec0db3a9712..2e70051dc2afb 100644 --- a/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java +++ b/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java @@ -95,8 +95,8 @@ public boolean process(Set annotations, RoundEnvironment // Skip all not-public elements checkPublicVisibility(null, element); - if (element instanceof TypeElement) { - process((TypeElement) element); + if (element instanceof TypeElement typeElement) { + process(typeElement); } } @@ -185,22 +185,22 @@ private void process(ExecutableElement executable, Element enclosing) { // Process method return types final TypeMirror returnType = executable.getReturnType(); - if (returnType instanceof ReferenceType) { - process(executable, (ReferenceType) returnType); + if (returnType instanceof ReferenceType refType) { + process(executable, refType); } // Process method thrown types for (final TypeMirror thrownType : executable.getThrownTypes()) { - if (thrownType instanceof ReferenceType) { - process(executable, (ReferenceType) thrownType); + if (thrownType instanceof ReferenceType refType) { + process(executable, refType); } } // Process method type parameters for (final TypeParameterElement typeParameter : executable.getTypeParameters()) { for (final TypeMirror boundType : typeParameter.getBounds()) { - if (boundType instanceof ReferenceType) { - process(executable, (ReferenceType) boundType); + if (boundType instanceof ReferenceType refType) { + process(executable, refType); } } } @@ -208,8 +208,8 @@ private void process(ExecutableElement executable, Element enclosing) { // Process method arguments for (final VariableElement parameter : executable.getParameters()) { final TypeMirror parameterType = parameter.asType(); - if (parameterType instanceof ReferenceType) { - process(executable, (ReferenceType) parameterType); + if (parameterType instanceof ReferenceType refType) { + process(executable, refType); } } } @@ -220,12 +220,12 @@ private void process(ExecutableElement executable, Element enclosing) { * @param type wildcard type */ private void process(ExecutableElement executable, WildcardType type) { - if (type.getExtendsBound() instanceof ReferenceType) { - process(executable, (ReferenceType) type.getExtendsBound()); + if (type.getExtendsBound() instanceof ReferenceType refType) { + process(executable, refType); } - if (type.getSuperBound() instanceof ReferenceType) { - process(executable, (ReferenceType) type.getSuperBound()); + if (type.getSuperBound() instanceof ReferenceType refType) { + process(executable, refType); } } @@ -240,8 +240,7 @@ private void process(ExecutableElement executable, ReferenceType ref) { return; } - if (ref instanceof DeclaredType) { - final DeclaredType declaredType = (DeclaredType) ref; + if (ref instanceof DeclaredType declaredType) { final Element element = declaredType.asElement(); if (inspectable(element)) { @@ -250,24 +249,23 @@ private void process(ExecutableElement executable, ReferenceType ref) { } for (final TypeMirror type : declaredType.getTypeArguments()) { - if (type instanceof ReferenceType) { - process(executable, (ReferenceType) type); - } else if (type instanceof WildcardType) { - process(executable, (WildcardType) type); + if (type instanceof ReferenceType refType) { + process(executable, refType); + } else if (type instanceof WildcardType wildcardType) { + process(executable, wildcardType); } } - } else if (ref instanceof ArrayType) { - final TypeMirror componentType = ((ArrayType) ref).getComponentType(); - if (componentType instanceof ReferenceType) { - process(executable, (ReferenceType) componentType); + } else if (ref instanceof ArrayType arrayType) { + final TypeMirror componentType = arrayType.getComponentType(); + if (componentType instanceof ReferenceType refType) { + process(executable, refType); } - } else if (ref instanceof TypeVariable) { - final TypeVariable typeVariable = (TypeVariable) ref; - if (typeVariable.getUpperBound() instanceof ReferenceType) { - process(executable, (ReferenceType) typeVariable.getUpperBound()); + } else if (ref instanceof TypeVariable typeVariable) { + if (typeVariable.getUpperBound() instanceof ReferenceType refType) { + process(executable, refType); } - if (typeVariable.getLowerBound() instanceof ReferenceType) { - process(executable, (ReferenceType) typeVariable.getLowerBound()); + if (typeVariable.getLowerBound() instanceof ReferenceType refType) { + process(executable, refType); } } @@ -348,8 +346,8 @@ private void process(Element element) { continue; } - if (enclosed instanceof ExecutableElement) { - process((ExecutableElement) enclosed, element); + if (enclosed instanceof ExecutableElement executableElement) { + process(executableElement, element); } } } diff --git a/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java b/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java index 470b92aaa2fab..67b857e081f76 100644 --- a/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java +++ b/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java @@ -96,8 +96,8 @@ public static void checkJarHell(Consumer output) throws IOException, URI ClassLoader loader = JarHell.class.getClassLoader(); output.accept("java.class.path: " + System.getProperty("java.class.path")); output.accept("sun.boot.class.path: " + System.getProperty("sun.boot.class.path")); - if (loader instanceof URLClassLoader) { - output.accept("classloader urls: " + Arrays.toString(((URLClassLoader) loader).getURLs())); + if (loader instanceof URLClassLoader urlClassLoader) { + output.accept("classloader urls: " + Arrays.toString(urlClassLoader.getURLs())); } checkJarHell(parseClassPath(), output); } diff --git a/libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java b/libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java index 72f8146cb969d..0af7035c55d6c 100644 --- a/libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java +++ b/libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java @@ -43,10 +43,7 @@ public class NetworkExceptionHelper { public static boolean isConnectException(Throwable e) { - if (e instanceof ConnectException) { - return true; - } - return false; + return e instanceof ConnectException; } public static boolean isCloseConnectionException(Throwable e) { diff --git a/libs/common/src/main/java/org/opensearch/common/util/io/IOUtils.java b/libs/common/src/main/java/org/opensearch/common/util/io/IOUtils.java index 6b72a0f92c14d..e9fe0e19f9a27 100644 --- a/libs/common/src/main/java/org/opensearch/common/util/io/IOUtils.java +++ b/libs/common/src/main/java/org/opensearch/common/util/io/IOUtils.java @@ -139,8 +139,8 @@ public static void close(final Exception ex, final Iterable } if (firstException != null) { - if (firstException instanceof IOException) { - throw (IOException) firstException; + if (firstException instanceof IOException ioe) { + throw ioe; } else { // since we only assigned an IOException or a RuntimeException to ex above, in this case ex must be a RuntimeException throw (RuntimeException) firstException; diff --git a/libs/common/src/main/java/org/opensearch/common/util/set/Sets.java b/libs/common/src/main/java/org/opensearch/common/util/set/Sets.java index 2dc2fb3175d27..658390836bc87 100644 --- a/libs/common/src/main/java/org/opensearch/common/util/set/Sets.java +++ b/libs/common/src/main/java/org/opensearch/common/util/set/Sets.java @@ -68,7 +68,7 @@ public static HashSet newHashSet(Iterator iterator) { public static HashSet newHashSet(Iterable iterable) { Objects.requireNonNull(iterable); - return iterable instanceof Collection ? new HashSet<>((Collection) iterable) : newHashSet(iterable.iterator()); + return iterable instanceof Collection collection ? new HashSet<>(collection) : newHashSet(iterable.iterator()); } public static HashSet newHashSet(T... elements) { diff --git a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java index 765cd1cbdc960..6e6c80546abfa 100644 --- a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java +++ b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java @@ -318,8 +318,8 @@ public static Throwable unwrap(Throwable t, Class... clazzes) { */ public static boolean reThrowIfNotNull(@Nullable Throwable e) { if (e != null) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; + if (e instanceof RuntimeException re) { + throw re; } else { throw new RuntimeException(e); } @@ -442,8 +442,8 @@ private static class GroupBy { // which does not include the cluster alias. String indexName = failure.index(); if (indexName == null) { - if (cause instanceof OpenSearchException) { - final Index index = ((OpenSearchException) cause).getIndex(); + if (cause instanceof OpenSearchException ose) { + final Index index = ose.getIndex(); if (index != null) { indexName = index.getName(); } diff --git a/libs/core/src/main/java/org/opensearch/OpenSearchException.java b/libs/core/src/main/java/org/opensearch/OpenSearchException.java index 8fb343630338b..4f477e3a06267 100644 --- a/libs/core/src/main/java/org/opensearch/OpenSearchException.java +++ b/libs/core/src/main/java/org/opensearch/OpenSearchException.java @@ -328,8 +328,8 @@ public String getDetailedMessage() { if (getCause() != null) { StringBuilder sb = new StringBuilder(); sb.append(toString()).append("; "); - if (getCause() instanceof OpenSearchException) { - sb.append(((OpenSearchException) getCause()).getDetailedMessage()); + if (getCause() instanceof OpenSearchException ose) { + sb.append(ose.getDetailedMessage()); } else { sb.append(getCause()); } @@ -409,8 +409,7 @@ protected static void innerToXContent( headerToXContent(builder, entry.getKey().substring(OPENSEARCH_PREFIX_KEY.length()), entry.getValue()); } - if (throwable instanceof OpenSearchException) { - OpenSearchException exception = (OpenSearchException) throwable; + if (throwable instanceof OpenSearchException exception) { exception.metadataToXContent(builder, params); } @@ -602,8 +601,8 @@ public static OpenSearchException innerFromXContent(XContentParser parser, boole public static void generateThrowableXContent(XContentBuilder builder, ToXContent.Params params, Throwable t) throws IOException { t = ExceptionsHelper.unwrapCause(t); - if (t instanceof OpenSearchException) { - ((OpenSearchException) t).toXContent(builder, params); + if (t instanceof OpenSearchException ose) { + ose.toXContent(builder, params); } else { innerToXContent(builder, params, t, getExceptionName(t), t.getMessage(), emptyMap(), emptyMap(), t.getCause()); } @@ -674,8 +673,8 @@ public static OpenSearchException failureFromXContent(XContentParser parser) thr */ public OpenSearchException[] guessRootCauses() { final Throwable cause = getCause(); - if (cause != null && cause instanceof OpenSearchException) { - return ((OpenSearchException) cause).guessRootCauses(); + if (cause instanceof OpenSearchException ose) { + return ose.guessRootCauses(); } return new OpenSearchException[] { this }; } @@ -687,9 +686,9 @@ public OpenSearchException[] guessRootCauses() { */ public static OpenSearchException[] guessRootCauses(Throwable t) { Throwable ex = ExceptionsHelper.unwrapCause(t); - if (ex instanceof OpenSearchException) { + if (ex instanceof OpenSearchException ose) { // OpenSearchException knows how to guess its own root cause - return ((OpenSearchException) ex).guessRootCauses(); + return ose.guessRootCauses(); } if (ex instanceof XContentParseException) { /* diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java index a2bf7e499dee8..4dc4dd22acc26 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java +++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java @@ -112,8 +112,7 @@ public boolean equals(Object other) { if (this == other) { return true; } - if (other instanceof BytesReference) { - final BytesReference otherRef = (BytesReference) other; + if (other instanceof BytesReference otherRef) { if (length() != otherRef.length()) { return false; } diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java index d7a8414935143..00c376d0a8a66 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java +++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java @@ -105,8 +105,7 @@ public boolean equals(Object other) { if (this == other) { return true; } - if (other instanceof BytesArray) { - final BytesArray that = (BytesArray) other; + if (other instanceof BytesArray that) { return Arrays.equals(bytes, offset, offset + length, that.bytes, that.offset, that.offset + that.length); } return super.equals(other); diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/DataOutputStreamOutput.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/DataOutputStreamOutput.java index b0bd6b101dc70..6ddcd31406209 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/DataOutputStreamOutput.java +++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/DataOutputStreamOutput.java @@ -71,8 +71,8 @@ public void reset() throws IOException { @Override public void close() throws IOException { - if (out instanceof Closeable) { - ((Closeable) out).close(); + if (out instanceof Closeable closeable) { + closeable.close(); } } } diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/NotSerializableExceptionWrapper.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/NotSerializableExceptionWrapper.java index 91d552be0950c..d690f35a1d98f 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/NotSerializableExceptionWrapper.java +++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/NotSerializableExceptionWrapper.java @@ -60,8 +60,7 @@ public NotSerializableExceptionWrapper(Throwable other) { for (Throwable otherSuppressed : other.getSuppressed()) { addSuppressed(otherSuppressed); } - if (other instanceof OpenSearchException) { - OpenSearchException ex = (OpenSearchException) other; + if (other instanceof OpenSearchException ex) { for (String key : ex.getHeaderKeys()) { this.addHeader(key, ex.getHeader(key)); } diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java index d27eb7197213f..c108f7403de81 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java +++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java @@ -997,105 +997,105 @@ private void writeException(Throwable rootException, Throwable throwable, int ne writeBoolean(true); boolean writeCause = true; boolean writeMessage = true; - if (throwable instanceof CorruptIndexException) { - writeVInt(1); - writeOptionalString(((CorruptIndexException) throwable).getOriginalMessage()); - writeOptionalString(((CorruptIndexException) throwable).getResourceDescription()); - writeMessage = false; - } else if (throwable instanceof IndexFormatTooNewException) { - writeVInt(2); - writeOptionalString(((IndexFormatTooNewException) throwable).getResourceDescription()); - writeInt(((IndexFormatTooNewException) throwable).getVersion()); - writeInt(((IndexFormatTooNewException) throwable).getMinVersion()); - writeInt(((IndexFormatTooNewException) throwable).getMaxVersion()); - writeMessage = false; - writeCause = false; - } else if (throwable instanceof IndexFormatTooOldException) { - writeVInt(3); - IndexFormatTooOldException t = (IndexFormatTooOldException) throwable; - writeOptionalString(t.getResourceDescription()); - if (t.getVersion() == null) { - writeBoolean(false); - writeOptionalString(t.getReason()); - } else { - writeBoolean(true); - writeInt(t.getVersion()); - writeInt(t.getMinVersion()); - writeInt(t.getMaxVersion()); - } - writeMessage = false; - writeCause = false; - } else if (throwable instanceof NullPointerException) { - writeVInt(4); - writeCause = false; - } else if (throwable instanceof NumberFormatException) { - writeVInt(5); - writeCause = false; - } else if (throwable instanceof IllegalArgumentException) { - writeVInt(6); - } else if (throwable instanceof AlreadyClosedException) { - writeVInt(7); - } else if (throwable instanceof EOFException) { - writeVInt(8); - writeCause = false; - } else if (throwable instanceof SecurityException) { - writeVInt(9); - } else if (throwable instanceof StringIndexOutOfBoundsException) { - writeVInt(10); - writeCause = false; - } else if (throwable instanceof ArrayIndexOutOfBoundsException) { - writeVInt(11); - writeCause = false; - } else if (throwable instanceof FileNotFoundException) { - writeVInt(12); - writeCause = false; - } else if (throwable instanceof FileSystemException) { - writeVInt(13); - if (throwable instanceof NoSuchFileException) { - writeVInt(0); - } else if (throwable instanceof NotDirectoryException) { + switch (throwable) { + case CorruptIndexException corruptEx -> { writeVInt(1); - } else if (throwable instanceof DirectoryNotEmptyException) { + writeOptionalString(corruptEx.getOriginalMessage()); + writeOptionalString(corruptEx.getResourceDescription()); + writeMessage = false; + } + case IndexFormatTooNewException tooNewEx -> { writeVInt(2); - } else if (throwable instanceof AtomicMoveNotSupportedException) { + writeOptionalString(tooNewEx.getResourceDescription()); + writeInt(tooNewEx.getVersion()); + writeInt(tooNewEx.getMinVersion()); + writeInt(tooNewEx.getMaxVersion()); + writeMessage = false; + writeCause = false; + } + case IndexFormatTooOldException t -> { writeVInt(3); - } else if (throwable instanceof FileAlreadyExistsException) { + writeOptionalString(t.getResourceDescription()); + if (t.getVersion() == null) { + writeBoolean(false); + writeOptionalString(t.getReason()); + } else { + writeBoolean(true); + writeInt(t.getVersion()); + writeInt(t.getMinVersion()); + writeInt(t.getMaxVersion()); + } + writeMessage = false; + writeCause = false; + } + case NullPointerException ignored -> { writeVInt(4); - } else if (throwable instanceof AccessDeniedException) { + writeCause = false; + } + case NumberFormatException ignored -> { writeVInt(5); - } else if (throwable instanceof FileSystemLoopException) { - writeVInt(6); - } else { - writeVInt(7); + writeCause = false; } - writeOptionalString(((FileSystemException) throwable).getFile()); - writeOptionalString(((FileSystemException) throwable).getOtherFile()); - writeOptionalString(((FileSystemException) throwable).getReason()); - writeCause = false; - } else if (throwable instanceof IllegalStateException) { - writeVInt(14); - } else if (throwable instanceof LockObtainFailedException) { - writeVInt(15); - } else if (throwable instanceof InterruptedException) { - writeVInt(16); - writeCause = false; - } else if (throwable instanceof IOException) { - writeVInt(17); - } else if (throwable instanceof OpenSearchRejectedExecutionException) { - writeVInt(18); - writeBoolean(((OpenSearchRejectedExecutionException) throwable).isExecutorShutdown()); - writeCause = false; - } else { - final OpenSearchException ex; - if (throwable instanceof OpenSearchException && OpenSearchException.isRegistered(throwable.getClass(), version)) { - ex = (OpenSearchException) throwable; - } else { - ex = new NotSerializableExceptionWrapper(throwable); + case IllegalArgumentException ignored -> writeVInt(6); + case AlreadyClosedException ignored -> writeVInt(7); + case EOFException ignored -> { + writeVInt(8); + writeCause = false; + } + case SecurityException ignored -> writeVInt(9); + case StringIndexOutOfBoundsException ignored -> { + writeVInt(10); + writeCause = false; + } + case ArrayIndexOutOfBoundsException ignored -> { + writeVInt(11); + writeCause = false; + } + case FileNotFoundException ignored -> { + writeVInt(12); + writeCause = false; + } + case FileSystemException fsEx -> { + writeVInt(13); + switch (throwable) { + case NoSuchFileException ignored -> writeVInt(0); + case NotDirectoryException ignored -> writeVInt(1); + case DirectoryNotEmptyException ignored -> writeVInt(2); + case AtomicMoveNotSupportedException ignored -> writeVInt(3); + case FileAlreadyExistsException ignored -> writeVInt(4); + case AccessDeniedException ignored -> writeVInt(5); + case FileSystemLoopException ignored -> writeVInt(6); + default -> writeVInt(7); + } + writeOptionalString(fsEx.getFile()); + writeOptionalString(fsEx.getOtherFile()); + writeOptionalString(fsEx.getReason()); + writeCause = false; + } + case IllegalStateException ignored -> writeVInt(14); + case LockObtainFailedException ignored -> writeVInt(15); + case InterruptedException ignored -> { + writeVInt(16); + writeCause = false; + } + case IOException ignored -> writeVInt(17); + case OpenSearchRejectedExecutionException rejectedEx -> { + writeVInt(18); + writeBoolean(rejectedEx.isExecutorShutdown()); + writeCause = false; + } + default -> { + final OpenSearchException ex; + if (throwable instanceof OpenSearchException osEx && OpenSearchException.isRegistered(throwable.getClass(), version)) { + ex = osEx; + } else { + ex = new NotSerializableExceptionWrapper(throwable); + } + writeVInt(0); + writeVInt(OpenSearchException.getId(ex.getClass())); + ex.writeTo(this); + return; } - writeVInt(0); - writeVInt(OpenSearchException.getId(ex.getClass())); - ex.writeTo(this); - return; } if (writeMessage) { writeOptionalString(throwable.getMessage()); diff --git a/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java b/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java index 5335c98182b64..8e874502b3546 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java +++ b/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java @@ -163,19 +163,12 @@ public static void ensureNoSelfReferences(Object value, String messageHint) { */ @SuppressWarnings("unchecked") private static Iterable convert(Object value) { - if (value == null) { - return null; - } - if (value instanceof Map) { - Map map = (Map) value; - return () -> Iterators.concat(map.keySet().iterator(), map.values().iterator()); - } else if ((value instanceof Iterable) && (value instanceof Path == false)) { - return (Iterable) value; - } else if (value instanceof Object[]) { - return Arrays.asList((Object[]) value); - } else { - return null; - } + return switch (value) { + case Map map -> () -> Iterators.concat(map.keySet().iterator(), map.values().iterator()); + case Iterable iterable when value instanceof Path == false -> iterable; + case Object[] objects -> Arrays.asList(objects); + case null, default -> null; + }; } private static void ensureNoSelfReferences( diff --git a/libs/core/src/main/java/org/opensearch/core/util/ConfigurationUtils.java b/libs/core/src/main/java/org/opensearch/core/util/ConfigurationUtils.java index b077d11644ece..391633b4ea3e4 100644 --- a/libs/core/src/main/java/org/opensearch/core/util/ConfigurationUtils.java +++ b/libs/core/src/main/java/org/opensearch/core/util/ConfigurationUtils.java @@ -76,8 +76,8 @@ private static String readString(String propertyName, Object value) { if (value == null) { return null; } - if (value instanceof String) { - return (String) value; + if (value instanceof String stringValue) { + return stringValue; } throw newConfigurationException(propertyName, "property isn't a string, but of type [" + value.getClass().getName() + "]"); } @@ -105,15 +105,15 @@ public static String readStringOrIntProperty(Map configuration, } private static String readStringOrInt(String propertyName, Object value) { - if (value == null) { - return null; - } - if (value instanceof String) { - return (String) value; - } else if (value instanceof Integer) { - return String.valueOf(value); - } - throw newConfigurationException(propertyName, "property isn't a string or int, but of type [" + value.getClass().getName() + "]"); + return switch (value) { + case null -> null; + case String stringValue -> stringValue; + case Integer intValue -> String.valueOf(intValue); + default -> throw newConfigurationException( + propertyName, + "property isn't a string or int, but of type [" + value.getClass().getName() + "]" + ); + }; } /** @@ -142,8 +142,8 @@ private static Boolean readBoolean(String propertyName, Object value) { if (value == null) { return null; } - if (value instanceof Boolean) { - return (boolean) value; + if (value instanceof Boolean boolValue) { + return boolValue; } throw newConfigurationException(propertyName, "property isn't a boolean, but of type [" + value.getClass().getName() + "]"); } diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java index 0a5cda324ddb7..27534c9226afa 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java @@ -62,8 +62,8 @@ public MapXContentParser( @Override protected boolean doBooleanValue() throws IOException { - if (iterator != null && iterator.currentValue() instanceof Boolean) { - return (Boolean) iterator.currentValue(); + if (iterator != null && iterator.currentValue() instanceof Boolean boolValue) { + return boolValue; } else { throw new IllegalStateException("Cannot get boolean value for the current token " + currentToken()); } @@ -96,8 +96,8 @@ protected double doDoubleValue() throws IOException { @Override protected BigInteger doBigIntegerValue() throws IOException { - if (numberValue() instanceof BigInteger) { - return (BigInteger) numberValue(); + if (numberValue() instanceof BigInteger bigIntValue) { + return bigIntValue; } else { return BigInteger.valueOf(numberValue().longValue()); } @@ -224,8 +224,8 @@ public NumberType numberType() throws IOException { @Override public byte[] binaryValue() throws IOException { - if (iterator != null && iterator.currentValue() instanceof byte[]) { - return (byte[]) iterator.currentValue(); + if (iterator != null && iterator.currentValue() instanceof byte[] byteArray) { + return byteArray; } else { throw new IllegalStateException("Cannot get binary value for the current token " + currentToken()); } @@ -285,20 +285,20 @@ public Token currentToken() { @SuppressWarnings("unchecked") TokenIterator processValue(Object value) { - if (value instanceof Map) { - return new MapIterator(this, childName(), (Map) value).next(); - } else if (value instanceof List) { - return new ArrayIterator(this, childName(), (List) value).next(); - } else if (value instanceof Number) { - currentToken = Token.VALUE_NUMBER; - } else if (value instanceof String) { - currentToken = Token.VALUE_STRING; - } else if (value instanceof Boolean) { - currentToken = Token.VALUE_BOOLEAN; - } else if (value instanceof byte[]) { - currentToken = Token.VALUE_EMBEDDED_OBJECT; - } else if (value == null) { - currentToken = Token.VALUE_NULL; + switch (value) { + case Map ignored -> { + return new MapIterator(this, childName(), (Map) value).next(); + } + case List ignored -> { + return new ArrayIterator(this, childName(), (List) value).next(); + } + case Number ignored -> currentToken = Token.VALUE_NUMBER; + case String ignored -> currentToken = Token.VALUE_STRING; + case Boolean ignored -> currentToken = Token.VALUE_BOOLEAN; + case byte[] ignored -> currentToken = Token.VALUE_EMBEDDED_OBJECT; + case null -> currentToken = Token.VALUE_NULL; + default -> { + } } return this; } diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java index 82cc3951be753..c001a59aa29f8 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java @@ -291,8 +291,7 @@ public static MediaType xContentType(InputStream si) throws IOException { */ @Deprecated public static MediaType xContentType(BytesReference bytes) { - if (bytes instanceof BytesArray) { - final BytesArray array = (BytesArray) bytes; + if (bytes instanceof BytesArray array) { return mediaTypeFromBytes(array.array(), array.offset(), array.length()); } try { diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectPath.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectPath.java index b1034eb66eb58..ae69357419229 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectPath.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectPath.java @@ -62,12 +62,12 @@ private static Object evalContext(String path, Object ctx) { if (ctx == null) { return null; } - if (ctx instanceof Map) { - ctx = ((Map) ctx).get(part); - } else if (ctx instanceof List) { + if (ctx instanceof Map map) { + ctx = map.get(part); + } else if (ctx instanceof List list) { try { int index = Integer.parseInt(part); - ctx = ((List) ctx).get(index); + ctx = list.get(index); } catch (NumberFormatException nfe) { return null; } diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java index 552945d085884..473c19b0c2896 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java @@ -846,19 +846,19 @@ private void unknownValue(Object value, boolean ensureNoSelfReferences) throws I Writer writer = WRITERS.get(value.getClass()); if (writer != null) { writer.write(this, value); - } else if (value instanceof Path) { + } else if (value instanceof Path path) { // Path implements Iterable and causes endless recursion and a StackOverFlow if treated as an Iterable here - value((Path) value); - } else if (value instanceof Map) { + value(path); + } else if (value instanceof Map) { @SuppressWarnings("unchecked") final Map valueMap = (Map) value; map(valueMap, ensureNoSelfReferences, true); - } else if (value instanceof Iterable) { - value((Iterable) value, ensureNoSelfReferences); - } else if (value instanceof Object[]) { - values((Object[]) value, ensureNoSelfReferences); - } else if (value instanceof ToXContent) { - value((ToXContent) value); + } else if (value instanceof Iterable iterable) { + value(iterable, ensureNoSelfReferences); + } else if (value instanceof Object[] objectArray) { + values(objectArray, ensureNoSelfReferences); + } else if (value instanceof ToXContent toXContent) { + value(toXContent); } else if (value instanceof Enum) { // Write out the Enum toString value(Objects.toString(value)); @@ -942,9 +942,9 @@ private XContentBuilder value(Iterable values, boolean ensureNoSelfReferences return nullValue(); } - if (values instanceof Path) { + if (values instanceof Path path) { // treat as single value - value((Path) values); + value(path); } else { // checks that the iterable does not contain references to itself because // iterating over entries will cause a stackoverflow error @@ -1073,12 +1073,12 @@ private static Iterable convert(Object value) { if (value == null) { return null; } - if (value instanceof Map) { - return ((Map) value).values(); - } else if ((value instanceof Iterable) && (value instanceof Path == false)) { - return (Iterable) value; - } else if (value instanceof Object[]) { - return Arrays.asList((Object[]) value); + if (value instanceof Map map) { + return map.values(); + } else if (value instanceof Iterable iterable && value instanceof Path == false) { + return iterable; + } else if (value instanceof Object[] objectArray) { + return Arrays.asList(objectArray); } else { return null; } diff --git a/libs/nio/src/main/java/org/opensearch/nio/EventHandler.java b/libs/nio/src/main/java/org/opensearch/nio/EventHandler.java index 780733fc5156a..2ac69f1320cc3 100644 --- a/libs/nio/src/main/java/org/opensearch/nio/EventHandler.java +++ b/libs/nio/src/main/java/org/opensearch/nio/EventHandler.java @@ -98,8 +98,8 @@ protected void registrationException(ChannelContext context, Exception except */ protected void handleActive(ChannelContext context) throws IOException { context.channelActive(); - if (context instanceof SocketChannelContext) { - if (((SocketChannelContext) context).readyForFlush()) { + if (context instanceof SocketChannelContext socketChannelContext) { + if (socketChannelContext.readyForFlush()) { SelectionKeyUtils.setConnectReadAndWriteInterested(context.getSelectionKey()); } else { SelectionKeyUtils.setConnectAndReadInterested(context.getSelectionKey()); diff --git a/libs/nio/src/main/java/org/opensearch/nio/NioSelector.java b/libs/nio/src/main/java/org/opensearch/nio/NioSelector.java index 4ed745723515c..080521e510afe 100644 --- a/libs/nio/src/main/java/org/opensearch/nio/NioSelector.java +++ b/libs/nio/src/main/java/org/opensearch/nio/NioSelector.java @@ -465,8 +465,8 @@ private void registerChannel(ChannelContext newChannel) { if (newChannel.isOpen()) { eventHandler.handleRegistration(newChannel); channelActive(newChannel); - if (newChannel instanceof SocketChannelContext) { - attemptConnect((SocketChannelContext) newChannel, false); + if (newChannel instanceof SocketChannelContext socketChannelContext) { + attemptConnect(socketChannelContext, false); } } else { eventHandler.registrationException(newChannel, new ClosedChannelException()); diff --git a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/DiagnosticTrustManager.java b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/DiagnosticTrustManager.java index a3856038bbca1..3c92d2266cb9d 100644 --- a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/DiagnosticTrustManager.java +++ b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/DiagnosticTrustManager.java @@ -162,8 +162,7 @@ private void diagnose(CertificateException cause, X509Certificate[] chain, SslDi } private SSLSession session(Socket socket) { - if (socket instanceof SSLSocket) { - final SSLSocket ssl = (SSLSocket) socket; + if (socket instanceof SSLSocket ssl) { final SSLSession handshakeSession = ssl.getHandshakeSession(); if (handshakeSession == null) { return ssl.getSession(); diff --git a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/KeyStoreUtil.java b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/KeyStoreUtil.java index b6b6cdd90af14..2181ca98c4d85 100644 --- a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/KeyStoreUtil.java +++ b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/KeyStoreUtil.java @@ -151,8 +151,8 @@ static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] passwor kmf.init(keyStore, password); KeyManager[] keyManagers = kmf.getKeyManagers(); for (KeyManager keyManager : keyManagers) { - if (keyManager instanceof X509ExtendedKeyManager) { - return (X509ExtendedKeyManager) keyManager; + if (keyManager instanceof X509ExtendedKeyManager x509KeyManager) { + return x509KeyManager; } } throw new SslConfigException( @@ -169,8 +169,8 @@ static X509ExtendedTrustManager createTrustManager(@Nullable KeyStore trustStore tmf.init(trustStore); TrustManager[] trustManagers = tmf.getTrustManagers(); for (TrustManager trustManager : trustManagers) { - if (trustManager instanceof X509ExtendedTrustManager) { - return (X509ExtendedTrustManager) trustManager; + if (trustManager instanceof X509ExtendedTrustManager x509TrustManager) { + return x509TrustManager; } } throw new SslConfigException( diff --git a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/PemUtils.java b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/PemUtils.java index 8719a617e8705..d6559aaf0fce8 100644 --- a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/PemUtils.java +++ b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/PemUtils.java @@ -123,24 +123,26 @@ private static PrivateKeyInfo loadPrivateKeyFromFile(Path keyPath, Supplier { + var inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider( + BouncyCastleFipsProvider.PROVIDER_NAME + ).build(passwordSupplier.get()); + return privateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider); + } + case PEMEncryptedKeyPair encryptedKeyPair -> { + var decryptorProvider = new JcePEMDecryptorProviderBuilder().setProvider(BouncyCastleFipsProvider.PROVIDER_NAME) + .build(passwordSupplier.get()); + var keyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider); + return keyPair.getPrivateKeyInfo(); + } + case PEMKeyPair pemKeyPair -> { + return pemKeyPair.getPrivateKeyInfo(); // unencrypted private key + } + case PrivateKeyInfo privateKeyInfo -> { + return privateKeyInfo; // unencrypted private key in pkcs8-format + } + default -> throw new SslConfigException( String.format( Locale.ROOT, "error parsing private key [%s], invalid encrypted private key class: [%s]", diff --git a/libs/x-content/src/main/java/org/opensearch/common/xcontent/json/JsonXContentGenerator.java b/libs/x-content/src/main/java/org/opensearch/common/xcontent/json/JsonXContentGenerator.java index 3f8493d7a4f14..7fe5d999ba11b 100644 --- a/libs/x-content/src/main/java/org/opensearch/common/xcontent/json/JsonXContentGenerator.java +++ b/libs/x-content/src/main/java/org/opensearch/common/xcontent/json/JsonXContentGenerator.java @@ -91,8 +91,8 @@ public JsonXContentGenerator(JsonGenerator jsonGenerator, OutputStream os, Set streamResponse, Exception c private void notifyHandlerOfException(TransportResponseHandler handler, Exception exception) { StreamException streamException; - if (exception instanceof StreamException) { - streamException = (StreamException) exception; + if (exception instanceof StreamException se) { + streamException = se; } else { streamException = new StreamException(StreamErrorCode.INTERNAL, "Stream processing failed", exception); } @@ -340,7 +340,7 @@ private void notifyListeners(List> listeners, CompletableFu private void notifyListener(ActionListener listener, CompletableFuture future) { if (future.isCompletedExceptionally()) { future.handle((result, ex) -> { - listener.onFailure(ex instanceof Exception ? (Exception) ex : new Exception(ex)); + listener.onFailure(ex instanceof Exception exception ? exception : new Exception(ex)); return null; }); } else { diff --git a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightOutboundHandler.java b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightOutboundHandler.java index 8678fa5a5ada5..b340b98492f01 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightOutboundHandler.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightOutboundHandler.java @@ -272,8 +272,8 @@ private void processErrorTask(BatchTask task) { try { Exception flightError = task.error(); - if (task.error() instanceof StreamException) { - flightError = FlightErrorMapper.toFlightException((StreamException) task.error()); + if (task.error() instanceof StreamException se) { + flightError = FlightErrorMapper.toFlightException(se); } flightServerChannel.sendError(getHeaderBuffer(task.requestId(), task.nodeVersion(), task.features()), flightError); messageListener.onResponseSent(task.requestId(), task.action(), task.error()); diff --git a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightServerChannel.java b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightServerChannel.java index 1a9877e6205dd..cef4ed0d99c92 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightServerChannel.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightServerChannel.java @@ -152,8 +152,8 @@ public void sendError(ByteBuffer header, Exception error) { if (!open.get()) { throw new IllegalStateException("FlightServerChannel already closed."); } - if (error instanceof FlightRuntimeException) { - flightExc = (FlightRuntimeException) error; + if (error instanceof FlightRuntimeException fre) { + flightExc = fre; } else { flightExc = CallStatus.INTERNAL.withCause(error) .withDescription(error.getMessage() != null ? error.getMessage() : "Stream error") diff --git a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightTransportChannel.java b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightTransportChannel.java index 25e343b906982..cba53819ff3c1 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightTransportChannel.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/FlightTransportChannel.java @@ -122,8 +122,8 @@ public void completeStream() { ((FlightOutboundHandler) outboundHandler).completeStream(version, features, getChannel(), this, requestId, action); } catch (Exception e) { release(true); - if (e instanceof StreamException) { - throw (StreamException) e; + if (e instanceof StreamException se) { + throw se; } throw new StreamException(StreamErrorCode.INTERNAL, "Error completing stream", e); } diff --git a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/MetricsTrackingResponseHandler.java b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/MetricsTrackingResponseHandler.java index bcc4043c516dd..04d22e5746141 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/MetricsTrackingResponseHandler.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/opensearch/arrow/flight/transport/MetricsTrackingResponseHandler.java @@ -46,8 +46,8 @@ public void handleResponse(T response) { @Override public void handleException(TransportException exp) { try { - if (exp instanceof StreamException) { - callTracker.recordCallEnd(((StreamException) exp).getErrorCode().name()); + if (exp instanceof StreamException se) { + callTracker.recordCallEnd(se.getErrorCode().name()); } else { callTracker.recordCallEnd(StreamErrorCode.INTERNAL.name()); } @@ -75,8 +75,8 @@ public void handleStreamResponse(StreamTransportResponse response) { delegate.handleStreamResponse(wrappedResponse); callTracker.recordCallEnd(StreamErrorCode.OK.name()); } catch (Exception e) { - if (e instanceof StreamException) { - callTracker.recordCallEnd(((StreamException) e).getErrorCode().name()); + if (e instanceof StreamException se) { + callTracker.recordCallEnd(se.getErrorCode().name()); } else { callTracker.recordCallEnd(StreamErrorCode.INTERNAL.name()); } diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java index bd1b91bfa4793..45dbde489cfda 100644 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java +++ b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java @@ -177,8 +177,8 @@ static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMe attrs.put(Node.NODE_ATTRIBUTES.getKey() + "aws_availability_zone", metadataResult); } } catch (final Exception e) { - if (e instanceof IllegalStateException) { - throw (IllegalStateException) e; + if (e instanceof IllegalStateException ise) { + throw ise; } // this is lenient so the plugin does not fail when installed outside of ec2 logger.error("failed to get metadata for [placement/availability-zone]", e); diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/GceSeedHostsProvider.java b/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/GceSeedHostsProvider.java index 5958c07e244ad..430868a1a945a 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/GceSeedHostsProvider.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/GceSeedHostsProvider.java @@ -254,8 +254,8 @@ public List getSeedAddresses(HostsResolver hostsResolver) { if (instance.getMetadata() != null && instance.getMetadata().containsKey("opensearch_port")) { Object opensearch_port = instance.getMetadata().get("opensearch_port"); logger.trace("opensearch_port is defined with {}", opensearch_port); - if (opensearch_port instanceof String) { - address = address.concat(":").concat((String) opensearch_port); + if (opensearch_port instanceof String osp) { + address = address.concat(":").concat(osp); } else { // Ignoring other values logger.trace("opensearch_port is instance of {}. Ignoring...", opensearch_port.getClass().getName()); diff --git a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroSubject.java b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroSubject.java index 73ce3f835fc9b..e4ce9b5328a30 100644 --- a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroSubject.java +++ b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroSubject.java @@ -42,7 +42,7 @@ public ShiroSubject(final ShiroTokenManager authTokenHandler, final org.apache.s public Principal getPrincipal() { final Object o = shiroSubject.getPrincipal(); if (o == null) return null; - if (o instanceof Principal) return (Principal) o; + if (o instanceof Principal principal) return principal; return () -> o.toString(); } diff --git a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroTokenManager.java b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroTokenManager.java index cd54bbf9b3124..e13fd3028986a 100644 --- a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroTokenManager.java +++ b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/ShiroTokenManager.java @@ -49,8 +49,7 @@ class ShiroTokenManager implements TokenManager { * @return An optional of the shiro auth token for login */ public Optional translateAuthToken(org.opensearch.identity.tokens.AuthToken authenticationToken) { - if (authenticationToken instanceof BasicAuthToken) { - final BasicAuthToken basicAuthToken = (BasicAuthToken) authenticationToken; + if (authenticationToken instanceof BasicAuthToken basicAuthToken) { return Optional.of(new UsernamePasswordToken(basicAuthToken.getUser(), basicAuthToken.getPassword())); } return Optional.empty(); @@ -85,16 +84,14 @@ public AuthToken issueServiceAccountToken(String audience) { } public String getTokenInfo(AuthToken token) { - if (token instanceof BasicAuthToken) { - final BasicAuthToken basicAuthToken = (BasicAuthToken) token; + if (token instanceof BasicAuthToken basicAuthToken) { return basicAuthToken.toString(); } throw new UnsupportedAuthenticationToken(); } public void revokeToken(AuthToken token) { - if (token instanceof BasicAuthToken) { - final BasicAuthToken basicAuthToken = (BasicAuthToken) token; + if (token instanceof BasicAuthToken basicAuthToken) { basicAuthToken.revoke(); return; } @@ -102,8 +99,7 @@ public void revokeToken(AuthToken token) { } public void resetToken(AuthToken token) { - if (token instanceof BasicAuthToken) { - final BasicAuthToken basicAuthToken = (BasicAuthToken) token; + if (token instanceof BasicAuthToken basicAuthToken) { basicAuthToken.revoke(); } } diff --git a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/realm/OpenSearchRealm.java b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/realm/OpenSearchRealm.java index 1fc9a1f437a42..d422de6180687 100644 --- a/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/realm/OpenSearchRealm.java +++ b/plugins/identity-shiro/src/main/java/org/opensearch/identity/shiro/realm/OpenSearchRealm.java @@ -105,8 +105,8 @@ public User getInternalUser(final String principalIdentifier) throws UnknownAcco */ @Override protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException { - if (token instanceof UsernamePasswordToken) { - final String username = ((UsernamePasswordToken) token).getUsername(); + if (token instanceof UsernamePasswordToken t) { + final String username = t.getUsername(); // Look up the user by the provide username final User userRecord = getInternalUser(username); // TODO: Check for other things, like a locked account, expired password, etc. diff --git a/plugins/ingest-attachment/src/main/java/org/opensearch/ingest/attachment/TikaImpl.java b/plugins/ingest-attachment/src/main/java/org/opensearch/ingest/attachment/TikaImpl.java index 068f1ae5d6d78..d120a34b05c73 100644 --- a/plugins/ingest-attachment/src/main/java/org/opensearch/ingest/attachment/TikaImpl.java +++ b/plugins/ingest-attachment/src/main/java/org/opensearch/ingest/attachment/TikaImpl.java @@ -174,10 +174,10 @@ static String parse(final byte content[], final Metadata metadata, final int lim } catch (PrivilegedActionException e) { // checked exception from tika: unbox it Throwable cause = e.getCause(); - if (cause instanceof TikaException) { - throw (TikaException) cause; - } else if (cause instanceof IOException) { - throw (IOException) cause; + if (cause instanceof TikaException te) { + throw te; + } else if (cause instanceof IOException ioe) { + throw ioe; } else { throw new AssertionError(cause); } @@ -205,8 +205,8 @@ static PermissionCollection getRestrictedPermissions() { // classpath addReadPermissions(perms, JarHell.parseClassPath()); // plugin jars - if (TikaImpl.class.getClassLoader() instanceof URLClassLoader) { - URL[] urls = ((URLClassLoader) TikaImpl.class.getClassLoader()).getURLs(); + if (TikaImpl.class.getClassLoader() instanceof URLClassLoader urlClassLoader) { + URL[] urls = urlClassLoader.getURLs(); Set set = new LinkedHashSet<>(Arrays.asList(urls)); if (set.size() != urls.length) { throw new AssertionError("duplicate jars: " + Arrays.toString(urls)); diff --git a/plugins/ingestion-fs/src/main/java/org/opensearch/plugin/ingestion/fs/FileOffset.java b/plugins/ingestion-fs/src/main/java/org/opensearch/plugin/ingestion/fs/FileOffset.java index 27da8b6ff078c..3d2afa98b4dd7 100644 --- a/plugins/ingestion-fs/src/main/java/org/opensearch/plugin/ingestion/fs/FileOffset.java +++ b/plugins/ingestion-fs/src/main/java/org/opensearch/plugin/ingestion/fs/FileOffset.java @@ -62,17 +62,17 @@ public Query newRangeQueryGreaterThan(String fieldName) { @Override public int compareTo(IngestionShardPointer o) { - if (o == null || !(o instanceof FileOffset)) { + if (!(o instanceof FileOffset fileOffset)) { throw new IllegalArgumentException("Incompatible pointer type: " + (o == null ? "null" : o.getClass())); } - return Long.compare(this.line, ((FileOffset) o).line); + return Long.compare(this.line, fileOffset.line); } @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof FileOffset)) return false; - return this.line == ((FileOffset) o).line; + if (!(o instanceof FileOffset fileOffset)) return false; + return this.line == fileOffset.line; } @Override diff --git a/plugins/ingestion-kafka/src/main/java/org/opensearch/plugin/kafka/KafkaOffset.java b/plugins/ingestion-kafka/src/main/java/org/opensearch/plugin/kafka/KafkaOffset.java index 0a1c11d5daa8b..fd7a7d58f296e 100644 --- a/plugins/ingestion-kafka/src/main/java/org/opensearch/plugin/kafka/KafkaOffset.java +++ b/plugins/ingestion-kafka/src/main/java/org/opensearch/plugin/kafka/KafkaOffset.java @@ -71,10 +71,9 @@ public int compareTo(IngestionShardPointer o) { if (o == null) { throw new IllegalArgumentException("the pointer is null"); } - if (!(o instanceof KafkaOffset)) { + if (!(o instanceof KafkaOffset other)) { throw new IllegalArgumentException("the pointer is of type " + o.getClass() + " and not KafkaOffset"); } - KafkaOffset other = (KafkaOffset) o; return Long.compare(offset, other.offset); } diff --git a/plugins/ingestion-kinesis/src/main/java/org/opensearch/plugin/kinesis/SequenceNumber.java b/plugins/ingestion-kinesis/src/main/java/org/opensearch/plugin/kinesis/SequenceNumber.java index 9a379627ac589..77d899d905141 100644 --- a/plugins/ingestion-kinesis/src/main/java/org/opensearch/plugin/kinesis/SequenceNumber.java +++ b/plugins/ingestion-kinesis/src/main/java/org/opensearch/plugin/kinesis/SequenceNumber.java @@ -73,10 +73,9 @@ public int compareTo(IngestionShardPointer o) { if (o == null) { throw new IllegalArgumentException("the pointer is null"); } - if (!(o instanceof SequenceNumber)) { + if (!(o instanceof SequenceNumber other)) { throw new IllegalArgumentException("the pointer is of type " + o.getClass() + " and not SequenceNumber"); } - SequenceNumber other = (SequenceNumber) o; return sequenceNumber.compareTo(other.sequenceNumber); } diff --git a/plugins/repository-gcs/src/main/java/org/opensearch/repositories/gcs/GoogleCloudStorageRepository.java b/plugins/repository-gcs/src/main/java/org/opensearch/repositories/gcs/GoogleCloudStorageRepository.java index f6d078868b875..0cb1b9fa071bf 100644 --- a/plugins/repository-gcs/src/main/java/org/opensearch/repositories/gcs/GoogleCloudStorageRepository.java +++ b/plugins/repository-gcs/src/main/java/org/opensearch/repositories/gcs/GoogleCloudStorageRepository.java @@ -150,7 +150,7 @@ static T getSetting(Setting setting, RepositoryMetadata metadata) { if (value == null) { throw new RepositoryException(metadata.name(), "Setting [" + setting.getKey() + "] is not defined for repository"); } - if ((value instanceof String) && (Strings.hasText((String) value)) == false) { + if (value instanceof String s && Strings.hasText(s) == false) { throw new RepositoryException(metadata.name(), "Setting [" + setting.getKey() + "] is empty for repository"); } return value; diff --git a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/AmazonAsyncS3Reference.java b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/AmazonAsyncS3Reference.java index 45170ea1ad209..58780f1ac74bf 100644 --- a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/AmazonAsyncS3Reference.java +++ b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/AmazonAsyncS3Reference.java @@ -31,9 +31,9 @@ public class AmazonAsyncS3Reference extends RefCountedReleasable { AmazonS3Reference(S3Client client, @Nullable AwsCredentialsProvider credentials) { super("AWS_S3_CLIENT", client, () -> { client.close(); - if (credentials instanceof AutoCloseable) { + if (credentials instanceof AutoCloseable autoCloseable) { try { - ((AutoCloseable) credentials).close(); + autoCloseable.close(); } catch (Exception e) { /* Do nothing here */ } diff --git a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3BlobContainer.java b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3BlobContainer.java index ef05deaa6b493..179b2ff400aed 100644 --- a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3BlobContainer.java +++ b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3BlobContainer.java @@ -906,9 +906,7 @@ public void onComplete() { if (throwable != null) { logger.error(() -> new ParameterizedMessage("Failed to complete async deletion for path [{}]", keyPath), throwable); completionListener.onFailure( - throwable instanceof Exception - ? (Exception) throwable - : new IOException("Unexpected error during async deletion", throwable) + throwable instanceof Exception e ? e : new IOException("Unexpected error during async deletion", throwable) ); } else { logger.debug( diff --git a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3RetryingInputStream.java b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3RetryingInputStream.java index 43b86e47c7b73..2a9edb2aa9e40 100644 --- a/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3RetryingInputStream.java +++ b/plugins/repository-s3/src/main/java/org/opensearch/repositories/s3/S3RetryingInputStream.java @@ -128,10 +128,8 @@ private void openStream() throws IOException { this.metadata = getObjectResponseInputStream.response().metadata(); this.isStreamAborted.set(false); } catch (final SdkException e) { - if (e instanceof S3Exception) { - if (404 == ((S3Exception) e).statusCode()) { - throw addSuppressedExceptions(new NoSuchFileException("Blob object [" + blobKey + "] not found: " + e.getMessage())); - } + if (e instanceof S3Exception s3e && 404 == s3e.statusCode()) { + throw addSuppressedExceptions(new NoSuchFileException("Blob object [" + blobKey + "] not found: " + e.getMessage())); } throw addSuppressedExceptions(e); } diff --git a/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/OTelAttributesConverter.java b/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/OTelAttributesConverter.java index 98d265e92ba3c..23d304bc877af 100644 --- a/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/OTelAttributesConverter.java +++ b/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/OTelAttributesConverter.java @@ -39,16 +39,14 @@ public static Attributes convert(org.opensearch.telemetry.tracing.attributes.Att } private static void addSpanAttribute(String key, Object value, AttributesBuilder attributesBuilder) { - if (value instanceof Boolean) { - attributesBuilder.put(key, (Boolean) value); - } else if (value instanceof Long) { - attributesBuilder.put(key, (Long) value); - } else if (value instanceof Double) { - attributesBuilder.put(key, (Double) value); - } else if (value instanceof String) { - attributesBuilder.put(key, (String) value); - } else { - throw new IllegalArgumentException(String.format(Locale.ROOT, "Span attribute value %s type not supported", value)); + switch (value) { + case Boolean b -> attributesBuilder.put(key, b); + case Long l -> attributesBuilder.put(key, l); + case Double v -> attributesBuilder.put(key, v); + case String s -> attributesBuilder.put(key, s); + case null, default -> throw new IllegalArgumentException( + String.format(Locale.ROOT, "Span attribute value %s type not supported", value) + ); } } diff --git a/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/tracing/OTelTracingTelemetry.java b/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/tracing/OTelTracingTelemetry.java index af39617a8c744..6443aefbb5c34 100644 --- a/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/tracing/OTelTracingTelemetry.java +++ b/plugins/telemetry-otel/src/main/java/org/opensearch/telemetry/tracing/OTelTracingTelemetry.java @@ -72,10 +72,10 @@ io.opentelemetry.api.trace.Span otelSpan( io.opentelemetry.api.common.Attributes attributes, io.opentelemetry.api.trace.SpanKind spanKind ) { - return parentOTelSpan == null || !(parentOTelSpan instanceof OTelSpan) + return !(parentOTelSpan instanceof OTelSpan oTelSpan) ? otelTracer.spanBuilder(spanName).setAllAttributes(attributes).startSpan() : otelTracer.spanBuilder(spanName) - .setParent(Context.current().with(((OTelSpan) parentOTelSpan).getDelegateSpan())) + .setParent(Context.current().with(oTelSpan.getDelegateSpan())) .setAllAttributes(attributes) .setSpanKind(spanKind) .startSpan(); diff --git a/plugins/transport-reactor-netty4/src/main/java/org/opensearch/http/reactor/netty4/ReactorNetty4HttpRequest.java b/plugins/transport-reactor-netty4/src/main/java/org/opensearch/http/reactor/netty4/ReactorNetty4HttpRequest.java index c6b90ba578447..10f06ad91b78d 100644 --- a/plugins/transport-reactor-netty4/src/main/java/org/opensearch/http/reactor/netty4/ReactorNetty4HttpRequest.java +++ b/plugins/transport-reactor-netty4/src/main/java/org/opensearch/http/reactor/netty4/ReactorNetty4HttpRequest.java @@ -224,7 +224,7 @@ public boolean isEmpty() { @Override public boolean containsKey(Object key) { - return key instanceof String && httpHeaders.contains((String) key); + return key instanceof String s && httpHeaders.contains(s); } @Override @@ -234,7 +234,7 @@ public boolean containsValue(Object value) { @Override public List get(Object key) { - return key instanceof String ? httpHeaders.getAll((String) key) : null; + return key instanceof String s ? httpHeaders.getAll(s) : null; } @Override