diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java index 214ce9ecaa0a9..d86ec9001d415 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java @@ -14,7 +14,6 @@ import org.gradle.api.model.ObjectFactory; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.TaskAction; -import org.gradle.internal.deprecation.DeprecatableConfiguration; import java.util.Collection; import java.util.stream.Collectors; @@ -50,8 +49,7 @@ private static boolean canBeResolved(Configuration configuration) { if (configuration.isCanBeResolved() == false) { return false; } - if (configuration instanceof org.gradle.internal.deprecation.DeprecatableConfiguration) { - var deprecatableConfiguration = (DeprecatableConfiguration) configuration; + if (configuration instanceof org.gradle.internal.deprecation.DeprecatableConfiguration deprecatableConfiguration) { if (deprecatableConfiguration.canSafelyBeResolved() == false) { return false; } diff --git a/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchNode.java b/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchNode.java index 3a6fb2a5c999d..009c2fed89f1e 100644 --- a/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchNode.java +++ b/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchNode.java @@ -1209,8 +1209,7 @@ private void sync(Path sourceRoot, Path destinationRoot, BiConsumer } }); } catch (UncheckedIOException e) { - if (e.getCause() instanceof NoSuchFileException) { - NoSuchFileException cause = (NoSuchFileException) e.getCause(); + if (e.getCause()instanceof NoSuchFileException cause) { // Ignore these files that are sometimes left behind by the JVM if (cause.getFile() == null || cause.getFile().contains(".attach_pid") == false) { throw new UncheckedIOException(cause); diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java index 60327e987dd69..f5bdcfb869139 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java @@ -2355,8 +2355,7 @@ public void onSuccess(Response response) { @Override public void onFailure(Exception exception) { - if (exception instanceof ResponseException) { - ResponseException responseException = (ResponseException) exception; + if (exception instanceof ResponseException responseException) { Response response = responseException.getResponse(); if (ignores.contains(response.getStatusLine().getStatusCode())) { try { @@ -2426,8 +2425,7 @@ public void onSuccess(Response response) { @Override public void onFailure(Exception exception) { - if (exception instanceof ResponseException) { - ResponseException responseException = (ResponseException) exception; + if (exception instanceof ResponseException responseException) { Response response = responseException.getResponse(); if (RestStatus.NOT_FOUND.getStatus() == response.getStatusLine().getStatusCode()) { actionListener.onResponse(Optional.empty()); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/BulkProcessorRetryIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/BulkProcessorRetryIT.java index befc02492501a..06044782661c0 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/BulkProcessorRetryIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/BulkProcessorRetryIT.java @@ -87,8 +87,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure) boolean rejectedAfterAllRetries = false; for (Object response : responses) { - if (response instanceof BulkResponse) { - BulkResponse bulkResponse = (BulkResponse) response; + if (response instanceof BulkResponse bulkResponse) { for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) { if (bulkItemResponse.isFailed()) { BulkItemResponse.Failure failure = bulkItemResponse.getFailure(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/test/RequestMatcher.java b/client/rest-high-level/src/test/java/org/elasticsearch/test/RequestMatcher.java index 61b84f1204fa8..a011bcf520395 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/test/RequestMatcher.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/test/RequestMatcher.java @@ -27,8 +27,7 @@ public RequestMatcher(String method, String endpoint) { @Override public boolean matches(Object actual) { - if (actual instanceof Request) { - Request req = (Request) actual; + if (actual instanceof Request req) { return method.equals(req.getMethod()) && endpoint.equals(req.getEndpoint()); } return false; diff --git a/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java b/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java index 6d4d4f59f9d45..f3eddbbfd5568 100644 --- a/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java +++ b/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java @@ -69,8 +69,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/lz4/src/test/java/org/elasticsearch/lz4/ESLZ4Tests.java b/libs/lz4/src/test/java/org/elasticsearch/lz4/ESLZ4Tests.java index ff2c0b0378c2b..3f7de0bfd4e0e 100644 --- a/libs/lz4/src/test/java/org/elasticsearch/lz4/ESLZ4Tests.java +++ b/libs/lz4/src/test/java/org/elasticsearch/lz4/ESLZ4Tests.java @@ -209,10 +209,10 @@ public void testRoundTrip(SrcDestTester tester, byte[] data, LZ4Compresso final int maxCompressedLength = tester.maxCompressedLength(data.length); final T compressed = tester.allocate(maxCompressedLength); final int compressedLen = tester.compress(compressor, original, compressed); - if (original instanceof ByteBuffer) { - assertEquals(data.length, ((ByteBuffer) original).position()); + if (original instanceof ByteBuffer byteBuffer) { + assertEquals(data.length, byteBuffer.position()); assertEquals(compressedLen, ((ByteBuffer) compressed).position()); - ((ByteBuffer) original).rewind(); + byteBuffer.rewind(); ((ByteBuffer) compressed).rewind(); } diff --git a/libs/nio/src/main/java/org/elasticsearch/nio/NioSelector.java b/libs/nio/src/main/java/org/elasticsearch/nio/NioSelector.java index d50839f7e5cc5..4760368140176 100644 --- a/libs/nio/src/main/java/org/elasticsearch/nio/NioSelector.java +++ b/libs/nio/src/main/java/org/elasticsearch/nio/NioSelector.java @@ -442,8 +442,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/elasticsearch/common/ssl/DiagnosticTrustManager.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DiagnosticTrustManager.java index 7d55f05181ae1..120a24d3c0364 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DiagnosticTrustManager.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DiagnosticTrustManager.java @@ -137,8 +137,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 final SSLSocket ssl) { final SSLSession handshakeSession = ssl.getHandshakeSession(); if (handshakeSession == null) { return ssl.getSession(); diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/KeyStoreUtil.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/KeyStoreUtil.java index 333c4c347bbac..b235ec986c741 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/KeyStoreUtil.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/KeyStoreUtil.java @@ -146,8 +146,8 @@ public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] kmf.init(keyStore, password); KeyManager[] keyManagers = kmf.getKeyManagers(); for (KeyManager keyManager : keyManagers) { - if (keyManager instanceof X509ExtendedKeyManager) { - return (X509ExtendedKeyManager) keyManager; + if (keyManager instanceof X509ExtendedKeyManager x509ExtendedKeyManager) { + return x509ExtendedKeyManager; } } throw new SslConfigException( @@ -164,8 +164,8 @@ public static X509ExtendedTrustManager createTrustManager(@Nullable KeyStore tru tmf.init(trustStore); TrustManager[] trustManagers = tmf.getTrustManagers(); for (TrustManager trustManager : trustManagers) { - if (trustManager instanceof X509ExtendedTrustManager) { - return (X509ExtendedTrustManager) trustManager; + if (trustManager instanceof X509ExtendedTrustManager x509ExtendedTrustManager) { + return x509ExtendedTrustManager; } } throw new SslConfigException( @@ -231,8 +231,8 @@ public String getAlias() { public X509Certificate getX509Certificate() { try { final Certificate c = store.getCertificate(alias); - if (c instanceof X509Certificate) { - return (X509Certificate) c; + if (c instanceof X509Certificate x509Certificate) { + return x509Certificate; } else { return null; } @@ -261,8 +261,8 @@ public boolean isKeyEntry() { public PrivateKey getKey(char[] password) { try { final Key key = store.getKey(alias, password); - if (key instanceof PrivateKey) { - return (PrivateKey) key; + if (key instanceof PrivateKey privateKey) { + return privateKey; } return null; } catch (GeneralSecurityException e) { diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemKeyConfig.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemKeyConfig.java index cf7b47575649e..765a648bcd727 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemKeyConfig.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemKeyConfig.java @@ -74,8 +74,8 @@ public Collection getConfiguredCertificates() { final List info = new ArrayList<>(certificates.size()); boolean first = true; for (Certificate cert : certificates) { - if (cert instanceof X509Certificate) { - info.add(new StoredCertificate((X509Certificate) cert, this.certificate, "PEM", null, first)); + if (cert instanceof X509Certificate x509Certificate) { + info.add(new StoredCertificate(x509Certificate, this.certificate, "PEM", null, first)); } first = false; } @@ -105,8 +105,8 @@ public List> getKeys() { return List.of(); } final Certificate leafCertificate = certificates.get(0); - if (leafCertificate instanceof X509Certificate) { - return List.of(Tuple.tuple(getPrivateKey(keyPath), (X509Certificate) leafCertificate)); + if (leafCertificate instanceof X509Certificate x509Certificate) { + return List.of(Tuple.tuple(getPrivateKey(keyPath), x509Certificate)); } else { return List.of(); } diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/MapXContentParser.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/MapXContentParser.java index 97b947e761d23..1250c4cae6bc2 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/MapXContentParser.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/MapXContentParser.java @@ -58,8 +58,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 aBoolean) { + return aBoolean; } else { throw new IllegalStateException("Cannot get boolean value for the current token " + currentToken()); } @@ -216,8 +216,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[] bytes) { + return bytes; } else { throw new IllegalStateException("Cannot get binary value for the current token " + currentToken()); } diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SetProcessorTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SetProcessorTests.java index 9001992f20f52..5a67fdd30c746 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SetProcessorTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SetProcessorTests.java @@ -182,8 +182,7 @@ public void testCopyFromOtherField() throws Exception { } private static void assertMapEquals(Object actual, Object expected) { - if (expected instanceof Map) { - Map expectedMap = (Map) expected; + if (expected instanceof Map expectedMap) { Map actualMap = (Map) actual; assertThat(actualMap.keySet().toArray(), arrayContainingInAnyOrder(expectedMap.keySet().toArray())); for (Map.Entry entry : actualMap.entrySet()) { diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java index d00a737235ee5..0adf6c66c9dd5 100644 --- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java +++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java @@ -54,8 +54,8 @@ static final class ArrayMap extends AbstractMap implements Itera public Object get(Object key) { if ("size".equals(key)) { return size(); - } else if (key instanceof Number) { - return Array.get(array, ((Number) key).intValue()); + } else if (key instanceof Number number) { + return Array.get(array, number.intValue()); } try { int index = Integer.parseInt(key.toString()); @@ -112,8 +112,8 @@ static final class CollectionMap extends AbstractMap implements public Object get(Object key) { if ("size".equals(key)) { return col.size(); - } else if (key instanceof Number) { - return Iterables.get(col, ((Number) key).intValue()); + } else if (key instanceof Number number) { + return Iterables.get(col, number.intValue()); } try { int index = Integer.parseInt(key.toString()); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java index c9c242f7ba1fe..f887f7c7e6027 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java @@ -456,8 +456,7 @@ public void visitForLoop(ForLoopNode irForLoopNode, WriteScope writeScope) { if (irInitializerNode instanceof DeclarationBlockNode) { visit(irInitializerNode, writeScope); - } else if (irInitializerNode instanceof ExpressionNode) { - ExpressionNode irExpressionNode = (ExpressionNode) irInitializerNode; + } else if (irInitializerNode instanceof ExpressionNode irExpressionNode) { visit(irExpressionNode, writeScope); methodWriter.writePop(MethodWriter.getType(irExpressionNode.getDecorationValue(IRDExpressionType.class)).getSize()); @@ -1672,8 +1671,7 @@ public void visitInvokeCallDef(InvokeCallDefNode irInvokeCallDefNode, WriteScope // handle the case for unknown functional interface // to hint at which values are the call's arguments // versus which values are captures - if (irArgumentNode instanceof DefInterfaceReferenceNode) { - DefInterfaceReferenceNode defInterfaceReferenceNode = (DefInterfaceReferenceNode) irArgumentNode; + if (irArgumentNode instanceof DefInterfaceReferenceNode defInterfaceReferenceNode) { List captureNames = defInterfaceReferenceNode.getDecorationValueOrDefault( IRDCaptureNames.class, Collections.emptyList() diff --git a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/test/ElasticsearchGeoAssertions.java b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/test/ElasticsearchGeoAssertions.java index 4f62c12a3030a..a7f9b5401088b 100644 --- a/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/test/ElasticsearchGeoAssertions.java +++ b/modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/test/ElasticsearchGeoAssertions.java @@ -193,9 +193,7 @@ public static void assertEquals(ShapeCollection s1, ShapeCollection s2) { public static void assertEquals(Object s1, Object s2) { if (s1 instanceof JtsGeometry && s2 instanceof JtsGeometry) { assertEquals((JtsGeometry) s1, (JtsGeometry) s2); - } else if (s1 instanceof JtsPoint && s2 instanceof JtsPoint) { - JtsPoint p1 = (JtsPoint) s1; - JtsPoint p2 = (JtsPoint) s2; + } else if (s1 instanceof JtsPoint p1 && s2 instanceof JtsPoint p2) { Assert.assertEquals(p1, p2); } else if (s1 instanceof ShapeCollection && s2 instanceof ShapeCollection) { assertEquals((ShapeCollection) s1, (ShapeCollection) s2); @@ -203,17 +201,17 @@ public static void assertEquals(Object s1, Object s2) { Assert.assertEquals(s1, s2); } else if (s1 instanceof RectangleImpl && s2 instanceof RectangleImpl) { Assert.assertEquals(s1, s2); - } else if (s1 instanceof org.apache.lucene.geo.Line[] && s2 instanceof org.apache.lucene.geo.Line[]) { - Assert.assertArrayEquals((org.apache.lucene.geo.Line[]) s1, (org.apache.lucene.geo.Line[]) s2); - } else if (s1 instanceof org.apache.lucene.geo.Polygon[] && s2 instanceof org.apache.lucene.geo.Polygon[]) { - Assert.assertArrayEquals((org.apache.lucene.geo.Polygon[]) s1, (org.apache.lucene.geo.Polygon[]) s2); + } else if (s1 instanceof org.apache.lucene.geo.Line[] lines1 && s2 instanceof org.apache.lucene.geo.Line[] lines2) { + Assert.assertArrayEquals(lines1, lines2); + } else if (s1 instanceof org.apache.lucene.geo.Polygon[] poly1 && s2 instanceof org.apache.lucene.geo.Polygon[] poly2) { + Assert.assertArrayEquals(poly1, poly2); } else if ((s1 instanceof org.apache.lucene.geo.Line && s2 instanceof org.apache.lucene.geo.Line) || (s1 instanceof org.apache.lucene.geo.Polygon && s2 instanceof org.apache.lucene.geo.Polygon) || (s1 instanceof org.apache.lucene.geo.Rectangle && s2 instanceof org.apache.lucene.geo.Rectangle) || (s1 instanceof GeoPoint && s2 instanceof GeoPoint)) { Assert.assertEquals(s1, s2); - } else if (s1 instanceof Object[] && s2 instanceof Object[]) { - Assert.assertArrayEquals((Object[]) s1, (Object[]) s2); + } else if (s1 instanceof Object[] objects1 && s2 instanceof Object[] objects2) { + Assert.assertArrayEquals(objects1, objects2); } else if (s1 instanceof org.elasticsearch.geometry.Geometry && s2 instanceof org.elasticsearch.geometry.Geometry) { Assert.assertEquals(s1, s2); } else { diff --git a/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java b/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java index 43c955ce3cafa..7e2cd439d009a 100644 --- a/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java +++ b/modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/RankFeatureQueryBuilder.java @@ -381,8 +381,7 @@ protected void doXContent(XContentBuilder builder, Params params) throws IOExcep protected Query doToQuery(SearchExecutionContext context) throws IOException { final MappedFieldType ft = context.getFieldType(field); - if (ft instanceof RankFeatureFieldType) { - final RankFeatureFieldType fft = (RankFeatureFieldType) ft; + if (ft instanceof final RankFeatureFieldType fft) { return scoreFunction.toQuery(RankFeatureMetaFieldMapper.NAME, field, fft.positiveScoreImpact()); } else if (ft == null) { final int lastDotIndex = field.lastIndexOf('.'); diff --git a/modules/percolator/src/main/java/org/elasticsearch/percolator/PercolatorFieldMapper.java b/modules/percolator/src/main/java/org/elasticsearch/percolator/PercolatorFieldMapper.java index c764da1e0b269..15d5f3b61a334 100644 --- a/modules/percolator/src/main/java/org/elasticsearch/percolator/PercolatorFieldMapper.java +++ b/modules/percolator/src/main/java/org/elasticsearch/percolator/PercolatorFieldMapper.java @@ -509,8 +509,7 @@ static void verifyQuery(QueryBuilder queryBuilder) { throw new IllegalArgumentException("the [has_child] query is unsupported inside a percolator query"); } else if (queryBuilder.getName().equals("has_parent")) { throw new IllegalArgumentException("the [has_parent] query is unsupported inside a percolator query"); - } else if (queryBuilder instanceof BoolQueryBuilder) { - BoolQueryBuilder boolQueryBuilder = (BoolQueryBuilder) queryBuilder; + } else if (queryBuilder instanceof BoolQueryBuilder boolQueryBuilder) { List clauses = new ArrayList<>(); clauses.addAll(boolQueryBuilder.filter()); clauses.addAll(boolQueryBuilder.must()); @@ -519,15 +518,14 @@ static void verifyQuery(QueryBuilder queryBuilder) { for (QueryBuilder clause : clauses) { verifyQuery(clause); } - } else if (queryBuilder instanceof ConstantScoreQueryBuilder) { - verifyQuery(((ConstantScoreQueryBuilder) queryBuilder).innerQuery()); - } else if (queryBuilder instanceof FunctionScoreQueryBuilder) { - verifyQuery(((FunctionScoreQueryBuilder) queryBuilder).query()); - } else if (queryBuilder instanceof BoostingQueryBuilder) { - verifyQuery(((BoostingQueryBuilder) queryBuilder).negativeQuery()); - verifyQuery(((BoostingQueryBuilder) queryBuilder).positiveQuery()); - } else if (queryBuilder instanceof DisMaxQueryBuilder) { - DisMaxQueryBuilder disMaxQueryBuilder = (DisMaxQueryBuilder) queryBuilder; + } else if (queryBuilder instanceof ConstantScoreQueryBuilder constantScoreQueryBuilder) { + verifyQuery(constantScoreQueryBuilder.innerQuery()); + } else if (queryBuilder instanceof FunctionScoreQueryBuilder functionScoreQueryBuilder) { + verifyQuery(functionScoreQueryBuilder.query()); + } else if (queryBuilder instanceof BoostingQueryBuilder boostingQueryBuilder) { + verifyQuery(boostingQueryBuilder.negativeQuery()); + verifyQuery(boostingQueryBuilder.positiveQuery()); + } else if (queryBuilder instanceof DisMaxQueryBuilder disMaxQueryBuilder) { for (QueryBuilder innerQueryBuilder : disMaxQueryBuilder.innerQueries()) { verifyQuery(innerQueryBuilder); } diff --git a/modules/percolator/src/main/java/org/elasticsearch/percolator/QueryAnalyzer.java b/modules/percolator/src/main/java/org/elasticsearch/percolator/QueryAnalyzer.java index f5b2e2ba54c11..7caad5976cdea 100644 --- a/modules/percolator/src/main/java/org/elasticsearch/percolator/QueryAnalyzer.java +++ b/modules/percolator/src/main/java/org/elasticsearch/percolator/QueryAnalyzer.java @@ -160,8 +160,7 @@ public QueryVisitor getSubVisitor(Occur occur, Query parent) { return QueryVisitor.EMPTY_VISITOR; } int minimumShouldMatchValue = 0; - if (parent instanceof BooleanQuery) { - BooleanQuery bq = (BooleanQuery) parent; + if (parent instanceof BooleanQuery bq) { if (bq.getMinimumNumberShouldMatch() == 0 && bq.clauses().stream().anyMatch(c -> c.getOccur() == Occur.MUST || c.getOccur() == Occur.FILTER)) { return QueryVisitor.EMPTY_VISITOR; @@ -198,8 +197,7 @@ public void consumeTerms(Query query, Term... termsToConsume) { @Override public void consumeTermsMatching(Query query, String field, Supplier automaton) { - if (query instanceof TermInSetQuery) { - TermInSetQuery q = (TermInSetQuery) query; + if (query instanceof TermInSetQuery q) { PrefixCodedTerms.TermIterator ti = q.getTermData().iterator(); BytesRef term; Set qe = new HashSet<>(); diff --git a/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteRequestBuilders.java b/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteRequestBuilders.java index 3b770aeff87d8..351427ce31526 100644 --- a/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteRequestBuilders.java +++ b/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteRequestBuilders.java @@ -75,8 +75,7 @@ static Request initialSearch(SearchRequest searchRequest, BytesReference query, // Detect if we should use search_type=scan rather than a sort if (remoteVersion.before(Version.fromId(2010099))) { for (SortBuilder sort : searchRequest.source().sorts()) { - if (sort instanceof FieldSortBuilder) { - FieldSortBuilder f = (FieldSortBuilder) sort; + if (sort instanceof FieldSortBuilder f) { if (f.getFieldName().equals(FieldSortBuilder.DOC_FIELD_NAME)) { useScan = true; break; @@ -174,8 +173,7 @@ private static String encodeIndex(String s) { } private static String sortToUri(SortBuilder sort) { - if (sort instanceof FieldSortBuilder) { - FieldSortBuilder f = (FieldSortBuilder) sort; + if (sort instanceof FieldSortBuilder f) { return f.getFieldName() + ":" + f.order(); } throw new IllegalArgumentException("Unsupported sort [" + sort + "]"); diff --git a/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteScrollableHitSource.java b/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteScrollableHitSource.java index c6f6351098ae2..c5ee0ebbd114b 100644 --- a/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteScrollableHitSource.java +++ b/modules/reindex/src/main/java/org/elasticsearch/reindex/remote/RemoteScrollableHitSource.java @@ -119,8 +119,7 @@ public void onFailure(Exception e) { } private void logFailure(Exception e) { - if (e instanceof ResponseException) { - ResponseException re = (ResponseException) e; + if (e instanceof ResponseException re) { if (remoteVersion.before(Version.fromId(2000099)) && re.getResponse().getStatusLine().getStatusCode() == 404) { logger.debug( (Supplier) () -> new ParameterizedMessage( @@ -217,8 +216,7 @@ public void onSuccess(org.elasticsearch.client.Response response) { public void onFailure(Exception e) { try (ThreadContext.StoredContext ctx = contextSupplier.get()) { assert ctx != null; // eliminates compiler warning - if (e instanceof ResponseException) { - ResponseException re = (ResponseException) e; + if (e instanceof ResponseException re) { int statusCode = re.getResponse().getStatusLine().getStatusCode(); e = wrapExceptionToPreserveStatus(statusCode, re.getResponse().getEntity(), re); if (RestStatus.TOO_MANY_REQUESTS.getStatus() == statusCode) { diff --git a/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java b/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java index 1312cddf015b8..79c7d2280a316 100644 --- a/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java +++ b/modules/reindex/src/test/java/org/elasticsearch/reindex/AsyncBulkByScrollActionTests.java @@ -1068,8 +1068,7 @@ protected void lastSearch.set(new RequestAndListener<>((SearchRequest) request, (ActionListener) responseActionListener)); return; } - if (request instanceof SearchScrollRequest) { - SearchScrollRequest scroll = (SearchScrollRequest) request; + if (request instanceof SearchScrollRequest scroll) { boolean newRequest = usedScolls.add(scroll); assertTrue("We can't reuse scroll requests", newRequest); if (scrollAttempts.incrementAndGet() <= scrollsToReject) { @@ -1079,14 +1078,12 @@ protected void lastScroll.set(new RequestAndListener<>(scroll, (ActionListener) responseActionListener)); return; } - if (request instanceof ClearScrollRequest) { - ClearScrollRequest clearScroll = (ClearScrollRequest) request; + if (request instanceof ClearScrollRequest clearScroll) { scrollsCleared.addAll(clearScroll.getScrollIds()); responseActionListener.onResponse((Response) new ClearScrollResponse(true, clearScroll.getScrollIds().size())); return; } - if (request instanceof BulkRequest) { - BulkRequest bulk = (BulkRequest) request; + if (request instanceof BulkRequest bulk) { int toReject; if (bulksAttempts.incrementAndGet() > bulksToReject) { toReject = -1; @@ -1098,8 +1095,7 @@ protected void DocWriteRequest item = bulk.requests().get(i); DocWriteResponse response; ShardId shardId = new ShardId(new Index(item.index(), "uuid"), 0); - if (item instanceof IndexRequest) { - IndexRequest index = (IndexRequest) item; + if (item instanceof IndexRequest index) { response = new IndexResponse( shardId, index.id() == null ? "dummy_id" : index.id(), @@ -1108,8 +1104,7 @@ protected void randomIntBetween(0, Integer.MAX_VALUE), true ); - } else if (item instanceof UpdateRequest) { - UpdateRequest update = (UpdateRequest) item; + } else if (item instanceof UpdateRequest update) { response = new UpdateResponse( shardId, update.id(), @@ -1118,8 +1113,7 @@ protected void randomIntBetween(0, Integer.MAX_VALUE), Result.CREATED ); - } else if (item instanceof DeleteRequest) { - DeleteRequest delete = (DeleteRequest) item; + } else if (item instanceof DeleteRequest delete) { response = new DeleteResponse( shardId, delete.id(), diff --git a/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/http/RetryingHttpInputStream.java b/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/http/RetryingHttpInputStream.java index 18912772d3939..e335553648acf 100644 --- a/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/http/RetryingHttpInputStream.java +++ b/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/http/RetryingHttpInputStream.java @@ -252,8 +252,8 @@ private HttpResponseInputStream openInputStream() throws IOException { }); } catch (PrivilegedActionException e) { final Throwable cause = e.getCause(); - if (cause instanceof IOException) { - throw (IOException) cause; + if (cause instanceof IOException ioException) { + throw ioException; } throw new IOException(getErrorMessage(), e); } catch (Exception e) {