Skip to content

Apache Lucene open-source search software

Replace "UTF-8" with StandardCharsets.UTF_8 and other typo and minor cleanups (#12979)

sabi064cf54a4bff9
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene40/blocktree/Stats.java b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene40/blocktree/Stats.java
index 9c0a819694b..812a959e714 100644
--- a/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene40/blocktree/Stats.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/backward_codecs/lucene40/blocktree/Stats.java
@@ -16,14 +16,14 @@
*/
package org.apache.lucene.backward_codecs.lucene40.blocktree;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
import java.util.Locale;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
/**
* BlockTree statistics for a single field returned by {@link FieldReader#getStats()}.
@@ -84,7 +84,7 @@ public class Stats {
/**
* Total number of bytes used to store term stats (not including what the {@link
- * PostingsReaderBase} stores.
+ * PostingsReaderBase} stores).
*/
public long totalBlockStatsBytes;
@@ -179,12 +179,7 @@ public class Stats {
@Override
public String toString() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- PrintStream out;
- try {
- out = new PrintStream(bos, false, IOUtils.UTF_8);
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
+ PrintStream out = new PrintStream(bos, false, UTF_8);
out.println(" index FST:");
out.println(" " + indexNumBytes + " bytes");
@@ -276,10 +271,6 @@ public class Stats {
assert totalBlockCount == total;
}
- try {
- return bos.toString(IOUtils.UTF_8);
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
+ return bos.toString(UTF_8);
}
}
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestBackwardsCompatibility.java b/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestBackwardsCompatibility.java
index 26284721096..d5250290db3 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestBackwardsCompatibility.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/backward_index/TestBackwardsCompatibility.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.backward_index;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import static org.apache.lucene.util.Version.LUCENE_9_0_0;
@@ -123,7 +124,6 @@ import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.Version;
import org.junit.AfterClass;
@@ -946,7 +946,7 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8));
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8));
CheckIndex.Status indexStatus = checker.checkIndex();
if (unsupportedNames[i].startsWith("8.")) {
assertTrue(indexStatus.clean);
@@ -956,8 +956,8 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
// IndexFormatTooOldException
// or an IllegalArgumentException saying that the codec doesn't exist.
boolean formatTooOld =
- bos.toString(IOUtils.UTF_8).contains(IndexFormatTooOldException.class.getName());
- boolean missingCodec = bos.toString(IOUtils.UTF_8).contains("Could not load codec");
+ bos.toString(UTF_8).contains(IndexFormatTooOldException.class.getName());
+ boolean missingCodec = bos.toString(UTF_8).contains("Could not load codec");
assertTrue(formatTooOld || missingCodec);
}
checker.close();
@@ -1123,9 +1123,9 @@ public class TestBackwardsCompatibility extends LuceneTestCase {
assertEquals("wrong number of hits", expectedCount, hitCount);
StoredFields storedFields = reader.storedFields();
TermVectors termVectors = reader.termVectors();
- for (int i = 0; i < hitCount; i++) {
- storedFields.document(hits[i].doc);
- termVectors.get(hits[i].doc);
+ for (ScoreDoc hit : hits) {
+ storedFields.document(hit.doc);
+ termVectors.get(hit.doc);
}
}
diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TestDocMaker.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TestDocMaker.java
index b3d76edaefb..b6da2d2f404 100644
--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TestDocMaker.java
+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TestDocMaker.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.benchmark.byTask.feeds;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -35,7 +37,6 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.util.IOUtils;
/** Tests the functionality of {@link DocMaker}. */
public class TestDocMaker extends BenchmarkTestCase {
@@ -164,7 +165,7 @@ public class TestDocMaker extends BenchmarkTestCase {
// DocMaker did not close its ContentSource if resetInputs was called twice,
// leading to a file handle leak.
Path f = getWorkDir().resolve("docMakerLeak.txt");
- PrintStream ps = new PrintStream(Files.newOutputStream(f), true, IOUtils.UTF_8);
+ PrintStream ps = new PrintStream(Files.newOutputStream(f), true, UTF_8);
ps.println("one title\t" + random().nextLong() + "\tsome content");
ps.close();
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Stats.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Stats.java
index 36361b5d78e..e8f25197074 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Stats.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Stats.java
@@ -16,14 +16,14 @@
*/
package org.apache.lucene.codecs.lucene90.blocktree;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
import java.util.Locale;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
/**
* BlockTree statistics for a single field returned by {@link FieldReader#getStats()}.
@@ -84,7 +84,7 @@ public class Stats {
/**
* Total number of bytes used to store term stats (not including what the {@link
- * PostingsReaderBase} stores.
+ * PostingsReaderBase} stores).
*/
public long totalBlockStatsBytes;
@@ -179,12 +179,7 @@ public class Stats {
@Override
public String toString() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- PrintStream out;
- try {
- out = new PrintStream(bos, false, IOUtils.UTF_8);
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
+ PrintStream out = new PrintStream(bos, false, UTF_8);
out.println(" index FST:");
out.println(" " + indexNumBytes + " bytes");
@@ -276,10 +271,6 @@ public class Stats {
assert totalBlockCount == total;
}
- try {
- return bos.toString(IOUtils.UTF_8);
- } catch (UnsupportedEncodingException bogus) {
- throw new RuntimeException(bogus);
- }
+ return bos.toString(UTF_8);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
index f899b331b92..ca884be5b7e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
@@ -16,19 +16,18 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -146,7 +145,7 @@ public final class CheckIndex implements Closeable {
/**
* SegmentInfos instance containing only segments that had no problems (this is used with the
- * {@link CheckIndex#exorciseIndex} method to repair the index.
+ * {@link CheckIndex#exorciseIndex} method to repair the index).
*/
SegmentInfos newSegments;
@@ -157,8 +156,8 @@ public final class CheckIndex implements Closeable {
public int numBadSegments;
/**
- * True if we checked only specific segments ({@link #checkIndex(List)}) was called with
- * non-null argument).
+ * True if we checked only specific segments ({@link #checkIndex(List)} was called with non-null
+ * argument).
*/
public boolean partial;
@@ -247,7 +246,7 @@ public final class CheckIndex implements Closeable {
public VectorValuesStatus vectorValuesStatus;
/** Status of soft deletes */
- public SoftDeletsStatus softDeletesStatus;
+ public SoftDeletesStatus softDeletesStatus;
/** Exception thrown during segment test (null on success) */
public Throwable error;
@@ -294,7 +293,7 @@ public final class CheckIndex implements Closeable {
/** Number of terms with at least one live doc. */
public long termCount = 0L;
- /** Number of terms with zero live docs docs. */
+ /** Number of terms with zero live docs. */
public long delTermCount = 0L;
/** Total frequency across all terms. */
@@ -308,7 +307,7 @@ public final class CheckIndex implements Closeable {
/**
* Holds details of block allocations in the block tree terms dictionary (this is only set if
- * the {@link PostingsFormat} for this segment uses block tree.
+ * the {@link PostingsFormat} for this segment uses block tree).
*/
public Map<String, Object> blockTreeStats = null;
}
@@ -409,8 +408,8 @@ public final class CheckIndex implements Closeable {
}
/** Status from testing soft deletes */
- public static final class SoftDeletsStatus {
- SoftDeletsStatus() {}
+ public static final class SoftDeletesStatus {
+ SoftDeletesStatus() {}
/** Exception thrown during soft deletes test (null on success) */
public Throwable error;
@@ -506,7 +505,7 @@ public final class CheckIndex implements Closeable {
private static void msg(PrintStream out, ByteArrayOutputStream msg) {
if (out != null) {
- out.println(msg.toString(StandardCharsets.UTF_8));
+ out.println(msg.toString(UTF_8));
}
}
@@ -609,15 +608,12 @@ public final class CheckIndex implements Closeable {
// way if an index has a broken last commit AND a broken old commit, we report the last commit
// error first:
allSegmentsFiles.sort(
- new Comparator<String>() {
- @Override
- public int compare(String a, String b) {
- long genA = SegmentInfos.generationFromSegmentsFileName(a);
- long genB = SegmentInfos.generationFromSegmentsFileName(b);
-
- // reversed natural sort (largest generation first):
- return -Long.compare(genA, genB);
- }
+ (a, b) -> {
+ long genA = SegmentInfos.generationFromSegmentsFileName(a);
+ long genB = SegmentInfos.generationFromSegmentsFileName(b);
+
+ // reversed natural sort (largest generation first):
+ return -Long.compare(genA, genB);
});
for (String fileName : allSegmentsFiles) {
@@ -821,7 +817,7 @@ public final class CheckIndex implements Closeable {
SegmentInfos finalSis = lastCommit;
ByteArrayOutputStream output = new ByteArrayOutputStream();
- PrintStream stream = new PrintStream(output, true, IOUtils.UTF_8);
+ PrintStream stream = new PrintStream(output, true, UTF_8);
msg(
stream,
(1 + i)
@@ -859,7 +855,7 @@ public final class CheckIndex implements Closeable {
+ info.info.name);
if (infoStream != null) e.printStackTrace(infoStream);
} catch (ExecutionException e) {
- msg(infoStream, output.toString(StandardCharsets.UTF_8));
+ msg(infoStream, output.toString(UTF_8));
assert failFast;
throw new CheckIndexException(
@@ -973,7 +969,7 @@ public final class CheckIndex implements Closeable {
}
segInfoStat.numFiles = info.files().size();
segInfoStat.sizeMB = info.sizeInBytes() / (1024. * 1024.);
- // nf#format is not thread-safe, and would generate random non valid results in concurrent
+ // nf#format is not thread-safe, and would generate random non-valid results in concurrent
// setting
synchronized (nf) {
msg(infoStream, " size (MB)=" + nf.format(segInfoStat.sizeMB));
@@ -1216,7 +1212,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -1282,7 +1278,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -1319,7 +1315,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -1362,7 +1358,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -2114,7 +2110,7 @@ public final class CheckIndex implements Closeable {
// Unusual: the FieldsEnum returned a field but
// the Terms for that field is null; this should
// only happen if it's a ghost field (field with
- // no terms, eg there used to be terms but all
+ // no terms, e.g. there used to be terms but all
// docs got deleted and then merged away):
} else {
@@ -3035,7 +3031,7 @@ public final class CheckIndex implements Closeable {
+ "\"");
}
- // Make sure this cell is not outside of the global min/max:
+ // Make sure this cell is not outside the global min/max:
if (comparator.compare(minPackedValue, offset, globalMinPackedValue, offset) < 0) {
throw new CheckIndexException(
"packed points cell minPackedValue "
@@ -3182,7 +3178,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -3229,7 +3225,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -3746,7 +3742,7 @@ public final class CheckIndex implements Closeable {
TermsEnum postingsTermsEnum = postingsTerms.iterator();
final boolean hasProx = terms.hasOffsets() || terms.hasPositions();
- BytesRef term = null;
+ BytesRef term;
while ((term = termsEnum.next()) != null) {
// This is the term vectors:
@@ -3946,7 +3942,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
@@ -4073,7 +4069,7 @@ public final class CheckIndex implements Closeable {
}
System.out.println("\nOpening index @ " + opts.indexPath + "\n");
- Directory directory = null;
+ Directory directory;
Path path = Paths.get(opts.indexPath);
try {
if (opts.dirImpl == null) {
@@ -4213,7 +4209,7 @@ public final class CheckIndex implements Closeable {
+ " -codec X: when exorcising, codec to write the new segments_N file with\n"
+ " -verbose: print additional details\n"
+ " -segment X: only check the specified segments. This can be specified multiple\n"
- + " times, to check more than one segment, eg '-segment _2 -segment _a'.\n"
+ + " times, to check more than one segment, e.g. '-segment _2 -segment _a'.\n"
+ " You can't use this with the -exorcise option\n"
+ " -threadCount X: number of threads used to check index concurrently.\n"
+ " When not specified, this will default to the number of CPU cores.\n"
@@ -4241,7 +4237,7 @@ public final class CheckIndex implements Closeable {
+ "corruption, else 0.\n");
}
- if (opts.onlySegments.size() == 0) {
+ if (opts.onlySegments.isEmpty()) {
opts.onlySegments = null;
} else if (opts.doExorcise) {
throw new IllegalArgumentException("ERROR: cannot specify both -exorcise and -segment");
@@ -4294,16 +4290,12 @@ public final class CheckIndex implements Closeable {
"Wrote new segments file \"" + result.newSegments.getSegmentsFileName() + "\"");
}
}
- opts.out.println("");
+ opts.out.println();
- if (result.clean == true) {
- return 0;
- } else {
- return 1;
- }
+ return result.clean ? 0 : 1;
}
- private static Status.SoftDeletsStatus checkSoftDeletes(
+ private static Status.SoftDeletesStatus checkSoftDeletes(
String softDeletesField,
SegmentCommitInfo info,
SegmentReader reader,
@@ -4311,7 +4303,7 @@ public final class CheckIndex implements Closeable {
boolean failFast)
throws IOException {
- Status.SoftDeletsStatus status = new Status.SoftDeletsStatus();
+ Status.SoftDeletesStatus status = new Status.SoftDeletesStatus();
if (infoStream != null) infoStream.print(" test: check soft deletes.....");
try {
int softDeletes =
@@ -4326,7 +4318,7 @@ public final class CheckIndex implements Closeable {
if (failFast) {
throw IOUtils.rethrowAlways(e);
}
- msg(infoStream, "ERROR [" + String.valueOf(e.getMessage()) + "]");
+ msg(infoStream, "ERROR [" + e.getMessage() + "]");
status.error = e;
if (infoStream != null) {
e.printStackTrace(infoStream);
diff --git a/lucene/core/src/test/org/apache/lucene/TestMergeSchedulerExternal.java b/lucene/core/src/test/org/apache/lucene/TestMergeSchedulerExternal.java
index da72c3273d1..506a76f9989 100644
--- a/lucene/core/src/test/org/apache/lucene/TestMergeSchedulerExternal.java
+++ b/lucene/core/src/test/org/apache/lucene/TestMergeSchedulerExternal.java
@@ -17,6 +17,8 @@
package org.apache.lucene;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -37,7 +39,6 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.analysis.MockAnalyzer;
import org.apache.lucene.tests.store.MockDirectoryWrapper;
import org.apache.lucene.tests.util.LuceneTestCase;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
import org.apache.lucene.util.PrintStreamInfoStream;
import org.junit.AfterClass;
@@ -95,7 +96,7 @@ public class TestMergeSchedulerExternal extends LuceneTestCase {
PrintWriter pw = new PrintWriter(sw);
ioe.printStackTrace(pw);
if (infoStream.isEnabled("IW")) {
- infoStream.message("IW", "TEST: now throw exc:\n" + sw.toString());
+ infoStream.message("IW", "TEST: now throw exc:\n" + sw);
}
throw ioe;
}
@@ -123,7 +124,7 @@ public class TestMergeSchedulerExternal extends LuceneTestCase {
.setMergePolicy(newLogMergePolicy());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- infoStream = new PrintStreamInfoStream(new PrintStream(baos, true, IOUtils.UTF_8));
+ infoStream = new PrintStreamInfoStream(new PrintStream(baos, true, UTF_8));
iwc.setInfoStream(infoStream);
IndexWriter writer = new IndexWriter(dir, iwc);
@@ -155,7 +156,7 @@ public class TestMergeSchedulerExternal extends LuceneTestCase {
assertTrue(excCalled);
} catch (AssertionError ae) {
System.out.println("TEST FAILED; IW infoStream output:");
- System.out.println(baos.toString(IOUtils.UTF_8));
+ System.out.println(baos.toString(UTF_8));
throw ae;
}
dir.close();
@@ -165,7 +166,7 @@ public class TestMergeSchedulerExternal extends LuceneTestCase {
@Override
public void merge(MergeSource mergeSource, MergeTrigger trigger) throws IOException {
- OneMerge merge = null;
+ OneMerge merge;
while ((merge = mergeSource.getNextMerge()) != null) {
if (VERBOSE) {
System.out.println("executing merge " + merge.segString());
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestCheckIndex.java b/lucene/core/src/test/org/apache/lucene/index/TestCheckIndex.java
index 16d73eea97c..96e545e6011 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestCheckIndex.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestCheckIndex.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
@@ -38,7 +40,6 @@ import org.apache.lucene.tests.index.BaseTestCheckIndex;
import org.apache.lucene.tests.store.MockDirectoryWrapper;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.VectorUtil;
import org.junit.Test;
@@ -149,62 +150,62 @@ public class TestCheckIndex extends BaseTestCheckIndex {
// confirm live docs testing status
assertEquals(0, segStatus.liveDocStatus.numDeleted);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: check live docs"));
+ assertTrue(output.toString(UTF_8).contains("test: check live docs"));
assertNull(segStatus.liveDocStatus.error);
// confirm field infos testing status
assertEquals(8, segStatus.fieldInfoStatus.totFields);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: field infos"));
+ assertTrue(output.toString(UTF_8).contains("test: field infos"));
assertNull(segStatus.fieldInfoStatus.error);
// confirm field norm (from term vector) testing status
assertEquals(1, segStatus.fieldNormStatus.totFields);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: field norms"));
+ assertTrue(output.toString(UTF_8).contains("test: field norms"));
assertNull(segStatus.fieldNormStatus.error);
// confirm term index testing status
assertTrue(segStatus.termIndexStatus.termCount > 0);
assertTrue(segStatus.termIndexStatus.totFreq > 0);
assertTrue(segStatus.termIndexStatus.totPos > 0);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: terms, freq, prox"));
+ assertTrue(output.toString(UTF_8).contains("test: terms, freq, prox"));
assertNull(segStatus.termIndexStatus.error);
// confirm stored field testing status
// add storedField from tombstone doc
assertEquals(liveDocCount + 1, segStatus.storedFieldStatus.docCount);
assertEquals(2 * liveDocCount, segStatus.storedFieldStatus.totFields);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: stored fields"));
+ assertTrue(output.toString(UTF_8).contains("test: stored fields"));
assertNull(segStatus.storedFieldStatus.error);
// confirm term vector testing status
assertEquals(liveDocCount, segStatus.termVectorStatus.docCount);
assertEquals(liveDocCount, segStatus.termVectorStatus.totVectors);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: term vectors"));
+ assertTrue(output.toString(UTF_8).contains("test: term vectors"));
assertNull(segStatus.termVectorStatus.error);
// confirm doc values testing status
assertEquals(2, segStatus.docValuesStatus.totalNumericFields);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: docvalues"));
+ assertTrue(output.toString(UTF_8).contains("test: docvalues"));
assertNull(segStatus.docValuesStatus.error);
// confirm point values testing status
assertEquals(1, segStatus.pointsStatus.totalValueFields);
assertEquals(liveDocCount, segStatus.pointsStatus.totalValuePoints);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: points"));
+ assertTrue(output.toString(UTF_8).contains("test: points"));
assertNull(segStatus.pointsStatus.error);
// confirm vector testing status
assertEquals(2 * liveDocCount, segStatus.vectorValuesStatus.totalVectorValues);
assertEquals(2, segStatus.vectorValuesStatus.totalKnnVectorFields);
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: vectors"));
+ assertTrue(output.toString(UTF_8).contains("test: vectors"));
assertNull(segStatus.vectorValuesStatus.error);
// confirm index sort testing status
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: index sort"));
+ assertTrue(output.toString(UTF_8).contains("test: index sort"));
assertNull(segStatus.indexSortStatus.error);
// confirm soft deletes testing status
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: check soft deletes"));
+ assertTrue(output.toString(UTF_8).contains("test: check soft deletes"));
assertNull(segStatus.softDeletesStatus.error);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java b/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java
index 8cb632e01a7..4ae2dacabc7 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -28,7 +30,6 @@ import org.apache.lucene.document.TextField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.tests.analysis.MockTokenizer;
import org.apache.lucene.tests.util.LuceneTestCase;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.PrintStreamInfoStream;
import org.junit.Test;
@@ -67,19 +68,15 @@ public class TestDocInverterPerFieldErrorInfo extends LuceneTestCase {
IndexWriter writer;
IndexWriterConfig c = new IndexWriterConfig(new ThrowingAnalyzer());
final ByteArrayOutputStream infoBytes = new ByteArrayOutputStream();
- PrintStream infoPrintStream = new PrintStream(infoBytes, true, IOUtils.UTF_8);
+ PrintStream infoPrintStream = new PrintStream(infoBytes, true, UTF_8);
PrintStreamInfoStream printStreamInfoStream = new PrintStreamInfoStream(infoPrintStream);
c.setInfoStream(printStreamInfoStream);
writer = new IndexWriter(dir, c);
Document doc = new Document();
doc.add(newField("distinctiveFieldName", "aaa ", storedTextType));
- expectThrows(
- BadNews.class,
- () -> {
- writer.addDocument(doc);
- });
+ expectThrows(BadNews.class, () -> writer.addDocument(doc));
infoPrintStream.flush();
- String infoStream = new String(infoBytes.toByteArray(), IOUtils.UTF_8);
+ String infoStream = infoBytes.toString(UTF_8);
assertTrue(infoStream.contains("distinctiveFieldName"));
writer.close();
@@ -92,7 +89,7 @@ public class TestDocInverterPerFieldErrorInfo extends LuceneTestCase {
IndexWriter writer;
IndexWriterConfig c = new IndexWriterConfig(new ThrowingAnalyzer());
final ByteArrayOutputStream infoBytes = new ByteArrayOutputStream();
- PrintStream infoPrintStream = new PrintStream(infoBytes, true, IOUtils.UTF_8);
+ PrintStream infoPrintStream = new PrintStream(infoBytes, true, UTF_8);
PrintStreamInfoStream printStreamInfoStream = new PrintStreamInfoStream(infoPrintStream);
c.setInfoStream(printStreamInfoStream);
writer = new IndexWriter(dir, c);
@@ -101,7 +98,7 @@ public class TestDocInverterPerFieldErrorInfo extends LuceneTestCase {
// should not throw BadNews
writer.addDocument(doc);
infoPrintStream.flush();
- String infoStream = new String(infoBytes.toByteArray(), IOUtils.UTF_8);
+ String infoStream = infoBytes.toString(UTF_8);
assertFalse(infoStream.contains("boringFieldName"));
writer.close();
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index 0390edb36cf..c1687acd07a 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.lucene.tests.index.DocHelper.TEXT_TYPE_STORED_WITH_TVS;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
@@ -126,14 +127,13 @@ public class TestIndexWriter extends LuceneTestCase {
public void testDocCount() throws IOException {
Directory dir = newDirectory();
- IndexWriter writer = null;
- IndexReader reader = null;
- int i;
+ IndexWriter writer;
+ IndexReader reader;
writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));
// add 100 documents
- for (i = 0; i < 100; i++) {
+ for (int i = 0; i < 100; i++) {
addDocWithIndex(writer, i);
if (random().nextBoolean()) {
writer.commit();
@@ -158,7 +158,7 @@ public class TestIndexWriter extends LuceneTestCase {
}
}));
- for (i = 0; i < 40; i++) {
+ for (int i = 0; i < 40; i++) {
writer.deleteDocuments(new Term("id", "" + i));
if (random().nextBoolean()) {
writer.commit();
@@ -286,11 +286,7 @@ public class TestIndexWriter extends LuceneTestCase {
// close
writer.close();
- expectThrows(
- AlreadyClosedException.class,
- () -> {
- addDoc(writer);
- });
+ expectThrows(AlreadyClosedException.class, () -> addDoc(writer));
dir.close();
}
@@ -417,7 +413,7 @@ public class TestIndexWriter extends LuceneTestCase {
customType.setOmitNorms(true);
for (int j = 0; j < 10; j++) {
Document doc = new Document();
- Field f = null;
+ Field f;
if (j != 8) {
f = newField("field", "aaa", customType);
} else {
@@ -445,7 +441,7 @@ public class TestIndexWriter extends LuceneTestCase {
// Enable norms for only 1 doc, post flush
for (int j = 0; j < 27; j++) {
Document doc = new Document();
- Field f = null;
+ Field f;
if (j != 26) {
f = newField("field", "aaa", customType);
} else {
@@ -609,15 +605,17 @@ public class TestIndexWriter extends LuceneTestCase {
String contents = "aa bb cc dd ee ff gg hh ii jj kk";
FieldType customType = new FieldType(TextField.TYPE_STORED);
- FieldType type = null;
if (i == 7) {
// Add empty docs here
doc.add(newTextField("content3", "", Field.Store.NO));
} else {
+ FieldType type;
if (i % 2 == 0) {
doc.add(newField("content4", contents, customType));
type = customType;
- } else type = TextField.TYPE_NOT_STORED;
+ } else {
+ type = TextField.TYPE_NOT_STORED;
+ }
doc.add(newTextField("content1", contents, Field.Store.NO));
doc.add(newField("content3", "", customType));
doc.add(newField("content5", "", type));
@@ -782,11 +780,7 @@ public class TestIndexWriter extends LuceneTestCase {
IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));
Document doc = new Document();
doc.add(new TextField("field", tokens));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
w.close();
dir.close();
@@ -877,7 +871,7 @@ public class TestIndexWriter extends LuceneTestCase {
final Random random;
final Directory adder;
final ByteArrayOutputStream bytesLog = new ByteArrayOutputStream();
- final PrintStream log = new PrintStream(bytesLog, true, IOUtils.UTF_8);
+ final PrintStream log = new PrintStream(bytesLog, true, UTF_8);
final int id;
IndexerThreadInterrupt(int id) throws IOException {
@@ -1150,7 +1144,7 @@ public class TestIndexWriter extends LuceneTestCase {
t.finish = true;
t.join();
if (t.failed) {
- fail(t.bytesLog.toString("UTF-8"));
+ fail(t.bytesLog.toString(UTF_8));
}
}
@@ -1276,9 +1270,8 @@ public class TestIndexWriter extends LuceneTestCase {
Path indexPath = provider.wrapPath(path);
// NOTE: on Unix, we cannot use MMapDir, because WindowsFS doesn't see/think it keeps file
- // handles open. Yet, on Windows, we MUST use
- // MMapDir because the windows OS will in fact prevent file deletion for us, and fails
- // otherwise:
+ // handles open. Yet, on Windows, we MUST use MMapDir because the Windows OS will in fact
+ // prevent file deletion for us, and fails otherwise:
FSDirectory dir;
if (Constants.WINDOWS) {
dir = new MMapDirectory(indexPath);
@@ -1523,10 +1516,10 @@ public class TestIndexWriter extends LuceneTestCase {
for (int i = 0; i < 2; i++) {
Document doc = new Document();
- doc.add(new Field("id", Integer.toString(i) + BIG, customType3));
- doc.add(new Field("str", Integer.toString(i) + BIG, customType2));
- doc.add(new Field("str2", Integer.toString(i) + BIG, storedTextType));
- doc.add(new Field("str3", Integer.toString(i) + BIG, customType));
+ doc.add(new Field("id", i + BIG, customType3));
+ doc.add(new Field("str", i + BIG, customType2));
+ doc.add(new Field("str2", i + BIG, storedTextType));
+ doc.add(new Field("str3", i + BIG, customType));
indexWriter.addDocument(doc);
}
@@ -1601,11 +1594,7 @@ public class TestIndexWriter extends LuceneTestCase {
// This contents produces a too-long term:
String contents = "abc xyz x" + bigTerm + " another term";
hugeDoc.add(new TextField("content", contents, Field.Store.NO));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(hugeDoc);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(hugeDoc));
// Make sure we can add another normal document
Document doc = new Document();
@@ -1724,9 +1713,7 @@ public class TestIndexWriter extends LuceneTestCase {
w1.deleteAll();
expectThrows(
LockObtainFailedException.class,
- () -> {
- new RandomIndexWriter(random(), d, newIndexWriterConfig(null));
- });
+ () -> new RandomIndexWriter(random(), d, newIndexWriterConfig(null)));
w1.close();
d.close();
@@ -1816,11 +1803,7 @@ public class TestIndexWriter extends LuceneTestCase {
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())));
w.prepareCommit();
- expectThrows(
- IllegalStateException.class,
- () -> {
- w.close();
- });
+ expectThrows(IllegalStateException.class, w::close);
w.commit();
w.close();
IndexReader r = DirectoryReader.open(dir);
@@ -2143,11 +2126,7 @@ public class TestIndexWriter extends LuceneTestCase {
}
// add broken doc
- expectThrows(
- NullPointerException.class,
- () -> {
- iw.addDocument(null);
- });
+ expectThrows(NullPointerException.class, () -> iw.addDocument(null));
// ensure good docs are still ok
IndexReader ir = iw.getReader();
@@ -2170,11 +2149,7 @@ public class TestIndexWriter extends LuceneTestCase {
}
// add broken doc block
- expectThrows(
- NullPointerException.class,
- () -> {
- iw.addDocuments(null);
- });
+ expectThrows(NullPointerException.class, () -> iw.addDocuments(null));
// ensure good docs are still ok
IndexReader ir = iw.getReader();
@@ -2203,7 +2178,7 @@ public class TestIndexWriter extends LuceneTestCase {
boolean success = false;
try {
- w.addDocument(new RandomFailingIterable<IndexableField>(fields, random()));
+ w.addDocument(new RandomFailingIterable<>(fields, random()));
success = true;
} catch (RuntimeException e) {
assertEquals("boom", e.getMessage());
@@ -2252,7 +2227,7 @@ public class TestIndexWriter extends LuceneTestCase {
boolean success = false;
try {
- w.addDocument(new RandomFailingIterable<IndexableField>(fields, random()));
+ w.addDocument(new RandomFailingIterable<>(fields, random()));
success = true;
} catch (RuntimeException e) {
assertEquals("boom", e.getMessage());
@@ -2332,7 +2307,7 @@ public class TestIndexWriter extends LuceneTestCase {
@Override
public Iterator<T> iterator() {
final Iterator<? extends T> docIter = list.iterator();
- return new Iterator<T>() {
+ return new Iterator<>() {
int count = 0;
@Override
@@ -2476,14 +2451,11 @@ public class TestIndexWriter extends LuceneTestCase {
random(),
dir,
iwc,
- new RandomIndexWriter.TestPoint() {
- @Override
- public void apply(String message) {
- if ("startCommitMerge".equals(message)) {
- keepFullyDeletedSegments.set(false);
- } else if ("startMergeInit".equals(message)) {
- keepFullyDeletedSegments.set(true);
- }
+ message -> {
+ if ("startCommitMerge".equals(message)) {
+ keepFullyDeletedSegments.set(false);
+ } else if ("startMergeInit".equals(message)) {
+ keepFullyDeletedSegments.set(true);
}
});
iwRef.set(evilWriter);
@@ -2533,11 +2505,7 @@ public class TestIndexWriter extends LuceneTestCase {
Document doc = new Document();
doc.add(new SortedDocValuesField("dv", newBytesRef("foo!")));
doc.add(new SortedDocValuesField("dv", newBytesRef("bar!")));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- iwriter.addDocument(doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> iwriter.addDocument(doc));
iwriter.commit();
assertFalse(iwriter.hasUncommittedChanges());
@@ -2653,16 +2621,13 @@ public class TestIndexWriter extends LuceneTestCase {
random(),
dir,
iwc,
- new RandomIndexWriter.TestPoint() {
- @Override
- public void apply(String message) {
- if (message.equals("finishStartCommit")) {
- startCommit.countDown();
- try {
- Thread.sleep(10);
- } catch (InterruptedException ie) {
- throw new ThreadInterruptedException(ie);
- }
+ message -> {
+ if (message.equals("finishStartCommit")) {
+ startCommit.countDown();
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException ie) {
+ throw new ThreadInterruptedException(ie);
}
}
});
@@ -2715,9 +2680,9 @@ public class TestIndexWriter extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(d);
checker.setLevel(CheckIndex.Level.MIN_LEVEL_FOR_INTEGRITY_CHECKS);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8), false);
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8), false);
CheckIndex.Status indexStatus = checker.checkIndex(null);
- String s = bos.toString(IOUtils.UTF_8);
+ String s = bos.toString(UTF_8);
checker.close();
// Make sure CheckIndex didn't fail
assertTrue(s, indexStatus != null && indexStatus.clean);
@@ -2969,11 +2934,7 @@ public class TestIndexWriter extends LuceneTestCase {
.setMaxBufferedDocs(2)
.setRAMBufferSizeMB(-1);
w = new IndexWriter(dir, iwc);
- expectThrows(
- NoSuchFileException.class,
- () -> {
- dir.deleteFile(randomFile);
- });
+ expectThrows(NoSuchFileException.class, () -> dir.deleteFile(randomFile));
}
w.close();
}
@@ -3053,11 +3014,7 @@ public class TestIndexWriter extends LuceneTestCase {
assertTrue(dir.getPendingDeletions().size() > 0);
// make sure we get NoSuchFileException if we try to delete and already-pending-delete file:
- expectThrows(
- NoSuchFileException.class,
- () -> {
- dir.deleteFile("segments_2");
- });
+ expectThrows(NoSuchFileException.class, () -> dir.deleteFile("segments_2"));
try (IndexWriter writer =
new IndexWriter(
@@ -3093,11 +3050,7 @@ public class TestIndexWriter extends LuceneTestCase {
assertTrue(dir.getPendingDeletions().size() > 0);
// make sure we get NoSuchFileException if we try to delete and already-pending-delete file:
- expectThrows(
- NoSuchFileException.class,
- () -> {
- dir.deleteFile("segments_1");
- });
+ expectThrows(NoSuchFileException.class, () -> dir.deleteFile("segments_1"));
new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random()))).close();
in.close();
}
@@ -3140,12 +3093,7 @@ public class TestIndexWriter extends LuceneTestCase {
final Document doc = new Document();
// doc.add(new TextField("big", b.toString(), Field.Store.YES));
doc.add(new StoredField("big", b.toString()));
- Exception e =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc);
- });
+ Exception e = expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
assertEquals(
"stored field \"big\" is too large (" + b.length() + " characters) to store",
e.getMessage());
@@ -3300,7 +3248,7 @@ public class TestIndexWriter extends LuceneTestCase {
if (random().nextBoolean()) {
w.deleteDocuments(new Term("id", "1"));
} else {
- w.updateDocValues(new Term("id", "1"), new NumericDocValuesField("foo", 1l));
+ w.updateDocValues(new Term("id", "1"), new NumericDocValuesField("foo", 1L));
}
deleteBytesUsed = w.docWriter.flushControl.getDeleteBytesUsed();
assertTrue("deletedBytesUsed: " + deleteBytesUsed, deleteBytesUsed > 0);
@@ -3453,15 +3401,12 @@ public class TestIndexWriter extends LuceneTestCase {
}
w.getConfig().setCheckPendingFlushUpdate(true);
numIters = 0;
- while (true) {
+ do {
assertFalse("should finish in less than 100 iterations", numIters++ >= 100);
waitForDocsInBuffers(w, Math.min(2, threads.length));
w.flush();
flushingThreads.retainAll(indexingThreads);
- if (flushingThreads.isEmpty() == false) {
- break;
- }
- }
+ } while (flushingThreads.isEmpty());
} finally {
done.set(true);
for (int i = 0; i < numThreads; i++) {
@@ -3503,29 +3448,23 @@ public class TestIndexWriter extends LuceneTestCase {
.setSoftDeletesField("soft_delete"));
expectThrows(
IllegalArgumentException.class,
- () -> {
- writer.softUpdateDocument(
- null, new Document(), new NumericDocValuesField("soft_delete", 1));
- });
+ () ->
+ writer.softUpdateDocument(
+ null, new Document(), new NumericDocValuesField("soft_delete", 1)));
expectThrows(
IllegalArgumentException.class,
- () -> {
- writer.softUpdateDocument(new Term("id", "1"), new Document());
- });
+ () -> writer.softUpdateDocument(new Term("id", "1"), new Document()));
expectThrows(
IllegalArgumentException.class,
- () -> {
- writer.softUpdateDocuments(
- null, Arrays.asList(new Document()), new NumericDocValuesField("soft_delete", 1));
- });
+ () ->
+ writer.softUpdateDocuments(
+ null, Arrays.asList(new Document()), new NumericDocValuesField("soft_delete", 1)));
expectThrows(
IllegalArgumentException.class,
- () -> {
- writer.softUpdateDocuments(new Term("id", "1"), Arrays.asList(new Document()));
- });
+ () -> writer.softUpdateDocuments(new Term("id", "1"), Arrays.asList(new Document())));
Document doc = new Document();
doc.add(new StringField("id", "1", Field.Store.YES));
@@ -3698,8 +3637,8 @@ public class TestIndexWriter extends LuceneTestCase {
started.await();
startLatch.countDown();
- for (int i = 0; i < threads.length; i++) {
- threads[i].join();
+ for (Thread thread : threads) {
+ thread.join();
}
DirectoryReader reader = DirectoryReader.open(writer);
IndexSearcher searcher = new IndexSearcher(reader);
@@ -3812,7 +3751,7 @@ public class TestIndexWriter extends LuceneTestCase {
.stream().filter(filter).collect(Collectors.toSet());
Set<String> dirFiles =
Arrays.stream(writer.getDirectory().listAll())
- .filter(file -> !ExtrasFS.isExtra(file)) // ExtraFS might add an files, ignore them
+ .filter(file -> !ExtrasFS.isExtra(file)) // ExtraFS might add files, ignore them
.filter(filter)
.collect(Collectors.toSet());
assertEquals(segFiles.size(), dirFiles.size());
@@ -3890,9 +3829,7 @@ public class TestIndexWriter extends LuceneTestCase {
IllegalArgumentException illegalError =
expectThrows(
IllegalArgumentException.class,
- () -> {
- new IndexWriter(dir, newIndexWriterConfig().setSoftDeletesField("your_deletes"));
- });
+ () -> new IndexWriter(dir, newIndexWriterConfig().setSoftDeletesField("your_deletes")));
assertEquals(
"cannot configure [your_deletes] as soft-deletes; "
+ "this index uses [my_deletes] as soft-deletes already",
@@ -3903,7 +3840,7 @@ public class TestIndexWriter extends LuceneTestCase {
.setSoftDeletesField("my_deletes")
.setMergePolicy(
new SoftDeletesRetentionMergePolicy(
- "my_deletes", () -> new MatchAllDocsQuery(), newMergePolicy()));
+ "my_deletes", MatchAllDocsQuery::new, newMergePolicy()));
writer = new IndexWriter(dir, softDeleteConfig);
Document tombstone = new Document();
tombstone.add(new StringField("id", "tombstone", Field.Store.YES));
@@ -3919,10 +3856,7 @@ public class TestIndexWriter extends LuceneTestCase {
// reopen writer without soft-deletes field should be prevented
IllegalArgumentException reopenError =
expectThrows(
- IllegalArgumentException.class,
- () -> {
- new IndexWriter(dir, newIndexWriterConfig());
- });
+ IllegalArgumentException.class, () -> new IndexWriter(dir, newIndexWriterConfig()));
assertEquals(
"this index has [my_deletes] as soft-deletes already"
+ " but soft-deletes field is not configured in IWC",
@@ -4458,7 +4392,7 @@ public class TestIndexWriter extends LuceneTestCase {
public void testMaxCompletedSequenceNumber() throws IOException, InterruptedException {
try (Directory dir = newDirectory();
- IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig()); ) {
+ IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig())) {
assertEquals(1, writer.addDocument(new Document()));
assertEquals(2, writer.updateDocument(new Term("foo", "bar"), new Document()));
writer.flushNextBuffer();
@@ -4515,8 +4449,8 @@ public class TestIndexWriter extends LuceneTestCase {
threads[i].start();
}
start.countDown();
- for (int i = 0; i < threads.length; i++) {
- threads[i].join();
+ for (Thread thread : threads) {
+ thread.join();
}
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
index 468c91fc6ec..f27298781ca 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -597,7 +599,7 @@ public class TestIndexWriterDelete extends LuceneTestCase {
boolean done = false;
- // Iterate w/ ever increasing free disk space:
+ // Iterate w/ ever-increasing free disk space:
while (!done) {
if (VERBOSE) {
System.out.println("TEST: cycle");
@@ -903,7 +905,7 @@ public class TestIndexWriterDelete extends LuceneTestCase {
modifier.deleteDocuments(term);
- // add a doc
+ // add a doc,
// doc remains buffered
if (VERBOSE) {
@@ -928,12 +930,7 @@ public class TestIndexWriterDelete extends LuceneTestCase {
if (VERBOSE) {
System.out.println("TEST: now commit for failure");
}
- RuntimeException expected =
- expectThrows(
- RuntimeException.class,
- () -> {
- modifier.commit();
- });
+ RuntimeException expected = expectThrows(RuntimeException.class, modifier::commit);
if (VERBOSE) {
System.out.println("TEST: hit exc:");
expected.printStackTrace(System.out);
@@ -1152,7 +1149,7 @@ public class TestIndexWriterDelete extends LuceneTestCase {
Directory dir = newDirectory();
// Cannot use RandomIndexWriter because we don't want to
// ever call commit() for this test:
- // note: tiny rambuffer used, as with a 1MB buffer the test is too slow (flush @ 128,999)
+ // note: tiny RAM buffer used, as with a 1MB buffer the test is too slow (flush @ 128,999)
IndexWriter w =
new IndexWriter(
dir,
@@ -1278,11 +1275,11 @@ public class TestIndexWriterDelete extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8), false);
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8), false);
CheckIndex.Status indexStatus = checker.checkIndex(null);
assertTrue(indexStatus.clean);
checker.close();
- String s = bos.toString(IOUtils.UTF_8);
+ String s = bos.toString(UTF_8);
// Segment should have deletions:
assertTrue(s.contains("has deletions"));
@@ -1293,11 +1290,11 @@ public class TestIndexWriterDelete extends LuceneTestCase {
bos = new ByteArrayOutputStream(1024);
checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8), false);
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8), false);
indexStatus = checker.checkIndex(null);
assertTrue(indexStatus.clean);
checker.close();
- s = bos.toString(IOUtils.UTF_8);
+ s = bos.toString(UTF_8);
assertFalse(s.contains("has deletions"));
dir.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
index 217d524d5db..70f63924b91 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
@@ -67,7 +69,7 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
// log all exceptions we hit, in case we fail (for debugging)
ByteArrayOutputStream exceptionLog = new ByteArrayOutputStream();
- PrintStream exceptionStream = new PrintStream(exceptionLog, true, "UTF-8");
+ PrintStream exceptionStream = new PrintStream(exceptionLog, true, UTF_8);
// PrintStream exceptionStream = System.out;
// create lots of non-aborting exceptions with a broken analyzer
@@ -271,14 +273,14 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
} catch (Throwable t) {
System.out.println("Unexpected exception: dumping fake-exception-log:...");
exceptionStream.flush();
- System.out.println(exceptionLog.toString("UTF-8"));
+ System.out.println(exceptionLog.toString(UTF_8));
System.out.flush();
Rethrow.rethrow(t);
}
if (VERBOSE) {
System.out.println("TEST PASSED: dumping fake-exception-log:...");
- System.out.println(exceptionLog.toString("UTF-8"));
+ System.out.println(exceptionLog.toString(UTF_8));
}
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnVMError.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnVMError.java
index 7b1a4d821a7..10a6f4878e6 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnVMError.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnVMError.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -57,7 +59,7 @@ public class TestIndexWriterOnVMError extends LuceneTestCase {
private void doTest(MockDirectoryWrapper.Failure failOn) throws Exception {
// log all exceptions we hit, in case we fail (for debugging)
ByteArrayOutputStream exceptionLog = new ByteArrayOutputStream();
- PrintStream exceptionStream = new PrintStream(exceptionLog, true, "UTF-8");
+ PrintStream exceptionStream = new PrintStream(exceptionLog, true, UTF_8);
// PrintStream exceptionStream = System.out;
final long analyzerSeed = random().nextLong();
@@ -66,7 +68,7 @@ public class TestIndexWriterOnVMError extends LuceneTestCase {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
MockTokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
- tokenizer.setEnableChecks(false); // we are gonna make it angry
+ tokenizer.setEnableChecks(false); // we are going to make it angry
TokenStream stream = tokenizer;
// emit some payloads
if (fieldName.contains("payloads")) {
@@ -211,7 +213,7 @@ public class TestIndexWriterOnVMError extends LuceneTestCase {
} catch (Throwable t) {
System.out.println("Unexpected exception: dumping fake-exception-log:...");
exceptionStream.flush();
- System.out.println(exceptionLog.toString("UTF-8"));
+ System.out.println(exceptionLog.toString(UTF_8));
System.out.flush();
Rethrow.rethrow(t);
}
@@ -219,7 +221,7 @@ public class TestIndexWriterOnVMError extends LuceneTestCase {
dir.close();
if (VERBOSE) {
System.out.println("TEST PASSED: dumping fake-exception-log:...");
- System.out.println(exceptionLog.toString("UTF-8"));
+ System.out.println(exceptionLog.toString(UTF_8));
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
index 2f9fd499cfd..ef29c9b0f62 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.lucene.codecs.Codec;
@@ -69,11 +71,7 @@ public class TestPointValues extends LuceneTestCase {
doc.add(new BinaryPoint("dim", new byte[4]));
doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
assertEquals(
"Inconsistency of field data structures across documents for field [dim] of doc [0]."
+ " point dimension: expected '1', but it has '2'.",
@@ -93,11 +91,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc2 = new Document();
doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc2));
assertEquals(
"Inconsistency of field data structures across documents for field [dim] of doc [1]."
+ " point dimension: expected '1', but it has '2'.",
@@ -118,11 +112,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc2 = new Document();
doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc2));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=4 "
+ "to inconsistent dimensionCount=2, indexDimensionCount=2, numBytes=4",
@@ -145,11 +135,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc2 = new Document();
doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w2.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w2.addDocument(doc2));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=4 "
+ "to inconsistent dimensionCount=2, indexDimensionCount=2, numBytes=4",
@@ -173,11 +159,7 @@ public class TestPointValues extends LuceneTestCase {
doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));
w2.addDocument(doc);
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w2.addIndexes(new Directory[] {dir});
- });
+ expectThrows(IllegalArgumentException.class, () -> w2.addIndexes(dir));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=2, indexDimensionCount=2, numBytes=4 "
@@ -204,9 +186,7 @@ public class TestPointValues extends LuceneTestCase {
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
- () -> {
- w2.addIndexes(new CodecReader[] {(CodecReader) getOnlyLeafReader(r)});
- });
+ () -> w2.addIndexes((CodecReader) getOnlyLeafReader(r)));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=2, indexDimensionCount=2, numBytes=4 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=4",
@@ -231,11 +211,7 @@ public class TestPointValues extends LuceneTestCase {
w2.addDocument(doc);
DirectoryReader r = DirectoryReader.open(dir);
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- TestUtil.addIndexesSlowly(w2, r);
- });
+ expectThrows(IllegalArgumentException.class, () -> TestUtil.addIndexesSlowly(w2, r));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=2, indexDimensionCount=2, numBytes=4 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=4",
@@ -251,11 +227,7 @@ public class TestPointValues extends LuceneTestCase {
doc.add(new BinaryPoint("dim", new byte[4]));
doc.add(new BinaryPoint("dim", new byte[6]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc));
assertEquals(
"Inconsistency of field data structures across documents for field [dim] of doc [0]."
+ " point num bytes: expected '4', but it has '6'.",
@@ -275,11 +247,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc2 = new Document();
doc2.add(new BinaryPoint("dim", new byte[6]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc2));
assertEquals(
"Inconsistency of field data structures across documents for field [dim] of doc [1]."
+ " point num bytes: expected '4', but it has '6'.",
@@ -300,11 +268,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc2 = new Document();
doc2.add(new BinaryPoint("dim", new byte[6]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w.addDocument(doc2));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=4 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=6",
@@ -328,11 +292,7 @@ public class TestPointValues extends LuceneTestCase {
doc2.add(new BinaryPoint("dim", new byte[6]));
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w2.addDocument(doc2);
- });
+ expectThrows(IllegalArgumentException.class, () -> w2.addDocument(doc2));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=4 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=6",
@@ -357,11 +317,7 @@ public class TestPointValues extends LuceneTestCase {
doc.add(new BinaryPoint("dim", new byte[6]));
w2.addDocument(doc);
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- w2.addIndexes(new Directory[] {dir});
- });
+ expectThrows(IllegalArgumentException.class, () -> w2.addIndexes(dir));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=6 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=4",
@@ -388,9 +344,7 @@ public class TestPointValues extends LuceneTestCase {
IllegalArgumentException expected =
expectThrows(
IllegalArgumentException.class,
- () -> {
- w2.addIndexes(new CodecReader[] {(CodecReader) getOnlyLeafReader(r)});
- });
+ () -> w2.addIndexes((CodecReader) getOnlyLeafReader(r)));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=6 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=4",
@@ -415,11 +369,7 @@ public class TestPointValues extends LuceneTestCase {
w2.addDocument(doc);
DirectoryReader r = DirectoryReader.open(dir);
IllegalArgumentException expected =
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- TestUtil.addIndexesSlowly(w2, r);
- });
+ expectThrows(IllegalArgumentException.class, () -> TestUtil.addIndexesSlowly(w2, r));
assertEquals(
"cannot change field \"dim\" from points dimensionCount=1, indexDimensionCount=1, numBytes=6 "
+ "to inconsistent dimensionCount=1, indexDimensionCount=1, numBytes=4",
@@ -434,9 +384,7 @@ public class TestPointValues extends LuceneTestCase {
Document doc = new Document();
expectThrows(
IllegalArgumentException.class,
- () -> {
- doc.add(new BinaryPoint("dim", new byte[PointValues.MAX_NUM_BYTES + 1]));
- });
+ () -> doc.add(new BinaryPoint("dim", new byte[PointValues.MAX_NUM_BYTES + 1])));
Document doc2 = new Document();
doc2.add(new IntPoint("dim", 17));
@@ -454,11 +402,7 @@ public class TestPointValues extends LuceneTestCase {
for (int i = 0; i < values.length; i++) {
values[i] = new byte[4];
}
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- doc.add(new BinaryPoint("dim", values));
- });
+ expectThrows(IllegalArgumentException.class, () -> doc.add(new BinaryPoint("dim", values)));
Document doc2 = new Document();
doc2.add(new IntPoint("dim", 17));
@@ -518,65 +462,33 @@ public class TestPointValues extends LuceneTestCase {
public void testInvalidIntPointUsage() throws Exception {
IntPoint field = new IntPoint("field", 17, 42);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- field.setIntValue(14);
- });
+ expectThrows(IllegalArgumentException.class, () -> field.setIntValue(14));
- expectThrows(
- IllegalStateException.class,
- () -> {
- field.numericValue();
- });
+ expectThrows(IllegalStateException.class, field::numericValue);
}
public void testInvalidLongPointUsage() throws Exception {
LongPoint field = new LongPoint("field", 17, 42);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- field.setLongValue(14);
- });
+ expectThrows(IllegalArgumentException.class, () -> field.setLongValue(14));
- expectThrows(
- IllegalStateException.class,
- () -> {
- field.numericValue();
- });
+ expectThrows(IllegalStateException.class, field::numericValue);
}
public void testInvalidFloatPointUsage() throws Exception {
FloatPoint field = new FloatPoint("field", 17, 42);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- field.setFloatValue(14);
- });
+ expectThrows(IllegalArgumentException.class, () -> field.setFloatValue(14));
- expectThrows(
- IllegalStateException.class,
- () -> {
- field.numericValue();
- });
+ expectThrows(IllegalStateException.class, field::numericValue);
}
public void testInvalidDoublePointUsage() throws Exception {
DoublePoint field = new DoublePoint("field", 17, 42);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- field.setDoubleValue(14);
- });
+ expectThrows(IllegalArgumentException.class, () -> field.setDoubleValue(14));
- expectThrows(
- IllegalStateException.class,
- () -> {
- field.numericValue();
- });
+ expectThrows(IllegalStateException.class, field::numericValue);
}
public void testTieBreakByDocID() throws Exception {
@@ -742,7 +654,7 @@ public class TestPointValues extends LuceneTestCase {
assertEquals(2, segStatus.pointsStatus.totalValueFields);
// Make sure CheckIndex in fact declares that it is testing points!
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: points..."));
+ assertTrue(output.toString(UTF_8).contains("test: points..."));
dir.close();
}
diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java
index 6ab5772c689..ab43e76b85b 100644
--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java
+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.facet.taxonomy;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -113,11 +115,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
assertTrue(((TaxonomyFacets) facets).childrenLoaded());
Facets finalFacets = facets;
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- finalFacets.getTopChildren(0, "Author");
- });
+ expectThrows(IllegalArgumentException.class, () -> finalFacets.getTopChildren(0, "Author"));
// Retrieve & verify results:
assertEquals(
@@ -133,9 +131,9 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
3,
5,
- new LabelAndValue[] {
- new LabelAndValue("1999", 1), new LabelAndValue("2010", 2), new LabelAndValue("2012", 2),
- });
+ new LabelAndValue("1999", 1),
+ new LabelAndValue("2010", 2),
+ new LabelAndValue("2012", 2));
assertFacetResult(
facets.getAllChildren("Author"),
@@ -143,12 +141,10 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
4,
5,
- new LabelAndValue[] {
- new LabelAndValue("Bob", 1),
- new LabelAndValue("Frank", 1),
- new LabelAndValue("Lisa", 2),
- new LabelAndValue("Susan", 1),
- });
+ new LabelAndValue("Bob", 1),
+ new LabelAndValue("Frank", 1),
+ new LabelAndValue("Lisa", 2),
+ new LabelAndValue("Susan", 1));
// test getAllDims
List<FacetResult> results = facets.getAllDims(10);
@@ -171,14 +167,14 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// Smoke test PrintTaxonomyStats:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
- PrintTaxonomyStats.printStats(taxoReader, new PrintStream(bos, false, IOUtils.UTF_8), true);
- String result = bos.toString(IOUtils.UTF_8);
- assertTrue(result.indexOf("/Author: 4 immediate children; 5 total categories") != -1);
- assertTrue(result.indexOf("/Publish Date: 3 immediate children; 12 total categories") != -1);
+ PrintTaxonomyStats.printStats(taxoReader, new PrintStream(bos, false, UTF_8), true);
+ String result = bos.toString(UTF_8);
+ assertTrue(result.contains("/Author: 4 immediate children; 5 total categories"));
+ assertTrue(result.contains("/Publish Date: 3 immediate children; 12 total categories"));
// Make sure at least a few nodes of the tree came out:
- assertTrue(result.indexOf(" /1999") != -1);
- assertTrue(result.indexOf(" /2012") != -1);
- assertTrue(result.indexOf(" /20") != -1);
+ assertTrue(result.contains(" /1999"));
+ assertTrue(result.contains(" /2012"));
+ assertTrue(result.contains(" /20"));
writer.close();
IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, taxoDir, dir);
@@ -231,11 +227,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
getAllFacets(FacetsConfig.DEFAULT_INDEX_FIELD_NAME, searcher, taxoReader, config);
// test getAllDims(0)
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getAllDims(0);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getAllDims(0));
// Ask for top 10 labels for any dims that have counts:
List<FacetResult> results = facets.getAllDims(10);
@@ -270,18 +262,10 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
assertEquals(results, allDimsResults);
// test getTopDims(0, 1)
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getTopDims(0, 1);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getTopDims(0, 1));
// test getTopDims(1, 0) with topNChildren = 0
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getTopDims(1, 0);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getTopDims(1, 0));
writer.close();
IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, taxoDir, dir);
@@ -323,22 +307,10 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
List<FacetResult> allTopDimsResults = facets.getTopDims(10, 10);
assertEquals(results, allTopDimsResults);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getSpecificValue("a");
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getSpecificValue("a"));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getTopChildren(10, "a");
- });
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getAllChildren("a");
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getTopChildren(10, "a"));
+ expectThrows(IllegalArgumentException.class, () -> facets.getAllChildren("a"));
writer.close();
IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, taxoDir, dir);
@@ -433,11 +405,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Facets facets =
getAllFacets(FacetsConfig.DEFAULT_INDEX_FIELD_NAME, searcher, taxoReader, config);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getSpecificValue("a");
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getSpecificValue("a"));
FacetResult result = facets.getTopChildren(10, "a");
assertEquals(1, result.labelValues.length);
@@ -494,9 +462,8 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
2,
-1,
- new LabelAndValue[] {
- new LabelAndValue("test\u001Etwo", 1), new LabelAndValue("test\u001Fone", 1),
- });
+ new LabelAndValue("test\u001Etwo", 1),
+ new LabelAndValue("test\u001Fone", 1));
writer.close();
IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, dir, taxoDir);
}
@@ -541,11 +508,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
assertEquals(1, facets.getAllChildren("dim2").value);
assertEquals(1, facets.getTopChildren(10, "dim3").value);
assertEquals(1, facets.getAllChildren("dim3").value);
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getSpecificValue("dim");
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getSpecificValue("dim"));
assertEquals(1, facets.getSpecificValue("dim2"));
assertEquals(1, facets.getSpecificValue("dim3"));
@@ -625,11 +588,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Document doc = new Document();
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path", "other"));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- config.build(taxoWriter, doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> config.build(taxoWriter, doc));
writer.close();
IOUtils.close(taxoWriter, dir, taxoDir);
@@ -649,11 +608,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
doc.add(newTextField("field", "text", Field.Store.NO));
doc.add(new FacetField("a", "path"));
doc.add(new FacetField("a", "path2"));
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- config.build(taxoWriter, doc);
- });
+ expectThrows(IllegalArgumentException.class, () -> config.build(taxoWriter, doc));
writer.close();
IOUtils.close(taxoWriter, dir, taxoDir);
@@ -724,25 +679,13 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
}
// test getTopDims(0, 1)
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getTopDims(0, 1);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getTopDims(0, 1));
// test getTopDims(1, 0) with topNChildren = 0
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getTopDims(1, 0);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getTopDims(1, 0));
// test getAllDims(0)
- expectThrows(
- IllegalArgumentException.class,
- () -> {
- facets.getAllDims(0);
- });
+ expectThrows(IllegalArgumentException.class, () -> facets.getAllDims(0));
iw.close();
IOUtils.close(taxoWriter, taxoReader, taxoDir, r, indexDir);
@@ -852,9 +795,8 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
2,
2,
- new LabelAndValue[] {
- new LabelAndValue("Bob", 1), new LabelAndValue("Lisa", 1),
- });
+ new LabelAndValue("Bob", 1),
+ new LabelAndValue("Lisa", 1));
// -- delete to trigger liveDocs != null
writer.deleteDocuments(new Term("id", "0"));
@@ -873,9 +815,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
1,
1,
- new LabelAndValue[] {
- new LabelAndValue("Lisa", 1),
- });
+ new LabelAndValue("Lisa", 1));
IOUtils.close(
writer,
@@ -926,9 +866,8 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
2,
2,
- new LabelAndValue[] {
- new LabelAndValue("Bob", 1), new LabelAndValue("Lisa", 1),
- });
+ new LabelAndValue("Bob", 1),
+ new LabelAndValue("Lisa", 1));
// -- delete to trigger liveDocs != null
writer.deleteDocuments(new Term("id", "0"));
@@ -947,9 +886,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
new String[0],
1,
1,
- new LabelAndValue[] {
- new LabelAndValue("Lisa", 1),
- });
+ new LabelAndValue("Lisa", 1));
IOUtils.close(
writer,
@@ -1077,12 +1014,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
List<FacetLabel> facetLabels = new ArrayList<>();
for (int j = 0; j < numDims; j++) {
if (doc.dims[j] != null) {
- Integer v = expectedCounts[j].get(doc.dims[j]);
- if (v == null) {
- expectedCounts[j].put(doc.dims[j], 1);
- } else {
- expectedCounts[j].put(doc.dims[j], v.intValue() + 1);
- }
+ expectedCounts[j].merge(doc.dims[j], 1, Integer::sum);
// Add document facet labels
facetLabels.add(new FacetLabel("dim" + j, doc.dims[j]));
}
@@ -1106,12 +1038,12 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
"dim" + i,
new String[0],
totCount,
- labelValues.toArray(new LabelAndValue[labelValues.size()]),
+ labelValues.toArray(new LabelAndValue[0]),
labelValues.size()));
}
}
- // Sort by highest value, tie break by value:
+ // Sort by highest value, tie-break by value:
sortFacetResults(expected);
List<FacetResult> actual = facets.getAllDims(10);
@@ -1130,7 +1062,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
// Test facet labels for each matching test doc
List<List<FacetLabel>> actualLabels = getAllTaxonomyFacetLabels(null, tr, fc);
assertEquals(expectedLabels.size(), actualLabels.size());
- assertTrue(sortedFacetLabels(expectedLabels).equals(sortedFacetLabels(actualLabels)));
+ assertEquals(sortedFacetLabels(expectedLabels), sortedFacetLabels(actualLabels));
// Test facet labels for each matching test doc, given a specific dimension chosen randomly
final String dimension = "dim" + random().nextInt(numDims);
@@ -1138,7 +1070,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
list -> list.removeIf(f -> f.components[0].equals(dimension) == false));
actualLabels = getAllTaxonomyFacetLabels(dimension, tr, fc);
- assertTrue(sortedFacetLabels(expectedLabels).equals(sortedFacetLabels(actualLabels)));
+ assertEquals(sortedFacetLabels(expectedLabels), sortedFacetLabels(actualLabels));
}
w.close();
@@ -1152,8 +1084,7 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {
Collections.sort(facetLabels);
}
- Collections.sort(
- allFacetLabels,
+ allFacetLabels.sort(
(o1, o2) -> {
int diff = o1.size() - o2.size();
if (diff != 0) {
diff --git a/lucene/luke/src/java/org/apache/lucene/luke/models/tools/IndexToolsImpl.java b/lucene/luke/src/java/org/apache/lucene/luke/models/tools/IndexToolsImpl.java
index 9a4bfdc6f6e..4e594c477b1 100644
--- a/lucene/luke/src/java/org/apache/lucene/luke/models/tools/IndexToolsImpl.java
+++ b/lucene/luke/src/java/org/apache/lucene/luke/models/tools/IndexToolsImpl.java
@@ -17,10 +17,11 @@
package org.apache.lucene.luke.models.tools;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintStream;
-import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -208,7 +209,7 @@ public final class IndexToolsImpl extends LukeModel implements IndexTools {
throw new LukeException(
String.format(Locale.US, "Field %s does not contain any terms to be exported", field));
}
- try (BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))) {
+ try (BufferedWriter writer = Files.newBufferedWriter(path, UTF_8)) {
TermsEnum termsEnum = terms.iterator();
BytesRef term;
while (!Thread.currentThread().isInterrupted() && (term = termsEnum.next()) != null) {
diff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestNRTReplication.java b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestNRTReplication.java
index f4889eeeac7..37ed05af266 100644
--- a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestNRTReplication.java
+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestNRTReplication.java
@@ -17,11 +17,12 @@
package org.apache.lucene.replicator.nrt;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.carrotsearch.randomizedtesting.SeedUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -40,7 +41,6 @@ import org.apache.lucene.tests.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.tests.util.LuceneTestCase.SuppressSysoutChecks;
import org.apache.lucene.tests.util.TestRuleIgnoreTestSuites;
import org.apache.lucene.tests.util.TestUtil;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.SuppressForbidden;
// MockRandom's .sd file has no index header/footer:
@@ -120,12 +120,7 @@ public class TestNRTReplication extends LuceneTestCase {
Process p = pb.start();
- BufferedReader r;
- try {
- r = new BufferedReader(new InputStreamReader(p.getInputStream(), IOUtils.UTF_8));
- } catch (UnsupportedEncodingException uee) {
- throw new RuntimeException(uee);
- }
+ BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8));
int tcpPort = -1;
long initCommitVersion = -1;
diff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestStressNRTReplication.java b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestStressNRTReplication.java
index 808e5a6b1ec..d84de781cf2 100644
--- a/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestStressNRTReplication.java
+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/nrt/TestStressNRTReplication.java
@@ -17,14 +17,14 @@
package org.apache.lucene.replicator.nrt;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.carrotsearch.randomizedtesting.SeedUtils;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
import java.io.Writer;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -619,10 +619,7 @@ public class TestStressNRTReplication extends LuceneTestCase {
message("logging to " + childOut);
childLog =
Files.newBufferedWriter(
- childOut,
- StandardCharsets.UTF_8,
- StandardOpenOption.APPEND,
- StandardOpenOption.CREATE);
+ childOut, UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
childLog.write("\n\nSTART NEW CHILD:\n");
} else {
childLog = null;
@@ -637,12 +634,7 @@ public class TestStressNRTReplication extends LuceneTestCase {
Process p = pb.start();
- BufferedReader r;
- try {
- r = new BufferedReader(new InputStreamReader(p.getInputStream(), IOUtils.UTF_8));
- } catch (UnsupportedEncodingException uee) {
- throw new RuntimeException(uee);
- }
+ BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8));
int tcpPort = -1;
long initCommitVersion = -1;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseDocValuesFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseDocValuesFormatTestCase.java
index fc02a99bebc..8c412946b87 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseDocValuesFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseDocValuesFormatTestCase.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.tests.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
@@ -447,7 +448,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
Query query = new TermQuery(new Term("fieldname", "text"));
TopDocs hits = isearcher.search(query, 1);
assertEquals(1, hits.totalHits.value);
- BytesRef scratch = newBytesRef();
+ BytesRef scratch;
// Iterate through the results:
for (int i = 0; i < hits.scoreDocs.length; i++) {
int docID = hits.scoreDocs[i].doc;
@@ -735,7 +736,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
Query query = new TermQuery(new Term("fieldname", "text"));
TopDocs hits = isearcher.search(query, 1);
assertEquals(1, hits.totalHits.value);
- BytesRef scratch = newBytesRef();
+ BytesRef scratch;
// Iterate through the results:
StoredFields storedFields = isearcher.storedFields();
for (int i = 0; i < hits.scoreDocs.length; i++) {
@@ -774,7 +775,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
maybeWrapWithMergingReader(DirectoryReader.open(directory)); // read-only=true
assert ireader.leaves().size() == 1;
SortedDocValues dv = ireader.leaves().get(0).reader().getSortedDocValues("dv");
- BytesRef scratch = newBytesRef();
+ BytesRef scratch;
assertEquals(0, dv.nextDoc());
scratch = dv.lookupOrd(dv.ordValue());
assertEquals("hello world 1", scratch.utf8ToString());
@@ -2503,10 +2504,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
for (int i = 0; i < numIterations; i++) {
final long min = -(((long) random().nextInt(1 << 30)) << 32);
final long mul = random().nextInt() & 0xFFFFFFFFL;
- final LongSupplier longs =
- () -> {
- return min + mul * random().nextInt(1 << 20);
- };
+ final LongSupplier longs = () -> min + mul * random().nextInt(1 << 20);
doTestNumericsVsStoredFields(density, longs);
}
}
@@ -2524,10 +2522,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
// the GCD of 0 and MIN_VALUE is negative
int numIterations = atLeast(1);
for (int i = 0; i < numIterations; i++) {
- final LongSupplier longs =
- () -> {
- return random().nextBoolean() ? 0 : Long.MIN_VALUE;
- };
+ final LongSupplier longs = () -> random().nextBoolean() ? 0 : Long.MIN_VALUE;
doTestNumericsVsStoredFields(1, longs);
}
}
@@ -2926,9 +2921,9 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
assertNotNull(sortedNumeric);
assertEquals(j, sortedNumeric.nextDoc());
assertEquals(numValues.length, sortedNumeric.docValueCount());
- for (int k = 0; k < numValues.length; k++) {
+ for (String numValue : numValues) {
long v = sortedNumeric.nextValue();
- assertEquals(numValues[k], Long.toString(v));
+ assertEquals(numValue, Long.toString(v));
}
}
}
@@ -3001,7 +2996,7 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
public void run() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- PrintStream infoStream = new PrintStream(bos, false, IOUtils.UTF_8);
+ PrintStream infoStream = new PrintStream(bos, false, UTF_8);
startingGun.await();
for (LeafReaderContext leaf : r.leaves()) {
DocValuesStatus status =
@@ -3016,12 +3011,12 @@ public abstract class BaseDocValuesFormatTestCase extends BaseIndexFileFormatTes
}
};
}
- for (int tid = 0; tid < threads.length; tid++) {
- threads[tid].start();
+ for (Thread thread : threads) {
+ thread.start();
}
startingGun.countDown();
- for (int tid = 0; tid < threads.length; tid++) {
- threads[tid].join();
+ for (Thread thread : threads) {
+ thread.join();
}
r.close();
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
index 6172d8eb140..29a1fe0fa08 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseKnnVectorsFormatTestCase.java
@@ -16,6 +16,7 @@
*/
package org.apache.lucene.tests.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
import java.io.ByteArrayOutputStream;
@@ -56,7 +57,6 @@ import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.tests.util.TestUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.VectorUtil;
import org.junit.Before;
@@ -555,7 +555,7 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
}
}
- // Write vectors, one segment with with SimpleText, another with default codec, then forceMerge
+ // Write vectors, one segment with SimpleText, another with default codec, then forceMerge
public void testDifferentCodecs2() throws Exception {
IndexWriterConfig iwc = newIndexWriterConfig();
iwc.setCodec(Codec.forName("SimpleText"));
@@ -1091,7 +1091,7 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
/**
* Index random vectors, sometimes skipping documents, sometimes updating a document, sometimes
- * merging, sometimes sorting the index, using an HNSW similarity function so as to also produce a
+ * merging, sometimes sorting the index, using an HNSW similarity function to also produce a
* graph, and verify that the expected values can be read back consistently.
*/
public void testRandomWithUpdatesAndGraph() throws Exception {
@@ -1289,7 +1289,7 @@ public abstract class BaseKnnVectorsFormatTestCase extends BaseIndexFileFormatTe
assertEquals(2, segStatus.vectorValuesStatus.totalKnnVectorFields);
// Make sure CheckIndex in fact declares that it is testing vectors!
- assertTrue(output.toString(IOUtils.UTF_8).contains("test: vectors..."));
+ assertTrue(output.toString(UTF_8).contains("test: vectors..."));
}
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTestCheckIndex.java b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTestCheckIndex.java
index 1573aa63728..621e2f8baf5 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTestCheckIndex.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/index/BaseTestCheckIndex.java
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.tests.index;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -33,7 +35,6 @@ import org.apache.lucene.tests.analysis.MockAnalyzer;
import org.apache.lucene.tests.util.LineFileDocs;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.apache.lucene.tests.util.TestUtil;
-import org.apache.lucene.util.IOUtils;
/** Base class for CheckIndex tests. */
public class BaseTestCheckIndex extends LuceneTestCase {
@@ -58,13 +59,13 @@ public class BaseTestCheckIndex extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8));
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8));
checker.setLevel(CheckIndex.Level.MIN_LEVEL_FOR_INTEGRITY_CHECKS);
if (VERBOSE) checker.setInfoStream(System.out);
CheckIndex.Status indexStatus = checker.checkIndex();
if (indexStatus.clean == false) {
System.out.println("CheckIndex failed");
- System.out.println(bos.toString(IOUtils.UTF_8));
+ System.out.println(bos.toString(UTF_8));
fail();
}
@@ -99,7 +100,7 @@ public class BaseTestCheckIndex extends LuceneTestCase {
final List<String> onlySegments = new ArrayList<>();
onlySegments.add("_0");
- assertTrue(checker.checkIndex(onlySegments).clean == true);
+ assertTrue(checker.checkIndex(onlySegments).clean);
checker.close();
}
@@ -118,7 +119,7 @@ public class BaseTestCheckIndex extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, false, IOUtils.UTF_8));
+ checker.setInfoStream(new PrintStream(bos, false, UTF_8));
if (VERBOSE) checker.setInfoStream(System.out);
CheckIndex.Status indexStatus = checker.checkIndex();
assertTrue(indexStatus.clean);
@@ -141,7 +142,7 @@ public class BaseTestCheckIndex extends LuceneTestCase {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
- checker.setInfoStream(new PrintStream(bos, true, IOUtils.UTF_8));
+ checker.setInfoStream(new PrintStream(bos, true, UTF_8));
if (VERBOSE) checker.setInfoStream(System.out);
CheckIndex.Status indexStatus = checker.checkIndex();
assertTrue(indexStatus.clean);
@@ -155,11 +156,7 @@ public class BaseTestCheckIndex extends LuceneTestCase {
iw.commit();
// keep IW open... should not be able to obtain write lock
- expectThrows(
- LockObtainFailedException.class,
- () -> {
- new CheckIndex(dir);
- });
+ expectThrows(LockObtainFailedException.class, () -> new CheckIndex(dir));
iw.close();
}
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 ece42e002bd..8bed935f7db 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
@@ -16,6 +16,8 @@
*/
package org.apache.lucene.tests.util;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
@@ -103,12 +105,9 @@ import org.apache.lucene.tests.codecs.blockterms.LuceneFixedGap;
import org.apache.lucene.tests.mockfile.FilterFileSystem;
import org.apache.lucene.tests.mockfile.VirusCheckingFS;
import org.apache.lucene.tests.mockfile.WindowsFS;
-import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeImpl;
-import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.UnicodeUtil;
import org.junit.Assert;
@@ -249,8 +248,7 @@ public final class TestUtil {
*/
public static <T> void checkReadOnly(Collection<T> coll) {
int size = 0;
- for (Iterator<?> it = coll.iterator(); it.hasNext(); ) {
- it.next();
+ for (@SuppressWarnings("unused") T t : coll) {
size += 1;
}
if (size != coll.size()) {
@@ -331,7 +329,7 @@ public final class TestUtil {
new CheckIndex(dir, NoLockFactory.INSTANCE.obtainLock(dir, "bogus"))) {
checker.setLevel(level);
checker.setFailFast(failFast);
- checker.setInfoStream(new PrintStream(output, false, IOUtils.UTF_8), false);
+ checker.setInfoStream(new PrintStream(output, false, UTF_8), false);
if (concurrent) {
checker.setThreadCount(RandomizedTest.randomIntBetween(2, 5));
} else {
@@ -341,11 +339,11 @@ public final class TestUtil {
if (indexStatus == null || indexStatus.clean == false) {
System.out.println("CheckIndex failed");
- System.out.println(output.toString(IOUtils.UTF_8));
+ System.out.println(output.toString(UTF_8));
throw new RuntimeException("CheckIndex failed");
} else {
if (LuceneTestCase.INFOSTREAM) {
- System.out.println(output.toString(IOUtils.UTF_8));
+ System.out.println(output.toString(UTF_8));
}
return indexStatus;
}
@@ -364,7 +362,7 @@ public final class TestUtil {
public static void checkReader(LeafReader reader, int level) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
- PrintStream infoStream = new PrintStream(bos, false, IOUtils.UTF_8);
+ PrintStream infoStream = new PrintStream(bos, false, UTF_8);
final CodecReader codecReader;
if (reader instanceof CodecReader) {
@@ -386,7 +384,7 @@ public final class TestUtil {
checkReaderSanity(reader);
if (LuceneTestCase.INFOSTREAM) {
- System.out.println(bos.toString(IOUtils.UTF_8));
+ System.out.println(bos.toString(UTF_8));
}
// FieldInfos should be cached at the reader and always return the same instance
@@ -575,7 +573,7 @@ public final class TestUtil {
}
/**
- * Returns a String thats "regexpish" (contains lots of operators typically found in regular
+ * Returns a String that's "regexpish" (contains lots of operators typically found in regular
* expressions) If you call this enough times, you might get a valid regex!
*/
public static String randomRegexpishString(Random r) {
@@ -603,7 +601,7 @@ public final class TestUtil {
"|");
/**
- * Returns a String thats "regexpish" (contains lots of operators typically found in regular
+ * Returns a String that's "regexpish" (contains lots of operators typically found in regular
* expressions) If you call this enough times, you might get a valid regex!
*
* <p>Note: to avoid practically endless backtracking patterns we replace asterisk and plus
@@ -1146,9 +1144,9 @@ public final class TestUtil {
int t;
if (bytes >= 4) {
t = r.nextInt(5);
- } else if (bytes >= 3) {
+ } else if (bytes == 3) {
t = r.nextInt(4);
- } else if (bytes >= 2) {
+ } else if (bytes == 2) {
t = r.nextInt(2);
} else {
t = 0;
@@ -1230,14 +1228,14 @@ public final class TestUtil {
/**
* Returns the actual default codec (e.g. LuceneMNCodec) for this version of Lucene. This may be
- * different than {@link Codec#getDefault()} because that is randomized.
+ * different from {@link Codec#getDefault()} because that is randomized.
*/
public static Codec getDefaultCodec() {
return new Lucene99Codec();
}
/**
- * Returns the actual default postings format (e.g. LuceneMNPostingsFormat for this version of
+ * Returns the actual default postings format (e.g. LuceneMNPostingsFormat) for this version of
* Lucene.
*/
public static PostingsFormat getDefaultPostingsFormat() {
@@ -1245,7 +1243,7 @@ public final class TestUtil {
}
/**
- * Returns the actual default postings format (e.g. LuceneMNPostingsFormat for this version of
+ * Returns the actual default postings format (e.g. LuceneMNPostingsFormat) for this version of
* Lucene.
*
* @lucene.internal this may disappear at any time
@@ -1270,7 +1268,7 @@ public final class TestUtil {
}
/**
- * Returns the actual default docvalues format (e.g. LuceneMNDocValuesFormat for this version of
+ * Returns the actual default docvalues format (e.g. LuceneMNDocValuesFormat) for this version of
* Lucene.
*/
public static DocValuesFormat getDefaultDocValuesFormat() {
@@ -1315,7 +1313,7 @@ public final class TestUtil {
}
/**
- * Returns the actual default vector format (e.g. LuceneMNKnnVectorsFormat for this version of
+ * Returns the actual default vector format (e.g. LuceneMNKnnVectorsFormat) for this version of
* Lucene.
*/
public static KnnVectorsFormat getDefaultKnnVectorsFormat() {
@@ -1339,7 +1337,7 @@ public final class TestUtil {
leaves.add(SlowCodecReaderWrapper.wrap(context.reader()));
}
}
- writer.addIndexes(leaves.toArray(new CodecReader[leaves.size()]));
+ writer.addIndexes(leaves.toArray(new CodecReader[0]));
}
/** just tries to configure things to keep the open file count lowish */
@@ -1357,7 +1355,7 @@ public final class TestUtil {
}
MergeScheduler ms = w.getConfig().getMergeScheduler();
if (ms instanceof ConcurrentMergeScheduler) {
- // wtf... shouldnt it be even lower since it's 1 by default?!?!
+ // wtf... shouldn't it be even lower since it's 1 by default?!?!
((ConcurrentMergeScheduler) ms).setMaxMergesAndThreads(3, 2);
}
}
@@ -1370,13 +1368,7 @@ public final class TestUtil {
public static <T> void assertAttributeReflection(
final AttributeImpl att, Map<String, T> reflectedValues) {
final Map<String, Object> map = new HashMap<>();
- att.reflectWith(
- new AttributeReflector() {
- @Override
- public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
- map.put(attClass.getName() + '#' + key, value);
- }
- });
+ att.reflectWith((attClass, key, value) -> map.put(attClass.getName() + '#' + key, value));
Assert.assertEquals("Reflection does not produce same map", reflectedValues, map);
}
@@ -1624,7 +1616,7 @@ public final class TestUtil {
if (evilness < 10) {
sb.append(TestUtil.randomSimpleString(random, wordLength));
} else if (evilness < 15) {
- assert sb.length() == 0; // we should always get wordLength back!
+ assert sb.isEmpty(); // we should always get wordLength back!
sb.append(TestUtil.randomRealisticUnicodeString(random, wordLength, wordLength));
} else if (evilness == 16) {
sb.append(TestUtil.randomHtmlishString(random, wordLength));
@@ -1662,11 +1654,11 @@ public final class TestUtil {
return "(null)";
} else {
try {
- return br.utf8ToString() + " " + br.toString();
+ return br.utf8ToString() + " " + br;
} catch (@SuppressWarnings("unused") AssertionError | IllegalArgumentException t) {
- // If BytesRef isn't actually UTF8, or it's eg a
+ // If BytesRef isn't actually UTF8, or it's e.g. a
// prefix of UTF8 that ends mid-unicode-char, we
- // fallback to hex:
+ // fall back to hex:
return br.toString();
}
}
diff --git a/lucene/test-framework/src/test/org/apache/lucene/tests/util/WithNestedTests.java b/lucene/test-framework/src/test/org/apache/lucene/tests/util/WithNestedTests.java
index d50b9a63b3f..1a88aa938c2 100644
--- a/lucene/test-framework/src/test/org/apache/lucene/tests/util/WithNestedTests.java
+++ b/lucene/test-framework/src/test/org/apache/lucene/tests/util/WithNestedTests.java
@@ -16,17 +16,16 @@
*/
package org.apache.lucene.tests.util;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.SysGlobals;
import com.carrotsearch.randomizedtesting.rules.TestRuleAdapter;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.lucene.tests.util.LuceneTestCase.SuppressSysoutChecks;
-import org.apache.lucene.util.IOUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
@@ -57,7 +56,7 @@ public abstract class WithNestedTests {
}
}
- private boolean suppressOutputStreams;
+ private final boolean suppressOutputStreams;
protected WithNestedTests(boolean suppressOutputStreams) {
this.suppressOutputStreams = suppressOutputStreams;
@@ -83,7 +82,7 @@ public abstract class WithNestedTests {
// We're running with a complex test filter that is properly handled by classes
// which are executed by RandomizedRunner. The "outer" classes testing
// LuceneTestCase
- // itself are executed by the default JUnit runner and would be always executed.
+ // itself are executed by the default JUnit runner and would always be executed.
// We thus always skip execution if any filtering is detected.
Assume.assumeTrue(false);
}
@@ -138,14 +137,10 @@ public abstract class WithNestedTests {
prevSysOut = System.out;
prevSysErr = System.err;
- try {
- sysout = new ByteArrayOutputStream();
- System.setOut(new PrintStream(sysout, true, IOUtils.UTF_8));
- syserr = new ByteArrayOutputStream();
- System.setErr(new PrintStream(syserr, true, IOUtils.UTF_8));
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
+ sysout = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(sysout, true, UTF_8));
+ syserr = new ByteArrayOutputStream();
+ System.setErr(new PrintStream(syserr, true, UTF_8));
}
FailureMarker.resetFailures();
@@ -178,7 +173,7 @@ public abstract class WithNestedTests {
+ " but was "
+ result.getFailureCount()
+ ", failures below: "
- + b.toString(),
+ + b,
true);
}
}
@@ -186,12 +181,12 @@ public abstract class WithNestedTests {
protected String getSysOut() {
Assert.assertTrue(suppressOutputStreams);
System.out.flush();
- return new String(sysout.toByteArray(), StandardCharsets.UTF_8);
+ return sysout.toString(UTF_8);
}
protected String getSysErr() {
Assert.assertTrue(suppressOutputStreams);
System.err.flush();
- return new String(syserr.toByteArray(), StandardCharsets.UTF_8);
+ return syserr.toString(UTF_8);
}
}