Skip to content

Commit

Permalink
x-pack batch 1 instanceof pattern matching replacement (elastic#81812)
Browse files Browse the repository at this point in the history
  • Loading branch information
astefan committed Dec 16, 2021
1 parent 0d3fc85 commit 591b492
Show file tree
Hide file tree
Showing 17 changed files with 28 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,15 @@ private PercentileConfig resolvePercentileConfig(
throw buildResolveError(agg, aggPathsList, propertyValue, "percentiles");
}

if (propertyValue instanceof InternalTDigestPercentiles) {
InternalTDigestPercentiles internalTDigestPercentiles = ((InternalTDigestPercentiles) propertyValue);
if (propertyValue instanceof InternalTDigestPercentiles internalTDigestPercentiles) {
return new PercentileConfig(
PercentilesMethod.TDIGEST,
internalTDigestPercentiles.getKeys(),
internalTDigestPercentiles.keyed(),
internalTDigestPercentiles.formatter()
);
}
if (propertyValue instanceof InternalHDRPercentiles) {
InternalHDRPercentiles internalHDRPercentiles = ((InternalHDRPercentiles) propertyValue);
if (propertyValue instanceof InternalHDRPercentiles internalHDRPercentiles) {
return new PercentileConfig(
PercentilesMethod.HDR,
internalHDRPercentiles.getKeys(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -619,8 +619,7 @@ public void testCcrRepositoryFailsToFetchSnapshotShardSizes() throws Exception {
final MockTransportService mockTransportService = (MockTransportService) transportService;
transportServices.add(mockTransportService);
mockTransportService.addRequestHandlingBehavior(IndicesStatsAction.NAME, (handler, request, channel, task) -> {
if (request instanceof IndicesStatsRequest) {
IndicesStatsRequest indicesStatsRequest = (IndicesStatsRequest) request;
if (request instanceof IndicesStatsRequest indicesStatsRequest) {
if (Arrays.equals(indicesStatsRequest.indices(), new String[] { leaderIndex })
&& indicesStatsRequest.store()
&& indicesStatsRequest.search() == false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,7 @@ private void sendShardChangesRequest(long from, int maxOperationCount, long maxR
fetchExceptions.put(from, Tuple.tuple(retryCounter, ExceptionsHelper.convertToElastic(e)));
}
Throwable cause = ExceptionsHelper.unwrapCause(e);
if (cause instanceof ResourceNotFoundException) {
ResourceNotFoundException resourceNotFoundException = (ResourceNotFoundException) cause;
if (cause instanceof ResourceNotFoundException resourceNotFoundException) {
if (resourceNotFoundException.getMetadataKeys().contains(Ccr.REQUESTED_OPS_MISSING_METADATA_KEY)) {
handleFallenBehindLeaderShard(e, from, maxOperationCount, maxRequiredSeqNo, retryCounter);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ protected void setupMasterNodeRequestsValidatorOnFollowerCluster() {
for (String nodeName : followerCluster.getNodeNames()) {
MockTransportService transportService = (MockTransportService) followerCluster.getInstance(TransportService.class, nodeName);
transportService.addSendBehavior((connection, requestId, action, request, options) -> {
if (isCcrAdminRequest(request) == false && request instanceof AcknowledgedRequest<?>) {
final TimeValue masterTimeout = ((AcknowledgedRequest<?>) request).masterNodeTimeout();
if (isCcrAdminRequest(request) == false && request instanceof AcknowledgedRequest<?> acknowledgedRequest) {
final TimeValue masterTimeout = acknowledgedRequest.masterNodeTimeout();
if (masterTimeout == null || masterTimeout.nanos() != TimeValue.MAX_VALUE.nanos()) {
throw new AssertionError("time out of a master request [" + request + "] on the follower is not set to unbounded");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,7 @@ private Engine.Result applyOperation(Engine engine, Engine.Operation op, long pr
throws IOException {
final VersionType versionType = origin == Engine.Operation.Origin.PRIMARY ? VersionType.EXTERNAL : null;
final Engine.Result result;
if (op instanceof Engine.Index) {
Engine.Index engineIndex = (Engine.Index) op;
if (op instanceof Engine.Index engineIndex) {
result = engine.index(
new Engine.Index(
engineIndex.uid(),
Expand All @@ -358,8 +357,7 @@ private Engine.Result applyOperation(Engine engine, Engine.Operation op, long pr
engineIndex.getIfPrimaryTerm()
)
);
} else if (op instanceof Engine.Delete) {
Engine.Delete delete = (Engine.Delete) op;
} else if (op instanceof Engine.Delete delete) {
result = engine.delete(
new Engine.Delete(
delete.id(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ void innerPerformAction(String followerIndex, ClusterState currentClusterState,
}
listener.onResponse(null);
}, exception -> {
if (exception instanceof ElasticsearchException
&& ((ElasticsearchException) exception).getMetadata("es.failed_to_remove_retention_leases") != null) {
List<String> leasesNotRemoved = ((ElasticsearchException) exception).getMetadata("es.failed_to_remove_retention_leases");
if (exception instanceof ElasticsearchException e && e.getMetadata("es.failed_to_remove_retention_leases") != null) {
List<String> leasesNotRemoved = e.getMetadata("es.failed_to_remove_retention_leases");
logger.debug(
"failed to remove leader retention lease(s) {} while unfollowing index [{}], " + "continuing with lifecycle execution",
leasesNotRemoved,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1097,8 +1097,7 @@ static void checkHistogramAggregationHasChildMaxTimeAgg(AggregationBuilder histo
}

for (AggregationBuilder agg : histogramAggregation.getSubAggregations()) {
if (agg instanceof MaxAggregationBuilder) {
MaxAggregationBuilder maxAgg = (MaxAggregationBuilder) agg;
if (agg instanceof MaxAggregationBuilder maxAgg) {
if (maxAgg.field().equals(timeField)) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,7 @@ protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOExc
}

private static void verifyNoOtherDocumentSubsetDirectoryReaderIsWrapped(DirectoryReader reader) {
if (reader instanceof FilterDirectoryReader) {
FilterDirectoryReader filterDirectoryReader = (FilterDirectoryReader) reader;
if (reader instanceof FilterDirectoryReader filterDirectoryReader) {
if (filterDirectoryReader instanceof DocumentSubsetDirectoryReader) {
throw new IllegalArgumentException(
LoggerMessageFormat.format("Can't wrap [{}] twice", DocumentSubsetDirectoryReader.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,7 @@ CharacterRunAutomaton getFilter() {
}

private static void verifyNoOtherFieldSubsetDirectoryReaderIsWrapped(DirectoryReader reader) {
if (reader instanceof FilterDirectoryReader) {
FilterDirectoryReader filterDirectoryReader = (FilterDirectoryReader) reader;
if (reader instanceof FilterDirectoryReader filterDirectoryReader) {
if (filterDirectoryReader instanceof FieldSubsetDirectoryReader) {
throw new IllegalArgumentException(
LoggerMessageFormat.format("Can't wrap [{}] twice", FieldSubsetDirectoryReader.class)
Expand Down Expand Up @@ -188,8 +187,7 @@ static Map<String, Object> filter(Map<String, ?> map, CharacterRunAutomaton incl
if (filteredValue.isEmpty() == false) {
filtered.put(key, filteredValue);
}
} else if (value instanceof Iterable) {
Iterable<?> iterableValue = (Iterable<?>) value;
} else if (value instanceof Iterable<?> iterableValue) {
List<Object> filteredValue = filter(iterableValue, includeAutomaton, state);
if (filteredValue.isEmpty() == false) {
filtered.put(key, filteredValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,11 @@ public static QueryBuilder evaluateAndVerifyRoleQuery(String query, NamedXConten
*/
// pkg protected for testing
static void verifyRoleQuery(QueryBuilder queryBuilder) {
if (queryBuilder instanceof TermsQueryBuilder) {
TermsQueryBuilder termsQueryBuilder = (TermsQueryBuilder) queryBuilder;
if (queryBuilder instanceof TermsQueryBuilder termsQueryBuilder) {
if (termsQueryBuilder.termsLookup() != null) {
throw new IllegalArgumentException("terms query with terms lookup isn't supported as part of a role query");
}
} else if (queryBuilder instanceof GeoShapeQueryBuilder) {
GeoShapeQueryBuilder geoShapeQueryBuilder = (GeoShapeQueryBuilder) queryBuilder;
} else if (queryBuilder instanceof GeoShapeQueryBuilder geoShapeQueryBuilder) {
if (geoShapeQueryBuilder.shape() == null) {
throw new IllegalArgumentException("geoshape query referring to indexed shapes isn't supported as part of a role query");
}
Expand All @@ -200,8 +198,7 @@ static void verifyRoleQuery(QueryBuilder queryBuilder) {
throw new IllegalArgumentException("has_child query isn't supported as part of a role query");
} else if (queryBuilder.getName().equals("has_parent")) {
throw new IllegalArgumentException("has_parent query isn't supported as part of a role query");
} else if (queryBuilder instanceof BoolQueryBuilder) {
BoolQueryBuilder boolQueryBuilder = (BoolQueryBuilder) queryBuilder;
} else if (queryBuilder instanceof BoolQueryBuilder boolQueryBuilder) {
List<QueryBuilder> clauses = new ArrayList<>();
clauses.addAll(boolQueryBuilder.filter());
clauses.addAll(boolQueryBuilder.must());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ protected TermsEnumResponse mergeResponses(
Object atomicResponse = atomicResponses.get(i);
if (atomicResponse == null) {
// simply ignore non active operations
} else if (atomicResponse instanceof NodeTermsEnumResponse) {
NodeTermsEnumResponse str = (NodeTermsEnumResponse) atomicResponse;
} else if (atomicResponse instanceof NodeTermsEnumResponse str) {
// Only one node response has to be incomplete for the entire result to be labelled incomplete.
if (str.isComplete() == false) {
complete = false;
Expand All @@ -247,8 +246,7 @@ protected TermsEnumResponse mergeResponses(
successfulShards += shards.size();
}
termsList.add(str.terms());
} else if (atomicResponse instanceof RemoteClusterTermsEnumResponse) {
RemoteClusterTermsEnumResponse rc = (RemoteClusterTermsEnumResponse) atomicResponse;
} else if (atomicResponse instanceof RemoteClusterTermsEnumResponse rc) {
// Only one node response has to be incomplete for the entire result to be labelled incomplete.
if (rc.resp.isComplete() == false || rc.resp.getFailedShards() > 0) {
complete = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,7 @@ public ActionWrapperResult execute(WatchExecutionContext ctx) {
List<Action.Result> results = new ArrayList<>();
Object object = ObjectPath.eval(path, toMap(ctx));
int runs = 0;
if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
if (object instanceof Collection<?> collection) {
if (collection.isEmpty()) {
throw new ElasticsearchException("foreach object [{}] was an empty list, could not run any action", path);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,7 @@ public MessageWatchRecord(WatchExecutionContext context, WatchExecutionResult ex

public MessageWatchRecord(WatchRecord record, ExecutionState state, String message) {
super(record, state);
if (record instanceof MessageWatchRecord) {
MessageWatchRecord messageWatchRecord = (MessageWatchRecord) record;
if (record instanceof MessageWatchRecord messageWatchRecord) {
if (messageWatchRecord.messages.length == 0) {
this.messages = new String[] { message };
} else {
Expand Down Expand Up @@ -344,8 +343,7 @@ public Exception getException() {
@Override
void innerToXContent(XContentBuilder builder, Params params) throws IOException {
if (exception != null) {
if (exception instanceof ElasticsearchException) {
ElasticsearchException elasticsearchException = (ElasticsearchException) exception;
if (exception instanceof ElasticsearchException elasticsearchException) {
builder.startObject(EXCEPTION.getPreferredName());
Params delegatingParams = new DelegatingMapParams(STACK_TRACE_ENABLED_PARAMS, params);
elasticsearchException.toXContent(builder, delegatingParams);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ public static Secret secretOrNull(XContentParser parser) throws IOException {
return new Secret(chars);
}

if (parser instanceof WatcherXContentParser) {
WatcherXContentParser watcherParser = (WatcherXContentParser) parser;
if (parser instanceof WatcherXContentParser watcherParser) {
if (REDACTED_PASSWORD.equals(text)) {
if (watcherParser.allowRedactedPasswords) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ public static Matcher<Path> pathExists(LinkOption... options) {
return new CustomMatcher<>("Path exists") {
@Override
public boolean matches(Object item) {
if (item instanceof Path) {
Path path = (Path) item;
if (item instanceof Path path) {
return Files.exists(path, options);
} else {
return false;
Expand Down Expand Up @@ -59,8 +58,7 @@ private abstract static class FileTypeMatcher extends CustomMatcher<Path> {

@Override
public boolean matches(Object item) {
if (item instanceof Path) {
Path path = (Path) item;
if (item instanceof Path path) {
return matchPath(path);
} else {
return false;
Expand All @@ -72,8 +70,7 @@ public boolean matches(Object item) {
@Override
public void describeMismatch(Object item, Description description) {
super.describeMismatch(item, description);
if (item instanceof Path) {
Path path = (Path) item;
if (item instanceof Path path) {
if (Files.exists(path, options) == false) {
description.appendText(" (file not found)");
} else if (Files.isDirectory(path, options)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public boolean matches(Object actual) {
@Override
public void describeMismatch(Object item, Description description) {
super.describeMismatch(item, description);
if (item instanceof Throwable) {
Throwable e = (Throwable) item;
if (item instanceof Throwable e) {
final StackTraceElement at = e.getStackTrace()[0];
description.appendText(" at ").appendText(at.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1719,8 +1719,7 @@ private static void verifyResolvability(
assertThat(e.getMessage(), equalTo(expectedErrorMessage));
}
} else {
if (requestBuilder instanceof SearchRequestBuilder) {
SearchRequestBuilder searchRequestBuilder = (SearchRequestBuilder) requestBuilder;
if (requestBuilder instanceof SearchRequestBuilder searchRequestBuilder) {
assertHitCount(searchRequestBuilder.get(), expectedCount);
} else if (requestBuilder instanceof MultiSearchRequestBuilder) {
MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get();
Expand Down

0 comments on commit 591b492

Please sign in to comment.