Skip to content

Apache Lucene open-source search software

errorprone-improvements (#14216)

Kevin Risdenb0ebaaed5650
diff --git a/gradle/validation/error-prone.gradle b/gradle/validation/error-prone.gradle
index 6972129d16d..90a98b594c2 100644
--- a/gradle/validation/error-prone.gradle
+++ b/gradle/validation/error-prone.gradle
@@ -65,6 +65,50 @@ allprojects { prj ->
return
}
+ // Exclude certain files (generated ones, mostly).
+ switch (project.path) {
+ case ":lucene:core":
+ options.errorprone.excludedPaths.set(".*/StandardTokenizerImpl.java")
+ break
+
+ case ":lucene:analysis:common":
+ options.errorprone.excludedPaths.set("" +
+ ".*/HTMLStripCharFilter.java|" +
+ ".*/UAX29URLEmailTokenizerImpl.java")
+ break
+
+ case ":lucene:test-framework":
+ options.errorprone.excludedPaths.set("" +
+ ".*/EmojiTokenizationTestUnicode_11_0.java|" +
+ ".*/WordBreakTestUnicode_9_0_0.java")
+ break
+
+ case ":lucene:expressions":
+ break
+
+ case ":lucene:queryparser":
+ options.errorprone.excludedPaths.set("" +
+ ".*/classic/ParseException.java|" +
+ ".*/classic/QueryParser.java|" +
+ ".*/classic/QueryParserConstants.java|" +
+ ".*/classic/QueryParserTokenManager.java|" +
+ ".*/classic/Token.java|" +
+ ".*/classic/TokenMgrError.java|" +
+ ".*/standard/parser/ParseException.java|" +
+ ".*/standard/parser/StandardSyntaxParser.java|" +
+ ".*/standard/parser/StandardSyntaxParserConstants.java|" +
+ ".*/standard/parser/StandardSyntaxParserTokenManager.java|" +
+ ".*/standard/parser/Token.java|" +
+ ".*/standard/parser/TokenMgrError.java|" +
+ ".*/surround/parser/ParseException.java|" +
+ ".*/surround/parser/QueryParser.java|" +
+ ".*/surround/parser/QueryParserConstants.java|" +
+ ".*/surround/parser/QueryParserTokenManager.java|" +
+ ".*/surround/parser/Token.java|" +
+ ".*/surround/parser/TokenMgrError.java")
+ break
+ }
+
task.dependsOn ":checkJdkInternalsExportedToGradle"
options.errorprone.disableWarningsInGeneratedCode = true
@@ -92,6 +136,7 @@ allprojects { prj ->
// '-Xep:AutoValueConstructorOrderChecker:OFF', // we don't use autovalue
'-Xep:BadAnnotationImplementation:ERROR',
'-Xep:BadShiftAmount:ERROR',
+ '-Xep:BanClassLoader:ERROR',
// '-Xep:BanJNDI:OFF', // implemented with forbidden APIs instead
'-Xep:BoxedPrimitiveEquality:ERROR',
// '-Xep:BundleDeserializationCast:OFF', // we don't use android
@@ -111,10 +156,12 @@ allprojects { prj ->
'-Xep:DangerousLiteralNull:ERROR',
'-Xep:DeadException:ERROR',
'-Xep:DeadThread:ERROR',
+ '-Xep:DereferenceWithNullBranch:ERROR',
'-Xep:DiscardedPostfixExpression:ERROR',
// '-Xep:DoNotCall:OFF', // we don't use this annotation
// '-Xep:DoNotMock:OFF', // we don't use mocking libraries
// '-Xep:DoubleBraceInitialization:OFF', // we don't use guava
+ '-Xep:DuplicateBranches:ERROR',
'-Xep:DuplicateMapKeys:ERROR',
// '-Xep:DurationFrom:OFF', // we don't use Duration.from()
// '-Xep:DurationGetTemporalUnit:OFF', // we don't use Duration.get()
@@ -183,6 +230,8 @@ allprojects { prj ->
'-Xep:LossyPrimitiveCompare:ERROR',
'-Xep:MathRoundIntLong:ERROR',
// '-Xep:MislabeledAndroidString:OFF', // we don't use android
+ '-Xep:MisleadingEscapedSpace:ERROR',
+ // '-Xep:MissingRuntimeRetention:OFF', // we don't use this annotation
// '-Xep:MisplacedScopeAnnotations:OFF', // we don't use this annotation
// '-Xep:MissingSuperCall:OFF', // we don't use this annotation
// '-Xep:MissingTestCall:OFF', // we don't use guava
@@ -226,9 +275,11 @@ allprojects { prj ->
// '-Xep:RequiredModifiers:OFF', // we don't use this annotation
// '-Xep:RestrictedApiChecker:OFF', // we don't use this annotation
// '-Xep:ReturnValueIgnored:OFF', // noisy
+ '-Xep:SelfAssertion:ERROR',
'-Xep:SelfAssignment:ERROR',
'-Xep:SelfComparison:ERROR',
'-Xep:SelfEquals:ERROR',
+ // '-Xep:SetUnrecognized:OFF', // we don't use protobuf
// '-Xep:ShouldHaveEvenArgs:OFF', // we don't use truth
'-Xep:SizeGreaterThanOrEqualsZero:ERROR',
'-Xep:StreamToString:ERROR',
@@ -241,7 +292,6 @@ allprojects { prj ->
// '-Xep:ThrowIfUncheckedKnownChecked:OFF', // we don't use this annotation
// '-Xep:ThrowNull:OFF', // noisy (LuceneTestCase)
// '-Xep:TreeToString:OFF', // we don't use javac API
- // '-Xep:TruthSelfEquals:OFF', // we don't use truth
// '-Xep:TryFailThrowable:OFF',
'-Xep:TypeParameterQualifier:ERROR',
'-Xep:UnicodeDirectionalityCharacters:ERROR',
@@ -265,10 +315,13 @@ allprojects { prj ->
// '-Xep:AnnotateFormatMethod:OFF', // we don't use this annotation
// '-Xep:ArgumentSelectionDefectChecker:OFF', // noisy
// '-Xep:ArrayAsKeyOfSetOrMap:OFF', // TODO: there are problems
+ // '-Xep:ArrayRecordComponent:OFF', // TODO: there are problems
'-Xep:AssertEqualsArgumentOrderChecker:WARN',
'-Xep:AssertThrowsMultipleStatements:WARN',
// '-Xep:AssertionFailureIgnored:OFF', // TODO: there are problems
// '-Xep:AssistedInjectAndInjectOnSameConstructor:OFF', // we don't use this annotation
+ '-Xep:AttemptedNegativeZero:WARN',
+ // '-Xep:AutoValueBoxedValues:OFF', // we don't use autovalue
// '-Xep:AutoValueFinalMethods:OFF', // we don't use autovalue
// '-Xep:AutoValueImmutableFields:OFF', // we don't use autovalue
// '-Xep:AutoValueSubclassLeaked:OFF', // we don't use autovalue
@@ -288,8 +341,10 @@ allprojects { prj ->
// '-Xep:ChainedAssertionLosesContext:OFF', // we don't use truth
// '-Xep:CharacterGetNumericValue:OFF', // noisy
// '-Xep:ClassCanBeStatic:OFF', // noisy
+ // '-Xep:ClassInitializationDeadlock:OFF', // TODO: there are problems
'-Xep:ClassNewInstance:WARN',
// '-Xep:CloseableProvides:OFF', // we don't use this annotation
+ '-Xep:ClosingStandardOutputStreams:WARN',
// '-Xep:CollectionUndefinedEquality:OFF', // TODO: there are problems
'-Xep:CollectorShouldNotUseState:WARN',
'-Xep:ComparableAndComparator:WARN',
@@ -298,17 +353,21 @@ allprojects { prj ->
// '-Xep:DateChecker:OFF', // we don't use these Date setters/ctors
// '-Xep:DateFormatConstant:OFF', // we don't use Date setters
// '-Xep:DefaultCharset:OFF', // we have forbiddenapis for that
+ // '-Xep:DefaultLocale:OFF', // we have forbiddenapis for that
// '-Xep:DefaultPackage:OFF',
'-Xep:DeprecatedVariable:WARN',
+ '-Xep:DeeplyNested:WARN',
// '-Xep:DirectInvocationOnMock:OFF', // we don't use mocking libraries
// '-Xep:DistinctVarargsChecker:OFF', // we don't use google collections
// '-Xep:DoNotCallSuggester:OFF', // we don't use this annotation
// '-Xep:DoNotClaimAnnotations:OFF', // we don't use annotation processors
// '-Xep:DoNotMockAutoValue:OFF', // we don't use autovalue
// '-Xep:DoubleCheckedLocking:OFF', // TODO: there are problems
+ '-Xep:DuplicateDateFormatField:WARN',
'-Xep:EmptyBlockTag:WARN',
// '-Xep:EmptyCatch:OFF', // ECJ takes care
// '-Xep:EmptySetMultibindingContributions:OFF', // we don't use this annotation
+ // '-Xep:EnumOrdinal:OFF', // noisy
// '-Xep:EqualsGetClass:OFF', // noisy
// '-Xep:EqualsIncompatibleType:OFF',
// '-Xep:EqualsUnsafeCast:OFF', // noisy
@@ -329,8 +388,11 @@ allprojects { prj ->
// '-Xep:FragmentInjection:OFF', // we don't use android
// '-Xep:FragmentNotInstantiable:OFF', // we don't use android
// '-Xep:FutureReturnValueIgnored:OFF', // TODO: there are problems
+ // '-Xep:FutureTransformAsync:OFF', // we don't use these google libraries
'-Xep:GetClassOnEnum:WARN',
+ // '-Xep:GuiceNestedCombine:OFF', // we don't use guice
// '-Xep:HidingField:OFF', // noisy
+ '-Xep:ICCProfileGetInstance:WARN',
// '-Xep:IdentityHashMapUsage:OFF', // noisy
// '-Xep:ImmutableAnnotationChecker:OFF', // we don't use this annotation
// '-Xep:ImmutableEnumChecker:OFF', // noisy
@@ -348,6 +410,7 @@ allprojects { prj ->
// '-Xep:InlineFormatString:OFF', // noisy
// '-Xep:InlineMeInliner:OFF', // we don't use this annotation
// '-Xep:InlineMeSuggester:OFF', // we don't use this annotation
+ // '-Xep:InlineTrivialConstant:OFF', // stylistic
// '-Xep:InputStreamSlowMultibyteRead:OFF',
'-Xep:InstanceOfAndCastMatchWrongType:WARN',
// '-Xep:IntLongMath:OFF', // noisy
@@ -362,6 +425,7 @@ allprojects { prj ->
// '-Xep:JUnit4ClassUsedInJUnit3:OFF', // we don't use junit3
// '-Xep:JUnitAmbiguousTestClass:OFF', // we don't use junit3
// '-Xep:JavaDurationGetSecondsGetNano:OFF', // we don't use these Duration methods
+ // '-Xep:JavaDurationGetSecondsToToSeconds:OFF', // we don't use these Duration methods
// '-Xep:JavaDurationWithNanos:OFF', // we don't use these Duration methods
// '-Xep:JavaDurationWithSeconds:OFF', // we don't use these Duration methods
// '-Xep:JavaInstantGetSecondsGetNano:OFF', // we don't use these Instant methods
@@ -381,10 +445,12 @@ allprojects { prj ->
// '-Xep:JodaPlusMinusLong:OFF', // we don't use joda-time
// '-Xep:JodaTimeConverterManager:OFF', // we don't use joda-time
// '-Xep:JodaWithDurationAddedLong:OFF', // we don't use joda-time
+ '-Xep:JUnitIncompatibleType:WARN',
// '-Xep:LabelledBreakTarget:OFF', // stylistic
// '-Xep:LiteEnumValueOf:OFF', // we don't use protobuf
// '-Xep:LiteProtoToString:OFF', // we don't use protobuf
// '-Xep:LockNotBeforeTry:OFF', // TODO: there are problems
+ // '-Xep:LockOnNonEnclosingClassLiteral:OFF', // TODO: there are problems
'-Xep:LogicalAssignment:WARN',
'-Xep:LongDoubleConversion:WARN',
'-Xep:LongFloatConversion:WARN',
@@ -392,32 +458,45 @@ allprojects { prj ->
'-Xep:MalformedInlineTag:WARN',
// '-Xep:MathAbsoluteNegative:OFF', // TODO: there are problems
// '-Xep:MemoizeConstantVisitorStateLookups:OFF', // we don't use this class
+ // '-Xep:MisformattedTestData:OFF', // stylistic
// '-Xep:MissingCasesInEnumSwitch:OFF', // redundant with ECJ incompleteEnumSwitch/missingEnumCaseDespiteDefault
// '-Xep:MissingFail:OFF', // TODO: there are problems
'-Xep:MissingImplementsComparable:WARN',
// '-Xep:MissingOverride:OFF', // ECJ takes care of this
+ // '-Xep:MissingRefasterAnnotation:OFF', // we don't use this annotation
// '-Xep:MissingSummary:OFF', // TODO: there are problems
// '-Xep:MixedMutabilityReturnType:OFF', // noisy
+ // '-Xep:MockitoDoSetup:OFF', // we don't use mocking libraries
// '-Xep:MockNotUsedInProduction:OFF', // we don't use mocking libraries
// '-Xep:ModifiedButNotUsed:OFF', // TODO: there are problems
'-Xep:ModifyCollectionInEnhancedForLoop:WARN',
'-Xep:ModifySourceCollectionInStream:WARN',
+ '-Xep:MultimapKeys:WARN',
+ // '-Xep:MultipleNullnessAnnotations:OFF', // we don't use these annotations
'-Xep:MultipleParallelOrSequentialCalls:WARN',
'-Xep:MultipleUnaryOperatorsInMethodCall:WARN',
+ // '-Xep:MutableGuiceModule:OFF', // we don't use guice
// '-Xep:MutablePublicArray:OFF', // TODO: there are problems
+ '-Xep:NamedLikeContextualKeyword:WARN',
'-Xep:NarrowCalculation:WARN',
// '-Xep:NarrowingCompoundAssignment:OFF', // noisy
'-Xep:NegativeCharLiteral:WARN',
'-Xep:NestedInstanceOfConditions:WARN',
// '-Xep:NewFileSystem:OFF', // we don't create new filesystems
+ // '-Xep:NonApiType:OFF', // noisy
// '-Xep:NonAtomicVolatileUpdate:OFF', // TODO: there are problems
// '-Xep:NonCanonicalType:OFF', // noisy
+ // '-Xep:NonFinalStaticField:OFF', // noisy
'-Xep:NonOverridingEquals:WARN',
+ '-Xep:NotJavadoc:WARN',
'-Xep:NullOptional:WARN',
// '-Xep:NullableConstructor:OFF', // we don't use this annotation
+ '-Xep:NullableOptional:WARN',
// '-Xep:NullablePrimitive:OFF', // we don't use this annotation
// '-Xep:NullablePrimitiveArray:OFF', // we don't use this annotation
+ // '-Xep:NullableTypeParameter:OFF', // we don't use this annotation
// '-Xep:NullableVoid:OFF', // we don't use this annotation
+ // '-Xep:NullableWildcard:OFF', // we don't use this annotation
'-Xep:ObjectEqualsForPrimitives:WARN',
// '-Xep:ObjectToString:OFF', // TODO: there are problems
// '-Xep:ObjectsHashCodePrimitive:OFF', // TODO: there are problems
@@ -429,6 +508,8 @@ allprojects { prj ->
'-Xep:OverrideThrowableToString:WARN',
'-Xep:Overrides:WARN',
// '-Xep:OverridesGuiceInjectableMethod:OFF', // we don't use guice
+ '-Xep:OverridingMethodInconsistentArgumentNamesChecker:WARN',
+ '-Xep:PatternMatchingInstanceof:WARN',
// '-Xep:ParameterName:OFF', // we don't pass parameters with comments in this way
// '-Xep:PreconditionsCheckNotNullRepeated:OFF', // we don't use guava
'-Xep:PrimitiveAtomicReference:WARN',
@@ -438,31 +519,43 @@ allprojects { prj ->
// '-Xep:ProtoTimestampGetSecondsGetNano:OFF', // we don't use protobuf
// '-Xep:QualifierOrScopeOnInjectMethod:OFF', // we don't use this annotation
'-Xep:ReachabilityFenceUsage:WARN',
+ // '-Xep:RedundantControlFlow:OFF', // stylistic
+ // '-Xep:RedundantSetterCall:OFF', // we don't use protobuf
// '-Xep:ReferenceEquality:OFF', // noisy
'-Xep:RethrowReflectiveOperationExceptionAsLinkageError:WARN',
+ // '-Xep:ReturnAtTheEndOfVoidFunction:OFF', // stylistic
'-Xep:ReturnFromVoid:WARN',
// '-Xep:RobolectricShadowDirectlyOn:OFF', // we don't use robolectric
// '-Xep:RxReturnValueIgnored:OFF', // we don't use rxjava
// '-Xep:SameNameButDifferent:OFF', // TODO: there are problems
// '-Xep:SelfAlwaysReturnsThis:OFF', // we don't use self() methods, this isn't python.
// '-Xep:ShortCircuitBoolean:OFF', // TODO: there are problems
+ '-Xep:StatementSwitchToExpressionSwitch:WARN',
// '-Xep:StaticAssignmentInConstructor:OFF',
// '-Xep:StaticAssignmentOfThrowable:OFF', // noisy
// '-Xep:StaticGuardedByInstance:OFF',
// '-Xep:StaticMockMember:OFF', // we don't use mock libraries
// '-Xep:StreamResourceLeak:OFF', // TODO: there are problems
'-Xep:StreamToIterable:WARN',
+ // '-Xep:StringCaseLocaleUsage:OFF', // noisy, can use forbidden-apis for this
+ '-Xep:StringCharset:WARN',
+ '-Xep:StringFormatWithLiteral:WARN',
// '-Xep:StringSplitter:OFF', // noisy, can use forbidden-apis for this
+ '-Xep:SystemConsoleNull:WARN',
+ '-Xep:SunApi:WARN',
+ '-Xep:SuperCallToObjectMethod:WARN',
// '-Xep:SwigMemoryLeak:OFF', // we don't use swig
// '-Xep:SynchronizeOnNonFinalField:OFF', // noisy
// '-Xep:ThreadJoinLoop:OFF',
// '-Xep:ThreadLocalUsage:OFF', // noisy
// '-Xep:ThreadPriorityCheck:OFF', // noisy, forbidden APIs can do this
+ // '-Xep:ThrowIfUncheckedKnownUnchecked:OFF', // we don't use these google libraries
'-Xep:ThreeLetterTimeZoneID:WARN',
'-Xep:TimeUnitConversionChecker:WARN',
// '-Xep:ToStringReturnsNull:OFF', // TODO: there are problems
// '-Xep:TruthAssertExpected:OFF', // we don't use truth
// '-Xep:TruthConstantAsserts:OFF', // we don't use truth
+ // '-Xep:TruthContainsExactlyElementsInUsage:OFF', // we don't use truth
// '-Xep:TruthGetOrDefault:OFF', // we don't use truth
// '-Xep:TruthIncompatibleType:OFF', // we don't use truth
// '-Xep:TypeEquals:OFF', // we don't use this internal javac api
@@ -473,12 +566,16 @@ allprojects { prj ->
// '-Xep:UndefinedEquals:OFF', // TODO: there are problems
// '-Xep:UnescapedEntity:OFF', // TODO: there are problems
// '-Xep:UnicodeEscape:OFF', // noisy
+ '-Xep:UnnecessaryAsync:WARN',
// '-Xep:UnnecessaryAssignment:OFF', // we don't use these annotations
+ '-Xep:UnnecessaryBreakInSwitch:WARN',
// '-Xep:UnnecessaryLambda:OFF', // TODO: there are problems
// '-Xep:UnnecessaryLongToIntConversion:OFF', // TODO: there are problems
// '-Xep:UnnecessaryMethodInvocationMatcher:OFF', // we don't use spring
'-Xep:UnnecessaryMethodReference:WARN',
// '-Xep:UnnecessaryParentheses:OFF', // noisy
+ '-Xep:UnnecessaryStringBuilder:WARN',
+ // '-Xep:UnnecessaryTestMethodPrefix:OFF', // stylistic
// '-Xep:UnqualifiedYield:OFF', // javac takes care
'-Xep:UnrecognisedJavadocTag:WARN',
// '-Xep:UnsafeFinalization:OFF', // we don't use finalizers, deprecated for removal, fails build
@@ -492,6 +589,7 @@ allprojects { prj ->
// '-Xep:UseBinds:OFF', // we don't use this annotation
// '-Xep:UseCorrectAssertInTests:OFF', // noisy
'-Xep:VariableNameSameAsType:WARN',
+ '-Xep:VoidUsed:WARN',
// '-Xep:WaitNotInLoop:OFF', // TODO: there are problems
// '-Xep:WakelockReleasedDangerously:OFF', // we don't use android
// '-Xep:WithSignatureDiscouraged:OFF', // we aren't using this error-prone internal api
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/HyphenationTree.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/HyphenationTree.java
index 4b38fb5d3bc..49a12f365ef 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/HyphenationTree.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/HyphenationTree.java
@@ -225,7 +225,7 @@ public class HyphenationTree extends TernaryTree implements PatternConsumer {
} else {
q = lo[q];
- /**
+ /*
* actually the code should be: q = sc[q] < 0 ? hi[q] : lo[q]; but java chars are
* unsigned
*/
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/PatternParser.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/PatternParser.java
index 7f176cccb30..6e9e6c73fb2 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/PatternParser.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/compound/hyphenation/PatternParser.java
@@ -172,8 +172,7 @@ public class PatternParser extends DefaultHandler {
ArrayList<Object> res = new ArrayList<>();
for (int i = 0; i < ex.size(); i++) {
Object item = ex.get(i);
- if (item instanceof String) {
- String str = (String) item;
+ if (item instanceof String str) {
StringBuilder buf = new StringBuilder();
for (int j = 0; j < str.length(); j++) {
char c = str.charAt(j);
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/KStemmer.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/KStemmer.java
index c571a3635b5..c1e1b5d8e2d 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/KStemmer.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/en/KStemmer.java
@@ -822,12 +822,12 @@ class KStemmer {
}
private DictEntry wordInDict() {
- /***
+ /*
* if (matchedEntry != null) { if (dict_ht.get(word.getArray(), 0,
* word.size()) != matchedEntry) {
* System.out.println("Uh oh... cached entry doesn't match"); } return
* matchedEntry; }
- ***/
+ */
if (matchedEntry != null) return matchedEntry;
DictEntry e = dict_ht.get(word.getArray(), 0, word.length());
if (e != null && !e.exception) {
@@ -861,11 +861,11 @@ class KStemmer {
* common
*/
- /****
+ /*
* YCS: this was the one place where lookup was not followed by return.
* So restructure it. if ((j>0)&&(lookup(word.toString())) &&
* !((word.charAt(j) == 's') && (word.charAt(j-1) == 's'))) return;
- *****/
+ */
boolean tryE = j > 0 && !((word.charAt(j) == 's') && (word.charAt(j - 1) == 's'));
if (tryE && lookup()) return;
@@ -913,7 +913,7 @@ class KStemmer {
DictEntry matchedEntry = null;
private boolean lookup() {
- /******
+ /*
* debugging code String thisLookup = word.toString(); boolean added =
* lookups.add(thisLookup); if (!added) {
* System.out.println("######extra lookup:" + thisLookup); // occaasional
@@ -921,7 +921,7 @@ class KStemmer {
* manipulations // throw new RuntimeException("######extra lookup:" +
* thisLookup); } else { // System.out.println("new lookup:" + thisLookup);
* }
- ******/
+ */
matchedEntry = dict_ht.get(word.getArray(), 0, word.size());
return matchedEntry != null;
@@ -1742,11 +1742,11 @@ class KStemmer {
String result;
private boolean matched() {
- /***
+ /*
* if (!lookups.contains(word.toString())) { throw new
* RuntimeException("didn't look up "+word.toString()+" prev="+prevLookup);
* }
- ***/
+ */
// lookup();
return matchedEntry != null;
}
@@ -1772,13 +1772,13 @@ class KStemmer {
return false;
}
- /***
+ /*
* caching off is normally faster if (cache == null) initializeStemHash();
*
* // now check the cache, before we copy chars to "word" if (cache != null)
* { String val = cache.get(term, 0, len); if (val != null) { if (val !=
* SAME) { result = val; return true; } return false; } }
- ***/
+ */
word.reset();
// allocate enough space so that an expansion is never needed
@@ -1792,9 +1792,9 @@ class KStemmer {
}
matchedEntry = null;
- /***
+ /*
* lookups.clear(); lookups.add(word.toString());
- ***/
+ */
/*
* This while loop will never be executed more than one time; it is here
@@ -1851,20 +1851,20 @@ class KStemmer {
result = entry.root; // may be null, which means that "word" is the stem
}
- /***
+ /*
* caching off is normally faster if (cache != null && cache.size() <
* maxCacheSize) { char[] key = new char[len]; System.arraycopy(term, 0,
* key, 0, len); if (result != null) { cache.put(key, result); } else {
* cache.put(key, word.toString()); } }
- ***/
+ */
- /***
+ /*
* if (entry == null) { if (!word.toString().equals(new String(term,0,len)))
* { System.out.println("CASE:" + word.toString() + "," + new
* String(term,0,len));
*
* } }
- ***/
+ */
// no entry matched means result is "word"
return true;
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/minhash/MinHashFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/minhash/MinHashFilter.java
index 706b87cf80d..28858944bfe 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/minhash/MinHashFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/minhash/MinHashFilter.java
@@ -18,6 +18,7 @@
package org.apache.lucene.analysis.minhash;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
@@ -160,7 +161,7 @@ public class MinHashFilter extends TokenFilter {
String current = new String(termAttribute.buffer(), 0, termAttribute.length());
for (int i = 0; i < hashCount; i++) {
- byte[] bytes = current.getBytes("UTF-16LE");
+ byte[] bytes = current.getBytes(StandardCharsets.UTF_16LE);
LongPair hash = new LongPair();
murmurhash3_x64_128(bytes, 0, bytes.length, 0, hash);
LongPair rehashed = combineOrdered(hash, getIntHash(i));
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestFlattenGraphFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestFlattenGraphFilter.java
index 28748f4f4b4..93209fb62e6 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestFlattenGraphFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestFlattenGraphFilter.java
@@ -816,7 +816,7 @@ public class TestFlattenGraphFilter extends BaseTokenStreamTestCase {
return accept;
}
- /**
+ /*
* This method checks if strings that lead to the accept state of the not flattened TokenStream
* also lead to the accept state in the flattened TokenStream. This gets complicated when you
* factor in holes. The FlattenGraphFilter will remove alternate paths that are made entirely of
@@ -840,7 +840,7 @@ public class TestFlattenGraphFilter extends BaseTokenStreamTestCase {
notFlattened.close();
}*/
- /**
+ /*
* gets up to 10000 strings that lead to accept state in the given automaton.
*
* @param automaton automaton
@@ -856,7 +856,7 @@ public class TestFlattenGraphFilter extends BaseTokenStreamTestCase {
return acceptedSequences;
}*/
- /**
+ /*
* @param automaton automaton to generate strings from
* @param state state to start at
* @param prefix string prefix
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/minhash/TestMinHashFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/minhash/TestMinHashFilter.java
index e6b9525a5e7..b6e5d4b8c86 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/minhash/TestMinHashFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/minhash/TestMinHashFilter.java
@@ -19,7 +19,7 @@ package org.apache.lucene.analysis.minhash;
import java.io.IOException;
import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -47,16 +47,16 @@ public class TestMinHashFilter extends BaseTokenStreamTestCase {
}
@Test
- public void testStringHash() throws UnsupportedEncodingException {
+ public void testStringHash() {
LongPair hash = new LongPair();
- byte[] bytes = "woof woof woof woof woof".getBytes("UTF-16LE");
+ byte[] bytes = "woof woof woof woof woof".getBytes(StandardCharsets.UTF_16LE);
MinHashFilter.murmurhash3_x64_128(bytes, 0, bytes.length, 0, hash);
assertEquals(7638079586852243959L, hash.val1);
assertEquals(4378804943379391304L, hash.val2);
}
@Test
- public void testSimpleOrder() throws UnsupportedEncodingException {
+ public void testSimpleOrder() {
LongPair hash1 = new LongPair();
hash1.val1 = 1;
hash1.val2 = 2;
diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/ViterbiNBest.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/ViterbiNBest.java
index 207feabe6b7..03f24ff421f 100644
--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/ViterbiNBest.java
+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/ViterbiNBest.java
@@ -179,7 +179,7 @@ final class ViterbiNBest extends org.apache.lucene.analysis.morph.ViterbiNBest<T
protected void backtrace(Position endPosData, int fromIDX) throws IOException {
final int endPos = endPosData.getPos();
- /**
+ /*
* LUCENE-10059: If the endPos is the same as lastBackTracePos, we don't want to backtrace to
* avoid an assertion error {@link RollingCharBuffer#get(int)} when it tries to generate an
* empty buffer
diff --git a/lucene/analysis/opennlp/src/java/org/apache/lucene/analysis/opennlp/OpenNLPSentenceBreakIterator.java b/lucene/analysis/opennlp/src/java/org/apache/lucene/analysis/opennlp/OpenNLPSentenceBreakIterator.java
index d81b06fd90d..af1ada421db 100644
--- a/lucene/analysis/opennlp/src/java/org/apache/lucene/analysis/opennlp/OpenNLPSentenceBreakIterator.java
+++ b/lucene/analysis/opennlp/src/java/org/apache/lucene/analysis/opennlp/OpenNLPSentenceBreakIterator.java
@@ -206,8 +206,7 @@ public final class OpenNLPSentenceBreakIterator extends BreakIterator {
private String characterIteratorToString() {
String fullText;
- if (text instanceof CharArrayIterator) {
- CharArrayIterator charArrayIterator = (CharArrayIterator) text;
+ if (text instanceof CharArrayIterator charArrayIterator) {
fullText =
new String(
charArrayIterator.getText(),
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/Lucene60PointsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/Lucene60PointsWriter.java
index ca148491753..62f227c699e 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/Lucene60PointsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/Lucene60PointsWriter.java
@@ -146,7 +146,7 @@ public class Lucene60PointsWriter extends PointsWriter {
@Override
public void merge(MergeState mergeState) throws IOException {
- /**
+ /*
* If indexSort is activated and some of the leaves are not sorted the next test will catch that
* and the non-optimized merge will run. If the readers are all sorted then it's safe to perform
* a bulk merge of the points.
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/bkd/BKDWriter60.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/bkd/BKDWriter60.java
index a1e304a3149..14da2cbd62e 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/bkd/BKDWriter60.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene60/bkd/BKDWriter60.java
@@ -1074,7 +1074,7 @@ public class BKDWriter60 implements Closeable {
}
}
- /** Reused while packing the index */
+ /* Reused while packing the index */
ByteBuffersDataOutput writeBuffer = new ByteBuffersDataOutput();
// This is the "file" we append the byte[] to:
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene86/Lucene86PointsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene86/Lucene86PointsWriter.java
index 94714111be1..d0bcc935811 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene86/Lucene86PointsWriter.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_codecs/lucene86/Lucene86PointsWriter.java
@@ -183,7 +183,7 @@ public class Lucene86PointsWriter extends PointsWriter {
@Override
public void merge(MergeState mergeState) throws IOException {
- /**
+ /*
* If indexSort is activated and some of the leaves are not sorted the next test will catch that
* and the non-optimized merge will run. If the readers are all sorted then it's safe to perform
* a bulk merge of the points.
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/ExpressionsBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/ExpressionsBenchmark.java
index 5badbc9f1aa..1e4bb87a76c 100644
--- a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/ExpressionsBenchmark.java
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/ExpressionsBenchmark.java
@@ -70,7 +70,7 @@ public class ExpressionsBenchmark {
m.put("mh_identity", MethodHandles.identity(double.class));
return Collections.unmodifiableMap(m);
} catch (ReflectiveOperationException e) {
- throw new AssertionError(e);
+ throw new LinkageError("Couldn't find function", e);
}
}
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SpatialDocMaker.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SpatialDocMaker.java
index 5bd00a5d865..488dad09356 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SpatialDocMaker.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/feeds/SpatialDocMaker.java
@@ -172,8 +172,7 @@ public class SpatialDocMaker extends DocMaker {
return new ShapeConverter() {
@Override
public Shape convert(Shape shape) {
- if (shape instanceof Point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
- Point point = (Point) shape;
+ if (shape instanceof Point point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
double radius = radiusDegrees;
if (plusMinus > 0.0) {
Random random =
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java
index 52e8cdfcb7c..48bb60508ea 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/PerfTask.java
@@ -163,7 +163,7 @@ public abstract class PerfTask implements Cloneable {
if (params == null) {
return name;
}
- return new StringBuilder(name).append('(').append(params).append(')').toString();
+ return name + '(' + params + ')';
}
/**
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java
index 282cd72279a..a01399baccd 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/TaskSequence.java
@@ -291,8 +291,7 @@ public class TaskSequence extends PerfTask {
if (task instanceof ResetInputsTask) {
exhausted = false;
resetExhausted = true;
- } else if (task instanceof TaskSequence) {
- TaskSequence t = (TaskSequence) task;
+ } else if (task instanceof TaskSequence t) {
if (t.resetExhausted) {
exhausted = false;
resetExhausted = true;
@@ -384,8 +383,7 @@ public class TaskSequence extends PerfTask {
for (int i = 0; i < t.length; i++) {
t[i].join();
count += t[i].count;
- if (t[i].task instanceof TaskSequence) {
- TaskSequence sub = (TaskSequence) t[i].task;
+ if (t[i].task instanceof TaskSequence sub) {
if (sub.countsByTime != null) {
if (countsByTime == null) {
countsByTime = new int[sub.countsByTime.length];
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java
index 25a688dbeee..4887af5fc00 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/utils/Config.java
@@ -288,18 +288,15 @@ public class Config {
for (final Map.Entry<String, Object> entry : valByRound.entrySet()) {
final String name = entry.getKey();
Object a = entry.getValue();
- if (a instanceof int[]) {
- int[] ai = (int[]) a;
+ if (a instanceof int[] ai) {
int n1 = (roundNumber - 1) % ai.length;
int n2 = roundNumber % ai.length;
sb.append(" ").append(name).append(":").append(ai[n1]).append("-->").append(ai[n2]);
- } else if (a instanceof double[]) {
- double[] ad = (double[]) a;
+ } else if (a instanceof double[] ad) {
int n1 = (roundNumber - 1) % ad.length;
int n2 = roundNumber % ad.length;
sb.append(" ").append(name).append(":").append(ad[n1]).append("-->").append(ad[n2]);
- } else if (a instanceof String[]) {
- String[] ad = (String[]) a;
+ } else if (a instanceof String[] ad) {
int n1 = (roundNumber - 1) % ad.length;
int n2 = roundNumber % ad.length;
sb.append(" ").append(name).append(":").append(ad[n1]).append("-->").append(ad[n2]);
@@ -423,16 +420,13 @@ public class Config {
// append actual values, for that round
Object a = valByRound.get(valByRoundName);
- if (a instanceof int[]) {
- int[] ai = (int[]) a;
+ if (a instanceof int[] ai) {
int n = roundNum % ai.length;
sb.append(Format.format(ai[n], template));
- } else if (a instanceof double[]) {
- double[] ad = (double[]) a;
+ } else if (a instanceof double[] ad) {
int n = roundNum % ad.length;
sb.append(Format.format(2, ad[n], template));
- } else if (a instanceof String[]) {
- String[] ad = (String[]) a;
+ } else if (a instanceof String[] ad) {
int n = roundNum % ad.length;
sb.append(ad[n]);
} else {
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
index 3982ab8e073..d5bdc3a83f3 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
@@ -375,13 +375,13 @@ public class BlockTermsReader extends FieldsProducer {
// target.utf8ToString() + " " + target + " current=" + term().utf8ToString() + " " + term()
// + " indexIsCurrent=" + indexIsCurrent + " didIndexNext=" + didIndexNext + " seekPending="
// + seekPending + " divisor=" + indexReader.getDivisor() + " this=" + this);
- if (didIndexNext) {
- if (nextIndexTerm == null) {
- // System.out.println(" nextIndexTerm=null");
- } else {
- // System.out.println(" nextIndexTerm=" + nextIndexTerm.utf8ToString());
- }
- }
+ // if (didIndexNext) {
+ // if (nextIndexTerm == null) {
+ // // System.out.println(" nextIndexTerm=null");
+ // } else {
+ // // System.out.println(" nextIndexTerm=" + nextIndexTerm.utf8ToString());
+ // }
+ // }
boolean doSeek = true;
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/CharArrayMap.java b/lucene/core/src/java/org/apache/lucene/analysis/CharArrayMap.java
index eace7d0edb3..628553ffaa3 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/CharArrayMap.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/CharArrayMap.java
@@ -35,7 +35,7 @@ public class CharArrayMap<V> extends AbstractMap<Object, V> {
private static final CharArrayMap<?> EMPTY_MAP = new EmptyCharArrayMap<>();
private static final int INIT_SIZE = 8;
- private boolean ignoreCase;
+ private final boolean ignoreCase;
private int count;
// package private because used in CharArraySet's non Set-conform CharArraySetIterator
char[][] keys;
@@ -106,8 +106,7 @@ public class CharArrayMap<V> extends AbstractMap<Object, V> {
@Override
public boolean containsKey(Object o) {
- if (o instanceof char[]) {
- final char[] text = (char[]) o;
+ if (o instanceof char[] text) {
return containsKey(text, 0, text.length);
}
return containsKey(o.toString());
@@ -128,8 +127,7 @@ public class CharArrayMap<V> extends AbstractMap<Object, V> {
@Override
public V get(Object o) {
- if (o instanceof char[]) {
- final char[] text = (char[]) o;
+ if (o instanceof char[] text) {
return get(text, 0, text.length);
}
return get(o.toString());
@@ -463,11 +461,9 @@ public class CharArrayMap<V> extends AbstractMap<Object, V> {
@Override
public String toString() {
- return new StringBuilder()
- .append(keys[pos])
- .append('=')
- .append((values[pos] == CharArrayMap.this) ? "(this Map)" : values[pos])
- .toString();
+ return String.valueOf(keys[pos])
+ + '='
+ + ((values[pos] == CharArrayMap.this) ? "(this Map)" : values[pos]);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/CharArraySet.java b/lucene/core/src/java/org/apache/lucene/analysis/CharArraySet.java
index 7b3bced96de..710991a972a 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/CharArraySet.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/CharArraySet.java
@@ -153,8 +153,7 @@ public class CharArraySet extends AbstractSet<Object> {
*/
public static CharArraySet copy(final Set<?> set) {
if (set == EMPTY_SET) return EMPTY_SET;
- if (set instanceof CharArraySet) {
- final CharArraySet source = (CharArraySet) set;
+ if (set instanceof CharArraySet source) {
return new CharArraySet(CharArrayMap.copy(source.map));
}
return new CharArraySet(set, false);
@@ -162,7 +161,6 @@ public class CharArraySet extends AbstractSet<Object> {
/** Returns an {@link Iterator} for {@code char[]} instances in this set. */
@Override
- @SuppressWarnings("unchecked")
public Iterator<Object> iterator() {
// use the AbstractSet#keySet()'s iterator (to not produce endless recursion)
return map.originalKeySet().iterator();
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
index c494bda1ab2..edb8b18b4db 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
@@ -27,7 +27,7 @@ import org.apache.lucene.util.BytesRefBuilder;
/** Default implementation of {@link CharTermAttribute}. */
public class CharTermAttributeImpl extends AttributeImpl
implements CharTermAttribute, TermToBytesRefAttribute {
- private static int MIN_BUFFER_SIZE = 10;
+ private static final int MIN_BUFFER_SIZE = 10;
private char[] termBuffer = new char[ArrayUtil.oversize(MIN_BUFFER_SIZE, Character.BYTES)];
private int termLength = 0;
@@ -137,8 +137,7 @@ public class CharTermAttributeImpl extends AttributeImpl
((StringBuilder) csq).getChars(start, end, termBuffer, termLength);
} else if (csq instanceof CharTermAttribute) {
System.arraycopy(((CharTermAttribute) csq).buffer(), start, termBuffer, termLength, len);
- } else if (csq instanceof CharBuffer && ((CharBuffer) csq).hasArray()) {
- final CharBuffer cb = (CharBuffer) csq;
+ } else if (csq instanceof CharBuffer cb && cb.hasArray()) {
System.arraycopy(
cb.array(), cb.arrayOffset() + cb.position() + start, termBuffer, termLength, len);
} else if (csq instanceof StringBuffer) {
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/OffsetAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/OffsetAttributeImpl.java
index 8e05ece82b3..375805d0504 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/OffsetAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/OffsetAttributeImpl.java
@@ -73,8 +73,7 @@ public class OffsetAttributeImpl extends AttributeImpl implements OffsetAttribut
return true;
}
- if (other instanceof OffsetAttributeImpl) {
- OffsetAttributeImpl o = (OffsetAttributeImpl) other;
+ if (other instanceof OffsetAttributeImpl o) {
return o.startOffset == startOffset && o.endOffset == endOffset;
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PackedTokenAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PackedTokenAttributeImpl.java
index 59df615ef10..16fc4f2ea0d 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PackedTokenAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PackedTokenAttributeImpl.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.analysis.tokenattributes;
+import java.util.Objects;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
@@ -194,13 +195,12 @@ public class PackedTokenAttributeImpl extends CharTermAttributeImpl
public boolean equals(Object obj) {
if (obj == this) return true;
- if (obj instanceof PackedTokenAttributeImpl) {
- final PackedTokenAttributeImpl other = (PackedTokenAttributeImpl) obj;
+ if (obj instanceof PackedTokenAttributeImpl other) {
return (startOffset == other.startOffset
&& endOffset == other.endOffset
&& positionIncrement == other.positionIncrement
&& positionLength == other.positionLength
- && (type == null ? other.type == null : type.equals(other.type))
+ && Objects.equals(type, other.type)
&& termFrequency == other.termFrequency
&& super.equals(obj));
} else {
@@ -222,8 +222,7 @@ public class PackedTokenAttributeImpl extends CharTermAttributeImpl
@Override
public void copyTo(AttributeImpl target) {
- if (target instanceof PackedTokenAttributeImpl) {
- final PackedTokenAttributeImpl to = (PackedTokenAttributeImpl) target;
+ if (target instanceof PackedTokenAttributeImpl to) {
to.copyBuffer(buffer(), 0, length());
to.positionIncrement = positionIncrement;
to.positionLength = positionLength;
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PayloadAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PayloadAttributeImpl.java
index 4ab42576ea9..a452bea0f83 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PayloadAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PayloadAttributeImpl.java
@@ -62,8 +62,7 @@ public class PayloadAttributeImpl extends AttributeImpl implements PayloadAttrib
return true;
}
- if (other instanceof PayloadAttributeImpl) {
- PayloadAttributeImpl o = (PayloadAttributeImpl) other;
+ if (other instanceof PayloadAttributeImpl o) {
if (o.payload == null || payload == null) {
return o.payload == null && payload == null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionIncrementAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionIncrementAttributeImpl.java
index 31ceca1a62f..8952d295c5c 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionIncrementAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionIncrementAttributeImpl.java
@@ -57,8 +57,7 @@ public class PositionIncrementAttributeImpl extends AttributeImpl
return true;
}
- if (other instanceof PositionIncrementAttributeImpl) {
- PositionIncrementAttributeImpl _other = (PositionIncrementAttributeImpl) other;
+ if (other instanceof PositionIncrementAttributeImpl _other) {
return positionIncrement == _other.positionIncrement;
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionLengthAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionLengthAttributeImpl.java
index b7dd308e0e1..0a98c739eb9 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionLengthAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/PositionLengthAttributeImpl.java
@@ -51,8 +51,7 @@ public class PositionLengthAttributeImpl extends AttributeImpl implements Positi
return true;
}
- if (other instanceof PositionLengthAttributeImpl) {
- PositionLengthAttributeImpl _other = (PositionLengthAttributeImpl) other;
+ if (other instanceof PositionLengthAttributeImpl _other) {
return positionLength == _other.positionLength;
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TermFrequencyAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TermFrequencyAttributeImpl.java
index f578e28aada..18fcd36112a 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TermFrequencyAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TermFrequencyAttributeImpl.java
@@ -56,8 +56,7 @@ public class TermFrequencyAttributeImpl extends AttributeImpl implements TermFre
return true;
}
- if (other instanceof TermFrequencyAttributeImpl) {
- TermFrequencyAttributeImpl _other = (TermFrequencyAttributeImpl) other;
+ if (other instanceof TermFrequencyAttributeImpl _other) {
return termFrequency == _other.termFrequency;
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TypeAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TypeAttributeImpl.java
index 0f444044cdd..3d271dfa11f 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TypeAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/TypeAttributeImpl.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.analysis.tokenattributes;
+import java.util.Objects;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
@@ -54,9 +55,8 @@ public class TypeAttributeImpl extends AttributeImpl implements TypeAttribute {
return true;
}
- if (other instanceof TypeAttributeImpl) {
- final TypeAttributeImpl o = (TypeAttributeImpl) other;
- return (this.type == null ? o.type == null : this.type.equals(o.type));
+ if (other instanceof TypeAttributeImpl o) {
+ return Objects.equals(this.type, o.type);
}
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90PointsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90PointsWriter.java
index 45a946e8ac4..2de98e55688 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90PointsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90PointsWriter.java
@@ -177,7 +177,7 @@ public class Lucene90PointsWriter extends PointsWriter {
@Override
public void merge(MergeState mergeState) throws IOException {
- /**
+ /*
* If indexSort is activated and some of the leaves are not sorted the next test will catch that
* and the non-optimized merge will run. If the readers are all sorted then it's safe to perform
* a bulk merge of the points.
diff --git a/lucene/core/src/java/org/apache/lucene/document/DocValuesLongHashSet.java b/lucene/core/src/java/org/apache/lucene/document/DocValuesLongHashSet.java
index 7daa0e2c6d1..cebf3e06330 100644
--- a/lucene/core/src/java/org/apache/lucene/document/DocValuesLongHashSet.java
+++ b/lucene/core/src/java/org/apache/lucene/document/DocValuesLongHashSet.java
@@ -119,8 +119,7 @@ final class DocValuesLongHashSet implements Accountable {
@Override
public boolean equals(Object obj) {
- if (obj != null && obj instanceof DocValuesLongHashSet) {
- DocValuesLongHashSet that = (DocValuesLongHashSet) obj;
+ if (obj instanceof DocValuesLongHashSet that) {
return size == that.size
&& minValue == that.minValue
&& maxValue == that.maxValue
diff --git a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
index f99b699565b..6dce66e6595 100644
--- a/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
+++ b/lucene/core/src/java/org/apache/lucene/document/LatLonShape.java
@@ -326,8 +326,7 @@ public class LatLonShape {
String field, QueryRelation queryRelation, LatLonGeometry... latLonGeometries) {
if (latLonGeometries.length == 1) {
LatLonGeometry geometry = latLonGeometries[0];
- if (geometry instanceof Rectangle) {
- Rectangle rect = (Rectangle) geometry;
+ if (geometry instanceof Rectangle rect) {
return newBoxQuery(
field, queryRelation, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
} else {
@@ -355,9 +354,8 @@ public class LatLonShape {
private static Query makeContainsGeometryQuery(String field, LatLonGeometry... latLonGeometries) {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
for (LatLonGeometry geometry : latLonGeometries) {
- if (geometry instanceof Rectangle) {
+ if (geometry instanceof Rectangle rect) {
// this handles rectangles across the dateline
- Rectangle rect = (Rectangle) geometry;
builder.add(
newBoxQuery(
field, QueryRelation.CONTAINS, rect.minLat, rect.maxLat, rect.minLon, rect.maxLon),
diff --git a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesSetQuery.java b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesSetQuery.java
index 192a751b43e..7b27cb0f4b6 100644
--- a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesSetQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesSetQuery.java
@@ -73,7 +73,7 @@ final class SortedNumericDocValuesSetQuery extends Query implements Accountable
@Override
public String toString(String defaultField) {
- return new StringBuilder().append(field).append(": ").append(numbers.toString()).toString();
+ return field + ": " + numbers.toString();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/geo/Tessellator.java b/lucene/core/src/java/org/apache/lucene/geo/Tessellator.java
index a2b8cad84ff..bc53006175f 100644
--- a/lucene/core/src/java/org/apache/lucene/geo/Tessellator.java
+++ b/lucene/core/src/java/org/apache/lucene/geo/Tessellator.java
@@ -327,8 +327,7 @@ public final class Tessellator {
final Node holeNode = holeList.get(i);
double holeMinX, holeMaxX, holeMinY, holeMaxY;
Object h = holeListPolygons.get(holeNode);
- if (h instanceof Polygon) {
- Polygon holePoly = (Polygon) h;
+ if (h instanceof Polygon holePoly) {
holeMinX = holePoly.minLon;
holeMaxX = holePoly.maxLon;
holeMinY = holePoly.minLat;
diff --git a/lucene/core/src/java/org/apache/lucene/index/CompositeReaderContext.java b/lucene/core/src/java/org/apache/lucene/index/CompositeReaderContext.java
index 0004df794e5..c30f2874226 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CompositeReaderContext.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CompositeReaderContext.java
@@ -98,8 +98,7 @@ public final class CompositeReaderContext extends IndexReaderContext {
private IndexReaderContext build(
CompositeReaderContext parent, IndexReader reader, int ord, int docBase) {
- if (reader instanceof LeafReader) {
- final LeafReader ar = (LeafReader) reader;
+ if (reader instanceof LeafReader ar) {
final LeafReaderContext atomic =
new LeafReaderContext(parent, ar, ord, docBase, leaves.size(), leafDocBase);
leaves.add(atomic);
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocsWithFieldSet.java b/lucene/core/src/java/org/apache/lucene/index/DocsWithFieldSet.java
index 1d018ac95cc..8c8b0cac26f 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocsWithFieldSet.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocsWithFieldSet.java
@@ -28,7 +28,7 @@ import org.apache.lucene.util.RamUsageEstimator;
*/
public final class DocsWithFieldSet extends DocIdSet {
- private static long BASE_RAM_BYTES_USED =
+ private static final long BASE_RAM_BYTES_USED =
RamUsageEstimator.shallowSizeOfInstance(DocsWithFieldSet.class);
private FixedBitSet set;
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexCommit.java b/lucene/core/src/java/org/apache/lucene/index/IndexCommit.java
index ff97cd5582f..c8d620e6d21 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexCommit.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexCommit.java
@@ -75,8 +75,7 @@ public abstract class IndexCommit implements Comparable<IndexCommit> {
/** Two IndexCommits are equal if both their Directory and versions are equal. */
@Override
public boolean equals(Object other) {
- if (other instanceof IndexCommit) {
- IndexCommit otherCommit = (IndexCommit) other;
+ if (other instanceof IndexCommit otherCommit) {
return otherCommit.getDirectory() == getDirectory()
&& otherCommit.getGeneration() == getGeneration();
} else {
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
index 2a265a093be..dc8d9013927 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
@@ -1450,7 +1450,7 @@ final class IndexingChain implements Accountable {
private VectorEncoding vectorEncoding = VectorEncoding.FLOAT32;
private VectorSimilarityFunction vectorSimilarityFunction = VectorSimilarityFunction.EUCLIDEAN;
- private static String errMsg =
+ private static final String errMsg =
"Inconsistency of field data structures across documents for field ";
FieldSchema(String name) {
diff --git a/lucene/core/src/java/org/apache/lucene/index/MappedMultiFields.java b/lucene/core/src/java/org/apache/lucene/index/MappedMultiFields.java
index a0aa0c9a012..203bd898b36 100644
--- a/lucene/core/src/java/org/apache/lucene/index/MappedMultiFields.java
+++ b/lucene/core/src/java/org/apache/lucene/index/MappedMultiFields.java
@@ -116,8 +116,7 @@ public class MappedMultiFields extends FilterFields {
@Override
public PostingsEnum postings(PostingsEnum reuse, int flags) throws IOException {
MappingMultiPostingsEnum mappingDocsAndPositionsEnum;
- if (reuse instanceof MappingMultiPostingsEnum) {
- MappingMultiPostingsEnum postings = (MappingMultiPostingsEnum) reuse;
+ if (reuse instanceof MappingMultiPostingsEnum postings) {
if (postings.field.equals(this.field)) {
mappingDocsAndPositionsEnum = postings;
} else {
diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentInfo.java b/lucene/core/src/java/org/apache/lucene/index/SegmentInfo.java
index 74528f97672..9e502b640b7 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SegmentInfo.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentInfo.java
@@ -263,8 +263,7 @@ public final class SegmentInfo {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
- if (obj instanceof SegmentInfo) {
- final SegmentInfo other = (SegmentInfo) obj;
+ if (obj instanceof SegmentInfo other) {
return other.dir == dir && other.name.equals(name);
} else {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/index/SoftDeletesDirectoryReaderWrapper.java b/lucene/core/src/java/org/apache/lucene/index/SoftDeletesDirectoryReaderWrapper.java
index bbe493d88d3..0d9aafbb499 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SoftDeletesDirectoryReaderWrapper.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SoftDeletesDirectoryReaderWrapper.java
@@ -154,8 +154,7 @@ public final class SoftDeletesDirectoryReaderWrapper extends FilterDirectoryRead
private static boolean assertDocCounts(
int expectedNumDocs, int numSoftDeletes, LeafReader reader) {
- if (reader instanceof SegmentReader) {
- SegmentReader segmentReader = (SegmentReader) reader;
+ if (reader instanceof SegmentReader segmentReader) {
SegmentCommitInfo segmentInfo = segmentReader.getSegmentInfo();
if (segmentReader.isNRT == false) {
int numDocs =
diff --git a/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java b/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
index 119d3ed13f7..319e67e1418 100644
--- a/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
@@ -497,8 +497,7 @@ public class BooleanQuery extends Query implements Iterable<BooleanClause> {
if (musts.size() == 1 && filters.size() > 0) {
Query must = musts.iterator().next();
float boost = 1f;
- if (must instanceof BoostQuery) {
- BoostQuery boostQuery = (BoostQuery) must;
+ if (must instanceof BoostQuery boostQuery) {
must = boostQuery.getQuery();
boost = boostQuery.getBoost();
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
index cb406389f37..bfc06c0986b 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreQuery.java
@@ -196,7 +196,7 @@ public final class ConstantScoreQuery extends Query {
@Override
public String toString(String field) {
- return new StringBuilder("ConstantScore(").append(query.toString(field)).append(')').toString();
+ return "ConstantScore(" + query.toString(field) + ')';
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/search/IndriAndScorer.java b/lucene/core/src/java/org/apache/lucene/search/IndriAndScorer.java
index 72cc2ff530a..6cb0203df1e 100644
--- a/lucene/core/src/java/org/apache/lucene/search/IndriAndScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/search/IndriAndScorer.java
@@ -45,8 +45,7 @@ public class IndriAndScorer extends IndriDisjunctionScorer {
double score = 0;
double boostSum = 0.0;
for (Scorer scorer : subScorers) {
- if (scorer instanceof IndriScorer) {
- IndriScorer indriScorer = (IndriScorer) scorer;
+ if (scorer instanceof IndriScorer indriScorer) {
int scorerDocId = indriScorer.docID();
// If the query exists in the document, score the document
// Otherwise, compute a smoothing score, which acts like an idf
diff --git a/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java b/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
index eac31428180..f180ed159c5 100644
--- a/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
+++ b/lucene/core/src/java/org/apache/lucene/search/UsageTrackingQueryCachingPolicy.java
@@ -75,15 +75,13 @@ public class UsageTrackingQueryCachingPolicy implements QueryCachingPolicy {
return true;
}
- if (query instanceof BooleanQuery) {
- BooleanQuery bq = (BooleanQuery) query;
+ if (query instanceof BooleanQuery bq) {
if (bq.clauses().isEmpty()) {
return true;
}
}
- if (query instanceof DisjunctionMaxQuery) {
- DisjunctionMaxQuery dmq = (DisjunctionMaxQuery) query;
+ if (query instanceof DisjunctionMaxQuery dmq) {
if (dmq.getDisjuncts().isEmpty()) {
return true;
}
diff --git a/lucene/core/src/java/org/apache/lucene/store/DataOutput.java b/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
index b312a693eba..543ff175867 100644
--- a/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
@@ -274,7 +274,7 @@ public abstract class DataOutput {
writeBytes(utf8Result.bytes, utf8Result.offset, utf8Result.length);
}
- private static int COPY_BUFFER_SIZE = 16384;
+ private static final int COPY_BUFFER_SIZE = 16384;
private byte[] copyBuffer;
/** Copy numBytes bytes from input to ourself. */
diff --git a/lucene/core/src/java/org/apache/lucene/util/AttributeSource.java b/lucene/core/src/java/org/apache/lucene/util/AttributeSource.java
index a59d0649192..9d8f9bf65dc 100644
--- a/lucene/core/src/java/org/apache/lucene/util/AttributeSource.java
+++ b/lucene/core/src/java/org/apache/lucene/util/AttributeSource.java
@@ -346,9 +346,7 @@ public class AttributeSource {
return true;
}
- if (obj instanceof AttributeSource) {
- AttributeSource other = (AttributeSource) obj;
-
+ if (obj instanceof AttributeSource other) {
if (hasAttributes()) {
if (!other.hasAttributes()) {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/util/CloseableThreadLocal.java b/lucene/core/src/java/org/apache/lucene/util/CloseableThreadLocal.java
index 58c4736e93b..be95ec9b8e5 100644
--- a/lucene/core/src/java/org/apache/lucene/util/CloseableThreadLocal.java
+++ b/lucene/core/src/java/org/apache/lucene/util/CloseableThreadLocal.java
@@ -52,7 +52,7 @@ public class CloseableThreadLocal<T> implements Closeable {
private Map<Thread, T> hardRefs = new WeakHashMap<>();
// Increase this to decrease frequency of purging in get:
- private static int PURGE_MULTIPLIER = 20;
+ private static final int PURGE_MULTIPLIER = 20;
// On each get or set we decrement this; when it hits 0 we
// purge. After purge, we set this to
diff --git a/lucene/core/src/java/org/apache/lucene/util/FixedBitSet.java b/lucene/core/src/java/org/apache/lucene/util/FixedBitSet.java
index 9867582dd52..6526b48466e 100644
--- a/lucene/core/src/java/org/apache/lucene/util/FixedBitSet.java
+++ b/lucene/core/src/java/org/apache/lucene/util/FixedBitSet.java
@@ -36,7 +36,7 @@ public final class FixedBitSet extends BitSet {
// An array that is small enough to use reasonable amounts of RAM and large enough to allow
// Arrays#mismatch to use SIMD instructions and multiple registers under the hood.
- private static long[] ZEROES = new long[32];
+ private static final long[] ZEROES = new long[32];
private final long[] bits; // Array of longs holding the bits
private final int numBits; // The number of bits in use
@@ -747,9 +747,8 @@ public final class FixedBitSet extends BitSet {
/** Make a copy of the given bits. */
public static FixedBitSet copyOf(Bits bits) {
- if (bits instanceof FixedBits) {
+ if (bits instanceof FixedBits fixedBits) {
// restore the original FixedBitSet
- FixedBits fixedBits = (FixedBits) bits;
bits = new FixedBitSet(fixedBits.bits, fixedBits.length);
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java b/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
index fd32ece1ebd..e922c00064f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
+++ b/lucene/core/src/java/org/apache/lucene/util/RamUsageEstimator.java
@@ -110,7 +110,7 @@ public final class RamUsageEstimator {
/** For testing only */
static final boolean JVM_IS_HOTSPOT_64BIT;
- /** Initialize constants and try to collect information about the JVM internals. */
+ /* Initialize constants and try to collect information about the JVM internals. */
static {
if (Constants.JRE_IS_64BIT) {
JVM_IS_HOTSPOT_64BIT = HotspotVMOptions.IS_HOTSPOT_VM;
diff --git a/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java b/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
index ee27bf1db6d..cb8c6cc0273 100644
--- a/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
+++ b/lucene/core/src/java/org/apache/lucene/util/SloppyMath.java
@@ -246,7 +246,7 @@ public class SloppyMath {
// 7.70381505559019352791e-02
private static final double ASIN_QS4 = Double.longBitsToDouble(0x3fb3b8c5b12e9282L);
- /** Initializes look-up tables. */
+ /* Initializes look-up tables. */
static {
// sin and cos
final int SIN_COS_PI_INDEX = (SIN_COS_TABS_SIZE - 1) / 2;
diff --git a/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java b/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java
index f85111f0d05..864980c249c 100644
--- a/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java
+++ b/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java
@@ -265,8 +265,7 @@ public final class WeakIdentityMap<K, V> {
if (this == o) {
return true;
}
- if (o instanceof IdentityWeakReference) {
- final IdentityWeakReference ref = (IdentityWeakReference) o;
+ if (o instanceof IdentityWeakReference ref) {
if (this.get() == ref.get()) {
return true;
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/automaton/StatePair.java b/lucene/core/src/java/org/apache/lucene/util/automaton/StatePair.java
index bd003507f2d..eb25ac30343 100644
--- a/lucene/core/src/java/org/apache/lucene/util/automaton/StatePair.java
+++ b/lucene/core/src/java/org/apache/lucene/util/automaton/StatePair.java
@@ -70,8 +70,7 @@ public class StatePair {
*/
@Override
public boolean equals(Object obj) {
- if (obj instanceof StatePair) {
- StatePair p = (StatePair) obj;
+ if (obj instanceof StatePair p) {
return p.s1 == s1 && p.s2 == s2;
} else {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
index 2af93ef5ca0..2ce7d7e87ef 100644
--- a/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/util/bkd/BKDWriter.java
@@ -1020,7 +1020,7 @@ public class BKDWriter implements Closeable {
* structure.
*/
private byte[] packIndex(BKDTreeLeafNodes leafNodes) throws IOException {
- /** Reused while packing the index */
+ /* Reused while packing the index */
ByteBuffersDataOutput writeBuffer = ByteBuffersDataOutput.newResettableInstance();
// This is the "file" we append the byte[] to:
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/PairOutputs.java b/lucene/core/src/java/org/apache/lucene/util/fst/PairOutputs.java
index 0bb9f77e17d..e991c3b93fa 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/PairOutputs.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/PairOutputs.java
@@ -48,8 +48,7 @@ public class PairOutputs<A, B> extends Outputs<PairOutputs.Pair<A, B>> {
public boolean equals(Object other) {
if (other == this) {
return true;
- } else if (other instanceof Pair) {
- Pair pair = (Pair) other;
+ } else if (other instanceof Pair pair) {
return output1.equals(pair.output1) && output2.equals(pair.output2);
} else {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/util/packed/BlockPackedReaderIterator.java b/lucene/core/src/java/org/apache/lucene/util/packed/BlockPackedReaderIterator.java
index cbbf5d70713..78f88f69325 100644
--- a/lucene/core/src/java/org/apache/lucene/util/packed/BlockPackedReaderIterator.java
+++ b/lucene/core/src/java/org/apache/lucene/util/packed/BlockPackedReaderIterator.java
@@ -134,8 +134,7 @@ public final class BlockPackedReaderIterator {
}
private void skipBytes(long count) throws IOException {
- if (in instanceof IndexInput) {
- final IndexInput iin = (IndexInput) in;
+ if (in instanceof IndexInput iin) {
iin.seek(iin.getFilePointer() + count);
} else {
if (blocks == null) {
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestCharArrayMap.java b/lucene/core/src/test/org/apache/lucene/analysis/TestCharArrayMap.java
index 43b6d20d683..c7c4add652e 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/TestCharArrayMap.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestCharArrayMap.java
@@ -134,6 +134,7 @@ public class TestCharArrayMap extends LuceneTestCase {
}
// TODO: break this up into simpler test methods vs. "telling a story"
+ @SuppressWarnings("UnnecessaryStringBuilder")
public void testModifyOnUnmodifiable() {
CharArrayMap<Integer> map = new CharArrayMap<>(2, false);
map.put("foo", 1);
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestCharArraySet.java b/lucene/core/src/test/org/apache/lucene/analysis/TestCharArraySet.java
index dcc5bf2cce7..6d16c5c248e 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/TestCharArraySet.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestCharArraySet.java
@@ -91,6 +91,7 @@ public class TestCharArraySet extends LuceneTestCase {
}
// TODO: break this up into simpler test methods, vs "telling a story"
+ @SuppressWarnings("UnnecessaryStringBuilder")
public void testModifyOnUnmodifiable() {
CharArraySet set = new CharArraySet(10, true);
set.addAll(Arrays.asList(TEST_STOP_WORDS));
diff --git a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java
index 3a151b4b026..bb260d6d8b0 100644
--- a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java
+++ b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java
@@ -167,6 +167,7 @@ public class TestCharTermAttributeImpl extends LuceneTestCase {
}
}
+ @SuppressWarnings("UnnecessaryStringBuilder")
public void testAppendableInterface() {
CharTermAttributeImpl t = new CharTermAttributeImpl();
Formatter formatter = new Formatter(t, Locale.ROOT);
@@ -216,6 +217,7 @@ public class TestCharTermAttributeImpl extends LuceneTestCase {
assertEquals("4testenull", t.toString());
}
+ @SuppressWarnings("UnnecessaryStringBuilder")
public void testAppendableInterfaceWithLongSequences() {
CharTermAttributeImpl t = new CharTermAttributeImpl();
t.append((CharSequence) "01234567890123456789012345678901234567890123456789");
diff --git a/lucene/core/src/test/org/apache/lucene/document/TestBinaryDocument.java b/lucene/core/src/test/org/apache/lucene/document/TestBinaryDocument.java
index f161f3375d5..689206e92b5 100644
--- a/lucene/core/src/test/org/apache/lucene/document/TestBinaryDocument.java
+++ b/lucene/core/src/test/org/apache/lucene/document/TestBinaryDocument.java
@@ -43,27 +43,27 @@ public class TestBinaryDocument extends LuceneTestCase {
doc.add(stringFldStored);
- /** test for field count */
+ /* test for field count */
assertEquals(2, doc.getFields().size());
- /** add the doc to a ram index */
+ /* add the doc to a ram index */
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
writer.addDocument(doc);
- /** open a reader and fetch the document */
+ /* open a reader and fetch the document */
IndexReader reader = writer.getReader();
Document docFromReader = reader.storedFields().document(0);
assertTrue(docFromReader != null);
- /** fetch the binary stored field and compare its content with the original one */
+ /* fetch the binary stored field and compare its content with the original one */
BytesRef bytes = docFromReader.getBinaryValue("binaryStored");
assertNotNull(bytes);
String binaryFldStoredTest =
new String(bytes.bytes, bytes.offset, bytes.length, StandardCharsets.UTF_8);
assertTrue(binaryFldStoredTest.equals(binaryValStored));
- /** fetch the string field and compare its content with the original one */
+ /* fetch the string field and compare its content with the original one */
String stringFldStoredTest = docFromReader.get("stringStored");
assertTrue(stringFldStoredTest.equals(binaryValStored));
diff --git a/lucene/core/src/test/org/apache/lucene/document/TestFieldType.java b/lucene/core/src/test/org/apache/lucene/document/TestFieldType.java
index 4b2136dfa4b..fcb1cb542ab 100644
--- a/lucene/core/src/test/org/apache/lucene/document/TestFieldType.java
+++ b/lucene/core/src/test/org/apache/lucene/document/TestFieldType.java
@@ -26,6 +26,7 @@ import org.apache.lucene.tests.util.LuceneTestCase;
/** simple testcases for concrete impl of IndexableFieldType */
public class TestFieldType extends LuceneTestCase {
+ @SuppressWarnings("SelfAssertion")
public void testEquals() throws Exception {
FieldType ft = new FieldType();
assertEquals(ft, ft);
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDemoParallelLeafReader.java b/lucene/core/src/test/org/apache/lucene/index/TestDemoParallelLeafReader.java
index 39166971e7e..c08814ae750 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDemoParallelLeafReader.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDemoParallelLeafReader.java
@@ -337,8 +337,7 @@ public class TestDemoParallelLeafReader extends LuceneTestCase {
@Override
public boolean equals(Object _other) {
- if (_other instanceof SegmentIDAndGen) {
- SegmentIDAndGen other = (SegmentIDAndGen) _other;
+ if (_other instanceof SegmentIDAndGen other) {
return segID.equals(other.segID) && schemaGen == other.schemaGen;
} else {
return false;
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
index 2f92606ba7d..c7e910c2536 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
@@ -2140,8 +2140,7 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
IndexWriterConfig iwc = newIndexWriterConfig();
MergePolicy mp = iwc.getMergePolicy();
- if (mp instanceof TieredMergePolicy) {
- TieredMergePolicy tmp = (TieredMergePolicy) mp;
+ if (mp instanceof TieredMergePolicy tmp) {
if (tmp.getMaxMergedSegmentMB() < 0.2) {
tmp.setMaxMergedSegmentMB(0.2);
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestLogMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestLogMergePolicy.java
index 8c121c1f6a0..99812b37d8c 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestLogMergePolicy.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestLogMergePolicy.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.MergePolicy.OneMerge;
import org.apache.lucene.tests.index.BaseMergePolicyTestCase;
import org.apache.lucene.util.Version;
+@SuppressWarnings("UnnecessaryAsync")
public class TestLogMergePolicy extends BaseMergePolicyTestCase {
@Override
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestStressIndexing2.java b/lucene/core/src/test/org/apache/lucene/index/TestStressIndexing2.java
index eb4e9cdffa2..89698bdd7fb 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestStressIndexing2.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestStressIndexing2.java
@@ -173,12 +173,12 @@ public class TestStressIndexing2 extends LuceneTestCase {
LogMergePolicy lmp = (LogMergePolicy) w.getConfig().getMergePolicy();
lmp.setNoCFSRatio(0.0);
lmp.setMergeFactor(mergeFactor);
- /***
+ /*
* w.setMaxMergeDocs(Integer.MAX_VALUE);
* w.setMaxFieldLength(10000);
* w.setRAMBufferSizeMB(1);
* w.setMergeFactor(10);
- ***/
+ */
threads = new IndexingThread[nThreads];
for (int i = 0; i < threads.length; i++) {
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTerm.java b/lucene/core/src/test/org/apache/lucene/index/TestTerm.java
index fc1ea752520..9e62d89e860 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestTerm.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestTerm.java
@@ -20,7 +20,7 @@ import org.apache.lucene.tests.util.LuceneTestCase;
public class TestTerm extends LuceneTestCase {
- @SuppressWarnings("unlikely-arg-type")
+ @SuppressWarnings({"unlikely-arg-type", "SelfAssertion"})
public void testEquals() {
final Term base = new Term("same", "same");
final Term same = new Term("same", "same");
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
index 6f11f71f3a9..1fdaf2d64a8 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java
@@ -977,6 +977,7 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {
assertEquals(50, mergeSpec.merges.get(0).segments.size());
}
+ @SuppressWarnings("UnnecessaryAsync")
public void testFullFlushMerges() throws IOException {
AtomicLong segNameGenerator = new AtomicLong();
IOStats stats = new IOStats();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java
index f014348739e..ca17ef88f60 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java
@@ -274,6 +274,7 @@ public class TestDocValuesRangeIterator extends LuceneTestCase {
}
@Override
+ @SuppressWarnings("DuplicateBranches")
public long minValue(int level) {
int d = doc % 1024;
if (d < 128) {
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDoubleValuesSource.java b/lucene/core/src/test/org/apache/lucene/search/TestDoubleValuesSource.java
index ccdb060047d..f7242d5cfb2 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDoubleValuesSource.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDoubleValuesSource.java
@@ -136,6 +136,7 @@ public class TestDoubleValuesSource extends LuceneTestCase {
new Sort(new SortField("double", SortField.Type.DOUBLE, random().nextBoolean())));
}
+ @SuppressWarnings("SelfAssertion")
public void testHashCodeAndEquals() {
DoubleValuesSource vs1 = DoubleValuesSource.fromDoubleField("double");
DoubleValuesSource vs2 = DoubleValuesSource.fromDoubleField("double");
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestQueryVisitor.java b/lucene/core/src/test/org/apache/lucene/search/TestQueryVisitor.java
index 09c858ba1f4..39df073ca87 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestQueryVisitor.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestQueryVisitor.java
@@ -211,8 +211,7 @@ public class TestQueryVisitor extends LuceneTestCase {
if (occur == BooleanClause.Occur.MUST_NOT) {
return QueryVisitor.EMPTY_VISITOR;
}
- if (parent instanceof BooleanQuery) {
- BooleanQuery bq = (BooleanQuery) parent;
+ if (parent instanceof BooleanQuery bq) {
if (bq.getClauses(BooleanClause.Occur.MUST).size() > 0
|| bq.getClauses(BooleanClause.Occur.FILTER).size() > 0) {
return QueryVisitor.EMPTY_VISITOR;
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java
index da0ea802eb9..e7f765a16f8 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericSortField.java
@@ -56,7 +56,7 @@ public class TestSortedNumericSortField extends LuceneTestCase {
}
}
- @SuppressWarnings("unlikely-arg-type")
+ @SuppressWarnings({"unlikely-arg-type", "SelfAssertion"})
public void testEquals() throws Exception {
SortField sf = new SortedNumericSortField("a", SortField.Type.LONG);
assertFalse(sf.equals(null));
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
index 74bea98cf60..939580125b2 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedSetSortField.java
@@ -43,7 +43,7 @@ public class TestSortedSetSortField extends LuceneTestCase {
}
}
- @SuppressWarnings("unlikely-arg-type")
+ @SuppressWarnings({"unlikely-arg-type", "SelfAssertion"})
public void testEquals() throws Exception {
SortField sf = new SortedSetSortField("a", false);
assertFalse(sf.equals(null));
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
index e4f25179018..7fe6dcaa23c 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTermRangeQuery.java
@@ -159,6 +159,7 @@ public class TestTermRangeQuery extends LuceneTestCase {
assertEquals(0, allowedTerms.size());
}
+ @SuppressWarnings("SelfAssertion")
public void testEqualsHashcode() {
Query query = TermRangeQuery.newStringRange("content", "A", "C", true, true);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTotalHits.java b/lucene/core/src/test/org/apache/lucene/search/TestTotalHits.java
index f404cc72ebc..876dd2343c4 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestTotalHits.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestTotalHits.java
@@ -22,7 +22,7 @@ import org.apache.lucene.tests.util.LuceneTestCase;
public class TestTotalHits extends LuceneTestCase {
- @SuppressWarnings("unlikely-arg-type")
+ @SuppressWarnings({"unlikely-arg-type", "SelfAssertion"})
public void testEqualsAndHashcode() {
TotalHits totalHits1 = randomTotalHits();
assertFalse(totalHits1.equals(null));
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestVectorSimilarityValuesSource.java b/lucene/core/src/test/org/apache/lucene/search/TestVectorSimilarityValuesSource.java
index eaf67279ee4..12123e58f93 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestVectorSimilarityValuesSource.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestVectorSimilarityValuesSource.java
@@ -359,6 +359,7 @@ public class TestVectorSimilarityValuesSource extends LuceneTestCase {
0.0001);
}
+ @SuppressWarnings("JUnitIncompatibleType")
public void testFailuresWithSimilarityValuesSource() throws Exception {
float[] floatQueryVector = new float[] {1.1f, 2.2f, 3.3f};
byte[] byteQueryVector = new byte[] {-10, 20, 30};
diff --git a/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestScripts.java b/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestScripts.java
index 153d0f1e168..472aaebf5cf 100644
--- a/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestScripts.java
+++ b/lucene/distribution.tests/src/test/org/apache/lucene/distribution/TestScripts.java
@@ -103,7 +103,7 @@ public class TestScripts extends AbstractLuceneDistributionTest {
.orElseThrow(() -> new AssertionError("No script found for the base path: " + scriptPath));
}
- private static Supplier<Charset> forkedProcessCharset =
+ private static final Supplier<Charset> forkedProcessCharset =
() -> {
// The default charset for a forked java process could be computed for the current
// platform but it adds more complexity. For now, assume it's just parseable ascii.
diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionSortField.java b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionSortField.java
index e02fff5ed1b..6351dec1785 100644
--- a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionSortField.java
+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionSortField.java
@@ -34,6 +34,7 @@ public class TestExpressionSortField extends LuceneTestCase {
assertEquals("<expr(sqrt(_score) + ln(popularity))>!", sf.toString());
}
+ @SuppressWarnings("SelfAssertion")
public void testEquals() throws Exception {
Expression expr = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");
diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValueSource.java b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValueSource.java
index 87f2e674406..6f6dcce17cf 100644
--- a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValueSource.java
+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValueSource.java
@@ -94,7 +94,7 @@ public class TestExpressionValueSource extends LuceneTestCase {
assertEquals(4, values.doubleValue(), 0);
}
- @SuppressWarnings("unlikely-arg-type")
+ @SuppressWarnings({"unlikely-arg-type", "SelfAssertion"})
public void testDoubleValuesSourceEquals() throws Exception {
Expression expr = JavascriptCompiler.compile("sqrt(a) + ln(b)");
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestAlwaysRefreshDirectoryTaxonomyReader.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestAlwaysRefreshDirectoryTaxonomyReader.java
index 64de01fa0c6..3b683dc1c6a 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestAlwaysRefreshDirectoryTaxonomyReader.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestAlwaysRefreshDirectoryTaxonomyReader.java
@@ -82,7 +82,7 @@ public class TestAlwaysRefreshDirectoryTaxonomyReader extends FacetTestCase {
final FacetsConfig config = new FacetsConfig();
SearcherTaxonomyManager.SearcherAndTaxonomy pair = mgr.acquire();
final FacetsCollector sfc = new FacetsCollector();
- /**
+ /*
* the call flow here initializes {@link DirectoryTaxonomyReader#taxoArrays}. These reused
* `taxoArrays` form the basis of the inconsistency *
*/
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
index b94f73baefb..1370afd736b 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/highlight/WeightedSpanTermExtractor.java
@@ -128,8 +128,7 @@ public class WeightedSpanTermExtractor {
*/
protected void extract(Query query, float boost, Map<String, WeightedSpanTerm> terms)
throws IOException {
- if (query instanceof BoostQuery) {
- BoostQuery boostQuery = (BoostQuery) query;
+ if (query instanceof BoostQuery boostQuery) {
extract(boostQuery.getQuery(), boost * boostQuery.getBoost(), terms);
} else if (query instanceof BooleanQuery) {
for (BooleanClause clause : (BooleanQuery) query) {
@@ -186,8 +185,7 @@ public class WeightedSpanTermExtractor {
for (Query clause : ((DisjunctionMaxQuery) query)) {
extract(clause, boost, terms);
}
- } else if (query instanceof MultiPhraseQuery) {
- final MultiPhraseQuery mpq = (MultiPhraseQuery) query;
+ } else if (query instanceof MultiPhraseQuery mpq) {
final Term[][] termArrays = mpq.getTermArrays();
final int[] positions = mpq.getPositions();
if (positions.length > 0) {
@@ -598,8 +596,7 @@ public class WeightedSpanTermExtractor {
}
}
return false;
- } else if (spanQuery instanceof SpanNotQuery) {
- SpanNotQuery spanNotQuery = (SpanNotQuery) spanQuery;
+ } else if (spanQuery instanceof SpanNotQuery spanNotQuery) {
return mustRewriteQuery(spanNotQuery.getInclude())
|| mustRewriteQuery(spanNotQuery.getExclude());
} else if (spanQuery instanceof SpanOrQuery) {
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/matchhighlight/OffsetRange.java b/lucene/highlighter/src/java/org/apache/lucene/search/matchhighlight/OffsetRange.java
index bdf2adeb732..82f35fd2a20 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/matchhighlight/OffsetRange.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/matchhighlight/OffsetRange.java
@@ -48,8 +48,7 @@ public class OffsetRange implements Cloneable {
@Override
public boolean equals(Object other) {
if (other == this) return true;
- if (other instanceof OffsetRange) {
- OffsetRange that = (OffsetRange) other;
+ if (other instanceof OffsetRange that) {
return from == that.from && to == that.to;
} else {
return false;
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
index 2351e6c08f9..fa489843beb 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldQuery.java
@@ -85,8 +85,7 @@ public class FieldQuery {
flatQuery = bq.getQuery();
boost *= bq.getBoost();
}
- if (!phraseHighlight && flatQuery instanceof PhraseQuery) {
- PhraseQuery pq = (PhraseQuery) flatQuery;
+ if (!phraseHighlight && flatQuery instanceof PhraseQuery pq) {
if (pq.getTerms().length > 1) {
for (Term term : pq.getTerms()) rootMap.addTerm(term, boost);
}
@@ -105,20 +104,17 @@ public class FieldQuery {
protected void flatten(
Query sourceQuery, IndexSearcher searcher, Collection<Query> flatQueries, float boost)
throws IOException {
- while (sourceQuery instanceof BoostQuery) {
- BoostQuery bq = (BoostQuery) sourceQuery;
+ while (sourceQuery instanceof BoostQuery bq) {
sourceQuery = bq.getQuery();
boost *= bq.getBoost();
}
- if (sourceQuery instanceof BooleanQuery) {
- BooleanQuery bq = (BooleanQuery) sourceQuery;
+ if (sourceQuery instanceof BooleanQuery bq) {
for (BooleanClause clause : bq) {
if (!clause.isProhibited()) {
flatten(clause.query(), searcher, flatQueries, boost);
}
}
- } else if (sourceQuery instanceof DisjunctionMaxQuery) {
- DisjunctionMaxQuery dmq = (DisjunctionMaxQuery) sourceQuery;
+ } else if (sourceQuery instanceof DisjunctionMaxQuery dmq) {
for (Query query : dmq) {
flatten(query, searcher, flatQueries, boost);
}
@@ -127,13 +123,11 @@ public class FieldQuery {
sourceQuery = new BoostQuery(sourceQuery, boost);
}
if (!flatQueries.contains(sourceQuery)) flatQueries.add(sourceQuery);
- } else if (sourceQuery instanceof SynonymQuery) {
- SynonymQuery synQuery = (SynonymQuery) sourceQuery;
+ } else if (sourceQuery instanceof SynonymQuery synQuery) {
for (Term term : synQuery.getTerms()) {
flatten(new TermQuery(term), searcher, flatQueries, boost);
}
- } else if (sourceQuery instanceof PhraseQuery) {
- PhraseQuery pq = (PhraseQuery) sourceQuery;
+ } else if (sourceQuery instanceof PhraseQuery pq) {
if (pq.getTerms().length == 1) sourceQuery = new TermQuery(pq.getTerms()[0]);
if (boost != 1f) {
sourceQuery = new BoostQuery(sourceQuery, boost);
@@ -150,16 +144,15 @@ public class FieldQuery {
flatten(q, searcher, flatQueries, boost);
}
} else if (searcher != null) {
- Query query = sourceQuery;
Query rewritten;
if (sourceQuery instanceof MultiTermQuery) {
rewritten =
new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(MAX_MTQ_TERMS)
- .rewrite(searcher, (MultiTermQuery) query);
+ .rewrite(searcher, (MultiTermQuery) sourceQuery);
} else {
- rewritten = query.rewrite(searcher);
+ rewritten = sourceQuery.rewrite(searcher);
}
- if (rewritten != query) {
+ if (rewritten != sourceQuery) {
// only rewrite once and then flatten again - the rewritten query could have a speacial
// treatment
// if this method is overwritten in a subclass.
@@ -287,8 +280,7 @@ public class FieldQuery {
query = ((BoostQuery) query).getQuery();
}
if (query instanceof TermQuery) return ((TermQuery) query).getTerm().field();
- else if (query instanceof PhraseQuery) {
- PhraseQuery pq = (PhraseQuery) query;
+ else if (query instanceof PhraseQuery pq) {
Term[] terms = pq.getTerms();
return terms[0].field();
} else if (query instanceof MultiTermQuery) {
@@ -413,8 +405,7 @@ public class FieldQuery {
}
if (query instanceof TermQuery) {
addTerm(((TermQuery) query).getTerm(), boost);
- } else if (query instanceof PhraseQuery) {
- PhraseQuery pq = (PhraseQuery) query;
+ } else if (query instanceof PhraseQuery pq) {
Term[] terms = pq.getTerms();
Map<String, QueryPhraseMap> map = subMap;
QueryPhraseMap qpm = null;
diff --git a/lucene/luke/src/java/org/apache/lucene/luke/app/desktop/components/fragments/search/AnalyzerPaneProvider.java b/lucene/luke/src/java/org/apache/lucene/luke/app/desktop/components/fragments/search/AnalyzerPaneProvider.java
index d6c77c057a3..d195f0f4d42 100644
--- a/lucene/luke/src/java/org/apache/lucene/luke/app/desktop/components/fragments/search/AnalyzerPaneProvider.java
+++ b/lucene/luke/src/java/org/apache/lucene/luke/app/desktop/components/fragments/search/AnalyzerPaneProvider.java
@@ -170,9 +170,7 @@ public final class AnalyzerPaneProvider implements AnalyzerTabOperator {
public void setAnalyzer(Analyzer analyzer) {
analyzerNameLbl.setText(analyzer.getClass().getName());
- if (analyzer instanceof CustomAnalyzer) {
- CustomAnalyzer customAnalyzer = (CustomAnalyzer) analyzer;
-
+ if (analyzer instanceof CustomAnalyzer customAnalyzer) {
DefaultListModel<String> charFilterListModel = new DefaultListModel<>();
customAnalyzer.getCharFilterFactories().stream()
.map(f -> f.getClass().getSimpleName())
diff --git a/lucene/luke/src/java/org/apache/lucene/luke/models/LukeModel.java b/lucene/luke/src/java/org/apache/lucene/luke/models/LukeModel.java
index d0968039718..4a3de97e269 100644
--- a/lucene/luke/src/java/org/apache/lucene/luke/models/LukeModel.java
+++ b/lucene/luke/src/java/org/apache/lucene/luke/models/LukeModel.java
@@ -44,8 +44,7 @@ public abstract class LukeModel {
protected LukeModel(IndexReader reader) {
this.reader = Objects.requireNonNull(reader);
- if (reader instanceof DirectoryReader) {
- DirectoryReader dr = (DirectoryReader) reader;
+ if (reader instanceof DirectoryReader dr) {
this.dir = dr.directory();
try {
this.commit = dr.getIndexCommit();
diff --git a/lucene/luke/src/java/org/apache/lucene/luke/models/analysis/AnalysisImpl.java b/lucene/luke/src/java/org/apache/lucene/luke/models/analysis/AnalysisImpl.java
index 9a70acc7c36..28de7e57d06 100644
--- a/lucene/luke/src/java/org/apache/lucene/luke/models/analysis/AnalysisImpl.java
+++ b/lucene/luke/src/java/org/apache/lucene/luke/models/analysis/AnalysisImpl.java
@@ -52,6 +52,7 @@ public final class AnalysisImpl implements Analysis {
private Analyzer analyzer = defaultAnalyzer();
+ @SuppressWarnings("BanClassLoader")
@Override
public void addExternalJars(List<String> jarFiles) {
List<URL> urls = new ArrayList<>();
diff --git a/lucene/misc/src/java/org/apache/lucene/misc/util/fst/UpToTwoPositiveIntOutputs.java b/lucene/misc/src/java/org/apache/lucene/misc/util/fst/UpToTwoPositiveIntOutputs.java
index c7e2da71552..d606ae1c009 100644
--- a/lucene/misc/src/java/org/apache/lucene/misc/util/fst/UpToTwoPositiveIntOutputs.java
+++ b/lucene/misc/src/java/org/apache/lucene/misc/util/fst/UpToTwoPositiveIntOutputs.java
@@ -119,8 +119,7 @@ public final class UpToTwoPositiveIntOutputs extends Outputs<Object> {
assert valid(_prefix, false);
assert valid(_output, true);
final Long prefix = (Long) _prefix;
- if (_output instanceof Long) {
- final Long output = (Long) _output;
+ if (_output instanceof Long output) {
if (prefix == NO_OUTPUT) {
return output;
} else if (output == NO_OUTPUT) {
@@ -138,8 +137,7 @@ public final class UpToTwoPositiveIntOutputs extends Outputs<Object> {
@Override
public void write(Object _output, DataOutput out) throws IOException {
assert valid(_output, true);
- if (_output instanceof Long) {
- final Long output = (Long) _output;
+ if (_output instanceof Long output) {
out.writeVLong(output << 1);
} else {
final TwoLongs output = (TwoLongs) _output;
diff --git a/lucene/misc/src/test/org/apache/lucene/misc/util/fst/TestFSTsMisc.java b/lucene/misc/src/test/org/apache/lucene/misc/util/fst/TestFSTsMisc.java
index 5d10c6a4911..7c7c7977dc8 100644
--- a/lucene/misc/src/test/org/apache/lucene/misc/util/fst/TestFSTsMisc.java
+++ b/lucene/misc/src/test/org/apache/lucene/misc/util/fst/TestFSTsMisc.java
@@ -112,14 +112,11 @@ public class TestFSTsMisc extends LuceneTestCase {
new FSTTester<Object>(random(), dir, inputMode, pairs, outputs) {
@Override
protected boolean outputsEqual(Object output1, Object output2) {
- if (output1 instanceof TwoLongs && output2 instanceof List) {
- TwoLongs twoLongs1 = (TwoLongs) output1;
- return Arrays.asList(new Long[] {twoLongs1.first(), twoLongs1.second()})
- .equals(output2);
- } else if (output2 instanceof TwoLongs && output1 instanceof List) {
- TwoLongs twoLongs2 = (TwoLongs) output2;
- return Arrays.asList(new Long[] {twoLongs2.first(), twoLongs2.second()})
- .equals(output1);
+ if (output1 instanceof TwoLongs(long first, long second) && output2 instanceof List) {
+ return Arrays.asList(first, second).equals(output2);
+ } else if (output2 instanceof TwoLongs(long first, long second)
+ && output1 instanceof List) {
+ return Arrays.asList(first, second).equals(output1);
}
return output1.equals(output2);
}
diff --git a/lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java b/lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java
index 11319be44d9..e2d47fdedac 100644
--- a/lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java
+++ b/lucene/monitor/src/java/org/apache/lucene/monitor/QueryAnalyzer.java
@@ -81,8 +81,7 @@ class QueryAnalyzer {
}
if (occur == BooleanClause.Occur.MUST_NOT) {
// Check if we're in a pure negative disjunction
- if (parent instanceof BooleanQuery) {
- BooleanQuery bq = (BooleanQuery) parent;
+ if (parent instanceof BooleanQuery bq) {
long positiveCount =
bq.clauses().stream().filter(c -> c.occur() != BooleanClause.Occur.MUST_NOT).count();
if (positiveCount == 0) {
@@ -93,8 +92,7 @@ class QueryAnalyzer {
}
// It's a disjunction clause. If the parent has MUST or FILTER clauses, we can
// ignore it
- if (parent instanceof BooleanQuery) {
- BooleanQuery bq = (BooleanQuery) parent;
+ if (parent instanceof BooleanQuery bq) {
long requiredCount =
bq.clauses().stream()
.filter(
diff --git a/lucene/monitor/src/java/org/apache/lucene/monitor/WritableQueryIndex.java b/lucene/monitor/src/java/org/apache/lucene/monitor/WritableQueryIndex.java
index 69ab393b9bf..791bf0edde6 100644
--- a/lucene/monitor/src/java/org/apache/lucene/monitor/WritableQueryIndex.java
+++ b/lucene/monitor/src/java/org/apache/lucene/monitor/WritableQueryIndex.java
@@ -242,7 +242,7 @@ class WritableQueryIndex extends QueryIndex {
}
@Override
- /**
+ /*
* Remove unused queries from the query cache.
*
* <p>This is normally called from a background thread at a rate set by configurePurgeFrequency().
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/intervals/TestIntervals.java b/lucene/queries/src/test/org/apache/lucene/queries/intervals/TestIntervals.java
index 3d9560858ac..19a16063531 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/intervals/TestIntervals.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/intervals/TestIntervals.java
@@ -700,6 +700,7 @@ public class TestIntervals extends LuceneTestCase {
assertEquals(2, source.minExtent());
}
+ @SuppressWarnings("SelfAssertion")
public void testMaxGaps() throws IOException {
IntervalsSource source =
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
index 07e1b75cbd8..7e5db828c6d 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/MultiFieldQueryParser.java
@@ -118,9 +118,7 @@ public class MultiFieldQueryParser extends QueryParser {
builder.add(terms[i], positions[i]);
}
q = builder.build();
- } else if (q instanceof MultiPhraseQuery) {
- MultiPhraseQuery mpq = (MultiPhraseQuery) q;
-
+ } else if (q instanceof MultiPhraseQuery mpq) {
if (slop != mpq.getSlop()) {
q = new MultiPhraseQuery.Builder(mpq).setSlop(slop).build();
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
index 20aae1e9f2d..e818ffecab2 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java
@@ -482,9 +482,7 @@ public abstract class QueryParserBase extends QueryBuilder
if (query instanceof PhraseQuery) {
query = addSlopToPhrase((PhraseQuery) query, slop);
- } else if (query instanceof MultiPhraseQuery) {
- MultiPhraseQuery mpq = (MultiPhraseQuery) query;
-
+ } else if (query instanceof MultiPhraseQuery mpq) {
if (slop != mpq.getSlop()) {
query = new MultiPhraseQuery.Builder(mpq).setSlop(slop).build();
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
index 18476f50c2b..dbef2f47ea6 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/complexPhrase/ComplexPhraseQueryParser.java
@@ -315,8 +315,7 @@ public class ComplexPhraseQueryParser extends QueryParser {
new SpanTermQuery(
new Term(field, "Dummy clause because no terms found - must match nothing"));
} else {
- if (qc instanceof TermQuery) {
- TermQuery tq = (TermQuery) qc;
+ if (qc instanceof TermQuery tq) {
allSpanClauses[i] = new SpanTermQuery(tq.getTerm());
} else {
throw new IllegalArgumentException(
@@ -389,12 +388,10 @@ public class ComplexPhraseQueryParser extends QueryParser {
chosenList = nots;
}
- if (childQuery instanceof TermQuery) {
- TermQuery tq = (TermQuery) childQuery;
+ if (childQuery instanceof TermQuery tq) {
SpanQuery stq = new SpanTermQuery(tq.getTerm());
chosenList.add(stq);
- } else if (childQuery instanceof BooleanQuery) {
- BooleanQuery cbq = (BooleanQuery) childQuery;
+ } else if (childQuery instanceof BooleanQuery cbq) {
addComplexPhraseClause(chosenList, cbq);
} else if (childQuery instanceof MatchNoDocsQuery) {
// Insert fake term e.g. phrase query was for "Fred Smithe*" and
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/AllowLeadingWildcardProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/AllowLeadingWildcardProcessor.java
index 43aaddb74a5..cb6dbedbd27 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/AllowLeadingWildcardProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/AllowLeadingWildcardProcessor.java
@@ -60,11 +60,8 @@ public class AllowLeadingWildcardProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof WildcardQueryNode) {
- WildcardQueryNode wildcardNode = (WildcardQueryNode) node;
-
- if (wildcardNode.getText().length() > 0) {
-
+ if (node instanceof WildcardQueryNode wildcardNode) {
+ if (!wildcardNode.getText().isEmpty()) {
// Validate if the wildcard was escaped
if (UnescapedCharSequence.wasEscaped(wildcardNode.getText(), 0)) return node;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanQuery2ModifierNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanQuery2ModifierNodeProcessor.java
index f7186c1ab62..5057874529e 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanQuery2ModifierNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanQuery2ModifierNodeProcessor.java
@@ -159,8 +159,7 @@ public class BooleanQuery2ModifierNodeProcessor implements QueryNodeProcessor {
}
protected void tagModifierButDoNotOverride(QueryNode node, Modifier mod) {
- if (node instanceof ModifierQueryNode) {
- ModifierQueryNode modNode = (ModifierQueryNode) node;
+ if (node instanceof ModifierQueryNode modNode) {
if (modNode.getModifier() == Modifier.MOD_NONE) {
node.setTag(TAG_MODIFIER, mod);
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanSingleChildOptimizationQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanSingleChildOptimizationQueryNodeProcessor.java
index 8a5bb1791dd..dcc16a9620f 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanSingleChildOptimizationQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BooleanSingleChildOptimizationQueryNodeProcessor.java
@@ -47,9 +47,7 @@ public class BooleanSingleChildOptimizationQueryNodeProcessor extends QueryNodeP
if (children != null && children.size() == 1) {
QueryNode child = children.get(0);
- if (child instanceof ModifierQueryNode) {
- ModifierQueryNode modNode = (ModifierQueryNode) child;
-
+ if (child instanceof ModifierQueryNode modNode) {
if (modNode instanceof BooleanModifierNode
|| modNode.getModifier() == Modifier.MOD_NONE) {
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BoostQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BoostQueryNodeProcessor.java
index ed6fa460798..508c1953a01 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BoostQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/BoostQueryNodeProcessor.java
@@ -41,10 +41,9 @@ public class BoostQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof FieldableNode
+ if (node instanceof FieldableNode fieldNode
&& (node.getParent() == null || !(node.getParent() instanceof FieldableNode))) {
- FieldableNode fieldNode = (FieldableNode) node;
QueryConfigHandler config = getQueryConfigHandler();
if (config != null) {
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/FuzzyQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/FuzzyQueryNodeProcessor.java
index 0d0730b23f5..c295418a720 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/FuzzyQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/FuzzyQueryNodeProcessor.java
@@ -48,8 +48,7 @@ public class FuzzyQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode preProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof FuzzyQueryNode) {
- FuzzyQueryNode fuzzyNode = (FuzzyQueryNode) node;
+ if (node instanceof FuzzyQueryNode fuzzyNode) {
QueryConfigHandler config = getQueryConfigHandler();
Analyzer analyzer = getQueryConfigHandler().get(ConfigurationKeys.ANALYZER);
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/IntervalQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/IntervalQueryNodeProcessor.java
index b4cf2caf7e8..1e0a963c92f 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/IntervalQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/IntervalQueryNodeProcessor.java
@@ -45,8 +45,7 @@ public class IntervalQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode preProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof IntervalQueryNode) {
- var intervalQueryNode = (IntervalQueryNode) node;
+ if (node instanceof IntervalQueryNode intervalQueryNode) {
if (this.analyzer == null) {
throw new QueryNodeException(
new MessageImpl(QueryParserMessages.ANALYZER_REQUIRED, intervalQueryNode.toString()));
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/MatchAllDocsQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/MatchAllDocsQueryNodeProcessor.java
index 7a95d8d00a4..3b3e6bb2d1d 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/MatchAllDocsQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/MatchAllDocsQueryNodeProcessor.java
@@ -41,11 +41,8 @@ public class MatchAllDocsQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof FieldQueryNode) {
- FieldQueryNode fqn = (FieldQueryNode) node;
-
+ if (node instanceof FieldQueryNode fqn) {
if (fqn.getField().toString().equals("*") && fqn.getText().toString().equals("*")) {
-
return new MatchAllDocsQueryNode();
}
}
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/OpenRangeQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/OpenRangeQueryNodeProcessor.java
index e328aef3b9c..3337f135f18 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/OpenRangeQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/OpenRangeQueryNodeProcessor.java
@@ -35,8 +35,7 @@ public class OpenRangeQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof TermRangeQueryNode) {
- TermRangeQueryNode rangeNode = (TermRangeQueryNode) node;
+ if (node instanceof TermRangeQueryNode rangeNode) {
FieldQueryNode lowerNode = rangeNode.getLowerBound();
FieldQueryNode upperNode = rangeNode.getUpperBound();
CharSequence lowerText = lowerNode.getText();
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/PhraseSlopQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/PhraseSlopQueryNodeProcessor.java
index cdda18e3dbd..2daae7efd43 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/PhraseSlopQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/PhraseSlopQueryNodeProcessor.java
@@ -40,9 +40,7 @@ public class PhraseSlopQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof SlopQueryNode) {
- SlopQueryNode phraseSlopNode = (SlopQueryNode) node;
-
+ if (node instanceof SlopQueryNode phraseSlopNode) {
if (!(phraseSlopNode.getChild() instanceof TokenizedPhraseQueryNode)
&& !(phraseSlopNode.getChild() instanceof MultiPhraseQueryNode)) {
return phraseSlopNode.getChild();
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/RegexpQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/RegexpQueryNodeProcessor.java
index afe676b007b..afc15ddda5c 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/RegexpQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/RegexpQueryNodeProcessor.java
@@ -34,8 +34,7 @@ public class RegexpQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof RegexpQueryNode) {
- RegexpQueryNode regexpNode = (RegexpQueryNode) node;
+ if (node instanceof RegexpQueryNode regexpNode) {
Analyzer analyzer = getQueryConfigHandler().get(ConfigurationKeys.ANALYZER);
if (analyzer != null) {
String text = regexpNode.getText().toString();
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/TermRangeQueryNodeProcessor.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/TermRangeQueryNodeProcessor.java
index cd58ffe2e60..6a893001559 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/TermRangeQueryNodeProcessor.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/processors/TermRangeQueryNodeProcessor.java
@@ -59,8 +59,7 @@ public class TermRangeQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof TermRangeQueryNode) {
- TermRangeQueryNode termRangeNode = (TermRangeQueryNode) node;
+ if (node instanceof TermRangeQueryNode termRangeNode) {
FieldQueryNode upper = termRangeNode.getUpperBound();
FieldQueryNode lower = termRangeNode.getLowerBound();
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
index e930295d7c3..4015778261d 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/query/DistanceQuery.java
@@ -51,8 +51,7 @@ public class DistanceQuery extends ComposedQuery implements DistanceSubQuery {
Iterator<?> sqi = getSubQueriesIterator();
while (sqi.hasNext()) {
Object leq = sqi.next();
- if (leq instanceof DistanceSubQuery) {
- DistanceSubQuery dsq = (DistanceSubQuery) leq;
+ if (leq instanceof DistanceSubQuery dsq) {
String m = dsq.distanceSubQueryNotAllowed();
if (m != null) {
return m;
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/DOMUtils.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/DOMUtils.java
index 20a2a0f9560..2ce342e17d8 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/DOMUtils.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/DOMUtils.java
@@ -91,8 +91,7 @@ public class DOMUtils {
if ((n == element) || (n == null)) {
return null;
}
- if (n instanceof Element) {
- Element parent = (Element) n;
+ if (n instanceof Element parent) {
return getAttributeWithInheritance(parent, attributeName);
}
return null; // we reached the top level of the document without finding attribute
diff --git a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
index 62dd72d83cf..ec4ac8122a5 100644
--- a/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
+++ b/lucene/queryparser/src/java/org/apache/lucene/queryparser/xml/builders/DisjunctionMaxQueryBuilder.java
@@ -50,8 +50,7 @@ public class DisjunctionMaxQueryBuilder implements QueryBuilder {
final int nlLen = nl.getLength();
for (int i = 0; i < nlLen; i++) {
Node node = nl.item(i);
- if (node instanceof Element) { // all elements are disjuncts.
- Element queryElem = (Element) node;
+ if (node instanceof Element queryElem) { // all elements are disjuncts.
Query q = factory.getQuery(queryElem);
disjuncts.add(q);
}
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
index 3c8f5a39b09..3a891e2d0e4 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java
@@ -328,7 +328,7 @@ public class TestQueryParser extends QueryParserTestBase {
@Override
public void testNewFieldQuery() throws Exception {
- /** ordinary behavior, synonyms form uncoordinated boolean query */
+ /* ordinary behavior, synonyms form uncoordinated boolean query */
QueryParser dumb = new QueryParser(FIELD, new Analyzer1());
Query expanded =
new SynonymQuery.Builder(FIELD)
@@ -336,10 +336,10 @@ public class TestQueryParser extends QueryParserTestBase {
.addTerm(new Term(FIELD, "dog"))
.build();
assertEquals(expanded, dumb.parse("\"dogs\""));
- /** even with the phrase operator the behavior is the same */
+ /* even with the phrase operator the behavior is the same */
assertEquals(expanded, dumb.parse("dogs"));
- /** custom behavior, the synonyms are expanded, unless you use quote operator */
+ /* custom behavior, the synonyms are expanded, unless you use quote operator */
QueryParser smart = new SmartQueryParser();
assertEquals(expanded, smart.parse("dogs"));
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/UniqueFieldQueryNodeProcessor.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/UniqueFieldQueryNodeProcessor.java
index e7a4a73370a..72a29859e93 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/UniqueFieldQueryNodeProcessor.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/UniqueFieldQueryNodeProcessor.java
@@ -42,9 +42,7 @@ public class UniqueFieldQueryNodeProcessor extends QueryNodeProcessorImpl {
@Override
protected QueryNode preProcessNode(QueryNode node) throws QueryNodeException {
- if (node instanceof FieldableNode) {
- FieldableNode fieldNode = (FieldableNode) node;
-
+ if (node instanceof FieldableNode fieldNode) {
QueryConfigHandler queryConfig = getQueryConfigHandler();
if (queryConfig == null) {
diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java
index 74612d6d9f9..2e91b3cffd5 100644
--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java
+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java
@@ -166,16 +166,16 @@ public class TestStandardQP extends QueryParserTestBase {
@Override
public void testNewFieldQuery() throws Exception {
- /** ordinary behavior, synonyms form uncoordinated boolean query */
+ /* ordinary behavior, synonyms form uncoordinated boolean query */
StandardQueryParser dumb = getParser(new Analyzer1());
BooleanQuery.Builder expanded = new BooleanQuery.Builder();
expanded.add(new TermQuery(new Term("field", "dogs")), BooleanClause.Occur.SHOULD);
expanded.add(new TermQuery(new Term("field", "dog")), BooleanClause.Occur.SHOULD);
assertEquals(expanded.build(), dumb.parse("\"dogs\"", "field"));
- /** even with the phrase operator the behavior is the same */
+ /* even with the phrase operator the behavior is the same */
assertEquals(expanded.build(), dumb.parse("dogs", "field"));
- /** custom behavior, the synonyms are expanded, unless you use quote operator */
+ /* custom behavior, the synonyms are expanded, unless you use quote operator */
// TODO test something like "SmartQueryParser()"
}
diff --git a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/PreCopyMergedSegmentWarmer.java b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/PreCopyMergedSegmentWarmer.java
index e3e42224ecf..2c2b27b2d35 100644
--- a/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/PreCopyMergedSegmentWarmer.java
+++ b/lucene/replicator/src/java/org/apache/lucene/replicator/nrt/PreCopyMergedSegmentWarmer.java
@@ -17,11 +17,6 @@
package org.apache.lucene.replicator.nrt;
-/**
- * A merged segment warmer that pre-copies the merged segment out to replicas before primary cuts
- * over to the merged segment. This ensures that NRT reopen time on replicas is only in proportion
- * to flushed segment sizes, not merged segments.
- */
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
@@ -35,6 +30,11 @@ import org.apache.lucene.index.SegmentReader;
// TODO: or ... replica node can do merging locally? tricky to keep things in sync, when one node
// merges more slowly than others...
+/**
+ * A merged segment warmer that pre-copies the merged segment out to replicas before primary cuts
+ * over to the merged segment. This ensures that NRT reopen time on replicas is only in proportion
+ * to flushed segment sizes, not merged segments.
+ */
class PreCopyMergedSegmentWarmer implements IndexReaderWarmer {
private final PrimaryNode primary;
diff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimplePrimaryNode.java b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimplePrimaryNode.java
index c05f5e028a0..be42a2c62e5 100644
--- a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimplePrimaryNode.java
+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/SimplePrimaryNode.java
@@ -161,11 +161,9 @@ class SimplePrimaryNode extends PrimaryNode {
// iwc.setInfoStream(new PrintStreamInfoStream(System.out));
// Force more frequent merging so we stress merge warming:
- if (mp instanceof TieredMergePolicy) {
- TieredMergePolicy tmp = (TieredMergePolicy) mp;
+ if (mp instanceof TieredMergePolicy tmp) {
tmp.setSegmentsPerTier(3);
- } else if (mp instanceof LogMergePolicy) {
- LogMergePolicy lmp = (LogMergePolicy) mp;
+ } else if (mp instanceof LogMergePolicy lmp) {
lmp.setMergeFactor(3);
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/payloads/PayloadSpanUtil.java b/lucene/sandbox/src/java/org/apache/lucene/payloads/PayloadSpanUtil.java
index 1631291b9ff..7d41fae5a1d 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/payloads/PayloadSpanUtil.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/payloads/PayloadSpanUtil.java
@@ -107,8 +107,7 @@ public class PayloadSpanUtil {
queryToSpanQuery(iterator.next(), payloads);
}
- } else if (query instanceof MultiPhraseQuery) {
- final MultiPhraseQuery mpq = (MultiPhraseQuery) query;
+ } else if (query instanceof MultiPhraseQuery mpq) {
final Term[][] termArrays = mpq.getTermArrays();
final int[] positions = mpq.getPositions();
if (positions.length > 0) {
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/MultiRangeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/MultiRangeQuery.java
index 66c490b791a..d75d9e9e7d8 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/MultiRangeQuery.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/MultiRangeQuery.java
@@ -226,7 +226,7 @@ public abstract class MultiRangeQuery extends Query implements Cloneable {
}
}
finalRangeClause.add(current);
- /**
+ /*
* in {@link #rewrite} it compares the returned rangeClauses with origin rangeClauses to decide
* if rewrite should return a new query or the origin query
*/
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/WithinPrefixTreeQuery.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/WithinPrefixTreeQuery.java
index daad6e2b591..4e7ed1571dd 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/WithinPrefixTreeQuery.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/WithinPrefixTreeQuery.java
@@ -116,8 +116,7 @@ public class WithinPrefixTreeQuery extends AbstractVisitingPrefixTreeQuery {
SpatialContext ctx = grid.getSpatialContext();
if (shape instanceof Point) {
return ctx.getShapeFactory().circle((Point) shape, distErr);
- } else if (shape instanceof Circle) {
- Circle circle = (Circle) shape;
+ } else if (shape instanceof Circle circle) {
double newDist = circle.getRadius() + distErr;
if (ctx.isGeo() && newDist > 180) {
newDist = 180;
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/DateRangePrefixTree.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/DateRangePrefixTree.java
index ca8f85b0211..dddf39dd7bc 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/DateRangePrefixTree.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/DateRangePrefixTree.java
@@ -158,8 +158,7 @@ public class DateRangePrefixTree extends NumberRangePrefixTree {
maxLV = toShape((Calendar) MAXCAL.clone());
minLV = toShape((Calendar) MINCAL.clone());
- if (MAXCAL instanceof GregorianCalendar) {
- GregorianCalendar gCal = (GregorianCalendar) MAXCAL;
+ if (MAXCAL instanceof GregorianCalendar gCal) {
gregorianChangeDateLV = toUnitShape(gCal.getGregorianChange());
} else {
gregorianChangeDateLV = null;
@@ -174,8 +173,9 @@ public class DateRangePrefixTree extends NumberRangePrefixTree {
public int getNumSubCells(UnitNRShape lv) {
int cmp = comparePrefix(lv, maxLV);
assert cmp <= 0;
- if (cmp == 0) // edge case (literally!)
- return maxLV.getValAtLevel(lv.getLevel() + 1) + 1;
+ if (cmp == 0) { // edge case (literally!)
+ return maxLV.getValAtLevel(lv.getLevel() + 1) + 1;
+ }
// if using GregorianCalendar and we're after the "Gregorian change date" then we'll compute
// the sub-cells ourselves more efficiently without the need to construct a Calendar.
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/LegacyCell.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/LegacyCell.java
index 8ffb2c852f4..5f9dd563e09 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/LegacyCell.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/LegacyCell.java
@@ -225,8 +225,7 @@ public abstract class LegacyCell implements CellCanPrune {
@Override
public boolean equals(Object obj) {
// this method isn't "normally" called; just in asserts/tests
- if (obj instanceof Cell) {
- Cell cell = (Cell) obj;
+ if (obj instanceof Cell cell) {
return getTokenBytesWithLeaf(null).equals(cell.getTokenBytesWithLeaf(null));
} else {
return false;
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/S2PrefixTreeCell.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/S2PrefixTreeCell.java
index 2bcd6c23490..4651bea8515 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/S2PrefixTreeCell.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/prefix/tree/S2PrefixTreeCell.java
@@ -278,7 +278,7 @@ class S2PrefixTreeCell implements CellCanPrune {
@Override
public int hashCode() {
if (cellId == null) {
- return super.hashCode();
+ return System.identityHashCode(this);
}
return this.cellId.hashCode();
}
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/spatial4j/Geo3dBinaryCodec.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/spatial4j/Geo3dBinaryCodec.java
index 2ccb5d3d9f0..8ea3d62e873 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/spatial4j/Geo3dBinaryCodec.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/spatial4j/Geo3dBinaryCodec.java
@@ -44,7 +44,7 @@ import org.locationtech.spatial4j.shape.ShapeCollection;
*/
public class Geo3dBinaryCodec extends BinaryCodec {
- private PlanetModel planetModel;
+ private final PlanetModel planetModel;
public Geo3dBinaryCodec(SpatialContext ctx, SpatialContextFactory factory) {
super(ctx, factory);
@@ -55,8 +55,7 @@ public class Geo3dBinaryCodec extends BinaryCodec {
public Shape readShape(DataInput dataInput) throws IOException {
SerializableObject serializableObject =
SerializableObject.readObject(planetModel, (InputStream) dataInput);
- if (serializableObject instanceof GeoAreaShape) {
- GeoAreaShape shape = (GeoAreaShape) serializableObject;
+ if (serializableObject instanceof GeoAreaShape shape) {
return new Geo3dShape<>(shape, ctx);
}
throw new IllegalArgumentException(
@@ -65,8 +64,7 @@ public class Geo3dBinaryCodec extends BinaryCodec {
@Override
public void writeShape(DataOutput dataOutput, Shape s) throws IOException {
- if (s instanceof Geo3dShape) {
- Geo3dShape<?> geoAreaShape = (Geo3dShape<?>) s;
+ if (s instanceof Geo3dShape<?> geoAreaShape) {
SerializableObject.writeObject((OutputStream) dataOutput, geoAreaShape.shape);
} else {
throw new IllegalArgumentException(
@@ -78,8 +76,7 @@ public class Geo3dBinaryCodec extends BinaryCodec {
public Point readPoint(DataInput dataInput) throws IOException {
SerializableObject serializableObject =
SerializableObject.readObject(planetModel, (InputStream) dataInput);
- if (serializableObject instanceof GeoPointShape) {
- GeoPointShape shape = (GeoPointShape) serializableObject;
+ if (serializableObject instanceof GeoPointShape shape) {
return new Geo3dPointShape(shape, ctx);
}
throw new IllegalArgumentException(
@@ -95,8 +92,7 @@ public class Geo3dBinaryCodec extends BinaryCodec {
public Rectangle readRect(DataInput dataInput) throws IOException {
SerializableObject serializableObject =
SerializableObject.readObject(planetModel, (InputStream) dataInput);
- if (serializableObject instanceof GeoBBox) {
- GeoBBox shape = (GeoBBox) serializableObject;
+ if (serializableObject instanceof GeoBBox shape) {
return new Geo3dRectangleShape(shape, ctx);
}
throw new IllegalArgumentException(
@@ -112,8 +108,7 @@ public class Geo3dBinaryCodec extends BinaryCodec {
public Circle readCircle(DataInput dataInput) throws IOException {
SerializableObject serializableObject =
SerializableObject.readObject(planetModel, (InputStream) dataInput);
- if (serializableObject instanceof GeoCircle) {
- GeoCircle shape = (GeoCircle) serializableObject;
+ if (serializableObject instanceof GeoCircle shape) {
return new Geo3dCircleShape(shape, ctx);
}
throw new IllegalArgumentException(
diff --git a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java
index 13b9c10f18a..0d377bec6c0 100644
--- a/lucene/spatial-extras/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java
+++ b/lucene/spatial-extras/src/java/org/apache/lucene/spatial/vector/PointVectorStrategy.java
@@ -187,11 +187,9 @@ public class PointVectorStrategy extends SpatialStrategy {
args.getOperation(), SpatialOperation.Intersects, SpatialOperation.IsWithin))
throw new UnsupportedSpatialOperation(args.getOperation());
Shape shape = args.getShape();
- if (shape instanceof Rectangle) {
- Rectangle bbox = (Rectangle) shape;
+ if (shape instanceof Rectangle bbox) {
return new ConstantScoreQuery(makeWithin(bbox));
- } else if (shape instanceof Circle) {
- Circle circle = (Circle) shape;
+ } else if (shape instanceof Circle circle) {
Rectangle bbox = circle.getBoundingBox();
return new DistanceRangeQuery(
makeWithin(bbox), makeDistanceValueSource(circle.getCenter()), circle.getRadius());
diff --git a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
index bd6ae9fa5b3..ba7f0e8c8cd 100644
--- a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
+++ b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/RandomSpatialOpStrategyTestCase.java
@@ -136,8 +136,7 @@ public abstract class RandomSpatialOpStrategyTestCase extends StrategyTestCase {
}
protected void preQueryHavoc() {
- if (strategy instanceof RecursivePrefixTreeStrategy) {
- RecursivePrefixTreeStrategy rpts = (RecursivePrefixTreeStrategy) strategy;
+ if (strategy instanceof RecursivePrefixTreeStrategy rpts) {
int scanLevel = randomIntBetween(0, rpts.getGrid().getMaxLevels());
rpts.setPrefixGridScanLevel(scanLevel);
}
diff --git a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestJtsPolygon.java b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestJtsPolygon.java
index 6298277fcb4..62099e90545 100644
--- a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestJtsPolygon.java
+++ b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestJtsPolygon.java
@@ -59,7 +59,7 @@ public class TestJtsPolygon extends StrategyTestCase {
}
@Test
- /** LUCENE-4464 */
+ /* LUCENE-4464 */
public void testCloseButNoMatch() throws Exception {
getAddAndVerifyIndexedDocuments("LUCENE-4464.txt");
SpatialArgs args =
diff --git a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestNumberRangeFacets.java b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestNumberRangeFacets.java
index 97e66dd5abe..168319f0f33 100644
--- a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestNumberRangeFacets.java
+++ b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestNumberRangeFacets.java
@@ -221,8 +221,7 @@ public class TestNumberRangeFacets extends StrategyTestCase {
}
private void preQueryHavoc() {
- if (strategy instanceof RecursivePrefixTreeStrategy) {
- RecursivePrefixTreeStrategy rpts = (RecursivePrefixTreeStrategy) strategy;
+ if (strategy instanceof RecursivePrefixTreeStrategy rpts) {
int scanLevel = randomIntBetween(0, rpts.getGrid().getMaxLevels());
rpts.setPrefixGridScanLevel(scanLevel);
}
diff --git a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestRandomSpatialOpFuzzyPrefixTree.java b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestRandomSpatialOpFuzzyPrefixTree.java
index 3dc3dc46e75..d7780430730 100644
--- a/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestRandomSpatialOpFuzzyPrefixTree.java
+++ b/lucene/spatial-extras/src/test/org/apache/lucene/spatial/prefix/TestRandomSpatialOpFuzzyPrefixTree.java
@@ -211,7 +211,7 @@ public class TestRandomSpatialOpFuzzyPrefixTree extends StrategyTestCase {
}
@Test
- /** LUCENE-4916 */
+ /* LUCENE-4916 */
public void testWithinLeafApproxRule() throws IOException {
setupQuadGrid(2, randomBoolean()); // 4x4 grid
// indexed shape will simplify to entire right half (2 top cells)
@@ -459,8 +459,7 @@ public class TestRandomSpatialOpFuzzyPrefixTree extends StrategyTestCase {
protected Shape gridSnap(Shape snapMe) {
if (snapMe == null) return null;
- if (snapMe instanceof ShapePair) {
- ShapePair me = (ShapePair) snapMe;
+ if (snapMe instanceof ShapePair me) {
return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin);
}
if (snapMe instanceof Point) {
@@ -505,8 +504,7 @@ public class TestRandomSpatialOpFuzzyPrefixTree extends StrategyTestCase {
private Shape toNonGeo(Shape shape) {
if (!ctx.isGeo()) return shape; // already non-geo
- if (shape instanceof Rectangle) {
- Rectangle rect = (Rectangle) shape;
+ if (shape instanceof Rectangle rect) {
if (rect.getCrossesDateLine()) {
return new ShapePair(
ctx2D.makeRectangle(rect.getMinX(), 180, rect.getMinY(), rect.getMaxY()),
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/BlendedInfixSuggester.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/BlendedInfixSuggester.java
index 46378032317..bce597530e9 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/BlendedInfixSuggester.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/BlendedInfixSuggester.java
@@ -195,7 +195,7 @@ public class BlendedInfixSuggester extends AnalyzingInfixSuggester {
boolean allTermsRequired,
boolean doHighlight)
throws IOException {
- /** We need to do num * numFactor here only because it is the last call in the lookup chain */
+ /* We need to do num * numFactor here only because it is the last call in the lookup chain */
return super.lookup(key, contextQuery, num * numFactor, allTermsRequired, doHighlight);
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
index 8db16c194a7..121451536cd 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionQuery.java
@@ -98,8 +98,7 @@ public abstract class CompletionQuery extends Query {
IOException e) {
continue;
}
- if (terms instanceof CompletionTerms) {
- CompletionTerms completionTerms = (CompletionTerms) terms;
+ if (terms instanceof CompletionTerms completionTerms) {
byte t = completionTerms.getType();
if (first) {
type = t;
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
index b4572c0c729..095517bd06a 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionWeight.java
@@ -107,8 +107,7 @@ public class CompletionWeight extends Weight {
if ((terms = reader.terms(completionQuery.getField())) == null) {
return null;
}
- if (terms instanceof CompletionTerms) {
- CompletionTerms completionTerms = (CompletionTerms) terms;
+ if (terms instanceof CompletionTerms completionTerms) {
if ((suggester = completionTerms.suggester()) == null) {
// a segment can have a null suggester
// i.e. no FST was built
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestBlendedInfixSuggester.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestBlendedInfixSuggester.java
index 93d47bc78bc..3ec2b48e159 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestBlendedInfixSuggester.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestBlendedInfixSuggester.java
@@ -307,7 +307,7 @@ public class TestBlendedInfixSuggester extends LuceneTestCase {
};
duplicateCheck(inputDocuments, 2);
- /**
+ /*
* same input, first not having a payload, the second having payload we would expect 2 entries
* out but we are getting only 1 because the InputArrayIterator#hasPayloads() returns false
* because the first item has no payload, therefore, when ingested, none of the 2 input has
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/analysis/Token.java b/lucene/test-framework/src/java/org/apache/lucene/tests/analysis/Token.java
index 193d57e82b2..7bc31122662 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/analysis/Token.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/analysis/Token.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.tests.analysis;
+import java.util.Objects;
import org.apache.lucene.analysis.tokenattributes.FlagsAttribute;
import org.apache.lucene.analysis.tokenattributes.PackedTokenAttributeImpl;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
@@ -144,11 +145,8 @@ public class Token extends PackedTokenAttributeImpl implements FlagsAttribute, P
public boolean equals(Object obj) {
if (obj == this) return true;
- if (obj instanceof Token) {
- final Token other = (Token) obj;
- return (flags == other.flags
- && (payload == null ? other.payload == null : payload.equals(other.payload))
- && super.equals(obj));
+ if (obj instanceof Token other) {
+ return (flags == other.flags && Objects.equals(payload, other.payload) && super.equals(obj));
} else return false;
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/geo/GeoTestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/tests/geo/GeoTestUtil.java
index 4b91a80373f..f9f03834b38 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/geo/GeoTestUtil.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/geo/GeoTestUtil.java
@@ -651,8 +651,7 @@ public class GeoTestUtil {
// encode each object
for (Object o : flattened) {
// tostring
- if (o instanceof double[]) {
- double[] point = (double[]) o;
+ if (o instanceof double[] point) {
sb.append("<!-- point: ");
sb.append(point[0]).append(',').append(point[1]);
sb.append(" -->\n");
@@ -668,8 +667,7 @@ public class GeoTestUtil {
gon = boxPolygon((Rectangle) o);
style = "fill:lightskyblue;stroke:black;stroke-width:0.2%;stroke-dasharray:0.5%,1%;";
opacity = "0.3";
- } else if (o instanceof double[]) {
- double[] point = (double[]) o;
+ } else if (o instanceof double[] point) {
gon =
boxPolygon(
new Rectangle(
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseMergePolicyTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseMergePolicyTestCase.java
index 6dee2ab7abc..64e7d33e35c 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseMergePolicyTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseMergePolicyTestCase.java
@@ -409,6 +409,7 @@ public abstract class BaseMergePolicyTestCase extends LuceneTestCase {
* Simulate an append-only use-case, ie. there are no deletes. {@code totalDocs} exist in the
* index in the end, and flushes contribute at most {@code maxDocsPerFlush} documents.
*/
+ @SuppressWarnings("UnnecessaryAsync")
protected void doTestSimulateAppendOnly(
MergePolicy mergePolicy, int totalDocs, int maxDocsPerFlush) throws IOException {
IOStats stats = new IOStats();
@@ -465,6 +466,7 @@ public abstract class BaseMergePolicyTestCase extends LuceneTestCase {
* totalDocs} exist in the index in the end, and flushes contribute at most {@code
* maxDocsPerFlush} documents.
*/
+ @SuppressWarnings("UnnecessaryAsync")
protected void doTestSimulateUpdates(MergePolicy mergePolicy, int totalDocs, int maxDocsPerFlush)
throws IOException {
IOStats stats = new IOStats();
@@ -532,6 +534,7 @@ public abstract class BaseMergePolicyTestCase extends LuceneTestCase {
long mergeBytesWritten;
}
+ @SuppressWarnings("UnnecessaryAsync")
public void testNoPathologicalMerges() throws IOException {
MergePolicy mergePolicy = mergePolicy();
IOStats stats = new IOStats();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseSegmentInfoFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseSegmentInfoFormatTestCase.java
index 1d65e3245dc..6a827f73a2d 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseSegmentInfoFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseSegmentInfoFormatTestCase.java
@@ -391,11 +391,7 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatT
for (int j = 0; j < numSortFields; ++j) {
sortFields[j] = randomIndexSortField();
}
- if (supportsHasBlocks()) {
- sort = new Sort(sortFields);
- } else {
- sort = new Sort(sortFields);
- }
+ sort = new Sort(sortFields);
}
Directory dir = newDirectory();
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTermVectorsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTermVectorsFormatTestCase.java
index 53df7671d85..7f27686d76a 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTermVectorsFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTermVectorsFormatTestCase.java
@@ -167,8 +167,7 @@ public abstract class BaseTermVectorsFormatTestCase extends BaseIndexFileFormatT
return true;
}
- if (other instanceof PermissiveOffsetAttributeImpl) {
- PermissiveOffsetAttributeImpl o = (PermissiveOffsetAttributeImpl) other;
+ if (other instanceof PermissiveOffsetAttributeImpl o) {
return o.start == start && o.end == end;
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterFileSystemProvider.java b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterFileSystemProvider.java
index 25833c3c59d..70693122bc2 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterFileSystemProvider.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterFileSystemProvider.java
@@ -258,8 +258,7 @@ public abstract class FilterFileSystemProvider extends FileSystemProvider {
}
protected Path toDelegate(Path path) {
- if (path instanceof FilterPath) {
- FilterPath fp = (FilterPath) path;
+ if (path instanceof FilterPath fp) {
if (fp.fileSystem != fileSystem) {
throw new ProviderMismatchException(
"mismatch, expected: "
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterPath.java b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterPath.java
index 3019c38c209..9f2ee15cbe1 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterPath.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/FilterPath.java
@@ -276,8 +276,7 @@ public class FilterPath implements Path, Unwrappable<Path> {
/** Override this to customize the unboxing of Path from various operations */
protected Path toDelegate(Path path) {
- if (path instanceof FilterPath) {
- FilterPath fp = (FilterPath) path;
+ if (path instanceof FilterPath fp) {
if (fp.fileSystem != fileSystem) {
throw new ProviderMismatchException(
"mismatch, expected: "
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/MockFileSystemTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/MockFileSystemTestCase.java
index f513581d734..d92fe491fb4 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/MockFileSystemTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/mockfile/MockFileSystemTestCase.java
@@ -38,6 +38,7 @@ public abstract class MockFileSystemTestCase extends LuceneTestCase {
protected abstract Path wrap(Path path);
/** Test that Path.hashcode/equals are sane */
+ @SuppressWarnings("SelfAssertion")
public void testHashCodeEquals() throws IOException {
Path dir = wrap(createTempDir());
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
index ff4eb908e9b..ecb522894e8 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/LuceneTestCase.java
@@ -587,7 +587,7 @@ public abstract class LuceneTestCase extends Assert {
ignoreAfterMaxFailures = TestRuleDelegate.of(ignoreAfterMaxFailuresDelegate);
}
- /**
+ /*
* Try to capture streams early so that other classes don't have a chance to steal references to
* them (as is the case with ju.logging handlers).
*/
@@ -1202,8 +1202,7 @@ public abstract class LuceneTestCase extends Assert {
if (rarely(r)) {
// change CMS merge parameters
MergeScheduler ms = c.getMergeScheduler();
- if (ms instanceof ConcurrentMergeScheduler) {
- ConcurrentMergeScheduler cms = (ConcurrentMergeScheduler) ms;
+ if (ms instanceof ConcurrentMergeScheduler cms) {
int maxThreadCount = TestUtil.nextInt(r, 1, 4);
int maxMergeCount = TestUtil.nextInt(r, maxThreadCount, maxThreadCount + 4);
boolean enableAutoIOThrottle = random().nextBoolean();
@@ -1220,16 +1219,14 @@ public abstract class LuceneTestCase extends Assert {
if (rarely(r)) {
MergePolicy mp = c.getMergePolicy();
configureRandom(r, mp);
- if (mp instanceof LogMergePolicy) {
- LogMergePolicy logmp = (LogMergePolicy) mp;
+ if (mp instanceof LogMergePolicy logmp) {
logmp.setCalibrateSizeByDeletes(r.nextBoolean());
if (rarely(r)) {
logmp.setMergeFactor(TestUtil.nextInt(r, 2, 9));
} else {
logmp.setMergeFactor(TestUtil.nextInt(r, 10, 50));
}
- } else if (mp instanceof TieredMergePolicy) {
- TieredMergePolicy tmp = (TieredMergePolicy) mp;
+ } else if (mp instanceof TieredMergePolicy tmp) {
if (rarely(r)) {
tmp.setMaxMergedSegmentMB(0.2 + r.nextDouble() * 2.0);
} else {
@@ -1694,8 +1691,7 @@ public abstract class LuceneTestCase extends Assert {
: new ParallelCompositeReader((CompositeReader) r);
break;
case 1:
- if (r instanceof LeafReader) {
- final LeafReader ar = (LeafReader) r;
+ if (r instanceof LeafReader ar) {
final List<String> allFields = new ArrayList<>();
for (FieldInfo fi : ar.getFieldInfos()) {
allFields.add(fi.name);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestRuleLimitSysouts.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestRuleLimitSysouts.java
index 87e000c531c..865b465a956 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestRuleLimitSysouts.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestRuleLimitSysouts.java
@@ -95,7 +95,7 @@ public class TestRuleLimitSysouts extends TestRuleAdapter {
private static final AtomicLong hardLimit;
- /**
+ /*
* We capture system output and error streams as early as possible because certain components
* (like the Java logging system) steal these references and never refresh them.
*
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
index c2f5d886e3c..b83b9265273 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/TestUtil.java
@@ -1448,11 +1448,9 @@ public final class TestUtil {
// keep number of open files lowish
MergePolicy mp = w.getConfig().getMergePolicy();
mp.setNoCFSRatio(1.0);
- if (mp instanceof LogMergePolicy) {
- LogMergePolicy lmp = (LogMergePolicy) mp;
+ if (mp instanceof LogMergePolicy lmp) {
lmp.setMergeFactor(Math.min(5, lmp.getMergeFactor()));
- } else if (mp instanceof TieredMergePolicy) {
- TieredMergePolicy tmp = (TieredMergePolicy) mp;
+ } else if (mp instanceof TieredMergePolicy tmp) {
tmp.setSegmentsPerTier(Math.min(5, tmp.getSegmentsPerTier()));
}
MergeScheduler ms = w.getConfig().getMergeScheduler();
diff --git a/versions.lock b/versions.lock
index db3e53ae38e..dda6829c863 100644
--- a/versions.lock
+++ b/versions.lock
@@ -35,15 +35,16 @@
"com.google.auto.value:auto-value-annotations:1.9" : "6897bc09,refs=38",
"com.google.auto:auto-common:1.2.2" : "6897bc09,refs=38",
"com.google.code.findbugs:jsr305:3.0.2" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_annotation:2.33.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_annotations:2.33.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_check_api:2.33.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_core:2.33.0" : "6897bc09,refs=38",
- "com.google.errorprone:error_prone_type_annotations:2.33.0" : "6897bc09,refs=38",
+ "com.google.errorprone:error_prone_annotation:2.36.0" : "6897bc09,refs=38",
+ "com.google.errorprone:error_prone_annotations:2.36.0" : "6897bc09,refs=38",
+ "com.google.errorprone:error_prone_check_api:2.36.0" : "6897bc09,refs=38",
+ "com.google.errorprone:error_prone_core:2.36.0" : "6897bc09,refs=38",
+ "com.google.errorprone:error_prone_type_annotations:2.36.0" : "6897bc09,refs=38",
+ "com.google.googlejavaformat:google-java-format:1.19.1" : "6897bc09,refs=38",
"com.google.guava:failureaccess:1.0.1" : "6897bc09,refs=38",
- "com.google.guava:guava:32.1.1-jre" : "6897bc09,refs=38",
- "com.google.guava:guava-parent:32.1.1-jre" : "6897bc09,refs=38",
- "com.google.protobuf:protobuf-java:4.28.2" : "6897bc09,refs=38",
+ "com.google.guava:guava:32.1.3-jre" : "6897bc09,refs=38",
+ "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava" : "6897bc09,refs=38",
+ "com.google.protobuf:protobuf-java:3.25.5" : "6897bc09,refs=38",
"com.ibm.icu:icu4j:74.2" : "ffa00415,refs=8",
"commons-codec:commons-codec:1.17.2" : "733734f0,refs=6",
"io.github.eisop:dataflow-errorprone:3.41.0-eisop1" : "6897bc09,refs=38",
@@ -61,7 +62,7 @@
"org.carrot2:morfologik-fsa:2.1.9" : "e077a675,refs=8",
"org.carrot2:morfologik-polish:2.1.9" : "cb00cecf,refs=5",
"org.carrot2:morfologik-stemming:2.1.9" : "e077a675,refs=8",
- "org.checkerframework:checker-qual:3.33.0" : "6897bc09,refs=38",
+ "org.checkerframework:checker-qual:3.37.0" : "6897bc09,refs=38",
"org.hamcrest:hamcrest:2.2" : "b35e5d7a,refs=74",
"org.jspecify:jspecify:1.0.0" : "6897bc09,refs=38",
"org.locationtech.jts:jts-core:1.17.0" : "180518e6,refs=2",
diff --git a/versions.toml b/versions.toml
index f14585e573a..772d7d9ab52 100644
--- a/versions.toml
+++ b/versions.toml
@@ -5,7 +5,7 @@ assertj = "3.21.0"
commons-codec = "1.17.2"
commons-compress = "1.19"
ecj = "3.36.0"
-errorprone = "2.33.0"
+errorprone = "2.36.0"
flexmark = "0.61.24"
# @keep This is GJF version for spotless/ tidy.
googleJavaFormat = "1.23.0"
@@ -75,7 +75,7 @@ zstd = { module = "com.github.luben:zstd-jni", version.ref = "zstd" }
[plugins]
benmanes-versions = "com.github.ben-manes.versions:0.51.0"
dependencychecks = "com.carrotsearch.gradle.dependencychecks:0.0.9"
-errorprone = "net.ltgt.errorprone:3.1.0"
+errorprone = "net.ltgt.errorprone:4.1.0"
forbiddenapis = "de.thetaphi.forbiddenapis:3.8"
jacocolog = "org.barfuin.gradle.jacocolog:3.1.0"
owasp-dependencycheck = "org.owasp.dependencycheck:7.2.0"