Skip to content

Commit c018c2c

Browse files
authored
Switch to Java 17 instanceof pattern matching for folders test and x-pack/qa (#82683)
1 parent d332729 commit c018c2c

File tree

13 files changed

+33
-60
lines changed

13 files changed

+33
-60
lines changed

test/framework/src/main/java/org/elasticsearch/common/inject/ModuleTestCase.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,14 @@ private <T> void assertInstanceBindingWithAnnotation(
4141
) {
4242
List<Element> elements = Elements.getElements(module);
4343
for (Element element : elements) {
44-
if (element instanceof InstanceBinding) {
45-
InstanceBinding<?> binding = (InstanceBinding<?>) element;
44+
if (element instanceof InstanceBinding<?> binding) {
4645
if (to.equals(binding.getKey().getTypeLiteral().getType())) {
4746
if (annotation == null || annotation.equals(binding.getKey().getAnnotationType())) {
4847
assertTrue(tester.test(to.cast(binding.getInstance())));
4948
return;
5049
}
5150
}
52-
} else if (element instanceof ProviderInstanceBinding) {
53-
ProviderInstanceBinding<?> binding = (ProviderInstanceBinding<?>) element;
51+
} else if (element instanceof ProviderInstanceBinding<?> binding) {
5452
if (to.equals(binding.getKey().getTypeLiteral().getType())) {
5553
assertTrue(tester.test(to.cast(binding.getProviderInstance().get())));
5654
return;

test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java

+3-6
Original file line numberDiff line numberDiff line change
@@ -1082,8 +1082,7 @@ public static void assertOpsOnReplica(
10821082
) throws IOException {
10831083
final Engine.Operation lastOp = ops.get(ops.size() - 1);
10841084
final String lastFieldValue;
1085-
if (lastOp instanceof Engine.Index) {
1086-
Engine.Index index = (Engine.Index) lastOp;
1085+
if (lastOp instanceof Engine.Index index) {
10871086
lastFieldValue = index.docs().get(0).get("value");
10881087
} else {
10891088
// delete
@@ -1582,11 +1581,9 @@ private static LazySoftDeletesDirectoryReaderWrapper.LazyBits lazyBits(LeafReade
15821581
return ((LazySoftDeletesDirectoryReaderWrapper.LazySoftDeletesFilterLeafReader) reader).getLiveDocs();
15831582
} else if (reader instanceof LazySoftDeletesDirectoryReaderWrapper.LazySoftDeletesFilterCodecReader) {
15841583
return ((LazySoftDeletesDirectoryReaderWrapper.LazySoftDeletesFilterCodecReader) reader).getLiveDocs();
1585-
} else if (reader instanceof FilterLeafReader) {
1586-
final FilterLeafReader fReader = (FilterLeafReader) reader;
1584+
} else if (reader instanceof final FilterLeafReader fReader) {
15871585
return lazyBits(FilterLeafReader.unwrap(fReader));
1588-
} else if (reader instanceof FilterCodecReader) {
1589-
final FilterCodecReader fReader = (FilterCodecReader) reader;
1586+
} else if (reader instanceof final FilterCodecReader fReader) {
15901587
return lazyBits(FilterCodecReader.unwrap(fReader));
15911588
} else if (reader instanceof SegmentReader) {
15921589
return null;

test/framework/src/main/java/org/elasticsearch/ingest/IngestDocumentMatcher.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ && deepEquals(docA.getSourceAndMetadata(), docB.getSourceAndMetadata(), false))
2727
}
2828

2929
private static boolean deepEquals(Object a, Object b, boolean isIngestMeta) {
30-
if (a instanceof Map) {
31-
Map<?, ?> mapA = (Map<?, ?>) a;
30+
if (a instanceof Map<?, ?> mapA) {
3231
if (b instanceof Map == false) {
3332
return false;
3433
}
@@ -44,8 +43,7 @@ private static boolean deepEquals(Object a, Object b, boolean isIngestMeta) {
4443
}
4544
}
4645
return true;
47-
} else if (a instanceof List) {
48-
List<?> listA = (List<?>) a;
46+
} else if (a instanceof List<?> listA) {
4947
if (b instanceof List == false) {
5048
return false;
5149
}

test/framework/src/main/java/org/elasticsearch/search/aggregations/AggregatorTestCase.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -801,13 +801,11 @@ protected <T extends AggregationBuilder, V extends InternalAggregation> void ver
801801

802802
Set<String> valueNames = new HashSet<>();
803803

804-
if (agg instanceof NumericMetricsAggregation.MultiValue) {
805-
NumericMetricsAggregation.MultiValue multiValueAgg = (NumericMetricsAggregation.MultiValue) agg;
804+
if (agg instanceof NumericMetricsAggregation.MultiValue multiValueAgg) {
806805
for (String name : multiValueAgg.valueNames()) {
807806
valueNames.add(name);
808807
}
809-
} else if (agg instanceof MultiValueAggregation) {
810-
MultiValueAggregation multiValueAgg = (MultiValueAggregation) agg;
808+
} else if (agg instanceof MultiValueAggregation multiValueAgg) {
811809
for (String name : multiValueAgg.valueNames()) {
812810
valueNames.add(name);
813811
}

test/framework/src/main/java/org/elasticsearch/test/AbstractQueryTestCase.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -523,8 +523,7 @@ private void assertLuceneQuery(QB queryBuilder, Query query, SearchExecutionCont
523523
if (query != null) {
524524
if (queryBuilder.boost() != AbstractQueryBuilder.DEFAULT_BOOST) {
525525
assertThat(query, either(instanceOf(BoostQuery.class)).or(instanceOf(MatchNoDocsQuery.class)));
526-
if (query instanceof BoostQuery) {
527-
BoostQuery boostQuery = (BoostQuery) query;
526+
if (query instanceof BoostQuery boostQuery) {
528527
if (boostQuery.getQuery() instanceof MatchNoDocsQuery == false) {
529528
assertThat(boostQuery.getBoost(), equalTo(queryBuilder.boost()));
530529
}

test/framework/src/main/java/org/elasticsearch/test/AbstractSchemaValidationTestCase.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -133,14 +133,12 @@ private void assertSchemaStrictness(Collection<JsonValidator> validatorSet, Stri
133133
boolean subSchemaFound = false;
134134

135135
for (JsonValidator validator : validatorSet) {
136-
if (validator instanceof PropertiesValidator) {
136+
if (validator instanceof PropertiesValidator propertiesValidator) {
137137
subSchemaFound = true;
138-
PropertiesValidator propertiesValidator = (PropertiesValidator) validator;
139138
for (Entry<String, JsonSchema> subSchema : propertiesValidator.getSchemas().entrySet()) {
140139
assertSchemaStrictness(subSchema.getValue().getValidators().values(), propertiesValidator.getSchemaPath());
141140
}
142-
} else if (validator instanceof ItemsValidator) {
143-
ItemsValidator itemValidator = (ItemsValidator) validator;
141+
} else if (validator instanceof ItemsValidator itemValidator) {
144142
if (itemValidator.getSchema() != null) {
145143
assertSchemaStrictness(itemValidator.getSchema().getValidators().values(), itemValidator.getSchemaPath());
146144
}

test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -1080,8 +1080,7 @@ private synchronized void reset(boolean wipeData) throws IOException {
10801080
// clear all rules for mock transport services
10811081
for (NodeAndClient nodeAndClient : nodes.values()) {
10821082
TransportService transportService = nodeAndClient.node.injector().getInstance(TransportService.class);
1083-
if (transportService instanceof MockTransportService) {
1084-
final MockTransportService mockTransportService = (MockTransportService) transportService;
1083+
if (transportService instanceof final MockTransportService mockTransportService) {
10851084
mockTransportService.clearAllRules();
10861085
}
10871086
}

test/framework/src/main/java/org/elasticsearch/test/NotEqualMessageBuilder.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,7 @@ public void compare(String field, boolean hadKey, @Nullable Object actual, Objec
146146
return;
147147
}
148148
if (Objects.equals(expected, actual)) {
149-
if (expected instanceof String) {
150-
String expectedString = (String) expected;
149+
if (expected instanceof String expectedString) {
151150
if (expectedString.length() > 50) {
152151
expectedString = expectedString.substring(0, 50) + "...";
153152
}

test/framework/src/main/java/org/elasticsearch/test/rest/yaml/Stash.java

+2-4
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,7 @@ public Map<String, Object> replaceStashedValues(Map<String, Object> map) throws
122122
}
123123

124124
private Object unstashObject(List<Object> path, Object obj) throws IOException {
125-
if (obj instanceof List) {
126-
List<?> list = (List<?>) obj;
125+
if (obj instanceof List<?> list) {
127126
List<Object> result = new ArrayList<>();
128127
int index = 0;
129128
for (Object o : list) {
@@ -137,8 +136,7 @@ private Object unstashObject(List<Object> path, Object obj) throws IOException {
137136
}
138137
return result;
139138
}
140-
if (obj instanceof Map) {
141-
Map<?, ?> map = (Map<?, ?>) obj;
139+
if (obj instanceof Map<?, ?> map) {
142140
Map<String, Object> result = new HashMap<>();
143141
for (Map.Entry<?, ?> entry : map.entrySet()) {
144142
String key = (String) entry.getKey();

test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/CloseToAssertion.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ public final double getError() {
6868
@Override
6969
protected void doAssert(Object actualValue, Object expectedValue) {
7070
logger.trace("assert that [{}] is close to [{}] with error [{}] (field [{}])", actualValue, expectedValue, error, getField());
71-
if (actualValue instanceof Number) {
72-
assertThat(((Number) actualValue).doubleValue(), closeTo((Double) expectedValue, error));
71+
if (actualValue instanceof Number actualValueNumber) {
72+
assertThat(actualValueNumber.doubleValue(), closeTo((Double) expectedValue, error));
7373
} else {
7474
throw new AssertionError("excpected a value close to " + expectedValue + " but got " + actualValue + ", which is not a number");
7575
}

test/logger-usage/src/main/java/org/elasticsearch/test/loggerusage/ESLoggerUsageChecker.java

+11-20
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,7 @@ public void findBadLoggerUsages(MethodNode methodNode) {
250250
int lineNumber = -1;
251251
for (int i = 0; i < insns.length; i++) {
252252
AbstractInsnNode insn = insns[i];
253-
if (insn instanceof LineNumberNode) {
254-
LineNumberNode lineNumberNode = (LineNumberNode) insn;
253+
if (insn instanceof LineNumberNode lineNumberNode) {
255254
lineNumber = lineNumberNode.line;
256255
}
257256
if (insn.getOpcode() == Opcodes.INVOKEINTERFACE) {
@@ -506,8 +505,7 @@ private int getChainedParams(AbstractInsnNode startNode) {
506505
AbstractInsnNode current = startNode;
507506
while (current.getNext() != null) {
508507
current = current.getNext();
509-
if (current instanceof MethodInsnNode) {
510-
MethodInsnNode method = (MethodInsnNode) current;
508+
if (current instanceof MethodInsnNode method) {
511509
if (method.name.equals("argAndField")) {
512510
c++;
513511
}
@@ -656,20 +654,18 @@ private static final class PlaceHolderStringInterpreter extends BasicInterpreter
656654
public BasicValue newOperation(AbstractInsnNode insnNode) throws AnalyzerException {
657655
if (insnNode.getOpcode() == Opcodes.LDC) {
658656
Object constant = ((LdcInsnNode) insnNode).cst;
659-
if (constant instanceof String) {
660-
return new PlaceHolderStringBasicValue(calculateNumberOfPlaceHolders((String) constant));
657+
if (constant instanceof String s) {
658+
return new PlaceHolderStringBasicValue(calculateNumberOfPlaceHolders(s));
661659
}
662660
}
663661
return super.newOperation(insnNode);
664662
}
665663

666664
@Override
667665
public BasicValue merge(BasicValue value1, BasicValue value2) {
668-
if (value1 instanceof PlaceHolderStringBasicValue
669-
&& value2 instanceof PlaceHolderStringBasicValue
666+
if (value1 instanceof PlaceHolderStringBasicValue c1
667+
&& value2 instanceof PlaceHolderStringBasicValue c2
670668
&& value1.equals(value2) == false) {
671-
PlaceHolderStringBasicValue c1 = (PlaceHolderStringBasicValue) value1;
672-
PlaceHolderStringBasicValue c2 = (PlaceHolderStringBasicValue) value2;
673669
return new PlaceHolderStringBasicValue(Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
674670
}
675671
return super.merge(value1, value2);
@@ -702,8 +698,8 @@ public BasicValue newOperation(AbstractInsnNode insnNode) throws AnalyzerExcepti
702698
return new IntegerConstantBasicValue(Type.INT_TYPE, ((IntInsnNode) insnNode).operand);
703699
case Opcodes.LDC: {
704700
Object constant = ((LdcInsnNode) insnNode).cst;
705-
if (constant instanceof Integer) {
706-
return new IntegerConstantBasicValue(Type.INT_TYPE, (Integer) constant);
701+
if (constant instanceof Integer integer) {
702+
return new IntegerConstantBasicValue(Type.INT_TYPE, integer);
707703
} else {
708704
return super.newOperation(insnNode);
709705
}
@@ -715,22 +711,17 @@ public BasicValue newOperation(AbstractInsnNode insnNode) throws AnalyzerExcepti
715711

716712
@Override
717713
public BasicValue merge(BasicValue value1, BasicValue value2) {
718-
if (value1 instanceof IntegerConstantBasicValue && value2 instanceof IntegerConstantBasicValue) {
719-
IntegerConstantBasicValue c1 = (IntegerConstantBasicValue) value1;
720-
IntegerConstantBasicValue c2 = (IntegerConstantBasicValue) value2;
714+
if (value1 instanceof IntegerConstantBasicValue c1 && value2 instanceof IntegerConstantBasicValue c2) {
721715
return new IntegerConstantBasicValue(Type.INT_TYPE, Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
722-
} else if (value1 instanceof ArraySizeBasicValue && value2 instanceof ArraySizeBasicValue) {
723-
ArraySizeBasicValue c1 = (ArraySizeBasicValue) value1;
724-
ArraySizeBasicValue c2 = (ArraySizeBasicValue) value2;
716+
} else if (value1 instanceof ArraySizeBasicValue c1 && value2 instanceof ArraySizeBasicValue c2) {
725717
return new ArraySizeBasicValue(Type.INT_TYPE, Math.min(c1.minValue, c2.minValue), Math.max(c1.maxValue, c2.maxValue));
726718
}
727719
return super.merge(value1, value2);
728720
}
729721

730722
@Override
731723
public BasicValue unaryOperation(AbstractInsnNode insnNode, BasicValue value) throws AnalyzerException {
732-
if (insnNode.getOpcode() == Opcodes.ANEWARRAY && value instanceof IntegerConstantBasicValue) {
733-
IntegerConstantBasicValue constantBasicValue = (IntegerConstantBasicValue) value;
724+
if (insnNode.getOpcode() == Opcodes.ANEWARRAY && value instanceof IntegerConstantBasicValue constantBasicValue) {
734725
String desc = ((TypeInsnNode) insnNode).desc;
735726
return new ArraySizeBasicValue(
736727
Type.getType("[" + Type.getObjectType(desc)),

x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoClient.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -247,8 +247,7 @@ static class KrbCallbackHandler implements CallbackHandler {
247247

248248
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
249249
for (Callback callback : callbacks) {
250-
if (callback instanceof PasswordCallback) {
251-
PasswordCallback pc = (PasswordCallback) callback;
250+
if (callback instanceof PasswordCallback pc) {
252251
if (pc.getPrompt().contains(principal)) {
253252
pc.setPassword(password.getChars());
254253
break;

x-pack/qa/kerberos-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SpnegoHttpClientConfigCallbackHandler.java

+3-4
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,8 @@ static <T> T doAsPrivilegedWrapper(final Subject subject, final PrivilegedExcept
206206
try {
207207
return AccessController.doPrivileged((PrivilegedExceptionAction<T>) () -> Subject.doAsPrivileged(subject, action, acc));
208208
} catch (PrivilegedActionException pae) {
209-
if (pae.getCause() instanceof PrivilegedActionException) {
210-
throw (PrivilegedActionException) pae.getCause();
209+
if (pae.getCause()instanceof PrivilegedActionException privilegedActionException) {
210+
throw privilegedActionException;
211211
}
212212
throw pae;
213213
}
@@ -258,8 +258,7 @@ private static class KrbCallbackHandler implements CallbackHandler {
258258

259259
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {
260260
for (Callback callback : callbacks) {
261-
if (callback instanceof PasswordCallback) {
262-
PasswordCallback pc = (PasswordCallback) callback;
261+
if (callback instanceof PasswordCallback pc) {
263262
if (pc.getPrompt().contains(principal)) {
264263
pc.setPassword(password.getChars());
265264
break;

0 commit comments

Comments
 (0)