Skip to content

Commit

Permalink
Pattern matching for instanceof. Wrapping up (elastic#82768)
Browse files Browse the repository at this point in the history
  • Loading branch information
astefan committed Jan 20, 2022
1 parent 73379f0 commit b84a5e2
Show file tree
Hide file tree
Showing 14 changed files with 23 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ protected void processTasks(final FollowStatsAction.StatsRequest request, final
final Set<String> followerIndices = findFollowerIndicesFromShardFollowTasks(state, request.indices());

for (final Task task : taskManager.getTasks().values()) {
if (task instanceof ShardFollowNodeTask) {
final ShardFollowNodeTask shardFollowNodeTask = (ShardFollowNodeTask) task;
if (task instanceof final ShardFollowNodeTask shardFollowNodeTask) {
if (followerIndices.contains(shardFollowNodeTask.getFollowShardId().getIndexName())) {
operation.accept(shardFollowNodeTask);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ public FieldValue(Object value) {
}

private static CharacterRunAutomaton buildAutomaton(Object value) {
if (value instanceof String) {
final String str = (String) value;
if (value instanceof final String str) {
if (Regex.isSimpleMatchPattern(str) || Automatons.isLuceneRegex(str)) {
return new CharacterRunAutomaton(Automatons.patterns(str));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,7 @@ protected boolean extendedCheck(String action, TransportRequest request, Authent

@Override
protected boolean doImplies(final ActionBasedPermissionCheck permissionCheck) {
if (permissionCheck instanceof ActionRequestBasedPermissionCheck) {
final ActionRequestBasedPermissionCheck otherCheck = (ActionRequestBasedPermissionCheck) permissionCheck;
if (permissionCheck instanceof final ActionRequestBasedPermissionCheck otherCheck) {
return this.clusterPrivilege.equals(otherCheck.clusterPrivilege);
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@ public ManageApplicationPrivileges(Set<String> applicationNames) {
this.applicationNames = Collections.unmodifiableSet(applicationNames);
this.applicationPredicate = StringMatcher.of(applicationNames);
this.requestPredicate = request -> {
if (request instanceof ApplicationPrivilegesRequest) {
final ApplicationPrivilegesRequest privRequest = (ApplicationPrivilegesRequest) request;
if (request instanceof final ApplicationPrivilegesRequest privRequest) {
final Collection<String> requestApplicationNames = privRequest.getApplicationNames();
return requestApplicationNames.isEmpty()
? this.applicationNames.contains("*")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,15 @@ private ManageOwnClusterPermissionCheck() {
protected boolean extendedCheck(String action, TransportRequest request, Authentication authentication) {
if (request instanceof CreateApiKeyRequest) {
return true;
} else if (request instanceof GetApiKeyRequest) {
final GetApiKeyRequest getApiKeyRequest = (GetApiKeyRequest) request;
} else if (request instanceof final GetApiKeyRequest getApiKeyRequest) {
return checkIfUserIsOwnerOfApiKeys(
authentication,
getApiKeyRequest.getApiKeyId(),
getApiKeyRequest.getUserName(),
getApiKeyRequest.getRealmName(),
getApiKeyRequest.ownedByAuthenticatedUser()
);
} else if (request instanceof InvalidateApiKeyRequest) {
final InvalidateApiKeyRequest invalidateApiKeyRequest = (InvalidateApiKeyRequest) request;
} else if (request instanceof final InvalidateApiKeyRequest invalidateApiKeyRequest) {
final String[] apiKeyIds = invalidateApiKeyRequest.getIds();
if (apiKeyIds == null) {
return checkIfUserIsOwnerOfApiKeys(
Expand All @@ -92,8 +90,7 @@ protected boolean extendedCheck(String action, TransportRequest request, Authent
)
);
}
} else if (request instanceof QueryApiKeyRequest) {
final QueryApiKeyRequest queryApiKeyRequest = (QueryApiKeyRequest) request;
} else if (request instanceof final QueryApiKeyRequest queryApiKeyRequest) {
return queryApiKeyRequest.isFilterForCurrentUser();
}
throw new IllegalArgumentException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ public void describeTo(Description description) {

@Override
public boolean matches(Object actual) {
if (actual instanceof Throwable) {
final Throwable throwable = (Throwable) actual;
if (actual instanceof final Throwable throwable) {
return messageMatcher.matches(throwable.getMessage());
} else {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1275,8 +1275,7 @@ public void onFailure(Exception e) {
*/
private <E extends Throwable> E traceLog(String action, String identifier, E exception) {
if (logger.isTraceEnabled()) {
if (exception instanceof ElasticsearchException) {
final ElasticsearchException esEx = (ElasticsearchException) exception;
if (exception instanceof final ElasticsearchException esEx) {
final Object detail = esEx.getHeader("error_description");
if (detail != null) {
logger.trace(() -> new ParameterizedMessage("Failure in [{}] for id [{}] - [{}]", action, identifier, detail), esEx);
Expand All @@ -1295,8 +1294,7 @@ private <E extends Throwable> E traceLog(String action, String identifier, E exc
*/
private <E extends Throwable> E traceLog(String action, E exception) {
if (logger.isTraceEnabled()) {
if (exception instanceof ElasticsearchException) {
final ElasticsearchException esEx = (ElasticsearchException) exception;
if (exception instanceof final ElasticsearchException esEx) {
final Object detail = esEx.getHeader("error_description");
if (detail != null) {
logger.trace(() -> new ParameterizedMessage("Failure in [{}] - [{}]", action, detail), esEx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,8 @@ private BiConsumer<Authenticator, ActionListener<AuthenticationResult<Authentica
// Because (1) unlike security errors which are intentionally obscure, non-security errors are clear
// about their nature so that no additional information is needed; (2) Non-security errors may
// not inherit ElasticsearchException and thus does not have the addMetadata method.
if (e instanceof ElasticsearchSecurityException) {
if (e instanceof final ElasticsearchSecurityException ese) {
// Attach any other unsuccessful messages to the final error
final ElasticsearchSecurityException ese = (ElasticsearchSecurityException) e;
if (false == context.getUnsuccessfulMessages().isEmpty()) {
addMetadata(context, ese);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2192,8 +2192,7 @@ private static ElasticsearchSecurityException unableToPerformAction(@Nullable Th
*/
private <E extends Throwable> E traceLog(String action, String identifier, E exception) {
if (logger.isTraceEnabled()) {
if (exception instanceof ElasticsearchException) {
final ElasticsearchException esEx = (ElasticsearchException) exception;
if (exception instanceof final ElasticsearchException esEx) {
final Object detail = esEx.getHeader("error_description");
if (detail != null) {
logger.trace(() -> new ParameterizedMessage("Failure in [{}] for id [{}] - [{}]", action, identifier, detail), esEx);
Expand All @@ -2212,8 +2211,7 @@ private <E extends Throwable> E traceLog(String action, String identifier, E exc
*/
private <E extends Throwable> E traceLog(String action, E exception) {
if (logger.isTraceEnabled()) {
if (exception instanceof ElasticsearchException) {
final ElasticsearchException esEx = (ElasticsearchException) exception;
if (exception instanceof final ElasticsearchException esEx) {
final Object detail = esEx.getHeader("error_description");
if (detail != null) {
logger.trace(() -> new ParameterizedMessage("Failure in [{}] - [{}]", action, detail), esEx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,7 @@ ResolvedIndices resolveIndicesAndAliases(
assert indicesRequest.indices() == null || indicesRequest.indices().length == 0
: "indices are: " + Arrays.toString(indicesRequest.indices()); // Arrays.toString() can handle null values - all good
resolvedIndicesBuilder.addLocal(getPutMappingIndexOrAlias((PutMappingRequest) indicesRequest, authorizedIndices, metadata));
} else if (indicesRequest instanceof IndicesRequest.Replaceable) {
final IndicesRequest.Replaceable replaceable = (IndicesRequest.Replaceable) indicesRequest;
} else if (indicesRequest instanceof final IndicesRequest.Replaceable replaceable) {
final IndicesOptions indicesOptions = indicesRequest.indicesOptions();
final boolean replaceWildcards = indicesOptions.expandWildcardsOpen() || indicesOptions.expandWildcardsClosed();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ public static ApiKeyBoolQueryBuilder build(QueryBuilder queryBuilder, @Nullable
}

private static QueryBuilder doProcess(QueryBuilder qb) {
if (qb instanceof BoolQueryBuilder) {
final BoolQueryBuilder query = (BoolQueryBuilder) qb;
if (qb instanceof final BoolQueryBuilder query) {
final BoolQueryBuilder newQuery = QueryBuilders.boolQuery()
.minimumShouldMatch(query.minimumShouldMatch())
.adjustPureNegative(query.adjustPureNegative());
Expand All @@ -87,29 +86,24 @@ private static QueryBuilder doProcess(QueryBuilder qb) {
return qb;
} else if (qb instanceof IdsQueryBuilder) {
return qb;
} else if (qb instanceof TermQueryBuilder) {
final TermQueryBuilder query = (TermQueryBuilder) qb;
} else if (qb instanceof final TermQueryBuilder query) {
final String translatedFieldName = ApiKeyFieldNameTranslators.translate(query.fieldName());
return QueryBuilders.termQuery(translatedFieldName, query.value()).caseInsensitive(query.caseInsensitive());
} else if (qb instanceof TermsQueryBuilder) {
final TermsQueryBuilder query = (TermsQueryBuilder) qb;
} else if (qb instanceof final TermsQueryBuilder query) {
if (query.termsLookup() != null) {
throw new IllegalArgumentException("terms query with terms lookup is not supported for API Key query");
}
final String translatedFieldName = ApiKeyFieldNameTranslators.translate(query.fieldName());
return QueryBuilders.termsQuery(translatedFieldName, query.getValues());
} else if (qb instanceof PrefixQueryBuilder) {
final PrefixQueryBuilder query = (PrefixQueryBuilder) qb;
} else if (qb instanceof final PrefixQueryBuilder query) {
final String translatedFieldName = ApiKeyFieldNameTranslators.translate(query.fieldName());
return QueryBuilders.prefixQuery(translatedFieldName, query.value()).caseInsensitive(query.caseInsensitive());
} else if (qb instanceof WildcardQueryBuilder) {
final WildcardQueryBuilder query = (WildcardQueryBuilder) qb;
} else if (qb instanceof final WildcardQueryBuilder query) {
final String translatedFieldName = ApiKeyFieldNameTranslators.translate(query.fieldName());
return QueryBuilders.wildcardQuery(translatedFieldName, query.value())
.caseInsensitive(query.caseInsensitive())
.rewrite(query.rewrite());
} else if (qb instanceof RangeQueryBuilder) {
final RangeQueryBuilder query = (RangeQueryBuilder) qb;
} else if (qb instanceof final RangeQueryBuilder query) {
final String translatedFieldName = ApiKeyFieldNameTranslators.translate(query.fieldName());
if (query.relation() != null) {
throw new IllegalArgumentException("range query with relation is not supported for API Key query");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,8 +282,7 @@ private MockSecureSettings normaliseSecureSettingPrefix(String prefix, SecureSet
if (settings == null) {
return null;
}
if (settings instanceof MockSecureSettings) {
final MockSecureSettings source = (MockSecureSettings) settings;
if (settings instanceof final MockSecureSettings source) {
final MockSecureSettings target = new MockSecureSettings();
for (String key : settings.getSettingNames()) {
target.setString(prefix + key, source.getString(key).toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,7 @@ public void testFindTokensForException() {
public void testDeleteToken() {
final AtomicBoolean cacheCleared = new AtomicBoolean(false);
responseProviderHolder.set((r, l) -> {
if (r instanceof DeleteRequest) {
final DeleteRequest dr = (DeleteRequest) r;
if (r instanceof final DeleteRequest dr) {
final boolean found = dr.id().equals(SERVICE_ACCOUNT_TOKEN_DOC_TYPE + "-elastic/fleet-server/token1");
l.onResponse(
new DeleteResponse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,7 @@ public static Tuple<Map<String, String>, Map<String, String>> getAggregationInpu
);
}

if (agg instanceof ValuesSourceAggregationBuilder) {
ValuesSourceAggregationBuilder<?> valueSourceAggregation = (ValuesSourceAggregationBuilder<?>) agg;
if (agg instanceof ValuesSourceAggregationBuilder<?> valueSourceAggregation) {
return new Tuple<>(
Collections.singletonMap(valueSourceAggregation.getName(), valueSourceAggregation.field()),
Collections.singletonMap(valueSourceAggregation.getName(), valueSourceAggregation.getType())
Expand Down

0 comments on commit b84a5e2

Please sign in to comment.