Skip to content

Commit b4b58db

Browse files
authored
server instanceof pattern matching replacement (elastic#82074) (elastic#82303)
Updating the codebase to use java 17th feature instanceof pattern matching
1 parent 6a04929 commit b4b58db

File tree

116 files changed

+196
-397
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

116 files changed

+196
-397
lines changed

server/src/internalClusterTest/java/org/elasticsearch/action/RejectionActionIT.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,7 @@ public void onFailure(Exception e) {
7171

7272
// validate all responses
7373
for (Object response : responses) {
74-
if (response instanceof SearchResponse) {
75-
SearchResponse searchResponse = (SearchResponse) response;
74+
if (response instanceof SearchResponse searchResponse) {
7675
for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
7776
assertThat(
7877
failure.reason().toLowerCase(Locale.ENGLISH),
@@ -82,8 +81,7 @@ public void onFailure(Exception e) {
8281
} else {
8382
Exception t = (Exception) response;
8483
Throwable unwrap = ExceptionsHelper.unwrapCause(t);
85-
if (unwrap instanceof SearchPhaseExecutionException) {
86-
SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap;
84+
if (unwrap instanceof SearchPhaseExecutionException e) {
8785
for (ShardSearchFailure failure : e.shardFailures()) {
8886
assertThat(
8987
failure.reason().toLowerCase(Locale.ENGLISH),

server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessorRetryIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
100100
// validate all responses
101101
boolean rejectedAfterAllRetries = false;
102102
for (Object response : responses) {
103-
if (response instanceof BulkResponse) {
104-
BulkResponse bulkResponse = (BulkResponse) response;
103+
if (response instanceof BulkResponse bulkResponse) {
105104
for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) {
106105
if (bulkItemResponse.isFailed()) {
107106
BulkItemResponse.Failure failure = bulkItemResponse.getFailure();

server/src/internalClusterTest/java/org/elasticsearch/blocks/SimpleBlocksIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -444,8 +444,7 @@ public void testAddBlockWhileDeletingIndices() throws Exception {
444444

445445
Consumer<Exception> exceptionConsumer = t -> {
446446
Throwable cause = ExceptionsHelper.unwrapCause(t);
447-
if (cause instanceof ClusterBlockException) {
448-
ClusterBlockException e = (ClusterBlockException) cause;
447+
if (cause instanceof ClusterBlockException e) {
449448
assertThat(e.blocks(), hasSize(1));
450449
assertTrue(e.blocks().stream().allMatch(b -> b.id() == block.getBlock().id()));
451450
} else {

server/src/internalClusterTest/java/org/elasticsearch/indices/IndicesOptionsIntegrationIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -712,8 +712,7 @@ private static void verify(ActionRequestBuilder<?, ?> requestBuilder, boolean fa
712712
} catch (IndexNotFoundException | IndexClosedException e) {}
713713
}
714714
} else {
715-
if (requestBuilder instanceof SearchRequestBuilder) {
716-
SearchRequestBuilder searchRequestBuilder = (SearchRequestBuilder) requestBuilder;
715+
if (requestBuilder instanceof SearchRequestBuilder searchRequestBuilder) {
717716
assertHitCount(searchRequestBuilder.get(), expectedCount);
718717
} else if (requestBuilder instanceof MultiSearchRequestBuilder) {
719718
MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get();

server/src/internalClusterTest/java/org/elasticsearch/indices/state/CloseIndexIT.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -684,16 +684,13 @@ static void assertIndexIsOpened(final String... indices) {
684684

685685
static void assertException(final Throwable throwable, final String indexName) {
686686
final Throwable t = ExceptionsHelper.unwrapCause(throwable);
687-
if (t instanceof ClusterBlockException) {
688-
ClusterBlockException clusterBlockException = (ClusterBlockException) t;
687+
if (t instanceof ClusterBlockException clusterBlockException) {
689688
assertThat(clusterBlockException.blocks(), hasSize(1));
690689
assertTrue(clusterBlockException.blocks().stream().allMatch(b -> b.id() == MetadataIndexStateService.INDEX_CLOSED_BLOCK_ID));
691-
} else if (t instanceof IndexClosedException) {
692-
IndexClosedException indexClosedException = (IndexClosedException) t;
690+
} else if (t instanceof IndexClosedException indexClosedException) {
693691
assertThat(indexClosedException.getIndex(), notNullValue());
694692
assertThat(indexClosedException.getIndex().getName(), equalTo(indexName));
695-
} else if (t instanceof IndexNotFoundException) {
696-
IndexNotFoundException indexNotFoundException = (IndexNotFoundException) t;
693+
} else if (t instanceof IndexNotFoundException indexNotFoundException) {
697694
assertThat(indexNotFoundException.getIndex(), notNullValue());
698695
assertThat(indexNotFoundException.getIndex().getName(), equalTo(indexName));
699696
} else {

server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/DateHistogramIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -623,8 +623,7 @@ public void testSingleValuedFieldOrderedByIllegalAgg() throws Exception {
623623
ElasticsearchException[] rootCauses = e.guessRootCauses();
624624
if (rootCauses.length == 1) {
625625
ElasticsearchException rootCause = rootCauses[0];
626-
if (rootCause instanceof AggregationExecutionException) {
627-
AggregationExecutionException aggException = (AggregationExecutionException) rootCause;
626+
if (rootCause instanceof AggregationExecutionException aggException) {
628627
assertThat(aggException.getMessage(), Matchers.startsWith("Invalid aggregation order path"));
629628
} else {
630629
throw e;

server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/HistogramIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -669,8 +669,7 @@ public void testSingleValuedFieldOrderedByIllegalAgg() throws Exception {
669669
ElasticsearchException[] rootCauses = e.guessRootCauses();
670670
if (rootCauses.length == 1) {
671671
ElasticsearchException rootCause = rootCauses[0];
672-
if (rootCause instanceof AggregationExecutionException) {
673-
AggregationExecutionException aggException = (AggregationExecutionException) rootCause;
672+
if (rootCause instanceof AggregationExecutionException aggException) {
674673
assertThat(aggException.getMessage(), Matchers.startsWith("Invalid aggregation order path"));
675674
} else {
676675
throw e;

server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -646,8 +646,7 @@ public void testSingleValuedFieldOrderedByIllegalAgg() throws Exception {
646646
ElasticsearchException[] rootCauses = e.guessRootCauses();
647647
if (rootCauses.length == 1) {
648648
ElasticsearchException rootCause = rootCauses[0];
649-
if (rootCause instanceof AggregationExecutionException) {
650-
AggregationExecutionException aggException = (AggregationExecutionException) rootCause;
649+
if (rootCause instanceof AggregationExecutionException aggException) {
651650
assertThat(aggException.getMessage(), startsWith("Invalid aggregation order path"));
652651
} else {
653652
throw e;

server/src/internalClusterTest/java/org/elasticsearch/versioning/SimpleVersioningIT.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,7 @@ public String toString() {
547547
sb.append(alreadyExists);
548548

549549
if (response != null) {
550-
if (response instanceof DeleteResponse) {
551-
DeleteResponse deleteResponse = (DeleteResponse) response;
550+
if (response instanceof DeleteResponse deleteResponse) {
552551
sb.append(" response:");
553552
sb.append(" index=");
554553
sb.append(deleteResponse.getIndex());
@@ -558,8 +557,7 @@ public String toString() {
558557
sb.append(deleteResponse.getVersion());
559558
sb.append(" found=");
560559
sb.append(deleteResponse.getResult() == DocWriteResponse.Result.DELETED);
561-
} else if (response instanceof IndexResponse) {
562-
IndexResponse indexResponse = (IndexResponse) response;
560+
} else if (response instanceof IndexResponse indexResponse) {
563561
sb.append(" index=");
564562
sb.append(indexResponse.getIndex());
565563
sb.append(" id=");

server/src/main/java/org/apache/lucene/search/vectorhighlight/CustomFieldQuery.java

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ public CustomFieldQuery(Query query, IndexReader reader, boolean phraseHighlight
4444

4545
@Override
4646
protected void flatten(Query sourceQuery, IndexReader reader, Collection<Query> flatQueries, float boost) throws IOException {
47-
if (sourceQuery instanceof BoostQuery) {
48-
BoostQuery bq = (BoostQuery) sourceQuery;
47+
if (sourceQuery instanceof BoostQuery bq) {
4948
sourceQuery = bq.getQuery();
5049
boost *= bq.getBoost();
5150
flatten(sourceQuery, reader, flatQueries, boost);
@@ -57,26 +56,20 @@ protected void flatten(Query sourceQuery, IndexReader reader, Collection<Query>
5756
flatten(((FunctionScoreQuery) sourceQuery).getSubQuery(), reader, flatQueries, boost);
5857
} else if (sourceQuery instanceof MultiPhrasePrefixQuery) {
5958
flatten(sourceQuery.rewrite(reader), reader, flatQueries, boost);
60-
} else if (sourceQuery instanceof MultiPhraseQuery) {
61-
MultiPhraseQuery q = ((MultiPhraseQuery) sourceQuery);
59+
} else if (sourceQuery instanceof MultiPhraseQuery q) {
6260
convertMultiPhraseQuery(0, new int[q.getTermArrays().length], q, q.getTermArrays(), q.getPositions(), reader, flatQueries);
63-
} else if (sourceQuery instanceof BlendedTermQuery) {
64-
final BlendedTermQuery blendedTermQuery = (BlendedTermQuery) sourceQuery;
61+
} else if (sourceQuery instanceof BlendedTermQuery blendedTermQuery) {
6562
flatten(blendedTermQuery.rewrite(reader), reader, flatQueries, boost);
66-
} else if (sourceQuery instanceof org.apache.lucene.queries.function.FunctionScoreQuery) {
67-
org.apache.lucene.queries.function.FunctionScoreQuery funcScoreQuery =
68-
(org.apache.lucene.queries.function.FunctionScoreQuery) sourceQuery;
63+
} else if (sourceQuery instanceof org.apache.lucene.queries.function.FunctionScoreQuery funcScoreQuery) {
6964
// flatten query with query boost
7065
flatten(funcScoreQuery.getWrappedQuery(), reader, flatQueries, boost);
71-
} else if (sourceQuery instanceof SynonymQuery) {
66+
} else if (sourceQuery instanceof SynonymQuery synQuery) {
7267
// SynonymQuery should be handled by the parent class directly.
7368
// This statement should be removed when https://issues.apache.org/jira/browse/LUCENE-7484 is merged.
74-
SynonymQuery synQuery = (SynonymQuery) sourceQuery;
7569
for (Term term : synQuery.getTerms()) {
7670
flatten(new TermQuery(term), reader, flatQueries, boost);
7771
}
78-
} else if (sourceQuery instanceof CombinedFieldQuery) {
79-
CombinedFieldQuery combinedFieldQuery = (CombinedFieldQuery) sourceQuery;
72+
} else if (sourceQuery instanceof CombinedFieldQuery combinedFieldQuery) {
8073
for (Term term : combinedFieldQuery.getTerms()) {
8174
flatten(new TermQuery(term), reader, flatQueries, boost);
8275
}

server/src/main/java/org/elasticsearch/ElasticsearchException.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -332,8 +332,7 @@ protected static void innerToXContent(
332332
headerToXContent(builder, entry.getKey().substring("es.".length()), entry.getValue());
333333
}
334334

335-
if (throwable instanceof ElasticsearchException) {
336-
ElasticsearchException exception = (ElasticsearchException) throwable;
335+
if (throwable instanceof ElasticsearchException exception) {
337336
exception.metadataToXContent(builder, params);
338337
}
339338

server/src/main/java/org/elasticsearch/action/admin/cluster/reroute/TransportClusterRerouteAction.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,7 @@ protected void masterOperation(
8888
) {
8989
Map<String, List<AbstractAllocateAllocationCommand>> stalePrimaryAllocations = new HashMap<>();
9090
for (AllocationCommand command : request.getCommands().commands()) {
91-
if (command instanceof AllocateStalePrimaryAllocationCommand) {
92-
final AllocateStalePrimaryAllocationCommand cmd = (AllocateStalePrimaryAllocationCommand) command;
91+
if (command instanceof final AllocateStalePrimaryAllocationCommand cmd) {
9392
stalePrimaryAllocations.computeIfAbsent(cmd.index(), k -> new ArrayList<>()).add(cmd);
9493
}
9594
}

server/src/main/java/org/elasticsearch/action/admin/cluster/stats/MappingStats.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,7 @@ public static MappingStats of(Metadata metadata, Runnable ensureNotCancelled) {
7676
stats.indexCount++;
7777
}
7878
Object scriptObject = fieldMapping.get("script");
79-
if (scriptObject instanceof Map) {
80-
Map<?, ?> script = (Map<?, ?>) scriptObject;
79+
if (scriptObject instanceof Map<?, ?> script) {
8180
Object sourceObject = script.get("source");
8281
stats.scriptCount++;
8382
updateScriptParams(sourceObject, stats.fieldScriptStats);
@@ -106,8 +105,7 @@ public static MappingStats of(Metadata metadata, Runnable ensureNotCancelled) {
106105
Object scriptObject = fieldMapping.get("script");
107106
if (scriptObject == null) {
108107
stats.scriptLessCount++;
109-
} else if (scriptObject instanceof Map) {
110-
Map<?, ?> script = (Map<?, ?>) scriptObject;
108+
} else if (scriptObject instanceof Map<?, ?> script) {
111109
Object sourceObject = script.get("source");
112110
updateScriptParams(sourceObject, stats.fieldScriptStats);
113111
Object langObject = script.get("lang");

server/src/main/java/org/elasticsearch/action/admin/indices/analyze/TransportAnalyzeAction.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,7 @@ private static AnalyzeAction.DetailAnalyzeResponse detailAnalyze(AnalyzeAction.R
300300
potentialCustomAnalyzer = ((NamedAnalyzer) analyzer).analyzer();
301301
}
302302

303-
if (potentialCustomAnalyzer instanceof AnalyzerComponentsProvider) {
304-
AnalyzerComponentsProvider customAnalyzer = (AnalyzerComponentsProvider) potentialCustomAnalyzer;
303+
if (potentialCustomAnalyzer instanceof AnalyzerComponentsProvider customAnalyzer) {
305304
// note: this is not field-name dependent in our cases so we can leave out the argument
306305
int positionIncrementGap = potentialCustomAnalyzer.getPositionIncrementGap("");
307306
int offsetGap = potentialCustomAnalyzer.getOffsetGap("");
@@ -547,8 +546,7 @@ private static Map<String, Object> extractExtendedAttributes(TokenStream stream,
547546
return;
548547
}
549548
if (includeAttributes == null || includeAttributes.isEmpty() || includeAttributes.contains(key.toLowerCase(Locale.ROOT))) {
550-
if (value instanceof BytesRef) {
551-
final BytesRef p = (BytesRef) value;
549+
if (value instanceof final BytesRef p) {
552550
value = p.toString();
553551
}
554552
extendedAttributes.put(key, value);

server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/IndexDiskUsageAnalyzer.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -294,16 +294,13 @@ private void readProximity(Terms terms, PostingsEnum postings) throws IOExceptio
294294
private BlockTermState getBlockTermState(TermsEnum termsEnum, BytesRef term) throws IOException {
295295
if (term != null && termsEnum.seekExact(term)) {
296296
final TermState termState = termsEnum.termState();
297-
if (termState instanceof Lucene90PostingsFormat.IntBlockTermState) {
298-
final Lucene90PostingsFormat.IntBlockTermState blockTermState = (Lucene90PostingsFormat.IntBlockTermState) termState;
297+
if (termState instanceof final Lucene90PostingsFormat.IntBlockTermState blockTermState) {
299298
return new BlockTermState(blockTermState.docStartFP, blockTermState.posStartFP, blockTermState.payStartFP);
300299
}
301-
if (termState instanceof Lucene84PostingsFormat.IntBlockTermState) {
302-
final Lucene84PostingsFormat.IntBlockTermState blockTermState = (Lucene84PostingsFormat.IntBlockTermState) termState;
300+
if (termState instanceof final Lucene84PostingsFormat.IntBlockTermState blockTermState) {
303301
return new BlockTermState(blockTermState.docStartFP, blockTermState.posStartFP, blockTermState.payStartFP);
304302
}
305-
if (termState instanceof Lucene50PostingsFormat.IntBlockTermState) {
306-
final Lucene50PostingsFormat.IntBlockTermState blockTermState = (Lucene50PostingsFormat.IntBlockTermState) termState;
303+
if (termState instanceof final Lucene50PostingsFormat.IntBlockTermState blockTermState) {
307304
return new BlockTermState(blockTermState.docStartFP, blockTermState.posStartFP, blockTermState.payStartFP);
308305
}
309306
}

server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/TransportAnalyzeIndexDiskUsageAction.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,8 @@ protected AnalyzeIndexDiskUsageResponse newResponse(
106106
final Map<String, IndexDiskUsageStats> combined = new HashMap<>();
107107
for (int i = 0; i < shardsResponses.length(); i++) {
108108
final Object r = shardsResponses.get(i);
109-
if (r instanceof AnalyzeDiskUsageShardResponse) {
109+
if (r instanceof AnalyzeDiskUsageShardResponse resp) {
110110
++successfulShards;
111-
AnalyzeDiskUsageShardResponse resp = (AnalyzeDiskUsageShardResponse) r;
112111
combined.compute(resp.getIndex(), (k, v) -> v == null ? resp.stats : v.add(resp.stats));
113112
} else if (r instanceof DefaultShardOperationFailedException) {
114113
shardFailures.add((DefaultShardOperationFailedException) r);

server/src/main/java/org/elasticsearch/action/admin/indices/mapping/get/TransportGetFieldMappingsAction.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ private GetFieldMappingsResponse merge(AtomicReferenceArray<Object> indexRespons
8787
Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetadata>> mergedResponses = new HashMap<>();
8888
for (int i = 0; i < indexResponses.length(); i++) {
8989
Object element = indexResponses.get(i);
90-
if (element instanceof GetFieldMappingsResponse) {
91-
GetFieldMappingsResponse response = (GetFieldMappingsResponse) element;
90+
if (element instanceof GetFieldMappingsResponse response) {
9291
mergedResponses.putAll(response.mappings());
9392
}
9493
}

server/src/main/java/org/elasticsearch/action/bulk/TransportBulkAction.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,7 @@ public static IndexRequest getIndexWriteRequest(DocWriteRequest<?> docWriteReque
164164
IndexRequest indexRequest = null;
165165
if (docWriteRequest instanceof IndexRequest) {
166166
indexRequest = (IndexRequest) docWriteRequest;
167-
} else if (docWriteRequest instanceof UpdateRequest) {
168-
UpdateRequest updateRequest = (UpdateRequest) docWriteRequest;
167+
} else if (docWriteRequest instanceof UpdateRequest updateRequest) {
169168
indexRequest = updateRequest.docAsUpsert() ? updateRequest.doc() : updateRequest.upsertRequest();
170169
}
171170
return indexRequest;
@@ -217,8 +216,7 @@ protected void doInternalExecute(Task task, BulkRequest bulkRequest, String exec
217216
hasIndexRequestsWithPipelines |= indexRequestHasPipeline;
218217
}
219218

220-
if (actionRequest instanceof IndexRequest) {
221-
IndexRequest ir = (IndexRequest) actionRequest;
219+
if (actionRequest instanceof IndexRequest ir) {
222220
ir.checkAutoIdWithOpTypeCreateSupportedByVersion(minNodeVersion);
223221
if (ir.getAutoGeneratedTimestamp() != IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP) {
224222
throw new IllegalArgumentException("autoGeneratedTimestamp should not be set externally");

server/src/main/java/org/elasticsearch/action/ingest/GetPipelineResponse.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,7 @@ public static GetPipelineResponse fromXContent(XContentParser parser) throws IOE
124124
public boolean equals(Object other) {
125125
if (other == null) {
126126
return false;
127-
} else if (other instanceof GetPipelineResponse) {
128-
GetPipelineResponse otherResponse = (GetPipelineResponse) other;
127+
} else if (other instanceof GetPipelineResponse otherResponse) {
129128
if (pipelines == null) {
130129
return otherResponse.pipelines == null;
131130
} else {

0 commit comments

Comments
 (0)