Skip to content

Commit

Permalink
Use pattern matching for instanceof in plugins through qa, server/int…
Browse files Browse the repository at this point in the history
…ernalClusterTest (#82161)
  • Loading branch information
gmarouli committed Jan 12, 2022
1 parent 11fe6d4 commit 4499050
Show file tree
Hide file tree
Showing 24 changed files with 61 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ private InputStream openInputStream(String blobName, long position, @Nullable Lo
return blobStore.getInputStream(blobKey, position, length);
} catch (Exception e) {
Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof BlobStorageException) {
if (((BlobStorageException) rootCause).getStatusCode() == 404) {
if (rootCause instanceof BlobStorageException blobStorageException) {
if (blobStorageException.getStatusCode() == 404) {
throw new NoSuchFileException("Blob [" + blobKey + "] not found");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ private static Mono<Void> getDeleteTask(String blobName, BlobAsyncClient blobAsy
// Ignore not found blobs, as it's possible that due to network errors a request
// for an already deleted blob is retried, causing an error.
.onErrorResume(
e -> e instanceof BlobStorageException && ((BlobStorageException) e).getStatusCode() == 404,
e -> e instanceof BlobStorageException blobStorageException && blobStorageException.getStatusCode() == 404,
throwable -> Mono.empty()
)
.onErrorMap(throwable -> new IOException("Error deleting blob " + blobName, throwable));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ static <T> T getSetting(Setting<T> 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 string && Strings.hasText(string) == false) {
throw new RepositoryException(metadata.name(), "Setting [" + setting.getKey() + "] is empty for repository");
}
return value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ public static void doPrivilegedVoidIOException(CheckedRunnable<IOException> acti

private static IOException causeAsIOException(PrivilegedActionException e) {
final Throwable cause = e.getCause();
if (cause instanceof IOException) {
return (IOException) cause;
if (cause instanceof IOException ioException) {
return ioException;
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
if (cause instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new RuntimeException(cause);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ private void openStream() throws IOException {
this.currentStreamLastOffset = Math.addExact(Math.addExact(start, currentOffset), getStreamLength(s3Object));
this.currentStream = s3Object.getObjectContent();
} catch (final AmazonClientException e) {
if (e instanceof AmazonS3Exception) {
if (404 == ((AmazonS3Exception) e).getStatusCode()) {
if (e instanceof AmazonS3Exception amazonS3Exception) {
if (404 == amazonS3Exception.getStatusCode()) {
throw addSuppressedExceptions(new NoSuchFileException("Blob object [" + blobKey + "] not found: " + e.getMessage()));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,8 +477,7 @@ public String toString() {
@Override
public void close() throws IOException {
super.close();
if (in instanceof S3RetryingInputStream) {
final S3RetryingInputStream s3Stream = (S3RetryingInputStream) in;
if (in instanceof final S3RetryingInputStream s3Stream) {
assertTrue(
"Stream "
+ toString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ protected BytesRef indexedValueForSearch(Object value) {
if (value == null) {
return null;
}
if (value instanceof BytesRef) {
value = ((BytesRef) value).utf8ToString();
if (value instanceof BytesRef bytesRef) {
value = bytesRef.utf8ToString();
}

if (collator != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ public List<TransportAddress> getSeedAddresses(HostsResolver hostsResolver) {
if (instance.getMetadata() != null && instance.getMetadata().containsKey("es_port")) {
Object es_port = instance.getMetadata().get("es_port");
logger.trace("es_port is defined with {}", es_port);
if (es_port instanceof String) {
address = address.concat(":").concat((String) es_port);
if (es_port instanceof String string) {
address = address.concat(":").concat(string);
} else {
// Ignoring other values
logger.trace("es_port is instance of {}. Ignoring...", es_port.getClass().getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,10 @@ public TopDocs rescore(TopDocs topDocs, IndexSearcher searcher, RescoreContext r
endDoc = leaf.docBase + leaf.reader().maxDoc();
} while (topDocs.scoreDocs[i].doc >= endDoc);
LeafFieldData fd = context.factorField.load(leaf);
if (false == (fd instanceof LeafNumericFieldData)) {
if (false == (fd instanceof LeafNumericFieldData leafNumericFieldData)) {
throw new IllegalArgumentException("[" + context.factorField.getFieldName() + "] is not a number");
}
data = ((LeafNumericFieldData) fd).getDoubleValues();
data = leafNumericFieldData.getDoubleValues();
}
if (false == data.advanceExact(topDocs.scoreDocs[i].doc - leaf.docBase)) {
throw new IllegalArgumentException("document [" + topDocs.scoreDocs[i].doc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,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 tikaException) {
throw tikaException;
} else if (cause instanceof IOException ioException) {
throw ioException;
} else {
throw new AssertionError(cause);
}
Expand All @@ -131,8 +131,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<URL> set = new LinkedHashSet<>(Arrays.asList(urls));
if (set.size() != urls.length) {
throw new AssertionError("duplicate jars: " + Arrays.toString(urls));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,8 @@ public boolean isAutoFailoverEnabled() {

private void close() {
for (HAServiceProtocol protocol : protocolsToClose) {
if (protocol instanceof HAServiceProtocolClientSideTranslatorPB) {
((HAServiceProtocolClientSideTranslatorPB) protocol).close();
if (protocol instanceof HAServiceProtocolClientSideTranslatorPB haServiceProtocolClientSideTranslatorPB) {
haServiceProtocolClientSideTranslatorPB.close();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,20 +203,20 @@ public ChannelPromise unvoid() {
}

public static NettyListener fromBiConsumer(BiConsumer<Void, Exception> biConsumer, Channel channel) {
if (biConsumer instanceof NettyListener) {
return (NettyListener) biConsumer;
if (biConsumer instanceof NettyListener nettyListener) {
return nettyListener;
} else {
ChannelPromise channelPromise = channel.newPromise();
channelPromise.addListener(f -> {
Throwable cause = f.cause();
if (cause == null) {
biConsumer.accept(null, null);
} else {
if (cause instanceof Error) {
if (cause instanceof Exception exception) {
biConsumer.accept(null, exception);
} else {
ExceptionsHelper.maybeDieOnAnotherThread(cause);
biConsumer.accept(null, new Exception(cause));
} else {
biConsumer.accept(null, (Exception) cause);
}
}
});
Expand All @@ -226,8 +226,8 @@ public static NettyListener fromBiConsumer(BiConsumer<Void, Exception> biConsume
}

public static NettyListener fromChannelPromise(ChannelPromise channelPromise) {
if (channelPromise instanceof NettyListener) {
return (NettyListener) channelPromise;
if (channelPromise instanceof NettyListener nettyListener) {
return nettyListener;
} else {
return new NettyListener(channelPromise);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public boolean isEmpty() {

@Override
public boolean containsKey(Object key) {
return key instanceof String && httpHeaders.contains((String) key);
return key instanceof String string && httpHeaders.contains(string);
}

@Override
Expand All @@ -264,7 +264,7 @@ public boolean containsValue(Object value) {

@Override
public List<String> get(Object key) {
return key instanceof String ? httpHeaders.getAll((String) key) : null;
return key instanceof String string ? httpHeaders.getAll(string) : null;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Objec
if (msg.decoderResult().isFailure()) {
final Throwable cause = msg.decoderResult().cause();
final Exception nonError;
if (cause instanceof Error) {
if (cause instanceof Exception exception) {
nonError = exception;
} else {
ExceptionsHelper.maybeDieOnAnotherThread(cause);
nonError = new Exception(cause);
} else {
nonError = (Exception) cause;
}
out.add(new NioHttpRequest(msg.retain(), nonError));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ protected void doRun() {
runExecutionTest(runner, runnable, willThrow, o -> {
assertEquals(willThrow, o.isPresent());
if (willThrow) {
if (o.get() instanceof Error) throw (Error) o.get();
if (o.get()instanceof Error error) throw error;
assertThat(o.get(), instanceOf(IllegalStateException.class));
assertThat(o.get(), hasToString(containsString("future exception")));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -840,8 +840,7 @@ private static void assertAggs(SearchResponse response) {
assertNotNull(response.getAggregations());
List<Aggregation> aggregations = response.getAggregations().asList();
for (Aggregation aggregation : aggregations) {
if (aggregation instanceof MultiBucketsAggregation) {
MultiBucketsAggregation multiBucketsAggregation = (MultiBucketsAggregation) aggregation;
if (aggregation instanceof MultiBucketsAggregation multiBucketsAggregation) {
assertThat(
"agg " + multiBucketsAggregation.getName() + " has 0 buckets",
multiBucketsAggregation.getBuckets().size(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ void runTest(Request request, String actionPrefix) throws Exception {
for (final IndexService indexService : indicesService) {
for (final IndexShard indexShard : indexService) {
final Engine engine = IndexShardTestCase.getEngine(indexShard);
if (engine instanceof SearcherBlockingEngine) {
searcherBlocks.add(((SearcherBlockingEngine) engine).searcherBlock);
if (engine instanceof SearcherBlockingEngine searcherBlockingEngine) {
searcherBlocks.add(searcherBlockingEngine.searcherBlock);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ public void testClusterStateRestCancellation() throws Exception {
for (final IndexService indexService : indicesService) {
for (final IndexShard indexShard : indexService) {
final Engine engine = IndexShardTestCase.getEngine(indexShard);
if (engine instanceof StatsBlockingEngine) {
statsBlocks.add(((StatsBlockingEngine) engine).statsBlock);
if (engine instanceof StatsBlockingEngine statsBlockingEngine) {
statsBlocks.add(statsBlockingEngine.statsBlock);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -650,13 +650,7 @@ private static void assertIndicesSubset(List<String> indices, boolean optional,
}

static IndicesRequest convertRequest(TransportRequest request) {
final IndicesRequest indicesRequest;
if (request instanceof IndicesRequest) {
indicesRequest = (IndicesRequest) request;
} else {
indicesRequest = TransportReplicationActionTests.resolveRequest(request);
}
return indicesRequest;
return request instanceof IndicesRequest indicesRequest ? indicesRequest : TransportReplicationActionTests.resolveRequest(request);
}

private String randomIndexOrAlias() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ public void testAckedIndexing() throws Exception {
}
// in case of a bridge partition, shard allocation can fail "index.allocation.max_retries" times if the master
// is the super-connected node and recovery source and target are on opposite sides of the bridge
if (disruptionScheme instanceof NetworkDisruption
&& ((NetworkDisruption) disruptionScheme).getDisruptedLinks() instanceof Bridge) {
if (disruptionScheme instanceof NetworkDisruption networkDisruption
&& networkDisruption.getDisruptedLinks() instanceof Bridge) {
assertBusy(() -> assertAcked(client().admin().cluster().prepareReroute().setRetryFailed(true)));
}
ensureGreen("test");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -700,8 +700,8 @@ private static void verify(ActionRequestBuilder<?, ?> requestBuilder, boolean fa

private static void verify(ActionRequestBuilder<?, ?> requestBuilder, boolean fail, long expectedCount) {
if (fail) {
if (requestBuilder instanceof MultiSearchRequestBuilder) {
MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get();
if (requestBuilder instanceof MultiSearchRequestBuilder multiSearchRequestBuilder) {
MultiSearchResponse multiSearchResponse = multiSearchRequestBuilder.get();
assertThat(multiSearchResponse.getResponses().length, equalTo(1));
assertThat(multiSearchResponse.getResponses()[0].isFailure(), is(true));
assertThat(multiSearchResponse.getResponses()[0].getResponse(), nullValue());
Expand All @@ -714,8 +714,8 @@ private static void verify(ActionRequestBuilder<?, ?> requestBuilder, boolean fa
} else {
if (requestBuilder instanceof SearchRequestBuilder searchRequestBuilder) {
assertHitCount(searchRequestBuilder.get(), expectedCount);
} else if (requestBuilder instanceof MultiSearchRequestBuilder) {
MultiSearchResponse multiSearchResponse = ((MultiSearchRequestBuilder) requestBuilder).get();
} else if (requestBuilder instanceof MultiSearchRequestBuilder multiSearchRequestBuilder) {
MultiSearchResponse multiSearchResponse = multiSearchRequestBuilder.get();
assertThat(multiSearchResponse.getResponses().length, equalTo(1));
assertThat(multiSearchResponse.getResponses()[0].getResponse(), notNullValue());
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ private Releasable interceptVerifyShardBeforeCloseActions(final String indexPatt
internalCluster().getInstance(TransportService.class, node.getName()),
(connection, requestId, action, request, options) -> {
if (action.startsWith(TransportVerifyShardBeforeCloseAction.NAME)) {
if (request instanceof TransportVerifyShardBeforeCloseAction.ShardRequest) {
final String index = ((TransportVerifyShardBeforeCloseAction.ShardRequest) request).shardId().getIndexName();
if (request instanceof TransportVerifyShardBeforeCloseAction.ShardRequest shardRequest) {
final String index = shardRequest.shardId().getIndexName();
if (Glob.globMatch(indexPattern, index)) {
logger.info("request {} intercepted for index {}", requestId, index);
onIntercept.run();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,14 +397,13 @@ private List<Object> convertSortValues(List<Object> sortValues) {
List<Object> converted = new ArrayList<>();
for (int i = 0; i < sortValues.size(); i++) {
Object from = sortValues.get(i);
if (from instanceof Integer) {
converted.add(((Integer) from).longValue());
} else if (from instanceof Short) {
converted.add(((Short) from).longValue());
} else if (from instanceof Byte) {
converted.add(((Byte) from).longValue());
} else if (from instanceof Boolean) {
boolean b = (boolean) from;
if (from instanceof Integer integer) {
converted.add(integer.longValue());
} else if (from instanceof Short s) {
converted.add(s.longValue());
} else if (from instanceof Byte b) {
converted.add(b.longValue());
} else if (from instanceof Boolean b) {
if (b) {
converted.add(1L);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -481,9 +481,9 @@ public Object initialState() {
@Override
public Optional<Object> nextState(Object currentState, Object input, Object output) {
State state = (State) currentState;
if (output instanceof IndexResponseHistoryOutput) {
if (output instanceof IndexResponseHistoryOutput indexResponseHistoryOutput) {
if (input.equals(state.safeVersion) || (state.lastFailed && ((Version) input).compareTo(state.safeVersion) > 0)) {
return Optional.of(casSuccess(((IndexResponseHistoryOutput) output).getVersion()));
return Optional.of(casSuccess(indexResponseHistoryOutput.getVersion()));
} else {
return Optional.empty();
}
Expand Down

0 comments on commit 4499050

Please sign in to comment.