Skip to content

Commit

Permalink
Java 17 instanceof pattern matching for modules (#82341)
Browse files Browse the repository at this point in the history
Switch to Java 17 instanceof pattern matching for folders build-conventions through modules
  • Loading branch information
astefan committed Jan 10, 2022
1 parent 7b90d6f commit 35a79bc
Show file tree
Hide file tree
Showing 23 changed files with 68 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1209,8 +1209,7 @@ private void sync(Path sourceRoot, Path destinationRoot, BiConsumer<Path, Path>
}
});
} 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ public static void checkJarHell(Consumer<String> 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);
}
Expand Down
6 changes: 3 additions & 3 deletions libs/lz4/src/test/java/org/elasticsearch/lz4/ESLZ4Tests.java
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,10 @@ public <T> void testRoundTrip(SrcDestTester<T> 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();
}

Expand Down
4 changes: 2 additions & 2 deletions libs/nio/src/main/java/org/elasticsearch/nio/NioSelector.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ public Collection<StoredCertificate> getConfiguredCertificates() {
final List<StoredCertificate> 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;
}
Expand Down Expand Up @@ -105,8 +105,8 @@ public List<Tuple<PrivateKey, X509Certificate>> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down Expand Up @@ -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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ static final class ArrayMap extends AbstractMap<Object, Object> 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());
Expand Down Expand Up @@ -112,8 +112,8 @@ static final class CollectionMap extends AbstractMap<Object, Object> 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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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<String> captureNames = defInterfaceReferenceNode.getDecorationValueOrDefault(
IRDCaptureNames.class,
Collections.emptyList()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,27 +193,25 @@ 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);
} else if (s1 instanceof GeoCircle && s2 instanceof GeoCircle) {
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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('.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<QueryBuilder> clauses = new ArrayList<>();
clauses.addAll(boolQueryBuilder.filter());
clauses.addAll(boolQueryBuilder.must());
Expand All @@ -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);
}
Expand Down

0 comments on commit 35a79bc

Please sign in to comment.