Apache Solr open-source search software
SOLR-16903: Migrate all tests using File to NIO Path (#3263)
Matthew Biscocho86f2afded125
diff --git a/gradle/testing/randomization/policies/solr-tests.policy b/gradle/testing/randomization/policies/solr-tests.policyindex 56f97971d20..c869aa9af80 100644--- a/gradle/testing/randomization/policies/solr-tests.policy+++ b/gradle/testing/randomization/policies/solr-tests.policy@@ -198,6 +198,9 @@ grant {permission "java.net.URLPermission" "http://[::1]:*/solr/-", "HEAD,GET,PUT,POST:*";permission "java.net.URLPermission" "https://[::1]:*/solr/-", "HEAD,GET,PUT,POST:*";permission "java.net.URLPermission" "socket://[::1]:*", "CONNECT:*";++ // Needed by TestCoreDiscovery+ permission java.lang.RuntimePermission "accessUserInformation";};// additional permissions based on system properties set by /bin/solrdiff --git a/solr/benchmark/src/java/org/apache/solr/bench/MiniClusterState.java b/solr/benchmark/src/java/org/apache/solr/bench/MiniClusterState.javaindex 39c1745d387..7aee416c948 100755--- a/solr/benchmark/src/java/org/apache/solr/bench/MiniClusterState.java+++ b/solr/benchmark/src/java/org/apache/solr/bench/MiniClusterState.java@@ -20,13 +20,13 @@ import static org.apache.commons.io.file.PathUtils.deleteDirectory;import static org.apache.solr.bench.BaseBenchState.log;import com.codahale.metrics.Meter;-import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.io.PrintStream;import java.lang.management.ManagementFactory;import java.net.URL;import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@@ -130,8 +130,7 @@ public class MiniClusterState {benchmarkParams.getBenchmark() + ".txt");Files.createDirectories(metricsResults.getParent());- cluster.dumpMetrics(- metricsResults.getParent().toFile(), metricsResults.getFileName().toString());+ cluster.dumpMetrics(metricsResults.getParent(), metricsResults.getFileName().toString());}/**@@ -170,8 +169,14 @@ public class MiniClusterState {long clusterSize =Files.walk(node).filter(Files::isRegularFile)- .map(Path::toFile)- .mapToLong(File::length)+ .mapToLong(+ file -> {+ try {+ return Files.size(file);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }).sum();log("mini cluster node size (bytes) " + node + " " + clusterSize);} catch (IOException e) {@@ -553,7 +558,9 @@ public class MiniClusterState {*/public static Path getFile(String name) {final URL url =- MiniClusterState.class.getClassLoader().getResource(name.replace(File.separatorChar, '/'));+ MiniClusterState.class+ .getClassLoader()+ .getResource(name.replace(FileSystems.getDefault().getSeparator(), "/"));if (url != null) {try {return Path.of(url.toURI());diff --git a/solr/core/src/java/org/apache/solr/blockcache/BlockDirectory.java b/solr/core/src/java/org/apache/solr/blockcache/BlockDirectory.javaindex b9cff0bbcc7..63d1db252b9 100644--- a/solr/core/src/java/org/apache/solr/blockcache/BlockDirectory.java+++ b/solr/core/src/java/org/apache/solr/blockcache/BlockDirectory.java@@ -16,10 +16,11 @@*/package org.apache.solr.blockcache;-import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Set;import org.apache.lucene.index.IndexFileNames;import org.apache.lucene.store.Directory;@@ -289,12 +290,12 @@ public class BlockDirectory extends FilterDirectory implements ShutdownAwareDireprivate long getFileModified(String name) throws IOException {if (in instanceof FSDirectory) {- File directory = ((FSDirectory) in).getDirectory().toFile();- File file = new File(directory, name);- if (!file.exists()) {+ Path directory = ((FSDirectory) in).getDirectory();+ Path file = directory.resolve(name);+ if (!Files.exists(file)) {throw new FileNotFoundException("File [" + name + "] not found");}- return file.lastModified();+ return Files.getLastModifiedTime(file).toMillis();} else {throw new UnsupportedOperationException();}diff --git a/solr/core/src/java/org/apache/solr/cli/CreateTool.java b/solr/core/src/java/org/apache/solr/cli/CreateTool.javaindex 12ed4f76711..e297baa9e80 100644--- a/solr/core/src/java/org/apache/solr/cli/CreateTool.java+++ b/solr/core/src/java/org/apache/solr/cli/CreateTool.java@@ -20,13 +20,13 @@ import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;+import java.nio.file.StandardCopyOption;import java.util.Locale;import java.util.Set;import java.util.concurrent.TimeUnit;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;-import org.apache.commons.io.FileUtils;import org.apache.commons.io.file.PathUtils;import org.apache.solr.cli.CommonCLIOptions.DefaultValues;import org.apache.solr.client.solrj.SolrClient;@@ -185,7 +185,7 @@ public class CreateTool extends ToolBase {"Failed to create new core instance directory: " + coreInstanceDir.toAbsolutePath());}- FileUtils.copyDirectoryToDirectory(confDir.toFile(), coreInstanceDir.toFile());+ PathUtils.copyDirectory(confDir, coreInstanceDir, StandardCopyOption.COPY_ATTRIBUTES);echoIfVerbose("\nCopying configuration to new core instance directory:\n"diff --git a/solr/core/src/test/org/apache/solr/AnalysisAfterCoreReloadTest.java b/solr/core/src/test/org/apache/solr/AnalysisAfterCoreReloadTest.javaindex 6fcdecc17e7..900768ae42b 100644--- a/solr/core/src/test/org/apache/solr/AnalysisAfterCoreReloadTest.java+++ b/solr/core/src/test/org/apache/solr/AnalysisAfterCoreReloadTest.java@@ -18,12 +18,12 @@ package org.apache.solr;import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import org.apache.commons.io.FileUtils;+import java.nio.file.StandardCopyOption;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;@@ -41,9 +41,9 @@ public class AnalysisAfterCoreReloadTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {- String tmpSolrHome = createTempDir().toFile().getAbsolutePath();- FileUtils.copyDirectory(new File(TEST_HOME()), new File(tmpSolrHome).getAbsoluteFile());- initCore("solrconfig.xml", "schema.xml", new File(tmpSolrHome).getAbsolutePath());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome, StandardCopyOption.COPY_ATTRIBUTES);+ initCore("solrconfig.xml", "schema.xml", tmpSolrHome);}@AfterClassdiff --git a/solr/core/src/test/org/apache/solr/SolrInfoBeanTest.java b/solr/core/src/test/org/apache/solr/SolrInfoBeanTest.javaindex 8b9fc1c48fe..c09be4fccfd 100644--- a/solr/core/src/test/org/apache/solr/SolrInfoBeanTest.java+++ b/solr/core/src/test/org/apache/solr/SolrInfoBeanTest.java@@ -16,12 +16,14 @@*/package org.apache.solr;-import java.io.File;import java.net.URI;import java.net.URL;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;+import java.util.stream.Stream;import org.apache.lucene.tests.util.TestUtil;import org.apache.solr.core.SolrInfoBean;import org.apache.solr.handler.admin.LukeRequestHandler;@@ -88,30 +90,37 @@ public class SolrInfoBeanTest extends SolrTestCaseJ4 {}private static List<Class<?>> getClassesForPackage(String pckgname) throws Exception {- ArrayList<File> directories = new ArrayList<>();+ ArrayList<Path> directories = new ArrayList<>();ClassLoader cld = h.getCore().getResourceLoader().getClassLoader();String path = pckgname.replace('.', '/');Enumeration<URL> resources = cld.getResources(path);while (resources.hasMoreElements()) {final URI uri = resources.nextElement().toURI();if (!"file".equalsIgnoreCase(uri.getScheme())) continue;- final File f = new File(uri);+ final Path f = Path.of(uri);directories.add(f);}ArrayList<Class<?>> classes = new ArrayList<>();- for (File directory : directories) {- if (directory.exists()) {- String[] files = directory.list();- for (String file : files) {- if (file.endsWith(".class")) {- String clazzName = file.substring(0, file.length() - 6);- // exclude Test classes that happen to be in these packages.- // class.ForName'ing some of them can cause trouble.- if (!clazzName.endsWith("Test") && !clazzName.startsWith("Test")) {- classes.add(Class.forName(pckgname + '.' + clazzName));- }- }+ for (Path directory : directories) {+ if (Files.exists(directory)) {+ try (Stream<Path> files = Files.list(directory)) {+ files.forEach(+ (file) -> {+ String fileName = file.getFileName().toString();+ if (fileName.endsWith(".class")) {+ String clazzName = fileName.substring(0, fileName.length() - 6);+ // exclude Test classes that happen to be in these packages.+ // class.ForName'ing some of them can cause trouble.+ if (!clazzName.endsWith("Test") && !clazzName.startsWith("Test")) {+ try {+ classes.add(Class.forName(pckgname + '.' + clazzName));+ } catch (ClassNotFoundException e) {+ throw new RuntimeException(e);+ }+ }+ }+ });}}}diff --git a/solr/core/src/test/org/apache/solr/SolrTestCaseJ4Test.java b/solr/core/src/test/org/apache/solr/SolrTestCaseJ4Test.javaindex 74d53019dbe..f565649adf7 100644--- a/solr/core/src/test/org/apache/solr/SolrTestCaseJ4Test.java+++ b/solr/core/src/test/org/apache/solr/SolrTestCaseJ4Test.java@@ -16,10 +16,9 @@*/package org.apache.solr;-import java.io.File;import java.nio.file.Files;import java.nio.file.Path;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.common.params.ModifiableSolrParams;import org.junit.AfterClass;import org.junit.BeforeClass;@@ -31,24 +30,24 @@ public class SolrTestCaseJ4Test extends SolrTestCaseJ4 {public static void beforeClass() throws Exception {// Create a temporary directory that holds a core NOT named "collection1". Use the smallest// configuration sets we can, so we don't copy that much junk around.- String tmpSolrHome = createTempDir().toFile().getAbsolutePath();+ Path tmpSolrHome = createTempDir();- Path subHome = Path.of(tmpSolrHome, "core0", "conf");+ Path subHome = tmpSolrHome.resolve("core0/conf");Files.createDirectories(subHome);- String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";- Files.copy(Path.of(top, "schema-tiny.xml"), subHome.resolve("schema-tiny.xml"));- Files.copy(Path.of(top, "solrconfig-minimal.xml"), subHome.resolve("solrconfig-minimal.xml"));+ Path top = SolrTestCaseJ4.TEST_HOME().resolve("collection1/conf");+ Files.copy(top.resolve("schema-tiny.xml"), subHome.resolve("schema-tiny.xml"));+ Files.copy(top.resolve("solrconfig-minimal.xml"), subHome.resolve("solrconfig-minimal.xml"));Files.copy(- Path.of(top, "solrconfig.snippet.randomindexconfig.xml"),+ top.resolve("solrconfig.snippet.randomindexconfig.xml"),subHome.resolve("solrconfig.snippet.randomindexconfig.xml"));- FileUtils.copyDirectory(new File(tmpSolrHome, "core0"), new File(tmpSolrHome, "core1"));+ PathUtils.copyDirectory(tmpSolrHome.resolve("core0"), tmpSolrHome.resolve("core1"));// Core discovery will default to the name of the dir the core.properties file is in. So if// everything else is OK as defaults, just the _presence_ of this file is sufficient.- FileUtils.touch(new File(tmpSolrHome, "core0/core.properties"));- FileUtils.touch(new File(tmpSolrHome, "core1/core.properties"));+ PathUtils.touch(tmpSolrHome.resolve("core0/core.properties"));+ PathUtils.touch(tmpSolrHome.resolve("core1/core.properties"));- Files.copy(getFile("solr/solr.xml"), Path.of(tmpSolrHome, "solr.xml"));+ Files.copy(getFile("solr/solr.xml"), tmpSolrHome.resolve("solr.xml"));initCore("solrconfig-minimal.xml", "schema-tiny.xml", tmpSolrHome, "core1");}diff --git a/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java b/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.javaindex 693cb7fdfa3..d2f6f47eb06 100644--- a/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java+++ b/solr/core/src/test/org/apache/solr/TestCpuTimeSearch.java@@ -48,7 +48,7 @@ public class TestCpuTimeSearch extends SolrTestCaseJ4 {System.setProperty(AllowListUrlChecker.DISABLE_URL_ALLOW_LIST, "true");Path configSet = createTempDir("configSet");- copyMinConf(configSet.toFile());+ copyMinConf(configSet);solrRule.startSolr(LuceneTestCase.createTempDir());solrRule.newCollection("core1").withConfigSet(configSet.toString()).create();diff --git a/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java b/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.javaindex 2c69a823a50..aad315e3eb9 100644--- a/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java+++ b/solr/core/src/test/org/apache/solr/TestSolrCoreProperties.java@@ -49,7 +49,7 @@ public class TestSolrCoreProperties extends SolrJettyTestBase {Files.createDirectories(dataDir);Files.createDirectories(confDir);- Files.copy(Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"), homeDir.resolve("solr.xml"));+ Files.copy(SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"), homeDir.resolve("solr.xml"));String src_dir = TEST_HOME() + "/collection1/conf";Files.copy(Path.of(src_dir, "schema-tiny.xml"), confDir.resolve("schema.xml"));Files.copy(@@ -71,7 +71,7 @@ public class TestSolrCoreProperties extends SolrJettyTestBase {Properties nodeProperties = new Properties();// this sets the property for jetty starting SolrDispatchFilterif (System.getProperty("solr.data.dir") == null) {- nodeProperties.setProperty("solr.data.dir", createTempDir().toFile().getCanonicalPath());+ nodeProperties.setProperty("solr.data.dir", createTempDir().toRealPath().toString());}solrClientTestRule.startSolr(homeDir, nodeProperties, JettyConfig.builder().build());diff --git a/solr/core/src/test/org/apache/solr/TestTolerantSearch.java b/solr/core/src/test/org/apache/solr/TestTolerantSearch.javaindex 868954c2a80..5d5841ba9e0 100644--- a/solr/core/src/test/org/apache/solr/TestTolerantSearch.java+++ b/solr/core/src/test/org/apache/solr/TestTolerantSearch.java@@ -16,7 +16,6 @@*/package org.apache.solr;-import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.nio.file.Files;@@ -45,23 +44,23 @@ public class TestTolerantSearch extends SolrJettyTestBase {private static String shard1;private static String shard2;- private static File createSolrHome() throws Exception {+ private static Path createSolrHome() throws Exception {Path workDir = createTempDir();- setupJettyTestHome(workDir.toFile(), "collection1");+ setupJettyTestHome(workDir, "collection1");Files.copy(Path.of(SolrTestCaseJ4.TEST_HOME() + "/collection1/conf/solrconfig-tolerant-search.xml"),workDir.resolve("collection1").resolve("conf").resolve("solrconfig.xml"),StandardCopyOption.REPLACE_EXISTING);FileUtils.copyDirectory(workDir.resolve("collection1").toFile(), workDir.resolve("collection2").toFile());- return workDir.toFile();+ return workDir;}@BeforeClasspublic static void createThings() throws Exception {systemSetPropertySolrDisableUrlAllowList("true");- File solrHome = createSolrHome();- createAndStartJetty(solrHome.getAbsolutePath());+ Path solrHome = createSolrHome();+ createAndStartJetty(solrHome);String url = getBaseUrl();collection1 = getHttpSolrClient(url, "collection1");collection2 = getHttpSolrClient(url, "collection2");diff --git a/solr/core/src/test/org/apache/solr/blockcache/BlockDirectoryTest.java b/solr/core/src/test/org/apache/solr/blockcache/BlockDirectoryTest.javaindex e114d1175a7..4e8078bc63c 100644--- a/solr/core/src/test/org/apache/solr/blockcache/BlockDirectoryTest.java+++ b/solr/core/src/test/org/apache/solr/blockcache/BlockDirectoryTest.java@@ -17,9 +17,9 @@package org.apache.solr.blockcache;import com.github.benmanes.caffeine.cache.Caffeine;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.Map;import java.util.Random;import org.apache.lucene.store.Directory;@@ -99,7 +99,7 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {private static final int MAX_BUFFER_SIZE = 12000;private static final int MAX_NUMBER_OF_READS = 20000;private BlockDirectory directory;- private File file;+ private Path file;private Random random;private MapperCache mapperCache;@@ -107,8 +107,8 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {@Beforepublic void setUp() throws Exception {super.setUp();- file = createTempDir().toFile();- FSDirectory dir = FSDirectory.open(new File(file, "base").toPath());+ file = createTempDir();+ FSDirectory dir = FSDirectory.open(file.resolve("base"));mapperCache = new MapperCache();if (random().nextBoolean()) {@@ -138,7 +138,7 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {@Testpublic void testEOF() throws IOException {- Directory fsDir = FSDirectory.open(new File(file, "normal").toPath());+ Directory fsDir = FSDirectory.open(file.resolve("normal"));String name = "test.eof";createFile(name, fsDir, directory);long fsLength = fsDir.fileLength(name);@@ -170,7 +170,7 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {int i = 0;try {for (; i < 10; i++) {- Directory fsDir = FSDirectory.open(new File(file, "normal").toPath());+ Directory fsDir = FSDirectory.open(file.resolve("normal"));String name = getName();createFile(name, fsDir, directory);assertInputsEquals(name, fsDir, directory);@@ -253,9 +253,9 @@ public class BlockDirectoryTest extends SolrTestCaseJ4 {return Long.toUnsignedString(random.nextLong());}- public static void rm(File file) {+ public static void rm(Path file) {try {- IOUtils.rm(file.toPath());+ IOUtils.rm(file);} catch (Throwable ignored) {// TODO: should this class care if a file couldnt be deleted?// this just emulates previous behavior, where only SecurityException would be handled.diff --git a/solr/core/src/test/org/apache/solr/cli/PostToolTest.java b/solr/core/src/test/org/apache/solr/cli/PostToolTest.javaindex 4783cacf1f7..7a3760992a3 100644--- a/solr/core/src/test/org/apache/solr/cli/PostToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/PostToolTest.java@@ -17,9 +17,8 @@package org.apache.solr.cli;+import java.io.BufferedWriter;import java.io.ByteArrayInputStream;-import java.io.File;-import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.net.URI;@@ -27,6 +26,8 @@ import java.net.URISyntaxException;import java.net.URL;import java.nio.ByteBuffer;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;@@ -73,9 +74,9 @@ public class PostToolTest extends SolrCloudTestCase {withBasicAuth(CollectionAdminRequest.createCollection(collection, "conf1", 1, 1, 0, 0)).processAndWait(cluster.getSolrClient(), 10);- File jsonDoc = File.createTempFile("temp", ".json");+ Path jsonDoc = Files.createTempFile("temp", ".json");- FileWriter fw = new FileWriter(jsonDoc, StandardCharsets.UTF_8);+ BufferedWriter fw = Files.newBufferedWriter(jsonDoc, StandardCharsets.UTF_8);Utils.writeJson(Map.of("id", "1", "title_s", "mytitle"), fw, true);fw.flush();@@ -87,7 +88,7 @@ public class PostToolTest extends SolrCloudTestCase {collection,"--credentials",SecurityJson.USER_PASS,- jsonDoc.getAbsolutePath()+ jsonDoc.toString(),};assertEquals(0, CLITestHelper.runTool(args, PostTool.class));@@ -117,14 +118,14 @@ public class PostToolTest extends SolrCloudTestCase {withBasicAuth(CollectionAdminRequest.createCollection(collection, "conf1", 1, 1, 0, 0)).processAndWait(cluster.getSolrClient(), 10);- File jsonDoc = File.createTempFile("temp", ".json");+ Path jsonDoc = Files.createTempFile("temp", ".json");- FileWriter fw = new FileWriter(jsonDoc, StandardCharsets.UTF_8);+ BufferedWriter fw = Files.newBufferedWriter(jsonDoc, StandardCharsets.UTF_8);Utils.writeJson(Map.of("id", "1", "title_s", "mytitle"), fw, true);fw.flush();String[] args = {- "post", "-c", collection, "--credentials", SecurityJson.USER_PASS, jsonDoc.getAbsolutePath()+ "post", "-c", collection, "--credentials", SecurityJson.USER_PASS, jsonDoc.toString(),};assertEquals(0, CLITestHelper.runTool(args, PostTool.class));@@ -154,9 +155,9 @@ public class PostToolTest extends SolrCloudTestCase {withBasicAuth(CollectionAdminRequest.createCollection(collection, "conf1", 1, 1, 0, 0)).processAndWait(cluster.getSolrClient(), 10);- File tsvDoc = File.createTempFile("temp", ".tsv");+ Path tsvDoc = Files.createTempFile("temp", ".tsv");- FileWriter fw = new FileWriter(tsvDoc, StandardCharsets.UTF_8);+ BufferedWriter fw = Files.newBufferedWriter(tsvDoc, StandardCharsets.UTF_8);fw.write("1\tmytitle\n");fw.close();@@ -170,7 +171,7 @@ public class PostToolTest extends SolrCloudTestCase {"\"separator=%09&header=false&fieldnames=id,title_s\"","--type","text/csv",- tsvDoc.getAbsolutePath()+ tsvDoc.toString(),};assertEquals(0, CLITestHelper.runTool(args, PostTool.class));@@ -270,12 +271,12 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testGuessType() {- File f = new File("foo.doc");- assertEquals("application/msword", PostTool.guessType(f.toPath()));- f = new File("foobar");- assertEquals("application/octet-stream", PostTool.guessType(f.toPath()));- f = new File("foo.json");- assertEquals("application/json", PostTool.guessType(f.toPath()));+ Path f = Path.of("foo.doc");+ assertEquals("application/msword", PostTool.guessType(f));+ f = Path.of("foobar");+ assertEquals("application/octet-stream", PostTool.guessType(f));+ f = Path.of("foo.json");+ assertEquals("application/json", PostTool.guessType(f));}@Test@@ -285,8 +286,7 @@ public class PostToolTest extends SolrCloudTestCase {postTool.recursive = 0;postTool.dryRun = true;postTool.solrUpdateUrl = URI.create("http://localhost:8983/solr/fake/update");- // TODO SOLR-8282 move to PATH- File dir = getFile("exampledocs").toFile();+ Path dir = getFile("exampledocs");int num = postTool.postFiles(new String[] {dir.toString()}, 0, null, null);assertEquals(2, num);}@@ -296,8 +296,8 @@ public class PostToolTest extends SolrCloudTestCase {ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);PostTool postTool = new PostTool(runtime);postTool.recursive = 1; // This is the default- File dir = getFile("exampledocs").toFile();- File doc = File.createTempFile("temp", ".json");+ Path dir = getFile("exampledocs");+ Path doc = Files.createTempFile("temp", ".json");assertTrue(postTool.recursionPossible(new String[] {dir.toString()}));assertFalse(postTool.recursionPossible(new String[] {doc.toString()}));assertTrue(postTool.recursionPossible(new String[] {doc.toString(), dir.toString()}));@@ -310,8 +310,7 @@ public class PostToolTest extends SolrCloudTestCase {postTool.recursive = 1; // This is the defaultpostTool.dryRun = true;postTool.solrUpdateUrl = URI.create("http://localhost:8983/solr/fake/update");- // TODO SOLR-8282 move to PATH- File dir = getFile("exampledocs").toFile();+ Path dir = getFile("exampledocs");int num = postTool.postFiles(new String[] {dir.toString()}, 0, null, null);assertEquals(2, num);}diff --git a/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java b/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.javaindex 75ab1e96150..696d65329c9 100644--- a/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java+++ b/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java@@ -17,13 +17,11 @@package org.apache.solr.cli;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.nio.file.SimpleFileVisitor;import java.nio.file.attribute.BasicFileAttributes;import java.util.ArrayList;@@ -53,7 +51,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {.withUrl(zkAddr).withTimeout(30000, TimeUnit.MILLISECONDS).build();- System.setProperty("solr.solr.home", TEST_HOME());+ System.setProperty("solr.solr.home", TEST_HOME().toString());}@AfterClass@@ -81,16 +79,10 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Now just use a name in the configsets directory, do we find it?configSet = TEST_PATH().resolve("configsets");- File confDir = new File(configSet.toFile(), "cloud-subdirs");+ Path confDir = configSet.resolve("cloud-subdirs");String[] args =new String[] {- "upconfig",- "--conf-name",- "upconfig2",- "--conf-dir",- confDir.getAbsolutePath(),- "-z",- zkAddr+ "upconfig", "--conf-name", "upconfig2", "--conf-dir", confDir.toString(), "-z", zkAddr};int res = CLITestHelper.runTool(args, ConfigSetUploadTool.class);@@ -117,8 +109,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {@Testpublic void testDownconfig() throws Exception {- Path tmp =- Paths.get(createTempDir("downConfigNewPlace").toAbsolutePath().toString(), "myconfset");+ Path tmp = createTempDir("downConfigNewPlace").resolve("myconfset");// First we need a configset on ZK to bring down.@@ -130,23 +121,16 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {String[] args =new String[] {- "downconfig",- "--conf-name",- "downconfig1",- "--conf-dir",- tmp.toAbsolutePath().toString(),- "-z",- zkAddr,+ "downconfig", "--conf-name", "downconfig1", "--conf-dir", tmp.toString(), "-z", zkAddr,};int res = CLITestHelper.runTool(args, ConfigSetDownloadTool.class);assertEquals("Download should have succeeded.", 0, res);- verifyZkLocalPathsMatch(- Paths.get(tmp.toAbsolutePath().toString(), "conf"), "/configs/downconfig1");+ verifyZkLocalPathsMatch(tmp.resolve("conf"), "/configs/downconfig1");// Ensure that empty files don't become directories (SOLR-11198)- Path emptyFile = Paths.get(tmp.toAbsolutePath().toString(), "conf", "stopwords", "emptyfile");+ Path emptyFile = tmp.resolve("conf").resolve("stopwords").resolve("emptyfile");Files.createFile(emptyFile);// Now copy it up and back and insure it's still a file in the new place@@ -154,21 +138,14 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {Path tmp2 = createTempDir("downConfigNewPlace2");args =new String[] {- "downconfig",- "--conf-name",- "downconfig2",- "--conf-dir",- tmp2.toAbsolutePath().toString(),- "-z",- zkAddr,+ "downconfig", "--conf-name", "downconfig2", "--conf-dir", tmp2.toString(), "-z", zkAddr,};res = CLITestHelper.runTool(args, ConfigSetDownloadTool.class);assertEquals("Download should have succeeded.", 0, res);- verifyZkLocalPathsMatch(- Paths.get(tmp.toAbsolutePath().toString(), "conf"), "/configs/downconfig2");+ verifyZkLocalPathsMatch(tmp.resolve("conf"), "/configs/downconfig2");// And insure the empty file is a text file- Path destEmpty = Paths.get(tmp2.toAbsolutePath().toString(), "conf", "stopwords", "emptyfile");+ Path destEmpty = tmp2.resolve("conf").resolve("stopwords").resolve("emptyfile");assertTrue("Empty files should NOT be copied down as directories", destEmpty.toFile().isFile());}@@ -192,14 +169,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// try with zk->localPath tmp = createTempDir("tmpNewPlace2");args =- new String[] {- "cp",- "--recursive",- "--zk-host",- zkAddr,- "zk:/configs/cp1",- "file:" + tmp.toAbsolutePath()- };+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", "file:" + tmp};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -208,14 +178,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// try with zk->local no file: prefixtmp = createTempDir("tmpNewPlace3");args =- new String[] {- "cp",- "--recursive",- "--zk-host",- zkAddr,- "zk:/configs/cp1",- tmp.toAbsolutePath().toString()- };+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", tmp.toString()};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -223,14 +186,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// try with local->zkargs =- new String[] {- "cp",- "--recursive",- "--zk-host",- zkAddr,- srcPathCheck.toAbsolutePath().toString(),- "zk:/cp3"- };+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, srcPathCheck.toString(), "zk:/cp3"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -238,24 +194,14 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// try with local->zk, file: specifiedargs =- new String[] {- "cp",- "--recursive",- "--zk-host",- zkAddr,- "file:" + srcPathCheck.toAbsolutePath(),- "zk:/cp4"- };+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, "file:" + srcPathCheck, "zk:/cp4"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(srcPathCheck, "/cp4");// try with recursive not specified, and therefore not happening- args =- new String[] {- "cp", "--zk-host", zkAddr, "file:" + srcPathCheck.toAbsolutePath(), "zk:/cp5Fail"- };+ args = new String[] {"cp", "--zk-host", zkAddr, "file:" + srcPathCheck, "zk:/cp5Fail"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertTrue("Copy should NOT have succeeded, recursive not specified.", 0 != res);@@ -265,14 +211,21 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// copy to local ending in separator// src and cp3 and cp4 are valid- String localSlash = tmp.normalize() + File.separator + "cpToLocal" + File.separator;- args = new String[] {"cp", "--zk-host", zkAddr, "zk:/cp3/schema.xml", localSlash};+ String localSlash = tmp.normalize().resolve("cpToLocal").toString();+ args =+ new String[] {+ "cp",+ "--zk-host",+ zkAddr,+ "zk:/cp3/schema.xml",+ localSlash + tmp.getFileSystem().getSeparator()+ };res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should nave created intermediate directory locally.", 0, res);assertTrue("File should have been copied to a directory successfully",- Files.exists(Paths.get(localSlash, "schema.xml")));+ Files.exists(Path.of(localSlash, "schema.xml")));// copy to ZK ending in '/'.// src and cp3 are valid@@ -281,7 +234,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {"cp","--zk-host",zkAddr,- "file:" + srcPathCheck.normalize().toAbsolutePath() + File.separator + "solrconfig.xml",+ "file:" + srcPathCheck.normalize().resolve("solrconfig.xml"),"zk:/powerup/"};@@ -298,7 +251,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {"cp","--zk-host",zkAddr,- "file:" + srcPathCheck.normalize().toAbsolutePath() + File.separator + "solrconfig.xml",+ "file:" + srcPathCheck.normalize().resolve("solrconfig.xml"),"zk:/copyUpFile.xml"};@@ -311,13 +264,12 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// copy individual file down// src and cp3 are valid- String localNamed =- tmp.normalize() + File.separator + "localnamed" + File.separator + "renamed.txt";+ String localNamed = tmp.normalize().resolve("localnamed").resolve("renamed.txt").toString();args = new String[] {"cp", "--zk-host", zkAddr, "zk:/cp4/solrconfig.xml", "file:" + localNamed};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy to local named file should have succeeded.", 0, res);- Path locPath = Paths.get(localNamed);+ Path locPath = Path.of(localNamed);assertTrue("Should have found file: " + localNamed, Files.exists(locPath));assertTrue("Should be an individual file", Files.isRegularFile(locPath));assertTrue("File should have some data", Files.size(locPath) > 100);@@ -341,14 +293,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Check that the form path/ works for copying files up. Should append the last bit of the// source path to the dstargs =- new String[] {- "cp",- "--recursive",- "--zk-host",- zkAddr,- "file:" + srcPathCheck.toAbsolutePath(),- "zk:/cp7/"- };+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, "file:" + srcPathCheck, "zk:/cp7/"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -356,15 +301,12 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Check for an intermediate ZNODE having content. You know cp7/stopwords is a parent node.tmp = createTempDir("dirdata");- Path file = Paths.get(tmp.toAbsolutePath().toString(), "zknode.data");+ Path file = tmp.resolve("zknode.data");List<String> lines = new ArrayList<>();lines.add("{Some Arbitrary Data}");Files.write(file, lines, StandardCharsets.UTF_8);// First, just copy the data up the cp7 since it's a directory.- args =- new String[] {- "cp", "--zk-host", zkAddr, "file:" + file.toAbsolutePath(), "zk:/cp7/conf/stopwords/"- };+ args = new String[] {"cp", "--zk-host", zkAddr, "file:" + file, "zk:/cp7/conf/stopwords/"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -378,22 +320,16 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {assertEquals("Copy should have succeeded.", 0, res);tmp = createTempDir("cp8");- args =- new String[] {- "cp", "--recursive", "--zk-host", zkAddr, "zk:/cp7", "file:" + tmp.toAbsolutePath()- };+ args = new String[] {"cp", "--recursive", "--zk-host", zkAddr, "zk:/cp7", "file:" + tmp};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);// Next, copy cp7 down and verify that zknode.data exists for cp7- Path zData = Paths.get(tmp.toAbsolutePath().toString(), "conf/stopwords/zknode.data");+ Path zData = tmp.resolve("conf/stopwords/zknode.data");assertTrue("znode.data should have been copied down", zData.toFile().exists());// Finally, copy up to cp8 and verify that the data is up there.- args =- new String[] {- "cp", "--recursive", "--zk-host", zkAddr, "file:" + tmp.toAbsolutePath(), "zk:/cp9"- };+ args = new String[] {"cp", "--recursive", "--zk-host", zkAddr, "file:" + tmp, "zk:/cp9"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);@@ -404,35 +340,28 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {assertTrue("There should be content in the node! ", content.contains("{Some Arbitrary Data}"));// Copy an individual empty file up and back down and insure it's still a file- Path emptyFile = Paths.get(tmp.toAbsolutePath().toString(), "conf", "stopwords", "emptyfile");+ Path emptyFile = tmp.resolve("conf/stopwords/emptyfile");Files.createFile(emptyFile);args =new String[] {- "cp",- "--zk-host",- zkAddr,- "file:" + emptyFile.toAbsolutePath(),- "zk:/cp7/conf/stopwords/emptyfile"+ "cp", "--zk-host", zkAddr, "file:" + emptyFile, "zk:/cp7/conf/stopwords/emptyfile"};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);Path tmp2 = createTempDir("cp9");- Path emptyDest = Paths.get(tmp2.toAbsolutePath().toString(), "emptyfile");+ Path emptyDest = tmp2.resolve("emptyfile");args =new String[] {- "cp",- "--zk-host",- zkAddr,- "zk:/cp7/conf/stopwords/emptyfile",- "file:" + emptyDest.toAbsolutePath()+ "cp", "--zk-host", zkAddr, "zk:/cp7/conf/stopwords/emptyfile", "file:" + emptyDest};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);- assertTrue("Empty files should NOT be copied down as directories", emptyDest.toFile().isFile());+ assertTrue(+ "Empty files should NOT be copied down as directories", Files.isRegularFile(emptyDest));// Now with recursive copy@@ -451,14 +380,11 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Now copy it all back and make sure empty file is still a file when recursively copying.tmp2 = createTempDir("cp10");- args =- new String[] {- "cp", "--recursive", "--zk-host", zkAddr, "zk:/cp10", "file:" + tmp2.toAbsolutePath()- };+ args = new String[] {"cp", "--recursive", "--zk-host", zkAddr, "zk:/cp10", "file:" + tmp2};res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);- Path locEmpty = Paths.get(tmp2.toAbsolutePath().toString(), "stopwords", "emptyfile");+ Path locEmpty = tmp2.resolve("stopwords/emptyfile");assertTrue("Empty files should NOT be copied down as directories", locEmpty.toFile().isFile());}@@ -485,7 +411,14 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Files are in mv2// Now fail if we specify "file:". Everything should still be in /mv2- args = new String[] {"mv", "--zk-host", zkAddr, "file:" + File.separator + "mv2", "/mv3"};+ args =+ new String[] {+ "mv",+ "--zk-host",+ zkAddr,+ "file:" + srcPathCheck.getFileSystem().getSeparator() + "mv2",+ "/mv3"+ };// Still in mv2res = CLITestHelper.runTool(args, ZkMvTool.class);@@ -672,9 +605,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {}if (isEphemeral(zkRoot + child)) continue;- Path thisPath = Paths.get(fileRoot.toAbsolutePath().toString(), child);+ Path thisPath = fileRoot.resolve(child);assertTrue(- "Znode " + child + " should have been found on disk at " + fileRoot.toAbsolutePath(),+ "Znode " + child + " should have been found on disk at " + fileRoot,Files.exists(thisPath));verifyAllZNodesAreFiles(thisPath, zkRoot + child);}diff --git a/solr/core/src/test/org/apache/solr/cli/SolrProcessManagerTest.java b/solr/core/src/test/org/apache/solr/cli/SolrProcessManagerTest.javaindex dca7e685a46..c715ad676d9 100644--- a/solr/core/src/test/org/apache/solr/cli/SolrProcessManagerTest.java+++ b/solr/core/src/test/org/apache/solr/cli/SolrProcessManagerTest.java@@ -17,7 +17,6 @@package org.apache.solr.cli;import java.io.BufferedReader;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@@ -84,9 +83,11 @@ public class SolrProcessManagerTest extends SolrTestCase {private static Pair<Integer, Process> createProcess(int port, boolean https) throws IOException {// Get the path to the java executable from the current JVMString classPath =- Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))+ Arrays.stream(+ System.getProperty("java.class.path").split(System.getProperty("path.separator"))).filter(p -> p.contains("solr") && p.contains("core") && p.contains("build"))- .collect(Collectors.joining(File.pathSeparator));+ .collect(Collectors.joining(System.getProperty("path.separator")));+ProcessBuilder processBuilder =new ProcessBuilder(System.getProperty("java.home") + "/bin/java",diff --git a/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java b/solr/core/src/test/org/apache/solr/cli/StreamToolTest.javaindex 5c37e521bbe..497b005ad71 100644--- a/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java@@ -19,8 +19,6 @@ package org.apache.solr.cli;import java.io.BufferedWriter;import java.io.ByteArrayInputStream;-import java.io.File;-import java.io.FileWriter;import java.io.LineNumberReader;import java.io.PrintWriter;import java.io.StringReader;@@ -183,11 +181,10 @@ public class StreamToolTest extends SolrCloudTestCase {@Test@SuppressWarnings({"unchecked", "rawtypes"})public void testLocalCatStream() throws Exception {- File localFile = File.createTempFile("topLevel1", ".txt");- populateFileWithData(localFile.toPath());+ Path localFile = Files.createTempFile("topLevel1", ".txt");+ populateFileWithData(localFile);- StreamTool.LocalCatStream catStream =- new StreamTool.LocalCatStream(localFile.getAbsolutePath(), -1);+ StreamTool.LocalCatStream catStream = new StreamTool.LocalCatStream(localFile.toString(), -1);List<Tuple> tuples = new ArrayList();try {catStream.open();@@ -208,8 +205,8 @@ public class StreamToolTest extends SolrCloudTestCase {for (int i = 0; i < 4; i++) {Tuple t = tuples.get(i);- assertEquals(localFile.getName() + " line " + (i + 1), t.get("line"));- assertEquals(localFile.getAbsolutePath(), t.get("file"));+ assertEquals(localFile.getFileName() + " line " + (i + 1), t.get("line"));+ assertEquals(localFile.toString(), t.get("file"));}}@@ -265,8 +262,8 @@ public class StreamToolTest extends SolrCloudTestCase {public void testRunEchoStreamLocally() throws Exception {String expression = "echo(Hello)";- File expressionFile = File.createTempFile("expression", ".EXPR");- FileWriter writer = new FileWriter(expressionFile, Charset.defaultCharset());+ Path expressionFile = Files.createTempFile("expression", ".EXPR");+ BufferedWriter writer = Files.newBufferedWriter(expressionFile, Charset.defaultCharset());writer.write(expression);writer.close();@@ -279,7 +276,7 @@ public class StreamToolTest extends SolrCloudTestCase {"--verbose","-zk-host",cluster.getZkClient().getZkServerAddress(),- expressionFile.getAbsolutePath()+ expressionFile.toString()};assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));@@ -310,8 +307,8 @@ public class StreamToolTest extends SolrCloudTestCase {clusterShape(1, 1));String expression = "echo(Hello)";- File expressionFile = File.createTempFile("expression", ".EXPR");- FileWriter writer = new FileWriter(expressionFile, Charset.defaultCharset());+ Path expressionFile = Files.createTempFile("expression", ".EXPR");+ BufferedWriter writer = Files.newBufferedWriter(expressionFile, Charset.defaultCharset());writer.write(expression);writer.close();@@ -327,7 +324,7 @@ public class StreamToolTest extends SolrCloudTestCase {cluster.getZkClient().getZkServerAddress(),"--credentials",SecurityJson.USER_PASS,- expressionFile.getAbsolutePath()+ expressionFile.toString()};assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));diff --git a/solr/core/src/test/org/apache/solr/cli/TestExportTool.java b/solr/core/src/test/org/apache/solr/cli/TestExportTool.javaindex 57db19f4e28..f74eedbb0d8 100644--- a/solr/core/src/test/org/apache/solr/cli/TestExportTool.java+++ b/solr/core/src/test/org/apache/solr/cli/TestExportTool.java@@ -17,12 +17,13 @@package org.apache.solr.cli;-import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.Reader;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -59,8 +60,7 @@ public class TestExportTool extends SolrCloudTestCase {.process(cluster.getSolrClient());cluster.waitForActiveCollection(COLLECTION_NAME, 2, 2);- String tmpFileLoc =- new File(cluster.getBaseDir().toFile().getAbsolutePath() + File.separator).getPath();+ Path baseDir = cluster.getBaseDir();UpdateRequest ur = new UpdateRequest();ur.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);@@ -85,7 +85,8 @@ public class TestExportTool extends SolrCloudTestCase {ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);ExportTool.Info info = new ExportTool.MultiThreadedRunner(runtime, url, null);- String absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";+ String absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".jsonl").toString();info.setOutFormat(absolutePath, "jsonl", false);info.setLimit("200");info.fields = "id,desc_s,a_dt";@@ -94,7 +95,8 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount(info, 200, record -> "2019-09-30T05:58:03Z".equals(record.get("a_dt")));info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".jsonl").toString();info.setOutFormat(absolutePath, "jsonl", false);info.setLimit("-1");info.fields = "id,desc_s";@@ -103,7 +105,8 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount(info, 1000, null);info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".javabin").toString();info.setOutFormat(absolutePath, "javabin", false);info.setLimit("200");info.fields = "id,desc_s";@@ -112,7 +115,8 @@ public class TestExportTool extends SolrCloudTestCase {assertJavabinDocsCount(info, 200);info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".javabin").toString();info.setOutFormat(absolutePath, "javabin", false);info.setLimit("-1");info.fields = "id,desc_s";@@ -120,7 +124,8 @@ public class TestExportTool extends SolrCloudTestCase {assertJavabinDocsCount(info, 1000);info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".json";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".json").toString();info.setOutFormat(absolutePath, "json", false);info.setLimit("200");info.fields = "id,desc_s";@@ -129,7 +134,8 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount2(info, 200);info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".json";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".json").toString();info.setOutFormat(absolutePath, "json", false);info.setLimit("-1");info.fields = "id,desc_s";@@ -152,8 +158,7 @@ public class TestExportTool extends SolrCloudTestCase {.process(cluster.getSolrClient());cluster.waitForActiveCollection(COLLECTION_NAME, 8, 8);- String tmpFileLoc =- new File(cluster.getBaseDir().toFile().getAbsolutePath() + File.separator).getPath();+ Path baseDir = cluster.getBaseDir();String url = cluster.getRandomJetty(random()).getBaseUrl() + "/" + COLLECTION_NAME;int docCount = 0;@@ -196,7 +201,8 @@ public class TestExportTool extends SolrCloudTestCase {String absolutePath;info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".javabin").toString();info.setOutFormat(absolutePath, "javabin", false);info.setLimit("-1");info.exportDocs();@@ -206,7 +212,8 @@ public class TestExportTool extends SolrCloudTestCase {e.getValue().longValue(), info.corehandlers.get(e.getKey()).receivedDocs.get());}info = new ExportTool.MultiThreadedRunner(runtime, url, null);- absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";+ absolutePath =+ baseDir.resolve(COLLECTION_NAME + random().nextInt(100000) + ".jsonl").toString();info.setOutFormat(absolutePath, "jsonl", false);info.fields = "id,desc_s";info.setLimit("-1");@@ -235,7 +242,7 @@ public class TestExportTool extends SolrCloudTestCase {.process(cluster.getSolrClient());cluster.waitForActiveCollection(COLLECTION_NAME, 2, 2);- File outFile = File.createTempFile("output", ".json");+ Path outFile = Files.createTempFile("output", ".json");String[] args = {"export",@@ -246,7 +253,7 @@ public class TestExportTool extends SolrCloudTestCase {"--credentials",SecurityJson.USER_PASS,"--output",- outFile.getAbsolutePath(),+ outFile.toString(),"--verbose"};diff --git a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.javaindex 558831242d3..a6b471df11d 100644--- a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java+++ b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java@@ -18,7 +18,6 @@ package org.apache.solr.cli;import java.io.ByteArrayInputStream;import java.io.Closeable;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.lang.invoke.MethodHandles;@@ -221,13 +220,13 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {int port = Integer.parseInt(getArg("-p", args));- File solrHomeDir = new File(getArg("--solr-home", args));+ Path solrHomeDir = Path.of(getArg("--solr-home", args));System.setProperty("host", "localhost");System.setProperty("jetty.port", String.valueOf(port));System.setProperty("solr.log.dir", createTempDir("solr_logs").toString());- standaloneSolr = new JettySolrRunner(solrHomeDir.getAbsolutePath(), port);+ standaloneSolr = new JettySolrRunner(solrHomeDir.toString(), port);Thread bg =new Thread() {@Override@@ -330,14 +329,13 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {protected void testExample(String exampleName) throws Exception {// Occasionally we want to test in User Managed mode, not the default SolrCloud mode.String testStandaloneMode = LuceneTestCase.rarely() ? "--user-managed" : "";- File defaultSolrHomeDir = new File(ExternalPaths.SERVER_HOME);- if (!defaultSolrHomeDir.isDirectory()) {- fail(defaultSolrHomeDir.getAbsolutePath() + " not found and is required to run this test!");+ Path defaultSolrHomeDir = ExternalPaths.SERVER_HOME;+ if (!Files.isDirectory(defaultSolrHomeDir)) {+ fail(defaultSolrHomeDir + " not found and is required to run this test!");}- Path tmpDir = createTempDir();- File testSolrHomeDir = tmpDir.toFile();- File solrServerDir = defaultSolrHomeDir.getParentFile();+ Path testSolrHomeDir = createTempDir();+ Path solrServerDir = defaultSolrHomeDir.getParent();for (int pass = 0; pass < 2; pass++) {// need a port to start the example server on@@ -353,9 +351,9 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {"-e",exampleName,"--server-dir",- solrServerDir.getAbsolutePath(),+ solrServerDir.toString(),"--solr-home",- testSolrHomeDir.getAbsolutePath(),+ testSolrHomeDir.toString(),"-p",String.valueOf(bindPort),testStandaloneMode@@ -435,20 +433,19 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {*/@Testpublic void testInteractiveSolrCloudExample() throws Exception {- File solrHomeDir = new File(ExternalPaths.SERVER_HOME);- if (!solrHomeDir.isDirectory())- fail(solrHomeDir.getAbsolutePath() + " not found and is required to run this test!");+ Path solrHomeDir = ExternalPaths.SERVER_HOME;+ if (!Files.isDirectory(solrHomeDir))+ fail(solrHomeDir + " not found and is required to run this test!");- Path tmpDir = createTempDir();- File solrExampleDir = tmpDir.toFile();+ Path solrExampleDir = createTempDir();- File solrServerDir = solrHomeDir.getParentFile();+ Path solrServerDir = solrHomeDir.getParent();String[] toolArgs =new String[] {"--example", "cloud",- "--server-dir", solrServerDir.getAbsolutePath(),- "--example-dir", solrExampleDir.getAbsolutePath()+ "--server-dir", solrServerDir.toString(),+ "--example-dir", solrExampleDir.toString()};int bindPort = -1;@@ -526,12 +523,9 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {}}- File node1SolrHome = new File(solrExampleDir, "cloud/node1/solr");- if (!node1SolrHome.isDirectory()) {- fail(- node1SolrHome.getAbsolutePath()- + " not found! run cloud example failed; tool output: "- + toolOutput);+ Path node1SolrHome = solrExampleDir.resolve("cloud/node1/solr");+ if (!Files.isDirectory(node1SolrHome)) {+ fail(node1SolrHome + " not found! run cloud example failed; tool output: " + toolOutput);}// delete the collection@@ -548,13 +542,12 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {@Testpublic void testFailExecuteScript() throws Exception {- File solrHomeDir = new File(ExternalPaths.SERVER_HOME);- if (!solrHomeDir.isDirectory())- fail(solrHomeDir.getAbsolutePath() + " not found and is required to run this test!");+ Path solrHomeDir = ExternalPaths.SERVER_HOME;+ if (!Files.isDirectory(solrHomeDir))+ fail(solrHomeDir + " not found and is required to run this test!");- Path tmpDir = createTempDir();- File solrExampleDir = tmpDir.toFile();- File solrServerDir = solrHomeDir.getParentFile();+ Path solrExampleDir = createTempDir();+ Path solrServerDir = solrHomeDir.getParent();// need a port to start the example server onint bindPort = -1;@@ -562,18 +555,20 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {bindPort = socket.getLocalPort();}- File toExecute = new File(tmpDir.toString(), "failExecuteScript");- assertTrue(- "Should have been able to create file '" + toExecute.getAbsolutePath() + "' ",- toExecute.createNewFile());+ Path toExecute = Path.of(solrExampleDir.toString(), "failExecuteScript");+ try {+ Files.createFile(toExecute);+ } catch (IOException e) {+ throw new IOException("Should have been able to create file '" + toExecute + "' ");+ }String[] toolArgs =new String[] {"-e", "techproducts",- "--server-dir", solrServerDir.getAbsolutePath(),- "--example-dir", solrExampleDir.getAbsolutePath(),+ "--server-dir", solrServerDir.toString(),+ "--example-dir", solrExampleDir.toString(),"-p", String.valueOf(bindPort),- "--script", toExecute.getAbsolutePath()+ "--script", toExecute.toString(),};DefaultExecutor executor = DefaultExecutor.builder().get();diff --git a/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.javaindex 78904038f86..4dc8a159b7a 100644--- a/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java+++ b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java@@ -16,20 +16,16 @@*/package org.apache.solr.cli;-import java.io.File;-import java.io.FileWriter;+import java.io.BufferedWriter;+import java.io.IOException;import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;-import java.util.Collection;import java.util.List;import java.util.concurrent.TimeUnit;-import org.apache.commons.io.FileUtils;-import org.apache.commons.io.filefilter.RegexFileFilter;-import org.apache.commons.io.filefilter.TrueFileFilter;+import java.util.stream.Stream;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.cloud.AbstractDistribZkTestBase;import org.apache.solr.cloud.AbstractZkTestCase;@@ -68,7 +64,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {private PrintStream originalSystemOut;- protected static final String SOLR_HOME = SolrTestCaseJ4.TEST_HOME();+ protected static final Path SOLR_HOME = SolrTestCaseJ4.TEST_HOME();@BeforeClasspublic static void beforeClass() {@@ -87,10 +83,10 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {log.info("####SETUP_START {}", getTestName());}- String exampleHome = legacyExampleCollection1SolrHome();+ Path exampleHome = legacyExampleCollection1SolrHome();Path tmpDir = createTempDir();- solrHome = exampleHome;+ solrHome = exampleHome.toString();originalSystemOut = System.out;@@ -117,15 +113,13 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {public void testPut() throws Exception {// test putString data = "my data";- File localFile = File.createTempFile("temp", ".data");- FileWriter writer = new FileWriter(localFile, StandardCharsets.UTF_8);+ Path localFile = Files.createTempFile("temp", ".data");+ BufferedWriter writer = Files.newBufferedWriter(localFile, StandardCharsets.UTF_8);writer.write(data);writer.close();String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/data.txt"- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), localFile.toString(), "zk:/data.txt"};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));@@ -136,7 +130,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {data = "my data deux";// Write text to the temporary file- writer = new FileWriter(localFile, StandardCharsets.UTF_8);+ writer = Files.newBufferedWriter(localFile, StandardCharsets.UTF_8);writer.write(data);writer.close();@@ -154,8 +148,8 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {String data = "my data";- File localFile = File.createTempFile("state", ".json");- FileWriter writer = new FileWriter(localFile, StandardCharsets.UTF_8);+ Path localFile = Files.createTempFile("state", ".json");+ BufferedWriter writer = Files.newBufferedWriter(localFile, StandardCharsets.UTF_8);writer.write(data);writer.close();@@ -164,9 +158,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {byte[] expected = zLibCompressor.compressBytes(dataBytes);String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/state.json"- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), localFile.toString(), "zk:/state.json"};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));@@ -176,29 +168,25 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {// test re-put to existingdata = "my data deux";- localFile = File.createTempFile("state", ".json");- writer = new FileWriter(localFile, StandardCharsets.UTF_8);+ localFile = Files.createTempFile("state", ".json");+ writer = Files.newBufferedWriter(localFile, StandardCharsets.UTF_8);writer.write(data);writer.close();dataBytes = data.getBytes(StandardCharsets.UTF_8);expected = zLibCompressor.compressBytes(dataBytes);- byte[] fromLoca =- new ZLibCompressor()- .compressBytes(Files.readAllBytes(Path.of(localFile.getAbsolutePath())));+ byte[] fromLoca = new ZLibCompressor().compressBytes(Files.readAllBytes(localFile));assertArrayEquals("Should get back what we put in ZK", fromLoca, expected);args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/state.json"- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), localFile.toString(), "zk:/state.json"};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));byte[] fromZkRaw =zkClient.getCuratorFramework().getData().undecompressed().forPath("/state.json");byte[] fromZk = zkClient.getCuratorFramework().getData().forPath("/state.json");- byte[] fromLocRaw = Files.readAllBytes(Path.of(localFile.getAbsolutePath()));+ byte[] fromLocRaw = Files.readAllBytes(localFile);byte[] fromLoc = new ZLibCompressor().compressBytes(fromLocRaw);assertArrayEquals("When asking to not decompress, we should get back the compressed data that what we put in ZK",@@ -222,7 +210,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp","-z",zkServer.getZkAddress(),- SOLR_HOME + File.separator + "solr-stress-new.xml",+ SOLR_HOME.resolve("solr-stress-new.xml").toString(),"zk:/foo.xml"};@@ -230,7 +218,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {String fromZk =new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);- Path localFile = Path.of(SOLR_HOME, "solr-stress-new.xml");+ Path localFile = SOLR_HOME.resolve("solr-stress-new.xml");String fromLocalFile = Files.readString(localFile);assertEquals("Should get back what we put in ZK", fromZk, fromLocalFile);}@@ -243,7 +231,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp","-z",zkServer.getZkAddress(),- SOLR_HOME + File.separator + "solr-stress-new.xml",+ SOLR_HOME.resolve("solr-stress-new.xml").toString(),"zk:foo.xml"};@@ -251,7 +239,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {String fromZk =new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);- Path localFile = Path.of(SOLR_HOME, "solr-stress-new.xml");+ Path localFile = SOLR_HOME.resolve("solr-stress-new.xml");String fromLocalFile = Files.readString(localFile);assertEquals("Should get back what we put in ZK", fromZk, fromLocalFile);}@@ -267,13 +255,13 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp","-z",zkServer.getZkAddress(),- SOLR_HOME + File.separator + "solr-stress-new.xml",+ SOLR_HOME.resolve("solr-stress-new.xml").toString(),"zk:/state.json"};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));- Path locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");+ Path locFile = SOLR_HOME.resolve("solr-stress-new.xml");byte[] fileBytes = Files.readAllBytes(locFile);// Check raw ZK data@@ -290,7 +278,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {// Lets do it againassertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));- locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");+ locFile = SOLR_HOME.resolve("solr-stress-new.xml");fileBytes = Files.readAllBytes(locFile);fromZk = zkClient.getCuratorFramework().getData().undecompressed().forPath("/state.json");@@ -311,7 +299,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp","-z",zkServer.getZkAddress(),- SOLR_HOME + File.separator + "not-there.xml",+ SOLR_HOME.resolve("not-there.xml").toString(),"zk:/foo.xml"};@@ -338,7 +326,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {@Testpublic void testUpConfigLinkConfigClearZk() throws Exception {- File tmpDir = createTempDir().toFile();+ Path tmpDir = createTempDir();// test upconfigString confsetname = "confsetone";@@ -349,7 +337,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"--conf-name",confsetname,"--conf-dir",- ExternalPaths.TECHPRODUCTS_CONFIGSET,+ ExternalPaths.TECHPRODUCTS_CONFIGSET.toString(),"-z",zkServer.getZkAddress()};@@ -357,11 +345,15 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {assertEquals(0, CLITestHelper.runTool(args, ConfigSetUploadTool.class));assertTrue(zkClient.exists(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, true));- File confDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);- File[] files = confDir.listFiles();+ final Path confDir = ExternalPaths.TECHPRODUCTS_CONFIGSET;+List<String> zkFiles =zkClient.getChildren(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, null, true);- assertEquals("Verify that all local files are uploaded to ZK", files.length, zkFiles.size());++ try (Stream<Path> filesStream = Files.list(confDir)) {+ assertEquals(+ "Verify that all local files are uploaded to ZK", filesStream.count(), zkFiles.size());+ }// test linkconfigargs =@@ -384,10 +376,10 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {assertEquals(confsetname, collectionProps.getStr("configName"));// test down config- File configSetDir =- new File(- tmpDir, "solrtest-confdropspot-" + this.getClass().getName() + "-" + System.nanoTime());- assertFalse(configSetDir.exists());+ Path configSetDir =+ tmpDir.resolve(+ "solrtest-confdropspot-" + this.getClass().getName() + "-" + System.nanoTime());+ assertFalse(Files.exists(configSetDir));args =new String[] {@@ -395,54 +387,64 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"--conf-name",confsetname,"--conf-dir",- configSetDir.getAbsolutePath(),+ configSetDir.toString(),"-z",zkServer.getZkAddress()};assertEquals(0, CLITestHelper.runTool(args, ConfigSetDownloadTool.class));- confDir = new File(configSetDir, "conf");- files = confDir.listFiles();- zkFiles =- zkClient.getChildren(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, null, true);- assertEquals(- "Comparing original conf files that were to be uploadedto what is in ZK",- files.length,- zkFiles.size());- assertEquals("Comparing downloaded files to what is in ZK", files.length, zkFiles.size());+ Path confSetDir = configSetDir.resolve("conf");+ try (Stream<Path> filesStream = Files.list(confSetDir)) {+ List<Path> files = filesStream.toList();+ zkFiles =+ zkClient.getChildren(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, null, true);+ assertEquals(+ "Comparing original conf files that were to be uploaded to what is in ZK",+ files.size(),+ zkFiles.size());+ assertEquals("Comparing downloaded files to what is in ZK", files.size(), zkFiles.size());+ }- File sourceConfDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);+ Path sourceConfDir = ExternalPaths.TECHPRODUCTS_CONFIGSET;// filter out all directories starting with . (e.g. .svn)- Collection<File> sourceFiles =- FileUtils.listFiles(- sourceConfDir, TrueFileFilter.INSTANCE, new RegexFileFilter("[^\\.].*"));- for (File sourceFile : sourceFiles) {- int indexOfRelativePath =- sourceFile- .getAbsolutePath()- .lastIndexOf("sample_techproducts_configs" + File.separator + "conf");- String relativePathofFile =- sourceFile- .getAbsolutePath()- .substring(indexOfRelativePath + 33, sourceFile.getAbsolutePath().length());- File downloadedFile = new File(confDir, relativePathofFile);- if (ConfigSetService.UPLOAD_FILENAME_EXCLUDE_PATTERN.matcher(relativePathofFile).matches()) {- assertFalse(- sourceFile.getAbsolutePath()- + " exists in ZK, downloaded:"- + downloadedFile.getAbsolutePath(),- downloadedFile.exists());- } else {- assertTrue(- downloadedFile.getAbsolutePath()- + " does not exist source:"- + sourceFile.getAbsolutePath(),- downloadedFile.exists());- assertTrue(- relativePathofFile + " content changed",- FileUtils.contentEquals(sourceFile, downloadedFile));- }+ try (Stream<Path> stream = Files.walk(sourceConfDir)) {+ List<Path> files =+ stream+ .filter(Files::isRegularFile)+ .filter(path -> path.getFileName().startsWith("."))+ .toList();+ files.forEach(+ (sourceFile) -> {+ int indexOfRelativePath =+ sourceFile+ .toString()+ .lastIndexOf(+ "sample_techproducts_configs"+ + sourceFile.getFileSystem().getSeparator()+ + "conf");+ String relativePathofFile = sourceFile.toString().substring(indexOfRelativePath + 33);+ Path downloadedFile = confDir.resolve(relativePathofFile);+ if (ConfigSetService.UPLOAD_FILENAME_EXCLUDE_PATTERN+ .matcher(relativePathofFile)+ .matches()) {+ assertFalse(+ sourceFile + " exists in ZK, downloaded:" + downloadedFile,+ Files.exists(downloadedFile));+ } else {+ assertTrue(+ downloadedFile + " does not exist source:" + sourceFile,+ Files.exists(downloadedFile));+ try {+ assertEquals(+ relativePathofFile + " content changed",+ -1,+ Files.mismatch(sourceFile, downloadedFile));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ });}// test reset zk@@ -459,19 +461,17 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {byte[] data = "getNode-data".getBytes(StandardCharsets.UTF_8);zkClient.create(getNode, data, CreateMode.PERSISTENT, true);- File localFile = File.createTempFile("temp", ".data");+ Path localFile = Files.createTempFile("temp", ".data");String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.getAbsolutePath()- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.toString()};CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);assertEquals(0, CLITestHelper.runTool(args, runtime, ZkCpTool.class));final String standardOutput2 = runtime.getOutput();assertTrue(standardOutput2.startsWith("Copying from 'zk:/getNode'"));- byte[] fileBytes = Files.readAllBytes(Paths.get(localFile.getAbsolutePath()));+ byte[] fileBytes = Files.readAllBytes(localFile);assertArrayEquals(data, fileBytes);}@@ -489,16 +489,14 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {: zLibCompressor.compressBytes(data, data.length / 10);zkClient.create(getNode, compressedData, CreateMode.PERSISTENT, true);- File localFile = File.createTempFile("temp", ".data");+ Path localFile = Files.createTempFile("temp", ".data");String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.getAbsolutePath()- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.toString()};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));- assertArrayEquals(data, Files.readAllBytes(Path.of(localFile.getAbsolutePath())));+ assertArrayEquals(data, Files.readAllBytes(localFile));}@Test@@ -513,9 +511,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {tmpDir.resolve("solrtest-getfile-" + this.getClass().getName() + "-" + System.nanoTime());String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toAbsolutePath().toString()- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toString()};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(data, Files.readAllBytes(file));@@ -538,9 +534,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {tmpDir.resolve("solrtest-getfile-" + this.getClass().getName() + "-" + System.nanoTime());String[] args =- new String[] {- "cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toAbsolutePath().toString()- };+ new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toString()};assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));@@ -551,10 +545,10 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {public void testGetFileNotExists() throws Exception {String getNode = "/getFileNotExistsNode";- File file = createTempFile("newfile", null).toFile();+ Path file = createTempFile("newfile", null);String[] args =- new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.getAbsolutePath()};+ new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toString()};assertEquals(1, CLITestHelper.runTool(args, ZkCpTool.class));}diff --git a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerSchemaAPI.java b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerSchemaAPI.javaindex c07d5f58602..e7e22a065a4 100644--- a/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerSchemaAPI.java+++ b/solr/core/src/test/org/apache/solr/client/solrj/embedded/TestEmbeddedSolrServerSchemaAPI.java@@ -53,9 +53,8 @@ public class TestEmbeddedSolrServerSchemaAPI extends SolrTestCaseJ4 {System.setProperty("managed.schema.mutable", "" + random().nextBoolean());Path tmpHome = createTempDir("tmp-home");Path coreDir = tmpHome.resolve(DEFAULT_TEST_CORENAME);- copyMinConf(coreDir.toFile(), null, "solrconfig-managed-schema.xml");- initCore(- "solrconfig.xml" /*it's renamed to*/, "schema.xml", tmpHome.toAbsolutePath().toString());+ copyMinConf(coreDir, null, "solrconfig-managed-schema.xml");+ initCore("solrconfig.xml" /*it's renamed to*/, "schema.xml", tmpHome.toAbsolutePath());server = new EmbeddedSolrServer(h.getCoreContainer(), DEFAULT_TEST_CORENAME);}diff --git a/solr/core/src/test/org/apache/solr/cloud/CleanupOldIndexTest.java b/solr/core/src/test/org/apache/solr/cloud/CleanupOldIndexTest.javaindex deb828c8aa4..0a4e0d3c1c9 100644--- a/solr/core/src/test/org/apache/solr/cloud/CleanupOldIndexTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/CleanupOldIndexTest.java@@ -16,12 +16,12 @@*/package org.apache.solr.cloud;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;import java.util.concurrent.TimeUnit;-import org.apache.commons.io.FileUtils;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.common.cloud.DocCollection;import org.apache.solr.core.CoreContainer;@@ -74,26 +74,26 @@ public class CleanupOldIndexTest extends SolrCloudTestCase {// create some "old" index directoriesJettySolrRunner jetty = cluster.getRandomJetty(random());CoreContainer coreContainer = jetty.getCoreContainer();- File dataDir = null;+ Path dataDir = null;try (SolrCore solrCore =coreContainer.getCore(coreContainer.getCoreDescriptors().get(0).getName())) {- dataDir = new File(solrCore.getDataDir());+ dataDir = Path.of(solrCore.getDataDir());}- assertTrue(dataDir.isDirectory());+ assertTrue(Files.isDirectory(dataDir));long msInDay = 60 * 60 * 24L;String timestamp1 =new SimpleDateFormat(SnapShooter.DATE_FMT, Locale.ROOT).format(new Date(1 * msInDay));String timestamp2 =new SimpleDateFormat(SnapShooter.DATE_FMT, Locale.ROOT).format(new Date(2 * msInDay));- File oldIndexDir1 = new File(dataDir, "index." + timestamp1);- FileUtils.forceMkdir(oldIndexDir1);- File oldIndexDir2 = new File(dataDir, "index." + timestamp2);- FileUtils.forceMkdir(oldIndexDir2);+ Path oldIndexDir1 = dataDir.resolve("index." + timestamp1);+ Files.createDirectories(oldIndexDir1);+ Path oldIndexDir2 = dataDir.resolve("index." + timestamp2);+ Files.createDirectories(oldIndexDir2);// verify the "old" index directories exist- assertTrue(oldIndexDir1.isDirectory());- assertTrue(oldIndexDir2.isDirectory());+ assertTrue(Files.isDirectory(oldIndexDir1));+ assertTrue(Files.isDirectory(oldIndexDir2));// bring shard replica downjetty.stop();@@ -119,7 +119,7 @@ public class CleanupOldIndexTest extends SolrCloudTestCase {TimeUnit.SECONDS,(n, c) -> DocCollection.isFullyActive(n, c, 1, 2));- assertFalse(oldIndexDir1.isDirectory());- assertFalse(oldIndexDir2.isDirectory());+ assertFalse(Files.isDirectory(oldIndexDir1));+ assertFalse(Files.isDirectory(oldIndexDir2));}}diff --git a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.javaindex 45f22ac3bd2..16859664139 100644--- a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionOnCommitTest.java@@ -16,8 +16,8 @@*/package org.apache.solr.cloud;-import java.io.File;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.List;import org.apache.http.NoHttpResponseException;import org.apache.solr.client.solrj.SolrClient;@@ -175,7 +175,7 @@ public class HttpPartitionOnCommitTest extends BasicDistributedZkTest {/** Overrides the parent implementation to install a SocketProxy in-front of the Jetty server. */@Overridepublic JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,diff --git a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.javaindex 0d4f1c2b722..d274539a2b3 100644--- a/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/HttpPartitionTest.java@@ -19,9 +19,9 @@ package org.apache.solr.cloud;import static org.apache.solr.common.cloud.Replica.State.DOWN;import static org.apache.solr.common.cloud.Replica.State.RECOVERING;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;@@ -95,7 +95,7 @@ public class HttpPartitionTest extends AbstractFullDistribZkTestBase {/** Overrides the parent implementation to install a SocketProxy in-front of the Jetty server. */@Overridepublic JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,diff --git a/solr/core/src/test/org/apache/solr/cloud/MissingSegmentRecoveryTest.java b/solr/core/src/test/org/apache/solr/cloud/MissingSegmentRecoveryTest.javaindex 22c2fb13288..084bf5a254e 100644--- a/solr/core/src/test/org/apache/solr/cloud/MissingSegmentRecoveryTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/MissingSegmentRecoveryTest.java@@ -16,12 +16,13 @@*/package org.apache.solr.cloud;-import java.io.File;import java.io.IOException;import java.nio.file.Files;+import java.nio.file.Path;import java.nio.file.StandardOpenOption;import java.util.ArrayList;import java.util.List;+import java.util.stream.Stream;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServerException;import org.apache.solr.client.solrj.request.CollectionAdminRequest;@@ -92,7 +93,7 @@ public class MissingSegmentRecoveryTest extends SolrCloudTestCase {System.setProperty("CoreInitFailedAction", "fromleader");// Simulate failure by truncating the segment_* files- for (File segment : getSegmentFiles(replica)) {+ for (Path segment : getSegmentFiles(replica)) {truncate(segment);}@@ -108,18 +109,17 @@ public class MissingSegmentRecoveryTest extends SolrCloudTestCase {assertEquals(10, resp.getResults().getNumFound());}- private File[] getSegmentFiles(Replica replica) {+ private List<Path> getSegmentFiles(Replica replica) throws IOException {try (SolrCore core =cluster.getReplicaJetty(replica).getCoreContainer().getCore(replica.getCoreName())) {- File indexDir = new File(core.getDataDir(), "index");- return indexDir.listFiles(- (File dir, String name) -> {- return name.startsWith("segments_");- });+ Path indexDir = Path.of(core.getDataDir(), "index");+ try (Stream<Path> files = Files.list(indexDir)) {+ return files.filter((file) -> file.getFileName().startsWith("segments_")).toList();+ }}}- private void truncate(File file) throws IOException {- Files.write(file.toPath(), new byte[0], StandardOpenOption.TRUNCATE_EXISTING);+ private void truncate(Path file) throws IOException {+ Files.write(file, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);}}diff --git a/solr/core/src/test/org/apache/solr/cloud/ParallelCommitExecutionTest.java b/solr/core/src/test/org/apache/solr/cloud/ParallelCommitExecutionTest.javaindex cf927a77516..1f07d6fcf45 100644--- a/solr/core/src/test/org/apache/solr/cloud/ParallelCommitExecutionTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ParallelCommitExecutionTest.java@@ -19,7 +19,6 @@ package org.apache.solr.cloud;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.LinkedHashMap;import java.util.Map;import java.util.concurrent.CountDownLatch;@@ -61,7 +60,7 @@ public class ParallelCommitExecutionTest extends SolrCloudTestCase {expectCount = numNodes;final String configName = DEBUG_LABEL + "_config-set";- final Path configDir = Paths.get(TEST_HOME(), "collection1", "conf");+ final Path configDir = TEST_HOME().resolve("collection1").resolve("conf");configureCluster(numNodes).addConfig(configName, configDir).configure();diff --git a/solr/core/src/test/org/apache/solr/cloud/RecoveryAfterSoftCommitTest.java b/solr/core/src/test/org/apache/solr/cloud/RecoveryAfterSoftCommitTest.javaindex 6cee0ed226e..ea013dfed46 100644--- a/solr/core/src/test/org/apache/solr/cloud/RecoveryAfterSoftCommitTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/RecoveryAfterSoftCommitTest.java@@ -16,7 +16,7 @@*/package org.apache.solr.cloud;-import java.io.File;+import java.nio.file.Path;import java.util.List;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.cloud.SocketProxy;@@ -66,7 +66,7 @@ public class RecoveryAfterSoftCommitTest extends AbstractFullDistribZkTestBase {/** Overrides the parent implementation to install a SocketProxy in-front of the Jetty server. */@Overridepublic JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,diff --git a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.javaindex e62b3005c8b..f375bfc229c 100644--- a/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ReplicationFactorTest.java@@ -16,9 +16,9 @@*/package org.apache.solr.cloud;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.ArrayList;import java.util.HashSet;import java.util.List;@@ -67,7 +67,7 @@ public class ReplicationFactorTest extends AbstractFullDistribZkTestBase {*/@Overridepublic JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,diff --git a/solr/core/src/test/org/apache/solr/cloud/ShardRoutingCustomTest.java b/solr/core/src/test/org/apache/solr/cloud/ShardRoutingCustomTest.javaindex a1985ea9483..53fe7a7b07a 100644--- a/solr/core/src/test/org/apache/solr/cloud/ShardRoutingCustomTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ShardRoutingCustomTest.java@@ -16,7 +16,8 @@*/package org.apache.solr.cloud;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.common.cloud.Replica;@@ -56,8 +57,8 @@ public class ShardRoutingCustomTest extends AbstractFullDistribZkTestBase {private void doCustomSharding() throws Exception {printLayout();- File jettyDir = createTempDir("jetty").toFile();- jettyDir.mkdirs();+ Path jettyDir = createTempDir("jetty");+ Files.createDirectories(jettyDir);setupJettySolrHome(jettyDir);JettySolrRunner j =createJetty(diff --git a/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java b/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.javaindex b186da20296..e55a4bb9807 100644--- a/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.cloud;-import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.file.Files;import java.nio.file.Path;@@ -63,8 +62,8 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {log.info("testLoadDocsIntoGettingStartedCollection initialized OK ... running test logic");String testCollectionName = "gettingstarted";- File defaultConfigs = new File(ExternalPaths.DEFAULT_CONFIGSET);- assertTrue(defaultConfigs.getAbsolutePath() + " not found!", defaultConfigs.isDirectory());+ Path defaultConfigs = ExternalPaths.DEFAULT_CONFIGSET;+ assertTrue(defaultConfigs + " not found!", Files.isDirectory(defaultConfigs));Set<String> liveNodes = cloudClient.getClusterState().getLiveNodes();if (liveNodes.isEmpty())@@ -114,8 +113,8 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {// now index docs ...log.info("Created collection, now posting example docs!");- Path exampleDocsDir = Path.of(ExternalPaths.SOURCE_HOME, "example", "exampledocs");- assertTrue(exampleDocsDir.toAbsolutePath() + " not found!", Files.isDirectory(exampleDocsDir));+ Path exampleDocsDir = ExternalPaths.SOURCE_HOME.resolve("example").resolve("exampledocs");+ assertTrue(exampleDocsDir + " not found!", Files.isDirectory(exampleDocsDir));String[] argsForPost =new String[] {@@ -125,7 +124,7 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {testCollectionName,"--filetypes","xml",- exampleDocsDir.toAbsolutePath().toString()+ exampleDocsDir.toString()};PostTool postTool = new PostTool(runtime);diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.javaindex 150ab7b5d27..d64c62b5ab5 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudRecovery.java@@ -20,16 +20,15 @@ package org.apache.solr.cloud;import com.codahale.metrics.Counter;import com.codahale.metrics.Metric;import com.codahale.metrics.Timer;-import java.io.File;import java.io.FileOutputStream;import java.nio.file.Files;import java.nio.file.Path;-import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.atomic.AtomicInteger;import java.util.stream.Collectors;+import java.util.stream.Stream;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.client.solrj.response.QueryResponse;@@ -188,13 +187,14 @@ public class TestCloudRecovery extends SolrCloudTestCase {Map<String, byte[]> contentFiles = new HashMap<>();for (JettySolrRunner solrRunner : cluster.getJettySolrRunners()) {for (SolrCore solrCore : solrRunner.getCoreContainer().getCores()) {- File tlogFolder = new File(solrCore.getUpdateHandler().getUpdateLog().getTlogDir());- String[] tLogFiles = tlogFolder.list();- Arrays.sort(tLogFiles);- String lastTLogFile = tlogFolder.getAbsolutePath() + "/" + tLogFiles[tLogFiles.length - 1];- byte[] tlogBytes = Files.readAllBytes(Path.of(lastTLogFile));- contentFiles.put(lastTLogFile, tlogBytes);- logHeaderSize = Math.min(tlogBytes.length, logHeaderSize);+ Path tlogFolder = Path.of(solrCore.getUpdateHandler().getUpdateLog().getTlogDir());+ try (Stream<Path> tLogFiles = Files.list(tlogFolder)) {+ Path lastTLogFile =+ tlogFolder.resolve(tLogFiles.sorted().toList().getLast().getFileName());+ byte[] tlogBytes = Files.readAllBytes(lastTLogFile);+ contentFiles.put(lastTLogFile.toString(), tlogBytes);+ logHeaderSize = Math.min(tlogBytes.length, logHeaderSize);+ }}}diff --git a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.javaindex ebc331c99d0..64c858ac4ea 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestConfigSetsAPI.java@@ -22,9 +22,7 @@ import static org.apache.solr.core.ConfigSetProperties.DEFAULT_FILENAME;import static org.hamcrest.CoreMatchers.containsString;import java.io.ByteArrayInputStream;-import java.io.File;import java.io.FileInputStream;-import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@@ -49,6 +47,7 @@ import java.util.Objects;import java.util.Properties;import java.util.Set;import java.util.concurrent.TimeUnit;+import java.util.stream.Stream;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;import javax.script.ScriptEngineManager;@@ -1179,7 +1178,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {boolean forbiddenContent)throws IOException {- File zipFile;+ Path zipFile;if (forbiddenTypes) {log.info("Uploading configset with forbidden file endings");zipFile =@@ -1201,7 +1200,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {// Read single file from sample configs. This should fail the unzippingreturn uploadGivenConfigSet(- SolrTestCaseJ4.getFile("solr/configsets/upload/regular/solrconfig.xml").toFile(),+ SolrTestCaseJ4.getFile("solr/configsets/upload/regular/solrconfig.xml"),configSetName,suffix,username,@@ -1211,7 +1210,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {}private long uploadGivenConfigSet(- File file,+ Path file,String configSetName,String suffix,String username,@@ -1223,8 +1222,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {if (v2) {// TODO: switch to using V2Request- final ByteBuffer fileBytes =- TestSolrConfigHandler.getFileContent(file.getAbsolutePath(), false);+ final ByteBuffer fileBytes = TestSolrConfigHandler.getFileContent(file.toString(), false);final String uriEnding ="/configsets/"+ configSetName@@ -1246,7 +1244,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {try {return (new Upload()).setConfigSetName(configSetName + suffix)- .setUploadFile(file.toPath(), "application/zip")+ .setUploadFile(file, "application/zip").setOverwrite(overwrite ? true : null) // expect server default to be 'false'.setCleanup(cleanup ? true : null) // expect server default to be 'false'.setBasicAuthCredentials(username, username) // for our MockAuthenticationPlugin@@ -1270,13 +1268,13 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {boolean v2)throws IOException {// Read single file from sample configs- final File file = SolrTestCaseJ4.getFile(localFilePath).toFile();+ final Path file = SolrTestCaseJ4.getFile(localFilePath);if (v2) {// TODO: switch to use V2Requestfinal ByteBuffer sampleConfigFile =- TestSolrConfigHandler.getFileContent(file.getAbsolutePath(), false);+ TestSolrConfigHandler.getFileContent(file.toString(), false);if (uploadPath != null && !uploadPath.startsWith("/")) {uploadPath = "/" + uploadPath;}@@ -1305,7 +1303,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {.setConfigSetName(configSetName + suffix).setFilePath(uploadPath)// NOTE: server doesn't actually care, and test plumbing doesn't tell us- .setUploadFile(file.toPath(), "application/octet-stream")+ .setUploadFile(file, "application/octet-stream").setOverwrite(overwrite ? true : null) // expect server default to be 'false'.setCleanup(cleanup ? true : null) // expect server default to be 'false'.setBasicAuthCredentials(username, username) // for our MockAuthenticationPlugin@@ -1322,16 +1320,16 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {* Create a zip file (in the temp directory) containing all the files within the specified* directory and return the zip file.*/- private File createTempZipFile(String directoryPath) {+ private Path createTempZipFile(String directoryPath) {try {- final File zipFile = createTempFile("configset", "zip").toFile();- final File directory = SolrTestCaseJ4.getFile(directoryPath).toFile();+ final Path zipFile = createTempFile("configset", "zip");+ final Path directory = SolrTestCaseJ4.getFile(directoryPath);if (log.isInfoEnabled()) {- log.info("Directory: {}", directory.getAbsolutePath());+ log.info("Directory: {}", directory);}zip(directory, zipFile);if (log.isInfoEnabled()) {- log.info("Zipfile: {}", zipFile.getAbsolutePath());+ log.info("Zipfile: {}", zipFile);}return zipFile;} catch (IOException e) {@@ -1343,16 +1341,16 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {* Create a zip file (in the temp directory) containing a file with all forbidden types (named* "test.fileType")*/- private File createTempZipFileWithForbiddenTypes(String file) {+ private Path createTempZipFileWithForbiddenTypes(String file) {try {- final File zipFile = createTempFile("configset", "zip").toFile();- final File directory = SolrTestCaseJ4.getFile(file).toFile();+ final Path zipFile = createTempFile("configset", "zip");+ final Path directory = SolrTestCaseJ4.getFile(file);if (log.isInfoEnabled()) {- log.info("Directory: {}", directory.getAbsolutePath());+ log.info("Directory: {}", directory);}zipWithForbiddenEndings(directory, zipFile);if (log.isInfoEnabled()) {- log.info("Zipfile: {}", zipFile.getAbsolutePath());+ log.info("Zipfile: {}", zipFile);}return zipFile;} catch (IOException e) {@@ -1361,16 +1359,16 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {}/** Create a zip file (in the temp directory) containing files with forbidden content */- private File createTempZipFileWithForbiddenContent(String resourcePath) {+ private Path createTempZipFileWithForbiddenContent(String resourcePath) {try {- final File zipFile = createTempFile("configset", "zip").toFile();- final File directory = SolrTestCaseJ4.getFile(resourcePath).toFile();+ final Path zipFile = createTempFile("configset", "zip");+ final Path directory = SolrTestCaseJ4.getFile(resourcePath);if (log.isInfoEnabled()) {- log.info("Directory: {}", directory.getAbsolutePath());+ log.info("Directory: {}", directory);}zipWithForbiddenContent(directory, zipFile);if (log.isInfoEnabled()) {- log.info("Zipfile: {}", zipFile.getAbsolutePath());+ log.info("Zipfile: {}", zipFile);}return zipFile;} catch (IOException e) {@@ -1378,69 +1376,88 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {}}- private static void zipWithForbiddenContent(File directory, File zipfile) throws IOException {- OutputStream out = Files.newOutputStream(zipfile.toPath());- assertTrue(directory.isDirectory());+ private static void zipWithForbiddenContent(Path directory, Path zipfile) throws IOException {+ OutputStream out = Files.newOutputStream(zipfile);+ assertTrue(Files.isDirectory(directory));try (ZipOutputStream zout = new ZipOutputStream(out)) {// Copy in all files from the directory- for (File file : Objects.requireNonNull(directory.listFiles())) {- zout.putNextEntry(new ZipEntry(file.getName()));- zout.write(Files.readAllBytes(file.toPath()));- zout.closeEntry();+ try (Stream<Path> files = Objects.requireNonNull(Files.list(directory))) {+ files.forEach(+ (file) -> {+ try {+ zout.putNextEntry(new ZipEntry(file.getFileName().toString()));+ zout.write(Files.readAllBytes(file));+ zout.closeEntry();+ } catch (IOException e) {+ throw new RuntimeException("Failed to write zip file", e);+ }+ });}}}- private static void zipWithForbiddenEndings(File fileOrDirectory, File zipfile)+ private static void zipWithForbiddenEndings(Path fileOrDirectory, Path zipfile)throws IOException {- OutputStream out = new FileOutputStream(zipfile);+ OutputStream out = Files.newOutputStream(zipfile);try (ZipOutputStream zout = new ZipOutputStream(out)) {- if (fileOrDirectory.isFile()) {+ if (Files.isRegularFile(fileOrDirectory)) {// Create entries with given file, one for each forbidden enddingfor (String fileType : ZkMaintenanceUtils.DEFAULT_FORBIDDEN_FILE_TYPES) {zout.putNextEntry(new ZipEntry("test." + fileType));- try (InputStream in = new FileInputStream(fileOrDirectory)) {+ try (InputStream in = Files.newInputStream(fileOrDirectory)) {in.transferTo(zout);}zout.closeEntry();}}- if (fileOrDirectory.isDirectory()) {+ if (Files.isDirectory(fileOrDirectory)) {// Copy in all files from the directory- for (File file : Objects.requireNonNull(fileOrDirectory.listFiles())) {- zout.putNextEntry(new ZipEntry(file.getName()));- zout.write(Files.readAllBytes(file.toPath()));- zout.closeEntry();+ try (Stream<Path> files = Objects.requireNonNull(Files.list(fileOrDirectory))) {+ files.forEach(+ (file) -> {+ try {+ zout.putNextEntry(new ZipEntry(file.getFileName().toString()));+ zout.write(Files.readAllBytes(file));+ zout.closeEntry();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}}}}- private static void zip(File directory, File zipfile) throws IOException {- URI base = directory.toURI();- Deque<File> queue = new ArrayDeque<>();+ private static void zip(Path directory, Path zipfile) throws IOException {+ URI base = directory.toUri();+ Deque<Path> queue = new ArrayDeque<>();queue.push(directory);- OutputStream out = new FileOutputStream(zipfile);+ OutputStream out = Files.newOutputStream(zipfile);try (ZipOutputStream zout = new ZipOutputStream(out)) {while (!queue.isEmpty()) {directory = queue.pop();- for (File kid : directory.listFiles()) {- String name = base.relativize(kid.toURI()).getPath();- if (kid.isDirectory()) {- queue.push(kid);- name = name.endsWith("/") ? name : name + "/";- zout.putNextEntry(new ZipEntry(name));- } else {- zout.putNextEntry(new ZipEntry(name));-- try (InputStream in = new FileInputStream(kid)) {- in.transferTo(zout);- }-- zout.closeEntry();- }+ try (Stream<Path> files = Files.list(directory)) {+ files.forEach(+ (kid) -> {+ try {+ String name = base.relativize(kid.toUri()).getPath();+ if (Files.isDirectory(kid)) {+ queue.push(kid);+ name = name.endsWith("/") ? name : name + "/";+ zout.putNextEntry(new ZipEntry(name));+ } else {+ zout.putNextEntry(new ZipEntry(name));+ try (InputStream in = Files.newInputStream(kid)) {+ in.transferTo(zout);+ }+ zout.closeEntry();+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });}}}@@ -1663,7 +1680,7 @@ public class TestConfigSetsAPI extends SolrCloudTestCase {*/@Testpublic void testUserAndTestDefaultConfigsetsAreSame() {- final Path extPath = Path.of(ExternalPaths.DEFAULT_CONFIGSET);+ final Path extPath = ExternalPaths.DEFAULT_CONFIGSET;assertTrue("_default dir doesn't exist: " + ExternalPaths.DEFAULT_CONFIGSET, Files.exists(extPath));assertTrue(diff --git a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.javaindex 32807418908..2e1f6dd7912 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestPullReplica.java@@ -17,9 +17,10 @@package org.apache.solr.cloud;import com.carrotsearch.randomizedtesting.annotations.Repeat;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;@@ -233,15 +234,15 @@ public class TestPullReplica extends SolrCloudTestCase {* otherwise returns the <code>tlog</code> subdirectory within {@link SolrCore#getDataDir()}.* (NOTE: the last of these is by far the most common default location of the tlog directory).*/- static File getHypotheticalTlogDir(SolrCore core) {+ static Path getHypotheticalTlogDir(SolrCore core) {String ulogDir;UpdateLog ulog = core.getUpdateHandler().getUpdateLog();if (ulog != null) {- return new File(ulog.getTlogDir());+ return Path.of(ulog.getTlogDir());} else if ((ulogDir = core.getCoreDescriptor().getUlogDir()) != null) {- return new File(ulogDir, UpdateLog.TLOG_NAME);+ return Path.of(ulogDir, UpdateLog.TLOG_NAME);} else {- return new File(core.getDataDir(), UpdateLog.TLOG_NAME);+ return Path.of(core.getDataDir(), UpdateLog.TLOG_NAME);}}@@ -258,11 +259,11 @@ public class TestPullReplica extends SolrCloudTestCase {try (SolrCore core =cluster.getReplicaJetty(r).getCoreContainer().getCore(r.getCoreName())) {assertNotNull(core);- File tlogDir = getHypotheticalTlogDir(core);+ Path tlogDir = getHypotheticalTlogDir(core);assertFalse("Update log should not exist for replicas of type Passive but file is present: "+ tlogDir,- tlogDir.exists());+ Files.exists(tlogDir));}}}diff --git a/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java b/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.javaindex 5a4b24c897a..ee4bab45620 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestSegmentSorting.java@@ -17,7 +17,6 @@package org.apache.solr.cloud;import java.lang.invoke.MethodHandles;-import java.nio.file.Paths;import java.util.HashMap;import java.util.Map;import org.apache.lucene.tests.util.TestUtil;@@ -52,7 +51,7 @@ public class TestSegmentSorting extends SolrCloudTestCase {System.setProperty("solr.tests.id.docValues", "true");}configureCluster(NUM_SERVERS)- .addConfig(configName, Paths.get(TEST_HOME(), "collection1", "conf"))+ .addConfig(configName, TEST_HOME().resolve("collection1").resolve("conf")).configure();}diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.javaindex 3d33f6da412..0c7b5a912bd 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestTlogReplica.java@@ -20,9 +20,10 @@ import static org.apache.solr.cloud.TestPullReplica.getHypotheticalTlogDir;import com.carrotsearch.randomizedtesting.annotations.Repeat;import com.codahale.metrics.Meter;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;@@ -145,8 +146,8 @@ public class TestTlogReplica extends SolrCloudTestCase {try {core = cluster.getReplicaJetty(r).getCoreContainer().getCore(r.getCoreName());assertNotNull(core);- File tlogDir = getHypotheticalTlogDir(core);- assertTrue("Update log should exist for replicas of type Append", tlogDir.exists());+ Path tlogDir = getHypotheticalTlogDir(core);+ assertTrue("Update log should exist for replicas of type Append", Files.exists(tlogDir));} finally {core.close();}diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.javaindex a7d59979928..f045d7d4522 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorCloud.java@@ -16,9 +16,9 @@*/package org.apache.solr.cloud;-import java.io.File;import java.io.IOException;import java.net.URL;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;@@ -95,10 +95,9 @@ public class TestTolerantUpdateProcessorCloud extends SolrCloudTestCase {public static void createMiniSolrCloudCluster() throws Exception {final String configName = "solrCloudCollectionConfig";- final File configDir =- new File(TEST_HOME() + File.separator + "collection1" + File.separator + "conf");+ final Path configDir = TEST_HOME().resolve("collection1").resolve("conf");- configureCluster(NUM_SERVERS).addConfig(configName, configDir.toPath()).configure();+ configureCluster(NUM_SERVERS).addConfig(configName, configDir).configure();COLLECTION_CLIENT = cluster.getSolrClient(COLLECTION_NAME);diff --git a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.javaindex 8b72b7fda35..a39197320cf 100644--- a/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java+++ b/solr/core/src/test/org/apache/solr/cloud/TestTolerantUpdateProcessorRandomCloud.java@@ -25,10 +25,10 @@ import static org.apache.solr.cloud.TestTolerantUpdateProcessorCloud.update;import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_PARAM;import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_START;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.net.URL;+import java.nio.file.Path;import java.util.ArrayList;import java.util.BitSet;import java.util.HashMap;@@ -80,8 +80,7 @@ public class TestTolerantUpdateProcessorRandomCloud extends SolrCloudTestCase {public static void createMiniSolrCloudCluster() throws Exception {final String configName = "solrCloudCollectionConfig";- final File configDir =- new File(TEST_HOME() + File.separator + "collection1" + File.separator + "conf");+ final Path configDir = TEST_HOME().resolve("collection1").resolve("conf");final int numShards = TestUtil.nextInt(random(), 2, TEST_NIGHTLY ? 5 : 3);final int repFactor = TestUtil.nextInt(random(), 2, TEST_NIGHTLY ? 5 : 3);@@ -93,7 +92,7 @@ public class TestTolerantUpdateProcessorRandomCloud extends SolrCloudTestCase {numServers,numShards,repFactor);- configureCluster(numServers).addConfig(configName, configDir.toPath()).configure();+ configureCluster(numServers).addConfig(configName, configDir).configure();Map<String, String> collectionProperties = new HashMap<>();collectionProperties.put("config", "solrconfig-distrib-update-processor-chains.xml");diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/BackupRestoreApiErrorConditionsTest.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/BackupRestoreApiErrorConditionsTest.javaindex 31e1eb5ee52..1e8d8658970 100644--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/BackupRestoreApiErrorConditionsTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/BackupRestoreApiErrorConditionsTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.cloud.api.collections;-import java.io.File;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.client.solrj.response.RequestStatusState;import org.apache.solr.cloud.MiniSolrCloudCluster;@@ -150,7 +149,10 @@ public class BackupRestoreApiErrorConditionsTest extends SolrCloudTestCase {() -> {CollectionAdminRequest.backupCollection(COLLECTION_NAME, BACKUP_NAME).setRepositoryName(VALID_REPOSITORY_NAME)- .setLocation(validBackupLocation + File.pathSeparator + "someNonexistentLocation")+ .setLocation(+ validBackupLocation+ + System.getProperty("path.separator")+ + "someNonexistentLocation").process(cluster.getSolrClient());});assertTrue(e.getMessage().contains("specified location"));@@ -163,7 +165,9 @@ public class BackupRestoreApiErrorConditionsTest extends SolrCloudTestCase {() -> {CollectionAdminRequest.listBackup(BACKUP_NAME).setBackupLocation(- validBackupLocation + File.pathSeparator + "someNonexistentLocation")+ validBackupLocation+ + System.getProperty("path.separator")+ + "someNonexistentLocation").setBackupRepository(VALID_REPOSITORY_NAME).process(cluster.getSolrClient());});@@ -176,7 +180,10 @@ public class BackupRestoreApiErrorConditionsTest extends SolrCloudTestCase {Exception.class,() -> {CollectionAdminRequest.deleteBackupById(BACKUP_NAME, 1)- .setLocation(validBackupLocation + File.pathSeparator + "someNonexistentLocation")+ .setLocation(+ validBackupLocation+ + System.getProperty("path.separator")+ + "someNonexistentLocation").setRepositoryName(VALID_REPOSITORY_NAME).process(cluster.getSolrClient());});@@ -189,7 +196,10 @@ public class BackupRestoreApiErrorConditionsTest extends SolrCloudTestCase {Exception.class,() -> {CollectionAdminRequest.restoreCollection(COLLECTION_NAME + "_restored", BACKUP_NAME)- .setLocation(validBackupLocation + File.pathSeparator + "someNonexistentLocation")+ .setLocation(+ validBackupLocation+ + System.getProperty("path.separator")+ + "someNonexistentLocation").setRepositoryName(VALID_REPOSITORY_NAME).process(cluster.getSolrClient());});diff --git a/solr/core/src/test/org/apache/solr/core/CachingDirectoryFactoryTest.java b/solr/core/src/test/org/apache/solr/core/CachingDirectoryFactoryTest.javaindex 3dd193703cf..e6dd56470be 100644--- a/solr/core/src/test/org/apache/solr/core/CachingDirectoryFactoryTest.java+++ b/solr/core/src/test/org/apache/solr/core/CachingDirectoryFactoryTest.java@@ -16,9 +16,9 @@*/package org.apache.solr.core;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;import java.nio.file.Path;import java.util.AbstractMap;import java.util.ArrayList;@@ -128,9 +128,9 @@ public class CachingDirectoryFactoryTest extends SolrTestCaseJ4 {"There are subdirs to wait on, so the parent directory should still exist",pathA.toFile().exists()); // parent must still be presentfor (Map.Entry<String, Directory> e : subdirs) {- String pathString = e.getKey();- boolean exists = new File(pathString).exists();- if (deleteAfter.contains(pathString)) {+ Path path = Path.of(e.getKey());+ boolean exists = Files.exists(path);+ if (deleteAfter.contains(path.toString())) {assertTrue(exists);} else {assertFalse(exists);diff --git a/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java b/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.javaindex b682236f0df..716bbac8f0c 100644--- a/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java+++ b/solr/core/src/test/org/apache/solr/core/SolrCoreCheckLockOnStartupTest.java@@ -16,9 +16,9 @@*/package org.apache.solr.core;-import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.file.Files;+import java.nio.file.Path;import java.util.Map;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;@@ -46,16 +46,14 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {// the file will remain after the native test (it cannot safely be deleted without the risk of// deleting another guys lock) it's ok, these aren't "compatible" anyway: really this test// should not re-use the same directory at all.- Files.deleteIfExists(- new File(new File(initAndGetDataDir(), "index"), IndexWriter.WRITE_LOCK_NAME).toPath());+ Files.deleteIfExists(initAndGetDataDir().resolve("index").resolve(IndexWriter.WRITE_LOCK_NAME));}@Testpublic void testSimpleLockErrorOnStartup() throws Exception {Directory directory =- newFSDirectory(- new File(initAndGetDataDir(), "index").toPath(), SimpleFSLockFactory.INSTANCE);+ newFSDirectory(initAndGetDataDir().resolve("index"), SimpleFSLockFactory.INSTANCE);// creates a new IndexWriter without releasing the lock yetIndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(null));@@ -78,11 +76,11 @@ public class SolrCoreCheckLockOnStartupTest extends SolrTestCaseJ4 {@Testpublic void testNativeLockErrorOnStartup() throws Exception {- File indexDir = new File(initAndGetDataDir(), "index");+ Path indexDir = initAndGetDataDir().resolve("index");if (log.isInfoEnabled()) {- log.info("Acquiring lock on {}", indexDir.getAbsolutePath());+ log.info("Acquiring lock on {}", indexDir);}- Directory directory = newFSDirectory(indexDir.toPath(), NativeFSLockFactory.INSTANCE);+ Directory directory = newFSDirectory(indexDir, NativeFSLockFactory.INSTANCE);// creates a new IndexWriter without releasing the lock yetIndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(null));diff --git a/solr/core/src/test/org/apache/solr/core/TestBackupRepositoryFactory.java b/solr/core/src/test/org/apache/solr/core/TestBackupRepositoryFactory.javaindex 34551c9b342..45c6cfc2e28 100644--- a/solr/core/src/test/org/apache/solr/core/TestBackupRepositoryFactory.java+++ b/solr/core/src/test/org/apache/solr/core/TestBackupRepositoryFactory.java@@ -16,7 +16,7 @@*/package org.apache.solr.core;-import java.io.File;+import java.nio.file.Path;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;@@ -34,13 +34,13 @@ import org.junit.Test;public class TestBackupRepositoryFactory extends SolrTestCaseJ4 {// tmp dir, cleaned up automatically.- private static File solrHome = null;+ private static Path solrHome = null;private static SolrResourceLoader loader = null;@BeforeClasspublic static void setupLoader() {- solrHome = createTempDir().toFile();- loader = new SolrResourceLoader(solrHome.toPath());+ solrHome = createTempDir();+ loader = new SolrResourceLoader(solrHome);}@AfterClassdiff --git a/solr/core/src/test/org/apache/solr/core/TestConfLoadPerf.java b/solr/core/src/test/org/apache/solr/core/TestConfLoadPerf.javaindex 4c348104b35..c3f51417465 100644--- a/solr/core/src/test/org/apache/solr/core/TestConfLoadPerf.java+++ b/solr/core/src/test/org/apache/solr/core/TestConfLoadPerf.java@@ -19,7 +19,6 @@ package org.apache.solr.core;import static org.apache.solr.core.TestConfigSets.solrxml;-import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;@@ -40,12 +39,12 @@ public class TestConfLoadPerf extends SolrTestCaseJ4 {@Ignore@SuppressForbidden(reason = "Needed to provide time for tests.")public void testPerf() throws Exception {- String sourceHome = ExternalPaths.SOURCE_HOME;- File configSetDir =- new File(sourceHome, "server/solr/configsets/sample_techproducts_configs/conf");+ Path sourceHome = ExternalPaths.SOURCE_HOME;+ Path configSetDir =+ sourceHome.resolve("server/solr/configsets/sample_techproducts_configs/conf");String configSetsBaseDir = TEST_PATH().resolve("configsets").toString();- byte[] b = Files.readAllBytes(new File(configSetDir, "solrconfig.xml").toPath());+ byte[] b = Files.readAllBytes(configSetDir.resolve("solrconfig.xml"));Path testDirectory = createTempDir();System.setProperty("configsets", configSetsBaseDir);@@ -72,13 +71,14 @@ public class TestConfLoadPerf extends SolrTestCaseJ4 {Stat stat = new Stat();stat.setVersion(1);return new ZkSolrResourceLoader.ZkByteArrayInputStream(- b, new File(configSetDir, "solrconfig.xml").getAbsolutePath(), stat);+ b, configSetDir.resolve("solrconfig.xml").toString(), stat);} else {throw new FileNotFoundException(resource);}}};System.gc();+long heapSize = Runtime.getRuntime().totalMemory();List<SolrConfig> allConfigs = new ArrayList<>();long startTime = System.currentTimeMillis();diff --git a/solr/core/src/test/org/apache/solr/core/TestConfigSetImmutable.java b/solr/core/src/test/org/apache/solr/core/TestConfigSetImmutable.javaindex 1ede297abdc..dc45e63380c 100644--- a/solr/core/src/test/org/apache/solr/core/TestConfigSetImmutable.java+++ b/solr/core/src/test/org/apache/solr/core/TestConfigSetImmutable.java@@ -46,7 +46,7 @@ public class TestConfigSetImmutable extends RestTestBase {public void before() throws Exception {Path tmpSolrHome = createTempDir();Path tmpConfDir = tmpSolrHome.resolve(confDir);- PathUtils.copyDirectory(Path.of(TEST_HOME()), tmpSolrHome);+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);// make the ConfigSet immutableFiles.writeString(tmpConfDir.resolve("configsetprops.json"),@@ -56,12 +56,7 @@ public class TestConfigSetImmutable extends RestTestBase {System.setProperty("managed.schema.mutable", "true");createJettyAndHarness(- tmpSolrHome.toAbsolutePath().toString(),- "solrconfig-schemaless.xml",- "schema-rest.xml",- "/solr",- true,- null);+ tmpSolrHome, "solrconfig-schemaless.xml", "schema-rest.xml", "/solr", true, null);}@Afterdiff --git a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.javaindex 2ef1cfc0188..d4fa3e6baab 100644--- a/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java+++ b/solr/core/src/test/org/apache/solr/core/TestCoreContainer.java@@ -23,7 +23,6 @@ import static org.hamcrest.CoreMatchers.nullValue;import static org.hamcrest.core.Is.is;import static org.hamcrest.core.IsInstanceOf.instanceOf;-import java.io.File;import java.io.FileOutputStream;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -369,29 +368,29 @@ public class TestCoreContainer extends SolrTestCaseJ4 {public void testSharedLib() throws Exception {Path tmpRoot = createTempDir("testSharedLib");- File lib = new File(tmpRoot.toFile(), "lib");- lib.mkdirs();+ Path lib = tmpRoot.resolve("lib");+ Files.createDirectories(lib);try (JarOutputStream jar1 =- new JarOutputStream(new FileOutputStream(new File(lib, "jar1.jar")))) {+ new JarOutputStream(Files.newOutputStream(lib.resolve("jar1.jar")))) {jar1.putNextEntry(new JarEntry("defaultSharedLibFile"));jar1.closeEntry();}- File customLib = new File(tmpRoot.toFile(), "customLib");- customLib.mkdirs();+ Path customLib = tmpRoot.resolve("customLib");+ Files.createDirectories(customLib);try (JarOutputStream jar2 =- new JarOutputStream(new FileOutputStream(new File(customLib, "jar2.jar")))) {+ new JarOutputStream(Files.newOutputStream(customLib.resolve("jar2.jar")))) {jar2.putNextEntry(new JarEntry("customSharedLibFile"));jar2.closeEntry();}- File customLib2 = new File(tmpRoot.toFile(), "customLib2");- customLib2.mkdirs();+ Path customLib2 = tmpRoot.resolve("customLib2");+ Files.createDirectories(customLib2);try (JarOutputStream jar3 =- new JarOutputStream(new FileOutputStream(new File(customLib2, "jar3.jar")))) {+ new JarOutputStream(Files.newOutputStream(customLib2.resolve("jar3.jar")))) {jar3.putNextEntry(new JarEntry("jar3File"));jar3.closeEntry();}@@ -436,11 +435,10 @@ public class TestCoreContainer extends SolrTestCaseJ4 {public void testModuleLibs() throws Exception {Path tmpRoot = createTempDir("testModLib");- File lib = Files.createDirectories(ModuleUtils.getModuleLibPath(tmpRoot, "mod1")).toFile();- ;+ Path lib = Files.createDirectories(ModuleUtils.getModuleLibPath(tmpRoot, "mod1"));try (JarOutputStream jar1 =- new JarOutputStream(new FileOutputStream(new File(lib, "jar1.jar")))) {+ new JarOutputStream(Files.newOutputStream(lib.resolve("jar1.jar")))) {jar1.putNextEntry(new JarEntry("moduleLibFile"));jar1.closeEntry();}diff --git a/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java b/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.javaindex 6f763537b72..600c4fd7e9a 100644--- a/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java+++ b/solr/core/src/test/org/apache/solr/core/TestCoreDiscovery.java@@ -22,24 +22,27 @@ import static org.apache.solr.core.CoreContainer.LOAD_COMPLETE;import static org.hamcrest.CoreMatchers.not;import static org.hamcrest.core.StringContains.containsString;-import java.io.File;-import java.io.FileInputStream;+import java.io.IOException;import java.io.InputStreamReader;import java.io.Writer;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;+import java.nio.file.attribute.PosixFilePermission;import java.util.List;import java.util.Map;import java.util.Properties;+import java.util.Set;import java.util.concurrent.TimeUnit;import org.apache.lucene.util.IOUtils;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrException;import org.apache.solr.common.util.RetryUtil;import org.junit.After;+import org.junit.AssumptionViolatedException;import org.junit.BeforeClass;import org.junit.Test;import org.slf4j.Logger;@@ -88,23 +91,25 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {return props;}- private void addCoreWithProps(Properties stockProps, File propFile) throws Exception {- if (!propFile.getParentFile().exists()) {- propFile.getParentFile().mkdirs();+ private void addCoreWithProps(Properties stockProps, Path propFile) throws Exception {+ if (!Files.exists(propFile.getParent())) {+ Files.createDirectories(propFile.getParent());}- try (Writer out = Files.newBufferedWriter(propFile.toPath(), StandardCharsets.UTF_8)) {+ try (Writer out = Files.newBufferedWriter(propFile, StandardCharsets.UTF_8)) {stockProps.store(out, null);}- addConfFiles(propFile.toPath().getParent().resolve("conf"));+ addConfFiles(propFile.getParent().resolve("conf"));}private void addCoreWithProps(String name, Properties stockProps) throws Exception {-- File propFile =- new File(- new File(solrHomeDirectory.toFile(), name), CorePropertiesLocator.PROPERTIES_FILENAME);- File parent = propFile.getParentFile();- assertTrue("Failed to mkdirs for " + parent.getAbsolutePath(), parent.mkdirs());+ Path propFile =+ solrHomeDirectory.resolve(name).resolve(CorePropertiesLocator.PROPERTIES_FILENAME);+ Path parent = propFile.getParent();+ try {+ Files.createDirectories(parent);+ } catch (Exception e) {+ throw new IOException("Failed to mkdirs for " + parent.toAbsolutePath());+ }addCoreWithProps(stockProps, propFile);}@@ -189,13 +194,11 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {Properties persistable = cd1.getPersistableUserProperties();persistable.setProperty("bogusprop", "bogusval");cc.getCoresLocator().persist(cc, cd1);- File propFile =- new File(- new File(solrHomeDirectory.toFile(), "core1"),- CorePropertiesLocator.PROPERTIES_FILENAME);+ Path propFile =+ solrHomeDirectory.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME);Properties newProps = new Properties();try (InputStreamReader is =- new InputStreamReader(new FileInputStream(propFile), StandardCharsets.UTF_8)) {+ new InputStreamReader(Files.newInputStream(propFile), StandardCharsets.UTF_8)) {newProps.load(is);}// is it there?@@ -394,25 +397,29 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {"Wrong exception thrown on duplicate core names",message.contains("Found multiple cores with the name [core1]"));assertTrue(- File.separator + "core1 should have been mentioned in the message: " + message,- message.contains(File.separator + "core1"));+ FileSystems.getDefault().getSeparator()+ + "core1 should have been mentioned in the message: "+ + message,+ message.contains(FileSystems.getDefault().getSeparator() + "core1"));assertTrue(- File.separator + "core2 should have been mentioned in the message:" + message,- message.contains(File.separator + "core2"));+ FileSystems.getDefault().getSeparator()+ + "core2 should have been mentioned in the message:"+ + message,+ message.contains(FileSystems.getDefault().getSeparator() + "core2"));}@Testpublic void testAlternateCoreDir() throws Exception {- File alt = createTempDir().toFile();+ Path alt = createTempDir();- setMeUp(alt.getAbsolutePath());+ setMeUp(alt.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true, "dataDir=core1"),- new File(alt, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ alt.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));addCoreWithProps(makeCoreProperties("core2", false, false, "dataDir=core2"),- new File(alt, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ alt.resolve("core2").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1");SolrCore core2 = cc.getCore("core2")) {@@ -435,22 +442,17 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {solrHomeDirectory.resolve(relative).resolve("core1")- .resolve(CorePropertiesLocator.PROPERTIES_FILENAME)- .toFile());+ .resolve(CorePropertiesLocator.PROPERTIES_FILENAME));addCoreWithProps(makeCoreProperties("core2", false, false, "dataDir=core2"),solrHomeDirectory.resolve(relative).resolve("core2")- .resolve(CorePropertiesLocator.PROPERTIES_FILENAME)- .toFile());+ .resolve(CorePropertiesLocator.PROPERTIES_FILENAME));// one core *not* under the relative directoryaddCoreWithProps(makeCoreProperties("core0", false, true, "datadir=core0"),- solrHomeDirectory- .resolve("core0")- .resolve(CorePropertiesLocator.PROPERTIES_FILENAME)- .toFile());+ solrHomeDirectory.resolve("core0").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1");@@ -470,14 +472,14 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {@Testpublic void testNoCoreDir() throws Exception {- File noCoreDir = createTempDir().toFile();- setMeUp(noCoreDir.getAbsolutePath());+ Path noCoreDir = createTempDir();+ setMeUp(noCoreDir.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true),- new File(noCoreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ noCoreDir.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));addCoreWithProps(makeCoreProperties("core2", false, false),- new File(noCoreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ noCoreDir.resolve("core2").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1");SolrCore core2 = cc.getCore("core2")) {@@ -490,21 +492,29 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {@Testpublic void testCoreDirCantRead() throws Exception {- File coreDir = solrHomeDirectory.toFile();- setMeUp(coreDir.getAbsolutePath());+ Path coreDir = solrHomeDirectory;+ setMeUp(coreDir.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true),- new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ coreDir.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));// Ensure that another core is opened successfullyaddCoreWithProps(makeCoreProperties("core2", false, false, "dataDir=core2"),- new File(coreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ coreDir.resolve("core2").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));- File toSet = new File(coreDir, "core1");- assumeTrue(- "Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));- assumeFalse("Appears we are a super user, skip test", toSet.canRead());+ Path toSet = coreDir.resolve("core1");+ try {+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.remove(PosixFilePermission.OWNER_READ);+ perms.remove(PosixFilePermission.GROUP_READ);+ perms.remove(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);+ } catch (UnsupportedOperationException e) {+ throw new AssumptionViolatedException(+ "Cannot make " + toSet + " non-readable. Test aborted.", e);+ }+ assumeFalse("Appears we are a super user, skip test", Files.isReadable(toSet));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1");SolrCore core2 = cc.getCore("core2")) {@@ -514,28 +524,43 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {cc.shutdown();}// So things can be cleaned up by the framework!- toSet.setReadable(true, false);+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.add(PosixFilePermission.OWNER_READ);+ perms.add(PosixFilePermission.GROUP_READ);+ perms.add(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);}@Testpublic void testNonCoreDirCantRead() throws Exception {- File coreDir = solrHomeDirectory.toFile();- setMeUp(coreDir.getAbsolutePath());+ Path coreDir = solrHomeDirectory;+ setMeUp(coreDir.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true),- new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ coreDir.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));addCoreWithProps(makeCoreProperties("core2", false, false, "dataDir=core2"),- new File(coreDir, "core2" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ coreDir.resolve("core2").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));- File toSet = new File(solrHomeDirectory.toFile(), "cantReadDir");- assertTrue(- "Should have been able to make directory '" + toSet.getAbsolutePath() + "' ",- toSet.mkdirs());- assumeTrue(- "Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));- assumeFalse("Appears we are a super user, skip test", toSet.canRead());+ Path toSet = solrHomeDirectory.resolve("cantReadDir");+ try {+ Files.createDirectories(toSet);+ } catch (IOException e) {+ throw new RuntimeException(+ "Should have been able to make directory '" + toSet.toAbsolutePath() + "' ", e);+ }+ try {+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.remove(PosixFilePermission.OWNER_READ);+ perms.remove(PosixFilePermission.GROUP_READ);+ perms.remove(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);+ } catch (UnsupportedOperationException e) {+ throw new AssumptionViolatedException(+ "Cannot make " + toSet + " non-readable. Test aborted.", e);+ }+ assumeFalse("Appears we are a super user, skip test", Files.isReadable(toSet));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1");SolrCore core2 = cc.getCore("core2")) {@@ -546,23 +571,41 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {cc.shutdown();}// So things can be cleaned up by the framework!- toSet.setReadable(true, false);+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.add(PosixFilePermission.OWNER_READ);+ perms.add(PosixFilePermission.GROUP_READ);+ perms.add(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);}@Testpublic void testFileCantRead() throws Exception {- File coreDir = solrHomeDirectory.toFile();- setMeUp(coreDir.getAbsolutePath());+ Path coreDir = solrHomeDirectory;+ setMeUp(coreDir.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true),- new File(coreDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ coreDir.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));++ Path toSet = solrHomeDirectory.resolve("cantReadFile");++ try {+ Files.createFile(toSet);+ } catch (IOException e) {+ throw new RuntimeException(+ "Should have been able to make file '" + toSet.toAbsolutePath() + "' ", e);+ }++ try {+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.remove(PosixFilePermission.OWNER_READ);+ perms.remove(PosixFilePermission.GROUP_READ);+ perms.remove(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);+ } catch (UnsupportedOperationException e) {+ throw new AssumptionViolatedException(+ "Cannot make " + toSet + " non-readable. Test aborted.", e);+ }- File toSet = new File(solrHomeDirectory.toFile(), "cantReadFile");- assertTrue(- "Should have been able to make file '" + toSet.getAbsolutePath() + "' ",- toSet.createNewFile());- assumeTrue(- "Cannot make " + toSet + " non-readable. Test aborted.", toSet.setReadable(false, false));CoreContainer cc = init();try (SolrCore core1 = cc.getCore("core1")) {assertNotNull(core1); // Should still be able to create core despite r/o file.@@ -570,13 +613,17 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {cc.shutdown();}// So things can be cleaned up by the framework!- toSet.setReadable(true, false);+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(toSet);+ perms.add(PosixFilePermission.OWNER_READ);+ perms.add(PosixFilePermission.GROUP_READ);+ perms.add(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(toSet, "posix:permissions", perms);}@Testpublic void testSolrHomeDoesntExist() throws Exception {- File homeDir = solrHomeDirectory.toFile();- IOUtils.rm(homeDir.toPath());+ Path homeDir = solrHomeDirectory;+ IOUtils.rm(homeDir);CoreContainer cc = null;try {cc = init();@@ -593,16 +640,24 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {@Testpublic void testSolrHomeNotReadable() throws Exception {- File homeDir = solrHomeDirectory.toFile();- setMeUp(homeDir.getAbsolutePath());+ Path homeDir = solrHomeDirectory;+ setMeUp(homeDir.toAbsolutePath().toString());addCoreWithProps(makeCoreProperties("core1", false, true),- new File(homeDir, "core1" + File.separator + CorePropertiesLocator.PROPERTIES_FILENAME));+ homeDir.resolve("core1").resolve(CorePropertiesLocator.PROPERTIES_FILENAME));++ try {+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(homeDir);+ perms.remove(PosixFilePermission.OWNER_READ);+ perms.remove(PosixFilePermission.GROUP_READ);+ perms.remove(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(homeDir, "posix:permissions", perms);+ } catch (UnsupportedOperationException e) {+ throw new AssumptionViolatedException(+ "Cannot make " + homeDir + " non-readable. Test aborted.", e);+ }- assumeTrue(- "Cannot make " + homeDir + " non-readable. Test aborted.",- homeDir.setReadable(false, false));- assumeFalse("Appears we are a super user, skip test", homeDir.canRead());+ assumeFalse("Appears we are a super user, skip test", Files.isReadable(homeDir));Exception thrown =expectThrows(Exception.class,@@ -616,7 +671,11 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {});assertThat(thrown.getMessage(), containsString("Error reading core root directory"));// So things can be cleaned up by the framework!- homeDir.setReadable(true, false);+ Set<PosixFilePermission> perms = Files.getPosixFilePermissions(homeDir);+ perms.add(PosixFilePermission.OWNER_READ);+ perms.add(PosixFilePermission.GROUP_READ);+ perms.add(PosixFilePermission.OTHERS_READ);+ Files.setAttribute(homeDir, "posix:permissions", perms);}// For testing whether finding a solr.xml overrides looking at solr.properties@@ -624,7 +683,7 @@ public class TestCoreDiscovery extends SolrTestCaseJ4 {"<solr> "+ "<int name=\"transientCacheSize\">2</int> "+ "<str name=\"configSetBaseDir\">"- + Paths.get(TEST_HOME()).resolve("configsets")+ + TEST_HOME().resolve("configsets")+ "</str>"+ "<solrcloud> "+ "<int name=\"zkClientTimeout\">20</int> "diff --git a/solr/core/src/test/org/apache/solr/core/TestCorePropertiesReload.java b/solr/core/src/test/org/apache/solr/core/TestCorePropertiesReload.javaindex c2fe57d39ac..0438df638fe 100644--- a/solr/core/src/test/org/apache/solr/core/TestCorePropertiesReload.java+++ b/solr/core/src/test/org/apache/solr/core/TestCorePropertiesReload.java@@ -17,26 +17,26 @@package org.apache.solr.core;import java.io.BufferedWriter;-import java.io.File;-import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Properties;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.SolrTestCaseJ4;import org.junit.Test;public class TestCorePropertiesReload extends SolrTestCaseJ4 {- private final File solrHomeDirectory = createTempDir().toFile();+ private final Path solrHomeDirectory = createTempDir();public void setMeUp() throws Exception {- FileUtils.copyDirectory(new File(TEST_HOME()), solrHomeDirectory);+ PathUtils.copyDirectory(TEST_HOME(), solrHomeDirectory);Properties props = new Properties();props.setProperty("test", "Before reload");writeProperties(props);- initCore("solrconfig.xml", "schema.xml", solrHomeDirectory.getAbsolutePath());+ initCore("solrconfig.xml", "schema.xml", solrHomeDirectory);}@Test@@ -63,11 +63,11 @@ public class TestCorePropertiesReload extends SolrTestCaseJ4 {private void writeProperties(Properties props) throws Exception {Writer out = null;try {- File confDir = new File(new File(solrHomeDirectory, "collection1"), "conf");+ Path confDir = solrHomeDirectory.resolve("collection1").resolve("conf");out =new BufferedWriter(new OutputStreamWriter(- new FileOutputStream(new File(confDir, "solrcore.properties")),+ Files.newOutputStream(confDir.resolve("solrcore.properties")),StandardCharsets.UTF_8));props.store(out, "Reload Test");diff --git a/solr/core/src/test/org/apache/solr/core/TestFileSystemConfigSetService.java b/solr/core/src/test/org/apache/solr/core/TestFileSystemConfigSetService.javaindex 6e8b8fd3a41..5c9af89c5b8 100644--- a/solr/core/src/test/org/apache/solr/core/TestFileSystemConfigSetService.java+++ b/solr/core/src/test/org/apache/solr/core/TestFileSystemConfigSetService.java@@ -19,7 +19,6 @@ package org.apache.solr.core;import static org.apache.solr.core.FileSystemConfigSetService.METADATA_FILE;import static org.hamcrest.Matchers.hasItem;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -71,10 +70,7 @@ public class TestFileSystemConfigSetService extends SolrTestCaseJ4 {// Each of these will fail "quietly" as ConfigSetService opts to log warnings but otherwise not// surface validation errors to enable bulk uploading- final var invalidFilePaths =- List.of(- ".." + File.separator + "escapePath",- "foo" + File.separator + ".." + File.separator + ".." + File.separator + "bar");+ final var invalidFilePaths = List.of("../escapePath", "foo/../../bar");for (String invalidFilePath : invalidFilePaths) {fileSystemConfigSetService.uploadFileToConfig(configName, invalidFilePath, testdata, true);assertFalse(Files.exists(specificConfigSetBase.resolve(invalidFilePath)));diff --git a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java b/solr/core/src/test/org/apache/solr/core/TestLazyCores.javaindex 30b038609cb..3cc8ed7c77f 100644--- a/solr/core/src/test/org/apache/solr/core/TestLazyCores.java+++ b/solr/core/src/test/org/apache/solr/core/TestLazyCores.java@@ -16,7 +16,6 @@*/package org.apache.solr.core;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -57,7 +56,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {/** Transient core cache max size defined in the test solr-transientCores.xml */private static final int TRANSIENT_CORE_CACHE_MAX_SIZE = 4;- private File solrHomeDirectory;+ private Path solrHomeDirectory;@BeforeClasspublic static void setupClass() throws Exception {@@ -96,21 +95,21 @@ public class TestLazyCores extends SolrTestCaseJ4 {};private CoreContainer init() throws Exception {- solrHomeDirectory = createTempDir().toFile();+ solrHomeDirectory = createTempDir();- copyXmlToHome(solrHomeDirectory.getAbsoluteFile(), "solr-transientCores.xml");+ copyXmlToHome(solrHomeDirectory, "solr-transientCores.xml");for (int idx = 1; idx < 10; ++idx) {- copyMinConf(new File(solrHomeDirectory, "collection" + idx));+ copyMinConf(solrHomeDirectory.resolve("collection" + idx));}- NodeConfig cfg = NodeConfig.loadNodeConfig(solrHomeDirectory.toPath(), null);+ NodeConfig cfg = NodeConfig.loadNodeConfig(solrHomeDirectory, null);return createCoreContainer(cfg, testCores);}private CoreContainer initEmpty() throws IOException {- solrHomeDirectory = createTempDir().toFile();- copyXmlToHome(solrHomeDirectory.getAbsoluteFile(), "solr-transientCores.xml");- NodeConfig cfg = NodeConfig.loadNodeConfig(solrHomeDirectory.toPath(), null);+ solrHomeDirectory = createTempDir();+ copyXmlToHome(solrHomeDirectory, "solr-transientCores.xml");+ NodeConfig cfg = NodeConfig.loadNodeConfig(solrHomeDirectory, null);return createCoreContainer(cfg,new ReadOnlyCoresLocator() {@@ -427,10 +426,10 @@ public class TestLazyCores extends SolrTestCaseJ4 {SolrCore lc5 = cc.getCore("collection5");SolrCore lc6 = cc.getCore("collection6");- copyMinConf(new File(solrHomeDirectory, "t2"));- copyMinConf(new File(solrHomeDirectory, "t4"));- copyMinConf(new File(solrHomeDirectory, "t5"));- copyMinConf(new File(solrHomeDirectory, "t6"));+ copyMinConf(solrHomeDirectory.resolve("t2"));+ copyMinConf(solrHomeDirectory.resolve("t4"));+ copyMinConf(solrHomeDirectory.resolve("t5"));+ copyMinConf(solrHomeDirectory.resolve("t6"));// Should also fail with the same nametryCreateFail(admin, "collection2", "t12", "Core with name", "collection2", "already exists");@@ -487,11 +486,11 @@ public class TestLazyCores extends SolrTestCaseJ4 {public void testCreateTransientFromAdmin() throws Exception {final CoreContainer cc = initEmpty();try {- copyMinConf(new File(solrHomeDirectory, "core1"));- copyMinConf(new File(solrHomeDirectory, "core2"));- copyMinConf(new File(solrHomeDirectory, "core3"));- copyMinConf(new File(solrHomeDirectory, "core4"));- copyMinConf(new File(solrHomeDirectory, "core5"));+ copyMinConf(solrHomeDirectory.resolve("core1"));+ copyMinConf(solrHomeDirectory.resolve("core2"));+ copyMinConf(solrHomeDirectory.resolve("core3"));+ copyMinConf(solrHomeDirectory.resolve("core4"));+ copyMinConf(solrHomeDirectory.resolve("core5"));createViaAdmin(cc, "core1", true, true);createViaAdmin(cc, "core2", true, false);@@ -596,10 +595,12 @@ public class TestLazyCores extends SolrTestCaseJ4 {// Did we get the expected message for each of the cores that failed to load? Make sure we// don't run afoul of the dreaded slash/backslash difference on Windows and *nix machines.- testMessage(cc.getCoreInitFailures(), makePath("badConfig1", "conf", "solrconfig.xml"));- testMessage(cc.getCoreInitFailures(), makePath("badConfig2", "conf", "solrconfig.xml"));- testMessage(cc.getCoreInitFailures(), makePath("badSchema1", "conf", "schema.xml"));- testMessage(cc.getCoreInitFailures(), makePath("badSchema2", "conf", "schema.xml"));+ testMessage(+ cc.getCoreInitFailures(), Path.of("badConfig1", "conf", "solrconfig.xml").toString());+ testMessage(+ cc.getCoreInitFailures(), Path.of("badConfig2", "conf", "solrconfig.xml").toString());+ testMessage(cc.getCoreInitFailures(), Path.of("badSchema1", "conf", "schema.xml").toString());+ testMessage(cc.getCoreInitFailures(), Path.of("badSchema2", "conf", "schema.xml").toString());// Status should report that there are failure messages for the bad cores and none for the// good cores.@@ -677,7 +678,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {private void writeCustomConfig(String coreName, String config, String schema, String rand_snip)throws IOException {- Path coreRoot = solrHomeDirectory.toPath().resolve(coreName);+ Path coreRoot = solrHomeDirectory.resolve(coreName);Path subHome = coreRoot.resolve("conf");Files.createDirectories(subHome);// Write the file for core discovery@@ -706,14 +707,14 @@ public class TestLazyCores extends SolrTestCaseJ4 {private CoreContainer initGoodAndBad(List<String> goodCores, List<String> badSchemaCores, List<String> badConfigCores)throws Exception {- solrHomeDirectory = createTempDir().toFile();+ solrHomeDirectory = createTempDir();// Don't pollute the log with exception traces when they're expected.ignoreException(Pattern.quote("SAXParseException"));// Create the cores that should be fine.for (String coreName : goodCores) {- File coreRoot = new File(solrHomeDirectory, coreName);+ Path coreRoot = solrHomeDirectory.resolve(coreName);copyMinConf(coreRoot, "name=" + coreName);}@@ -740,7 +741,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {writeCustomConfig(coreName, min_config, bad_schema, rand_snip);}- NodeConfig config = SolrXmlConfig.fromString(solrHomeDirectory.toPath(), "<solr/>");+ NodeConfig config = SolrXmlConfig.fromString(solrHomeDirectory, "<solr/>");// OK this should succeed, but at the end we should have recorded a series of errors.return createCoreContainer(config, new CorePropertiesLocator(config));@@ -749,7 +750,7 @@ public class TestLazyCores extends SolrTestCaseJ4 {// We want to see that the core "heals itself" if an un-corrupted file is written to the// directory.private void copyGoodConf(String coreName, String srcName, String dstName) throws IOException {- Path coreRoot = solrHomeDirectory.toPath().resolve(coreName);+ Path coreRoot = solrHomeDirectory.resolve(coreName);Path subHome = coreRoot.resolve("conf");String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";Files.copy(@@ -895,10 +896,6 @@ public class TestLazyCores extends SolrTestCaseJ4 {return new LocalSolrQueryRequest(core, params(paramPairs));}- private static String makePath(String... args) {- return String.join(File.separator, args);- }-@Testpublic void testMidUseUnload() throws Exception {// sleep for up to 10 s Must add 1 because usingdiff --git a/solr/core/src/test/org/apache/solr/core/TestSolrConfigHandler.java b/solr/core/src/test/org/apache/solr/core/TestSolrConfigHandler.javaindex 7e4eb1db75f..9591d28bba1 100644--- a/solr/core/src/test/org/apache/solr/core/TestSolrConfigHandler.java+++ b/solr/core/src/test/org/apache/solr/core/TestSolrConfigHandler.java@@ -19,13 +19,14 @@ package org.apache.solr.core;import static java.util.Arrays.asList;import static org.apache.solr.common.util.Utils.getObjectByPath;-import java.io.File;-import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;+import java.io.InputStream;import java.io.StringReader;import java.lang.invoke.MethodHandles;import java.nio.ByteBuffer;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -35,7 +36,7 @@ import java.util.TreeMap;import java.util.concurrent.TimeUnit;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.common.LinkedHashMapWriter;@@ -78,8 +79,8 @@ public class TestSolrConfigHandler extends RestTestBase {*/public static ByteBuffer getFileContent(String f, boolean loadFromClassPath) throws IOException {ByteBuffer jar;- File file = loadFromClassPath ? getFile(f).toFile() : new File(f);- try (FileInputStream fis = new FileInputStream(file)) {+ Path file = loadFromClassPath ? getFile(f) : Path.of(f);+ try (InputStream fis = Files.newInputStream(file)) {byte[] buf = new byte[fis.available()];// TODO: This should check that we read the entire streamfis.read(buf);@@ -115,8 +116,8 @@ public class TestSolrConfigHandler extends RestTestBase {@Beforepublic void before() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();@@ -124,7 +125,7 @@ public class TestSolrConfigHandler extends RestTestBase {System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),+ tmpSolrHome,"solrconfig-managed-schema.xml","schema-rest.xml","/solr",diff --git a/solr/core/src/test/org/apache/solr/core/TestSolrXml.java b/solr/core/src/test/org/apache/solr/core/TestSolrXml.javaindex 55769fc369b..4d9faac73f5 100644--- a/solr/core/src/test/org/apache/solr/core/TestSolrXml.java+++ b/solr/core/src/test/org/apache/solr/core/TestSolrXml.java@@ -18,7 +18,6 @@ package org.apache.solr.core;import static org.hamcrest.core.StringContains.containsString;-import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;@@ -164,15 +163,16 @@ public class TestSolrXml extends SolrTestCaseJ4 {// Test a few property substitutions that happen to be in solr-50-all.xml.public void testPropertySub() throws IOException {+ Path testSrcRoot = TEST_PATH();System.setProperty(ContainerPluginsRegistry.CLUSTER_PLUGIN_EDIT_ENABLED, "false");- System.setProperty("coreRootDirectory", "myCoreRoot" + File.separator);+ System.setProperty(+ "coreRootDirectory", "myCoreRoot" + testSrcRoot.getFileSystem().getSeparator());System.setProperty("hostPort", "8888");System.setProperty("shareSchema", "false");System.setProperty("socketTimeout", "220");System.setProperty("connTimeout", "200");- Path testSrcRoot = TEST_PATH();Files.copy(testSrcRoot.resolve("solr-50-all.xml"), solrHome.resolve("solr.xml"));NodeConfig cfg = SolrXmlConfig.fromSolrHome(solrHome, new Properties());diff --git a/solr/core/src/test/org/apache/solr/handler/PingRequestHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/PingRequestHandlerTest.javaindex ae2fbae833e..3f151e51efc 100644--- a/solr/core/src/test/org/apache/solr/handler/PingRequestHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/PingRequestHandlerTest.java@@ -16,12 +16,11 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;+import java.nio.file.Path;import java.util.List;-import org.apache.commons.io.FileUtils;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;@@ -44,7 +43,7 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {protected int REPLICATION_FACTOR = 2;private final String fileName = this.getClass().getName() + ".server-enabled";- private File healthcheckFile = null;+ private Path healthcheckFile = null;private PingRequestHandler handler = null;@BeforeClass@@ -55,15 +54,15 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {@Beforepublic void before() throws IOException {// by default, use relative file in dataDir- healthcheckFile = new File(initAndGetDataDir(), fileName);+ healthcheckFile = initAndGetDataDir().resolve(fileName);String fileNameParam = fileName;// sometimes randomly use an absolute File path insteadif (random().nextBoolean()) {- fileNameParam = healthcheckFile.getAbsolutePath();+ fileNameParam = healthcheckFile.toString();}- if (healthcheckFile.exists()) FileUtils.forceDelete(healthcheckFile);+ if (Files.exists(healthcheckFile)) Files.delete(healthcheckFile);handler = new PingRequestHandler();NamedList<String> initParams = new NamedList<>();@@ -90,7 +89,7 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {public void testEnablingServer() throws Exception {- assertFalse(healthcheckFile.exists());+ assertFalse(Files.exists(healthcheckFile));// first make sure that ping responds back that the service is disabledSolrQueryResponse sqr = makeRequest(handler, req());@@ -104,8 +103,8 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {makeRequest(handler, req("action", "enable"));- assertTrue(healthcheckFile.exists());- assertNotNull(Files.readString(healthcheckFile.toPath(), StandardCharsets.UTF_8));+ assertTrue(Files.exists(healthcheckFile));+ assertNotNull(Files.readString(healthcheckFile, StandardCharsets.UTF_8));// now verify that the handler response with success@@ -114,14 +113,14 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {// enable when already enabled shouldn't cause any problemsmakeRequest(handler, req("action", "enable"));- assertTrue(healthcheckFile.exists());+ assertTrue(Files.exists(healthcheckFile));}public void testDisablingServer() throws Exception {- assertFalse(healthcheckFile.exists());+ assertFalse(Files.exists(healthcheckFile));- healthcheckFile.createNewFile();+ Files.createFile(healthcheckFile);// first make sure that ping responds back that the service is enabled@@ -132,7 +131,7 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {makeRequest(handler, req("action", "disable"));- assertFalse(healthcheckFile.exists());+ assertFalse(Files.exists(healthcheckFile));// now make sure that ping responds back that the service is disabledSolrQueryResponse sqr = makeRequest(handler, req());@@ -144,7 +143,7 @@ public class PingRequestHandlerTest extends SolrTestCaseJ4 {// disable when already disabled shouldn't cause any problemsmakeRequest(handler, req("action", "disable"));- assertFalse(healthcheckFile.exists());+ assertFalse(Files.exists(healthcheckFile));}public void testGettingStatus() throws Exception {diff --git a/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java b/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.javaindex deba80bece7..51d5d72ee78 100644--- a/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java+++ b/solr/core/src/test/org/apache/solr/handler/ReplicationTestHelper.java@@ -17,7 +17,6 @@package org.apache.solr.handler;import java.io.BufferedReader;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.Writer;@@ -25,6 +24,7 @@ import java.lang.invoke.MethodHandles;import java.net.URI;import java.net.URL;import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;@@ -52,11 +52,16 @@ public final class ReplicationTestHelper {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());public static final String CONF_DIR =- "solr" + File.separator + "collection1" + File.separator + "conf" + File.separator;+ "solr"+ + FileSystems.getDefault().getSeparator()+ + "collection1"+ + FileSystems.getDefault().getSeparator()+ + "conf"+ + FileSystems.getDefault().getSeparator();public static JettySolrRunner createAndStartJetty(SolrInstance instance) throws Exception {Files.copy(- Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"),+ SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"),Path.of(instance.getHomeDir(), "solr.xml"),StandardCopyOption.REPLACE_EXISTING);Properties nodeProperties = new Properties();@@ -98,10 +103,10 @@ public final class ReplicationTestHelper {* character copy of file using UTF-8. If port is non-null, will be substituted any time* "TEST_PORT" is found.*/- private static void copyFile(Path src, File dst, Integer port, boolean internalCompression)+ private static void copyFile(Path src, Path dst, Integer port, boolean internalCompression)throws IOException {try (BufferedReader in = Files.newBufferedReader(src, StandardCharsets.UTF_8);- Writer out = Files.newBufferedWriter(dst.toPath(), StandardCharsets.UTF_8)) {+ Writer out = Files.newBufferedWriter(dst, StandardCharsets.UTF_8)) {for (String line = in.readLine(); null != line; line = in.readLine()) {if (null != port) {line = line.replace("TEST_PORT", port.toString());@@ -239,9 +244,9 @@ public final class ReplicationTestHelper {private final String name;private Integer testPort;- private final File homeDir;- private File confDir;- private File dataDir;+ private final Path homeDir;+ private Path confDir;+ private Path dataDir;/*** @param homeDir Base directory to build solr configuration and index in@@ -249,7 +254,7 @@ public final class ReplicationTestHelper {* new conf dir.* @param testPort if not null, used as a replacement for TEST_PORT in the cloned config files.*/- public SolrInstance(File homeDir, String name, Integer testPort) {+ public SolrInstance(Path homeDir, String name, Integer testPort) {this.homeDir = homeDir;this.name = name;this.testPort = testPort;@@ -268,7 +273,7 @@ public final class ReplicationTestHelper {}public String getDataDir() {- return dataDir.getAbsolutePath();+ return dataDir.toString();}public String getSolrConfigFile() {@@ -288,14 +293,14 @@ public final class ReplicationTestHelper {props.setProperty("name", "collection1");SolrTestCaseJ4.writeCoreProperties(- homeDir.toPath().resolve("collection1"), props, "TestReplicationHandler");+ homeDir.resolve("collection1"), props, "TestReplicationHandler");- dataDir = new File(homeDir + "/collection1", "data");- confDir = new File(homeDir + "/collection1", "conf");+ dataDir = Path.of(homeDir + "/collection1", "data");+ confDir = Path.of(homeDir + "/collection1", "conf");- homeDir.mkdirs();- dataDir.mkdirs();- confDir.mkdirs();+ Files.createDirectories(homeDir);+ Files.createDirectories(dataDir);+ Files.createDirectories(confDir);copyConfigFile(getSolrConfigFile(), "solrconfig.xml");copyConfigFile(getSchemaFile(), "schema.xml");@@ -307,7 +312,7 @@ public final class ReplicationTestHelper {public void copyConfigFile(String srcFile, String destFile) throws IOException {copyFile(SolrTestCaseJ4.getFile(srcFile),- new File(confDir, destFile),+ confDir.resolve(destFile),testPort,LuceneTestCase.random().nextBoolean());}diff --git a/solr/core/src/test/org/apache/solr/handler/TestCSVLoader.java b/solr/core/src/test/org/apache/solr/handler/TestCSVLoader.javaindex 2126747c19d..94fe9195d08 100644--- a/solr/core/src/test/org/apache/solr/handler/TestCSVLoader.java+++ b/solr/core/src/test/org/apache/solr/handler/TestCSVLoader.java@@ -16,7 +16,6 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -42,7 +41,7 @@ public class TestCSVLoader extends SolrTestCaseJ4 {}String filename;- File file;+ Path file;@Override@Before@@ -50,9 +49,9 @@ public class TestCSVLoader extends SolrTestCaseJ4 {// if you override setUp or tearDown, you better call// the super classes versionsuper.setUp();- File tempDir = createTempDir("TestCSVLoader").toFile();- file = new File(tempDir, "solr_tmp.csv");- filename = file.getPath();+ Path tempDir = createTempDir("TestCSVLoader");+ file = tempDir.resolve("solr_tmp.csv");+ filename = file.toString();cleanup();}@@ -63,7 +62,7 @@ public class TestCSVLoader extends SolrTestCaseJ4 {// the super classes versionsuper.tearDown();if (null != file) {- Files.delete(file.toPath());+ Files.delete(file);file = null;}}diff --git a/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java b/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.javaindex fe25a08da3c..e3d71e71ddc 100644--- a/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java+++ b/solr/core/src/test/org/apache/solr/handler/TestHealthCheckHandlerLegacyMode.java@@ -53,9 +53,7 @@ public class TestHealthCheckHandlerLegacyMode extends SolrTestCaseJ4 {systemSetPropertySolrDisableUrlAllowList("true");- leader =- new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "leader", null);+ leader = new ReplicationTestHelper.SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();leaderJetty = ReplicationTestHelper.createAndStartJetty(leader);leaderClient =@@ -65,8 +63,7 @@ public class TestHealthCheckHandlerLegacyMode extends SolrTestCaseJ4 {ReplicationTestHelper.createNewSolrClient(buildUrl(leaderJetty.getLocalPort()));follower =- new SolrInstance(- createTempDir("solr-instance").toFile(), "follower", leaderJetty.getLocalPort());+ new SolrInstance(createTempDir("solr-instance"), "follower", leaderJetty.getLocalPort());follower.setUp();followerJetty = createAndStartJetty(follower);followerClient =diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.javaindex 02098fb734d..cb81b084cc0 100644--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java@@ -23,13 +23,13 @@ import static org.apache.solr.handler.ReplicationTestHelper.createNewSolrClient;import static org.apache.solr.handler.ReplicationTestHelper.invokeReplicationCommand;import static org.hamcrest.CoreMatchers.containsString;-import java.io.File;-import java.io.FilenameFilter;import java.io.IOException;import java.io.InputStream;import java.lang.invoke.MethodHandles;import java.net.URI;import java.net.URL;+import java.nio.file.Files;+import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays;import java.util.Collection;@@ -37,6 +37,7 @@ import java.util.Date;import java.util.List;import java.util.Set;import java.util.concurrent.TimeUnit;+import java.util.stream.Stream;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;import org.apache.lucene.store.Directory;@@ -109,7 +110,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory");// For manual testing only// useFactory(null); // force an FS factory.- leader = new SolrInstance(createTempDir("solr-instance").toFile(), "leader", null);+ leader = new SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();leaderJetty = createAndStartJetty(leader);leaderClient =@@ -117,8 +118,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {buildUrl(leaderJetty.getLocalPort()), DEFAULT_TEST_CORENAME);follower =- new SolrInstance(- createTempDir("solr-instance").toFile(), "follower", leaderJetty.getLocalPort());+ new SolrInstance(createTempDir("solr-instance"), "follower", leaderJetty.getLocalPort());follower.setUp();followerJetty = createAndStartJetty(follower);followerClient =@@ -353,8 +353,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {SolrClient repeaterClient = null;try {repeater =- new SolrInstance(- createTempDir("solr-instance").toFile(), "repeater", leaderJetty.getLocalPort());+ new SolrInstance(createTempDir("solr-instance"), "repeater", leaderJetty.getLocalPort());repeater.setUp();repeaterJetty = createAndStartJetty(repeater);repeaterClient =@@ -528,14 +527,18 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {followerJetty.stop();// set up a subdirectory /foo/ in order to force subdir file replication- File leaderFooDir = new File(leader.getConfDir() + File.separator + "foo");- File leaderBarFile = new File(leaderFooDir, "bar.txt");- assertTrue("could not make dir " + leaderFooDir, leaderFooDir.mkdirs());- assertTrue(leaderBarFile.createNewFile());+ Path leaderFooDir = Path.of(leader.getConfDir()).resolve("foo");+ Path leaderBarFile = leaderFooDir.resolve("bar.txt");+ try {+ Files.createDirectories(leaderFooDir);+ Files.createFile(leaderBarFile);+ } catch (Exception e) {+ throw new RuntimeException("could not make dir or file " + leaderFooDir, e);+ }- File followerFooDir = new File(follower.getConfDir() + File.separator + "foo");- File followerBarFile = new File(followerFooDir, "bar.txt");- assertFalse(followerFooDir.exists());+ Path followerFooDir = Path.of(follower.getConfDir()).resolve("foo");+ Path followerBarFile = followerFooDir.resolve("bar.txt");+ assertFalse(Files.exists(followerFooDir));followerJetty = createAndStartJetty(follower);followerClient.close();@@ -552,8 +555,8 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {SolrDocument d = ((SolrDocumentList) followerQueryRsp.get("response")).get(0);assertEquals("newname = 2000", d.getFieldValue("newname"));- assertTrue(followerFooDir.isDirectory());- assertTrue(followerBarFile.exists());+ assertTrue(Files.isDirectory(followerFooDir));+ assertTrue(Files.exists(followerBarFile));checkForSingleIndex(leaderJetty);checkForSingleIndex(followerJetty, true);@@ -990,11 +993,11 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {return (CachingDirectoryFactory) core.getDirectoryFactory();}- private void checkForSingleIndex(JettySolrRunner jetty) {+ private void checkForSingleIndex(JettySolrRunner jetty) throws IOException {checkForSingleIndex(jetty, false);}- private void checkForSingleIndex(JettySolrRunner jetty, boolean afterReload) {+ private void checkForSingleIndex(JettySolrRunner jetty, boolean afterReload) throws IOException {CoreContainer cores = jetty.getCoreContainer();Collection<SolrCore> theCores = cores.getCores();for (SolrCore core : theCores) {@@ -1015,31 +1018,30 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {// :TODO: assert that one of the paths is a subpath of hte other}if (dirFactory instanceof StandardDirectoryFactory) {- System.out.println(Arrays.asList(new File(ddir).list()));- // we also allow one extra index dir - it may not be removed until the core is closed- int cnt = indexDirCount(ddir);- // if after reload, there may be 2 index dirs while the reloaded SolrCore closes.- if (afterReload) {- assertTrue("found:" + cnt + Arrays.asList(new File(ddir).list()), 1 == cnt || 2 == cnt);- } else {- assertEquals("found:" + cnt + Arrays.asList(new File(ddir).list()), 1, cnt);+ try (Stream<Path> files = Files.list(Path.of(ddir))) {+ List<Path> filesList = files.toList();+ System.out.println(filesList);+ // we also allow one extra index dir - it may not be removed until the core is closed+ int cnt = indexDirCount(ddir);+ // if after reload, there may be 2 index dirs while the reloaded SolrCore closes.+ if (afterReload) {+ assertTrue("found:" + cnt + filesList, 1 == cnt || 2 == cnt);+ } else {+ assertEquals("found:" + cnt + filesList, 1, cnt);+ }}}}}- private int indexDirCount(String ddir) {- String[] list =- new File(ddir)- .list(- new FilenameFilter() {- @Override- public boolean accept(File dir, String name) {- File f = new File(dir, name);- return f.isDirectory() && !name.startsWith("snapshot");- }- });- return list.length;+ private int indexDirCount(String ddir) throws IOException {+ try (Stream<Path> files = Files.list(Path.of(ddir))) {+ return (int)+ files+ .filter(+ (file) -> Files.isDirectory(file) && !file.getFileName().startsWith("snapshot"))+ .count();+ }}public static void pullFromTo(JettySolrRunner srcSolr, JettySolrRunner destSolr)@@ -1062,8 +1064,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {try {repeater =- new SolrInstance(- createTempDir("solr-instance").toFile(), "repeater", leaderJetty.getLocalPort());+ new SolrInstance(createTempDir("solr-instance"), "repeater", leaderJetty.getLocalPort());repeater.setUp();repeater.copyConfigFile(CONF_DIR + "solrconfig-repeater.xml", "solrconfig.xml");repeaterJetty = createAndStartJetty(repeater);@@ -1547,10 +1548,10 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {@Testpublic void testEmptyBackups() throws Exception {- final File backupDir = createTempDir().toFile();+ final Path backupDir = createTempDir();final BackupStatusChecker backupStatus = new BackupStatusChecker(leaderClient);- leaderJetty.getCoreContainer().getAllowPaths().add(backupDir.toPath());+ leaderJetty.getCoreContainer().getAllowPaths().add(backupDir);{ // initial request w/o any committed docsfinal String backupName = "empty_backup1";@@ -1558,13 +1559,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {new GenericSolrRequest(SolrRequest.METHOD.GET,"/replication",- params(- "command",- "backup",- "location",- backupDir.getAbsolutePath(),- "name",- backupName))+ params("command", "backup", "location", backupDir.toString(), "name", backupName)).setRequiresCollection(true);final TimeOut timeout = new TimeOut(30, TimeUnit.SECONDS, TimeSource.NANO_TIME);final SimpleSolrResponse rsp = req.process(leaderClient);@@ -1576,7 +1571,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {dirName);assertTrue(dirName + " doesn't exist in expected location for backup " + backupName,- new File(backupDir, dirName).exists());+ Files.exists(backupDir.resolve(dirName)));}index(leaderClient, "id", "1", "name", "foo");@@ -1587,13 +1582,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {new GenericSolrRequest(SolrRequest.METHOD.GET,"/replication",- params(- "command",- "backup",- "location",- backupDir.getAbsolutePath(),- "name",- backupName))+ params("command", "backup", "location", backupDir.toString(), "name", backupName)).setRequiresCollection(true);final TimeOut timeout = new TimeOut(30, TimeUnit.SECONDS, TimeSource.NANO_TIME);final SimpleSolrResponse rsp = req.process(leaderClient);@@ -1605,13 +1594,13 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {dirName);assertTrue(dirName + " doesn't exist in expected location for backup " + backupName,- new File(backupDir, dirName).exists());+ Files.exists(backupDir.resolve(dirName)));}// confirm backups really are emptyfor (int i = 1; i <= 2; i++) {final String name = "snapshot.empty_backup" + i;- try (Directory dir = new NIOFSDirectory(new File(backupDir, name).toPath());+ try (Directory dir = new NIOFSDirectory(backupDir.resolve(name));IndexReader reader = DirectoryReader.open(dir)) {assertEquals(name + " is not empty", 0, reader.numDocs());}diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerBackup.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerBackup.javaindex 83990058abc..b46627825ee 100644--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerBackup.java+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerBackup.java@@ -16,7 +16,6 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.lang.invoke.MethodHandles;@@ -61,8 +60,7 @@ public class TestReplicationHandlerBackup extends SolrJettyTestBase {ReplicationTestHelper.SolrInstance leader = null;SolrClient leaderClient;- private static final String CONF_DIR =- "solr" + File.separator + "collection1" + File.separator + "conf" + File.separator;+ private static final Path CONF_DIR = Path.of("solr", "collection1", "conf");boolean addNumberToKeepInRequest = true;String backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_REQUEST_PARAM;@@ -72,8 +70,7 @@ public class TestReplicationHandlerBackup extends SolrJettyTestBase {private static JettySolrRunner createAndStartJetty(ReplicationTestHelper.SolrInstance instance)throws Exception {Files.copy(- Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"),- Path.of(instance.getHomeDir(), "solr.xml"));+ SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"), Path.of(instance.getHomeDir(), "solr.xml"));Properties nodeProperties = new Properties();nodeProperties.setProperty("solr.data.dir", instance.getDataDir());JettyConfig jettyConfig = JettyConfig.builder().setPort(0).build();@@ -101,11 +98,9 @@ public class TestReplicationHandlerBackup extends SolrJettyTestBase {addNumberToKeepInRequest = false;backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_INIT_PARAM;}- leader =- new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "leader", null);+ leader = new ReplicationTestHelper.SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();- leader.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml");+ leader.copyConfigFile(CONF_DIR.resolve(configFile).toString(), "solrconfig.xml");leaderJetty = createAndStartJetty(leader);leaderClient = createNewSolrClient(leaderJetty.getLocalPort());diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.javaindex 7bd54f68c77..aa43d39dab9 100644--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandlerDiskOverFlow.java@@ -74,9 +74,7 @@ public class TestReplicationHandlerDiskOverFlow extends SolrTestCaseJ4 {? "solr.NRTCachingDirectoryFactory": "solr.StandardDirectoryFactory"; // test the default most of the timeSystem.setProperty("solr.directoryFactory", factory);- leader =- new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "leader", null);+ leader = new ReplicationTestHelper.SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();leaderJetty = createAndStartJetty(leader);leaderClient =@@ -86,7 +84,7 @@ public class TestReplicationHandlerDiskOverFlow extends SolrTestCaseJ4 {follower =new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "follower", leaderJetty.getLocalPort());+ createTempDir("solr-instance"), "follower", leaderJetty.getLocalPort());follower.setUp();followerJetty = createAndStartJetty(follower);followerClient =diff --git a/solr/core/src/test/org/apache/solr/handler/TestRestoreCore.java b/solr/core/src/test/org/apache/solr/handler/TestRestoreCore.javaindex a4de0796d69..e0d5a1a0110 100644--- a/solr/core/src/test/org/apache/solr/handler/TestRestoreCore.java+++ b/solr/core/src/test/org/apache/solr/handler/TestRestoreCore.java@@ -16,7 +16,6 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;@@ -49,16 +48,14 @@ public class TestRestoreCore extends SolrJettyTestBase {ReplicationTestHelper.SolrInstance leader = null;SolrClient leaderClient;- private static final String CONF_DIR =- "solr" + File.separator + DEFAULT_TEST_CORENAME + File.separator + "conf" + File.separator;+ private static final Path CONF_DIR = Path.of("solr", DEFAULT_TEST_CORENAME, "conf");private static long docsSeed; // see indexDocs()private static JettySolrRunner createAndStartJetty(ReplicationTestHelper.SolrInstance instance)throws Exception {Files.copy(- Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"),- Path.of(instance.getHomeDir(), "solr.xml"));+ SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"), Path.of(instance.getHomeDir(), "solr.xml"));Properties nodeProperties = new Properties();nodeProperties.setProperty("solr.data.dir", instance.getDataDir());JettyConfig jettyConfig = JettyConfig.builder().setPort(0).build();@@ -82,11 +79,9 @@ public class TestRestoreCore extends SolrJettyTestBase {super.setUp();String configFile = "solrconfig-leader.xml";- leader =- new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "leader", null);+ leader = new ReplicationTestHelper.SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();- leader.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml");+ leader.copyConfigFile(CONF_DIR.resolve(configFile).toString(), "solrconfig.xml");leaderJetty = createAndStartJetty(leader);leaderClient = createNewSolrClient(leaderJetty.getLocalPort());diff --git a/solr/core/src/test/org/apache/solr/handler/TestSampleDocumentsLoader.java b/solr/core/src/test/org/apache/solr/handler/TestSampleDocumentsLoader.javaindex d56000c1b36..cda9006ffd1 100644--- a/solr/core/src/test/org/apache/solr/handler/TestSampleDocumentsLoader.java+++ b/solr/core/src/test/org/apache/solr/handler/TestSampleDocumentsLoader.java@@ -17,8 +17,9 @@package org.apache.solr.handler;-import java.io.File;import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.List;import org.apache.solr.SolrTestCase;import org.apache.solr.common.SolrInputDocument;@@ -38,21 +39,21 @@ import org.junit.Test;public class TestSampleDocumentsLoader extends SolrTestCase {SampleDocumentsLoader loader;- File exampleDir;+ Path exampleDir;@Beforepublic void setup() throws IOException {loader = new DefaultSampleDocumentsLoader();loader.init(new NamedList<>());- exampleDir = new File(ExternalPaths.SOURCE_HOME, "example");+ exampleDir = ExternalPaths.SOURCE_HOME.resolve("example");assertTrue(- "Required test data directory " + exampleDir.getCanonicalPath() + " not found!",- exampleDir.isDirectory());+ "Required test data directory " + exampleDir.toRealPath() + " not found!",+ Files.isDirectory(exampleDir));}@Testpublic void testJson() throws Exception {- loadTestDocs(SolrParams.of(), new File(exampleDir, "films/films.json"), 500, 500);+ loadTestDocs(SolrParams.of(), exampleDir.resolve("films/films.json"), 500, 500);}@Test@@ -60,7 +61,7 @@ public class TestSampleDocumentsLoader extends SolrTestCase {ModifiableSolrParams params = new ModifiableSolrParams();params.set(DefaultSampleDocumentsLoader.CSV_MULTI_VALUE_DELIM_PARAM, "\\|");List<SolrInputDocument> docs =- loadTestDocs(params, new File(exampleDir, "films/films.csv"), -1, 1100);+ loadTestDocs(params, exampleDir.resolve("films/films.csv"), -1, 1100);boolean foundIt = false;for (SolrInputDocument next : docs) {if (".45".equals(next.getFieldValue("name"))) {@@ -78,12 +79,12 @@ public class TestSampleDocumentsLoader extends SolrTestCase {@Testpublic void testSolrXml() throws Exception {- loadTestDocs(SolrParams.of(), new File(exampleDir, "films/films.xml"), 1000, 1000);+ loadTestDocs(SolrParams.of(), exampleDir.resolve("films/films.xml"), 1000, 1000);}protected List<SolrInputDocument> loadTestDocs(- SolrParams params, File inputDocs, int maxDocsToLoad, int expectedDocs) throws IOException {- assertTrue(inputDocs.getCanonicalPath() + " not found", inputDocs.isFile());+ SolrParams params, Path inputDocs, int maxDocsToLoad, int expectedDocs) throws IOException {+ assertTrue(inputDocs.toRealPath() + " not found", Files.isRegularFile(inputDocs));ContentStream stream = getContentStream(inputDocs);SampleDocuments sampleDocs = loader.parseDocsFromStream(params, stream, maxDocsToLoad);assertNotNull(sampleDocs);@@ -109,12 +110,12 @@ public class TestSampleDocumentsLoader extends SolrTestCase {return "application/octet-stream";}- protected ContentStream getContentStream(File file) throws IOException {- return getContentStream(file, guessContentTypeFromFilename(file.getName()));+ protected ContentStream getContentStream(Path file) throws IOException {+ return getContentStream(file, guessContentTypeFromFilename(file.getFileName().toString()));}- protected ContentStream getContentStream(File file, String contentType) throws IOException {- ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(file.toPath());+ protected ContentStream getContentStream(Path file, String contentType) throws IOException {+ ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(file);stream.setContentType(contentType);return stream;}diff --git a/solr/core/src/test/org/apache/solr/handler/TestSnapshotCoreBackup.java b/solr/core/src/test/org/apache/solr/handler/TestSnapshotCoreBackup.javaindex 43cda66938d..91021c144e9 100644--- a/solr/core/src/test/org/apache/solr/handler/TestSnapshotCoreBackup.java+++ b/solr/core/src/test/org/apache/solr/handler/TestSnapshotCoreBackup.java@@ -16,9 +16,9 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;-import java.nio.file.Paths;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Arrays;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexCommit;@@ -61,11 +61,11 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {assertQ(req("q", "id:2"), "//result[@numFound='0']");// call backup- String location = createTempDir().toFile().getAbsolutePath();+ Path location = createTempDir();String snapshotName = TestUtil.randomSimpleString(random(), 1, 5);final CoreContainer cores = h.getCoreContainer();- cores.getAllowPaths().add(Paths.get(location));+ cores.getAllowPaths().add(location);try (final CoreAdminHandler admin = new CoreAdminHandler(cores)) {SolrQueryResponse resp = new SolrQueryResponse();admin.handleRequestBody(@@ -77,12 +77,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name",snapshotName,"location",- location,+ location.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());- simpleBackupCheck(new File(location, "snapshot." + snapshotName), 2);+ simpleBackupCheck(location.resolve("snapshot." + snapshotName), 2);}}@@ -108,8 +108,8 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {final CoreContainer cores = h.getCoreContainer();final CoreAdminHandler admin = new CoreAdminHandler(cores);- final File backupDir = createTempDir().toFile();- cores.getAllowPaths().add(backupDir.toPath());+ final Path backupDir = createTempDir();+ cores.getAllowPaths().add(backupDir);{ // first a backup before we've ever done *anything*...SolrQueryResponse resp = new SolrQueryResponse();@@ -122,13 +122,13 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name","empty_backup1","location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());simpleBackupCheck(- new File(backupDir, "snapshot.empty_backup1"), 0, initialEmptyIndexSegmentFileName);+ backupDir.resolve("snapshot.empty_backup1"), 0, initialEmptyIndexSegmentFileName);}{ // Empty (named) snapshot...@@ -158,13 +158,13 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name","empty_backup2","location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());simpleBackupCheck(- new File(backupDir, "snapshot.empty_backup2"), 0, initialEmptyIndexSegmentFileName);+ backupDir.resolve("snapshot.empty_backup2"), 0, initialEmptyIndexSegmentFileName);}{ // Second empty (named) snapshot...@@ -185,8 +185,7 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {assertU(commit());for (String name : Arrays.asList("empty_backup1", "empty_backup2")) {- simpleBackupCheck(- new File(backupDir, "snapshot." + name), 0, initialEmptyIndexSegmentFileName);+ simpleBackupCheck(backupDir.resolve("snapshot." + name), 0, initialEmptyIndexSegmentFileName);}// Make backups from each of the snapshots and check they are still empty as well...@@ -205,13 +204,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"commitName",snapName,"location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup " + name + " should have succeeded", resp.getException());- simpleBackupCheck(- new File(backupDir, "snapshot." + name), 0, initialEmptyIndexSegmentFileName);+ simpleBackupCheck(backupDir.resolve("snapshot." + name), 0, initialEmptyIndexSegmentFileName);}admin.close();}@@ -237,8 +235,8 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {final CoreContainer cores = h.getCoreContainer();final CoreAdminHandler admin = new CoreAdminHandler(cores);- final File backupDir = createTempDir().toFile();- cores.getAllowPaths().add(backupDir.toPath());+ final Path backupDir = createTempDir();+ cores.getAllowPaths().add(backupDir);{ // take an initial 'backup1a' containing our 1 documentfinal SolrQueryResponse resp = new SolrQueryResponse();@@ -251,12 +249,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name","backup1a","location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());- simpleBackupCheck(new File(backupDir, "snapshot.backup1a"), 1, oneDocSegmentFile);+ simpleBackupCheck(backupDir.resolve("snapshot.backup1a"), 1, oneDocSegmentFile);}{ // and an initial "snapshot1a' that should eventually match@@ -294,12 +292,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name","backup1b","location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());- simpleBackupCheck(new File(backupDir, "snapshot.backup1b"), 1, oneDocSegmentFile);+ simpleBackupCheck(backupDir.resolve("snapshot.backup1b"), 1, oneDocSegmentFile);}{ // and a second "snapshot1b' should also still be identical@@ -320,7 +318,7 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {assertU(commit());for (String name : Arrays.asList("backup1a", "backup1b")) {- simpleBackupCheck(new File(backupDir, "snapshot." + name), 1, oneDocSegmentFile);+ simpleBackupCheck(backupDir.resolve("snapshot." + name), 1, oneDocSegmentFile);}{ // But we should be able to confirm both docs appear in a new backup (not based on a previous@@ -335,12 +333,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"name","backup2","location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup should have succeeded", resp.getException());- simpleBackupCheck(new File(backupDir, "snapshot.backup2"), 2);+ simpleBackupCheck(backupDir.resolve("snapshot.backup2"), 2);}// if we go back and create backups from our earlier snapshots they should still only@@ -360,12 +358,12 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {"commitName",snapName,"location",- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false"),resp);assertNull("Backup " + name + " should have succeeded", resp.getException());- simpleBackupCheck(new File(backupDir, "snapshot." + name), 1, oneDocSegmentFile);+ simpleBackupCheck(backupDir.resolve("snapshot." + name), 1, oneDocSegmentFile);}admin.close();}@@ -433,7 +431,7 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {/*** Simple check that the backup exists, is a valid index, and contains the expected number of docs*/- private static void simpleBackupCheck(final File backup, final int numDocs) throws IOException {+ private static void simpleBackupCheck(final Path backup, final int numDocs) throws IOException {simpleBackupCheck(backup, numDocs, null);}@@ -444,16 +442,16 @@ public class TestSnapshotCoreBackup extends SolrTestCaseJ4 {* backup.*/private static void simpleBackupCheck(- final File backup, final int numDocs, final String expectedSegmentsFileName)+ final Path backup, final int numDocs, final String expectedSegmentsFileName)throws IOException {assertNotNull(backup);- assertTrue("Backup doesn't exist" + backup, backup.exists());+ assertTrue("Backup doesn't exist" + backup, Files.exists(backup));if (null != expectedSegmentsFileName) {assertTrue(expectedSegmentsFileName + " doesn't exist in " + backup,- new File(backup, expectedSegmentsFileName).exists());+ Files.exists(backup.resolve(expectedSegmentsFileName)));}- try (Directory dir = FSDirectory.open(backup.toPath())) {+ try (Directory dir = FSDirectory.open(backup)) {TestUtil.checkIndex(dir, true, true, true, null);try (DirectoryReader r = DirectoryReader.open(dir)) {assertEquals("numDocs in " + backup, numDocs, r.numDocs());diff --git a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.javaindex 1817361d508..e8ee01898d3 100644--- a/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java+++ b/solr/core/src/test/org/apache/solr/handler/TestStressThreadBackup.java@@ -16,11 +16,11 @@*/package org.apache.solr.handler;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayDeque;-import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.Queue;@@ -29,6 +29,7 @@ import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicReference;import java.util.regex.Matcher;import java.util.regex.Pattern;+import java.util.stream.Stream;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.Term;import org.apache.lucene.store.Directory;@@ -66,7 +67,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());private static final Pattern ENDS_WITH_INT_DIGITS = Pattern.compile("\\d+$");- private File backupDir;+ private Path backupDir;private SolrClient adminClient;private SolrClient coreClient;private String coreName;@@ -83,7 +84,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {@Beforepublic void beforeTest() throws Exception {- backupDir = createTempDir(getTestClass().getSimpleName() + "_backups").toFile();+ backupDir = createTempDir(getTestClass().getSimpleName() + "_backups");// NOTE: we don't actually care about using SolrCloud, but we want to use SolrClient and I can't// bring myself to deal with the nonsense that is SolrJettyTestBase.@@ -150,7 +151,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {"name",backupName,CoreAdminParams.BACKUP_LOCATION,- backupDir.getAbsolutePath());+ backupDir.toString());if (null != snapName) {p.add(CoreAdminParams.COMMIT_NAME, snapName);}@@ -285,13 +286,14 @@ public class TestStressThreadBackup extends SolrCloudTestCase {log.info("Validating {} random backups to ensure they are un-affected by deleting all docs...",numBackupsToCheck);- final List<File> allBackups = Arrays.asList(backupDir.listFiles());- // insure consistent (arbitrary) ordering before shuffling- Collections.sort(allBackups);- Collections.shuffle(allBackups, random());- for (int i = 0; i < numBackupsToCheck; i++) {- final File backup = allBackups.get(i);- validateBackup(backup);+ try (Stream<Path> files = Files.list(backupDir)) {+ // insure consistent (arbitrary) ordering before shuffling+ final List<Path> allBackups = files.sorted().toList();+ Collections.shuffle(allBackups, random());+ for (int i = 0; i < numBackupsToCheck; i++) {+ final Path backup = allBackups.get(i);+ validateBackup(backup);+ }}}}@@ -312,10 +314,10 @@ public class TestStressThreadBackup extends SolrCloudTestCase {* Validates a backup exists, passes check index, and contains a number of "real" documents that* match its name*- * @see #validateBackup(File)+ * @see #validateBackup(Path)*/private void validateBackup(final String backupName) throws IOException {- final File backup = new File(backupDir, "snapshot." + backupName);+ final Path backup = backupDir.resolve("snapshot." + backupName);validateBackup(backup);}@@ -323,14 +325,14 @@ public class TestStressThreadBackup extends SolrCloudTestCase {* Validates a backup dir exists, passes check index, and contains a number of "real" documents* that match its name*/- private void validateBackup(final File backup) throws IOException {+ private void validateBackup(final Path backup) throws IOException {log.info("Checking Validity of {}", backup);- assertTrue(backup.toString() + ": isDir?", backup.isDirectory());- final Matcher m = ENDS_WITH_INT_DIGITS.matcher(backup.getName());+ assertTrue(backup.toString() + ": isDir?", Files.isDirectory(backup));+ final Matcher m = ENDS_WITH_INT_DIGITS.matcher(backup.getFileName().toString());assertTrue("Backup dir name does not end with int digits: " + backup, m.find());final int numRealDocsExpected = Integer.parseInt(m.group());- try (Directory dir = FSDirectory.open(backup.toPath())) {+ try (Directory dir = FSDirectory.open(backup)) {TestUtil.checkIndex(dir, true, true, true, null);try (DirectoryReader r = DirectoryReader.open(dir)) {assertEquals(@@ -402,7 +404,7 @@ public class TestStressThreadBackup extends SolrCloudTestCase {CoreAdminParams.NAME,backupName,CoreAdminParams.BACKUP_LOCATION,- backupDir.getAbsolutePath(),+ backupDir.toString(),CoreAdminParams.BACKUP_INCREMENTAL,"false");if (null != snapName) {diff --git a/solr/core/src/test/org/apache/solr/handler/TestUserManagedReplicationWithAuth.java b/solr/core/src/test/org/apache/solr/handler/TestUserManagedReplicationWithAuth.javaindex 98a5684791d..b8fac832514 100644--- a/solr/core/src/test/org/apache/solr/handler/TestUserManagedReplicationWithAuth.java+++ b/solr/core/src/test/org/apache/solr/handler/TestUserManagedReplicationWithAuth.java@@ -76,9 +76,7 @@ public class TestUserManagedReplicationWithAuth extends SolrTestCaseJ4 {super.setUp();systemSetPropertySolrDisableUrlAllowList("true");// leader with Basic auth enabled via security.json- leader =- new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "leader", null);+ leader = new ReplicationTestHelper.SolrInstance(createTempDir("solr-instance"), "leader", null);leader.setUp();// Configuring basic auth for LeaderPath solrLeaderHome = Path.of(leader.getHomeDir());@@ -92,7 +90,7 @@ public class TestUserManagedReplicationWithAuth extends SolrTestCaseJ4 {// follower with no basic auth credentials for leader configured.follower =new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "follower", leaderJetty.getLocalPort());+ createTempDir("solr-instance"), "follower", leaderJetty.getLocalPort());follower.setUp();followerJetty = createAndStartJetty(follower);followerClient =@@ -102,7 +100,7 @@ public class TestUserManagedReplicationWithAuth extends SolrTestCaseJ4 {// follower with basic auth credentials for leader configured in solrconfig.xml.followerWithAuth =new ReplicationTestHelper.SolrInstance(- createTempDir("solr-instance").toFile(), "follower-auth", leaderJetty.getLocalPort());+ createTempDir("solr-instance"), "follower-auth", leaderJetty.getLocalPort());followerWithAuth.setUp();followerJettyWithAuth = createAndStartJetty(followerWithAuth);followerClientWithAuth =diff --git a/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java b/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.javaindex b3fb16312c6..43163e10218 100644--- a/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java+++ b/solr/core/src/test/org/apache/solr/handler/V2StandaloneTest.java@@ -32,13 +32,13 @@ public class V2StandaloneTest extends SolrTestCaseJ4 {@Testpublic void testWelcomeMessage() throws Exception {- Path solrHomeTmp = createTempDir().toAbsolutePath();+ Path solrHomeTmp = createTempDir();PathUtils.copyDirectory(- Path.of(TEST_HOME(), "configsets/minimal/conf"), solrHomeTmp.resolve("conf"));- Files.copy(Path.of(TEST_HOME(), "solr.xml"), solrHomeTmp.resolve("solr.xml"));+ TEST_HOME().resolve("configsets/minimal/conf"), solrHomeTmp.resolve("conf"));+ Files.copy(TEST_HOME().resolve("solr.xml"), solrHomeTmp.resolve("solr.xml"));JettySolrRunner jetty =- new JettySolrRunner(solrHomeTmp.toAbsolutePath().toString(), JettyConfig.builder().build());+ new JettySolrRunner(solrHomeTmp.toString(), JettyConfig.builder().build());jetty.start();try (SolrClient client = getHttpSolrClient(buildUrl(jetty.getLocalPort()))) {diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminCreateDiscoverTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminCreateDiscoverTest.javaindex ae50c308f90..3281b4eb36a 100644--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminCreateDiscoverTest.java+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminCreateDiscoverTest.java@@ -17,7 +17,6 @@package org.apache.solr.handler.admin;import com.fasterxml.jackson.core.type.TypeReference;-import java.io.File;import java.io.IOException;import java.io.Reader;import java.nio.charset.StandardCharsets;@@ -38,7 +37,7 @@ import org.junit.Test;public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {- private static File solrHomeDirectory = null;+ private static Path solrHomeDirectory = null;private static CoreAdminHandler admin = null;@@ -50,9 +49,9 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {public static void beforeClass() throws Exception {useFactory(null); // I require FS-based indexes for this test.- solrHomeDirectory = createTempDir().toFile();+ solrHomeDirectory = createTempDir();- setupNoCoreTest(solrHomeDirectory.toPath(), null);+ setupNoCoreTest(solrHomeDirectory, null);admin = new CoreAdminHandler(h.getCoreContainer());}@@ -64,7 +63,7 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {}private static void setupCore(String coreName) throws IOException {- Path instDir = solrHomeDirectory.toPath().resolve(coreName);+ Path instDir = solrHomeDirectory.resolve(coreName);Path subHome = instDir.resolve("conf");Files.createDirectories(subHome);@@ -85,12 +84,12 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {// create a new core (using CoreAdminHandler) w/ properties// Just to be sure it's NOT written to the core.properties file- File workDir = new File(solrHomeDirectory, coreSysProps);- System.setProperty("INSTDIR_TEST", workDir.getAbsolutePath());+ Path workDir = solrHomeDirectory.resolve(coreSysProps);+ System.setProperty("INSTDIR_TEST", workDir.toString());System.setProperty("CONFIG_TEST", "solrconfig_ren.xml");System.setProperty("SCHEMA_TEST", "schema_ren.xml");- File dataDir = new File(workDir.getAbsolutePath(), "data_diff");+ Path dataDir = workDir.resolve("data_diff");System.setProperty("DATA_TEST", "data_diff");SolrQueryResponse resp = new SolrQueryResponse();@@ -115,31 +114,28 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {Properties props = new Properties();Path propFile =- solrHomeDirectory- .toPath()- .resolve(coreSysProps)- .resolve(CorePropertiesLocator.PROPERTIES_FILENAME);+ solrHomeDirectory.resolve(coreSysProps).resolve(CorePropertiesLocator.PROPERTIES_FILENAME);try (Reader r = Files.newBufferedReader(propFile, StandardCharsets.UTF_8)) {props.load(r);}assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.NAME),coreSysProps);assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.CONFIG),"${CONFIG_TEST}");assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.SCHEMA),"${SCHEMA_TEST}");assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.DATA_DIR),"${DATA_TEST}");@@ -150,17 +146,15 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {// see SOLR-4982. Really, we should be able to just verify that the index files exist.// Should NOT be a datadir named ${DATA_TEST} (literal).- File badDir = new File(workDir, "${DATA_TEST}");- assertFalse(- "Should have substituted the sys var, found file " + badDir.getAbsolutePath(),- badDir.exists());+ Path badDir = workDir.resolve("${DATA_TEST}");+ assertFalse("Should have substituted the sys var, found file " + badDir, Files.exists(badDir));// For the other 3 vars, we couldn't get past creating the core if dereferencing didn't work// correctly.// Should have segments in the directory pointed to by the ${DATA_TEST}.- File test = new File(dataDir, "index");- assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists());+ Path test = dataDir.resolve("index");+ assertTrue("Should have found index dir at " + test, Files.exists(test));}@Test@@ -168,8 +162,8 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {setupCore(coreDuplicate);- File workDir = new File(solrHomeDirectory, coreDuplicate);- File data = new File(workDir, "data");+ Path workDir = solrHomeDirectory.resolve(coreDuplicate);+ Path data = workDir.resolve("data");// Create one coreSolrQueryResponse resp = new SolrQueryResponse();@@ -180,13 +174,13 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {CoreAdminParams.NAME,coreDuplicate,CoreAdminParams.INSTANCE_DIR,- workDir.getAbsolutePath(),+ workDir.toString(),CoreAdminParams.CONFIG,"solrconfig_ren.xml",CoreAdminParams.SCHEMA,"schema_ren.xml",CoreAdminParams.DATA_DIR,- data.getAbsolutePath()),+ data.toString()),resp);assertNull("Exception on create", resp.getException());@@ -202,13 +196,13 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {CoreAdminParams.NAME,"different_name_core",CoreAdminParams.INSTANCE_DIR,- workDir.getAbsolutePath(),+ workDir.toString(),CoreAdminParams.CONFIG,"solrconfig_ren.xml",CoreAdminParams.SCHEMA,"schema_ren.xml",CoreAdminParams.DATA_DIR,- data.getAbsolutePath()),+ data.toString()),new SolrQueryResponse());});assertTrue(e.getMessage().contains("already defined there"));@@ -220,8 +214,8 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {setupCore("testInstanceDirAsPropertyParam-XYZ");// make sure workDir is different even if core name is used as instanceDir- File workDir = new File(solrHomeDirectory, "testInstanceDirAsPropertyParam-XYZ");- File data = new File(workDir, "data");+ Path workDir = solrHomeDirectory.resolve("testInstanceDirAsPropertyParam-XYZ");+ Path data = workDir.resolve("data");// Create one coreSolrQueryResponse resp = new SolrQueryResponse();@@ -232,13 +226,13 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {CoreAdminParams.NAME,"testInstanceDirAsPropertyParam","property.instanceDir",- workDir.getAbsolutePath(),+ workDir.toString(),CoreAdminParams.CONFIG,"solrconfig_ren.xml",CoreAdminParams.SCHEMA,"schema_ren.xml",CoreAdminParams.DATA_DIR,- data.getAbsolutePath()),+ data.toString()),resp);assertNull("Exception on create", resp.getException());@@ -257,12 +251,12 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {assertNotNull(statusByCore);final var coreProps = statusByCore.get("testInstanceDirAsPropertyParam");assertNotNull(coreProps);- String instanceDir = coreProps.instanceDir;+ Path instanceDir = Path.of(coreProps.instanceDir);assertNotNull(instanceDir);assertEquals("Instance dir does not match param given in property.instanceDir syntax",- workDir.getAbsolutePath(),- new File(instanceDir).getAbsolutePath());+ workDir.toString(),+ instanceDir.toString());}@Test@@ -272,8 +266,8 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {// create a new core (using CoreAdminHandler) w/ properties// Just to be sure it's NOT written to the core.properties file- File workDir = new File(solrHomeDirectory, coreNormal);- File data = new File(workDir, "data");+ Path workDir = solrHomeDirectory.resolve(coreNormal);+ Path data = workDir.resolve("data");SolrQueryResponse resp = new SolrQueryResponse();admin.handleRequestBody(@@ -283,46 +277,43 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {CoreAdminParams.NAME,coreNormal,CoreAdminParams.INSTANCE_DIR,- workDir.getAbsolutePath(),+ workDir.toString(),CoreAdminParams.CONFIG,"solrconfig_ren.xml",CoreAdminParams.SCHEMA,"schema_ren.xml",CoreAdminParams.DATA_DIR,- data.getAbsolutePath()),+ data.toString()),resp);assertNull("Exception on create", resp.getException());// verify props are in persisted fileProperties props = new Properties();Path propFile =- solrHomeDirectory- .toPath()- .resolve(coreNormal)- .resolve(CorePropertiesLocator.PROPERTIES_FILENAME);+ solrHomeDirectory.resolve(coreNormal).resolve(CorePropertiesLocator.PROPERTIES_FILENAME);try (Reader r = Files.newBufferedReader(propFile, StandardCharsets.UTF_8)) {props.load(r);}assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.NAME),coreNormal);assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.CONFIG),"solrconfig_ren.xml");assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.SCHEMA),"schema_ren.xml");assertEquals(- "Unexpected value preserved in properties file " + propFile.toAbsolutePath(),+ "Unexpected value preserved in properties file " + propFile,props.getProperty(CoreAdminParams.DATA_DIR),- data.getAbsolutePath());+ data.toString());assertEquals(props.size(), 4);@@ -331,7 +322,7 @@ public class CoreAdminCreateDiscoverTest extends SolrTestCaseJ4 {// correctly.// Should have segments in the directory pointed to by the ${DATA_TEST}.- File test = new File(data, "index");- assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists());+ Path test = data.resolve("index");+ assertTrue("Should have found index dir at " + test, Files.exists(test));}}diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.javaindex 3e17d115a93..fa895e7a842 100644--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminHandlerTest.java@@ -300,11 +300,11 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {@Testpublic void testDeleteInstanceDir() throws Exception {Path solrHomeDirectory = createTempDir("solr-home");- copySolrHomeToTemp(solrHomeDirectory.toFile(), "corex");+ copySolrHomeToTemp(solrHomeDirectory, "corex");Path corex = solrHomeDirectory.resolve("corex");Files.writeString(corex.resolve("core.properties"), "", StandardCharsets.UTF_8);- copySolrHomeToTemp(solrHomeDirectory.toFile(), "corerename");+ copySolrHomeToTemp(solrHomeDirectory, "corerename");Path coreRename = solrHomeDirectory.resolve("corerename");Path renamePropFile = coreRename.resolve("core.properties");@@ -381,7 +381,7 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {@Testpublic void testUnloadForever() throws Exception {Path solrHomeDirectory = createTempDir("solr-home");- copySolrHomeToTemp(solrHomeDirectory.toFile(), "corex");+ copySolrHomeToTemp(solrHomeDirectory, "corex");Path corex = solrHomeDirectory.resolve("corex");Files.writeString(corex.resolve("core.properties"), "", StandardCharsets.UTF_8);JettySolrRunner runner =@@ -446,7 +446,7 @@ public class CoreAdminHandlerTest extends SolrTestCaseJ4 {"Ignore test on windows because it does not delete data directory immediately after unload",Constants.WINDOWS);Path solrHomeDirectory = createTempDir("solr-home");- copySolrHomeToTemp(solrHomeDirectory.toFile(), "corex");+ copySolrHomeToTemp(solrHomeDirectory, "corex");Path corex = solrHomeDirectory.resolve("corex");Files.writeString(corex.resolve("core.properties"), "", StandardCharsets.UTF_8);JettySolrRunner runner =diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminRequestStatusTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminRequestStatusTest.javaindex 59b7fac53d4..504b24eeb11 100644--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminRequestStatusTest.java+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreAdminRequestStatusTest.java@@ -16,10 +16,9 @@*/package org.apache.solr.handler.admin;-import java.io.File;import java.nio.file.Files;import java.nio.file.Path;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.params.CommonAdminParams;import org.apache.solr.common.params.CoreAdminParams;@@ -37,10 +36,10 @@ public class CoreAdminRequestStatusTest extends SolrTestCaseJ4 {@Testpublic void testCoreAdminRequestStatus() throws Exception {- final File workDir = createTempDir().toFile();+ final Path workDir = createTempDir();final CoreContainer cores = h.getCoreContainer();- cores.getAllowPaths().add(workDir.toPath()); // Allow core to be created in workDir+ cores.getAllowPaths().add(workDir); // Allow core to be created in workDirfinal CoreAdminHandler admin = new CoreAdminHandler(cores);@@ -52,8 +51,8 @@ public class CoreAdminRequestStatusTest extends SolrTestCaseJ4 {}assertTrue("instDir doesn't exist: " + instDir, Files.exists(instDir));- final File instPropFile = new File(workDir, "instProp");- FileUtils.copyDirectory(instDir.toFile(), instPropFile);+ final Path instPropFile = workDir.resolve("instProp");+ PathUtils.copyDirectory(instDir, instPropFile);// create a new core (using CoreAdminHandler) w/ properties@@ -63,7 +62,7 @@ public class CoreAdminRequestStatusTest extends SolrTestCaseJ4 {CoreAdminParams.ACTION,CoreAdminParams.CoreAdminAction.CREATE.toString(),CoreAdminParams.INSTANCE_DIR,- instPropFile.getAbsolutePath(),+ instPropFile.toString(),CoreAdminParams.NAME,"dummycore",CommonAdminParams.ASYNC,diff --git a/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java b/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.javaindex cbe7e7f46e6..698ca31b74a 100644--- a/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java+++ b/solr/core/src/test/org/apache/solr/handler/admin/CoreMergeIndexesAdminHandlerTest.java@@ -16,8 +16,8 @@*/package org.apache.solr.handler.admin;-import java.io.File;import java.io.IOException;+import java.nio.file.Path;import org.apache.lucene.store.Directory;import org.apache.lucene.store.LockFactory;import org.apache.solr.SolrTestCaseJ4;@@ -63,10 +63,10 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {@Testpublic void testMergeIndexesCoreAdminHandler() throws Exception {- final File workDir = createTempDir().toFile();+ final Path workDir = createTempDir();final CoreContainer cores = h.getCoreContainer();- cores.getAllowPaths().add(workDir.toPath());+ cores.getAllowPaths().add(workDir);try (final CoreAdminHandler admin = new CoreAdminHandler(cores);SolrCore core = cores.getCore("collection1")) {@@ -87,7 +87,7 @@ public class CoreMergeIndexesAdminHandlerTest extends SolrTestCaseJ4 {CoreAdminParams.CORE,"collection1",CoreAdminParams.INDEX_DIR,- workDir.getAbsolutePath()),+ workDir.toString()),new SolrQueryResponse());});assertEquals(diff --git a/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.javaindex bbbc5ad81e5..8ed448d5ebe 100644--- a/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/DistributedDebugComponentTest.java@@ -16,8 +16,8 @@*/package org.apache.solr.handler.component;-import java.io.File;import java.io.IOException;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;@@ -26,7 +26,7 @@ import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.SolrJettyTestBase;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrQuery;@@ -49,18 +49,18 @@ public class DistributedDebugComponentTest extends SolrJettyTestBase {private static String shard1;private static String shard2;- private static File createSolrHome() throws Exception {- File workDir = createTempDir().toFile();+ private static Path createSolrHome() throws Exception {+ Path workDir = createTempDir();setupJettyTestHome(workDir, "collection1");- FileUtils.copyDirectory(new File(workDir, "collection1"), new File(workDir, "collection2"));+ PathUtils.copyDirectory(workDir.resolve("collection1"), workDir.resolve("collection2"));return workDir;}@BeforeClasspublic static void createThings() throws Exception {systemSetPropertySolrDisableUrlAllowList("true");- File solrHome = createSolrHome();- createAndStartJetty(solrHome.getAbsolutePath());+ Path solrHome = createSolrHome();+ createAndStartJetty(solrHome);String url = getBaseUrl();collection1 = getHttpSolrClient(url, "collection1");diff --git a/solr/core/src/test/org/apache/solr/handler/component/FacetPivot2CollectionsTest.java b/solr/core/src/test/org/apache/solr/handler/component/FacetPivot2CollectionsTest.javaindex ed7d8c9c15d..814fd5308f6 100644--- a/solr/core/src/test/org/apache/solr/handler/component/FacetPivot2CollectionsTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/FacetPivot2CollectionsTest.java@@ -17,7 +17,6 @@package org.apache.solr.handler.component;import com.carrotsearch.randomizedtesting.generators.RandomStrings;-import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map;@@ -65,8 +64,8 @@ public class FacetPivot2CollectionsTest extends SolrCloudTestCase {public static void setupCluster() throws Exception {// create and configure clusterconfigureCluster(1)- .addConfig(COLL_A, configset("different-stopwords" + File.separator + COLL_A))- .addConfig(COLL_B, configset("different-stopwords" + File.separator + COLL_B))+ .addConfig(COLL_A, configset("different-stopwords/" + COLL_A))+ .addConfig(COLL_B, configset("different-stopwords/" + COLL_B)).configure();try {diff --git a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.javaindex bc28036665e..3300ab741c6 100644--- a/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/QueryElevationComponentTest.java@@ -21,7 +21,6 @@ import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_PARAM;import static org.apache.solr.common.params.CursorMarkParams.CURSOR_MARK_START;import static org.apache.solr.common.util.Utils.fromJSONString;-import java.io.File;import java.io.PrintWriter;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;@@ -1258,9 +1257,8 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {}// write an elevation config file to boost some docs- private void writeElevationConfigFile(File file, String query, String... ids) throws Exception {- try (PrintWriter out =- new PrintWriter(Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8))) {+ private void writeElevationConfigFile(Path file, String query, String... ids) throws Exception {+ try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8))) {out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");out.println("<elevate>");out.println("<query text=\"" + query + "\">");@@ -1273,7 +1271,7 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {}if (log.isInfoEnabled()) {- log.info("OUT: {}", file.getAbsolutePath());+ log.info("OUT: {}", file);}}@@ -1281,20 +1279,19 @@ public class QueryElevationComponentTest extends SolrTestCaseJ4 {public void testElevationReloading() throws Exception {// need a mutable solr home. Copying all collection1 is a lot but this is only one test.final Path solrHome = createTempDir();- copyMinConf(solrHome.resolve("collection1").toFile(), null, "solrconfig-elevate.xml");+ copyMinConf(solrHome.resolve("collection1"), null, "solrconfig-elevate.xml");- File configFile =- solrHome.resolve("collection1").resolve("conf").resolve("elevate.xml").toFile();+ Path configFile = solrHome.resolve("collection1").resolve("conf").resolve("elevate.xml");writeElevationConfigFile(configFile, "aaa", "A");- initCore("solrconfig.xml", "schema.xml", solrHome.toString());+ initCore("solrconfig.xml", "schema.xml", solrHome);try {QueryElevationComponent comp =(QueryElevationComponent) h.getCore().getSearchComponent("elevate");NamedList<String> args = new NamedList<>();- args.add(QueryElevationComponent.CONFIG_FILE, configFile.getName());+ args.add(QueryElevationComponent.CONFIG_FILE, configFile.getFileName().toString());comp.init(args);comp.inform(h.getCore());diff --git a/solr/core/src/test/org/apache/solr/handler/component/SpellCheckComponentTest.java b/solr/core/src/test/org/apache/solr/handler/component/SpellCheckComponentTest.javaindex 4a0eda8e506..ccb0651b78e 100644--- a/solr/core/src/test/org/apache/solr/handler/component/SpellCheckComponentTest.java+++ b/solr/core/src/test/org/apache/solr/handler/component/SpellCheckComponentTest.java@@ -16,7 +16,8 @@*/package org.apache.solr.handler.component;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.List;import org.apache.lucene.tests.util.LuceneTestCase.SuppressTempFileChecks;@@ -481,14 +482,14 @@ public class SpellCheckComponentTest extends SolrTestCaseJ4 {@Testpublic void testRelativeIndexDirLocation() {SolrCore core = h.getCore();- File indexDir = new File(core.getDataDir() + File.separator + "spellchecker1");- assertTrue(indexDir.exists());+ Path indexDir = Path.of(core.getDataDir(), "spellchecker1");+ assertTrue(Files.exists(indexDir));- indexDir = new File(core.getDataDir() + File.separator + "spellchecker2");- assertTrue(indexDir.exists());+ indexDir = Path.of(core.getDataDir(), "spellchecker2");+ assertTrue(Files.exists(indexDir));- indexDir = new File(core.getDataDir() + File.separator + "spellchecker3");- assertTrue(indexDir.exists());+ indexDir = Path.of(core.getDataDir(), "spellchecker3");+ assertTrue(Files.exists(indexDir));}@Testdiff --git a/solr/core/src/test/org/apache/solr/handler/designer/ManagedSchemaDiffTest.java b/solr/core/src/test/org/apache/solr/handler/designer/ManagedSchemaDiffTest.javaindex a53521bfec9..90897d7343e 100644--- a/solr/core/src/test/org/apache/solr/handler/designer/ManagedSchemaDiffTest.java+++ b/solr/core/src/test/org/apache/solr/handler/designer/ManagedSchemaDiffTest.java@@ -20,7 +20,6 @@ package org.apache.solr.handler.designer;import static org.apache.solr.handler.admin.ConfigSetsHandler.DEFAULT_CONFIGSET_NAME;import static org.apache.solr.handler.designer.ManagedSchemaDiff.mapFieldsToPropertyValues;-import java.io.File;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;@@ -41,7 +40,7 @@ public class ManagedSchemaDiffTest extends SolrCloudTestCase {public static void createCluster() throws Exception {System.setProperty("managed.schema.mutable", "true");configureCluster(1)- .addConfig(DEFAULT_CONFIGSET_NAME, new File(ExternalPaths.DEFAULT_CONFIGSET).toPath())+ .addConfig(DEFAULT_CONFIGSET_NAME, ExternalPaths.DEFAULT_CONFIGSET).configure();}diff --git a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerAPI.java b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerAPI.javaindex 83b589466fa..b18c78f523f 100644--- a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerAPI.java+++ b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerAPI.java@@ -24,7 +24,8 @@ import static org.apache.solr.response.RawResponseWriter.CONTENT;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Arrays;import java.util.Collection;import java.util.Collections;@@ -32,6 +33,7 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;+import java.util.stream.Stream;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.client.solrj.response.QueryResponse;@@ -68,7 +70,7 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDepublic static void createCluster() throws Exception {System.setProperty("managed.schema.mutable", "true");configureCluster(1)- .addConfig(DEFAULT_CONFIGSET_NAME, new File(ExternalPaths.DEFAULT_CONFIGSET).toPath())+ .addConfig(DEFAULT_CONFIGSET_NAME, ExternalPaths.DEFAULT_CONFIGSET).configure();// SchemaDesignerAPI depends on the blob store ".system" collection existing.CollectionAdminRequest.createCollection(BLOB_STORE_ID, 1, 1).process(cluster.getSolrClient());@@ -132,16 +134,23 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDe@Test@SuppressWarnings("unchecked")public void testAddTechproductsProgressively() throws Exception {- File docsDir = new File(ExternalPaths.SOURCE_HOME, "example/exampledocs");- assertTrue(docsDir.getAbsolutePath() + " not found!", docsDir.isDirectory());- File[] toAdd =- docsDir.listFiles(- (dir, name) ->- name.endsWith(".xml")- || name.endsWith(".json")- || name.endsWith(".csv")- || name.endsWith(".jsonl"));- assertNotNull("No test data files found in " + docsDir.getAbsolutePath(), toAdd);+ Path docsDir = ExternalPaths.SOURCE_HOME.resolve("example/exampledocs");+ assertTrue(docsDir + " not found!", Files.isDirectory(docsDir));+ List<Path> toAdd;+ try (Stream<Path> files = Files.list(docsDir)) {+ toAdd =+ files+ .filter(+ (dir) -> {+ String name = dir.getFileName().toString();+ return name.endsWith(".xml")+ || name.endsWith(".json")+ || name.endsWith(".csv")+ || name.endsWith(".jsonl");+ })+ .toList();+ assertNotNull("No test data files found in " + docsDir, toAdd);+ }String configSet = "techproducts";@@ -177,7 +186,7 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDerspData = rsp.getValues().toSolrParams();schemaVersion = rspData.getInt(SCHEMA_VERSION_PARAM);- for (File next : toAdd) {+ for (Path next : toAdd) {// Analyze some sample documents to refine the schemareqParams.clear();reqParams.set(CONFIG_SET_PARAM, configSet);@@ -188,8 +197,9 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDewhen(req.getParams()).thenReturn(reqParams);// POST some sample JSON docs- ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(next.toPath());- stream.setContentType(TestSampleDocumentsLoader.guessContentTypeFromFilename(next.getName()));+ ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(next);+ stream.setContentType(+ TestSampleDocumentsLoader.guessContentTypeFromFilename(next.getFileName().toString()));when(req.getContentStreams()).thenReturn(Collections.singletonList(stream));rsp = new SolrQueryResponse();@@ -288,10 +298,10 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDeModifiableSolrParams reqParams = new ModifiableSolrParams();- File filmsDir = new File(ExternalPaths.SOURCE_HOME, "example/films");- assertTrue(filmsDir.getAbsolutePath() + " not found!", filmsDir.isDirectory());- File filmsXml = new File(filmsDir, "films.xml");- assertTrue("example/films/films.xml not found", filmsXml.isFile());+ Path filmsDir = ExternalPaths.SOURCE_HOME.resolve("example/films");+ assertTrue(filmsDir + " not found!", Files.isDirectory(filmsDir));+ Path filmsXml = filmsDir.resolve("films.xml");+ assertTrue("example/films/films.xml not found", Files.isRegularFile(filmsXml));reqParams.set(CONFIG_SET_PARAM, configSet);reqParams.set(ENABLE_DYNAMIC_FIELDS_PARAM, "true");@@ -300,7 +310,7 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDewhen(req.getParams()).thenReturn(reqParams);// POST some sample XML docs- ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(filmsXml.toPath());+ ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(filmsXml);stream.setContentType("application/xml");when(req.getContentStreams()).thenReturn(Collections.singletonList(stream));@@ -353,8 +363,8 @@ public class TestSchemaDesignerAPI extends SolrCloudTestCase implements SchemaDewhen(req.getParams()).thenReturn(reqParams);// POST some sample JSON docs- File booksJson = new File(ExternalPaths.SOURCE_HOME, "example/exampledocs/books.json");- ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(booksJson.toPath());+ Path booksJson = ExternalPaths.SOURCE_HOME.resolve("example/exampledocs/books.json");+ ContentStreamBase.FileStream stream = new ContentStreamBase.FileStream(booksJson);stream.setContentType(JSON_MIME);when(req.getContentStreams()).thenReturn(Collections.singletonList(stream));diff --git a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerConfigSetHelper.java b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerConfigSetHelper.javaindex f1eea1de702..9961afa6d07 100644--- a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerConfigSetHelper.java+++ b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerConfigSetHelper.java@@ -24,7 +24,6 @@ import static org.apache.solr.schema.IndexSchema.NEST_PATH_FIELD_NAME;import static org.apache.solr.schema.IndexSchema.ROOT_FIELD_NAME;import java.io.ByteArrayInputStream;-import java.io.File;import java.io.IOException;import java.util.Arrays;import java.util.Collections;@@ -58,7 +57,7 @@ public class TestSchemaDesignerConfigSetHelper extends SolrCloudTestCasepublic static void createCluster() throws Exception {System.setProperty("managed.schema.mutable", "true");configureCluster(1)- .addConfig(DEFAULT_CONFIGSET_NAME, new File(ExternalPaths.DEFAULT_CONFIGSET).toPath())+ .addConfig(DEFAULT_CONFIGSET_NAME, ExternalPaths.DEFAULT_CONFIGSET).configure();// SchemaDesignerConfigSetHelper depends on the blob storeCollectionAdminRequest.createCollection(BLOB_STORE_ID, 1, 1).process(cluster.getSolrClient());diff --git a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerSettingsDAO.java b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerSettingsDAO.javaindex 85a1232af23..e0cc7eea106 100644--- a/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerSettingsDAO.java+++ b/solr/core/src/test/org/apache/solr/handler/designer/TestSchemaDesignerSettingsDAO.java@@ -19,7 +19,6 @@ package org.apache.solr.handler.designer;import static org.apache.solr.handler.admin.ConfigSetsHandler.DEFAULT_CONFIGSET_NAME;-import java.io.File;import java.util.Collections;import java.util.Map;import org.apache.solr.client.solrj.SolrResponse;@@ -42,7 +41,7 @@ public class TestSchemaDesignerSettingsDAO extends SolrCloudTestCasepublic static void createCluster() throws Exception {System.setProperty("managed.schema.mutable", "true");configureCluster(1)- .addConfig(DEFAULT_CONFIGSET_NAME, new File(ExternalPaths.DEFAULT_CONFIGSET).toPath())+ .addConfig(DEFAULT_CONFIGSET_NAME, ExternalPaths.DEFAULT_CONFIGSET).configure();}diff --git a/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java b/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.javaindex 39dba55365c..9da5cfcaf7c 100644--- a/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java+++ b/solr/core/src/test/org/apache/solr/metrics/SolrMetricsIntegrationTest.java@@ -91,7 +91,7 @@ public class SolrMetricsIntegrationTest extends SolrTestCaseJ4 {cfg,new TestHarness.TestCoresLocator(DEFAULT_TEST_CORENAME,- initAndGetDataDir().getAbsolutePath(),+ initAndGetDataDir().toString(),"solrconfig.xml","schema.xml"));diff --git a/solr/core/src/test/org/apache/solr/metrics/reporters/SolrGraphiteReporterTest.java b/solr/core/src/test/org/apache/solr/metrics/reporters/SolrGraphiteReporterTest.javaindex 24984623f1e..da26b845ef0 100644--- a/solr/core/src/test/org/apache/solr/metrics/reporters/SolrGraphiteReporterTest.java+++ b/solr/core/src/test/org/apache/solr/metrics/reporters/SolrGraphiteReporterTest.java@@ -24,7 +24,6 @@ import java.net.Socket;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.ArrayList;import java.util.List;import java.util.Map;@@ -44,7 +43,7 @@ public class SolrGraphiteReporterTest extends SolrTestCaseJ4 {@Testpublic void testReporter() throws Exception {int jmxReporter = JmxUtil.findFirstMBeanServer() != null ? 1 : 0;- Path home = Paths.get(TEST_HOME());+ Path home = TEST_HOME();// define these properties, they are used in solrconfig.xmlSystem.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");@@ -63,7 +62,7 @@ public class SolrGraphiteReporterTest extends SolrTestCaseJ4 {cfg,new TestHarness.TestCoresLocator(DEFAULT_TEST_CORENAME,- initAndGetDataDir().getAbsolutePath(),+ initAndGetDataDir().toString(),"solrconfig.xml","schema.xml"));diff --git a/solr/core/src/test/org/apache/solr/metrics/reporters/SolrSlf4jReporterTest.java b/solr/core/src/test/org/apache/solr/metrics/reporters/SolrSlf4jReporterTest.javaindex aac67dbc34a..ed554448f99 100644--- a/solr/core/src/test/org/apache/solr/metrics/reporters/SolrSlf4jReporterTest.java+++ b/solr/core/src/test/org/apache/solr/metrics/reporters/SolrSlf4jReporterTest.java@@ -21,7 +21,6 @@ import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.Map;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrDocumentList;@@ -44,7 +43,7 @@ public class SolrSlf4jReporterTest extends SolrTestCaseJ4 {@Testpublic void testReporter() throws Exception {ensureLoggingConfiguredAppropriately();- Path home = Paths.get(TEST_HOME());+ Path home = TEST_HOME();// define these properties, they are used in solrconfig.xmlSystem.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");@@ -57,7 +56,7 @@ public class SolrSlf4jReporterTest extends SolrTestCaseJ4 {cfg,new TestHarness.TestCoresLocator(DEFAULT_TEST_CORENAME,- initAndGetDataDir().getAbsolutePath(),+ initAndGetDataDir().toString(),"solrconfig.xml","schema.xml"));diff --git a/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java b/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.javaindex 8fb2da411d9..c1350ae970b 100644--- a/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java+++ b/solr/core/src/test/org/apache/solr/request/TestRemoteStreaming.java@@ -16,7 +16,6 @@*/package org.apache.solr.request;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;@@ -24,6 +23,7 @@ import java.io.StringWriter;import java.net.URI;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;+import java.nio.file.Path;import org.apache.lucene.tests.util.LuceneTestCase;import org.apache.solr.SolrJettyTestBase;import org.apache.solr.SolrTestCaseJ4.SuppressSSL;@@ -47,9 +47,9 @@ public class TestRemoteStreaming extends SolrJettyTestBase {System.setProperty("solr.enableRemoteStreaming", "true");System.setProperty("solr.enableStreamBody", "true");// this one has handleSelect=true which a test here needs- File solrHomeDirectory = createTempDir(LuceneTestCase.getTestClass().getSimpleName()).toFile();+ Path solrHomeDirectory = createTempDir(LuceneTestCase.getTestClass().getSimpleName());setupJettyTestHome(solrHomeDirectory, "collection1");- createAndStartJetty(solrHomeDirectory.getAbsolutePath());+ createAndStartJetty(solrHomeDirectory.toAbsolutePath());}@Beforediff --git a/solr/core/src/test/org/apache/solr/request/TestStreamBody.java b/solr/core/src/test/org/apache/solr/request/TestStreamBody.javaindex 197fd2d5986..4fb530d2594 100644--- a/solr/core/src/test/org/apache/solr/request/TestStreamBody.java+++ b/solr/core/src/test/org/apache/solr/request/TestStreamBody.java@@ -16,11 +16,11 @@*/package org.apache.solr.request;-import java.io.File;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.SortedMap;import java.util.TreeMap;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.request.QueryRequest;import org.apache.solr.common.SolrException;@@ -38,8 +38,8 @@ public class TestStreamBody extends RestTestBase {private static final String collection = "collection1";public void startSolr() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();@@ -47,12 +47,7 @@ public class TestStreamBody extends RestTestBase {System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),- "solrconfig-minimal.xml",- "schema-rest.xml",- "/solr",- true,- extraServlets);+ tmpSolrHome, "solrconfig-minimal.xml", "schema-rest.xml", "/solr", true, extraServlets);if (random().nextBoolean()) {log.info("These tests are run with V2 API");restTestHarness.setServerProvider(diff --git a/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java b/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.javaindex 7f15a6ae894..a4d38ccf68d 100644--- a/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java+++ b/solr/core/src/test/org/apache/solr/response/TestPrometheusResponseWriter.java@@ -54,7 +54,10 @@ public class TestPrometheusResponseWriter extends SolrTestCaseJ4 {SharedMetricRegistries.clear();solrClientTestRule.startSolr(LuceneTestCase.createTempDir());- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.DEFAULT_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.DEFAULT_CONFIGSET.toString())+ .create();var cc = solrClientTestRule.getCoreContainer();cc.waitForLoadingCoresToFinish(30000);diff --git a/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java b/solr/core/src/test/org/apache/solr/response/TestRawTransformer.javaindex 43947cd49b2..cf492623407 100644--- a/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java+++ b/solr/core/src/test/org/apache/solr/response/TestRawTransformer.java@@ -19,7 +19,6 @@ package org.apache.solr.response;import java.lang.invoke.MethodHandles;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.LinkedHashMap;import java.util.Map;import java.util.Properties;@@ -80,7 +79,7 @@ public class TestRawTransformer extends SolrCloudTestCase {final Path collDir = homeDir.resolve("collection1");final Path confDir = collDir.resolve("conf");Files.createDirectories(confDir);- Files.copy(Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"), homeDir.resolve("solr.xml"));+ Files.copy(SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"), homeDir.resolve("solr.xml"));String src_dir = TEST_HOME() + "/collection1/conf";Files.copy(Path.of(src_dir, "schema_latest.xml"), confDir.resolve("schema.xml"));Files.copy(Path.of(src_dir, "solrconfig-minimal.xml"), confDir.resolve("solrconfig.xml"));@@ -105,7 +104,7 @@ public class TestRawTransformer extends SolrCloudTestCase {private static void initCloud() throws Exception {final String configName = DEBUG_LABEL + "_config-set";- final Path configDir = Paths.get(TEST_HOME(), "collection1", "conf");+ final Path configDir = TEST_HOME().resolve("collection1").resolve("conf");final int numNodes = 3;MiniSolrCloudCluster cloud =diff --git a/solr/core/src/test/org/apache/solr/rest/SolrRestletTestBase.java b/solr/core/src/test/org/apache/solr/rest/SolrRestletTestBase.javaindex 59d2a35d88c..90fc33ab952 100644--- a/solr/core/src/test/org/apache/solr/rest/SolrRestletTestBase.java+++ b/solr/core/src/test/org/apache/solr/rest/SolrRestletTestBase.java@@ -44,7 +44,7 @@ public abstract class SolrRestletTestBase extends RestTestBase {Path coresDir = tempDir.resolve("cores");System.setProperty("coreRootDirectory", coresDir.toString());- System.setProperty("configSetBaseDir", TEST_HOME());+ System.setProperty("configSetBaseDir", TEST_HOME().toString());System.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");diff --git a/solr/core/src/test/org/apache/solr/rest/TestManagedFileStorage.java b/solr/core/src/test/org/apache/solr/rest/TestManagedFileStorage.javaindex 8c0fce60c3c..0386c87497c 100644--- a/solr/core/src/test/org/apache/solr/rest/TestManagedFileStorage.java+++ b/solr/core/src/test/org/apache/solr/rest/TestManagedFileStorage.java@@ -16,7 +16,7 @@*/package org.apache.solr.rest;-import java.io.File;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;@@ -35,10 +35,10 @@ public class TestManagedFileStorage extends SolrTestCaseJ4 {/** Runs persisted managed resource creation and update tests on JSON storage. */@Testpublic void testFileBasedJsonStorage() throws Exception {- File instanceDir = createTempDir("json-storage").toFile();- try (SolrResourceLoader loader = new SolrResourceLoader(instanceDir.toPath())) {+ Path instanceDir = createTempDir("json-storage");+ try (SolrResourceLoader loader = new SolrResourceLoader(instanceDir)) {NamedList<String> initArgs = new NamedList<>();- String managedDir = instanceDir.getAbsolutePath() + File.separator + "managed";+ String managedDir = instanceDir.resolve("managed").toString();initArgs.add(ManagedResourceStorage.STORAGE_DIR_INIT_ARG, managedDir);FileStorageIO fileStorageIO = new FileStorageIO();fileStorageIO.configure(loader, initArgs);diff --git a/solr/core/src/test/org/apache/solr/rest/TestRestManager.java b/solr/core/src/test/org/apache/solr/rest/TestRestManager.javaindex b8ef9b0de84..bda498b62e6 100644--- a/solr/core/src/test/org/apache/solr/rest/TestRestManager.java+++ b/solr/core/src/test/org/apache/solr/rest/TestRestManager.java@@ -16,8 +16,9 @@*/package org.apache.solr.rest;-import java.io.File;import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays;import org.apache.solr.common.util.NamedList;@@ -123,16 +124,13 @@ public class TestRestManager extends SolrRestletTestBase {@Testpublic void testReloadFromPersistentStorage() throws IOException {SolrResourceLoader loader = new SolrResourceLoader(Paths.get("./"));- File unitTestStorageDir = createTempDir("testRestManager").toFile();- assertTrue(- unitTestStorageDir.getAbsolutePath() + " is not a directory!",- unitTestStorageDir.isDirectory());- assertTrue(unitTestStorageDir.canRead());- assertTrue(unitTestStorageDir.canWrite());+ Path unitTestStorageDir = createTempDir("testRestManager");+ assertTrue(unitTestStorageDir + " is not a directory!", Files.isDirectory(unitTestStorageDir));+ assertTrue(Files.isReadable(unitTestStorageDir));+ assertTrue(Files.isWritable(unitTestStorageDir));NamedList<String> ioInitArgs = new NamedList<>();- ioInitArgs.add(- ManagedResourceStorage.STORAGE_DIR_INIT_ARG, unitTestStorageDir.getAbsolutePath());+ ioInitArgs.add(ManagedResourceStorage.STORAGE_DIR_INIT_ARG, unitTestStorageDir.toString());StorageIO storageIO = new ManagedResourceStorage.FileStorageIO();storageIO.configure(loader, ioInitArgs);diff --git a/solr/core/src/test/org/apache/solr/rest/schema/TestBulkSchemaAPI.java b/solr/core/src/test/org/apache/solr/rest/schema/TestBulkSchemaAPI.javaindex 81b252e57d3..57f69a34ec5 100644--- a/solr/core/src/test/org/apache/solr/rest/schema/TestBulkSchemaAPI.java+++ b/solr/core/src/test/org/apache/solr/rest/schema/TestBulkSchemaAPI.java@@ -19,8 +19,8 @@ package org.apache.solr.rest.schema;import static org.apache.solr.common.util.Utils.fromJSONString;import static org.hamcrest.Matchers.containsString;-import java.io.File;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;@@ -29,7 +29,7 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.function.Consumer;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.lucene.misc.SweetSpotSimilarity;import org.apache.lucene.search.similarities.BM25Similarity;import org.apache.lucene.search.similarities.DFISimilarity;@@ -58,19 +58,14 @@ public class TestBulkSchemaAPI extends RestTestBase {@Beforepublic void before() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),- "solrconfig-managed-schema.xml",- "schema-rest.xml",- "/solr",- true,- null);+ tmpSolrHome, "solrconfig-managed-schema.xml", "schema-rest.xml", "/solr", true, null);if (random().nextBoolean()) {log.info("These tests are run with V2 API");restTestHarness.setServerProvider(diff --git a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedStopFilterFactory.java b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedStopFilterFactory.javaindex d3aa476693c..676736db094 100644--- a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedStopFilterFactory.java+++ b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedStopFilterFactory.java@@ -16,11 +16,11 @@*/package org.apache.solr.rest.schema.analysis;-import java.io.File;+import java.nio.file.Path;import java.util.Arrays;import java.util.SortedMap;import java.util.TreeMap;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.common.util.Utils;import org.apache.solr.util.RestTestBase;import org.eclipse.jetty.servlet.ServletHolder;@@ -42,8 +42,8 @@ public class TestManagedStopFilterFactory extends RestTestBase {@Beforepublic void before() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();@@ -51,7 +51,7 @@ public class TestManagedStopFilterFactory extends RestTestBase {System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),+ tmpSolrHome,"solrconfig-managed-schema.xml","schema-rest.xml","/solr",diff --git a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymFilterFactory.java b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymFilterFactory.javaindex 4738196017c..9767d8173e0 100644--- a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymFilterFactory.java+++ b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymFilterFactory.java@@ -42,14 +42,14 @@ public class TestManagedSynonymFilterFactory extends RestTestBase {@Beforepublic void before() throws Exception {tmpSolrHome = createTempDir();- PathUtils.copyDirectory(TEST_PATH(), tmpSolrHome.toAbsolutePath());+ PathUtils.copyDirectory(TEST_PATH(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.toAbsolutePath().toString(),+ tmpSolrHome,"solrconfig-managed-schema.xml","schema-rest.xml","/solr",diff --git a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymGraphFilterFactory.java b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymGraphFilterFactory.javaindex f27bdbc0d5d..9bcb3745359 100644--- a/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymGraphFilterFactory.java+++ b/solr/core/src/test/org/apache/solr/rest/schema/analysis/TestManagedSynonymGraphFilterFactory.java@@ -19,8 +19,8 @@ package org.apache.solr.rest.schema.analysis;import static org.apache.solr.common.util.Utils.toJSONString;-import java.io.File;import java.net.URLEncoder;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;@@ -28,7 +28,6 @@ import java.util.List;import java.util.Map;import java.util.SortedMap;import java.util.TreeMap;-import org.apache.commons.io.FileUtils;import org.apache.commons.io.file.PathUtils;import org.apache.solr.util.RestTestBase;import org.eclipse.jetty.servlet.ServletHolder;@@ -40,20 +39,20 @@ import org.junit.Test;// machines occasionallypublic class TestManagedSynonymGraphFilterFactory extends RestTestBase {- private static File tmpSolrHome;+ private static Path tmpSolrHome;/** Setup to make the schema mutable */@Beforepublic void before() throws Exception {- tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),+ tmpSolrHome,"solrconfig-managed-schema.xml","schema-rest.xml","/solr",@@ -65,7 +64,7 @@ public class TestManagedSynonymGraphFilterFactory extends RestTestBase {public void after() throws Exception {solrClientTestRule.reset();if (null != tmpSolrHome) {- PathUtils.deleteDirectory(tmpSolrHome.toPath());+ PathUtils.deleteDirectory(tmpSolrHome);}System.clearProperty("managed.schema.mutable");System.clearProperty("enable.update.log");diff --git a/solr/core/src/test/org/apache/solr/schema/ChangedSchemaMergeTest.java b/solr/core/src/test/org/apache/solr/schema/ChangedSchemaMergeTest.javaindex cd74da819a6..9e43e0c8a6e 100644--- a/solr/core/src/test/org/apache/solr/schema/ChangedSchemaMergeTest.java+++ b/solr/core/src/test/org/apache/solr/schema/ChangedSchemaMergeTest.java@@ -84,7 +84,7 @@ public class ChangedSchemaMergeTest extends SolrTestCaseJ4 {private CoreContainer init() throws Exception {Path changed = solrHomeDirectory.resolve("changed");- copyMinConf(changed.toFile(), "name=changed");+ copyMinConf(changed, "name=changed");// Overlay with my local schemaschemaFile = changed.resolve("conf").resolve("schema.xml");Files.writeString(schemaFile, withWhich, StandardCharsets.UTF_8);diff --git a/solr/core/src/test/org/apache/solr/schema/DateFieldTest.java b/solr/core/src/test/org/apache/solr/schema/DateFieldTest.javaindex b908fa1ecd7..3db98117565 100644--- a/solr/core/src/test/org/apache/solr/schema/DateFieldTest.java+++ b/solr/core/src/test/org/apache/solr/schema/DateFieldTest.java@@ -16,8 +16,7 @@*/package org.apache.solr.schema;-import java.io.File;-import java.nio.file.Paths;+import java.nio.file.Path;import java.util.Collections;import java.util.Date;import org.apache.lucene.index.IndexableField;@@ -26,8 +25,8 @@ import org.apache.solr.common.util.ByteArrayUtf8CharSequence;import org.apache.solr.core.SolrConfig;public class DateFieldTest extends SolrTestCaseJ4 {- private final String testInstanceDir = TEST_HOME() + File.separator + "collection1";- private final String testConfHome = testInstanceDir + File.separator + "conf" + File.separator;+ private final Path testInstanceDir = TEST_HOME().resolve("collection1");+ private final Path testConfHome = testInstanceDir.resolve("conf");private FieldType f = null;@Override@@ -36,8 +35,10 @@ public class DateFieldTest extends SolrTestCaseJ4 {// set some system properties for use by testsSystem.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");- SolrConfig config = new SolrConfig(Paths.get(testInstanceDir), testConfHome + "solrconfig.xml");- IndexSchema schema = IndexSchemaFactory.buildIndexSchema(testConfHome + "schema.xml", config);+ SolrConfig config =+ new SolrConfig(testInstanceDir, testConfHome.resolve("solrconfig.xml").toString());+ IndexSchema schema =+ IndexSchemaFactory.buildIndexSchema(testConfHome.resolve("schema.xml").toString(), config);f = Boolean.getBoolean(NUMERIC_POINTS_SYSPROP) ? new DatePointField() : new TrieDateField();f.init(schema, Collections.<String, String>emptyMap());}diff --git a/solr/core/src/test/org/apache/solr/schema/PrimitiveFieldTypeTest.java b/solr/core/src/test/org/apache/solr/schema/PrimitiveFieldTypeTest.javaindex 810a695d0ca..c0097e79190 100644--- a/solr/core/src/test/org/apache/solr/schema/PrimitiveFieldTypeTest.java+++ b/solr/core/src/test/org/apache/solr/schema/PrimitiveFieldTypeTest.java@@ -16,7 +16,7 @@*/package org.apache.solr.schema;-import java.io.File;+import java.nio.file.Path;import java.util.Arrays;import java.util.HashMap;import java.util.List;@@ -27,8 +27,7 @@ import org.junit.Test;/** Tests that defaults are set for Primitive (non-analyzed) fields */public class PrimitiveFieldTypeTest extends SolrTestCaseJ4 {- private final String testConfHome =- TEST_HOME() + File.separator + "collection1" + File.separator + "conf" + File.separator;+ private final Path testConfHome = TEST_HOME().resolve("collection1").resolve("conf");protected SolrConfig config;protected IndexSchema schema;protected HashMap<String, String> initMap;@@ -42,7 +41,9 @@ public class PrimitiveFieldTypeTest extends SolrTestCaseJ4 {System.setProperty("solr.test.sys.prop2", "proptwo");initMap = new HashMap<>();- config = new SolrConfig(TEST_PATH().resolve("collection1"), testConfHome + "solrconfig.xml");+ config =+ new SolrConfig(+ TEST_PATH().resolve("collection1"), testConfHome.resolve("solrconfig.xml").toString());}@Override@@ -68,7 +69,9 @@ public class PrimitiveFieldTypeTest extends SolrTestCaseJ4 {// ***********************// With schema version 1.4:// ***********************- schema = IndexSchemaFactory.buildIndexSchema(testConfHome + "schema12.xml", config);+ schema =+ IndexSchemaFactory.buildIndexSchema(+ testConfHome.resolve("schema12.xml").toString(), config);for (Class<? extends FieldType> clazz : types) {FieldType ft = clazz.getConstructor().newInstance();@@ -79,7 +82,9 @@ public class PrimitiveFieldTypeTest extends SolrTestCaseJ4 {// ***********************// With schema version 1.5// ***********************- schema = IndexSchemaFactory.buildIndexSchema(testConfHome + "schema15.xml", config);+ schema =+ IndexSchemaFactory.buildIndexSchema(+ testConfHome.resolve("schema15.xml").toString(), config);for (Class<? extends FieldType> clazz : types) {FieldType ft = clazz.getConstructor().newInstance();@@ -92,7 +97,9 @@ public class PrimitiveFieldTypeTest extends SolrTestCaseJ4 {}public void testDateField() {- schema = IndexSchemaFactory.buildIndexSchema(testConfHome + "schema15.xml", config);+ schema =+ IndexSchemaFactory.buildIndexSchema(+ testConfHome.resolve("schema15.xml").toString(), config);final TrieDateField tdt = new TrieDateField();{diff --git a/solr/core/src/test/org/apache/solr/schema/SpatialRPTFieldTypeTest.java b/solr/core/src/test/org/apache/solr/schema/SpatialRPTFieldTypeTest.javaindex c76a2afdbe1..6de03f515eb 100644--- a/solr/core/src/test/org/apache/solr/schema/SpatialRPTFieldTypeTest.java+++ b/solr/core/src/test/org/apache/solr/schema/SpatialRPTFieldTypeTest.java@@ -16,11 +16,12 @@*/package org.apache.solr.schema;-import java.io.File;import java.nio.file.Files;+import java.nio.file.Path;import java.util.HashMap;import java.util.Map;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.common.SolrException;import org.apache.solr.core.AbstractBadConfigTestBase;import org.junit.After;@@ -29,35 +30,36 @@ import org.locationtech.spatial4j.shape.Shape;public class SpatialRPTFieldTypeTest extends AbstractBadConfigTestBase {- private static File tmpSolrHome;- private static File tmpConfDir;+ private static Path tmpSolrHome;+ private static Path tmpConfDir;private static final String collection = "collection1";private static final String confDir = collection + "/conf";@Beforepublic void initManagedSchemaCore() throws Exception {- tmpSolrHome = createTempDir().toFile();- tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-basic.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-one-field-no-dynamic-field.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-one-field-no-dynamic-field-unique-key.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-minimal.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema_codec.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-bm25.xml"), tmpConfDir);+ tmpSolrHome = createTempDir();+ tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig-managed-schema.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("solrconfig-basic.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-one-field-no-dynamic-field.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-one-field-no-dynamic-field-unique-key.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema-minimal.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema_codec.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema-bm25.xml"), tmpConfDir);// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />System.setProperty("managed.schema.mutable", "false");System.setProperty("enable.update.log", "false");- initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome);}@After@@ -142,14 +144,11 @@ public class SpatialRPTFieldTypeTest extends AbstractBadConfigTestBase {public void testMaxDistErrConversion() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);String fieldName = "new_text_field";assertNull(@@ -263,14 +262,11 @@ public class SpatialRPTFieldTypeTest extends AbstractBadConfigTestBase {private void setupRPTField(String distanceUnits, String format, FieldType fieldType)throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);String fieldName = "new_text_field";assertNull(diff --git a/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java b/solr/core/src/test/org/apache/solr/schema/TestBinaryField.javaindex 93595656017..e7fe3013bc4 100644--- a/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java+++ b/solr/core/src/test/org/apache/solr/schema/TestBinaryField.java@@ -52,7 +52,7 @@ public class TestBinaryField extends SolrJettyTestBase {Files.createDirectories(dataDir);Files.createDirectories(confDir);- Files.copy(Path.of(SolrTestCaseJ4.TEST_HOME(), "solr.xml"), homeDir.resolve("solr.xml"));+ Files.copy(SolrTestCaseJ4.TEST_HOME().resolve("solr.xml"), homeDir.resolve("solr.xml"));String src_dir = TEST_HOME() + "/collection1/conf";Files.copy(Path.of(src_dir, "schema-binaryfield.xml"), confDir.resolve("schema.xml"));@@ -69,7 +69,7 @@ public class TestBinaryField extends SolrJettyTestBase {coreProps.store(w, "");}- createAndStartJetty(homeDir.toAbsolutePath().toString());+ createAndStartJetty(homeDir);}public void testSimple() throws Exception {diff --git a/solr/core/src/test/org/apache/solr/schema/TestCollationField.java b/solr/core/src/test/org/apache/solr/schema/TestCollationField.javaindex 437c397ea59..9dea69e4608 100644--- a/solr/core/src/test/org/apache/solr/schema/TestCollationField.java+++ b/solr/core/src/test/org/apache/solr/schema/TestCollationField.java@@ -31,7 +31,7 @@ public class TestCollationField extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {String home = setupSolrHome();- initCore("solrconfig.xml", "schema.xml", home);+ initCore("solrconfig.xml", "schema.xml", Path.of(home));// add some docsassertU(adoc("id", "1", "text", "\u0633\u0627\u0628"));assertU(adoc("id", "2", "text", "I WİLL USE TURKİSH CASING"));diff --git a/solr/core/src/test/org/apache/solr/schema/TestCollationFieldDocValues.java b/solr/core/src/test/org/apache/solr/schema/TestCollationFieldDocValues.javaindex 1443d2f1f90..b6cbfa51809 100644--- a/solr/core/src/test/org/apache/solr/schema/TestCollationFieldDocValues.java+++ b/solr/core/src/test/org/apache/solr/schema/TestCollationFieldDocValues.java@@ -31,7 +31,7 @@ public class TestCollationFieldDocValues extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {String home = setupSolrHome();- initCore("solrconfig.xml", "schema.xml", home);+ initCore("solrconfig.xml", "schema.xml", Path.of(home));// add some docsassertU(adoc("id", "1", "text", "\u0633\u0627\u0628"));assertU(adoc("id", "2", "text", "I WİLL USE TURKİSH CASING"));diff --git a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.javaindex 7efbdf09aa9..9d16da317e7 100644--- a/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java+++ b/solr/core/src/test/org/apache/solr/schema/TestManagedSchema.java@@ -17,16 +17,18 @@package org.apache.solr.schema;import com.fasterxml.jackson.core.type.TypeReference;-import java.io.File;import java.io.InputStream;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.regex.Pattern;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.client.api.model.CoreStatusResponse;import org.apache.solr.client.solrj.JacksonContentWriter;import org.apache.solr.common.SolrException;@@ -46,37 +48,40 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- private static File tmpSolrHome;- private static File tmpConfDir;+ private static Path tmpSolrHome;+ private static Path tmpConfDir;private static final String collection = "collection1";private static final String confDir = collection + "/conf";@Beforepublic void initManagedSchemaCore() throws Exception {- tmpSolrHome = createTempDir().toFile();- tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-basic.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-managed-schema-test.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-one-field-no-dynamic-field.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-one-field-no-dynamic-field-unique-key.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-minimal.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema_codec.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-bm25.xml"), tmpConfDir);+ tmpSolrHome = createTempDir();+ tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig-managed-schema.xml"),+ tmpConfDir,+ StandardCopyOption.REPLACE_EXISTING);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("solrconfig-basic.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig-managed-schema-test.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-one-field-no-dynamic-field.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-one-field-no-dynamic-field-unique-key.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema-minimal.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema_codec.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("schema-bm25.xml"), tmpConfDir);// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />System.setProperty("managed.schema.mutable", "false");System.setProperty("enable.update.log", "false");- initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome);}@After@@ -87,27 +92,27 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {}public void testUpgrade() throws Exception {- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");- assertTrue(managedSchemaFile.exists());- String managedSchema = Files.readString(managedSchemaFile.toPath(), StandardCharsets.UTF_8);+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");+ assertTrue(Files.exists(managedSchemaFile));+ String managedSchema = Files.readString(managedSchemaFile, StandardCharsets.UTF_8);assertTrue(managedSchema.contains("DO NOT EDIT"));- File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");- assertTrue(upgradedOriginalSchemaFile.exists());+ Path upgradedOriginalSchemaFile = tmpConfDir.resolve("schema-minimal.xml.bak");+ assertTrue(Files.exists(upgradedOriginalSchemaFile));assertSchemaResource(collection, "managed-schema.xml");}public void testUpgradeThenRestart() throws Exception {assertSchemaResource(collection, "managed-schema.xml");deleteCore();- File nonManagedSchemaFile = new File(tmpConfDir, "schema-minimal.xml");- assertFalse(nonManagedSchemaFile.exists());- initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");- assertTrue(managedSchemaFile.exists());- String managedSchema = Files.readString(managedSchemaFile.toPath(), StandardCharsets.UTF_8);+ Path nonManagedSchemaFile = tmpConfDir.resolve("schema-minimal.xml");+ assertFalse(Files.exists(nonManagedSchemaFile));+ initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome);+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");+ assertTrue(Files.exists(managedSchemaFile));+ String managedSchema = Files.readString(managedSchemaFile, StandardCharsets.UTF_8);assertTrue(managedSchema.contains("DO NOT EDIT"));- File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");- assertTrue(upgradedOriginalSchemaFile.exists());+ Path upgradedOriginalSchemaFile = tmpConfDir.resolve("schema-minimal.xml.bak");+ assertTrue(Files.exists(upgradedOriginalSchemaFile));assertSchemaResource(collection, "managed-schema.xml");}@@ -118,28 +123,28 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {assertConfigs("solrconfig-basic.xml","schema-minimal.xml",- tmpSolrHome.getPath(),+ tmpSolrHome.toString(),"Can't find resource 'schema-minimal.xml'");}public void testUpgradeThenRestartNonManagedAfterPuttingBackNonManagedSchema() throws Exception {assertSchemaResource(collection, "managed-schema.xml");deleteCore();- File nonManagedSchemaFile = new File(tmpConfDir, "schema-minimal.xml");- assertFalse(nonManagedSchemaFile.exists());- File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");- assertTrue(upgradedOriginalSchemaFile.exists());+ Path nonManagedSchemaFile = tmpConfDir.resolve("schema-minimal.xml");+ assertFalse(Files.exists(nonManagedSchemaFile));+ Path upgradedOriginalSchemaFile = tmpConfDir.resolve("schema-minimal.xml.bak");+ assertTrue(Files.exists(upgradedOriginalSchemaFile));// After upgrade to managed schema, downgrading to non-managed should work after putting back// the non-managed schema.- FileUtils.moveFile(upgradedOriginalSchemaFile, nonManagedSchemaFile);- initCore("solrconfig-basic.xml", "schema-minimal.xml", tmpSolrHome.getPath());+ Files.move(upgradedOriginalSchemaFile, nonManagedSchemaFile);+ initCore("solrconfig-basic.xml", "schema-minimal.xml", tmpSolrHome);assertSchemaResource(collection, "schema-minimal.xml");}public void testDefaultSchemaFactory() throws Exception {deleteCore();- initCore("solrconfig-managed-schema-test.xml", "schema-minimal.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema-test.xml", "schema-minimal.xml", tmpSolrHome);final CoreContainer cores = h.getCoreContainer();final CoreAdminHandler admin = new CoreAdminHandler(cores);@@ -202,20 +207,15 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddFieldPersistence() throws Exception {assertSchemaResource(collection, "managed-schema.xml");deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");Files.delete(- managedSchemaFile- .toPath()); // Delete managed-schema.xml, so it won't block parsing a new schema+ managedSchemaFile); // Delete managed-schema.xml, so it won't block parsing a new schemaSystem.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);- assertTrue(managedSchemaFile.exists());- String managedSchemaContents =- Files.readString(managedSchemaFile.toPath(), StandardCharsets.UTF_8);+ assertTrue(Files.exists(managedSchemaFile));+ String managedSchemaContents = Files.readString(managedSchemaFile, StandardCharsets.UTF_8);assertFalse(managedSchemaContents.contains("\"new_field\""));Map<String, Object> options = new HashMap<>();@@ -227,8 +227,8 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {IndexSchema newSchema = oldSchema.addField(newField);h.getCore().setLatestSchema(newSchema);- assertTrue(managedSchemaFile.exists());- try (InputStream stream = Files.newInputStream(managedSchemaFile.toPath())) {+ assertTrue(Files.exists(managedSchemaFile));+ try (InputStream stream = Files.newInputStream(managedSchemaFile)) {managedSchemaContents = new String(stream.readAllBytes(), StandardCharsets.UTF_8);}assertTrue(@@ -239,18 +239,14 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddedFieldIndexableAndQueryable() throws Exception {assertSchemaResource(collection, "managed-schema.xml");deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);- assertTrue(managedSchemaFile.exists());- String managedSchemaContents =- Files.readString(managedSchemaFile.toPath(), StandardCharsets.UTF_8);+ assertTrue(Files.exists(managedSchemaFile));+ String managedSchemaContents = Files.readString(managedSchemaFile, StandardCharsets.UTF_8);assertFalse(managedSchemaContents.contains("\"new_field\""));clearIndex();@@ -293,14 +289,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddFieldWhenItAlreadyExists() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);assertNotNull("Field 'str' is not present in the schema",@@ -334,14 +327,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddSameFieldTwice() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);Map<String, Object> options = new HashMap<>();options.put("stored", "false");@@ -375,14 +365,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddDynamicField() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);assertNull("Field '*_s' is present in the schema",@@ -416,11 +403,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddWithSchemaCodecFactory() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore("solrconfig-managed-schema.xml", "schema_codec.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema_codec.xml", tmpSolrHome);String uniqueKey = "string_f";assertNotNull(@@ -447,11 +434,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddWithSchemaSimilarityFactory() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore("solrconfig-managed-schema.xml", "schema-bm25.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-bm25.xml", tmpSolrHome);String uniqueKey = "id";assertNotNull(@@ -479,18 +466,17 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testPersistUniqueKey() throws Exception {assertSchemaResource(collection, "managed-schema.xml");deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");initCore("solrconfig-managed-schema.xml","schema-one-field-no-dynamic-field-unique-key.xml",- tmpSolrHome.getPath());+ tmpSolrHome);- assertTrue(managedSchemaFile.exists());- String managedSchemaContents =- Files.readString(managedSchemaFile.toPath(), StandardCharsets.UTF_8);+ assertTrue(Files.exists(managedSchemaFile));+ String managedSchemaContents = Files.readString(managedSchemaFile, StandardCharsets.UTF_8);assertFalse(managedSchemaContents.contains("\"new_field\""));Map<String, Object> options = new HashMap<>();@@ -508,8 +494,8 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {log.info("####close harness end");initCore();- assertTrue(managedSchemaFile.exists());- try (InputStream stream = Files.newInputStream(managedSchemaFile.toPath())) {+ assertTrue(Files.exists(managedSchemaFile));+ try (InputStream stream = Files.newInputStream(managedSchemaFile)) {managedSchemaContents = new String(stream.readAllBytes(), StandardCharsets.UTF_8);}assertTrue(@@ -522,14 +508,11 @@ public class TestManagedSchema extends AbstractBadConfigTestBase {public void testAddFieldThenReload() throws Exception {deleteCore();- File managedSchemaFile = new File(tmpConfDir, "managed-schema.xml");+ Path managedSchemaFile = tmpConfDir.resolve("managed-schema.xml");// Delete managed-schema.xml, so it won't block parsing a new schema- Files.delete(managedSchemaFile.toPath());+ Files.delete(managedSchemaFile);System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-one-field-no-dynamic-field.xml",- tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome);String fieldName = "new_text_field";assertNull(diff --git a/solr/core/src/test/org/apache/solr/schema/TestSchemalessBufferedUpdates.java b/solr/core/src/test/org/apache/solr/schema/TestSchemalessBufferedUpdates.javaindex 6e35ea5b11e..022f5ae497b 100644--- a/solr/core/src/test/org/apache/solr/schema/TestSchemalessBufferedUpdates.java+++ b/solr/core/src/test/org/apache/solr/schema/TestSchemalessBufferedUpdates.java@@ -19,15 +19,17 @@ package org.apache.solr.schema;import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;-import java.io.File;import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.concurrent.Future;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.request.SolrQueryRequest;@@ -57,19 +59,17 @@ public class TestSchemalessBufferedUpdates extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {- File tmpSolrHome = createTempDir().toFile();- File tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-schemaless.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-add-schema-fields-update-processor.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ Path tmpSolrHome = createTempDir();+ Path tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("solrconfig-schemaless.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-add-schema-fields-update-processor.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);initCore(- "solrconfig-schemaless.xml",- "schema-add-schema-fields-update-processor.xml",- tmpSolrHome.getPath());+ "solrconfig-schemaless.xml", "schema-add-schema-fields-update-processor.xml", tmpSolrHome);}@Testdiff --git a/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored.java b/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored.javaindex b6b2e98eab8..438a72878b0 100644--- a/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored.java+++ b/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored.java@@ -16,9 +16,10 @@*/package org.apache.solr.schema;-import java.io.File;import java.io.InputStream;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.time.Instant;import java.time.LocalDateTime;import java.time.Month;@@ -32,7 +33,8 @@ import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathFactory;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.lucene.tests.util.TestUtil;import org.apache.lucene.util.IOUtils;import org.apache.solr.common.util.DOMUtil;@@ -95,23 +97,23 @@ public class TestUseDocValuesAsStored extends AbstractBadConfigTestBase {@Beforepublic void initManagedSchemaCore() throws Exception {- File tmpSolrHome = createTempDir().toFile();- File tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, "enumsConfig.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-non-stored-docvalues.xml"), tmpConfDir);+ Path tmpSolrHome = createTempDir();+ Path tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig-managed-schema.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("enumsConfig.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-non-stored-docvalues.xml"), tmpConfDir);// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />System.setProperty("enable.update.log", "false");System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml", "schema-non-stored-docvalues.xml", tmpSolrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-non-stored-docvalues.xml", tmpSolrHome);assertQ("sanity check", req("q", "*:*"), "//*[@numFound='0']");}diff --git a/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored2.java b/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored2.javaindex 0a1c6d19dc8..748ae316cd1 100644--- a/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored2.java+++ b/solr/core/src/test/org/apache/solr/schema/TestUseDocValuesAsStored2.java@@ -16,9 +16,9 @@*/package org.apache.solr.schema;-import java.io.File;+import java.nio.file.Path;import java.util.Map;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.common.util.Utils;import org.apache.solr.rest.schema.TestBulkSchemaAPI;import org.apache.solr.util.RestTestBase;@@ -33,19 +33,14 @@ public class TestUseDocValuesAsStored2 extends RestTestBase {@Beforepublic void before() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),- "solrconfig-managed-schema.xml",- "schema-rest.xml",- "/solr",- true,- null);+ tmpSolrHome, "solrconfig-managed-schema.xml", "schema-rest.xml", "/solr", true, null);}@Afterdiff --git a/solr/core/src/test/org/apache/solr/search/ComponentStageLimitsTest.java b/solr/core/src/test/org/apache/solr/search/ComponentStageLimitsTest.javaindex c3c5d72548e..5fce638c7b7 100644--- a/solr/core/src/test/org/apache/solr/search/ComponentStageLimitsTest.java+++ b/solr/core/src/test/org/apache/solr/search/ComponentStageLimitsTest.java@@ -42,7 +42,7 @@ public class ComponentStageLimitsTest extends SolrCloudTestCase {private static Path createConfigSet() throws Exception {Path configSet = createTempDir();- copyMinConf(configSet.toFile());+ copyMinConf(configSet);// insert an expensive search componentPath solrConfig = configSet.resolve("conf/solrconfig.xml");Files.writeString(diff --git a/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java b/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.javaindex 2d22f90db5a..1c0e0fa4969 100644--- a/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java+++ b/solr/core/src/test/org/apache/solr/search/CurrencyRangeFacetCloudTest.java@@ -17,7 +17,6 @@package org.apache.solr.search;import java.lang.invoke.MethodHandles;-import java.nio.file.Paths;import java.util.Arrays;import java.util.Collections;import java.util.List;@@ -64,7 +63,7 @@ public class CurrencyRangeFacetCloudTest extends SolrCloudTestCase {final int nodeCount = numShards * numReplicas;configureCluster(nodeCount)- .addConfig(CONF, Paths.get(TEST_HOME(), "collection1", "conf"))+ .addConfig(CONF, TEST_HOME().resolve("collection1").resolve("conf")).configure();assertEquals(diff --git a/solr/core/src/test/org/apache/solr/search/SignificantTermsQParserPluginTest.java b/solr/core/src/test/org/apache/solr/search/SignificantTermsQParserPluginTest.javaindex 1b623d73b12..a961ebd17e2 100644--- a/solr/core/src/test/org/apache/solr/search/SignificantTermsQParserPluginTest.java+++ b/solr/core/src/test/org/apache/solr/search/SignificantTermsQParserPluginTest.java@@ -17,14 +17,14 @@package org.apache.solr.search;-import java.io.File;import java.io.IOException;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.MapSolrParams;@@ -46,9 +46,9 @@ public class SignificantTermsQParserPluginTest extends SolrTestCaseJ4 {@BeforeClasspublic static void setUpCore() throws Exception {- String tmpSolrHome = createTempDir().toFile().getAbsolutePath();- FileUtils.copyDirectory(new File(TEST_HOME()), new File(tmpSolrHome).getAbsoluteFile());- initCore("solrconfig.xml", "schema.xml", new File(tmpSolrHome).getAbsolutePath());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(TEST_HOME(), tmpSolrHome);+ initCore("solrconfig.xml", "schema.xml", tmpSolrHome);}/**diff --git a/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.javaindex 756c3e3d7cc..755d9eb7691 100644--- a/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java+++ b/solr/core/src/test/org/apache/solr/search/TestAddFieldRealTimeGet.java@@ -16,9 +16,11 @@*/package org.apache.solr.search;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collections;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.schema.IndexSchema;import org.apache.solr.schema.SchemaField;import org.junit.Before;@@ -30,22 +32,22 @@ public class TestAddFieldRealTimeGet extends TestRTGBase {@Beforepublic void initManagedSchemaCore() throws Exception {- final String tmpSolrHomePath = createTempDir().toFile().getAbsolutePath();- File tmpSolrHome = new File(tmpSolrHomePath).getAbsoluteFile();- File tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);+ final Path tmpSolrHome = createTempDir();+ Path tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);final String configFileName = "solrconfig-managed-schema.xml";final String schemaFileName = "schema-id-and-version-fields-only.xml";- FileUtils.copyFileToDirectory(new File(testHomeConfDir, configFileName), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, schemaFileName), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve(configFileName), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve(schemaFileName), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "true");- initCore(configFileName, schemaFileName, tmpSolrHome.getPath());+ initCore(configFileName, schemaFileName, tmpSolrHome);}public void test() throws Exception {diff --git a/solr/core/src/test/org/apache/solr/search/TestCpuAllowedLimit.java b/solr/core/src/test/org/apache/solr/search/TestCpuAllowedLimit.javaindex 4611de10eca..740e385214c 100644--- a/solr/core/src/test/org/apache/solr/search/TestCpuAllowedLimit.java+++ b/solr/core/src/test/org/apache/solr/search/TestCpuAllowedLimit.java@@ -42,7 +42,7 @@ public class TestCpuAllowedLimit extends SolrCloudTestCase {private static Path createConfigSet() throws Exception {Path configSet = createTempDir();- copyMinConf(configSet.toFile());+ copyMinConf(configSet);// insert an expensive search componentPath solrConfig = configSet.resolve("conf/solrconfig.xml");Files.writeString(diff --git a/solr/core/src/test/org/apache/solr/search/TestDocValuesIteratorCache.java b/solr/core/src/test/org/apache/solr/search/TestDocValuesIteratorCache.javaindex 338be897c70..2a1921a663a 100644--- a/solr/core/src/test/org/apache/solr/search/TestDocValuesIteratorCache.java+++ b/solr/core/src/test/org/apache/solr/search/TestDocValuesIteratorCache.java@@ -74,7 +74,7 @@ public class TestDocValuesIteratorCache extends SolrTestCaseJ4 {@SuppressWarnings("try")public void test() throws Exception {Path configSet = LuceneTestCase.createTempDir();- SolrTestCaseJ4.copyMinConf(configSet.toFile());+ SolrTestCaseJ4.copyMinConf(configSet);Path schemaXml = configSet.resolve("conf/schema.xml");Files.writeString(schemaXml,diff --git a/solr/core/src/test/org/apache/solr/search/TestMemAllowedLimit.java b/solr/core/src/test/org/apache/solr/search/TestMemAllowedLimit.javaindex 5dac479eb90..533054dca0f 100644--- a/solr/core/src/test/org/apache/solr/search/TestMemAllowedLimit.java+++ b/solr/core/src/test/org/apache/solr/search/TestMemAllowedLimit.java@@ -44,7 +44,7 @@ public class TestMemAllowedLimit extends SolrCloudTestCase {private static Path createConfigSet() throws Exception {Path configSet = createTempDir();- copyMinConf(configSet.toFile());+ copyMinConf(configSet);// insert an expensive search componentPath solrConfig = configSet.resolve("conf/solrconfig.xml");Files.writeString(diff --git a/solr/core/src/test/org/apache/solr/search/TestRecovery.java b/solr/core/src/test/org/apache/solr/search/TestRecovery.javaindex 2c814cf9b5f..ec2dead4da4 100644--- a/solr/core/src/test/org/apache/solr/search/TestRecovery.java+++ b/solr/core/src/test/org/apache/solr/search/TestRecovery.java@@ -24,11 +24,11 @@ import com.codahale.metrics.Gauge;import com.codahale.metrics.Meter;import com.codahale.metrics.Metric;import com.codahale.metrics.MetricRegistry;-import java.io.File;import java.io.RandomAccessFile;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Arrays;@@ -1462,16 +1462,16 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(commit());UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();- File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());+ Path logDir = Path.of(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());h.close();- String[] files = ulog.getLogList(logDir.toPath());+ String[] files = ulog.getLogList(logDir);for (String file : files) {- Files.delete(new File(logDir, file).toPath());+ Files.delete(logDir.resolve(file));}- assertEquals(0, ulog.getLogList(logDir.toPath()).length);+ assertEquals(0, ulog.getLogList(logDir).length);createCore();@@ -1502,8 +1502,7 @@ public class TestRecovery extends SolrTestCaseJ4 {assertJQ(req("qt", "/get", "getVersions", "" + maxReq),"/versions==" + versions.subList(0, Math.min(maxReq, versExpected)));- assertEquals(- Math.min(i, ulog.getMaxNumLogsToKeep()), ulog.getLogList(logDir.toPath()).length);+ assertEquals(Math.min(i, ulog.getMaxNumLogsToKeep()), ulog.getLogList(logDir).length);}docsPerBatch = ulog.getNumRecordsToKeep() + 20;@@ -1524,7 +1523,7 @@ public class TestRecovery extends SolrTestCaseJ4 {"/versions==" + versions.subList(0, Math.min(maxReq, versExpected)));// previous logs should be gone now- assertEquals(1, ulog.getLogList(logDir.toPath()).length);+ assertEquals(1, ulog.getLogList(logDir).length);addDocs(1, numIndexed, versions);numIndexed += 1;@@ -1561,7 +1560,7 @@ public class TestRecovery extends SolrTestCaseJ4 {"/versions==" + versions.subList(0, Math.min(maxReq, expectedToRetain)));// previous logs should be gone now- assertEquals(1, ulog.getLogList(logDir.toPath()).length);+ assertEquals(1, ulog.getLogList(logDir).length);//// test that a corrupt tlog file doesn't stop us from coming up, or seeing versions before@@ -1573,10 +1572,10 @@ public class TestRecovery extends SolrTestCaseJ4 {new LinkedList<Long>()); // don't add this to the versions list because we are going to lose it...h.close();- files = ulog.getLogList(logDir.toPath());+ files = ulog.getLogList(logDir);Arrays.sort(files);try (RandomAccessFile raf =- new RandomAccessFile(new File(logDir, files[files.length - 1]), "rw")) {+ new RandomAccessFile(logDir.resolve(files[files.length - 1]).toFile(), "rw")) {raf.writeChars("This is a trashed log file that really shouldn't work at all, but we'll see...");}@@ -1619,7 +1618,7 @@ public class TestRecovery extends SolrTestCaseJ4 {UpdateLog.testing_logReplayFinishHook = () -> logReplayFinish.release();UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();- File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());+ Path logDir = Path.of(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());clearIndex();assertU(commit());@@ -1629,10 +1628,10 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(adoc("id", "F3"));h.close();- String[] files = ulog.getLogList(logDir.toPath());+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);try (RandomAccessFile raf =- new RandomAccessFile(new File(logDir, files[files.length - 1]), "rw")) {+ new RandomAccessFile(logDir.resolve(files[files.length - 1]).toFile(), "rw")) {raf.seek(raf.length()); // seek to endraf.writeLong(0xffffffffffffffffL);raf.writeChars(@@ -1685,7 +1684,7 @@ public class TestRecovery extends SolrTestCaseJ4 {TestInjection.skipIndexWriterCommitOnClose = true;UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();- File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());+ Path logDir = Path.of(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());clearIndex();assertU(commit());@@ -1696,10 +1695,10 @@ public class TestRecovery extends SolrTestCaseJ4 {h.close();- String[] files = ulog.getLogList(logDir.toPath());+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);try (RandomAccessFile raf =- new RandomAccessFile(new File(logDir, files[files.length - 1]), "rw")) {+ new RandomAccessFile(logDir.resolve(files[files.length - 1]).toFile(), "rw")) {long len = raf.length();raf.seek(0); // seek to startraf.write(new byte[(int) len]); // zero out file@@ -1769,7 +1768,7 @@ public class TestRecovery extends SolrTestCaseJ4 {UpdateLog.testing_logReplayFinishHook = () -> logReplayFinish.release();UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();- File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());+ Path logDir = Path.of(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());clearIndex();assertU(commit());@@ -1779,11 +1778,11 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(adoc("id", "CCCCCC"));h.close();- String[] files = ulog.getLogList(logDir.toPath());+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);String fname = files[files.length - 1];byte[] content;- try (RandomAccessFile raf = new RandomAccessFile(new File(logDir, fname), "rw")) {+ try (RandomAccessFile raf = new RandomAccessFile(logDir.resolve(fname).toFile(), "rw")) {raf.seek(raf.length()); // seek to endraf.writeLong(0xffffffffffffffffL);raf.writeChars(@@ -1814,7 +1813,7 @@ public class TestRecovery extends SolrTestCaseJ4 {String fname2 =String.format(Locale.ROOT, UpdateLog.LOG_FILENAME_PATTERN, UpdateLog.TLOG_NAME, logNumber + 1);- try (RandomAccessFile raf = new RandomAccessFile(new File(logDir, fname2), "rw")) {+ try (RandomAccessFile raf = new RandomAccessFile(logDir.resolve(fname2).toFile(), "rw")) {raf.write(content);}@@ -2001,17 +2000,17 @@ public class TestRecovery extends SolrTestCaseJ4 {// stops the core, removes the transaction logs, restarts the core.void deleteLogs() throws Exception {UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();- File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());+ Path logDir = Path.of(h.getCore().getUpdateHandler().getUpdateLog().getTlogDir());h.close();try {- String[] files = ulog.getLogList(logDir.toPath());+ String[] files = ulog.getLogList(logDir);for (String file : files) {- Files.delete(new File(logDir, file).toPath());+ Files.delete(logDir.resolve(file));}- assertEquals(0, ulog.getLogList(logDir.toPath()).length);+ assertEquals(0, ulog.getLogList(logDir).length);} finally {// make sure we create the core again, even if the assert operation fails, so it won't mess// up the next test.diff --git a/solr/core/src/test/org/apache/solr/search/TestSearcherReuse.java b/solr/core/src/test/org/apache/solr/search/TestSearcherReuse.javaindex e3924b3d2ea..0f722037241 100644--- a/solr/core/src/test/org/apache/solr/search/TestSearcherReuse.java+++ b/solr/core/src/test/org/apache/solr/search/TestSearcherReuse.java@@ -16,9 +16,11 @@*/package org.apache.solr.search;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collections;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.schema.IndexSchema;@@ -36,7 +38,7 @@ import org.junit.BeforeClass;*/public class TestSearcherReuse extends SolrTestCaseJ4 {- private static File solrHome;+ private static Path solrHome;private static final String collection = "collection1";private static final String confPath = collection + "/conf";@@ -47,25 +49,21 @@ public class TestSearcherReuse extends SolrTestCaseJ4 {*/@BeforeClasspublic static void setupTempDirAndCoreWithManagedSchema() throws Exception {- solrHome = createTempDir().toFile();- solrHome = solrHome.getAbsoluteFile();-- File confDir = new File(solrHome, confPath);- File testHomeConfDir = new File(TEST_HOME(), confPath);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-managed-schema.xml"), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-id-and-version-fields-only.xml"), confDir);+ solrHome = createTempDir();+ Path confDir = FilterPath.unwrap(solrHome.resolve(confPath));+ Path testHomeConfDir = TEST_HOME().resolve(confPath);+ Files.createDirectories(confDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig-managed-schema.xml"), confDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), confDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-id-and-version-fields-only.xml"), confDir);// initCore will trigger an upgrade to managed schema, since the solrconfig has// <schemaFactory class="ManagedIndexSchemaFactory" ... />System.setProperty("managed.schema.mutable", "true");- initCore(- "solrconfig-managed-schema.xml",- "schema-id-and-version-fields-only.xml",- solrHome.getPath());+ initCore("solrconfig-managed-schema.xml", "schema-id-and-version-fields-only.xml", solrHome);}@AfterClassdiff --git a/solr/core/src/test/org/apache/solr/search/TestThinCache.java b/solr/core/src/test/org/apache/solr/search/TestThinCache.javaindex c485b9fe46a..6a23b82568f 100644--- a/solr/core/src/test/org/apache/solr/search/TestThinCache.java+++ b/solr/core/src/test/org/apache/solr/search/TestThinCache.java@@ -60,7 +60,7 @@ public class TestThinCache extends SolrTestCaseJ4 {solrRule.startSolr(home);Path configSet = createTempDir("configSet");- copyMinConf(configSet.toFile());+ copyMinConf(configSet);// insert a special filterCache configurationPath solrConfig = configSet.resolve("conf/solrconfig.xml");Files.writeString(diff --git a/solr/core/src/test/org/apache/solr/search/facet/RangeFacetCloudTest.java b/solr/core/src/test/org/apache/solr/search/facet/RangeFacetCloudTest.javaindex 66c23dad137..ea909c57d5e 100644--- a/solr/core/src/test/org/apache/solr/search/facet/RangeFacetCloudTest.java+++ b/solr/core/src/test/org/apache/solr/search/facet/RangeFacetCloudTest.java@@ -18,7 +18,6 @@ package org.apache.solr.search.facet;import java.lang.invoke.MethodHandles;import java.lang.reflect.Array;-import java.nio.file.Paths;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -92,7 +91,7 @@ public class RangeFacetCloudTest extends SolrCloudTestCase {final int nodeCount = numShards * numReplicas;configureCluster(nodeCount)- .addConfig(CONF, Paths.get(TEST_HOME(), "collection1", "conf"))+ .addConfig(CONF, TEST_HOME().resolve("collection1").resolve("conf")).configure();assertEquals(diff --git a/solr/core/src/test/org/apache/solr/search/json/TestJsonRequestWithEdismaxDefType.java b/solr/core/src/test/org/apache/solr/search/json/TestJsonRequestWithEdismaxDefType.javaindex 3d3ec25a878..7c5a87bc5b1 100644--- a/solr/core/src/test/org/apache/solr/search/json/TestJsonRequestWithEdismaxDefType.java+++ b/solr/core/src/test/org/apache/solr/search/json/TestJsonRequestWithEdismaxDefType.java@@ -36,7 +36,7 @@ public class TestJsonRequestWithEdismaxDefType extends SolrTestCaseJ4 {solrClientTestRule.startSolr(LuceneTestCase.createTempDir());Path configSet = LuceneTestCase.createTempDir();- SolrTestCaseJ4.copyMinConf(configSet.toFile());+ SolrTestCaseJ4.copyMinConf(configSet);solrClientTestRule.newCollection().withConfigSet(configSet.toString()).create();diff --git a/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java b/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.javaindex 3405539490e..bdd1df4b61a 100644--- a/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java+++ b/solr/core/src/test/org/apache/solr/security/BasicAuthStandaloneTest.java@@ -25,7 +25,6 @@ import java.io.IOException;import java.lang.invoke.MethodHandles;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.Base64;import java.util.Collections;import java.util.Properties;@@ -54,7 +53,7 @@ import org.slf4j.LoggerFactory;public class BasicAuthStandaloneTest extends SolrTestCaseJ4 {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- private static final Path ROOT_DIR = Paths.get(TEST_HOME());+ private static final Path ROOT_DIR = TEST_HOME();private static final Path CONF_DIR =ROOT_DIR.resolve("configsets").resolve("configset-2").resolve("conf");diff --git a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.javaindex 2aaa5c4b788..f304468abd7 100644--- a/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java+++ b/solr/core/src/test/org/apache/solr/servlet/CacheHeaderTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.servlet;-import java.io.File;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -39,27 +38,27 @@ public class CacheHeaderTest extends CacheHeaderTestBase {public static void beforeTest() throws Exception {System.setProperty("solr.enableRemoteStreaming", "true"); // needed for testCacheVetoHandler- File solrHomeDirectory = createTempDir().toFile();+ Path solrHomeDirectory = createTempDir();setupJettyTestHome(solrHomeDirectory, "collection1");- createAndStartJetty(solrHomeDirectory.getAbsolutePath());+ createAndStartJetty(solrHomeDirectory);}protected static final String CONTENTS = "id\n100\n101\n102";@Testpublic void testCacheVetoHandler() throws Exception {- File f = makeFile(CacheHeaderTest.CONTENTS, StandardCharsets.UTF_8.name());+ Path f = makeFile(CacheHeaderTest.CONTENTS, StandardCharsets.UTF_8.name());HttpRequestBase m =getUpdateMethod("GET",CommonParams.STREAM_FILE,- f.getCanonicalPath(),+ f.toRealPath().toString(),CommonParams.STREAM_CONTENTTYPE,"text/csv");HttpResponse response = getHttpClient().execute(m);assertEquals(200, response.getStatusLine().getStatusCode());checkVetoHeaders(response, true);- Files.delete(f.toPath());+ Files.delete(f);}@Test@@ -266,11 +265,11 @@ public class CacheHeaderTest extends CacheHeaderTestBase {}}- protected File makeFile(String contents, String charset) {+ protected Path makeFile(String contents, String charset) {try {Path f = createTempFile("cachetest", "csv");Files.writeString(f, contents, Charset.forName(charset));- return f.toFile();+ return f;} catch (Exception e) {throw new RuntimeException(e);}diff --git a/solr/core/src/test/org/apache/solr/servlet/HideStackTraceTest.java b/solr/core/src/test/org/apache/solr/servlet/HideStackTraceTest.javaindex 54ac3e28b5a..867796733b4 100644--- a/solr/core/src/test/org/apache/solr/servlet/HideStackTraceTest.java+++ b/solr/core/src/test/org/apache/solr/servlet/HideStackTraceTest.java@@ -46,7 +46,7 @@ public class HideStackTraceTest extends SolrTestCaseJ4 {System.setProperty("solr.hideStackTrace", "true");Path configSet = createTempDir("configSet");- copyMinConf(configSet.toFile());+ copyMinConf(configSet);// insert a special filterCache configurationPath solrConfig = configSet.resolve("conf/solrconfig.xml");Files.writeString(diff --git a/solr/core/src/test/org/apache/solr/servlet/ResponseHeaderTest.java b/solr/core/src/test/org/apache/solr/servlet/ResponseHeaderTest.javaindex b9e821c3acb..8db6e6c7e66 100644--- a/solr/core/src/test/org/apache/solr/servlet/ResponseHeaderTest.java+++ b/solr/core/src/test/org/apache/solr/servlet/ResponseHeaderTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.servlet;-import java.io.File;import java.io.IOException;import java.net.URI;import java.nio.file.Files;@@ -35,18 +34,18 @@ import org.junit.Test;public class ResponseHeaderTest extends SolrJettyTestBase {- private static File solrHomeDirectory;+ private static Path solrHomeDirectory;@BeforeClasspublic static void beforeTest() throws Exception {- solrHomeDirectory = createTempDir().toFile();+ solrHomeDirectory = createTempDir();setupJettyTestHome(solrHomeDirectory, "collection1");String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";Files.copy(Path.of(top, "solrconfig-headers.xml"),Path.of(solrHomeDirectory + "/collection1/conf", "solrconfig.xml"),StandardCopyOption.REPLACE_EXISTING);- createAndStartJetty(solrHomeDirectory.getAbsolutePath());+ createAndStartJetty(solrHomeDirectory);}@AfterClassdiff --git a/solr/core/src/test/org/apache/solr/spelling/FileBasedSpellCheckerTest.java b/solr/core/src/test/org/apache/solr/spelling/FileBasedSpellCheckerTest.javaindex c4d33b77912..61e17dbfca8 100644--- a/solr/core/src/test/org/apache/solr/spelling/FileBasedSpellCheckerTest.java+++ b/solr/core/src/test/org/apache/solr/spelling/FileBasedSpellCheckerTest.java@@ -16,7 +16,8 @@*/package org.apache.solr.spelling;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collection;import java.util.Collections;import java.util.Map;@@ -68,8 +69,8 @@ public class FileBasedSpellCheckerTest extends SolrTestCaseJ4 {spellchecker.add(AbstractLuceneSpellChecker.LOCATION, "spellings.txt");spellchecker.add(AbstractLuceneSpellChecker.FIELD, "teststop");spellchecker.add(FileBasedSpellChecker.SOURCE_FILE_CHAR_ENCODING, "UTF-8");- File indexDir = createTempDir(LuceneTestCase.getTestClass().getSimpleName()).toFile();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());+ Path indexDir = createTempDir(LuceneTestCase.getTestClass().getSimpleName());+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());SolrCore core = h.getCore();String dictName = checker.init(spellchecker, core);assertEquals(dictName + " is not equal to " + "external", "external", dictName);@@ -117,9 +118,9 @@ public class FileBasedSpellCheckerTest extends SolrTestCaseJ4 {spellchecker.add(AbstractLuceneSpellChecker.LOCATION, "spellings.txt");spellchecker.add(AbstractLuceneSpellChecker.FIELD, "teststop");spellchecker.add(FileBasedSpellChecker.SOURCE_FILE_CHAR_ENCODING, "UTF-8");- File indexDir = createTempDir().toFile();- indexDir.mkdirs();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());+ Path indexDir = createTempDir();+ Files.createDirectories(indexDir);+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());spellchecker.add(SolrSpellChecker.FIELD_TYPE, "teststop_type");SolrCore core = h.getCore();String dictName = checker.init(spellchecker, core);diff --git a/solr/core/src/test/org/apache/solr/spelling/IndexBasedSpellCheckerTest.java b/solr/core/src/test/org/apache/solr/spelling/IndexBasedSpellCheckerTest.javaindex 0db7a5d8462..da25b002a7e 100644--- a/solr/core/src/test/org/apache/solr/spelling/IndexBasedSpellCheckerTest.java+++ b/solr/core/src/test/org/apache/solr/spelling/IndexBasedSpellCheckerTest.java@@ -16,7 +16,8 @@*/package org.apache.solr.spelling;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Collection;import java.util.Collections;import java.util.Comparator;@@ -107,9 +108,9 @@ public class IndexBasedSpellCheckerTest extends SolrTestCaseJ4 {NamedList<Object> spellchecker = new NamedList<>();spellchecker.add("classname", IndexBasedSpellChecker.class.getName());- File indexDir = createTempDir().toFile();+ Path indexDir = createTempDir();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());spellchecker.add(AbstractLuceneSpellChecker.FIELD, "title");spellchecker.add(AbstractLuceneSpellChecker.SPELLCHECKER_ARG_NAME, spellchecker);SolrCore core = h.getCore();@@ -212,9 +213,9 @@ public class IndexBasedSpellCheckerTest extends SolrTestCaseJ4 {NamedList<Object> spellchecker = new NamedList<>();spellchecker.add("classname", IndexBasedSpellChecker.class.getName());- File indexDir = createTempDir().toFile();- indexDir.mkdirs();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());+ Path indexDir = createTempDir();+ Files.createDirectories(indexDir);+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());spellchecker.add(AbstractLuceneSpellChecker.FIELD, "title");spellchecker.add(AbstractLuceneSpellChecker.SPELLCHECKER_ARG_NAME, spellchecker);SolrCore core = h.getCore();@@ -274,8 +275,8 @@ public class IndexBasedSpellCheckerTest extends SolrTestCaseJ4 {NamedList<Object> spellchecker = new NamedList<>();spellchecker.add("classname", IndexBasedSpellChecker.class.getName());- File indexDir = createTempDir().toFile();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());+ Path indexDir = createTempDir();+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());spellchecker.add(AbstractLuceneSpellChecker.FIELD, "title");spellchecker.add(AbstractLuceneSpellChecker.SPELLCHECKER_ARG_NAME, spellchecker);spellchecker.add(@@ -318,11 +319,11 @@ public class IndexBasedSpellCheckerTest extends SolrTestCaseJ4 {NamedList<Object> spellchecker = new NamedList<>();spellchecker.add("classname", IndexBasedSpellChecker.class.getName());- File tmpDir = createTempDir().toFile();- File indexDir = new File(tmpDir, "spellingIdx");+ Path tmpDir = createTempDir();+ Path indexDir = tmpDir.resolve("spellingIdx");// create a standalone index- File altIndexDir = new File(tmpDir, "alternateIdx" + new Date().getTime());- Directory dir = newFSDirectory(altIndexDir.toPath());+ Path altIndexDir = tmpDir.resolve("alternateIdx" + new Date().getTime());+ Directory dir = newFSDirectory(altIndexDir);IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(new WhitespaceAnalyzer()));for (String alt_doc : ALT_DOCS) {Document doc = new Document();@@ -332,9 +333,9 @@ public class IndexBasedSpellCheckerTest extends SolrTestCaseJ4 {iw.forceMerge(1);iw.close();dir.close();- indexDir.mkdirs();- spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.getAbsolutePath());- spellchecker.add(AbstractLuceneSpellChecker.LOCATION, altIndexDir.getAbsolutePath());+ Files.createDirectories(indexDir);+ spellchecker.add(AbstractLuceneSpellChecker.INDEX_DIR, indexDir.toString());+ spellchecker.add(AbstractLuceneSpellChecker.LOCATION, altIndexDir.toString());spellchecker.add(AbstractLuceneSpellChecker.FIELD, "title");spellchecker.add(AbstractLuceneSpellChecker.SPELLCHECKER_ARG_NAME, spellchecker);SolrCore core = h.getCore();diff --git a/solr/core/src/test/org/apache/solr/update/CustomTLogDirTest.java b/solr/core/src/test/org/apache/solr/update/CustomTLogDirTest.javaindex 3c284e8dd12..1f575cc5406 100644--- a/solr/core/src/test/org/apache/solr/update/CustomTLogDirTest.java+++ b/solr/core/src/test/org/apache/solr/update/CustomTLogDirTest.java@@ -16,9 +16,11 @@*/package org.apache.solr.update;-import java.io.File;+import java.nio.file.Files;import java.nio.file.Path;+import java.util.List;import java.util.concurrent.atomic.AtomicInteger;+import java.util.stream.Stream;import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.lucene.tests.util.LuceneTestCase;import org.apache.solr.SolrTestCaseJ4;@@ -81,7 +83,7 @@ public class CustomTLogDirTest extends SolrTestCaseJ4 {System.setProperty("enable.update.log", "true");System.setProperty("solr.test.sys.prop2", "proptwo");System.setProperty("solr.ulog.dir", ulogDir.toString()); // picked up from `solrconfig.xml`- SolrTestCaseJ4.copyMinConf(configSet.toFile(), null, "solrconfig.xml");+ SolrTestCaseJ4.copyMinConf(configSet, null, "solrconfig.xml");// relative dir path specs should not be able to "escape" the core-scoped instance dir;// check that this config is unsuccessful@@ -147,7 +149,7 @@ public class CustomTLogDirTest extends SolrTestCaseJ4 {if (ulogDir != null) {System.setProperty("solr.ulog.dir", ulogDir.toString()); // picked up from `solrconfig.xml`}- SolrTestCaseJ4.copyMinConf(configSet.toFile(), null, "solrconfig.xml");+ SolrTestCaseJ4.copyMinConf(configSet, null, "solrconfig.xml");String collectionName = instanceDir.getFileName().toString();@@ -161,13 +163,19 @@ public class CustomTLogDirTest extends SolrTestCaseJ4 {client.add(sdoc("id", "3"));client.commit();- File[] list =- resolvedTlogDir.toFile().listFiles((f) -> f.isFile() && f.getName().startsWith("tlog."));-- assertNotNull(list);- assertEquals(1, list.length);- CoreContainer cc = ((EmbeddedSolrServer) client).getCoreContainer();- cc.unload(collectionName, true, true, true);- assertFalse(resolvedTlogDir.toFile().exists());+ try (Stream<Path> files = Files.list(resolvedTlogDir)) {+ List<Path> list =+ files+ .filter(+ file ->+ Files.isRegularFile(file)+ && file.getFileName().toString().startsWith("tlog."))+ .toList();+ assertNotNull(list);+ assertEquals(1, list.size());+ CoreContainer cc = ((EmbeddedSolrServer) client).getCoreContainer();+ cc.unload(collectionName, true, true, true);+ assertFalse(Files.exists(resolvedTlogDir));+ }}}diff --git a/solr/core/src/test/org/apache/solr/update/DataDrivenBlockJoinTest.java b/solr/core/src/test/org/apache/solr/update/DataDrivenBlockJoinTest.javaindex d8cf69c623b..d73d73d73a6 100644--- a/solr/core/src/test/org/apache/solr/update/DataDrivenBlockJoinTest.java+++ b/solr/core/src/test/org/apache/solr/update/DataDrivenBlockJoinTest.java@@ -16,8 +16,10 @@*/package org.apache.solr.update;-import java.io.File;-import org.apache.commons.io.FileUtils;+import java.nio.file.Files;+import java.nio.file.Path;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.SolrTestCaseJ4;import org.junit.Before;import org.junit.Test;@@ -29,22 +31,20 @@ public class DataDrivenBlockJoinTest extends SolrTestCaseJ4 {@Beforepublic void before() throws Exception {- File tmpSolrHome = createTempDir().toFile();- File tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig-schemaless.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "schema-add-schema-fields-update-processor.xml"), tmpConfDir);- FileUtils.copyFileToDirectory(- new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);+ Path tmpSolrHome = createTempDir();+ Path tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve("solrconfig-schemaless.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("schema-add-schema-fields-update-processor.xml"), tmpConfDir);+ PathUtils.copyFileToDirectory(+ testHomeConfDir.resolve("solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);System.setProperty("managed.schema.mutable", "true");System.setProperty("enable.update.log", "false");initCore(- "solrconfig-schemaless.xml",- "schema-add-schema-fields-update-processor.xml",- tmpSolrHome.getPath());+ "solrconfig-schemaless.xml", "schema-add-schema-fields-update-processor.xml", tmpSolrHome);}@Testdiff --git a/solr/core/src/test/org/apache/solr/update/RootFieldTest.java b/solr/core/src/test/org/apache/solr/update/RootFieldTest.javaindex b11da415045..09c405ff1a3 100644--- a/solr/core/src/test/org/apache/solr/update/RootFieldTest.java+++ b/solr/core/src/test/org/apache/solr/update/RootFieldTest.java@@ -19,7 +19,6 @@ package org.apache.solr.update;import static org.hamcrest.CoreMatchers.is;-import java.nio.file.Path;import org.apache.solr.EmbeddedSolrServerTestBase;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.SolrClient;@@ -51,7 +50,7 @@ public class RootFieldTest extends EmbeddedSolrServerTestBase {@BeforeClasspublic static void beforeTest() throws Exception {- solrClientTestRule.startSolr(Path.of(SolrTestCaseJ4.TEST_HOME()));+ solrClientTestRule.startSolr(SolrTestCaseJ4.TEST_HOME());useRootSchema = random().nextBoolean();// schema15.xml declares _root_ field, while schema-rest.xml does not.diff --git a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.javaindex f41874b9525..0bdb7078bea 100644--- a/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java+++ b/solr/core/src/test/org/apache/solr/update/SolrCmdDistributorTest.java@@ -17,7 +17,6 @@package org.apache.solr.update;import java.io.ByteArrayInputStream;-import java.io.File;import java.io.IOException;import java.net.SocketException;import java.nio.file.Path;@@ -108,14 +107,13 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {@Overrideprotected void createServers(int numShards) throws Exception {- System.setProperty("configSetBaseDir", TEST_HOME());+ System.setProperty("configSetBaseDir", TEST_HOME().toString());- File controlHome = testDir.toPath().resolve("control").toFile();+ Path controlHome = testDir.resolve("control");seedSolrHome(controlHome);writeCoreProperties(- controlHome.toPath().resolve("cores").resolve(DEFAULT_TEST_CORENAME),- DEFAULT_TEST_CORENAME);+ controlHome.resolve("cores").resolve(DEFAULT_TEST_CORENAME), DEFAULT_TEST_CORENAME);controlJetty =createJetty(controlHome, testDir + "/control/data", null, getSolrConfigFile(), getSchemaFile());@@ -127,13 +125,13 @@ public class SolrCmdDistributorTest extends BaseDistributedSearchTestCase {for (int i = 0; i < numShards; i++) {if (sb.length() > 0) sb.append(',');String shardname = "shard" + i;- Path shardHome = testDir.toPath().resolve(shardname);- seedSolrHome(shardHome.toFile());+ Path shardHome = testDir.resolve(shardname);+ seedSolrHome(shardHome);Path coresPath = shardHome.resolve("cores");writeCoreProperties(coresPath.resolve(DEFAULT_TEST_CORENAME), DEFAULT_TEST_CORENAME);JettySolrRunner j =createJetty(- shardHome.toFile(),+ shardHome,testDir + "/shard" + i + "/data",null,getSolrConfigFile(),diff --git a/solr/core/src/test/org/apache/solr/update/SolrIndexSplitterTest.java b/solr/core/src/test/org/apache/solr/update/SolrIndexSplitterTest.javaindex 78906e9b8e0..6650dc40414 100644--- a/solr/core/src/test/org/apache/solr/update/SolrIndexSplitterTest.java+++ b/solr/core/src/test/org/apache/solr/update/SolrIndexSplitterTest.java@@ -16,9 +16,9 @@*/package org.apache.solr.update;-import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;+import java.nio.file.Path;import java.util.List;import java.util.Map;import java.util.Set;@@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory;public class SolrIndexSplitterTest extends SolrTestCaseJ4 {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- File indexDir1 = null, indexDir2 = null, indexDir3 = null;+ Path indexDir1 = null, indexDir2 = null, indexDir3 = null;@BeforeClasspublic static void beforeClass() throws Exception {@@ -64,12 +64,10 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {super.setUp();clearIndex();assertU(commit());- indexDir1 = createTempDir("_testSplit1").toFile();- indexDir2 = createTempDir("_testSplit2").toFile();- indexDir3 = createTempDir("_testSplit3").toFile();- h.getCoreContainer()- .getAllowPaths()- .addAll(Set.of(indexDir1.toPath(), indexDir2.toPath(), indexDir3.toPath()));+ indexDir1 = createTempDir("_testSplit1");+ indexDir2 = createTempDir("_testSplit2");+ indexDir3 = createTempDir("_testSplit3");+ h.getCoreContainer().getAllowPaths().addAll(Set.of(indexDir1, indexDir2, indexDir3));}@Test@@ -102,7 +100,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {new SplitIndexCommand(request,rsp,- List.of(indexDir1.getAbsolutePath(), indexDir2.getAbsolutePath()),+ List.of(indexDir1.toString(), indexDir2.toString()),null,ranges,new PlainIdRouter(),@@ -115,7 +113,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir1.getAbsolutePath(),+ indexDir1.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);DirectoryReader reader = DirectoryReader.open(directory);@@ -134,7 +132,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir2.getAbsolutePath(),+ indexDir2.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);reader = DirectoryReader.open(directory);@@ -192,7 +190,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {new SplitIndexCommand(request,rsp,- List.of(indexDir1.getAbsolutePath(), indexDir2.getAbsolutePath()),+ List.of(indexDir1.toString(), indexDir2.toString()),null,ranges,new PlainIdRouter(),@@ -205,7 +203,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir1.getAbsolutePath(),+ indexDir1.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);DirectoryReader reader = DirectoryReader.open(directory);@@ -224,7 +222,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir2.getAbsolutePath(),+ indexDir2.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);reader = DirectoryReader.open(directory);@@ -267,13 +265,11 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {core1 =h.getCoreContainer().create(- "split1",- Map.of("dataDir", indexDir1.getAbsolutePath(), "configSet", "cloud-minimal"));+ "split1", Map.of("dataDir", indexDir1.toString(), "configSet", "cloud-minimal"));core2 =h.getCoreContainer().create(- "split2",- Map.of("dataDir", indexDir2.getAbsolutePath(), "configSet", "cloud-minimal"));+ "split2", Map.of("dataDir", indexDir2.toString(), "configSet", "cloud-minimal"));LocalSolrQueryRequest request = null;try {@@ -350,10 +346,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {new SplitIndexCommand(request,rsp,- List.of(- indexDir1.getAbsolutePath(),- indexDir2.getAbsolutePath(),- indexDir3.getAbsolutePath()),+ List.of(indexDir1.toString(), indexDir2.toString(), indexDir3.toString()),null,null,new PlainIdRouter(),@@ -366,7 +359,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir1.getAbsolutePath(),+ indexDir1.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);DirectoryReader reader = DirectoryReader.open(directory);@@ -377,7 +370,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir2.getAbsolutePath(),+ indexDir2.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);reader = DirectoryReader.open(directory);@@ -388,7 +381,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir3.getAbsolutePath(),+ indexDir3.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);reader = DirectoryReader.open(directory);@@ -420,7 +413,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {}private void doTestSplitByRouteKey(SolrIndexSplitter.SplitMethod splitMethod) throws Exception {- File indexDir = createTempDir().toFile();+ Path indexDir = createTempDir();CompositeIdRouter r1 = new CompositeIdRouter();String splitKey = "sea-line!";@@ -456,7 +449,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {new SplitIndexCommand(request,rsp,- List.of(indexDir.getAbsolutePath()),+ List.of(indexDir.toString()),null,List.of(splitKeyRange),new CompositeIdRouter(),@@ -468,7 +461,7 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {h.getCore().getDirectoryFactory().get(- indexDir.getAbsolutePath(),+ indexDir.toString(),DirectoryFactory.DirContext.DEFAULT,h.getCore().getSolrConfig().indexConfig.lockType);DirectoryReader reader = DirectoryReader.open(directory);@@ -498,8 +491,6 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {public void doTestSplitWithChildDocs(SolrIndexSplitter.SplitMethod splitMethod) throws Exception {// Overall test/split pattern copied from doTestSplitByCores- File indexDir = createTempDir().toFile();-CompositeIdRouter r1 = new CompositeIdRouter();String routeKeyBase = "sea-line!";@@ -534,13 +525,11 @@ public class SolrIndexSplitterTest extends SolrTestCaseJ4 {core1 =h.getCoreContainer().create(- "split1",- Map.of("dataDir", indexDir1.getAbsolutePath(), "configSet", "cloud-minimal"));+ "split1", Map.of("dataDir", indexDir1.toString(), "configSet", "cloud-minimal"));core2 =h.getCoreContainer().create(- "split2",- Map.of("dataDir", indexDir2.getAbsolutePath(), "configSet", "cloud-minimal"));+ "split2", Map.of("dataDir", indexDir2.toString(), "configSet", "cloud-minimal"));LocalSolrQueryRequest request = null;try {diff --git a/solr/core/src/test/org/apache/solr/update/processor/AbstractAtomicUpdatesMultivalueTestBase.java b/solr/core/src/test/org/apache/solr/update/processor/AbstractAtomicUpdatesMultivalueTestBase.javaindex ee31cd1077e..e851088b99b 100644--- a/solr/core/src/test/org/apache/solr/update/processor/AbstractAtomicUpdatesMultivalueTestBase.java+++ b/solr/core/src/test/org/apache/solr/update/processor/AbstractAtomicUpdatesMultivalueTestBase.java@@ -21,7 +21,6 @@ import static org.hamcrest.CoreMatchers.hasItems;import static org.hamcrest.CoreMatchers.not;import java.io.IOException;-import java.nio.file.Paths;import java.time.ZonedDateTime;import java.util.Arrays;import java.util.Collection;@@ -46,7 +45,7 @@ public abstract class AbstractAtomicUpdatesMultivalueTestBase extends EmbeddedSoprotected static void initWithRequestWriter(RequestWriterSupplier requestWriterSupplier)throws Exception {- solrClientTestRule.startSolr(Paths.get(SolrTestCaseJ4.TEST_HOME()));+ solrClientTestRule.startSolr(SolrTestCaseJ4.TEST_HOME());System.setProperty("enable.update.log", "true");SolrTestCaseJ4.newRandomConfig();diff --git a/solr/core/src/test/org/apache/solr/update/processor/AddSchemaFieldsUpdateProcessorFactoryTest.java b/solr/core/src/test/org/apache/solr/update/processor/AddSchemaFieldsUpdateProcessorFactoryTest.javaindex ca19cd3505c..ef470d5e3fc 100644--- a/solr/core/src/test/org/apache/solr/update/processor/AddSchemaFieldsUpdateProcessorFactoryTest.java+++ b/solr/core/src/test/org/apache/solr/update/processor/AddSchemaFieldsUpdateProcessorFactoryTest.java@@ -16,7 +16,8 @@*/package org.apache.solr.update.processor;-import java.io.File;+import java.nio.file.Files;+import java.nio.file.Path;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneOffset;@@ -24,7 +25,8 @@ import java.time.format.DateTimeFormatter;import java.util.Collections;import java.util.Date;import java.util.Locale;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.schema.IndexSchema;@@ -44,15 +46,16 @@ public class AddSchemaFieldsUpdateProcessorFactoryTest extends UpdateProcessorTe@Beforepublic void initManagedSchemaCore() throws Exception {- File tmpSolrHome = createTempDir().toFile();- File tmpConfDir = new File(tmpSolrHome, confDir);- File testHomeConfDir = new File(TEST_HOME(), confDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, SOLRCONFIG_XML), tmpConfDir);- FileUtils.copyFileToDirectory(new File(testHomeConfDir, SCHEMA_XML), tmpConfDir);+ Path tmpSolrHome = createTempDir();+ Path tmpConfDir = FilterPath.unwrap(tmpSolrHome.resolve(confDir));+ Path testHomeConfDir = TEST_HOME().resolve(confDir);+ Files.createDirectories(tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve(SOLRCONFIG_XML), tmpConfDir);+ PathUtils.copyFileToDirectory(testHomeConfDir.resolve(SCHEMA_XML), tmpConfDir);// initCore will trigger an upgrade to managed schema, since the solrconfig*.xml has// <schemaFactory class="ManagedIndexSchemaFactory" ... />- initCore(SOLRCONFIG_XML, SCHEMA_XML, tmpSolrHome.getPath());+ initCore(SOLRCONFIG_XML, SCHEMA_XML, tmpSolrHome);}public void testEmptyValue() {diff --git a/solr/core/src/test/org/apache/solr/util/FileUtilsTest.java b/solr/core/src/test/org/apache/solr/util/FileUtilsTest.javaindex e6e96380026..b8fd09ea9e1 100644--- a/solr/core/src/test/org/apache/solr/util/FileUtilsTest.java+++ b/solr/core/src/test/org/apache/solr/util/FileUtilsTest.java@@ -16,7 +16,7 @@*/package org.apache.solr.util;-import java.io.File;+import java.nio.file.FileSystems;import java.nio.file.Path;import org.apache.solr.SolrTestCase;import org.junit.Test;@@ -64,7 +64,7 @@ public class FileUtilsTest extends SolrTestCase {for (int i = 0; i < pathSegments.length; i++) {sb.append(pathSegments[i]);if (i < pathSegments.length - 1) {- sb.append(File.separator);+ sb.append(FileSystems.getDefault().getSeparator());}}return sb.toString();diff --git a/solr/core/src/test/org/apache/solr/util/TestCborDataFormat.java b/solr/core/src/test/org/apache/solr/util/TestCborDataFormat.javaindex cd4285b19fb..074813c731d 100644--- a/solr/core/src/test/org/apache/solr/util/TestCborDataFormat.java+++ b/solr/core/src/test/org/apache/solr/util/TestCborDataFormat.java@@ -24,7 +24,6 @@ import com.fasterxml.jackson.dataformat.cbor.CBORFactory;import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;@@ -70,9 +69,7 @@ public class TestCborDataFormat extends SolrCloudTestCase {CollectionAdminRequest.createCollection(testCollection, "conf", 1, 1).process(client);modifySchema(testCollection, client);- byte[] b =- Files.readAllBytes(- new File(ExternalPaths.SOURCE_HOME, "example/films/films.json").toPath());+ byte[] b = Files.readAllBytes(ExternalPaths.SOURCE_HOME.resolve("example/films/films.json"));// every operation is performed twice. We should only take the second number// so that we give JVM a chance to optimize that codeindex(testCollection, client, createJsonReq(b), true);@@ -197,7 +194,7 @@ public class TestCborDataFormat extends SolrCloudTestCase {@SuppressWarnings("unchecked")public void test() throws Exception {- Path filmsJson = new File(ExternalPaths.SOURCE_HOME, "example/films/films.json").toPath();+ Path filmsJson = ExternalPaths.SOURCE_HOME.resolve("example/films/films.json");List<Object> films = null;try (InputStream is = Files.newInputStream(filmsJson)) {diff --git a/solr/core/src/test/org/apache/solr/util/TestSystemIdResolver.java b/solr/core/src/test/org/apache/solr/util/TestSystemIdResolver.javaindex 8aea4ba8178..97bd51fe05d 100644--- a/solr/core/src/test/org/apache/solr/util/TestSystemIdResolver.java+++ b/solr/core/src/test/org/apache/solr/util/TestSystemIdResolver.java@@ -16,7 +16,6 @@*/package org.apache.solr.util;-import java.io.File;import java.io.IOException;import java.nio.file.Path;import java.util.Arrays;@@ -50,7 +49,7 @@ public class TestSystemIdResolver extends SolrTestCaseJ4 {final ResourceLoader loader =new SolrResourceLoader(testHome.resolve("collection1"), this.getClass().getClassLoader());final SystemIdResolver resolver = new SystemIdResolver(loader);- final String fileUri = new File(testHome + "/crazy-path-to-config.xml").toURI().toASCIIString();+ final String fileUri = Path.of(testHome + "/crazy-path-to-config.xml").toUri().toASCIIString();assertEquals("solrres:/test.xml", SystemIdResolver.createSystemIdFromResourceName("test.xml"));assertEquals(@@ -58,7 +57,8 @@ public class TestSystemIdResolver extends SolrTestCaseJ4 {SystemIdResolver.createSystemIdFromResourceName("/usr/local/etc/test.xml"));assertEquals("solrres://@/test.xml",- SystemIdResolver.createSystemIdFromResourceName(File.separatorChar + "test.xml"));+ SystemIdResolver.createSystemIdFromResourceName(+ testHome.getFileSystem().getSeparator() + "test.xml"));// check relative URI resolvingassertEquals(diff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/analysis/TestFoldingMultitermExtrasQuery.java b/solr/modules/analysis-extras/src/test/org/apache/solr/analysis/TestFoldingMultitermExtrasQuery.javaindex e5b066263a5..0733cecda72 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/analysis/TestFoldingMultitermExtrasQuery.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/analysis/TestFoldingMultitermExtrasQuery.java@@ -34,10 +34,7 @@ public class TestFoldingMultitermExtrasQuery extends SolrTestCaseJ4 {public static void beforeTests() throws Exception {Path testHome = createTempDir();PathUtils.copyDirectory(getFile("analysis-extras/solr"), testHome);- initCore(- "solrconfig-icucollate.xml",- "schema-folding-extra.xml",- testHome.toAbsolutePath().toString());+ initCore("solrconfig-icucollate.xml", "schema-folding-extra.xml", testHome);int idx = 1;// ICUFoldingFilterFactorydiff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationField.java b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationField.javaindex d66f959c799..de19490f5bc 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationField.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationField.java@@ -35,7 +35,7 @@ public class TestICUCollationField extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {String home = setupSolrHome();- initCore("solrconfig.xml", "schema.xml", home);+ initCore("solrconfig.xml", "schema.xml", Path.of(home));// add some docsassertU(adoc("id", "1", "text", "\u0633\u0627\u0628"));assertU(adoc("id", "2", "text", "I WİLL USE TURKİSH CASING"));diff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldDocValues.java b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldDocValues.javaindex 37c85d9392b..09bd67d885a 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldDocValues.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldDocValues.java@@ -31,7 +31,7 @@ public class TestICUCollationFieldDocValues extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {String home = setupSolrHome();- initCore("solrconfig.xml", "schema.xml", home);+ initCore("solrconfig.xml", "schema.xml", Path.of(home));// add some docsassertU(adoc("id", "1", "text", "\u0633\u0627\u0628"));assertU(adoc("id", "2", "text", "I WİLL USE TURKİSH CASING"));diff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldOptions.java b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldOptions.javaindex 62f1cbea550..25e72d9d822 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldOptions.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldOptions.java@@ -27,10 +27,7 @@ public class TestICUCollationFieldOptions extends SolrTestCaseJ4 {public static void beforeClass() throws Exception {Path testHome = createTempDir();PathUtils.copyDirectory(getFile("analysis-extras/solr"), testHome);- initCore(- "solrconfig-icucollate.xml",- "schema-icucollateoptions.xml",- testHome.toAbsolutePath().toString());+ initCore("solrconfig-icucollate.xml", "schema-icucollateoptions.xml", testHome);// add some docsassertU(adoc("id", "1", "text", "foo-bar"));assertU(adoc("id", "2", "text", "foo bar"));diff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldUDVAS.java b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldUDVAS.javaindex a57a45abee3..9af65f9de65 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldUDVAS.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/schema/TestICUCollationFieldUDVAS.java@@ -16,6 +16,7 @@*/package org.apache.solr.schema;+import java.nio.file.Path;import org.apache.lucene.util.Version;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.SolrException;@@ -75,7 +76,7 @@ public class TestICUCollationFieldUDVAS extends SolrTestCaseJ4 {}try (LogListener warnLog =LogListener.warn(XmlConfigFile.class).substring(ICUCollationField.UDVAS_MESSAGE)) {- initCore("solrconfig.xml", "schema.xml", home);+ initCore("solrconfig.xml", "schema.xml", Path.of(home));switch (mode) {case FAIL:fail("expected failure for version " + useVersion);diff --git a/solr/modules/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java b/solr/modules/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.javaindex 8144bba6cd5..7d61ba45cc0 100644--- a/solr/modules/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java+++ b/solr/modules/analysis-extras/src/test/org/apache/solr/update/processor/TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory.java@@ -30,10 +30,7 @@ public class TestOpenNLPExtractNamedEntitiesUpdateProcessorFactory extends Updatpublic static void beforeClass() throws Exception {Path testHome = createTempDir();PathUtils.copyDirectory(getFile("analysis-extras/solr"), testHome);- initCore(- "solrconfig-opennlp-extract.xml",- "schema-opennlp-extract.xml",- testHome.toAbsolutePath().toString());+ initCore("solrconfig-opennlp-extract.xml", "schema-opennlp-extract.xml", testHome);}@Testdiff --git a/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentDistributedTest.java b/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentDistributedTest.javaindex 003276312e3..f240b9b8640 100644--- a/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentDistributedTest.java+++ b/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentDistributedTest.java@@ -17,6 +17,7 @@package org.apache.solr.handler.clustering;import java.io.IOException;+import java.nio.file.Path;import java.util.List;import java.util.function.Consumer;import java.util.stream.Collectors;@@ -35,8 +36,8 @@ public class ClusteringComponentDistributedTest extends BaseDistributedSearchTesprivate static final String QUERY_TESTSET_SAMPLE_DOCUMENTS = "testSet:sampleDocs";@Override- public String getSolrHome() {- return getFile("clustering/solr/collection1").getParent().toString();+ public Path getSolrHome() {+ return getFile("clustering/solr/collection1").getParent();}@Beforediff --git a/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentTest.java b/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentTest.javaindex 6ff1c63a859..90b264649df 100644--- a/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentTest.java+++ b/solr/modules/clustering/src/test/org/apache/solr/handler/clustering/ClusteringComponentTest.java@@ -57,7 +57,7 @@ public class ClusteringComponentTest extends SolrTestCaseJ4 {public static void beforeClass() throws Exception {Path testHome = createTempDir();PathUtils.copyDirectory(getFile("clustering/solr"), testHome);- initCore("solrconfig.xml", "schema.xml", testHome.toAbsolutePath().toString());+ initCore("solrconfig.xml", "schema.xml", testHome);String[] languages = {"English", "French", "German", "Unknown",diff --git a/solr/modules/cross-dc/src/test/org/apache/solr/crossdc/CrossDCProducerSolrStandaloneTest.java b/solr/modules/cross-dc/src/test/org/apache/solr/crossdc/CrossDCProducerSolrStandaloneTest.javaindex c35adbc17ed..d472d65a62a 100644--- a/solr/modules/cross-dc/src/test/org/apache/solr/crossdc/CrossDCProducerSolrStandaloneTest.java+++ b/solr/modules/cross-dc/src/test/org/apache/solr/crossdc/CrossDCProducerSolrStandaloneTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.crossdc;-import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;@@ -89,7 +88,7 @@ public class CrossDCProducerSolrStandaloneTest extends SolrTestCaseJ4 {Path tmpHome = createTempDir("tmp-home");Path coreDir = tmpHome.resolve(coreName);populateCoreDirectory("configs/cloud-minimal/conf", solrConfigName, coreDir);- initCore("solrconfig.xml", "schema.xml", tmpHome.toAbsolutePath().toString(), coreName);+ initCore("solrconfig.xml", "schema.xml", tmpHome, coreName);return new EmbeddedSolrServer(h.getCoreContainer(), coreName);}@@ -120,13 +119,13 @@ public class CrossDCProducerSolrStandaloneTest extends SolrTestCaseJ4 {Files.createFile(coreDirectory.resolve("core.properties"));// Copy "schema.xml" from the source location to the "conf" subdirectory- File sourceSchemaFile = getFile(Path.of(sourceLocation, "schema.xml").toString()).toFile();+ Path sourceSchemaFile = getFile(Path.of(sourceLocation, "schema.xml").toString());Path targetSchemaPath = subHome.resolve("schema.xml");- Files.copy(sourceSchemaFile.toPath(), targetSchemaPath, StandardCopyOption.REPLACE_EXISTING);+ Files.copy(sourceSchemaFile, targetSchemaPath, StandardCopyOption.REPLACE_EXISTING);// Copy solr config file from the source location to the "conf" subdirectory- File sourceConfigFile = getFile(Path.of(sourceLocation, solrConfigName).toString()).toFile();+ Path sourceConfigFile = getFile(Path.of(sourceLocation, solrConfigName).toString());Path targetConfigPath = subHome.resolve("solrconfig.xml");- Files.copy(sourceConfigFile.toPath(), targetConfigPath, StandardCopyOption.REPLACE_EXISTING);+ Files.copy(sourceConfigFile, targetConfigPath, StandardCopyOption.REPLACE_EXISTING);}}diff --git a/solr/modules/extraction/src/java/org/apache/solr/handler/extraction/ExtractingRequestHandler.java b/solr/modules/extraction/src/java/org/apache/solr/handler/extraction/ExtractingRequestHandler.javaindex 99222c04964..6caef96cf62 100644--- a/solr/modules/extraction/src/java/org/apache/solr/handler/extraction/ExtractingRequestHandler.java+++ b/solr/modules/extraction/src/java/org/apache/solr/handler/extraction/ExtractingRequestHandler.java@@ -16,8 +16,8 @@*/package org.apache.solr.handler.extraction;-import java.io.File;import java.io.InputStream;+import java.nio.file.Path;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.core.SolrCore;@@ -60,7 +60,7 @@ public class ExtractingRequestHandler extends ContentStreamHandlerBaseconfig = new TikaConfig(is);}} else {- File configFile = new File(tikaConfigLoc);+ Path configFile = Path.of(tikaConfigLoc);if (configFile.isAbsolute()) {config = new TikaConfig(configFile);} else { // in conf/diff --git a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTest.java b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTest.javaindex 7ad7ef1dc70..0097b86e818 100644--- a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTest.java+++ b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/ExtractingRequestHandlerTest.java@@ -52,8 +52,7 @@ public class ExtractingRequestHandlerTest extends SolrTestCaseJ4 {false);}- initCore(- "solrconfig.xml", "schema.xml", getFile("extraction/solr").toAbsolutePath().toString());+ initCore("solrconfig.xml", "schema.xml", getFile("extraction/solr"));}@Overridediff --git a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/TestXLSXResponseWriter.java b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/TestXLSXResponseWriter.javaindex 4aa5f9eb09f..a19ba976591 100644--- a/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/TestXLSXResponseWriter.java+++ b/solr/modules/extraction/src/test/org/apache/solr/handler/extraction/TestXLSXResponseWriter.java@@ -47,8 +47,7 @@ public class TestXLSXResponseWriter extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {System.setProperty("enable.update.log", "false");- initCore(- "solrconfig.xml", "schema.xml", getFile("extraction/solr").toAbsolutePath().toString());+ initCore("solrconfig.xml", "schema.xml", getFile("extraction/solr").toAbsolutePath());createIndex();// find a reference to the default response writer so we can redirect its output laterSolrCore testCore = h.getCore();diff --git a/solr/modules/jwt-auth/src/test/org/apache/solr/security/jwt/JWTAuthPluginIntegrationTest.java b/solr/modules/jwt-auth/src/test/org/apache/solr/security/jwt/JWTAuthPluginIntegrationTest.javaindex 3bb08460218..c0a2b418d26 100644--- a/solr/modules/jwt-auth/src/test/org/apache/solr/security/jwt/JWTAuthPluginIntegrationTest.java+++ b/solr/modules/jwt-auth/src/test/org/apache/solr/security/jwt/JWTAuthPluginIntegrationTest.java@@ -106,6 +106,7 @@ public class JWTAuthPluginIntegrationTest extends SolrCloudAuthTestCase {Path tempDir = Files.createTempDirectory(JWTAuthPluginIntegrationTest.class.getSimpleName());tempDir.toFile().deleteOnExit();+Path modifiedP12Cert = tempDir.resolve(p12Cert.getFileName());new KeystoreGenerator().generateKeystore(diff --git a/solr/modules/langid/src/test/org/apache/solr/update/processor/LanguageIdentifierUpdateProcessorFactoryTestCase.java b/solr/modules/langid/src/test/org/apache/solr/update/processor/LanguageIdentifierUpdateProcessorFactoryTestCase.javaindex 4690fc1569c..76581cc88e0 100644--- a/solr/modules/langid/src/test/org/apache/solr/update/processor/LanguageIdentifierUpdateProcessorFactoryTestCase.java+++ b/solr/modules/langid/src/test/org/apache/solr/update/processor/LanguageIdentifierUpdateProcessorFactoryTestCase.java@@ -37,10 +37,7 @@ public abstract class LanguageIdentifierUpdateProcessorFactoryTestCase extends S@BeforeClasspublic static void beforeClass() throws Exception {- initCore(- "solrconfig-languageidentifier.xml",- "schema.xml",- getFile("langid/solr").toAbsolutePath().toString());+ initCore("solrconfig-languageidentifier.xml", "schema.xml", getFile("langid/solr"));SolrCore core = h.getCore();UpdateRequestProcessorChain chained = core.getUpdateProcessingChain("lang_id_tika");assertNotNull(chained);diff --git a/solr/modules/llm/src/test/org/apache/solr/llm/TestLlmBase.java b/solr/modules/llm/src/test/org/apache/solr/llm/TestLlmBase.javaindex 6cd6ed2b5ae..84da95ca3ad 100644--- a/solr/modules/llm/src/test/org/apache/solr/llm/TestLlmBase.java+++ b/solr/modules/llm/src/test/org/apache/solr/llm/TestLlmBase.java@@ -53,8 +53,7 @@ public class TestLlmBase extends RestTestBase {String solrconfig, String schema, boolean buildIndex, boolean persistModelStore)throws Exception {initFolders(persistModelStore);- createJettyAndHarness(- tmpSolrHome.toAbsolutePath().toString(), solrconfig, schema, "/solr", true, null);+ createJettyAndHarness(tmpSolrHome.toAbsolutePath(), solrconfig, schema, "/solr", true, null);if (buildIndex) prepareIndex();}diff --git a/solr/modules/ltr/src/test/org/apache/solr/ltr/TestRerankBase.java b/solr/modules/ltr/src/test/org/apache/solr/ltr/TestRerankBase.javaindex 88a60efea59..4570df1e7a8 100644--- a/solr/modules/ltr/src/test/org/apache/solr/ltr/TestRerankBase.java+++ b/solr/modules/ltr/src/test/org/apache/solr/ltr/TestRerankBase.java@@ -137,7 +137,7 @@ public class TestRerankBase extends RestTestBase {tmpSolrHome = createTempDir();tmpConfDir = tmpSolrHome.resolve(CONF_DIR);tmpConfDir.toFile().deleteOnExit();- PathUtils.copyDirectory(TEST_PATH(), tmpSolrHome.toAbsolutePath());+ PathUtils.copyDirectory(TEST_PATH(), tmpSolrHome);final Path fstore = tmpConfDir.resolve(FEATURE_FILE_NAME);final Path mstore = tmpConfDir.resolve(MODEL_FILE_NAME);@@ -149,13 +149,13 @@ public class TestRerankBase extends RestTestBase {if (Files.exists(fstore)) {if (log.isInfoEnabled()) {- log.info("remove feature store config file in {}", fstore.toAbsolutePath());+ log.info("remove feature store config file in {}", fstore);}Files.delete(fstore);}if (Files.exists(mstore)) {if (log.isInfoEnabled()) {- log.info("remove model store config file in {}", mstore.toAbsolutePath());+ log.info("remove model store config file in {}", mstore);}Files.delete(mstore);}@@ -178,16 +178,14 @@ public class TestRerankBase extends RestTestBase {setupTestInit(solrconfig, schema, false);System.setProperty("enable.update.log", "false");- createJettyAndHarness(- tmpSolrHome.toAbsolutePath().toString(), solrconfig, schema, "/solr", true, null);+ createJettyAndHarness(tmpSolrHome, solrconfig, schema, "/solr", true, null);}public static void setupPersistentTest(String solrconfig, String schema) throws Exception {setupTestInit(solrconfig, schema, true);- createJettyAndHarness(- tmpSolrHome.toAbsolutePath().toString(), solrconfig, schema, "/solr", true, null);+ createJettyAndHarness(tmpSolrHome, solrconfig, schema, "/solr", true, null);}protected static void aftertest() throws Exception {diff --git a/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3BackupRepositoryTest.java b/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3BackupRepositoryTest.javaindex 0a613172723..54fddfae4d6 100644--- a/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3BackupRepositoryTest.java+++ b/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3BackupRepositoryTest.java@@ -19,14 +19,16 @@ package org.apache.solr.s3;import static org.apache.solr.s3.S3BackupRepository.S3_SCHEME;import com.adobe.testing.s3mock.junit4.S3MockRule;-import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URI;import java.net.URISyntaxException;import java.nio.charset.StandardCharsets;-import org.apache.commons.io.FileUtils;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;+import org.apache.commons.io.file.PathUtils;import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.store.BufferedIndexInput;import org.apache.lucene.store.Directory;@@ -173,8 +175,8 @@ public class S3BackupRepositoryTest extends AbstractBackupRepositoryTest {try (S3BackupRepository repo = getRepository()) {// A file on the local disk- File tmp = temporaryFolder.newFolder();- try (OutputStream os = FileUtils.openOutputStream(new File(tmp, "from-file"));+ Path tmp = temporaryFolder.newFolder().toPath();+ try (OutputStream os = PathUtils.newOutputStream(tmp.resolve("from-file"), false);IndexOutput indexOutput = new OutputStreamIndexOutput("", "", os, content.length())) {byte[] bytes = content.getBytes(StandardCharsets.UTF_8);indexOutput.writeBytes(bytes, bytes.length);@@ -182,18 +184,18 @@ public class S3BackupRepositoryTest extends AbstractBackupRepositoryTest {CodecUtil.writeFooter(indexOutput);}- try (Directory sourceDir = newFSDirectory(tmp.toPath())) {+ try (Directory sourceDir = newFSDirectory(tmp)) {repo.copyIndexFileFrom(sourceDir, "from-file", new URI("s3://to-folder"), "to-file");}// Sanity check: we do have different files- File actualSource = new File(tmp, "from-file");- File actualDest = pullObject("to-folder/to-file");+ Path actualSource = tmp.resolve("from-file");+ Path actualDest = pullObject("to-folder/to-file");assertNotEquals(actualSource, actualDest);// Check the copied content- assertTrue(actualDest.isFile());- assertTrue(FileUtils.contentEquals(actualSource, actualDest));+ assertTrue(Files.isRegularFile(actualDest));+ assertTrue(PathUtils.fileContentEquals(actualSource, actualDest));}}@@ -203,23 +205,23 @@ public class S3BackupRepositoryTest extends AbstractBackupRepositoryTest {try (S3BackupRepository repo = getRepository()) {// Local folder for destination- File tmp = temporaryFolder.newFolder();+ Path tmp = temporaryFolder.newFolder().toPath();// Directly create a file on S3pushObject("from-file", content);- try (Directory destDir = newFSDirectory(tmp.toPath())) {+ try (Directory destDir = newFSDirectory(tmp)) {repo.copyIndexFileTo(new URI("s3:///"), "from-file", destDir, "to-file");}// Sanity check: we do have different files- File actualSource = pullObject("from-file");- File actualDest = new File(tmp, "to-file");+ Path actualSource = pullObject("from-file");+ Path actualDest = tmp.resolve("to-file");assertNotEquals(actualSource, actualDest);// Check the copied content- assertTrue(actualDest.isFile());- assertTrue(FileUtils.contentEquals(actualSource, actualDest));+ assertTrue(Files.isRegularFile(actualDest));+ assertTrue(PathUtils.fileContentEquals(actualSource, actualDest));}}@@ -331,11 +333,11 @@ public class S3BackupRepositoryTest extends AbstractBackupRepositoryTest {}}- private File pullObject(String path) throws IOException {+ private Path pullObject(String path) throws IOException {try (S3Client s3 = S3_MOCK_RULE.createS3ClientV2()) {- File file = temporaryFolder.newFile();+ Path file = temporaryFolder.newFile().toPath();InputStream input = s3.getObject(b -> b.bucket(BUCKET_NAME).key(path));- FileUtils.copyInputStreamToFile(input, file);+ Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);return file;}}diff --git a/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3IndexInputTest.java b/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3IndexInputTest.javaindex a52fdab0fb7..56d8c64cc06 100644--- a/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3IndexInputTest.java+++ b/solr/modules/s3-repository/src/test/org/apache/solr/s3/S3IndexInputTest.java@@ -17,14 +17,13 @@package org.apache.solr.s3;import com.carrotsearch.randomizedtesting.generators.RandomStrings;-import java.io.File;-import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.ByteBuffer;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;+import java.nio.file.Path;import org.apache.solr.SolrTestCaseJ4;import org.junit.Rule;import org.junit.Test;@@ -63,19 +62,19 @@ public class S3IndexInputTest extends SolrTestCaseJ4 {private void doTestPartialRead(boolean directBuffer, String content, int slice)throws IOException {- File tmp = temporaryFolder.newFolder();- File file = new File(tmp, "content");- Files.writeString(file.toPath(), content, StandardCharsets.UTF_8);+ Path tmp = temporaryFolder.newFolder().toPath();+ Path file = tmp.resolve("content");+ Files.writeString(file, content, StandardCharsets.UTF_8);- try (SliceInputStream slicedStream = new SliceInputStream(new FileInputStream(file), slice);- S3IndexInput input = new S3IndexInput(slicedStream, "path", file.length())) {+ try (SliceInputStream slicedStream = new SliceInputStream(Files.newInputStream(file), slice);+ S3IndexInput input = new S3IndexInput(slicedStream, "path", Files.size(file))) {// Now read the fileByteBuffer buffer;if (directBuffer) {- buffer = ByteBuffer.allocateDirect((int) file.length());+ buffer = ByteBuffer.allocateDirect((int) Files.size(file));} else {- buffer = ByteBuffer.allocate((int) file.length());+ buffer = ByteBuffer.allocate((int) Files.size(file));}input.readInternal(buffer);diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.javaindex 0433440cb25..ba342128649 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/ScriptUpdateProcessorFactoryTest.java@@ -41,10 +41,7 @@ public class ScriptUpdateProcessorFactoryTest extends UpdateProcessorTestBase {@BeforeClasspublic static void beforeClass() throws Exception {Assume.assumeNotNull((new ScriptEngineManager()).getEngineByExtension("js"));- initCore(- "solrconfig-script-updateprocessor.xml",- "schema.xml",- getFile("scripting/solr").toAbsolutePath().toString());+ initCore("solrconfig-script-updateprocessor.xml", "schema.xml", getFile("scripting/solr"));}/**diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.javaindex c20ef78b620..81351e5b4a9 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/update/TestBadScriptingUpdateProcessorConfig.java@@ -16,6 +16,7 @@*/package org.apache.solr.scripting.update;+import java.nio.file.Path;import java.util.Map;import java.util.regex.Pattern;import javax.script.ScriptEngineManager;@@ -74,7 +75,7 @@ public class TestBadScriptingUpdateProcessorConfig extends SolrTestCaseJ4 {if (null == solrHome) {initCore(solrconfigFile, schemaFile);} else {- initCore(solrconfigFile, schemaFile, solrHome);+ initCore(solrconfigFile, schemaFile, Path.of(solrHome));}CoreContainer cc = h.getCoreContainer();diff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.javaindex f0dd2d85d9d..99a1df06d54 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTOutputWriterTest.java@@ -30,7 +30,7 @@ public class XSLTOutputWriterTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() throws Exception {- initCore("solrconfig.xml", "schema.xml", getFile("scripting/solr").toAbsolutePath().toString());+ initCore("solrconfig.xml", "schema.xml", getFile("scripting/solr"));}@Testdiff --git a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.javaindex 5397780e2e6..4e3eff4b6a5 100644--- a/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java+++ b/solr/modules/scripting/src/test/org/apache/solr/scripting/xslt/XSLTUpdateRequestHandlerTest.java@@ -40,7 +40,7 @@ public class XSLTUpdateRequestHandlerTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeTests() throws Exception {- initCore("solrconfig.xml", "schema.xml", getFile("scripting/solr").toAbsolutePath().toString());+ initCore("solrconfig.xml", "schema.xml", getFile("scripting/solr"));}@Overridediff --git a/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandlerNonCloud.java b/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandlerNonCloud.javaindex 7dd50fcb5e7..ff8a19085a1 100644--- a/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandlerNonCloud.java+++ b/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandlerNonCloud.java@@ -16,8 +16,8 @@*/package org.apache.solr.handler.sql;-import java.io.File;import java.io.IOException;+import java.nio.file.Path;import java.util.ArrayList;import java.util.List;import org.apache.solr.SolrJettyTestBase;@@ -32,17 +32,16 @@ import org.junit.Test;public class TestSQLHandlerNonCloud extends SolrJettyTestBase {- private static File createSolrHome() throws Exception {- File workDir = createTempDir().toFile();+ private static Path createSolrHome() throws Exception {+ Path workDir = createTempDir();setupJettyTestHome(workDir, DEFAULT_TEST_COLLECTION_NAME);return workDir;}@BeforeClasspublic static void beforeClass() throws Exception {- File solrHome = createSolrHome();- solrHome.deleteOnExit();- createAndStartJetty(solrHome.getAbsolutePath());+ Path solrHome = createSolrHome();+ createAndStartJetty(solrHome);}@Testdiff --git a/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/MetricsConfiguration.java b/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/MetricsConfiguration.javaindex 6c4939c3b91..00c52e75434 100644--- a/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/MetricsConfiguration.java+++ b/solr/prometheus-exporter/src/java/org/apache/solr/prometheus/exporter/MetricsConfiguration.java@@ -17,7 +17,6 @@package org.apache.solr.prometheus.exporter;-import java.io.File;import java.io.InputStream;import java.lang.invoke.MethodHandles;import java.nio.file.Files;@@ -101,7 +100,7 @@ public class MetricsConfiguration {MethodHandles.lookup().lookupClass().getClassLoader()- .getResourceAsStream(resource.replace(File.separatorChar, '/'))) {+ .getResourceAsStream(resource.replace(path.getFileSystem().getSeparator(), "/"))) {document = dbf.newDocumentBuilder().parse(configInputStream);}}diff --git a/solr/prometheus-exporter/src/test/org/apache/solr/prometheus/utils/Helpers.java b/solr/prometheus-exporter/src/test/org/apache/solr/prometheus/utils/Helpers.javaindex 6c78149f817..ca14a499e2d 100644--- a/solr/prometheus-exporter/src/test/org/apache/solr/prometheus/utils/Helpers.java+++ b/solr/prometheus-exporter/src/test/org/apache/solr/prometheus/utils/Helpers.java@@ -17,9 +17,11 @@package org.apache.solr.prometheus.utils;-import java.io.File;import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Objects;+import java.util.stream.Stream;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrServerException;@@ -35,16 +37,22 @@ public class Helpers {}public static void indexAllDocs(SolrClient client) throws IOException, SolrServerException {- File exampleDocsDir =- new File(SolrTestCaseJ4.getFile("exampledocs").toAbsolutePath().toString());- File[] xmlFiles =- Objects.requireNonNull(exampleDocsDir.listFiles((dir, name) -> name.endsWith(".xml")));- for (File xml : xmlFiles) {- ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update");- req.addFile(xml.toPath(), "application/xml");- client.request(req, PrometheusExporterTestBase.COLLECTION);+ Path exampleDocsDir = SolrTestCaseJ4.getFile("exampledocs").toAbsolutePath();+ try (Stream<Path> files = Objects.requireNonNull(Files.list(exampleDocsDir))) {+ files+ .filter(xmlFile -> xmlFile.getFileName().toString().endsWith(".xml"))+ .forEach(+ xml -> {+ ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update");+ try {+ req.addFile(xml, "application/xml");+ client.request(req, PrometheusExporterTestBase.COLLECTION);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ });+ client.commit(PrometheusExporterTestBase.COLLECTION);}- client.commit(PrometheusExporterTestBase.COLLECTION);}// Parses a prometheus line into key and value, e.g.diff --git a/solr/solr-ref-guide/modules/deployment-guide/examples/UsingPingRefGuideExamplesTest.java b/solr/solr-ref-guide/modules/deployment-guide/examples/UsingPingRefGuideExamplesTest.javaindex 8c5e0e28f8b..71e3f7b2586 100644--- a/solr/solr-ref-guide/modules/deployment-guide/examples/UsingPingRefGuideExamplesTest.java+++ b/solr/solr-ref-guide/modules/deployment-guide/examples/UsingPingRefGuideExamplesTest.java@@ -16,7 +16,6 @@**/-import java.io.File;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.client.solrj.request.SolrPing;@@ -39,7 +38,7 @@ public class UsingPingRefGuideExamplesTest extends SolrCloudTestCase {@BeforeClasspublic static void setUpCluster() throws Exception {configureCluster(NUM_LIVE_NODES)- .addConfig("conf", new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())+ .addConfig("conf", ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminRequest.createCollection("techproducts", "conf", 1, 1)diff --git a/solr/solr-ref-guide/modules/deployment-guide/examples/UsingSolrJRefGuideExamplesTest.java b/solr/solr-ref-guide/modules/deployment-guide/examples/UsingSolrJRefGuideExamplesTest.javaindex 63a29e71c53..5cf438775a1 100644--- a/solr/solr-ref-guide/modules/deployment-guide/examples/UsingSolrJRefGuideExamplesTest.java+++ b/solr/solr-ref-guide/modules/deployment-guide/examples/UsingSolrJRefGuideExamplesTest.java@@ -17,7 +17,6 @@*/package org.apache.solr.client.ref_guide_examples;-import java.io.File;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.HashMap;@@ -66,7 +65,7 @@ public class UsingSolrJRefGuideExamplesTest extends SolrCloudTestCase {@BeforeClasspublic static void setUpCluster() throws Exception {configureCluster(NUM_LIVE_NODES)- .addConfig("conf", new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())+ .addConfig("conf", ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminResponse response =diff --git a/solr/solr-ref-guide/modules/deployment-guide/examples/ZkConfigFilesTest.java b/solr/solr-ref-guide/modules/deployment-guide/examples/ZkConfigFilesTest.javaindex f3d9c41fb1e..d2bfd9da011 100644--- a/solr/solr-ref-guide/modules/deployment-guide/examples/ZkConfigFilesTest.java+++ b/solr/solr-ref-guide/modules/deployment-guide/examples/ZkConfigFilesTest.java@@ -17,8 +17,7 @@package org.apache.solr.client.ref_guide_examples;-import java.io.File;-import java.nio.file.Paths;+import java.nio.file.Path;import java.util.List;import org.apache.solr.cloud.SolrCloudTestCase;import org.apache.solr.core.ConfigSetService;@@ -64,13 +63,12 @@ public class ZkConfigFilesTest extends SolrCloudTestCase {@Testpublic void testCanUploadConfigToZk() throws Exception {- final String localConfigSetDirectory =- new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).getAbsolutePath();+ final Path localConfigSetDirectory = ExternalPaths.TECHPRODUCTS_CONFIGSET;assertConfigsContainOnly();// tag::zk-configset-upload[]- getConfigSetService().uploadConfig("nameForConfigset", Paths.get(localConfigSetDirectory));+ getConfigSetService().uploadConfig("nameForConfigset", localConfigSetDirectory);// end::zk-configset-upload[]assertConfigsContainOnly("nameForConfigset");diff --git a/solr/solr-ref-guide/modules/indexing-guide/examples/IndexingNestedDocuments.java b/solr/solr-ref-guide/modules/indexing-guide/examples/IndexingNestedDocuments.javaindex de3c4b9cbbd..e6576f655b9 100644--- a/solr/solr-ref-guide/modules/indexing-guide/examples/IndexingNestedDocuments.java+++ b/solr/solr-ref-guide/modules/indexing-guide/examples/IndexingNestedDocuments.java@@ -17,7 +17,6 @@package org.apache.solr.client.ref_guide_examples;-import java.io.File;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@@ -49,7 +48,7 @@ public class IndexingNestedDocuments extends SolrCloudTestCase {configureCluster(1)// when indexing 'anonymous' kids, we need a schema that doesn't use _nest_path_ so// that we can use [child] transformer with a parentFilter...- .addConfig(ANON_KIDS_CONFIG, new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())+ .addConfig(ANON_KIDS_CONFIG, ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();}diff --git a/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiHeatmapFacetingTest.java b/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiHeatmapFacetingTest.javaindex 845913a65d4..3565fd1c8c3 100644--- a/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiHeatmapFacetingTest.java+++ b/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiHeatmapFacetingTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.ref_guide_examples;-import java.io.File;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@@ -54,10 +53,8 @@ public class JsonRequestApiHeatmapFacetingTest extends SolrCloudTestCase {configureCluster(1).addConfig(CONFIG_NAME,- new File(- ExternalPaths.SOURCE_HOME,- "solrj/src/test-files/solrj/solr/configsets/spatial/conf")- .toPath())+ ExternalPaths.SOURCE_HOME.resolve(+ "solrj/src/test-files/solrj/solr/configsets/spatial/conf")).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1)diff --git a/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiTest.java b/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiTest.javaindex 0f3091838a1..2d488589a12 100644--- a/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiTest.java+++ b/solr/solr-ref-guide/modules/query-guide/examples/JsonRequestApiTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.ref_guide_examples;-import java.io.File;import java.util.ArrayList;import java.util.Collection;import java.util.Date;@@ -57,9 +56,7 @@ public class JsonRequestApiTest extends SolrCloudTestCase {@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig(CONFIG_NAME, new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig(CONFIG_NAME, ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1).process(cluster.getSolrClient());diff --git a/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/stream/StreamExpressionTest.java b/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/stream/StreamExpressionTest.javaindex 2433164e365..a7c8d370a88 100644--- a/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/stream/StreamExpressionTest.java+++ b/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/stream/StreamExpressionTest.java@@ -18,11 +18,11 @@ package org.apache.solr.client.solrj.io.stream;import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;import java.io.BufferedWriter;-import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;@@ -4284,25 +4284,27 @@ public class StreamExpressionTest extends SolrCloudTestCase {List<Tuple> tuples = getTuples(solrStream);assertEquals(8, tuples.size());- final String expectedSecondLevel1Path = "directory1" + File.separator + "secondLevel1.txt";+ final Path expectedSecondLevel1Path = Path.of("directory1", "secondLevel1.txt");for (int i = 0; i < 4; i++) {Tuple t = tuples.get(i);assertEquals("secondLevel1.txt line " + (i + 1), t.get("line"));- assertEquals(expectedSecondLevel1Path, t.get("file"));+ assertEquals(expectedSecondLevel1Path.toString(), t.get("file"));}- final String expectedSecondLevel2Path = "directory1" + File.separator + "secondLevel2.txt";+ final Path expectedSecondLevel2Path = Path.of("directory1", "secondLevel2.txt");for (int i = 4; i < 8; i++) {Tuple t = tuples.get(i);assertEquals("secondLevel2.txt line " + (i - 3), t.get("line"));- assertEquals(expectedSecondLevel2Path, t.get("file"));+ assertEquals(expectedSecondLevel2Path.toString(), t.get("file"));}}@Testpublic void testCatStreamMultipleExplicitFiles() throws Exception {final String catStream =- "cat(\"topLevel1.txt,directory1" + File.separator + "secondLevel2.txt\")";+ "cat(\"topLevel1.txt,directory1"+ + FileSystems.getDefault().getSeparator()+ + "secondLevel2.txt\")";ModifiableSolrParams paramsLoc = new ModifiableSolrParams();paramsLoc.set("expr", catStream);paramsLoc.set("qt", "/stream");@@ -4322,11 +4324,11 @@ public class StreamExpressionTest extends SolrCloudTestCase {assertEquals("topLevel1.txt", t.get("file"));}- final String expectedSecondLevel2Path = "directory1" + File.separator + "secondLevel2.txt";+ final Path expectedSecondLevel2Path = Path.of("directory1", "secondLevel2.txt");for (int i = 4; i < 8; i++) {Tuple t = tuples.get(i);assertEquals("secondLevel2.txt line " + (i - 3), t.get("line"));- assertEquals(expectedSecondLevel2Path, t.get("file"));+ assertEquals(expectedSecondLevel2Path.toString(), t.get("file"));}}diff --git a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.javaindex 55ac5cf30a8..ee5c2fe393a 100644--- a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java+++ b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/ZkMaintenanceUtils.java@@ -17,9 +17,9 @@package org.apache.solr.common.cloud;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.FileSystems;import java.nio.file.FileVisitResult;import java.nio.file.Files;import java.nio.file.Path;@@ -180,8 +180,8 @@ public class ZkMaintenanceUtils {// Single file ZK -> local copy where ZK is a leaf nodeif (Files.isDirectory(Paths.get(dst))) {- if (!dst.endsWith(File.separator)) {- dst += File.separator;+ if (!dst.endsWith(FileSystems.getDefault().getSeparator())) {+ dst += FileSystems.getDefault().getSeparator();}dst = normalizeDest(src, dst, srcIsZk, dstIsZk);}@@ -204,8 +204,8 @@ public class ZkMaintenanceUtils {return Paths.get(".").normalize().toAbsolutePath().toString();}- String dstSeparator = (dstIsZk) ? "/" : File.separator;- String srcSeparator = (srcIsZk) ? "/" : File.separator;+ String dstSeparator = (dstIsZk) ? "/" : FileSystems.getDefault().getSeparator();+ String srcSeparator = (srcIsZk) ? "/" : FileSystems.getDefault().getSeparator();// Dest is a directory or non-leaf znode, append last element of the src path.if (dstName.endsWith(dstSeparator)) {@@ -357,7 +357,7 @@ public class ZkMaintenanceUtils {String zkNode = createZkNodeName(zkPath, rootPath, file);try {// if the path exists (and presumably we're uploading data to it) just set its data- if (file.toFile().getName().equals(ZKNODE_DATA_FILE)+ if (file.getFileName().toString().equals(ZKNODE_DATA_FILE)&& zkClient.exists(zkNode, true)) {zkClient.setData(zkNode, file, true);} else if (file == rootPath) {@@ -558,10 +558,11 @@ public class ZkMaintenanceUtils {public static String createZkNodeName(String zkRoot, Path root, Path file) {String relativePath = root.relativize(file).toString();// Windows shenanigans- if ("\\".equals(File.separator)) relativePath = relativePath.replace("\\", "/");+ if ("\\".equals(FileSystems.getDefault().getSeparator()))+ relativePath = relativePath.replace("\\", "/");// It's possible that the relative path and file are the same, in which case// adding the bare slash is A Bad Idea unless it's a non-leaf data node- boolean isNonLeafData = file.toFile().getName().equals(ZKNODE_DATA_FILE);+ boolean isNonLeafData = file.getFileName().toString().equals(ZKNODE_DATA_FILE);if (relativePath.length() == 0 && !isNonLeafData) return zkRoot;// Important to have this check if the source is file:whatever/ and the destination is just zk:/diff --git a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/SolrZkClientTest.java b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/SolrZkClientTest.javaindex 9a3429520c0..0231c1aee1e 100644--- a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/SolrZkClientTest.java+++ b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/SolrZkClientTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.common.cloud;-import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.nio.file.Path;@@ -66,9 +65,7 @@ public class SolrZkClientTest extends SolrCloudTestCase {@Overridepublic void setUp() throws Exception {super.setUp();- configureCluster(1)- .addConfig("_default", new File(ExternalPaths.DEFAULT_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig("_default", ExternalPaths.DEFAULT_CONFIGSET).configure();solrClient =new RandomizingCloudSolrClientBuilder(Collections.singletonList(cluster.getZkServer().getZkAddress()), Optional.empty())diff --git a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkConfigSetService.java b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkConfigSetService.javaindex 9f726035691..ed23cb863a1 100644--- a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkConfigSetService.java+++ b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkConfigSetService.java@@ -20,7 +20,6 @@ import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.security.NoSuchAlgorithmException;import java.util.Arrays;import java.util.List;@@ -218,9 +217,9 @@ public class TestZkConfigSetService extends SolrTestCaseJ4 {@Testpublic void testBootstrapConf() throws IOException, KeeperException, InterruptedException {- String solrHome = legacyExampleCollection1SolrHome();+ Path solrHome = legacyExampleCollection1SolrHome();- CoreContainer cc = new CoreContainer(Paths.get(solrHome), new Properties());+ CoreContainer cc = new CoreContainer(solrHome, new Properties());System.setProperty("zkHost", zkServer.getZkAddress());SolrZkClient zkClient =diff --git a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkMaintenanceUtils.java b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkMaintenanceUtils.javaindex e13004278c0..dae8bf88dba 100644--- a/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkMaintenanceUtils.java+++ b/solr/solrj-zookeeper/src/test/org/apache/solr/common/cloud/TestZkMaintenanceUtils.java@@ -20,7 +20,6 @@ import java.io.FileInputStream;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Path;-import java.nio.file.Paths;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@@ -174,7 +173,7 @@ public class TestZkMaintenanceUtils extends SolrTestCaseJ4 {oneByte[0] = 0x30;zkClient.makePath("/test1byte/one", oneByte, true);- Path tmpDest = Paths.get(createTempDir().toFile().getAbsolutePath(), "MustBeOne");+ Path tmpDest = createTempDir().resolve("MustBeOne");ZkMaintenanceUtils.downloadFromZK(zkClient, "/test1byte/one", tmpDest);try (FileInputStream fis = new FileInputStream(tmpDest.toFile())) {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/GetByIdTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/GetByIdTest.javaindex 1626dc2bbc8..15c7944dd9a 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/GetByIdTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/GetByIdTest.java@@ -36,7 +36,10 @@ public class GetByIdTest extends EmbeddedSolrServerTestBase {public static void beforeClass() throws Exception {solrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();}@Beforediff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/MergeIndexesExampleTestBase.java b/solr/solrj/src/test/org/apache/solr/client/solrj/MergeIndexesExampleTestBase.javaindex 660aa53080b..5187bf5ffec 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/MergeIndexesExampleTestBase.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/MergeIndexesExampleTestBase.java@@ -16,7 +16,6 @@*/package org.apache.solr.client.solrj;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.nio.file.Path;@@ -43,8 +42,8 @@ public abstract class MergeIndexesExampleTestBase extends SolrTestCaseJ4 {protected CoreContainer cores;private String saveProp;- private File dataDir1;- private File dataDir2;+ private Path dataDir1;+ private Path dataDir2;private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());@@ -63,20 +62,20 @@ public abstract class MergeIndexesExampleTestBase extends SolrTestCaseJ4 {saveProp = System.getProperty("solr.directoryFactory");System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory");super.setUp();- File dataDir1 = createTempDir().toFile();+ Path dataDir1 = createTempDir();// setup datadirs- System.setProperty("solr.core0.data.dir", dataDir1.getCanonicalPath());+ System.setProperty("solr.core0.data.dir", dataDir1.toRealPath().toString());- dataDir2 = createTempDir().toFile();+ dataDir2 = createTempDir();- System.setProperty("solr.core1.data.dir", this.dataDir2.getCanonicalPath());+ System.setProperty("solr.core1.data.dir", this.dataDir2.toRealPath().toString());setupCoreContainer();if (log.isInfoEnabled()) {log.info("CORES={} : {}", cores, cores.getLoadedCoreNames());}- cores.getAllowPaths().add(dataDir1.toPath());- cores.getAllowPaths().add(dataDir2.toPath());+ cores.getAllowPaths().add(dataDir1);+ cores.getAllowPaths().add(dataDir2);}@Overridediff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.javaindex cc7f52b4c34..05a5756d931 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java@@ -21,13 +21,13 @@ import static org.hamcrest.CoreMatchers.is;import static org.hamcrest.core.StringContains.containsString;import java.io.ByteArrayInputStream;-import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.lang.invoke.MethodHandles;import java.nio.ByteBuffer;import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;@@ -936,13 +936,13 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {assertEquals(0, rsp.getResults().getNumFound());ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update");- File file = getFile("solrj/books.csv").toFile();+ Path file = getFile("solrj/books.csv");final int opened[] = new int[] {0};final int closed[] = new int[] {0};boolean assertClosed = random().nextBoolean();if (assertClosed) {- byte[] allBytes = Files.readAllBytes(file.toPath());+ byte[] allBytes = Files.readAllBytes(file);ContentStreamBase.ByteArrayStream contentStreamMock =new ContentStreamBase.ByteArrayStream(allBytes, "solrj/books.csv", "application/csv") {@@ -960,7 +960,7 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {};up.addContentStream(contentStreamMock);} else {- up.addFile(file.toPath(), "application/csv");+ up.addFile(file, "application/csv");}up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrSchemalessExampleTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrSchemalessExampleTest.javaindex e66d8362631..df166981431 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrSchemalessExampleTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrSchemalessExampleTest.java@@ -17,14 +17,15 @@package org.apache.solr.client.solrj;import java.io.ByteArrayInputStream;-import java.io.File;import java.io.OutputStreamWriter;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Properties;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;@@ -44,22 +45,23 @@ public class SolrSchemalessExampleTest extends SolrExampleTestsBase {@BeforeClasspublic static void beforeClass() throws Exception {- File tempSolrHome = createTempDir().toFile();+ Path tempSolrHome = createTempDir();// Schemaless renames schema.xml -> schema.xml.bak, and creates + modifies conf/managed-schema,// which violates the test security manager's rules, which disallow writes outside the build// dir, so we copy the example/example-schemaless/solr/ directory to a new temp dir where writes// are allowed.- FileUtils.copyFileToDirectory(new File(ExternalPaths.SERVER_HOME, "solr.xml"), tempSolrHome);- File collection1Dir = new File(tempSolrHome, "collection1");- FileUtils.forceMkdir(collection1Dir);- FileUtils.copyDirectoryToDirectory(new File(ExternalPaths.DEFAULT_CONFIGSET), collection1Dir);+ final Path sourceFile = ExternalPaths.SERVER_HOME.resolve("solr.xml");+ Files.copy(sourceFile, tempSolrHome.resolve("solr.xml"));+ Path collection1Dir = tempSolrHome.resolve("collection1");+ Files.createDirectories(collection1Dir);+ PathUtils.copyDirectory(ExternalPaths.DEFAULT_CONFIGSET, collection1Dir);Properties props = new Properties();props.setProperty("name", "collection1");OutputStreamWriter writer = null;try {writer =new OutputStreamWriter(- FileUtils.openOutputStream(new File(collection1Dir, "core.properties")),+ PathUtils.newOutputStream(collection1Dir.resolve("core.properties"), false),StandardCharsets.UTF_8);props.store(writer, null);} finally {@@ -70,7 +72,7 @@ public class SolrSchemalessExampleTest extends SolrExampleTestsBase {}}}- createAndStartJetty(tempSolrHome.getAbsolutePath());+ createAndStartJetty(tempSolrHome);}@Testdiff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrClient.java b/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrClient.javaindex ec26de0af05..16f56d74ae0 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrClient.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/TestLBHttpSolrClient.java@@ -16,7 +16,6 @@*/package org.apache.solr.client.solrj;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.nio.file.Files;@@ -83,8 +82,7 @@ public class TestLBHttpSolrClient extends SolrTestCaseJ4 {httpClient = HttpClientUtil.createClient(null);for (int i = 0; i < solr.length; i++) {- solr[i] =- new SolrInstance("solr/collection1" + i, createTempDir("instance-" + i).toFile(), 0);+ solr[i] = new SolrInstance("solr/collection1" + i, createTempDir("instance-" + i), 0);solr[i].setUp();solr[i].startJetty();addDocs(solr[i]);@@ -260,19 +258,19 @@ public class TestLBHttpSolrClient extends SolrTestCaseJ4 {private static class SolrInstance {String name;- File homeDir;- File dataDir;- File confDir;+ Path homeDir;+ Path dataDir;+ Path confDir;int port;JettySolrRunner jetty;- public SolrInstance(String name, File homeDir, int port) {+ public SolrInstance(String name, Path homeDir, int port) {this.name = name;this.homeDir = homeDir;this.port = port;- dataDir = new File(homeDir + "/collection1", "data");- confDir = new File(homeDir + "/collection1", "conf");+ dataDir = homeDir.resolve("collection1").resolve("data");+ confDir = homeDir.resolve("collection1").resolve("conf");}public String getHomeDir() {@@ -312,22 +310,22 @@ public class TestLBHttpSolrClient extends SolrTestCaseJ4 {}public void setUp() throws Exception {- homeDir.mkdirs();- dataDir.mkdirs();- confDir.mkdirs();+ Files.createDirectories(homeDir);+ Files.createDirectories(dataDir);+ Files.createDirectories(confDir);- Files.copy(SolrTestCaseJ4.getFile(getSolrXmlFile()), homeDir.toPath().resolve("solr.xml"));+ Files.copy(SolrTestCaseJ4.getFile(getSolrXmlFile()), homeDir.resolve("solr.xml"));- Path f = confDir.toPath().resolve("solrconfig.xml");+ Path f = confDir.resolve("solrconfig.xml");Files.copy(SolrTestCaseJ4.getFile(getSolrConfigFile()), f);- f = confDir.toPath().resolve("schema.xml");+ f = confDir.resolve("schema.xml");Files.copy(SolrTestCaseJ4.getFile(getSchemaFile()), f);- Files.createFile(homeDir.toPath().resolve("collection1/core.properties"));+ Files.createFile(homeDir.resolve("collection1/core.properties"));}public void tearDown() throws Exception {if (jetty != null) jetty.stop();- IOUtils.rm(homeDir.toPath());+ IOUtils.rm(homeDir);}public void startJetty() throws Exception {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/AbstractEmbeddedSolrServerTestCase.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/AbstractEmbeddedSolrServerTestCase.javaindex 98841227f73..5d65ff8725d 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/AbstractEmbeddedSolrServerTestCase.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/AbstractEmbeddedSolrServerTestCase.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.embedded;import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;-import java.io.File;import java.io.IOException;import java.nio.file.Path;import org.apache.commons.io.FileUtils;@@ -47,7 +46,7 @@ public abstract class AbstractEmbeddedSolrServerTestCase extends SolrTestCaseJ4@BeforeClasspublic static void setUpHome() throws IOException {- CONFIG_HOME = getFile("solrj/solr/shared").toAbsolutePath();+ CONFIG_HOME = getFile("solrj/solr/shared");SOLR_HOME = createTempDir("solrHome");FileUtils.copyDirectory(CONFIG_HOME.toFile(), SOLR_HOME.toFile());}@@ -62,13 +61,13 @@ public abstract class AbstractEmbeddedSolrServerTestCase extends SolrTestCaseJ4System.setProperty("coreRootDirectory", "."); // relative to Solr home// The index is always stored within a temporary directory- File tempDir = createTempDir().toFile();+ Path tempDir = createTempDir();- File dataDir = new File(tempDir, "data1");- File dataDir2 = new File(tempDir, "data2");- System.setProperty("dataDir1", dataDir.getAbsolutePath());- System.setProperty("dataDir2", dataDir2.getAbsolutePath());- System.setProperty("tempDir", tempDir.getAbsolutePath());+ Path dataDir = tempDir.resolve("data1");+ Path dataDir2 = tempDir.resolve("data2");+ System.setProperty("dataDir1", dataDir.toString());+ System.setProperty("dataDir2", dataDir2.toString());+ System.setProperty("tempDir", tempDir.toString());SolrTestCaseJ4.newRandomConfig();solrClientTestRule.startSolr(SOLR_HOME);diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/JettyWebappTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/JettyWebappTest.javaindex 024b79b5c1d..edcb3584111 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/JettyWebappTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/JettyWebappTest.java@@ -16,9 +16,10 @@*/package org.apache.solr.client.solrj.embedded;-import java.io.File;import java.io.InputStream;import java.net.URI;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.Locale;import java.util.Random;import org.apache.http.Header;@@ -48,15 +49,15 @@ public class JettyWebappTest extends SolrTestCaseJ4 {@Overridepublic void setUp() throws Exception {super.setUp();- System.setProperty("solr.solr.home", legacyExampleCollection1SolrHome());+ System.setProperty("solr.solr.home", legacyExampleCollection1SolrHome().toString());System.setProperty("tests.shardhandler.randomSeed", Long.toString(random().nextLong()));System.setProperty("solr.tests.doContainerStreamCloseAssert", "false");- File dataDir = createTempDir().toFile();- dataDir.mkdirs();+ Path dataDir = createTempDir();+ Files.createDirectories(dataDir);- System.setProperty("solr.data.dir", dataDir.getCanonicalPath());- String path = ExternalPaths.WEBAPP_HOME;+ System.setProperty("solr.data.dir", dataDir.toRealPath().toString());+ String path = ExternalPaths.WEBAPP_HOME.toString();server = new Server(port);// insecure: only use for tests!!!!diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeBinaryJettyTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeBinaryJettyTest.javaindex 69f5bed712c..632145f4df8 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeBinaryJettyTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeBinaryJettyTest.java@@ -29,6 +29,9 @@ public class LargeVolumeBinaryJettyTest extends LargeVolumeTestBase {public static void beforeTest() throws Exception {solrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();}}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeEmbeddedTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeEmbeddedTest.javaindex 59d867bc17a..e9c473f9572 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeEmbeddedTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeEmbeddedTest.java@@ -25,6 +25,9 @@ public class LargeVolumeEmbeddedTest extends LargeVolumeTestBase {public static void beforeTest() throws Exception {solrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();}}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeJettyTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeJettyTest.javaindex dde40c8d6e3..de56408cb95 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeJettyTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/LargeVolumeJettyTest.java@@ -26,6 +26,9 @@ public class LargeVolumeJettyTest extends LargeVolumeTestBase {// TODOsolrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();}}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateHttp2SolrClientMultiCollectionTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateHttp2SolrClientMultiCollectionTest.javaindex 180a913de33..b285f819cf9 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateHttp2SolrClientMultiCollectionTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateHttp2SolrClientMultiCollectionTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.impl;-import java.io.File;import java.io.IOException;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrQuery;@@ -45,9 +44,7 @@ public class ConcurrentUpdateHttp2SolrClientMultiCollectionTest extends SolrClou@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig("conf", new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig("conf", ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();}@Beforediff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClientMultiCollectionTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClientMultiCollectionTest.javaindex 0dfddb150dc..4227df3f5c8 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClientMultiCollectionTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/ConcurrentUpdateSolrClientMultiCollectionTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.impl;-import java.io.File;import java.io.IOException;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrQuery;@@ -45,9 +44,7 @@ public class ConcurrentUpdateSolrClientMultiCollectionTest extends SolrCloudTest@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig("conf", new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig("conf", ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();}@Beforediff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientProxyTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientProxyTest.javaindex 99ea3af66c1..10dc7930cdf 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientProxyTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/Http2SolrClientProxyTest.java@@ -49,7 +49,8 @@ public class Http2SolrClientProxyTest extends SolrTestCaseJ4 {// Actually only need extremely minimal configSet but just use the defaultsolrClientTestRule.newCollection()- .withConfigSet(ExternalPaths.DEFAULT_CONFIGSET) // TODO should be default for empty home+ .withConfigSet(+ ExternalPaths.DEFAULT_CONFIGSET.toString()) // TODO should be default for empty home.create();}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientConPoolTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientConPoolTest.javaindex 078812f0600..edde231559a 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientConPoolTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/HttpSolrClientConPoolTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.impl;import java.io.IOException;-import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -50,7 +49,7 @@ public class HttpSolrClientConPoolTest extends SolrJettyTestBase {createAndStartJetty(legacyExampleCollection1SolrHome());fooUrl = getBaseUrl();- secondJetty.startSolr(Path.of(legacyExampleCollection1SolrHome()));+ secondJetty.startSolr(legacyExampleCollection1SolrHome());barUrl = secondJetty.getBaseUrl();}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LBHttp2SolrClientIntegrationTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LBHttp2SolrClientIntegrationTest.javaindex fe31f521422..3f24984f90e 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LBHttp2SolrClientIntegrationTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/LBHttp2SolrClientIntegrationTest.java@@ -16,7 +16,6 @@*/package org.apache.solr.client.solrj.impl;-import java.io.File;import java.io.IOException;import java.io.UncheckedIOException;import java.lang.invoke.MethodHandles;@@ -82,8 +81,7 @@ public class LBHttp2SolrClientIntegrationTest extends SolrTestCaseJ4 {super.setUp();for (int i = 0; i < solr.length; i++) {- solr[i] =- new SolrInstance("solr/collection1" + i, createTempDir("instance-" + i).toFile(), 0);+ solr[i] = new SolrInstance("solr/collection1" + i, createTempDir("instance-" + i), 0);solr[i].setUp();solr[i].startJetty();addDocs(solr[i]);@@ -228,19 +226,19 @@ public class LBHttp2SolrClientIntegrationTest extends SolrTestCaseJ4 {private static class SolrInstance {String name;- File homeDir;- File dataDir;- File confDir;+ Path homeDir;+ Path dataDir;+ Path confDir;int port;JettySolrRunner jetty;- public SolrInstance(String name, File homeDir, int port) {+ public SolrInstance(String name, Path homeDir, int port) {this.name = name;this.homeDir = homeDir;this.port = port;- dataDir = new File(homeDir + "/collection1", "data");- confDir = new File(homeDir + "/collection1", "conf");+ dataDir = homeDir.resolve("collection1").resolve("data");+ confDir = homeDir.resolve("collection1").resolve("conf");}public String getHomeDir() {@@ -280,22 +278,22 @@ public class LBHttp2SolrClientIntegrationTest extends SolrTestCaseJ4 {}public void setUp() throws Exception {- homeDir.mkdirs();- dataDir.mkdirs();- confDir.mkdirs();+ Files.createDirectories(homeDir);+ Files.createDirectories(dataDir);+ Files.createDirectories(confDir);- Files.copy(SolrTestCaseJ4.getFile(getSolrXmlFile()), homeDir.toPath().resolve("solr.xml"));+ Files.copy(SolrTestCaseJ4.getFile(getSolrXmlFile()), homeDir.resolve("solr.xml"));- Path f = confDir.toPath().resolve("solrconfig.xml");+ Path f = confDir.resolve("solrconfig.xml");Files.copy(SolrTestCaseJ4.getFile(getSolrConfigFile()), f);- f = confDir.toPath().resolve("schema.xml");+ f = confDir.resolve("schema.xml");Files.copy(SolrTestCaseJ4.getFile(getSchemaFile()), f);- Files.createFile(homeDir.toPath().resolve("collection1/core.properties"));+ Files.createFile(homeDir.resolve("collection1/core.properties"));}public void tearDown() throws Exception {if (jetty != null) jetty.stop();- IOUtils.rm(homeDir.toPath());+ IOUtils.rm(homeDir);}public void startJetty() throws Exception {diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/PreemptiveBasicAuthClientBuilderFactoryTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/PreemptiveBasicAuthClientBuilderFactoryTest.javaindex 8a90f7cf004..0a785dd3dc5 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/impl/PreemptiveBasicAuthClientBuilderFactoryTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/impl/PreemptiveBasicAuthClientBuilderFactoryTest.java@@ -88,8 +88,7 @@ public class PreemptiveBasicAuthClientBuilderFactoryTest extends SolrTestCase {"tmp properties file for PreemptiveBasicAuthClientBuilderFactoryTest.testCredentialsFromConfigFile");}System.setProperty(- PreemptiveBasicAuthClientBuilderFactory.SYS_PROP_HTTP_CLIENT_CONFIG,- f.toFile().getAbsolutePath());+ PreemptiveBasicAuthClientBuilderFactory.SYS_PROP_HTTP_CLIENT_CONFIG, f.toString());PreemptiveBasicAuthClientBuilderFactory.CredentialsResolver credentialsResolver =new PreemptiveBasicAuthClientBuilderFactory.CredentialsResolver();assertEquals("foo", credentialsResolver.defaultParams.get(HttpClientUtil.PROP_BASIC_AUTH_USER));diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/SchemaTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/SchemaTest.javaindex d3169ace898..6502bd2a5ce 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/SchemaTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/SchemaTest.java@@ -20,7 +20,7 @@ import static org.hamcrest.CoreMatchers.anyOf;import static org.hamcrest.CoreMatchers.equalTo;import static org.hamcrest.CoreMatchers.is;-import java.io.File;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -30,7 +30,7 @@ import java.util.Locale;import java.util.Map;import java.util.SortedMap;import java.util.TreeMap;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.impl.BaseHttpSolrClient;import org.apache.solr.client.solrj.request.schema.AnalyzerDefinition;@@ -110,10 +110,8 @@ public class SchemaTest extends RestTestBase {@Beforepublic void init() throws Exception {- File tmpSolrHome = createTempDir().toFile();- FileUtils.copyDirectory(- new File(getFile("solrj/solr/collection1").getParent().toString()),- tmpSolrHome.getAbsoluteFile());+ Path tmpSolrHome = createTempDir();+ PathUtils.copyDirectory(getFile("solrj/solr/collection1").getParent(), tmpSolrHome);final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();@@ -121,12 +119,7 @@ public class SchemaTest extends RestTestBase {System.setProperty("enable.update.log", "false");createJettyAndHarness(- tmpSolrHome.getAbsolutePath(),- "solrconfig-managed-schema.xml",- "schema.xml",- "/solr",- true,- extraServlets);+ tmpSolrHome, "solrconfig-managed-schema.xml", "schema.xml", "/solr", true, extraServlets);}@Afterdiff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.javaindex fc68b2d48e7..86da8b2ab80 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java@@ -20,13 +20,12 @@ import static org.hamcrest.CoreMatchers.notNullValue;import static org.hamcrest.core.Is.is;import com.codahale.metrics.MetricRegistry;-import java.io.File;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Collection;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.lucene.tests.util.LuceneTestCase;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrQuery;@@ -52,13 +51,13 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {public void testConfigSet() throws Exception {SolrClient client = getSolrAdmin();- File testDir = createTempDir(LuceneTestCase.getTestClass().getSimpleName()).toFile();- File newCoreInstanceDir = new File(testDir, "newcore");- cores.getAllowPaths().add(testDir.toPath()); // Allow the test dir+ Path testDir = createTempDir(LuceneTestCase.getTestClass().getSimpleName());+ Path newCoreInstanceDir = testDir.resolve("newcore");+ cores.getAllowPaths().add(testDir); // Allow the test dirCoreAdminRequest.Create req = new CoreAdminRequest.Create();req.setCoreName("corewithconfigset");- req.setInstanceDir(newCoreInstanceDir.getAbsolutePath());+ req.setInstanceDir(newCoreInstanceDir.toString());req.setConfigSet("configset-2");CoreAdminResponse response = req.process(client);@@ -74,20 +73,20 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {try (SolrClient client = getSolrAdmin()) {- File dataDir = createTempDir("data").toFile();+ Path dataDir = createTempDir("data");- File newCoreInstanceDir = createTempDir("instance").toFile();- cores.getAllowPaths().add(dataDir.toPath()); // Allow the test dir- cores.getAllowPaths().add(newCoreInstanceDir.toPath()); // Allow the test dir+ Path newCoreInstanceDir = createTempDir("instance");+ cores.getAllowPaths().add(dataDir); // Allow the test dir+ cores.getAllowPaths().add(newCoreInstanceDir); // Allow the test dir- File instanceDir = cores.getSolrHome().toFile();- FileUtils.copyDirectory(instanceDir, new File(newCoreInstanceDir, "newcore"));+ Path instanceDir = cores.getSolrHome();+ PathUtils.copyDirectory(instanceDir, newCoreInstanceDir.resolve("newcore"));CoreAdminRequest.Create req = new CoreAdminRequest.Create();req.setCoreName("newcore");- req.setInstanceDir(newCoreInstanceDir.getAbsolutePath() + File.separator + "newcore");- req.setDataDir(dataDir.getAbsolutePath());- req.setUlogDir(new File(dataDir, "ulog").getAbsolutePath());+ req.setInstanceDir(newCoreInstanceDir.resolve("newcore").toString());+ req.setDataDir(dataDir.toString());+ req.setUlogDir(dataDir.resolve("ulog").toString());req.setConfigSet("shared");// These should be the inverse of defaults.@@ -97,7 +96,7 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {// Show that the newly-created core has values for load on startup and transient that differ// from defaults due to the above.- File logDir;+ Path logDir;try (SolrCore coreProveIt = cores.getCore("collection1");SolrCore core = cores.getCore("newcore")) {@@ -107,12 +106,10 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {assertFalse(core.getCoreDescriptor().isLoadOnStartup());assertTrue(coreProveIt.getCoreDescriptor().isLoadOnStartup());- logDir = new File(core.getUpdateHandler().getUpdateLog().getTlogDir());+ logDir = Path.of(core.getUpdateHandler().getUpdateLog().getTlogDir());}- assertEquals(- new File(dataDir, "ulog" + File.separator + "tlog").getAbsolutePath(),- logDir.getAbsolutePath());+ assertEquals(dataDir.resolve("ulog").resolve("tlog").toString(), logDir.toString());}}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingEmbeddedTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingEmbeddedTest.javaindex 8103dda8e19..203f115b7a9 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingEmbeddedTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingEmbeddedTest.java@@ -55,7 +55,7 @@ public class DirectJsonQueryRequestFacetingEmbeddedTest extends EmbeddedSolrServsolrClientTestRule.newCollection(COLLECTION_NAME)- .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET)+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString()).create();SolrClient client = solrClientTestRule.getSolrClient(COLLECTION_NAME);diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingIntegrationTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingIntegrationTest.javaindex 7663e44852d..6e0c8b8891b 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingIntegrationTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/DirectJsonQueryRequestFacetingIntegrationTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.request.json;-import java.io.File;import java.util.List;import org.apache.solr.client.solrj.request.AbstractUpdateRequest;import org.apache.solr.client.solrj.request.CollectionAdminRequest;@@ -47,9 +46,7 @@ public class DirectJsonQueryRequestFacetingIntegrationTest extends SolrCloudTest@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig(CONFIG_NAME, new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig(CONFIG_NAME, ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1).process(cluster.getSolrClient());diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.javaindex bb66ef233a1..b6ed7c24958 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestFacetingIntegrationTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.request.json;-import java.io.File;import java.io.IOException;import java.time.Instant;import java.util.Date;@@ -54,9 +53,7 @@ public class JsonQueryRequestFacetingIntegrationTest extends SolrCloudTestCase {@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig(CONFIG_NAME, new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig(CONFIG_NAME, ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1).process(cluster.getSolrClient());diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestHeatmapFacetingTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestHeatmapFacetingTest.javaindex bd62347b434..384983b04fb 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestHeatmapFacetingTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestHeatmapFacetingTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.request.json;-import java.io.File;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@@ -41,10 +40,8 @@ public class JsonQueryRequestHeatmapFacetingTest extends SolrCloudTestCase {configureCluster(1).addConfig(CONFIG_NAME,- new File(- ExternalPaths.SOURCE_HOME,- "solrj/src/test-files/solrj/solr/configsets/spatial/conf")- .toPath())+ ExternalPaths.SOURCE_HOME.resolve(+ "solrj/src/test-files/solrj/solr/configsets/spatial/conf")).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1)diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestIntegrationTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestIntegrationTest.javaindex 203f69189ce..dc516e00f3a 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestIntegrationTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/json/JsonQueryRequestIntegrationTest.java@@ -17,7 +17,6 @@package org.apache.solr.client.solrj.request.json;-import java.io.File;import java.io.IOException;import java.util.Collection;import java.util.HashMap;@@ -49,9 +48,7 @@ public class JsonQueryRequestIntegrationTest extends SolrCloudTestCase {@BeforeClasspublic static void setupCluster() throws Exception {- configureCluster(1)- .addConfig(CONFIG_NAME, new File(ExternalPaths.TECHPRODUCTS_CONFIGSET).toPath())- .configure();+ configureCluster(1).addConfig(CONFIG_NAME, ExternalPaths.TECHPRODUCTS_CONFIGSET).configure();CollectionAdminRequest.createCollection(COLLECTION_NAME, CONFIG_NAME, 1, 1).process(cluster.getSolrClient());diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/response/TermsResponseTest.java b/solr/solrj/src/test/org/apache/solr/client/solrj/response/TermsResponseTest.javaindex 617a72b3bb8..da9c569ef1f 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/response/TermsResponseTest.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/response/TermsResponseTest.java@@ -34,7 +34,10 @@ public class TermsResponseTest extends EmbeddedSolrServerTestBase {public static void beforeClass() throws Exception {solrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();}@Beforediff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/response/TestSpellCheckResponse.java b/solr/solrj/src/test/org/apache/solr/client/solrj/response/TestSpellCheckResponse.javaindex 2f9487a6a3b..23fb77492d4 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/response/TestSpellCheckResponse.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/response/TestSpellCheckResponse.java@@ -43,7 +43,10 @@ public class TestSpellCheckResponse extends EmbeddedSolrServerTestBase {public static void beforeClass() throws Exception {solrClientTestRule.startSolr();- solrClientTestRule.newCollection().withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET).create();+ solrClientTestRule+ .newCollection()+ .withConfigSet(ExternalPaths.TECHPRODUCTS_CONFIGSET.toString())+ .create();client = getSolrClient();}diff --git a/solr/solrj/src/test/org/apache/solr/common/util/ContentStreamTest.java b/solr/solrj/src/test/org/apache/solr/common/util/ContentStreamTest.javaindex 884ebfe1ff0..4d31019bba0 100644--- a/solr/solrj/src/test/org/apache/solr/common/util/ContentStreamTest.java+++ b/solr/solrj/src/test/org/apache/solr/common/util/ContentStreamTest.java@@ -16,14 +16,14 @@*/package org.apache.solr.common.util;-import java.io.File;-import java.io.FileInputStream;-import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;+import java.io.OutputStream;import java.io.Reader;import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;import java.nio.file.Paths;import java.util.zip.GZIPInputStream;import java.util.zip.GZIPOutputStream;@@ -43,21 +43,21 @@ public class ContentStreamTest extends SolrTestCaseJ4 {}public void testFileStream() throws IOException {- File file = new File(createTempDir().toFile(), "README");+ Path file = createTempDir().resolve("README");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file)) {+ OutputStream os = Files.newOutputStream(file)) {assertNotNull(is);is.transferTo(os);}- ContentStreamBase stream = new ContentStreamBase.FileStream(file.toPath());+ ContentStreamBase stream = new ContentStreamBase.FileStream(file);try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);InputStreamReader isr =- new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);+ new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8);Reader r = stream.getReader()) {- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());// Test the code that sets content based on < being the 1st characterassertEquals("application/xml", stream.getContentType());assertTrue(IOUtils.contentEquals(fis, s));@@ -66,24 +66,24 @@ public class ContentStreamTest extends SolrTestCaseJ4 {}public void testFileStreamGZIP() throws IOException {- File file = new File(createTempDir().toFile(), "README.gz");+ Path file = createTempDir().resolve("README.gz");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file);+ OutputStream os = Files.newOutputStream(file);GZIPOutputStream zos = new GZIPOutputStream(os)) {is.transferTo(zos);}- ContentStreamBase stream = new ContentStreamBase.FileStream(file.toPath());+ ContentStreamBase stream = new ContentStreamBase.FileStream(file);try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);GZIPInputStream zis = new GZIPInputStream(fis);InputStreamReader isr = new InputStreamReader(zis, StandardCharsets.UTF_8);- FileInputStream fis2 = new FileInputStream(file);+ InputStream fis2 = Files.newInputStream(file);GZIPInputStream zis2 = new GZIPInputStream(fis2);Reader r = stream.getReader()) {- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());// Test the code that sets content based on < being the 1st characterassertEquals("application/xml", stream.getContentType());assertTrue(IOUtils.contentEquals(isr, r));@@ -92,19 +92,19 @@ public class ContentStreamTest extends SolrTestCaseJ4 {}public void testURLStream() throws IOException {- File file = new File(createTempDir().toFile(), "README");+ Path file = createTempDir().resolve("README");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file)) {+ OutputStream os = Files.newOutputStream(file)) {is.transferTo(os);}- ContentStreamBase stream = new ContentStreamBase.URLStream(file.toURI().toURL());+ ContentStreamBase stream = new ContentStreamBase.URLStream(file.toUri().toURL());try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);- FileInputStream fis2 = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);+ InputStream fis2 = Files.newInputStream(file);InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);Reader r = stream.getReader()) {// For File URLs, the content type is determined automatically by the mime type associated@@ -115,87 +115,87 @@ public class ContentStreamTest extends SolrTestCaseJ4 {//assertEquals("text/html", stream.getContentType());assertTrue(IOUtils.contentEquals(fis2, s));- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());assertTrue(IOUtils.contentEquals(isr, r));- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());}}public void testURLStreamGZIP() throws IOException {- File file = new File(createTempDir().toFile(), "README.gz");+ Path file = createTempDir().resolve("README.gz");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file);+ OutputStream os = Files.newOutputStream(file);GZIPOutputStream zos = new GZIPOutputStream(os)) {is.transferTo(zos);}- ContentStreamBase stream = new ContentStreamBase.URLStream(file.toURI().toURL());+ ContentStreamBase stream = new ContentStreamBase.URLStream(file.toUri().toURL());try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);GZIPInputStream zis = new GZIPInputStream(fis);InputStreamReader isr = new InputStreamReader(zis, StandardCharsets.UTF_8);- FileInputStream fis2 = new FileInputStream(file);+ InputStream fis2 = Files.newInputStream(file);GZIPInputStream zis2 = new GZIPInputStream(fis2);Reader r = stream.getReader()) {// See the non-GZIP test case for an explanation of header handling.assertEquals("application/xml", stream.getContentType());assertTrue(IOUtils.contentEquals(isr, r));assertTrue(IOUtils.contentEquals(zis2, s));- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());}}public void testURLStreamCSVGZIPExtension() throws IOException {- File file = new File(createTempDir().toFile(), "README.CSV.gz");+ Path file = createTempDir().resolve("README.CSV.gz");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file);+ OutputStream os = Files.newOutputStream(file);GZIPOutputStream zos = new GZIPOutputStream(os)) {is.transferTo(zos);}- ContentStreamBase stream = new ContentStreamBase.URLStream(file.toURI().toURL());+ ContentStreamBase stream = new ContentStreamBase.URLStream(file.toUri().toURL());try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);GZIPInputStream zis = new GZIPInputStream(fis);InputStreamReader isr = new InputStreamReader(zis, StandardCharsets.UTF_8);- FileInputStream fis2 = new FileInputStream(file);+ InputStream fis2 = Files.newInputStream(file);GZIPInputStream zis2 = new GZIPInputStream(fis2);Reader r = stream.getReader()) {// See the non-GZIP test case for an explanation of header handling.assertEquals("text/csv", stream.getContentType());assertTrue(IOUtils.contentEquals(isr, r));assertTrue(IOUtils.contentEquals(zis2, s));- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());}}public void testURLStreamJSONGZIPExtension() throws IOException {- File file = new File(createTempDir().toFile(), "README.json.gzip");+ Path file = createTempDir().resolve("README.json.gzip");try (SolrResourceLoader srl = new SolrResourceLoader(Paths.get("").toAbsolutePath());InputStream is = srl.openResource("solrj/README");- FileOutputStream os = new FileOutputStream(file);+ OutputStream os = Files.newOutputStream(file);GZIPOutputStream zos = new GZIPOutputStream(os)) {is.transferTo(zos);}- ContentStreamBase stream = new ContentStreamBase.URLStream(file.toURI().toURL());+ ContentStreamBase stream = new ContentStreamBase.URLStream(file.toUri().toURL());try (InputStream s = stream.getStream();- FileInputStream fis = new FileInputStream(file);+ InputStream fis = Files.newInputStream(file);GZIPInputStream zis = new GZIPInputStream(fis);InputStreamReader isr = new InputStreamReader(zis, StandardCharsets.UTF_8);- FileInputStream fis2 = new FileInputStream(file);+ InputStream fis2 = Files.newInputStream(file);GZIPInputStream zis2 = new GZIPInputStream(fis2);Reader r = stream.getReader()) {// See the non-GZIP test case for an explanation of header handling.assertEquals("application/json", stream.getContentType());assertTrue(IOUtils.contentEquals(isr, r));assertTrue(IOUtils.contentEquals(zis2, s));- assertEquals(file.length(), stream.getSize().longValue());+ assertEquals(Files.size(file), stream.getSize().longValue());}}}diff --git a/solr/solrj/src/test/org/apache/solr/common/util/TestJavaBinCodec.java b/solr/solrj/src/test/org/apache/solr/common/util/TestJavaBinCodec.javaindex 3a85f4e0f04..eb9cc217113 100644--- a/solr/solrj/src/test/org/apache/solr/common/util/TestJavaBinCodec.java+++ b/solr/solrj/src/test/org/apache/solr/common/util/TestJavaBinCodec.java@@ -19,11 +19,12 @@ package org.apache.solr.common.util;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;+import java.io.OutputStream;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.ArrayList;import java.util.Arrays;import java.util.Date;@@ -483,14 +484,14 @@ public class TestJavaBinCodec extends SolrTestCaseJ4 {Object data = generateAllDataTypes();byte[] out = getBytes(data);- FileOutputStream fs = new FileOutputStream(new File(BIN_FILE_LOCATION));+ OutputStream fs = Files.newOutputStream(Path.of(BIN_FILE_LOCATION));BufferedOutputStream bos = new BufferedOutputStream(fs);bos.write(out);bos.close();// Binary file with child documentsSolrDocument sdoc = generateSolrDocumentWithChildDocs();- fs = new FileOutputStream(new File(BIN_FILE_LOCATION_CHILD_DOCS));+ fs = Files.newOutputStream(Path.of(BIN_FILE_LOCATION_CHILD_DOCS));bos = new BufferedOutputStream(fs);bos.write(getBytes(sdoc));bos.close();diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.javaindex 53848e55776..0e156982941 100644--- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java+++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java@@ -16,7 +16,6 @@*/package org.apache.solr;-import java.io.File;import java.io.IOException;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;@@ -45,7 +44,7 @@ import java.util.concurrent.SynchronousQueue;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import javax.servlet.Filter;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.lucene.util.Constants;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrResponse;@@ -175,7 +174,7 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {protected volatile String[] deadServers;protected volatile String shards;protected volatile String[] shardsArr;- protected volatile File testDir;+ protected volatile Path testDir;protected volatile SolrClient controlClient;// to stress with higher thread counts and requests, make sure the junit@@ -252,7 +251,7 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {}/** Subclasses can override this to change a test's solr home (default is in test-files) */- public String getSolrHome() {+ public Path getSolrHome() {return SolrTestCaseJ4.TEST_HOME();}@@ -263,7 +262,7 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {SolrTestCaseJ4.resetExceptionIgnores(); // ignore anything with ignore_exception in itSystem.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");- testDir = createTempDir().toFile();+ testDir = createTempDir();}private volatile boolean distribTearDownCalled = false;@@ -274,19 +273,18 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {}protected JettySolrRunner createControlJetty() throws Exception {- Path jettyHome = testDir.toPath().resolve("control");- File jettyHomeFile = jettyHome.toFile();- seedSolrHome(jettyHomeFile);+ Path jettyHome = testDir.resolve("control");+ seedSolrHome(jettyHome);seedCoreRootDirWithDefaultTestCore(jettyHome.resolve("cores"));JettySolrRunner jetty =- createJetty(jettyHomeFile, null, null, getSolrConfigFile(), getSchemaFile());+ createJetty(jettyHome, null, null, getSolrConfigFile(), getSchemaFile());jetty.start();return jetty;}protected void createServers(int numShards) throws Exception {- System.setProperty("configSetBaseDir", getSolrHome());+ System.setProperty("configSetBaseDir", getSolrHome().toString());controlJetty = createControlJetty();controlClient = createNewSolrClient(controlJetty.getLocalPort());@@ -296,12 +294,10 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {for (int i = 0; i < numShards; i++) {if (sb.length() > 0) sb.append(',');final String shardname = "shard" + i;- Path jettyHome = testDir.toPath().resolve(shardname);- File jettyHomeFile = jettyHome.toFile();- seedSolrHome(jettyHomeFile);+ Path jettyHome = testDir.resolve(shardname);+ seedSolrHome(jettyHome);seedCoreRootDirWithDefaultTestCore(jettyHome.resolve("cores"));- JettySolrRunner j =- createJetty(jettyHomeFile, null, null, getSolrConfigFile(), getSchemaFile());+ JettySolrRunner j = createJetty(jettyHome, null, null, getSolrConfigFile(), getSchemaFile());j.start();jettys.add(j);clients.add(createNewSolrClient(j.getLocalPort()));@@ -382,17 +378,17 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {jettys.clear();}- public JettySolrRunner createJetty(File solrHome, String dataDir) throws Exception {+ public JettySolrRunner createJetty(Path solrHome, String dataDir) throws Exception {return createJetty(solrHome, dataDir, null, null, null);}- public JettySolrRunner createJetty(File solrHome, String dataDir, String shardId)+ public JettySolrRunner createJetty(Path solrHome, String dataDir, String shardId)throws Exception {return createJetty(solrHome, dataDir, shardId, null, null);}public JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,@@ -403,7 +399,7 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {}public JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,@@ -421,11 +417,11 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {if (explicitCoreNodeName) {props.setProperty("coreNodeName", Integer.toString(nodeCnt.incrementAndGet()));}- props.setProperty("coreRootDirectory", solrHome.toPath().resolve("cores").toString());+ props.setProperty("coreRootDirectory", solrHome.resolve("cores").toString());JettySolrRunner jetty =new JettySolrRunner(- solrHome.getAbsolutePath(),+ solrHome.toAbsolutePath().toString(),props,JettyConfig.builder().stopAtShutdown(true)@@ -1175,13 +1171,13 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {* with the contents of {@link #getSolrHome} and ensures that the proper {@link #getSolrXml} file* is in place.*/- protected void seedSolrHome(File jettyHome) throws IOException {- FileUtils.copyDirectory(new File(getSolrHome()), jettyHome);+ protected void seedSolrHome(Path jettyHome) throws IOException {+ PathUtils.copyDirectory(getSolrHome(), jettyHome);String solrxml = getSolrXml();if (solrxml != null) {Files.copy(- Path.of(getSolrHome(), solrxml),- jettyHome.toPath().resolve("solr.xml"),+ getSolrHome().resolve(solrxml),+ jettyHome.resolve("solr.xml"),StandardCopyOption.REPLACE_EXISTING);}}@@ -1203,10 +1199,10 @@ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 {} // else nothing to do, DEFAULT_TEST_CORENAME already exists}- protected void setupJettySolrHome(File jettyHome) throws IOException {+ protected void setupJettySolrHome(Path jettyHome) throws IOException {seedSolrHome(jettyHome);- Files.createDirectories(jettyHome.toPath().resolve("cores").resolve("collection1"));+ Files.createDirectories(jettyHome.resolve("cores").resolve("collection1"));}protected ModifiableSolrParams createParams(Object... q) {diff --git a/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java b/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.javaindex d86de3bab64..52cba9be94d 100644--- a/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrJettyTestBase.java@@ -16,7 +16,7 @@*/package org.apache.solr;-import java.io.File;+import java.nio.file.Files;import java.nio.file.Path;import java.util.Properties;import java.util.SortedMap;@@ -35,7 +35,7 @@ public abstract class SolrJettyTestBase extends SolrTestCaseJ4 {@ClassRule public static SolrJettyTestRule solrClientTestRule = new SolrJettyTestRule();protected static JettySolrRunner createAndStartJetty(- String solrHome,+ Path solrHome,String configFile,String schemaFile,String context,@@ -53,29 +53,29 @@ public abstract class SolrJettyTestBase extends SolrTestCaseJ4 {if (configFile != null) nodeProps.setProperty("solrconfig", configFile);if (schemaFile != null) nodeProps.setProperty("schema", schemaFile);if (System.getProperty("solr.data.dir") == null) {- nodeProps.setProperty("solr.data.dir", createTempDir().toFile().getCanonicalPath());+ nodeProps.setProperty("solr.data.dir", createTempDir().toRealPath().toString());}return createAndStartJetty(solrHome, nodeProps, jettyConfig);}protected static JettySolrRunner createAndStartJetty(- String solrHome, String configFile, String context) throws Exception {+ Path solrHome, String configFile, String context) throws Exception {return createAndStartJetty(solrHome, configFile, null, context, true, null);}- protected static JettySolrRunner createAndStartJetty(String solrHome, JettyConfig jettyConfig)+ protected static JettySolrRunner createAndStartJetty(Path solrHome, JettyConfig jettyConfig)throws Exception {return createAndStartJetty(solrHome, new Properties(), jettyConfig);}- protected static JettySolrRunner createAndStartJetty(String solrHome) throws Exception {+ protected static JettySolrRunner createAndStartJetty(Path solrHome) throws Exception {return createAndStartJetty(solrHome, new Properties(), JettyConfig.builder().build());}protected static JettySolrRunner createAndStartJetty(- String solrHome, Properties nodeProperties, JettyConfig jettyConfig) throws Exception {+ Path solrHome, Properties nodeProperties, JettyConfig jettyConfig) throws Exception {Path coresDir = createTempDir().resolve("cores");@@ -89,9 +89,9 @@ public abstract class SolrJettyTestBase extends SolrTestCaseJ4 {Properties nodeProps = new Properties(nodeProperties);nodeProps.setProperty("coreRootDirectory", coresDir.toString());- nodeProps.setProperty("configSetBaseDir", solrHome);+ nodeProps.setProperty("configSetBaseDir", solrHome.toString());- solrClientTestRule.startSolr(Path.of(solrHome), nodeProps, jettyConfig);+ solrClientTestRule.startSolr(solrHome, nodeProps, jettyConfig);return getJetty();}@@ -133,16 +133,16 @@ public abstract class SolrJettyTestBase extends SolrTestCaseJ4 {// from the test file directory are used, but some also require that the solr.xml file be// explicitly there as of SOLR-4817@Deprecated // Instead use a basic config + whatever is needed or default config- protected static void setupJettyTestHome(File solrHome, String collection) throws Exception {+ protected static void setupJettyTestHome(Path solrHome, String collection) throws Exception {// TODO remove these sys props!System.setProperty("solr.test.sys.prop1", "propone");System.setProperty("solr.test.sys.prop2", "proptwo");copySolrHomeToTemp(solrHome, collection);}- protected static void cleanUpJettyHome(File solrHome) throws Exception {- if (solrHome.exists()) {- PathUtils.deleteDirectory(solrHome.toPath());+ protected static void cleanUpJettyHome(Path solrHome) throws Exception {+ if (Files.exists(solrHome)) {+ PathUtils.deleteDirectory(solrHome);}}}diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCase.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCase.javaindex 909a38479ad..f586044f651 100644--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCase.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCase.java@@ -24,8 +24,9 @@ import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;import com.carrotsearch.randomizedtesting.rules.TestRuleAdapter;-import java.io.File;import java.lang.invoke.MethodHandles;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.List;import java.util.Objects;import java.util.regex.Pattern;@@ -131,15 +132,16 @@ public class SolrTestCase extends LuceneTestCase {existingValue);return;}- final File extPath = new File(ExternalPaths.DEFAULT_CONFIGSET);- if (extPath.canRead(/* implies exists() */ ) && extPath.isDirectory()) {+ final Path extPath = ExternalPaths.DEFAULT_CONFIGSET;+ if (Files.isReadable(extPath /* implies exists() */) && Files.isDirectory(extPath)) {log.info("Setting '{}' system property to test-framework derived value of '{}'",SolrDispatchFilter.SOLR_DEFAULT_CONFDIR_ATTRIBUTE,ExternalPaths.DEFAULT_CONFIGSET);assert null == existingValue;System.setProperty(- SolrDispatchFilter.SOLR_DEFAULT_CONFDIR_ATTRIBUTE, ExternalPaths.DEFAULT_CONFIGSET);+ SolrDispatchFilter.SOLR_DEFAULT_CONFDIR_ATTRIBUTE,+ ExternalPaths.DEFAULT_CONFIGSET.toString());} else {log.warn("System property '{}' is not already set, but test-framework derived value ('{}') either "@@ -151,7 +153,7 @@ public class SolrTestCase extends LuceneTestCase {// set solr.install.dir needed by some test configs outside of the test sandbox (!)if (ExternalPaths.SOURCE_HOME != null) {- System.setProperty("solr.install.dir", ExternalPaths.SOURCE_HOME);+ System.setProperty("solr.install.dir", ExternalPaths.SOURCE_HOME.toString());}if (!TEST_NIGHTLY) {diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.javaindex f7a19e5423c..3fd8bd99c3a 100644--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java@@ -16,7 +16,6 @@*/package org.apache.solr;-import java.io.File;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;@@ -441,13 +440,13 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {private int port = 0;private String solrconfigFile;private String schemaFile;- private File baseDir;+ private Path baseDir;private JettySolrRunner jetty;private SolrClient solrj;private boolean homeCreated = false;- public SolrInstance(File homeDir, String solrconfigFile, String schemaFile) {+ public SolrInstance(Path homeDir, String solrconfigFile, String schemaFile) {this.baseDir = homeDir;this.solrconfigFile = solrconfigFile;this.schemaFile = schemaFile;@@ -484,11 +483,10 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {copyConfFile(baseDir, collection, solrconfigFile);copyConfFile(baseDir, collection, schemaFile);- File collDir = new File(baseDir, collection);+ Path collDir = baseDir.resolve(collection);try (Writer w =new OutputStreamWriter(- Files.newOutputStream(collDir.toPath().resolve("core.properties")),- StandardCharsets.UTF_8)) {+ Files.newOutputStream(collDir.resolve("core.properties")), StandardCharsets.UTF_8)) {Properties coreProps = new Properties();coreProps.put("name", "collection1");coreProps.put("config", solrconfigFile);@@ -507,7 +505,8 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {Properties nodeProperties = new Properties();nodeProperties.setProperty("solrconfig", solrconfigFile);nodeProperties.setProperty(CoreDescriptor.CORE_SCHEMA, schemaFile);- jetty = new JettySolrRunner(baseDir.getAbsolutePath(), nodeProperties, jettyConfig);+ jetty =+ new JettySolrRunner(baseDir.toAbsolutePath().toString(), nodeProperties, jettyConfig);}// silly stuff included from solrconfig.snippet.randomindexconfig.xml@@ -532,17 +531,17 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {}public void tearDown() throws Exception {- IOUtils.deleteFilesIfExist(baseDir.toPath());+ IOUtils.deleteFilesIfExist(baseDir);}- private static void copyConfFile(File dstRoot, String destCollection, String file)+ private static void copyConfFile(Path dstRoot, String destCollection, String file)throws Exception {- Path subHome = dstRoot.toPath().resolve(destCollection).resolve("conf");+ Path subHome = dstRoot.resolve(destCollection).resolve("conf");Path top = SolrTestCaseJ4.TEST_PATH().resolve("collection1").resolve("conf");Files.copy(top.resolve(file), subHome.resolve(file));}- public void copyConfigFile(File dstRoot, String destCollection, String file) throws Exception {+ public void copyConfigFile(Path dstRoot, String destCollection, String file) throws Exception {if (!homeCreated) {createHome();}@@ -568,8 +567,7 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {public SolrInstances(int numServers, String solrconfig, String schema) throws Exception {slist = new ArrayList<>(numServers);for (int i = 0; i < numServers; i++) {- SolrInstance instance =- new SolrInstance(createTempDir("s" + i).toFile(), solrconfig, schema);+ SolrInstance instance = new SolrInstance(createTempDir("s" + i), solrconfig, schema);slist.add(instance);instance.start();}diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.javaindex 7dd7121406e..126698945ee 100644--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java@@ -25,7 +25,6 @@ import static org.hamcrest.core.StringContains.containsString;import com.carrotsearch.randomizedtesting.RandomizedContext;import com.carrotsearch.randomizedtesting.RandomizedTest;import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule;-import java.io.File;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Reader;@@ -43,9 +42,9 @@ import java.lang.invoke.MethodHandles;import java.lang.reflect.InvocationTargetException;import java.net.URL;import java.nio.charset.StandardCharsets;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;-import java.nio.file.Paths;import java.nio.file.StandardCopyOption;import java.security.SecureRandom;import java.time.Instant;@@ -77,6 +76,7 @@ import org.apache.http.client.HttpClient;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.tests.analysis.MockAnalyzer;import org.apache.lucene.tests.analysis.MockTokenizer;+import org.apache.lucene.tests.mockfile.FilterPath;import org.apache.lucene.tests.util.LuceneTestCase;import org.apache.lucene.tests.util.LuceneTestCase.SuppressFileSystems;import org.apache.lucene.tests.util.TestUtil;@@ -158,7 +158,7 @@ import org.xml.sax.SAXException;/*** A junit4 Solr test harness that extends SolrTestCase and, by extension, LuceneTestCase. To change* which core is used when loading the schema and solrconfig.xml, simply invoke the {@link- * #initCore(String, String, String, String)} method.+ * #initCore(String, String, Path, String)} method.*/// ExtrasFS might be ok, the failures with e.g. nightly runs might be "normal"@SuppressFileSystems("ExtrasFS")@@ -532,14 +532,14 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {** @see #initCoreDataDir*/- protected static File initAndGetDataDir() {- File dataDir = initCoreDataDir;+ protected static Path initAndGetDataDir() {+ Path dataDir = initCoreDataDir;if (null == dataDir) {final int id = dataDirCount.incrementAndGet();- dataDir = initCoreDataDir = createTempDir("data-dir-" + id).toFile();+ dataDir = initCoreDataDir = createTempDir("data-dir-" + id);assertNotNull(dataDir);if (log.isInfoEnabled()) {- log.info("Created dataDir: {}", dataDir.getAbsolutePath());+ log.info("Created dataDir: {}", dataDir.toAbsolutePath());}}return dataDir;@@ -567,12 +567,12 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {* Call initCore in @BeforeClass to instantiate a solr core in your test class. deleteCore will be* called for you via SolrTestCaseJ4 @AfterClass*/- public static void initCore(String config, String schema, String solrHome) throws Exception {+ public static void initCore(String config, String schema, Path solrHome) throws Exception {assertNotNull(solrHome);configString = config;schemaString = schema;- testSolrHome = Paths.get(solrHome);- System.setProperty("solr.solr.home", solrHome);+ testSolrHome = solrHome;+ System.setProperty("solr.solr.home", solrHome.toString());initCore();}@@ -580,7 +580,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {* Call initCore in @BeforeClass to instantiate a solr core in your test class. deleteCore will be* called for you via SolrTestCaseJ4 @AfterClass*/- public static void initCore(String config, String schema, String solrHome, String pCoreName)+ public static void initCore(String config, String schema, Path solrHome, String pCoreName)throws Exception {coreName = pCoreName;initCore(config, schema, solrHome);@@ -695,7 +695,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {* @see #initAndGetDataDir()* @deprecated use initAndGetDataDir instead of directly accessing this variable*/- @Deprecated protected static volatile File initCoreDataDir;+ @Deprecated protected static volatile Path initCoreDataDir;/*** Initializes things your test might need@@ -729,7 +729,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {solrConfig = TestHarness.createConfig(testSolrHome, coreName, getSolrConfigFile());h =new TestHarness(- coreName, initAndGetDataDir().getAbsolutePath(), solrConfig, getSchemaFile());+ coreName, initAndGetDataDir().toAbsolutePath().toString(), solrConfig, getSchemaFile());lrf = h.getRequestFactory("", 0, 20, CommonParams.VERSION, "2.2");}@@ -762,7 +762,10 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {System.setProperty("solr.solr.home", solrHome.toAbsolutePath().toString());h =new TestHarness(- "collection1", initAndGetDataDir().getAbsolutePath(), "solrconfig.xml", "schema.xml");+ "collection1",+ initAndGetDataDir().toAbsolutePath().toString(),+ "solrconfig.xml",+ "schema.xml");lrf = h.getRequestFactory("", 0, 20, CommonParams.VERSION, "2.2");return h.getCoreContainer();}@@ -2135,7 +2138,9 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {*/public static Path getFile(String name) {final URL url =- SolrTestCaseJ4.class.getClassLoader().getResource(name.replace(File.separatorChar, '/'));+ SolrTestCaseJ4.class+ .getClassLoader()+ .getResource(name.replace(FileSystems.getDefault().getSeparator(), "/"));if (url != null) {try {return Path.of(url.toURI());@@ -2152,11 +2157,11 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {}throw new RuntimeException("Cannot find resource in classpath or in file-system (relative to CWD): "- + new File(name).getAbsolutePath());+ + Path.of(name).toAbsolutePath());}- public static String TEST_HOME() {- return getFile("solr/collection1").getParent().toString();+ public static Path TEST_HOME() {+ return getFile("solr/collection1").getParent();}public static Path TEST_PATH() {@@ -2179,20 +2184,15 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {return result;}- public static void assertXmlFile(final File file, String... xpath)+ public static void assertXmlFile(final Path file, String... xpath)throws IOException, SAXException {try {- String xml = Files.readString(file.toPath());+ String xml = Files.readString(file);String results = TestHarness.validateXPath(xml, xpath);if (null != results) {String msg =- "File XPath failure: file="- + file.getPath()- + " xpath="- + results- + "\n\nxml was: "- + xml;+ "File XPath failure: file=" + file + " xpath=" + results + "\n\nxml was: " + xml;fail(msg);}} catch (XPathExpressionException e2) {@@ -2235,7 +2235,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {}}- public static void copyMinConf(File dstRoot) throws IOException {+ public static void copyMinConf(Path dstRoot) throws IOException {copyMinConf(dstRoot, null);}@@ -2243,18 +2243,17 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {// the string to write to the core.properties file may be null in which case nothing is done with// it.// propertiesContent may be an empty string, which will actually work.- public static void copyMinConf(File dstRoot, String propertiesContent) throws IOException {+ public static void copyMinConf(Path dstRoot, String propertiesContent) throws IOException {copyMinConf(dstRoot, propertiesContent, "solrconfig-minimal.xml");}- public static void copyMinConf(File dstRoot, String propertiesContent, String solrconfigXmlName)+ public static void copyMinConf(Path dstRoot, String propertiesContent, String solrconfigXmlName)throws IOException {- Path dstPath = dstRoot.toPath();- Path subHome = dstPath.resolve("conf");+ Path subHome = dstRoot.resolve("conf");Files.createDirectories(subHome);if (propertiesContent != null) {- Files.writeString(dstRoot.toPath().resolve(CORE_PROPERTIES_FILENAME), propertiesContent);+ Files.writeString(dstRoot.resolve(CORE_PROPERTIES_FILENAME), propertiesContent);}Path top = SolrTestCaseJ4.TEST_PATH().resolve("collection1").resolve("conf");Files.copy(top.resolve("schema-tiny.xml"), subHome.resolve("schema.xml"));@@ -2265,17 +2264,16 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {}// Creates minimal full setup, including solr.xml- public static void copyMinFullSetup(File dstRoot) throws IOException {- Files.createDirectories(dstRoot.toPath());- Files.copy(- SolrTestCaseJ4.TEST_PATH().resolve("solr.xml"), dstRoot.toPath().resolve("solr.xml"));+ public static void copyMinFullSetup(Path dstRoot) throws IOException {+ Files.createDirectories(dstRoot);+ Files.copy(SolrTestCaseJ4.TEST_PATH().resolve("solr.xml"), dstRoot.resolve("solr.xml"));copyMinConf(dstRoot);}// Just copies the file indicated to the tmp home directory naming it "solr.xml"- public static void copyXmlToHome(File dstRoot, String fromFile) throws IOException {- Files.createDirectories(dstRoot.toPath());- Files.copy(SolrTestCaseJ4.TEST_PATH().resolve(fromFile), dstRoot.toPath().resolve("solr.xml"));+ public static void copyXmlToHome(Path dstRoot, String fromFile) throws IOException {+ Files.createDirectories(dstRoot);+ Files.copy(SolrTestCaseJ4.TEST_PATH().resolve(fromFile), dstRoot.resolve("solr.xml"));}// Creates a consistent configuration, _including_ solr.xml at dstRoot. Creates collection1/conf@@ -2283,13 +2281,13 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {/** Copies the test collection1 config into {@code dstRoot}/{@code collection}/conf */@Deprecated // Instead use a basic config + whatever is needed or default config- public static void copySolrHomeToTemp(File dstRoot, String collection) throws IOException {- Path subHome = dstRoot.toPath().resolve(collection).resolve("conf");+ public static void copySolrHomeToTemp(Path dstRoot, String collection) throws IOException {+ Path subHome = dstRoot.resolve(collection).resolve("conf");Files.createDirectories(subHome);Files.copy(SolrTestCaseJ4.TEST_PATH().resolve("solr.xml"),- dstRoot.toPath().resolve("solr.xml"),+ dstRoot.resolve("solr.xml"),StandardCopyOption.REPLACE_EXISTING);Path top = SolrTestCaseJ4.TEST_PATH().resolve("collection1").resolve("conf");@@ -2312,15 +2310,15 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {/** Creates a temp solr home using sample_techproducts_configs. Returns the home path. */@Deprecated // Instead use a basic config + whatever is needed or default config- public static String legacyExampleCollection1SolrHome() {- String sourceHome = ExternalPaths.SOURCE_HOME;+ public static Path legacyExampleCollection1SolrHome() {+ Path sourceHome = ExternalPaths.SOURCE_HOME;if (sourceHome == null)throw new IllegalStateException("No source home! Cannot create the legacy example solr home directory.");try {- Path tempSolrHome = LuceneTestCase.createTempDir();- Path serverSolr = tempSolrHome.getFileSystem().getPath(sourceHome, "server", "solr");+ Path tempSolrHome = FilterPath.unwrap(LuceneTestCase.createTempDir());+ Path serverSolr = tempSolrHome.resolve(sourceHome).resolve("server").resolve("solr");Files.copy(serverSolr.resolve("solr.xml"), tempSolrHome.resolve("solr.xml"));Path sourceConfig = serverSolr.resolve("configsets").resolve("sample_techproducts_configs");@@ -2337,7 +2335,7 @@ public abstract class SolrTestCaseJ4 extends SolrTestCase {StandardCharsets.UTF_8)) {props.store(writer, null);}- return tempSolrHome.toString();+ return tempSolrHome;} catch (RuntimeException e) {throw e;} catch (IOException e) {diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractBasicDistributedZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractBasicDistributedZkTestBase.javaindex 0cf43b7bf8f..4fcd1b1279f 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractBasicDistributedZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractBasicDistributedZkTestBase.java@@ -1524,7 +1524,7 @@ public abstract class AbstractBasicDistributedZkTestBase extends AbstractFullDisif (shardId == null) {createCmd.setNumShards(2);}- createCmd.setDataDir(getDataDir(createTempDir(collection).toFile().getAbsolutePath()));+ createCmd.setDataDir(getDataDir(createTempDir(collection).toString()));if (shardId != null) {createCmd.setShardId(shardId);}diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.javaindex bc378039ec7..c223ba55c98 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java@@ -18,14 +18,13 @@ package org.apache.solr.cloud;import static java.util.concurrent.TimeUnit.SECONDS;-import java.io.File;import java.lang.invoke.MethodHandles;import java.nio.file.Path;import java.util.Map;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.concurrent.atomic.AtomicInteger;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.solr.BaseDistributedSearchTestCase;import org.apache.solr.cli.ConfigSetUploadTool;import org.apache.solr.cli.DefaultToolRuntime;@@ -69,7 +68,7 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTespublic void distribSetUp() throws Exception {super.distribSetUp();- Path zkDir = testDir.toPath().resolve("zookeeper/server1/data");+ Path zkDir = testDir.resolve("zookeeper/server1/data");zkServer = new ZkTestServer(zkDir);zkServer.run();@@ -100,9 +99,8 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTes@Overrideprotected void createServers(int numShards) throws Exception {// give everyone there own solrhome- File controlHome =- new File(new File(getSolrHome()).getParentFile(), "control" + homeCount.incrementAndGet());- FileUtils.copyDirectory(new File(getSolrHome()), controlHome);+ Path controlHome = getSolrHome().getParent().resolve("control" + homeCount.incrementAndGet());+ PathUtils.copyDirectory(getSolrHome(), controlHome);setupJettySolrHome(controlHome);controlJetty = createJetty(controlHome, null); // let the shardId default to shard1@@ -124,8 +122,7 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTesfor (int i = 1; i <= numShards; i++) {if (sb.length() > 0) sb.append(',');// give everyone there own solrhome- File jettyHome =- new File(new File(getSolrHome()).getParentFile(), "jetty" + homeCount.incrementAndGet());+ Path jettyHome = getSolrHome().getParent().resolve("jetty" + homeCount.incrementAndGet());setupJettySolrHome(jettyHome);JettySolrRunner j = createJetty(jettyHome, null, "shard" + (i + 2));j.start();@@ -388,11 +385,11 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTesPath configSetDir, String srcConfigSet, String dstConfigName, String zkAddr)throws Exception {- File fullConfDir = new File(configSetDir.toFile(), srcConfigSet);+ Path fullConfDir = configSetDir.resolve(srcConfigSet);String[] args =new String[] {"--conf-name", dstConfigName,- "--conf-dir", fullConfDir.getAbsolutePath(),+ "--conf-dir", fullConfDir.toAbsolutePath().toString(),"-z", zkAddr};diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.javaindex edbf20dc519..681bf7152e5 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java@@ -19,10 +19,10 @@ package org.apache.solr.cloud;import static org.apache.solr.common.cloud.ZkStateReader.HTTPS;import static org.apache.solr.common.cloud.ZkStateReader.URL_SCHEME;-import java.io.File;import java.io.IOException;import java.lang.invoke.MethodHandles;import java.net.URI;+import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Collection;@@ -340,7 +340,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes@Overrideprotected void createServers(int numServers) throws Exception {- File controlJettyDir = createTempDir("control").toFile();+ Path controlJettyDir = createTempDir("control");setupJettySolrHome(controlJettyDir);controlJetty =createJetty(@@ -457,9 +457,9 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesif (sb.length() > 0) sb.append(',');int cnt = this.jettyIntCntr.incrementAndGet();- File jettyDir = createTempDir("shard-" + i).toFile();+ Path jettyDir = createTempDir("shard-" + i);- jettyDir.mkdirs();+ Files.createDirectories(jettyDir);setupJettySolrHome(jettyDir);int currentI = i;if (numOtherReplicas > 0) {@@ -743,7 +743,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesprops.setProperty("solr.ulog.dir", ulogDir);props.setProperty("solrconfig", solrConfigOverride);- JettySolrRunner jetty = new JettySolrRunner(getSolrHome(), props, jettyconfig);+ JettySolrRunner jetty = new JettySolrRunner(getSolrHome().toString(), props, jettyconfig);jetty.start();@@ -752,7 +752,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes@Overridepublic final JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,@@ -762,7 +762,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes}public JettySolrRunner createJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,@@ -791,9 +791,9 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes} else if (random().nextBoolean()) {props.setProperty("replicaType", Replica.Type.NRT.toString());}- props.setProperty("coreRootDirectory", solrHome.toPath().resolve("cores").toString());+ props.setProperty("coreRootDirectory", solrHome.resolve("cores").toString());- JettySolrRunner jetty = new JettySolrRunner(solrHome.getPath(), props, jettyconfig);+ JettySolrRunner jetty = new JettySolrRunner(solrHome.toString(), props, jettyconfig);return jetty;}@@ -803,7 +803,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes* us the ability to simulate network partitions without having to fuss with IPTables.*/public JettySolrRunner createProxiedJetty(- File solrHome,+ Path solrHome,String dataDir,String shardList,String solrConfigOverride,@@ -828,9 +828,9 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes} else if (random().nextBoolean()) {props.setProperty("replicaType", Replica.Type.NRT.toString());}- props.setProperty("coreRootDirectory", solrHome.toPath().resolve("cores").toString());+ props.setProperty("coreRootDirectory", solrHome.resolve("cores").toString());- JettySolrRunner jetty = new JettySolrRunner(solrHome.getPath(), props, jettyconfig, true);+ JettySolrRunner jetty = new JettySolrRunner(solrHome.toString(), props, jettyconfig, true);return jetty;}@@ -883,26 +883,24 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesreturn null;}- private File getRelativeSolrHomePath(File solrHome) {- final Path solrHomePath = solrHome.toPath();- final Path curDirPath = new File("").getAbsoluteFile().toPath();+ private Path getRelativeSolrHomePath(Path solrHome) {+ final Path curDirPath = Path.of("").toAbsolutePath();- if (!solrHomePath.getRoot().equals(curDirPath.getRoot())) {+ if (!solrHome.getRoot().equals(curDirPath.getRoot())) {// root of current directory and solrHome are not the same, therefore cannot relativizereturn solrHome;}- final Path root = solrHomePath.getRoot();+ final Path root = solrHome.getRoot();// relativize current directory to root: /tmp/foo -> /tmp/foo/../..- final File relativizedCurDir =- new File(curDirPath.toFile(), curDirPath.relativize(root).toString());+ final Path relativizedCurDir = curDirPath.resolve(curDirPath.relativize(root));// exclude the root from solrHome: /tmp/foo/solrHome -> tmp/foo/solrHome- final Path solrHomeRelativeToRoot = root.relativize(solrHomePath);+ final Path solrHomeRelativeToRoot = root.relativize(solrHome);// create the relative solrHome: /tmp/foo/../../tmp/foo/solrHome- return new File(relativizedCurDir, solrHomeRelativeToRoot.toString()).getAbsoluteFile();+ return relativizedCurDir.resolve(solrHomeRelativeToRoot).toAbsolutePath();}protected void updateMappingsFromZk(List<JettySolrRunner> jettys, List<SolrClient> clients)diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java b/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.javaindex 2cd9795b714..7f9a05229e8 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/MiniSolrCloudCluster.java@@ -19,7 +19,6 @@ package org.apache.solr.cloud;import static org.apache.solr.core.ConfigSetProperties.DEFAULT_FILENAME;import com.codahale.metrics.MetricRegistry;-import java.io.File;import java.io.IOException;import java.io.PrintStream;import java.lang.invoke.MethodHandles;@@ -968,7 +967,7 @@ public class MiniSolrCloudCluster {}}- public void dumpMetrics(File outputDirectory, String fileName) throws IOException {+ public void dumpMetrics(Path outputDirectory, String fileName) throws IOException {for (JettySolrRunner jetty : jettys) {jetty.outputMetrics(outputDirectory, fileName);}diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractBackupRepositoryTest.java b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractBackupRepositoryTest.javaindex 56db52cc9cb..6a49e940164 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractBackupRepositoryTest.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractBackupRepositoryTest.java@@ -22,18 +22,18 @@ import static org.apache.lucene.codecs.CodecUtil.writeBEInt;import static org.apache.lucene.codecs.CodecUtil.writeBELong;import static org.apache.solr.core.backup.repository.DelegatingBackupRepository.PARAM_DELEGATE_REPOSITORY_NAME;-import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.net.URI;import java.net.URISyntaxException;import java.nio.charset.StandardCharsets;+import java.nio.file.Path;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;-import org.apache.commons.io.FileUtils;+import org.apache.commons.io.file.PathUtils;import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FilterDirectory;@@ -286,10 +286,10 @@ public abstract class AbstractBackupRepositoryTest extends SolrTestCaseJ4 {Collections.shuffle(Arrays.asList(plugins), random());// Given a file on the local disk with an invalid checksum (e.g. could be encrypted).- File sourceDir = createTempDir().toFile();+ Path sourceDir = createTempDir();String fileName = "source-file";String content = "content";- try (OutputStream os = FileUtils.openOutputStream(new File(sourceDir, fileName));+ try (OutputStream os = PathUtils.newOutputStream(sourceDir.resolve(fileName), false);IndexOutput io = new OutputStreamIndexOutput("", "", os, Long.BYTES)) {byte[] bytes = content.getBytes(StandardCharsets.UTF_8);io.writeBytes(bytes, bytes.length);@@ -301,14 +301,14 @@ public abstract class AbstractBackupRepositoryTest extends SolrTestCaseJ4 {}BackupRepositoryFactory repoFactory = new BackupRepositoryFactory(plugins);- try (SolrResourceLoader resourceLoader = new SolrResourceLoader(sourceDir.toPath())) {+ try (SolrResourceLoader resourceLoader = new SolrResourceLoader(sourceDir)) {// When we copy the local file with the standard BackupRepository,// then it fails because the checksum is invalid.expectThrows(CorruptIndexException.class,() -> copyFileToRepo(sourceDir, fileName, repoName, repoFactory, resourceLoader));- File destinationDir = createTempDir().toFile();+ Path destinationDir = createTempDir();expectThrows(CorruptIndexException.class,() ->@@ -329,30 +329,30 @@ public abstract class AbstractBackupRepositoryTest extends SolrTestCaseJ4 {}private void copyFileToRepo(- File dir,+ Path dir,String fileName,String repoName,BackupRepositoryFactory repoFactory,SolrResourceLoader resourceLoader)throws IOException, URISyntaxException {try (BackupRepository repo = repoFactory.newInstance(resourceLoader, repoName);- Directory directory = newFSDirectory(dir.toPath())) {+ Directory directory = newFSDirectory(dir)) {URI destinationDir = repo.resolve(getBaseUri(), "destination-folder");repo.copyIndexFileFrom(directory, fileName, destinationDir, fileName);}}private void copyFileToDir(- File sourceDir,+ Path sourceDir,String fileName,- File destinationDir,+ Path destinationDir,String repoName,BackupRepositoryFactory repoFactory,SolrResourceLoader resourceLoader)throws IOException {try (BackupRepository repo = repoFactory.newInstance(resourceLoader, repoName);- Directory sourceDirectory = newFSDirectory(sourceDir.toPath());- Directory destinationDirectory = newFSDirectory(destinationDir.toPath())) {+ Directory sourceDirectory = newFSDirectory(sourceDir);+ Directory destinationDirectory = newFSDirectory(destinationDir)) {repo.copyIndexFileFrom(sourceDirectory, fileName, destinationDirectory, fileName);}}diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.javaindex 2b1973a09ec..0cc34c59d72 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractCollectionsAPIDistributedZkTestBase.java@@ -146,7 +146,7 @@ public abstract class AbstractCollectionsAPIDistributedZkTestBase extends SolrCl.setCreateNodeSet("").process(cluster.getSolrClient()).getStatus());- String dataDir = createTempDir().toFile().getAbsolutePath();+ String dataDir = createTempDir().toString();// create a core that simulates something left over from a partially-deleted collectionassertTrue(CollectionAdminRequest.addReplicaToShard(collectionName, "shard1")@@ -523,7 +523,7 @@ public abstract class AbstractCollectionsAPIDistributedZkTestBase extends SolrCl"Could not find expected core.properties file",Files.exists(instancedir.resolve("core.properties")));- Path expected = Paths.get(jetty.getSolrHome()).toAbsolutePath().resolve(core.getName());+ Path expected = Paths.get(jetty.getSolrHome()).resolve(core.getName());assertTrue("Expected: " + expected + "\nFrom core stats: " + instancedir,diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractInstallShardTest.java b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractInstallShardTest.javaindex b12f579bf3f..ecac1c49464 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractInstallShardTest.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/api/collections/AbstractInstallShardTest.java@@ -21,6 +21,7 @@ import static org.apache.solr.client.solrj.request.CollectionAdminRequest.deleteimport java.lang.invoke.MethodHandles;import java.net.URI;+import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Collection;@@ -290,12 +291,12 @@ public abstract class AbstractInstallShardTest extends SolrCloudTestCase {.get();final CoreDescriptor cd = cc.getCoreDescriptor(coreName);final Path coreInstanceDir = cd.getInstanceDir();- assert coreInstanceDir.toFile().exists();- assert coreInstanceDir.toFile().isDirectory();+ assert Files.exists(coreInstanceDir);+ assert Files.isDirectory(coreInstanceDir);final Path coreIndexDir = coreInstanceDir.resolve("data").resolve("index");- assert coreIndexDir.toFile().exists();- assert coreIndexDir.toFile().isDirectory();+ assert Files.exists(coreIndexDir);+ assert Files.isDirectory(coreIndexDir);try (final BackupRepository backupRepository = cc.newBackupRepository(BACKUP_REPO_NAME);final SolrCore core = cc.getCore(coreName)) {diff --git a/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java b/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.javaindex 30b51c150a4..a7db8a4667c 100644--- a/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/core/AbstractBadConfigTestBase.java@@ -16,6 +16,7 @@*/package org.apache.solr.core;+import java.nio.file.Path;import java.util.Map;import java.util.regex.Pattern;import org.apache.solr.SolrTestCaseJ4;@@ -51,7 +52,7 @@ public abstract class AbstractBadConfigTestBase extends SolrTestCaseJ4 {if (null == solrHome) {initCore(solrconfigFile, schemaFile);} else {- initCore(solrconfigFile, schemaFile, solrHome);+ initCore(solrconfigFile, schemaFile, Path.of(solrHome));}CoreContainer cc = h.getCoreContainer();diff --git a/solr/test-framework/src/java/org/apache/solr/core/MockDirectoryFactory.java b/solr/test-framework/src/java/org/apache/solr/core/MockDirectoryFactory.javaindex 7e20d4b4241..4ba58c5645b 100644--- a/solr/test-framework/src/java/org/apache/solr/core/MockDirectoryFactory.java+++ b/solr/test-framework/src/java/org/apache/solr/core/MockDirectoryFactory.java@@ -16,8 +16,8 @@*/package org.apache.solr.core;-import java.io.File;import java.io.IOException;+import java.nio.file.Path;import org.apache.lucene.store.Directory;import org.apache.lucene.store.LockFactory;import org.apache.lucene.store.NRTCachingDirectory;@@ -90,6 +90,6 @@ public class MockDirectoryFactory extends EphemeralDirectoryFactory {public boolean isAbsolute(String path) {// TODO: kind of a hack - we don't know what the delegate is, so// we treat it as file based since this works on most ephem impls- return new File(path).isAbsolute();+ return Path.of(path).isAbsolute();}}diff --git a/solr/test-framework/src/java/org/apache/solr/core/MockFSDirectoryFactory.java b/solr/test-framework/src/java/org/apache/solr/core/MockFSDirectoryFactory.javaindex b130a0bc877..30f8cdd266c 100644--- a/solr/test-framework/src/java/org/apache/solr/core/MockFSDirectoryFactory.java+++ b/solr/test-framework/src/java/org/apache/solr/core/MockFSDirectoryFactory.java@@ -16,7 +16,6 @@*/package org.apache.solr.core;-import java.io.File;import java.io.IOException;import java.nio.file.Path;import org.apache.lucene.store.Directory;@@ -53,7 +52,7 @@ public class MockFSDirectoryFactory extends StandardDirectoryFactory {public boolean isAbsolute(String path) {// TODO: kind of a hack - we don't know what the delegate is, so// we treat it as file based since this works on most ephem impls- return new File(path).isAbsolute();+ return Path.of(path).isAbsolute();}private Directory reduce(Directory dir) {diff --git a/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java b/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.javaindex 7d121096a36..49e2f3139fc 100644--- a/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java+++ b/solr/test-framework/src/java/org/apache/solr/embedded/JettySolrRunner.java@@ -19,7 +19,6 @@ package org.apache.solr.embedded;import com.codahale.metrics.ConsoleReporter;import com.codahale.metrics.MetricFilter;import com.codahale.metrics.MetricRegistry;-import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.io.PrintStream;@@ -673,11 +672,11 @@ public class JettySolrRunner {}}- public void outputMetrics(File outputDirectory, String fileName) throws IOException {+ public void outputMetrics(Path outputDirectory, String fileName) throws IOException {if (getCoreContainer() != null) {if (outputDirectory != null) {- Path outDir = outputDirectory.toPath();+ Path outDir = outputDirectory;Files.createDirectories(outDir);}@@ -690,7 +689,7 @@ public class JettySolrRunner {outputDirectory == null? new PrintStream(OutputStream.nullOutputStream(), false, StandardCharsets.UTF_8): new PrintStream(- new File(outputDirectory, registryName + "_" + fileName),+ outputDirectory.resolve(registryName + "_" + fileName).toString(),StandardCharsets.UTF_8)) {ConsoleReporter reporter =ConsoleReporter.forRegistry(metricsRegisty)diff --git a/solr/test-framework/src/java/org/apache/solr/util/ExternalPaths.java b/solr/test-framework/src/java/org/apache/solr/util/ExternalPaths.javaindex 8d21f9e3e84..9d5f82a2408 100644--- a/solr/test-framework/src/java/org/apache/solr/util/ExternalPaths.java+++ b/solr/test-framework/src/java/org/apache/solr/util/ExternalPaths.java@@ -16,8 +16,9 @@*/package org.apache.solr.util;-import java.io.File;import java.net.URL;+import java.nio.file.Files;+import java.nio.file.Path;/*** Some tests need to reach outside the classpath to get certain resources (e.g. the example@@ -35,55 +36,56 @@ public class ExternalPaths {* <p>Note that all other static paths available in this class are derived from the source home,* and if it is null, those paths will just be relative to 'null' and may not be meaningful.*/- public static final String SOURCE_HOME = determineSourceHome();+ public static final Path SOURCE_HOME = determineSourceHome();/*** @see #SOURCE_HOME*/- public static String WEBAPP_HOME = new File(SOURCE_HOME, "webapp/web").getAbsolutePath();+ public static Path WEBAPP_HOME = SOURCE_HOME.resolve("webapp/web").toAbsolutePath();/*** @see #SOURCE_HOME*/- public static String DEFAULT_CONFIGSET =- new File(SOURCE_HOME, "server/solr/configsets/_default/conf").getAbsolutePath();+ public static Path DEFAULT_CONFIGSET =+ SOURCE_HOME.resolve("server/solr/configsets/_default/conf").toAbsolutePath();/*** @see #SOURCE_HOME*/- public static String TECHPRODUCTS_CONFIGSET =- new File(SOURCE_HOME, "server/solr/configsets/sample_techproducts_configs/conf")- .getAbsolutePath();+ public static Path TECHPRODUCTS_CONFIGSET =+ SOURCE_HOME+ .resolve("server/solr/configsets/sample_techproducts_configs/conf")+ .toAbsolutePath();/*** @see #SOURCE_HOME*/- public static String SERVER_HOME = new File(SOURCE_HOME, "server/solr").getAbsolutePath();+ public static Path SERVER_HOME = SOURCE_HOME.resolve("server/solr").toAbsolutePath();/*** Ugly, ugly hack to determine the example home without depending on the CWD this is needed for* example/multicore tests which reside outside the classpath. if the source home can't be* determined, this method returns null.*/- static String determineSourceHome() {+ static Path determineSourceHome() {try {- File file = new File("solr/conf");- if (!file.exists()) {+ Path file = Path.of("solr/conf");+ if (!Files.exists(file)) {URL resourceUrl = ExternalPaths.class.getClassLoader().getResource("solr/conf");if (resourceUrl != null) {- file = new File(resourceUrl.toURI());+ file = Path.of(resourceUrl.toURI());} else {// If there is no "solr/conf" in the classpath, fall back to searching from the current// directory.- file = new File(System.getProperty("tests.src.home", "."));+ file = Path.of(System.getProperty("tests.src.home", "."));}}- File base = file.getAbsoluteFile();- while (!(new File(base, "solr/CHANGES.txt").exists()) && null != base) {- base = base.getParentFile();+ Path base = file.toAbsolutePath();+ while (!Files.exists(base.resolve("solr/CHANGES.txt")) && null != base) {+ base = base.getParent();}- return (null == base) ? null : new File(base, "solr/").getAbsolutePath();+ return (null == base) ? null : base.resolve("solr/").toAbsolutePath();} catch (Exception e) {// all bets are offreturn null;diff --git a/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java b/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.javaindex 4b0eb19eaad..d65086e5a72 100644--- a/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/util/RestTestBase.java@@ -18,6 +18,7 @@ package org.apache.solr.util;import java.io.IOException;import java.lang.invoke.MethodHandles;+import java.nio.file.Path;import java.util.Map;import java.util.SortedMap;import javax.xml.xpath.XPathExpressionException;@@ -46,7 +47,7 @@ public abstract class RestTestBase extends SolrJettyTestBase {}public static void createJettyAndHarness(- String solrHome,+ Path solrHome,String configFile,String schemaFile,String context,