瀏覽代碼

Ban java.io.File in tests.

Restrict use of java.io.File to 5 methods (excluded), but otherwise ban.
This is a prerequisite to do any mocking here.

I don't try to do any heavy cleanup on these tests, I am not familiar with them.
So this is mostly a rote straightforward conversion.

Closes #8836
Robert Muir 11 年之前
父節點
當前提交
39186edc86
共有 56 個文件被更改,包括 623 次插入560 次删除
  1. 11 5
      dev-tools/forbidden/all-signatures.txt
  2. 0 14
      dev-tools/forbidden/core-signatures.txt
  3. 4 0
      pom.xml
  4. 2 2
      src/test/java/org/elasticsearch/benchmark/common/lucene/uidscan/LuceneUidScanBenchmark.java
  5. 5 17
      src/test/java/org/elasticsearch/benchmark/fs/FsAppendBenchmark.java
  6. 7 17
      src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java
  7. 2 1
      src/test/java/org/elasticsearch/bwcompat/StaticIndexBackwardCompatibilityTest.java
  8. 3 2
      src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityUponUpgradeTests.java
  9. 5 5
      src/test/java/org/elasticsearch/common/ChannelsTests.java
  10. 2 2
      src/test/java/org/elasticsearch/common/PidFileTests.java
  11. 1 1
      src/test/java/org/elasticsearch/common/blobstore/BlobStoreTest.java
  12. 13 12
      src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTest.java
  13. 2 3
      src/test/java/org/elasticsearch/common/io/FileSystemUtilsTests.java
  14. 6 5
      src/test/java/org/elasticsearch/common/logging/log4j/Log4jESLoggerTests.java
  15. 25 24
      src/test/java/org/elasticsearch/common/logging/log4j/LoggingConfigurationTests.java
  16. 1 14
      src/test/java/org/elasticsearch/env/EnvironmentTests.java
  17. 1 1
      src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java
  18. 26 18
      src/test/java/org/elasticsearch/gateway/local/state/meta/MetaDataStateFormatTest.java
  19. 12 15
      src/test/java/org/elasticsearch/index/analysis/AnalysisModuleTests.java
  20. 2 2
      src/test/java/org/elasticsearch/index/analysis/HunspellTokenFilterFactoryTests.java
  21. 16 13
      src/test/java/org/elasticsearch/index/mapper/FileBasedMappingsTests.java
  22. 1 1
      src/test/java/org/elasticsearch/index/query/TemplateQueryParserTest.java
  23. 1 1
      src/test/java/org/elasticsearch/index/query/TemplateQueryTest.java
  24. 68 47
      src/test/java/org/elasticsearch/index/store/CorruptedFileTest.java
  25. 36 21
      src/test/java/org/elasticsearch/index/store/CorruptedTranslogTests.java
  26. 8 9
      src/test/java/org/elasticsearch/index/store/DirectoryUtilsTest.java
  27. 16 17
      src/test/java/org/elasticsearch/index/translog/AbstractSimpleTranslogTests.java
  28. 4 3
      src/test/java/org/elasticsearch/index/translog/fs/FsBufferedTranslogTests.java
  29. 4 3
      src/test/java/org/elasticsearch/index/translog/fs/FsSimpleTranslogTests.java
  30. 5 5
      src/test/java/org/elasticsearch/indices/analyze/HunspellServiceTests.java
  31. 10 8
      src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java
  32. 3 2
      src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java
  33. 1 1
      src/test/java/org/elasticsearch/plugins/PluginManagerTests.java
  34. 5 4
      src/test/java/org/elasticsearch/plugins/PluginManagerUnitTests.java
  35. 4 3
      src/test/java/org/elasticsearch/plugins/SitePluginTests.java
  36. 1 1
      src/test/java/org/elasticsearch/script/OnDiskScriptTests.java
  37. 2 3
      src/test/java/org/elasticsearch/script/ScriptServiceTests.java
  38. 1 1
      src/test/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricTests.java
  39. 16 13
      src/test/java/org/elasticsearch/snapshots/AbstractSnapshotTests.java
  40. 4 3
      src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java
  41. 8 6
      src/test/java/org/elasticsearch/snapshots/RepositoriesTests.java
  42. 41 40
      src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreTests.java
  43. 7 4
      src/test/java/org/elasticsearch/snapshots/SnapshotBackwardsCompatibilityTest.java
  44. 11 7
      src/test/java/org/elasticsearch/snapshots/mockstore/MockRepository.java
  45. 9 7
      src/test/java/org/elasticsearch/test/ElasticsearchBackwardsCompatIntegrationTest.java
  46. 23 20
      src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java
  47. 34 14
      src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java
  48. 10 7
      src/test/java/org/elasticsearch/test/ExternalNode.java
  49. 3 1
      src/test/java/org/elasticsearch/test/InternalTestCluster.java
  50. 4 16
      src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java
  51. 5 3
      src/test/java/org/elasticsearch/test/rest/ElasticsearchRestTests.java
  52. 14 16
      src/test/java/org/elasticsearch/test/rest/parser/RestTestSuiteParser.java
  53. 7 3
      src/test/java/org/elasticsearch/test/rest/spec/RestSpec.java
  54. 52 49
      src/test/java/org/elasticsearch/test/rest/support/FileUtils.java
  55. 18 17
      src/test/java/org/elasticsearch/test/rest/test/FileUtilsTests.java
  56. 41 31
      src/test/java/org/elasticsearch/watcher/FileWatcherTest.java

+ 11 - 5
dev-tools/forbidden/all-signatures.txt

@@ -2,8 +2,14 @@
 java.net.URL#getPath()
 java.net.URL#getFile()
 
-java.io.File#delete() @ use Files.delete for real exception, IOUtils.deleteFilesIgnoringExceptions if you dont care
-
-# temporary situation, until we upgrade with LUCENE-6051 fix 
-# (at which point forbidden apis will fail and we remove this section)
-@defaultMessage Use FileSystemUtils methods for now to workaround LUCENE-6051
+@defaultMessage Use java.nio.file instead of java.io.File API
+java.util.jar.JarFile
+java.util.zip.ZipFile
+java.io.File
+java.io.FileInputStream
+java.io.FileOutputStream
+java.io.PrintStream#<init>(java.lang.String,java.lang.String)
+java.io.PrintWriter#<init>(java.lang.String,java.lang.String)
+java.util.Formatter#<init>(java.lang.String,java.lang.String,java.util.Locale)
+java.io.RandomAccessFile
+java.nio.file.Path#toFile()

+ 0 - 14
dev-tools/forbidden/core-signatures.txt

@@ -114,17 +114,3 @@ org.apache.lucene.search.TimeLimitingCollector#getGlobalCounter()
 
 @defaultMessage Don't interrupt threads use FutureUtils#cancel(Future<T>) instead
 java.util.concurrent.Future#cancel(boolean)
-
-@defaultMessage Use java.nio.file.Path / java.nio.file.Files instead of java.io.File API
-java.util.jar.JarFile
-java.util.zip.ZipFile
-java.io.File
-java.io.FileInputStream
-java.io.FileOutputStream
-java.io.PrintStream#<init>(java.lang.String,java.lang.String)
-java.io.PrintWriter#<init>(java.lang.String,java.lang.String)
-java.util.Formatter#<init>(java.lang.String,java.lang.String,java.util.Locale)
-java.io.RandomAccessFile
-java.nio.file.Path#toFile()
-
-

+ 4 - 0
pom.xml

@@ -1281,6 +1281,10 @@
                                 <!-- start exclude for test GC simulation using Thread.suspend -->
                                 <exclude>org/elasticsearch/test/disruption/LongGCDisruption.class</exclude>
                                 <!-- end exclude for GC simulation  -->
+                                <!-- start exclude for java.io.File bridging -->
+                                <exclude>org/elasticsearch/test/ExternalNode.class</exclude>
+                                <exclude>org/elasticsearch/test/ElasticsearchTestCase.class</exclude>
+                                <!-- end exclude for java.io.File bridging -->
                             </excludes>
                             <signaturesFiles>
                                 <signaturesFile>dev-tools/forbidden/test-signatures.txt</signaturesFile>

+ 2 - 2
src/test/java/org/elasticsearch/benchmark/common/lucene/uidscan/LuceneUidScanBenchmark.java

@@ -29,7 +29,7 @@ import org.elasticsearch.common.lucene.Lucene;
 import org.elasticsearch.common.lucene.uid.Versions;
 import org.elasticsearch.common.unit.SizeValue;
 
-import java.io.File;
+import java.nio.file.Paths;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ThreadLocalRandom;
 
@@ -40,7 +40,7 @@ public class LuceneUidScanBenchmark {
 
     public static void main(String[] args) throws Exception {
 
-        FSDirectory dir = FSDirectory.open(new File("work/test").toPath());
+        FSDirectory dir = FSDirectory.open(Paths.get("work/test"));
         IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(Lucene.STANDARD_ANALYZER));
 
         final int NUMBER_OF_THREADS = 2;

+ 5 - 17
src/test/java/org/elasticsearch/benchmark/fs/FsAppendBenchmark.java

@@ -22,11 +22,11 @@ import org.apache.lucene.util.IOUtils;
 import org.elasticsearch.common.StopWatch;
 import org.elasticsearch.common.unit.ByteSizeValue;
 
-import java.io.File;
-import java.io.RandomAccessFile;
 import java.nio.ByteBuffer;
 import java.nio.channels.FileChannel;
+import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
 import java.util.Random;
 
 /**
@@ -35,11 +35,9 @@ import java.util.Random;
 public class FsAppendBenchmark {
 
     public static void main(String[] args) throws Exception {
-        IOUtils.deleteFilesIgnoringExceptions(Paths.get("work/test.log"));
-        RandomAccessFile raf = new RandomAccessFile("work/test.log", "rw");
-        raf.setLength(0);
+        Path path = Paths.get("work/test.log");
+        IOUtils.deleteFilesIgnoringExceptions(path);
 
-        boolean CHANNEL = true;
         int CHUNK = (int) ByteSizeValue.parseBytesSizeValue("1k").bytes();
         long DATA = ByteSizeValue.parseBytesSizeValue("10gb").bytes();
 
@@ -47,8 +45,7 @@ public class FsAppendBenchmark {
         new Random().nextBytes(data);
 
         StopWatch watch = new StopWatch().start("write");
-        if (CHANNEL) {
-            FileChannel channel = raf.getChannel();
+        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
             long position = 0;
             while (position < DATA) {
                 channel.write(ByteBuffer.wrap(data), position);
@@ -56,16 +53,7 @@ public class FsAppendBenchmark {
             }
             watch.stop().start("flush");
             channel.force(true);
-        } else {
-            long position = 0;
-            while (position < DATA) {
-                raf.write(data);
-                position += data.length;
-            }
-            watch.stop().start("flush");
-            raf.getFD().sync();
         }
-        raf.close();
         watch.stop();
         System.out.println("Wrote [" + (new ByteSizeValue(DATA)) + "], chunk [" + (new ByteSizeValue(CHUNK)) + "], in " + watch);
     }

+ 7 - 17
src/test/java/org/elasticsearch/benchmark/scripts/score/BasicScriptBenchmark.java

@@ -19,8 +19,6 @@
 
 package org.elasticsearch.benchmark.scripts.score;
 
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
 import org.elasticsearch.action.bulk.BulkRequestBuilder;
 import org.elasticsearch.action.search.SearchRequest;
 import org.elasticsearch.action.search.SearchResponse;
@@ -37,9 +35,11 @@ import org.elasticsearch.index.query.functionscore.script.ScriptScoreFunctionBui
 import org.joda.time.DateTime;
 
 import java.io.BufferedWriter;
-import java.io.File;
 import java.io.IOException;
 import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.security.SecureRandom;
 import java.util.*;
 import java.util.Map.Entry;
@@ -150,24 +150,18 @@ public class BasicScriptBenchmark {
     }
 
     public static void writeHelperFunction() throws IOException {
-        File file = new File("addToPlot.m");
-        BufferedWriter out = Files.newWriter(file, Charsets.UTF_8);
-
-        out.write("function handle = addToPlot(numTerms, perDoc, color, linestyle, linewidth)\n" + "handle = line(numTerms, perDoc);\n"
+        try (BufferedWriter out = Files.newBufferedWriter(Paths.get("addToPlot.m"), StandardCharsets.UTF_8)) {
+            out.write("function handle = addToPlot(numTerms, perDoc, color, linestyle, linewidth)\n" + "handle = line(numTerms, perDoc);\n"
                 + "set(handle, 'color', color);\n" + "set(handle, 'linestyle',linestyle);\n" + "set(handle, 'LineWidth',linewidth);\n"
                 + "end\n");
-        out.close();
+        }
     }
 
     public static void printOctaveScript(List<Results> allResults, String[] args) throws IOException {
         if (args.length == 0) {
             return;
         }
-        BufferedWriter out = null;
-        try {
-            File file = new File(args[0]);
-            out = Files.newWriter(file, Charsets.UTF_8);
-
+        try (BufferedWriter out = Files.newBufferedWriter(Paths.get(args[0]), StandardCharsets.UTF_8)) {
             out.write("#! /usr/local/bin/octave -qf");
             out.write("\n\n\n\n");
             out.write("######################################\n");
@@ -195,10 +189,6 @@ public class BasicScriptBenchmark {
             out.write("hold off;\n\n");
         } catch (IOException e) {
             System.err.println("Error: " + e.getMessage());
-        } finally {
-            if (out != null) {
-                out.close();
-            }
         }
         writeHelperFunction();
     }

+ 2 - 1
src/test/java/org/elasticsearch/bwcompat/StaticIndexBackwardCompatibilityTest.java

@@ -35,6 +35,7 @@ import org.elasticsearch.test.rest.client.http.HttpRequestBuilder;
 
 import java.io.File;
 import java.net.InetSocketAddress;
+import java.nio.file.Paths;
 
 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
 
@@ -48,7 +49,7 @@ public class StaticIndexBackwardCompatibilityTest extends ElasticsearchIntegrati
 
     public void loadIndex(String index, Object... settings) throws Exception {
         logger.info("Checking static index " + index);
-        Settings nodeSettings = prepareBackwardsDataDir(new File(getClass().getResource(index).toURI()), settings);
+        Settings nodeSettings = prepareBackwardsDataDir(Paths.get(getClass().getResource(index).toURI()), settings);
         internalCluster().startNode(nodeSettings);
         ensureGreen("test");
         assertIndexSanity();

+ 3 - 2
src/test/java/org/elasticsearch/cluster/routing/RoutingBackwardCompatibilityUponUpgradeTests.java

@@ -33,7 +33,8 @@ import org.elasticsearch.node.internal.InternalNode;
 import org.elasticsearch.search.SearchHit;
 import org.elasticsearch.test.ElasticsearchIntegrationTest;
 
-import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
@@ -50,7 +51,7 @@ public class RoutingBackwardCompatibilityUponUpgradeTests extends ElasticsearchI
     }
 
     private void test(String name, Class<? extends HashFunction> expectedHashFunction, boolean expectedUseType) throws Exception {
-        File zippedIndexDir = new File(getClass().getResource("/org/elasticsearch/cluster/routing/" + name + ".zip").toURI());
+        Path zippedIndexDir = Paths.get(getClass().getResource("/org/elasticsearch/cluster/routing/" + name + ".zip").toURI());
         Settings baseSettings = prepareBackwardsDataDir(zippedIndexDir);
         internalCluster().startNode(ImmutableSettings.builder()
                 .put(baseSettings)

+ 5 - 5
src/test/java/org/elasticsearch/common/ChannelsTests.java

@@ -41,26 +41,26 @@ import java.nio.channels.FileChannel;
 import java.nio.channels.FileLock;
 import java.nio.channels.ReadableByteChannel;
 import java.nio.channels.WritableByteChannel;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 
 public class ChannelsTests extends ElasticsearchTestCase {
 
     byte[] randomBytes;
     FileChannel fileChannel;
-    RandomAccessFile randomAccessFile;
 
     @Before
     public void setUp() throws Exception {
         super.setUp();
-        File tmpFile = newTempFile();
-        randomAccessFile = new RandomAccessFile(tmpFile, "rw");
-        fileChannel = new MockFileChannel(randomAccessFile.getChannel());
+        Path tmpFile = newTempFilePath();
+        FileChannel randomAccessFile = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
+        fileChannel = new MockFileChannel(randomAccessFile);
         randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes("UTF-8");
     }
 
     @After
     public void tearDown() throws Exception {
         fileChannel.close();
-        randomAccessFile.close();
         super.tearDown();
     }
 

+ 2 - 2
src/test/java/org/elasticsearch/common/PidFileTests.java

@@ -37,7 +37,7 @@ public class PidFileTests extends ElasticsearchTestCase {
 
     @Test(expected = ElasticsearchIllegalArgumentException.class)
     public void testParentIsFile() throws IOException {
-        Path dir = newTempDir().toPath();
+        Path dir = newTempDirPath();
         Path parent = dir.resolve("foo");
         try(BufferedWriter stream = Files.newBufferedWriter(parent, Charsets.UTF_8, StandardOpenOption.CREATE_NEW)) {
             stream.write("foo");
@@ -48,7 +48,7 @@ public class PidFileTests extends ElasticsearchTestCase {
 
     @Test
     public void testPidFile() throws IOException {
-        Path dir = newTempDir().toPath();
+        Path dir = newTempDirPath();
         Path parent = dir.resolve("foo");
         if (randomBoolean()) {
             Files.createDirectories(parent);

+ 1 - 1
src/test/java/org/elasticsearch/common/blobstore/BlobStoreTest.java

@@ -140,7 +140,7 @@ public class BlobStoreTest extends ElasticsearchTestCase {
     }
 
     protected BlobStore newBlobStore() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         Settings settings = randomBoolean() ? ImmutableSettings.EMPTY : ImmutableSettings.builder().put("buffer_size", new ByteSizeValue(randomIntBetween(1, 100), ByteSizeUnit.KB)).build();
         FsBlobStore store = new FsBlobStore(settings, tempDir);
         return store;

+ 13 - 12
src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTest.java

@@ -37,10 +37,11 @@ import org.junit.Before;
 import org.junit.Test;
 
 import java.io.EOFException;
-import java.io.File;
 import java.io.IOException;
-import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
 import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 import java.util.Arrays;
 
 public class PagedBytesReferenceTest extends ElasticsearchTestCase {
@@ -260,12 +261,12 @@ public class PagedBytesReferenceTest extends ElasticsearchTestCase {
     public void testWriteToChannel() throws IOException {
         int length = randomIntBetween(10, PAGE_SIZE * 4);
         BytesReference pbr = getRandomizedPagedBytesReference(length);
-        File tFile = newTempFile();
-        try (RandomAccessFile file = new RandomAccessFile(tFile, "rw")) {
-            pbr.writeTo(file.getChannel());
-            assertEquals(pbr.length(), file.length());
-            assertArrayEquals(pbr.toBytes(), Files.readAllBytes(tFile.toPath()));
+        Path tFile = newTempFilePath();
+        try (FileChannel channel = FileChannel.open(tFile, StandardOpenOption.WRITE)) {
+            pbr.writeTo(channel);
+            assertEquals(pbr.length(), channel.position());
         }
+        assertArrayEquals(pbr.toBytes(), Files.readAllBytes(tFile));
     }
 
     public void testSliceWriteToOutputStream() throws IOException {
@@ -287,12 +288,12 @@ public class PagedBytesReferenceTest extends ElasticsearchTestCase {
         int sliceOffset = randomIntBetween(1, length / 2);
         int sliceLength = length - sliceOffset;
         BytesReference slice = pbr.slice(sliceOffset, sliceLength);
-        File tFile = newTempFile();
-        try (RandomAccessFile file = new RandomAccessFile(tFile, "rw")) {
-            slice.writeTo(file.getChannel());
-            assertEquals(slice.length(), file.length());
-            assertArrayEquals(slice.toBytes(), Files.readAllBytes(tFile.toPath()));
+        Path tFile = newTempFilePath();
+        try (FileChannel channel = FileChannel.open(tFile, StandardOpenOption.WRITE)) {
+            slice.writeTo(channel);
+            assertEquals(slice.length(), channel.position());
         }
+        assertArrayEquals(slice.toBytes(), Files.readAllBytes(tFile));
     }
 
     public void testToBytes() {

+ 2 - 3
src/test/java/org/elasticsearch/common/io/FileSystemUtilsTests.java

@@ -24,7 +24,6 @@ import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.file.Files;
@@ -47,7 +46,7 @@ public class FileSystemUtilsTests extends ElasticsearchTestCase {
 
     @Before
     public void copySourceFilesToTarget() throws IOException {
-        Path globalTempDir = globalTempDir().toPath();
+        Path globalTempDir = globalTempDirPath();
         src = globalTempDir.resolve("iocopyappend-src");
         dst = globalTempDir.resolve("iocopyappend-dst");
         Files.createDirectories(src);
@@ -92,7 +91,7 @@ public class FileSystemUtilsTests extends ElasticsearchTestCase {
 
     @Test
     public void testMoveOverExistingFileAndIgnore() throws IOException {
-        Path dest = globalTempDir().toPath();
+        Path dest = globalTempDirPath();
 
         FileSystemUtils.moveFilesWithoutOverwriting(src.resolve("v1"), dest, null);
         assertFileContent(dest, "file1.txt", "version1");

+ 6 - 5
src/test/java/org/elasticsearch/common/logging/log4j/Log4jESLoggerTests.java

@@ -30,8 +30,9 @@ import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.test.ElasticsearchTestCase;
 import org.junit.Test;
 
-import java.io.File;
 import java.net.URL;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -47,10 +48,10 @@ public class Log4jESLoggerTests extends ElasticsearchTestCase {
     public void setUp() throws Exception {
         super.setUp();
         LogConfigurator.reset();
-        File configDir = resolveConfigDir();
+        Path configDir = resolveConfigDir();
         // Need to set custom path.conf so we can use a custom logging.yml file for the test
         Settings settings = ImmutableSettings.builder()
-                .put("path.conf", configDir.getAbsolutePath())
+                .put("path.conf", configDir.toAbsolutePath())
                 .build();
         LogConfigurator.configure(settings);
 
@@ -114,9 +115,9 @@ public class Log4jESLoggerTests extends ElasticsearchTestCase {
         
     }
 
-    private static File resolveConfigDir() throws Exception {
+    private static Path resolveConfigDir() throws Exception {
         URL url = Log4jESLoggerTests.class.getResource("config");
-        return new File(url.toURI());
+        return Paths.get(url.toURI());
     }
 
     private static class TestAppender extends AppenderSkeleton {

+ 25 - 24
src/test/java/org/elasticsearch/common/logging/log4j/LoggingConfigurationTests.java

@@ -19,7 +19,6 @@
 
 package org.elasticsearch.common.logging.log4j;
 
-import com.google.common.io.Files;
 import org.apache.log4j.Appender;
 import org.apache.log4j.Logger;
 import org.elasticsearch.common.logging.ESLogger;
@@ -31,9 +30,11 @@ import org.hamcrest.Matchers;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.io.File;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.notNullValue;
@@ -50,9 +51,9 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
 
     @Test
     public void testResolveMultipleConfigs() throws Exception {
-        File configDir = resolveConfigDir();
+        Path configDir = resolveConfigDir();
         Settings settings = ImmutableSettings.builder()
-                .put("path.conf", configDir.getAbsolutePath())
+                .put("path.conf", configDir.toAbsolutePath())
                 .build();
         LogConfigurator.configure(settings);
 
@@ -74,11 +75,11 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
 
     @Test
     public void testResolveJsonLoggingConfig() throws Exception {
-        File tmpDir = newTempDir();
-        File loggingConf = new File(tmpDir, loggingConfiguration("json"));
-        Files.write("{\"json\": \"foo\"}", loggingConf, StandardCharsets.UTF_8);
+        Path tmpDir = newTempDirPath();
+        Path loggingConf = tmpDir.resolve(loggingConfiguration("json"));
+        Files.write(loggingConf, "{\"json\": \"foo\"}".getBytes(StandardCharsets.UTF_8));
         Environment environment = new Environment(
-                ImmutableSettings.builder().put("path.conf", tmpDir.getAbsolutePath()).build());
+                ImmutableSettings.builder().put("path.conf", tmpDir.toAbsolutePath()).build());
 
         ImmutableSettings.Builder builder = ImmutableSettings.builder();
         LogConfigurator.resolveConfig(environment, builder);
@@ -89,11 +90,11 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
 
     @Test
     public void testResolvePropertiesLoggingConfig() throws Exception {
-        File tmpDir = newTempDir();
-        File loggingConf = new File(tmpDir, loggingConfiguration("properties"));
-        Files.write("key: value", loggingConf, StandardCharsets.UTF_8);
+        Path tmpDir = newTempDirPath();
+        Path loggingConf = tmpDir.resolve(loggingConfiguration("properties"));
+        Files.write(loggingConf, "key: value".getBytes(StandardCharsets.UTF_8));
         Environment environment = new Environment(
-                ImmutableSettings.builder().put("path.conf", tmpDir.getAbsolutePath()).build());
+                ImmutableSettings.builder().put("path.conf", tmpDir.toAbsolutePath()).build());
 
         ImmutableSettings.Builder builder = ImmutableSettings.builder();
         LogConfigurator.resolveConfig(environment, builder);
@@ -104,13 +105,13 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
 
     @Test
     public void testResolveYamlLoggingConfig() throws Exception {
-        File tmpDir = newTempDir();
-        File loggingConf1 = new File(tmpDir, loggingConfiguration("yml"));
-        File loggingConf2 = new File(tmpDir, loggingConfiguration("yaml"));
-        Files.write("yml: bar", loggingConf1, StandardCharsets.UTF_8);
-        Files.write("yaml: bar", loggingConf2, StandardCharsets.UTF_8);
+        Path tmpDir = newTempDirPath();
+        Path loggingConf1 = tmpDir.resolve(loggingConfiguration("yml"));
+        Path loggingConf2 = tmpDir.resolve(loggingConfiguration("yaml"));
+        Files.write(loggingConf1, "yml: bar".getBytes(StandardCharsets.UTF_8));
+        Files.write(loggingConf2, "yaml: bar".getBytes(StandardCharsets.UTF_8));
         Environment environment = new Environment(
-                ImmutableSettings.builder().put("path.conf", tmpDir.getAbsolutePath()).build());
+                ImmutableSettings.builder().put("path.conf", tmpDir.toAbsolutePath()).build());
 
         ImmutableSettings.Builder builder = ImmutableSettings.builder();
         LogConfigurator.resolveConfig(environment, builder);
@@ -122,11 +123,11 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
 
     @Test
     public void testResolveConfigInvalidFilename() throws Exception {
-        File tmpDir = newTempDir();
-        File invalidSuffix = new File(tmpDir, loggingConfiguration(randomFrom(LogConfigurator.ALLOWED_SUFFIXES)) + randomInvalidSuffix());
-        Files.write("yml: bar", invalidSuffix, StandardCharsets.UTF_8);
+        Path tmpDir = newTempDirPath();
+        Path invalidSuffix = tmpDir.resolve(loggingConfiguration(randomFrom(LogConfigurator.ALLOWED_SUFFIXES)) + randomInvalidSuffix());
+        Files.write(invalidSuffix, "yml: bar".getBytes(StandardCharsets.UTF_8));
         Environment environment = new Environment(
-                ImmutableSettings.builder().put("path.conf", invalidSuffix.getAbsolutePath()).build());
+                ImmutableSettings.builder().put("path.conf", invalidSuffix.toAbsolutePath()).build());
 
         ImmutableSettings.Builder builder = ImmutableSettings.builder();
         LogConfigurator.resolveConfig(environment, builder);
@@ -135,9 +136,9 @@ public class LoggingConfigurationTests extends ElasticsearchTestCase {
         assertThat(logSettings.get("yml"), Matchers.nullValue());
     }
 
-    private static File resolveConfigDir() throws Exception {
+    private static Path resolveConfigDir() throws Exception {
         URL url = LoggingConfigurationTests.class.getResource("config");
-        return new File(url.toURI());
+        return Paths.get(url.toURI());
     }
 
     private static String loggingConfiguration(String suffix) {

+ 1 - 14
src/test/java/org/elasticsearch/env/EnvironmentTests.java

@@ -19,29 +19,16 @@
 package org.elasticsearch.env;
 
 import com.google.common.base.Charsets;
-import org.apache.lucene.store.LockObtainFailedException;
-import org.apache.lucene.util.IOUtils;
-import org.elasticsearch.ElasticsearchIllegalStateException;
 import org.elasticsearch.common.io.FileSystemUtils;
 import org.elasticsearch.common.io.Streams;
 import org.elasticsearch.common.settings.ImmutableSettings;
 import org.elasticsearch.common.settings.Settings;
-import org.elasticsearch.index.Index;
-import org.elasticsearch.index.shard.ShardId;
 import org.elasticsearch.test.ElasticsearchTestCase;
 import org.junit.Test;
 
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.net.URL;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * Simple unit-tests for Environment.java
@@ -55,7 +42,7 @@ public class EnvironmentTests extends ElasticsearchTestCase {
     public Environment newEnvironment(Settings settings) throws IOException {
         Settings build = ImmutableSettings.builder()
                 .put(settings)
-                .put("path.home", newTempDir().getAbsolutePath())
+                .put("path.home", newTempDirPath().toAbsolutePath())
                 .putArray("path.data", tmpPaths()).build();
         return new Environment(build);
     }

+ 1 - 1
src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java

@@ -291,7 +291,7 @@ public class NodeEnvironmentTests extends ElasticsearchTestCase {
     public NodeEnvironment newNodeEnvironment(Settings settings) throws IOException {
         Settings build = ImmutableSettings.builder()
                 .put(settings)
-                .put("path.home", newTempDir().getAbsolutePath())
+                .put("path.home", newTempDirPath().toAbsolutePath())
                 .putArray("path.data", tmpPaths()).build();
         return new NodeEnvironment(build, new Environment(build));
     }

+ 26 - 18
src/test/java/org/elasticsearch/gateway/local/state/meta/MetaDataStateFormatTest.java

@@ -20,6 +20,7 @@ package org.elasticsearch.gateway.local.state.meta;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.google.common.collect.Iterators;
+
 import org.apache.lucene.codecs.CodecUtil;
 import org.apache.lucene.store.BaseDirectoryWrapper;
 import org.apache.lucene.store.ChecksumIndexInput;
@@ -50,10 +51,12 @@ import java.io.InputStream;
 import java.io.IOException;
 import java.io.RandomAccessFile;
 import java.net.URISyntaxException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
 import java.nio.file.DirectoryStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
-
+import java.nio.file.StandardOpenOption;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -88,7 +91,7 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
                 return MetaData.Builder.fromXContent(parser);
             }
         };
-        Path tmp = newTempDir().toPath();
+        Path tmp = newTempDirPath();
         final InputStream resource = this.getClass().getResourceAsStream("global-3.st");
         assertThat(resource, notNullValue());
         Path dst = tmp.resolve("global-3.st");
@@ -102,7 +105,7 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
     public void testReadWriteState() throws IOException {
         Path[] dirs = new Path[randomIntBetween(1, 5)];
         for (int i = 0; i < dirs.length; i++) {
-            dirs[i] = newTempDir(LifecycleScope.TEST).toPath();
+            dirs[i] = newTempDirPath(LifecycleScope.TEST);
         }
         final boolean deleteOldFiles = randomBoolean();
         Format format = new Format(randomFrom(XContentType.values()), deleteOldFiles);
@@ -153,7 +156,7 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
     public void testVersionMismatch() throws IOException {
         Path[] dirs = new Path[randomIntBetween(1, 5)];
         for (int i = 0; i < dirs.length; i++) {
-            dirs[i] = newTempDir(LifecycleScope.TEST).toPath();
+            dirs[i] = newTempDirPath(LifecycleScope.TEST);
         }
         final boolean deleteOldFiles = randomBoolean();
         Format format = new Format(randomFrom(XContentType.values()), deleteOldFiles);
@@ -183,7 +186,7 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
     public void testCorruption() throws IOException {
         Path[] dirs = new Path[randomIntBetween(1, 5)];
         for (int i = 0; i < dirs.length; i++) {
-            dirs[i] = newTempDir(LifecycleScope.TEST).toPath();
+            dirs[i] = newTempDirPath(LifecycleScope.TEST);
         }
         final boolean deleteOldFiles = randomBoolean();
         Format format = new Format(randomFrom(XContentType.values()), deleteOldFiles);
@@ -219,14 +222,19 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
             try (IndexInput input = dir.openInput(fileToCorrupt.getFileName().toString(), IOContext.DEFAULT)) {
                 checksumBeforeCorruption = CodecUtil.retrieveChecksum(input);
             }
-            try (RandomAccessFile raf = new RandomAccessFile(fileToCorrupt.toAbsolutePath().toString(), "rw")) {
-                raf.seek(randomIntBetween(0, (int)Math.min(Integer.MAX_VALUE, raf.length()-1)));
-                long filePointer = raf.getFilePointer();
-                byte b = raf.readByte();
-                raf.seek(filePointer);
-                raf.writeByte(~b);
-                raf.getFD().sync();
-                logger.debug("Corrupting file {} --  flipping at position {} from {} to {} ", fileToCorrupt.getFileName().toString(), filePointer, Integer.toHexString(b), Integer.toHexString(~b));
+            try (FileChannel raf = FileChannel.open(fileToCorrupt, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
+                raf.position(randomIntBetween(0, (int)Math.min(Integer.MAX_VALUE, raf.size()-1)));
+                long filePointer = raf.position();
+                ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
+                raf.read(bb);
+                
+                bb.flip();
+                byte oldValue = bb.get(0);
+                byte newValue = (byte) ~oldValue;
+                
+                raf.position(filePointer);
+                raf.write(bb);
+                logger.debug("Corrupting file {} --  flipping at position {} from {} to {} ", fileToCorrupt.getFileName().toString(), filePointer, Integer.toHexString(oldValue), Integer.toHexString(newValue));
             }
         long checksumAfterCorruption;
         long actualChecksumAfterCorruption;
@@ -253,8 +261,8 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
         final ToXContent.Params params = ToXContent.EMPTY_PARAMS;
         MetaDataStateFormat<MetaData> format = LocalGatewayMetaState.globalStateFormat(randomFrom(XContentType.values()), params, randomBoolean());
         final Path[] dirs = new Path[2];
-        dirs[0] = newTempDir(LifecycleScope.TEST).toPath();
-        dirs[1] = newTempDir(LifecycleScope.TEST).toPath();
+        dirs[0] = newTempDirPath(LifecycleScope.TEST);
+        dirs[1] = newTempDirPath(LifecycleScope.TEST);
         for (Path dir : dirs) {
             Files.createDirectories(dir.resolve(MetaDataStateFormat.STATE_DIR_NAME));
         }
@@ -288,8 +296,8 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
         final ToXContent.Params params = ToXContent.EMPTY_PARAMS;
         MetaDataStateFormat<MetaData> format = LocalGatewayMetaState.globalStateFormat(randomFrom(XContentType.values()), params, randomBoolean());
         final Path[] dirs = new Path[2];
-        dirs[0] = newTempDir(LifecycleScope.TEST).toPath();
-        dirs[1] = newTempDir(LifecycleScope.TEST).toPath();
+        dirs[0] = newTempDirPath(LifecycleScope.TEST);
+        dirs[1] = newTempDirPath(LifecycleScope.TEST);
         for (Path dir : dirs) {
             Files.createDirectories(dir.resolve(MetaDataStateFormat.STATE_DIR_NAME));
         }
@@ -329,7 +337,7 @@ public class MetaDataStateFormatTest extends ElasticsearchTestCase {
         Set<Path> corruptedFiles = new HashSet<>();
         MetaDataStateFormat<MetaData> format = LocalGatewayMetaState.globalStateFormat(randomFrom(XContentType.values()), params, randomBoolean());
         for (int i = 0; i < dirs.length; i++) {
-            dirs[i] = newTempDir(LifecycleScope.TEST).toPath();
+            dirs[i] = newTempDirPath(LifecycleScope.TEST);
             Files.createDirectories(dirs[i].resolve(MetaDataStateFormat.STATE_DIR_NAME));
             for (int j = 0; j < numLegacy; j++) {
                 XContentType type = format.format();

+ 12 - 15
src/test/java/org/elasticsearch/index/analysis/AnalysisModuleTests.java

@@ -19,7 +19,6 @@
 
 package org.elasticsearch.index.analysis;
 
-import com.google.common.base.Charsets;
 import org.apache.lucene.analysis.Analyzer;
 import org.apache.lucene.analysis.TokenStream;
 import org.apache.lucene.analysis.Tokenizer;
@@ -48,7 +47,12 @@ import org.elasticsearch.test.ElasticsearchTestCase;
 import org.hamcrest.MatcherAssert;
 import org.junit.Test;
 
-import java.io.*;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Set;
 
 import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
@@ -198,29 +202,22 @@ public class AnalysisModuleTests extends ElasticsearchTestCase {
         Environment env = new Environment(ImmutableSettings.Builder.EMPTY_SETTINGS);
         String[] words = new String[]{"donau", "dampf", "schiff", "spargel", "creme", "suppe"};
 
-        File wordListFile = generateWordList(words);
-        Settings settings = settingsBuilder().loadFromSource("index: \n  word_list_path: " + wordListFile.getAbsolutePath()).build();
+        Path wordListFile = generateWordList(words);
+        Settings settings = settingsBuilder().loadFromSource("index: \n  word_list_path: " + wordListFile.toAbsolutePath()).build();
 
         Set<?> wordList = Analysis.getWordSet(env, settings, "index.word_list");
         MatcherAssert.assertThat(wordList.size(), equalTo(6));
 //        MatcherAssert.assertThat(wordList, hasItems(words));
+        Files.delete(wordListFile);
     }
 
-    private File generateWordList(String[] words) throws Exception {
-        File wordListFile = File.createTempFile("wordlist", ".txt");
-        wordListFile.deleteOnExit();
-
-        BufferedWriter writer = null;
-        try {
-            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(wordListFile), Charsets.UTF_8));
+    private Path generateWordList(String[] words) throws Exception {
+        Path wordListFile = newTempDirPath().resolve("wordlist.txt");
+        try (BufferedWriter writer = Files.newBufferedWriter(wordListFile, StandardCharsets.UTF_8)) {
             for (String word : words) {
                 writer.write(word);
                 writer.write('\n');
             }
-        } finally {
-            if (writer != null) {
-                writer.close();
-            }
         }
         return wordListFile;
     }

+ 2 - 2
src/test/java/org/elasticsearch/index/analysis/HunspellTokenFilterFactoryTests.java

@@ -33,7 +33,7 @@ public class HunspellTokenFilterFactoryTests extends ElasticsearchTestCase {
     @Test
     public void testDedup() throws IOException {
         Settings settings = settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/conf_dir"))
                 .put("index.analysis.filter.en_US.type", "hunspell")
                 .put("index.analysis.filter.en_US.locale", "en_US")
                 .build();
@@ -45,7 +45,7 @@ public class HunspellTokenFilterFactoryTests extends ElasticsearchTestCase {
         assertThat(hunspellTokenFilter.dedup(), is(true));
 
         settings = settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/conf_dir"))
                 .put("index.analysis.filter.en_US.type", "hunspell")
                 .put("index.analysis.filter.en_US.dedup", false)
                 .put("index.analysis.filter.en_US.locale", "en_US")

+ 16 - 13
src/test/java/org/elasticsearch/index/mapper/FileBasedMappingsTests.java

@@ -20,7 +20,7 @@
 package org.elasticsearch.index.mapper;
 
 import com.google.common.collect.ImmutableSet;
-import com.google.common.io.Files;
+
 import org.apache.lucene.util.IOUtils;
 import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
 import org.elasticsearch.cluster.ClusterName;
@@ -33,8 +33,9 @@ import org.elasticsearch.node.Node;
 import org.elasticsearch.node.NodeBuilder;
 import org.elasticsearch.test.ElasticsearchTestCase;
 
-import java.io.File;
-import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Map;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
@@ -44,15 +45,16 @@ public class FileBasedMappingsTests extends ElasticsearchTestCase {
     private static final String NAME = FileBasedMappingsTests.class.getSimpleName();
 
     public void testFileBasedMappings() throws Exception {
-        File configDir = Files.createTempDir();
-        File mappingsDir = new File(configDir, "mappings");
-        File indexMappings = new File(new File(mappingsDir, "index"), "type.json");
-        File defaultMappings = new File(new File(mappingsDir, "_default"), "type.json");
+        Path configDir = newTempDirPath();
+        Path mappingsDir = configDir.resolve("mappings");
+        Path indexMappings = mappingsDir.resolve("index").resolve("type.json");
+        Path defaultMappings = mappingsDir.resolve("_default").resolve("type.json");
         try {
-            indexMappings.getParentFile().mkdirs();
-            defaultMappings.getParentFile().mkdirs();
+            Files.createDirectories(indexMappings.getParent());
+            Files.createDirectories(defaultMappings.getParent());
 
-            try (XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, new FileOutputStream(indexMappings))) {
+            try (OutputStream stream = Files.newOutputStream(indexMappings);
+                 XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, stream)) {
                 builder.startObject()
                         .startObject("type")
                             .startObject("properties")
@@ -64,7 +66,8 @@ public class FileBasedMappingsTests extends ElasticsearchTestCase {
                     .endObject();
             }
 
-            try (XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, new FileOutputStream(defaultMappings))) {
+            try (OutputStream stream = Files.newOutputStream(defaultMappings);
+                 XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, stream)) {
                 builder.startObject()
                         .startObject("type")
                             .startObject("properties")
@@ -79,7 +82,7 @@ public class FileBasedMappingsTests extends ElasticsearchTestCase {
             Settings settings = ImmutableSettings.builder()
                     .put(ClusterName.SETTING, NAME)
                     .put("node.name", NAME)
-                    .put("path.conf", configDir.getAbsolutePath())
+                    .put("path.conf", configDir.toAbsolutePath())
                     .put("http.enabled", false)
                     .build();
 
@@ -100,7 +103,7 @@ public class FileBasedMappingsTests extends ElasticsearchTestCase {
                 }
             }
         } finally {
-            IOUtils.rm(configDir.toPath());
+            IOUtils.rm(configDir);
         }
     }
 

+ 1 - 1
src/test/java/org/elasticsearch/index/query/TemplateQueryParserTest.java

@@ -68,7 +68,7 @@ public class TemplateQueryParserTest extends ElasticsearchTestCase {
     @Before
     public void setup() throws IOException {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put("path.conf", this.getResource("config").getPath())
+                .put("path.conf", this.getResourcePath("config"))
                 .put("name", getClass().getName())
                 .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                 .build();

+ 1 - 1
src/test/java/org/elasticsearch/index/query/TemplateQueryTest.java

@@ -65,7 +65,7 @@ public class TemplateQueryTest extends ElasticsearchIntegrationTest {
     @Override
     public Settings nodeSettings(int nodeOrdinal) {
         return settingsBuilder().put(super.nodeSettings(nodeOrdinal))
-                .put("path.conf", this.getResource("config").getPath()).build();
+                .put("path.conf", this.getResourcePath("config")).build();
     }
 
     @Test

+ 68 - 47
src/test/java/org/elasticsearch/index/store/CorruptedFileTest.java

@@ -23,6 +23,7 @@ import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.carrotsearch.randomizedtesting.generators.RandomPicks;
 import com.google.common.base.Charsets;
 import com.google.common.base.Predicate;
+
 import org.apache.lucene.codecs.CodecUtil;
 import org.apache.lucene.index.CheckIndex;
 import org.apache.lucene.index.IndexFileNames;
@@ -72,7 +73,15 @@ import org.elasticsearch.test.transport.MockTransportService;
 import org.elasticsearch.transport.*;
 import org.junit.Test;
 
-import java.io.*;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
 import java.util.*;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
@@ -283,10 +292,10 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
                 }
             }
         }
-        final List<File> files = listShardFiles(shardRouting);
-        File corruptedFile = null;
-        for (File file : files) {
-            if (file.getName().startsWith("corrupted_")) {
+        final List<Path> files = listShardFiles(shardRouting);
+        Path corruptedFile = null;
+        for (Path file : files) {
+            if (file.getFileName().toString().startsWith("corrupted_")) {
                 corruptedFile = file;
                 break;
             }
@@ -430,17 +439,17 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
         logger.info("-->  creating repository");
         assertAcked(client().admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE).getAbsolutePath())
+                        .put("location", newTempDirPath(LifecycleScope.SUITE).toAbsolutePath())
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
         logger.info("--> snapshot");
         CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test").get();
         assertThat(createSnapshotResponse.getSnapshotInfo().state(), equalTo(SnapshotState.PARTIAL));
         logger.info("failed during snapshot -- maybe SI file got corrupted");
-        final List<File> files = listShardFiles(shardRouting);
-        File corruptedFile = null;
-        for (File file : files) {
-            if (file.getName().startsWith("corrupted_")) {
+        final List<Path> files = listShardFiles(shardRouting);
+        Path corruptedFile = null;
+        for (Path file : files) {
+            if (file.getFileName().toString().startsWith("corrupted_")) {
                 corruptedFile = file;
                 break;
             }
@@ -470,43 +479,51 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
         assertTrue(shardRouting.assignedToNode());
         String nodeId = shardRouting.currentNodeId();
         NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
-        Set<File> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
+        Set<Path> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
         for (FsStats.Info info : nodeStatses.getNodes()[0].getFs()) {
             String path = info.getPath();
             final String relativeDataLocationPath = "indices/test/" + Integer.toString(shardRouting.getId()) + "/index";
-            File file = new File(path, relativeDataLocationPath);
-            files.addAll(Arrays.asList(file.listFiles(new FileFilter() {
-                @Override
-                public boolean accept(File pathname) {
-                    if (pathname.isFile() && "write.lock".equals(pathname.getName()) == false) {
-                        return (includePerCommitFiles || isPerSegmentFile(pathname.getName()));
+            Path file = Paths.get(path).resolve(relativeDataLocationPath);
+            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
+                for (Path item : stream) {
+                    if (Files.isRegularFile(item) && "write.lock".equals(item.getFileName()) == false) {
+                        if (includePerCommitFiles || isPerSegmentFile(item.getFileName().toString())) {
+                            files.add(item);
+                        }
                     }
-                    return false; // no dirs no write.locks
                 }
-            })));
+            }
         }
         pruneOldDeleteGenerations(files);
-        File fileToCorrupt = null;
+        Path fileToCorrupt = null;
         if (!files.isEmpty()) {
             fileToCorrupt = RandomPicks.randomFrom(getRandom(), files);
-            try (Directory dir = FSDirectory.open(fileToCorrupt.getParentFile().toPath())) {
+            try (Directory dir = FSDirectory.open(fileToCorrupt.toAbsolutePath().getParent())) {
                 long checksumBeforeCorruption;
-                try (IndexInput input = dir.openInput(fileToCorrupt.getName(), IOContext.DEFAULT)) {
+                try (IndexInput input = dir.openInput(fileToCorrupt.getFileName().toString(), IOContext.DEFAULT)) {
                     checksumBeforeCorruption = CodecUtil.retrieveChecksum(input);
                 }
-                try (RandomAccessFile raf = new RandomAccessFile(fileToCorrupt, "rw")) {
-                    raf.seek(randomIntBetween(0, (int) Math.min(Integer.MAX_VALUE, raf.length() - 1)));
-                    long filePointer = raf.getFilePointer();
-                    byte b = raf.readByte();
-                    raf.seek(filePointer);
-                    int corruptedValue = (b + 1) & 0xff;
-                    raf.writeByte(corruptedValue);
-                    raf.getFD().sync();
-                    logger.info("Corrupting file for shard {} --  flipping at position {} from {} to {} file: {}", shardRouting, filePointer, Integer.toHexString(b), Integer.toHexString(corruptedValue), fileToCorrupt.getName());
+                try (FileChannel raf = FileChannel.open(fileToCorrupt, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
+                    // read
+                    raf.position(randomIntBetween(0, (int) Math.min(Integer.MAX_VALUE, raf.size() - 1)));
+                    long filePointer = raf.position();
+                    ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
+                    raf.read(bb);
+                    bb.flip();
+                    
+                    // corrupt
+                    byte oldValue = bb.get(0);
+                    byte newValue = (byte) (oldValue + 1);
+                    bb.put(0, newValue);
+                    
+                    // rewrite
+                    raf.position(filePointer);
+                    raf.write(bb);
+                    logger.info("Corrupting file for shard {} --  flipping at position {} from {} to {} file: {}", shardRouting, filePointer, Integer.toHexString(oldValue), Integer.toHexString(newValue), fileToCorrupt.getFileName());
                 }
                 long checksumAfterCorruption;
                 long actualChecksumAfterCorruption;
-                try (ChecksumIndexInput input = dir.openChecksumInput(fileToCorrupt.getName(), IOContext.DEFAULT)) {
+                try (ChecksumIndexInput input = dir.openChecksumInput(fileToCorrupt.getFileName().toString(), IOContext.DEFAULT)) {
                     assertThat(input.getFilePointer(), is(0l));
                     input.seek(input.length() - 8); // one long is the checksum... 8 bytes
                     checksumAfterCorruption = input.getChecksum();
@@ -518,7 +535,7 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
                 msg.append("Checksum before: [").append(checksumBeforeCorruption).append("]");
                 msg.append(" after: [").append(checksumAfterCorruption).append("]");
                 msg.append(" checksum value after corruption: ").append(actualChecksumAfterCorruption).append("]");
-                msg.append(" file: ").append(fileToCorrupt.getName()).append(" length: ").append(dir.fileLength(fileToCorrupt.getName()));
+                msg.append(" file: ").append(fileToCorrupt.getFileName()).append(" length: ").append(dir.fileLength(fileToCorrupt.getFileName().toString()));
                 logger.info(msg.toString());
                 assumeTrue("Checksum collision - " + msg.toString(),
                         checksumAfterCorruption != checksumBeforeCorruption // collision
@@ -541,21 +558,21 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
     /**
      * prunes the list of index files such that only the latest del generation files are contained.
      */
-    private void pruneOldDeleteGenerations(Set<File> files) {
-        final TreeSet<File> delFiles = new TreeSet<>();
-        for (File file : files) {
-            if (file.getName().endsWith(".liv")) {
+    private void pruneOldDeleteGenerations(Set<Path> files) {
+        final TreeSet<Path> delFiles = new TreeSet<>();
+        for (Path file : files) {
+            if (file.getFileName().toString().endsWith(".liv")) {
                 delFiles.add(file);
             }
         }
-        File last = null;
-        for (File current : delFiles) {
+        Path last = null;
+        for (Path current : delFiles) {
             if (last != null) {
-                final String newSegmentName = IndexFileNames.parseSegmentName(current.getName());
-                final String oldSegmentName = IndexFileNames.parseSegmentName(last.getName());
+                final String newSegmentName = IndexFileNames.parseSegmentName(current.getFileName().toString());
+                final String oldSegmentName = IndexFileNames.parseSegmentName(last.getFileName().toString());
                 if (newSegmentName.equals(oldSegmentName)) {
-                    int oldGen = Integer.parseInt(IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(last.getName())).replace("_", ""), Character.MAX_RADIX);
-                    int newGen = Integer.parseInt(IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(current.getName())).replace("_", ""), Character.MAX_RADIX);
+                    int oldGen = Integer.parseInt(IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(last.getFileName().toString())).replace("_", ""), Character.MAX_RADIX);
+                    int newGen = Integer.parseInt(IndexFileNames.stripExtension(IndexFileNames.stripSegmentName(current.getFileName().toString())).replace("_", ""), Character.MAX_RADIX);
                     if (newGen > oldGen) {
                         files.remove(last);
                     } else {
@@ -568,15 +585,19 @@ public class CorruptedFileTest extends ElasticsearchIntegrationTest {
         }
     }
 
-    public List<File> listShardFiles(ShardRouting routing) {
+    public List<Path> listShardFiles(ShardRouting routing) throws IOException {
         NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(routing.currentNodeId()).setFs(true).get();
 
         assertThat(routing.toString(), nodeStatses.getNodes().length, equalTo(1));
-        List<File> files = new ArrayList<>();
+        List<Path> files = new ArrayList<>();
         for (FsStats.Info info : nodeStatses.getNodes()[0].getFs()) {
             String path = info.getPath();
-            File file = new File(path, "indices/test/" + Integer.toString(routing.getId()) + "/index");
-            files.addAll(Arrays.asList(file.listFiles()));
+            Path file = Paths.get(path).resolve("indices/test/" + Integer.toString(routing.getId()) + "/index");
+            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
+                for (Path item : stream) {
+                    files.add(item);
+                }
+            }
         }
         return files;
     }

+ 36 - 21
src/test/java/org/elasticsearch/index/store/CorruptedTranslogTests.java

@@ -21,6 +21,7 @@ package org.elasticsearch.index.store;
 
 import com.carrotsearch.ant.tasks.junit4.dependencies.com.google.common.collect.Lists;
 import com.carrotsearch.randomizedtesting.generators.RandomPicks;
+
 import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
 import org.elasticsearch.action.index.IndexRequestBuilder;
 import org.elasticsearch.action.search.SearchPhaseExecutionException;
@@ -36,10 +37,14 @@ import org.elasticsearch.test.transport.MockTransportService;
 import org.elasticsearch.transport.TransportModule;
 import org.junit.Test;
 
-import java.io.File;
-import java.io.FileFilter;
 import java.io.IOException;
-import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
@@ -115,34 +120,44 @@ public class CorruptedTranslogTests extends ElasticsearchIntegrationTest {
         assertTrue(shardRouting.assignedToNode());
         String nodeId = shardRouting.currentNodeId();
         NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
-        Set<File> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
+        Set<Path> files = new TreeSet<>(); // treeset makes sure iteration order is deterministic
         for (FsStats.Info info : nodeStatses.getNodes()[0].getFs()) {
             String path = info.getPath();
             final String relativeDataLocationPath =  "indices/test/" + Integer.toString(shardRouting.getId()) + "/translog";
-            File file = new File(path, relativeDataLocationPath);
+            Path file = Paths.get(path).resolve(relativeDataLocationPath);
             logger.info("--> path: {}", file);
-            files.addAll(Arrays.asList(file.listFiles(new FileFilter() {
-                @Override
-                public boolean accept(File pathname) {
-                    logger.info("--> File: {}", pathname);
-                    return pathname.isFile() && pathname.getName().startsWith("translog-");
+            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
+                for (Path item : stream) {
+                    logger.info("--> File: {}", item);
+                    if (Files.isRegularFile(item) && item.getFileName().toString().startsWith("translog-")) {
+                        files.add(item);
+                    }
+
                 }
-            })));
+            }
         }
-        File fileToCorrupt = null;
+        Path fileToCorrupt = null;
         if (!files.isEmpty()) {
             int corruptions = randomIntBetween(5, 20);
             for (int i = 0; i < corruptions; i++) {
                 fileToCorrupt = RandomPicks.randomFrom(getRandom(), files);
-                try (RandomAccessFile raf = new RandomAccessFile(fileToCorrupt, "rw")) {
-                    raf.seek(randomIntBetween(0, (int) Math.min(Integer.MAX_VALUE, raf.length() - 1)));
-                    long filePointer = raf.getFilePointer();
-                    byte b = raf.readByte();
-                    raf.seek(filePointer);
-                    int corruptedValue = (b + 1) & 0xff;
-                    raf.writeByte(corruptedValue);
-                    raf.getFD().sync();
-                    logger.info("--> corrupting file {} --  flipping at position {} from {} to {} file: {}", fileToCorrupt.getName(), filePointer, Integer.toHexString(b), Integer.toHexString(corruptedValue), fileToCorrupt);
+                try (FileChannel raf = FileChannel.open(fileToCorrupt, StandardOpenOption.READ, StandardOpenOption.WRITE)) {
+                    // read
+                    raf.position(randomIntBetween(0, (int) Math.min(Integer.MAX_VALUE, raf.size() - 1)));
+                    long filePointer = raf.position();
+                    ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
+                    raf.read(bb);
+                    bb.flip();
+                    
+                    // corrupt
+                    byte oldValue = bb.get(0);
+                    byte newValue = (byte) (oldValue + 1);
+                    bb.put(0, newValue);
+                    
+                    // rewrite
+                    raf.position(filePointer);
+                    raf.write(bb);
+                    logger.info("--> corrupting file {} --  flipping at position {} from {} to {} file: {}", fileToCorrupt, filePointer, Integer.toHexString(oldValue), Integer.toHexString(newValue), fileToCorrupt);
                 }
             }
         }

+ 8 - 9
src/test/java/org/elasticsearch/index/store/DirectoryUtilsTest.java

@@ -19,15 +19,14 @@
 package org.elasticsearch.index.store;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
-import com.carrotsearch.randomizedtesting.annotations.Repeat;
-import com.carrotsearch.randomizedtesting.annotations.Seed;
+
 import org.apache.lucene.store.*;
 import org.elasticsearch.test.ElasticsearchLuceneTestCase;
 import org.elasticsearch.test.ElasticsearchTestCase;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 import java.util.Collections;
 import java.util.Set;
 
@@ -37,11 +36,11 @@ public class DirectoryUtilsTest extends ElasticsearchLuceneTestCase {
 
     @Test
     public void testGetLeave() throws IOException {
-        File file = ElasticsearchTestCase.newTempDir(LifecycleScope.TEST);
+        Path file = ElasticsearchTestCase.newTempDirPath(LifecycleScope.TEST);
         final int iters = scaledRandomIntBetween(10, 100);
         for (int i = 0; i < iters; i++) {
             {
-                BaseDirectoryWrapper dir = newFSDirectory(file.toPath());
+                BaseDirectoryWrapper dir = newFSDirectory(file);
                 FSDirectory directory = DirectoryUtils.getLeaf(new FilterDirectory(dir) {}, FSDirectory.class, null);
                 assertThat(directory, notNullValue());
                 assertThat(directory, sameInstance(DirectoryUtils.getLeafDirectory(dir)));
@@ -49,7 +48,7 @@ public class DirectoryUtilsTest extends ElasticsearchLuceneTestCase {
             }
 
             {
-                BaseDirectoryWrapper dir = newFSDirectory(file.toPath());
+                BaseDirectoryWrapper dir = newFSDirectory(file);
                 FSDirectory directory = DirectoryUtils.getLeaf(dir, FSDirectory.class, null);
                 assertThat(directory, notNullValue());
                 assertThat(directory, sameInstance(DirectoryUtils.getLeafDirectory(dir)));
@@ -58,7 +57,7 @@ public class DirectoryUtilsTest extends ElasticsearchLuceneTestCase {
 
             {
                 Set<String> stringSet = Collections.emptySet();
-                BaseDirectoryWrapper dir = newFSDirectory(file.toPath());
+                BaseDirectoryWrapper dir = newFSDirectory(file);
                 FSDirectory directory = DirectoryUtils.getLeaf(new FileSwitchDirectory(stringSet, dir, dir, random().nextBoolean()), FSDirectory.class, null);
                 assertThat(directory, notNullValue());
                 assertThat(directory, sameInstance(DirectoryUtils.getLeafDirectory(dir)));
@@ -67,7 +66,7 @@ public class DirectoryUtilsTest extends ElasticsearchLuceneTestCase {
 
             {
                 Set<String> stringSet = Collections.emptySet();
-                BaseDirectoryWrapper dir = newFSDirectory(file.toPath());
+                BaseDirectoryWrapper dir = newFSDirectory(file);
                 FSDirectory directory = DirectoryUtils.getLeaf(new FilterDirectory(new FileSwitchDirectory(stringSet, dir, dir, random().nextBoolean())) {}, FSDirectory.class, null);
                 assertThat(directory, notNullValue());
                 assertThat(directory, sameInstance(DirectoryUtils.getLeafDirectory(dir)));
@@ -76,7 +75,7 @@ public class DirectoryUtilsTest extends ElasticsearchLuceneTestCase {
 
             {
                 Set<String> stringSet = Collections.emptySet();
-                BaseDirectoryWrapper dir = newFSDirectory(file.toPath());
+                BaseDirectoryWrapper dir = newFSDirectory(file);
                 RAMDirectory directory = DirectoryUtils.getLeaf(new FilterDirectory(new FileSwitchDirectory(stringSet, dir, dir, random().nextBoolean())) {}, RAMDirectory.class, null);
                 assertThat(directory, nullValue());
                 dir.close();

+ 16 - 17
src/test/java/org/elasticsearch/index/translog/AbstractSimpleTranslogTests.java

@@ -35,11 +35,12 @@ import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
-import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.ArrayBlockingQueue;
@@ -87,7 +88,7 @@ public abstract class AbstractSimpleTranslogTests extends ElasticsearchTestCase
 
     protected abstract Translog create() throws IOException;
 
-    protected abstract String translogFileDirectory();
+    protected abstract Path translogFileDirectory();
 
     @Test
     public void testRead() throws IOException {
@@ -528,21 +529,19 @@ public abstract class AbstractSimpleTranslogTests extends ElasticsearchTestCase
     /**
      * Randomly overwrite some bytes in the translog files
      */
-    private void corruptTranslogs(String directory) throws Exception {
-        File[] files = new File(directory).listFiles();
-        if (files != null) {
-            for (File file : files) {
-                if (file.getName().startsWith("translog-")) {
-                    logger.info("--> corrupting {}...", file.getName());
-                    RandomAccessFile f = new RandomAccessFile(file, "rw");
-                    int corruptions = scaledRandomIntBetween(10, 50);
-                    for (int i = 0; i < corruptions; i++) {
-                        f.seek(randomIntBetween(0, (int)f.length()));
-                        f.write(randomByte());
-                    }
-                    f.close();
-                }
+    private void corruptTranslogs(Path directory) throws Exception {
+        Path[] files = FileSystemUtils.files(directory, "translog-*");
+        for (Path file : files) {
+            logger.info("--> corrupting {}...", file);
+            FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
+            int corruptions = scaledRandomIntBetween(10, 50);
+            for (int i = 0; i < corruptions; i++) {
+                // note: with the current logic, this will sometimes be a no-op
+                long pos = randomIntBetween(0, (int)f.size());
+                ByteBuffer junk = ByteBuffer.wrap(new byte[] { randomByte() });
+                f.write(junk, pos);
             }
+            f.close();
         }
     }
 

+ 4 - 3
src/test/java/org/elasticsearch/index/translog/fs/FsBufferedTranslogTests.java

@@ -28,6 +28,7 @@ import org.junit.AfterClass;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 import java.nio.file.Paths;
 
 /**
@@ -42,13 +43,13 @@ public class FsBufferedTranslogTests extends AbstractSimpleTranslogTests {
                         .put("index.translog.fs.type", FsTranslogFile.Type.BUFFERED.name())
                         .put("index.translog.fs.buffer_size", 10 + randomInt(128 * 1024))
                         .build(),
-                Paths.get(translogFileDirectory())
+                translogFileDirectory()
         );
     }
 
     @Override
-    protected String translogFileDirectory() {
-        return "data/fs-buf-translog";
+    protected Path translogFileDirectory() {
+        return Paths.get("data/fs-buf-translog");
     }
 
     @AfterClass

+ 4 - 3
src/test/java/org/elasticsearch/index/translog/fs/FsSimpleTranslogTests.java

@@ -28,6 +28,7 @@ import org.junit.AfterClass;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 import java.nio.file.Paths;
 
 /**
@@ -39,12 +40,12 @@ public class FsSimpleTranslogTests extends AbstractSimpleTranslogTests {
     protected Translog create() throws IOException {
         return new FsTranslog(shardId,
                 ImmutableSettings.settingsBuilder().put("index.translog.fs.type", FsTranslogFile.Type.SIMPLE.name()).build(),
-                Paths.get(translogFileDirectory()));
+                translogFileDirectory());
     }
 
     @Override
-    protected String translogFileDirectory() {
-        return "data/fs-simple-translog";
+    protected Path translogFileDirectory() {
+        return Paths.get("data/fs-simple-translog");
     }
 
     @AfterClass

+ 5 - 5
src/test/java/org/elasticsearch/indices/analyze/HunspellServiceTests.java

@@ -44,7 +44,7 @@ public class HunspellServiceTests extends ElasticsearchIntegrationTest {
     @Test
     public void testLocaleDirectoryWithNodeLevelConfig() throws Exception {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/conf_dir"))
                 .put(HUNSPELL_LAZY_LOAD, randomBoolean())
                 .put(HUNSPELL_IGNORE_CASE, true)
                 .build();
@@ -58,7 +58,7 @@ public class HunspellServiceTests extends ElasticsearchIntegrationTest {
     @Test
     public void testLocaleDirectoryWithLocaleSpecificConfig() throws Exception {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/conf_dir"))
                 .put(HUNSPELL_LAZY_LOAD, randomBoolean())
                 .put(HUNSPELL_IGNORE_CASE, true)
                 .put("indices.analysis.hunspell.dictionary.en_US.strict_affix_parsing", false)
@@ -81,7 +81,7 @@ public class HunspellServiceTests extends ElasticsearchIntegrationTest {
     @Test
     public void testCustomizeLocaleDirectory() throws Exception {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put(HUNSPELL_LOCATION, getResource("/indices/analyze/conf_dir/hunspell"))
+                .put(HUNSPELL_LOCATION, getResourcePath("/indices/analyze/conf_dir/hunspell"))
                 .build();
 
         internalCluster().startNode(settings);
@@ -92,7 +92,7 @@ public class HunspellServiceTests extends ElasticsearchIntegrationTest {
     @Test
     public void testDicWithNoAff() throws Exception {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/no_aff_conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/no_aff_conf_dir"))
                 .put(HUNSPELL_LAZY_LOAD, randomBoolean())
                 .build();
 
@@ -111,7 +111,7 @@ public class HunspellServiceTests extends ElasticsearchIntegrationTest {
     @Test
     public void testDicWithTwoAffs() throws Exception {
         Settings settings = ImmutableSettings.settingsBuilder()
-                .put("path.conf", getResource("/indices/analyze/two_aff_conf_dir"))
+                .put("path.conf", getResourcePath("/indices/analyze/two_aff_conf_dir"))
                 .put(HUNSPELL_LAZY_LOAD, randomBoolean())
                 .build();
 

+ 10 - 8
src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java

@@ -20,7 +20,7 @@ package org.elasticsearch.indices.template;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.google.common.base.Charsets;
-import com.google.common.io.Files;
+
 import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
 import org.elasticsearch.common.io.Streams;
 import org.elasticsearch.common.settings.ImmutableSettings;
@@ -29,7 +29,9 @@ import org.elasticsearch.test.ElasticsearchIntegrationTest;
 import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
 import org.junit.Test;
 
-import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.HashSet;
 import java.util.Set;
 
@@ -46,18 +48,18 @@ public class IndexTemplateFileLoadingTests extends ElasticsearchIntegrationTest
         settingsBuilder.put(super.nodeSettings(nodeOrdinal));
 
         try {
-            File directory = newTempDir(LifecycleScope.SUITE);
-            settingsBuilder.put("path.conf", directory.getPath());
+            Path directory = newTempDirPath(LifecycleScope.SUITE);
+            settingsBuilder.put("path.conf", directory.toAbsolutePath());
 
-            File templatesDir = new File(directory + File.separator + "templates");
-            templatesDir.mkdir();
+            Path templatesDir = directory.resolve("templates");
+            Files.createDirectory(templatesDir);
 
-            File dst = new File(templatesDir, "template.json");
+            Path dst = templatesDir.resolve("template.json");
             String templatePath = "/org/elasticsearch/indices/template/template" + randomInt(5) + ".json";
             logger.info("Picking template path [{}]", templatePath);
             // random template, one uses the 'setting.index.number_of_shards', the other 'settings.number_of_shards'
             String template = Streams.copyToStringFromClasspath(templatePath);
-            Files.write(template, dst, Charsets.UTF_8);
+            Files.write(dst, template.getBytes(StandardCharsets.UTF_8));
         } catch (Exception e) {
             throw new RuntimeException(e);
         }

+ 3 - 2
src/test/java/org/elasticsearch/nodesinfo/SimpleNodesInfoTests.java

@@ -20,6 +20,7 @@
 package org.elasticsearch.nodesinfo;
 
 import com.google.common.collect.Lists;
+
 import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
 import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
 import org.elasticsearch.action.admin.cluster.node.info.PluginInfo;
@@ -33,9 +34,9 @@ import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
 import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
 import org.junit.Test;
 
-import java.io.File;
 import java.net.URISyntaxException;
 import java.net.URL;
+import java.nio.file.Paths;
 import java.util.Collections;
 import java.util.List;
 
@@ -161,7 +162,7 @@ public class SimpleNodesInfoTests extends ElasticsearchIntegrationTest {
         ImmutableSettings.Builder settings = settingsBuilder();
         settings.put(nodeSettings);
         if (resource != null) {
-            settings.put("path.plugins", new File(resource.toURI()).getAbsolutePath());
+            settings.put("path.plugins", Paths.get(resource.toURI()).toAbsolutePath());
         }
 
         if (pluginClassNames.length > 0) {

+ 1 - 1
src/test/java/org/elasticsearch/plugins/PluginManagerTests.java

@@ -386,7 +386,7 @@ public class PluginManagerTests extends ElasticsearchIntegrationTest {
 
         // We want to check that Plugin Manager moves content to _site
         String pluginDir = PLUGIN_DIR.concat("/plugin-site/_site");
-        assertFileExists(new File(pluginDir));
+        assertFileExists(Paths.get(pluginDir));
     }
 
 

+ 5 - 4
src/test/java/org/elasticsearch/plugins/PluginManagerUnitTests.java

@@ -20,13 +20,14 @@
 package org.elasticsearch.plugins;
 
 import com.google.common.io.Files;
+
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.env.Environment;
 import org.elasticsearch.test.ElasticsearchTestCase;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 
 import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
 import static org.hamcrest.Matchers.is;
@@ -39,8 +40,8 @@ public class PluginManagerUnitTests extends ElasticsearchTestCase {
     @Test
     public void testThatConfigDirectoryCanBeOutsideOfElasticsearchHomeDirectory() throws IOException {
         String pluginName = randomAsciiOfLength(10);
-        File homeFolder = newTempDir();
-        File genericConfigFolder = newTempDir();
+        Path homeFolder = newTempDirPath();
+        Path genericConfigFolder = newTempDirPath();
 
         Settings settings = settingsBuilder()
                 .put("path.conf", genericConfigFolder)
@@ -50,7 +51,7 @@ public class PluginManagerUnitTests extends ElasticsearchTestCase {
 
         PluginManager.PluginHandle pluginHandle = new PluginManager.PluginHandle(pluginName, "version", "user", "repo");
         String configDirPath = Files.simplifyPath(pluginHandle.configDir(environment).normalize().toString());
-        String expectedDirPath = Files.simplifyPath(new File(genericConfigFolder, pluginName).toPath().normalize().toString());
+        String expectedDirPath = Files.simplifyPath(genericConfigFolder.resolve(pluginName).normalize().toString());
 
         assertThat(configDirPath, is(expectedDirPath));
     }

+ 4 - 3
src/test/java/org/elasticsearch/plugins/SitePluginTests.java

@@ -30,8 +30,9 @@ import org.elasticsearch.test.rest.client.http.HttpRequestBuilder;
 import org.elasticsearch.test.rest.client.http.HttpResponse;
 import org.junit.Test;
 
-import java.io.File;
 import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 
 import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
 import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope;
@@ -48,10 +49,10 @@ public class SitePluginTests extends ElasticsearchIntegrationTest {
     @Override
     protected Settings nodeSettings(int nodeOrdinal) {
         try {
-            File pluginDir = new File(SitePluginTests.class.getResource("/org/elasticsearch/plugins").toURI());
+            Path pluginDir = Paths.get(SitePluginTests.class.getResource("/org/elasticsearch/plugins").toURI());
             return settingsBuilder()
                     .put(super.nodeSettings(nodeOrdinal))
-                    .put("path.plugins", pluginDir.getAbsolutePath())
+                    .put("path.plugins", pluginDir.toAbsolutePath())
                     .put("force.http.enabled", true)
                     .build();
         } catch (URISyntaxException ex) {

+ 1 - 1
src/test/java/org/elasticsearch/script/OnDiskScriptTests.java

@@ -41,7 +41,7 @@ public class OnDiskScriptTests extends ElasticsearchIntegrationTest {
     public Settings nodeSettings(int nodeOrdinal) {
         //Set path so ScriptService will pick up the test scripts
         return settingsBuilder().put(super.nodeSettings(nodeOrdinal))
-                .put("path.conf", this.getResource("config").getPath()).build();
+                .put("path.conf", this.getResourcePath("config")).build();
     }
 
 

+ 2 - 3
src/test/java/org/elasticsearch/script/ScriptServiceTests.java

@@ -29,7 +29,6 @@ import org.elasticsearch.test.ElasticsearchTestCase;
 import org.elasticsearch.watcher.ResourceWatcherService;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -46,8 +45,8 @@ public class ScriptServiceTests extends ElasticsearchTestCase {
 
     @Test
     public void testScriptsWithoutExtensions() throws IOException {
-        Path homeFolder = newTempDir().toPath();
-        Path genericConfigFolder = newTempDir().toPath();
+        Path homeFolder = newTempDirPath();
+        Path genericConfigFolder = newTempDirPath();
 
         Settings settings = settingsBuilder()
                 .put("path.conf", genericConfigFolder)

+ 1 - 1
src/test/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricTests.java

@@ -114,7 +114,7 @@ public class ScriptedMetricTests extends ElasticsearchIntegrationTest {
     protected Settings nodeSettings(int nodeOrdinal) {
         Settings settings = ImmutableSettings.settingsBuilder()
                 .put(super.nodeSettings(nodeOrdinal))
-                .put("path.conf", getResource("/org/elasticsearch/search/aggregations/metrics/scripted/conf"))
+                .put("path.conf", getResourcePath("/org/elasticsearch/search/aggregations/metrics/scripted/conf"))
                 .build();
         return settings;
     }

+ 16 - 13
src/test/java/org/elasticsearch/snapshots/AbstractSnapshotTests.java

@@ -20,6 +20,7 @@ package org.elasticsearch.snapshots;
 
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
+
 import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
 import org.elasticsearch.cluster.metadata.SnapshotId;
 import org.elasticsearch.cluster.metadata.SnapshotMetaData;
@@ -30,8 +31,13 @@ import org.elasticsearch.snapshots.mockstore.MockRepository;
 import org.elasticsearch.test.ElasticsearchIntegrationTest;
 import org.junit.Ignore;
 
-import java.io.File;
 import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import static org.hamcrest.Matchers.equalTo;
 
@@ -49,19 +55,16 @@ public abstract class AbstractSnapshotTests extends ElasticsearchIntegrationTest
         return failureCount;
     }
 
-    public static int numberOfFiles(File dir) {
-        int count = 0;
-        File[] files = dir.listFiles();
-        if (files != null) {
-            for (File file : files) {
-                if (file.isDirectory()) {
-                    count += numberOfFiles(file);
-                } else {
-                    count++;
-                }
+    public static int numberOfFiles(Path dir) throws IOException {
+        final AtomicInteger count = new AtomicInteger();
+        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
+            @Override
+            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+                count.incrementAndGet();
+                return FileVisitResult.CONTINUE;
             }
-        }
-        return count;
+        });
+        return count.get();
     }
 
     public static void stopNode(final String node) throws IOException {

+ 4 - 3
src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java

@@ -25,6 +25,7 @@ import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.util.concurrent.ListenableFuture;
+
 import org.elasticsearch.ElasticsearchParseException;
 import org.elasticsearch.action.ListenableActionFuture;
 import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse;
@@ -58,8 +59,8 @@ import org.elasticsearch.threadpool.ThreadPool;
 import org.junit.Ignore;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.EnumSet;
 import java.util.List;
@@ -116,7 +117,7 @@ public class DedicatedClusterSnapshotRestoreTests extends AbstractSnapshotTests
 
     @Test
     public void restoreCustomMetadata() throws Exception {
-        File tempDir = newTempDir();
+        Path tempDir = newTempDirPath();
 
         logger.info("--> start node");
         internalCluster().startNode(settingsBuilder().put("gateway.type", "local"));
@@ -308,7 +309,7 @@ public class DedicatedClusterSnapshotRestoreTests extends AbstractSnapshotTests
         assertThat(client.prepareCount("test-idx").get().getCount(), equalTo(100L));
 
         logger.info("--> creating repository");
-        File repo = newTempDir(LifecycleScope.TEST);
+        Path repo = newTempDirPath(LifecycleScope.TEST);
         PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
                         ImmutableSettings.settingsBuilder()

+ 8 - 6
src/test/java/org/elasticsearch/snapshots/RepositoriesTests.java

@@ -20,6 +20,7 @@ package org.elasticsearch.snapshots;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.google.common.collect.ImmutableList;
+
 import org.elasticsearch.action.admin.cluster.repositories.delete.DeleteRepositoryResponse;
 import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesResponse;
 import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse;
@@ -29,6 +30,7 @@ import org.elasticsearch.client.Client;
 import org.elasticsearch.cluster.metadata.MetaData;
 import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
 import org.elasticsearch.cluster.metadata.RepositoryMetaData;
+import org.elasticsearch.common.io.FileSystemUtils;
 import org.elasticsearch.common.settings.ImmutableSettings;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.repositories.RepositoryException;
@@ -36,7 +38,7 @@ import org.elasticsearch.repositories.RepositoryVerificationException;
 import org.elasticsearch.snapshots.mockstore.MockRepositoryModule;
 import org.junit.Test;
 
-import java.io.File;
+import java.nio.file.Path;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
@@ -52,7 +54,7 @@ public class RepositoriesTests extends AbstractSnapshotTests {
     public void testRepositoryCreation() throws Exception {
         Client client = client();
 
-        File location = newTempDir(LifecycleScope.SUITE);
+        Path location = newTempDirPath(LifecycleScope.SUITE);
 
         logger.info("-->  creating repository");
         PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo-1")
@@ -62,12 +64,12 @@ public class RepositoriesTests extends AbstractSnapshotTests {
         assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
 
         logger.info("--> verify the repository");
-        int numberOfFiles = location.listFiles().length;
+        int numberOfFiles = FileSystemUtils.files(location).length;
         VerifyRepositoryResponse verifyRepositoryResponse = client.admin().cluster().prepareVerifyRepository("test-repo-1").get();
         assertThat(verifyRepositoryResponse.getNodes().length, equalTo(cluster().numDataAndMasterNodes()));
 
         logger.info("--> verify that we didn't leave any files as a result of verification");
-        assertThat(location.listFiles().length, equalTo(numberOfFiles));
+        assertThat(FileSystemUtils.files(location).length, equalTo(numberOfFiles));
 
         logger.info("--> check that repository is really there");
         ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().clear().setMetaData(true).get();
@@ -185,7 +187,7 @@ public class RepositoriesTests extends AbstractSnapshotTests {
         logger.info("-->  verifying repository");
         assertThrows(client.admin().cluster().prepareVerifyRepository("test-repo-1"), RepositoryVerificationException.class);
 
-        File location = newTempDir(LifecycleScope.SUITE);
+        Path location = newTempDirPath(LifecycleScope.SUITE);
 
         logger.info("-->  creating repository");
         try {
@@ -220,7 +222,7 @@ public class RepositoriesTests extends AbstractSnapshotTests {
         logger.info("-->  verifying repository");
         assertThrows(client.admin().cluster().prepareVerifyRepository("test-repo-1"), RepositoryVerificationException.class);
 
-        File location = newTempDir(LifecycleScope.SUITE);
+        Path location = newTempDirPath(LifecycleScope.SUITE);
 
         logger.info("-->  creating repository");
         try {

+ 41 - 40
src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreTests.java

@@ -22,6 +22,7 @@ package org.elasticsearch.snapshots;
 import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
+
 import org.apache.lucene.util.IOUtils;
 import org.apache.lucene.util.LuceneTestCase.Slow;
 import org.elasticsearch.ExceptionsHelper;
@@ -53,8 +54,8 @@ import org.elasticsearch.repositories.RepositoriesService;
 import org.elasticsearch.snapshots.mockstore.MockRepositoryModule;
 import org.junit.Test;
 
-import java.io.File;
 import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -76,7 +77,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
 
@@ -169,7 +170,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         String indexName = "testindex";
         String repoName = "test-restore-snapshot-repo";
         String snapshotName = "test-restore-snapshot";
-        String absolutePath = newTempDir().getAbsolutePath();
+        String absolutePath = newTempDirPath().toAbsolutePath().toString();
         logger.info("Path [{}]", absolutePath);
         String restoredIndexName = indexName + "-restored";
         String typeName = "actions";
@@ -215,7 +216,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
 
@@ -263,7 +264,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
         logger.info("-->  creating repository");
         PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
-                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())).get();
+                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDirPath())).get();
         assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
 
         logger.info("--> snapshot");
@@ -280,7 +281,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
-                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())));
+                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDirPath())));
 
         logger.info("--> create test indices");
         createIndex("test-idx-1", "test-idx-2", "test-idx-3");
@@ -336,7 +337,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
-                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())));
+                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDirPath())));
 
         logger.info("-->  creating test template");
         assertThat(client.admin().indices().preparePutTemplate("test-template").setTemplate("te*").addMapping("test-mapping", "{}").get().isAcknowledged(), equalTo(true));
@@ -368,7 +369,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         Client client = client();
 
         logger.info("-->  creating repository");
-        File location = newTempDir();
+        Path location = newTempDirPath();
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", location)));
 
@@ -450,7 +451,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
                         ImmutableSettings.settingsBuilder()
-                                .put("location", newTempDir(LifecycleScope.TEST))
+                                .put("location", newTempDirPath(LifecycleScope.TEST))
                                 .put("random", randomAsciiOfLength(10))
                                 .put("random_control_io_exception_rate", 0.2))
                 .setVerify(false));
@@ -500,7 +501,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
                         ImmutableSettings.settingsBuilder()
-                                .put("location", newTempDir(LifecycleScope.TEST))
+                                .put("location", newTempDirPath(LifecycleScope.TEST))
                                 .put("random", randomAsciiOfLength(10))
                                 .put("random_data_file_io_exception_rate", 0.3)));
 
@@ -562,7 +563,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
     @Test
     public void dataFileFailureDuringRestoreTest() throws Exception {
-        File repositoryLocation = newTempDir(LifecycleScope.TEST);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.TEST);
         Client client = client();
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
@@ -604,7 +605,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
     @Test
     public void deletionOfFailingToRecoverIndexShouldStopRestore() throws Exception {
-        File repositoryLocation = newTempDir(LifecycleScope.TEST);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.TEST);
         Client client = client();
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
@@ -673,7 +674,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))));
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))));
 
         logger.info("-->  creating index that cannot be allocated");
         prepareCreate("test-idx", 2, ImmutableSettings.builder().put(FilterAllocationDecider.INDEX_ROUTING_INCLUDE_GROUP + ".tag", "nowhere").put("index.number_of_shards", 3)).get();
@@ -691,8 +692,8 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         final int numberOfSnapshots = between(5, 15);
         Client client = client();
 
-        File repo = newTempDir(LifecycleScope.SUITE);
-        logger.info("-->  creating repository at " + repo.getAbsolutePath());
+        Path repo = newTempDirPath(LifecycleScope.SUITE);
+        logger.info("-->  creating repository at " + repo.toAbsolutePath());
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
                         .put("location", repo)
@@ -748,8 +749,8 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
     public void deleteSnapshotWithMissingIndexAndShardMetadataTest() throws Exception {
         Client client = client();
 
-        File repo = newTempDir(LifecycleScope.SUITE);
-        logger.info("-->  creating repository at " + repo.getAbsolutePath());
+        Path repo = newTempDirPath(LifecycleScope.SUITE);
+        logger.info("-->  creating repository at " + repo.toAbsolutePath());
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
                         .put("location", repo)
@@ -769,12 +770,12 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
 
         logger.info("--> delete index metadata and shard metadata");
-        File indices = new File(repo, "indices");
-        File testIndex1 = new File(indices, "test-idx-1");
-        File testIndex2 = new File(indices, "test-idx-2");
-        File testIndex2Shard0 = new File(testIndex2, "0");
-        IOUtils.deleteFilesIgnoringExceptions(new File(testIndex1, "snapshot-test-snap-1").toPath());
-        IOUtils.deleteFilesIgnoringExceptions(new File(testIndex2Shard0, "snapshot-test-snap-1").toPath());
+        Path indices = repo.resolve("indices");
+        Path testIndex1 = indices.resolve("test-idx-1");
+        Path testIndex2 = indices.resolve("test-idx-2");
+        Path testIndex2Shard0 = testIndex2.resolve("0");
+        IOUtils.deleteFilesIgnoringExceptions(testIndex1.resolve("snapshot-test-snap-1"));
+        IOUtils.deleteFilesIgnoringExceptions(testIndex2Shard0.resolve("snapshot-test-snap-1"));
 
         logger.info("--> delete snapshot");
         client.admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap-1").get();
@@ -787,8 +788,8 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
     public void deleteSnapshotWithMissingMetadataTest() throws Exception {
         Client client = client();
 
-        File repo = newTempDir(LifecycleScope.SUITE);
-        logger.info("-->  creating repository at " + repo.getAbsolutePath());
+        Path repo = newTempDirPath(LifecycleScope.SUITE);
+        logger.info("-->  creating repository at " + repo.toAbsolutePath());
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
                         .put("location", repo)
@@ -808,8 +809,8 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
 
         logger.info("--> delete index metadata and shard metadata");
-        File metadata = new File(repo, "metadata-test-snap-1");
-        Files.delete(metadata.toPath());
+        Path metadata = repo.resolve("metadata-test-snap-1");
+        Files.delete(metadata);
 
         logger.info("--> delete snapshot");
         client.admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap-1").get();
@@ -825,7 +826,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))));
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))));
 
         createIndex("test-idx", "test-idx-closed");
         ensureGreen();
@@ -851,7 +852,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))));
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))));
 
         createIndex("test-idx");
         ensureGreen();
@@ -872,7 +873,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))));
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))));
 
         createIndex("test-idx-1", "test-idx-2", "test-idx-3");
         ensureGreen();
@@ -988,7 +989,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
     @Test
     public void moveShardWhileSnapshottingTest() throws Exception {
         Client client = client();
-        File repositoryLocation = newTempDir(LifecycleScope.TEST);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.TEST);
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
@@ -1050,7 +1051,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
     @Test
     public void deleteRepositoryWhileSnapshottingTest() throws Exception {
         Client client = client();
-        File repositoryLocation = newTempDir(LifecycleScope.TEST);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.TEST);
         logger.info("-->  creating repository");
         PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
@@ -1092,7 +1093,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("--> trying to move repository to another location");
         try {
             client.admin().cluster().preparePutRepository("test-repo")
-                    .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", new File(repositoryLocation, "test"))
+                    .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", repositoryLocation.resolve("test"))
             ).get();
             fail("shouldn't be able to replace in-use repository");
         } catch (Exception ex) {
@@ -1101,7 +1102,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
 
         logger.info("--> trying to create a repository with different name");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo-2")
-                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", new File(repositoryLocation, "test"))));
+                .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", repositoryLocation.resolve("test"))));
 
         logger.info("--> unblocking blocked node");
         unblockNode(blockedNode);
@@ -1135,7 +1136,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         Client client = client();
 
         logger.info("-->  creating repository");
-        File repositoryLocation = newTempDir(LifecycleScope.SUITE);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.SUITE);
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
                         .put("location", repositoryLocation)
@@ -1165,7 +1166,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("--> create read-only URL repository");
         assertAcked(client.admin().cluster().preparePutRepository("url-repo")
                 .setType("url").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("url", repositoryLocation.toURI().toURL())
+                        .put("url", repositoryLocation.toUri().toURL())
                         .put("list_directories", randomBoolean())));
         logger.info("--> restore index after deletion");
         RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot("url-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx").execute().actionGet();
@@ -1193,7 +1194,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         Client client = client();
 
         logger.info("-->  creating repository");
-        File repositoryLocation = newTempDir(LifecycleScope.SUITE);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.SUITE);
         boolean throttleSnapshot = randomBoolean();
         boolean throttleRestore = randomBoolean();
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
@@ -1251,7 +1252,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
     @Test
     public void snapshotStatusTest() throws Exception {
         Client client = client();
-        File repositoryLocation = newTempDir(LifecycleScope.TEST);
+        Path repositoryLocation = newTempDirPath(LifecycleScope.TEST);
         logger.info("-->  creating repository");
         PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo")
                 .setType(MockRepositoryModule.class.getCanonicalName()).setSettings(
@@ -1346,7 +1347,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
 
@@ -1394,7 +1395,7 @@ public class SharedClusterSnapshotRestoreTests extends AbstractSnapshotTests {
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE))
+                        .put("location", newTempDirPath(LifecycleScope.SUITE))
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
 

+ 7 - 4
src/test/java/org/elasticsearch/snapshots/SnapshotBackwardsCompatibilityTest.java

@@ -20,6 +20,7 @@ package org.elasticsearch.snapshots;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.carrotsearch.randomizedtesting.generators.RandomPicks;
+
 import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryResponse;
 import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
 import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
@@ -31,13 +32,15 @@ import org.elasticsearch.action.index.IndexRequestBuilder;
 import org.elasticsearch.client.Client;
 import org.elasticsearch.cluster.metadata.IndexMetaData;
 import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
+import org.elasticsearch.common.io.FileSystemUtils;
 import org.elasticsearch.common.settings.ImmutableSettings;
 import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest;
 import org.junit.Ignore;
 import org.junit.Test;
 
-import java.io.File;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
@@ -56,7 +59,7 @@ public class SnapshotBackwardsCompatibilityTest extends ElasticsearchBackwardsCo
         logger.info("-->  creating repository");
         assertAcked(client().admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
-                        .put("location", newTempDir(LifecycleScope.SUITE).getAbsolutePath())
+                        .put("location", newTempDirPath(LifecycleScope.SUITE).toAbsolutePath())
                         .put("compress", randomBoolean())
                         .put("chunk_size", randomIntBetween(100, 1000))));
         String[] indicesBefore = new String[randomIntBetween(2,5)];
@@ -162,7 +165,7 @@ public class SnapshotBackwardsCompatibilityTest extends ElasticsearchBackwardsCo
 
     public void testSnapshotMoreThanOnce() throws ExecutionException, InterruptedException, IOException {
         Client client = client();
-        final File tempDir = newTempDir(LifecycleScope.SUITE).getAbsoluteFile();
+        final Path tempDir = newTempDirPath(LifecycleScope.SUITE).toAbsolutePath();
         logger.info("-->  creating repository");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo")
                 .setType("fs").setSettings(ImmutableSettings.settingsBuilder()
@@ -219,7 +222,7 @@ public class SnapshotBackwardsCompatibilityTest extends ElasticsearchBackwardsCo
             logger.info("--> move from 0 to 1 replica");
             client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)).get();
         }
-        logger.debug("---> repo exists: " + new File(tempDir, "indices/test/0").exists() + " files: " + Arrays.toString(new File(tempDir, "indices/test/0").list())); // it's only one shard!
+        logger.debug("---> repo exists: " + Files.exists(tempDir.resolve("indices/test/0")) + " files: " + Arrays.toString(FileSystemUtils.files(tempDir.resolve("indices/test/0")))); // it's only one shard!
         CreateSnapshotResponse createSnapshotResponseSecond = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-1").setWaitForCompletion(true).setIndices("test").get();
         assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), greaterThan(0));
         assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseSecond.getSnapshotInfo().totalShards()));

+ 11 - 7
src/test/java/org/elasticsearch/snapshots/mockstore/MockRepository.java

@@ -20,6 +20,7 @@
 package org.elasticsearch.snapshots.mockstore;
 
 import com.google.common.collect.ImmutableMap;
+
 import org.elasticsearch.ElasticsearchException;
 import org.elasticsearch.cluster.ClusterService;
 import org.elasticsearch.common.blobstore.BlobMetaData;
@@ -33,7 +34,12 @@ import org.elasticsearch.repositories.RepositoryName;
 import org.elasticsearch.repositories.RepositorySettings;
 import org.elasticsearch.repositories.fs.FsRepository;
 
-import java.io.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.util.concurrent.ConcurrentHashMap;
@@ -92,9 +98,9 @@ public class MockRepository extends FsRepository {
     }
 
     private static Settings localizeLocation(Settings settings, ClusterService clusterService) {
-        File location = new File(settings.get("location"));
-        location = new File(location, clusterService.localNode().getId());
-        return settingsBuilder().put(settings).put("location", location.getAbsolutePath()).build();
+        Path location = Paths.get(settings.get("location"));
+        location = location.resolve(clusterService.localNode().getId());
+        return settingsBuilder().put(settings).put("location", location.toAbsolutePath()).build();
     }
 
     private void addFailure() {
@@ -200,9 +206,7 @@ public class MockRepository extends FsRepository {
                     int i = 0;
                     return ((bytes[i++] & 0xFF) << 24) | ((bytes[i++] & 0xFF) << 16)
                             | ((bytes[i++] & 0xFF) << 8) | (bytes[i++] & 0xFF);
-                } catch (NoSuchAlgorithmException ex) {
-                    throw new ElasticsearchException("cannot calculate hashcode", ex);
-                } catch (UnsupportedEncodingException ex) {
+                } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
                     throw new ElasticsearchException("cannot calculate hashcode", ex);
                 }
             }

+ 9 - 7
src/test/java/org/elasticsearch/test/ElasticsearchBackwardsCompatIntegrationTest.java

@@ -37,8 +37,10 @@ import org.elasticsearch.transport.netty.NettyTransport;
 import org.junit.Before;
 import org.junit.Ignore;
 
-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.Map;
 
 import static org.hamcrest.Matchers.is;
@@ -84,7 +86,7 @@ import static org.hamcrest.Matchers.is;
 @Ignore
 public abstract class ElasticsearchBackwardsCompatIntegrationTest extends ElasticsearchIntegrationTest {
 
-    private static File backwardsCompatibilityPath() {
+    private static Path backwardsCompatibilityPath() {
         String path = System.getProperty(TESTS_BACKWARDS_COMPATIBILITY_PATH);
         if (path == null || path.isEmpty()) {
             throw new IllegalArgumentException("Must specify backwards test path with property " + TESTS_BACKWARDS_COMPATIBILITY_PATH);
@@ -97,12 +99,12 @@ public abstract class ElasticsearchBackwardsCompatIntegrationTest extends Elasti
             throw new IllegalArgumentException("Backcompat elasticsearch version must be same major version as current. " +
                 "backcompat: " + version + ", current: " + Version.CURRENT.toString());
         }
-        File file = new File(path, "elasticsearch-" + version);
-        if (!file.exists()) {
-            throw new IllegalArgumentException("Backwards tests location is missing: " + file.getAbsolutePath());
+        Path file = Paths.get(path, "elasticsearch-" + version);
+        if (!Files.exists(file)) {
+            throw new IllegalArgumentException("Backwards tests location is missing: " + file.toAbsolutePath());
         }
-        if (!file.isDirectory()) {
-            throw new IllegalArgumentException("Backwards tests location is not a directory: " + file.getAbsolutePath());
+        if (!Files.isDirectory(file)) {
+            throw new IllegalArgumentException("Backwards tests location is not a directory: " + file.toAbsolutePath());
         }
         return file;
     }

+ 23 - 20
src/test/java/org/elasticsearch/test/ElasticsearchIntegrationTest.java

@@ -26,6 +26,7 @@ import com.carrotsearch.randomizedtesting.generators.RandomPicks;
 import com.google.common.base.Joiner;
 import com.google.common.base.Predicate;
 import com.google.common.collect.Lists;
+
 import org.apache.lucene.store.StoreRateLimiting;
 import org.apache.lucene.util.AbstractRandomizedTest;
 import org.apache.lucene.util.IOUtils;
@@ -71,6 +72,7 @@ import org.elasticsearch.common.Priority;
 import org.elasticsearch.common.Strings;
 import org.elasticsearch.common.collect.ImmutableOpenMap;
 import org.elasticsearch.common.collect.Tuple;
+import org.elasticsearch.common.io.FileSystemUtils;
 import org.elasticsearch.common.regex.Regex;
 import org.elasticsearch.common.settings.ImmutableSettings;
 import org.elasticsearch.common.settings.Settings;
@@ -115,13 +117,14 @@ import org.hamcrest.Matchers;
 import org.joda.time.DateTimeZone;
 import org.junit.*;
 
-import java.io.File;
-import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.*;
 import java.util.concurrent.*;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -1850,31 +1853,31 @@ public abstract class ElasticsearchIntegrationTest extends ElasticsearchTestCase
     /**
      * Return settings that could be used to start a node that has the given zipped home directory.
      */
-    protected Settings prepareBackwardsDataDir(File backwardsIndex, Object... settings) throws IOException {
-        File indexDir = newTempDir();
-        File dataDir = new File(indexDir, "data");
-        try (FileInputStream stream = new FileInputStream(backwardsIndex)) {
-            TestUtil.unzip(stream, indexDir.toPath());
+    protected Settings prepareBackwardsDataDir(Path backwardsIndex, Object... settings) throws IOException {
+        Path indexDir = newTempDirPath();
+        Path dataDir = indexDir.resolve("data");
+        try (InputStream stream = Files.newInputStream(backwardsIndex)) {
+            TestUtil.unzip(stream, indexDir);
         }
-        assertTrue(dataDir.exists());
-        String[] list = dataDir.list();
-        if (list == null || list.length > 1) {
+        assertTrue(Files.exists(dataDir));
+        Path[] list = FileSystemUtils.files(dataDir);
+        if (list.length != 1) {
             throw new IllegalStateException("Backwards index must contain exactly one cluster");
         }
-        File src = new File(dataDir, list[0]);
-        File dest = new File(dataDir, internalCluster().getClusterName());
-        assertTrue(src.exists());
-        src.renameTo(dest);
-        assertFalse(src.exists());
-        assertTrue(dest.exists());
+        Path src = list[0];
+        Path dest = dataDir.resolve(internalCluster().getClusterName());
+        assertTrue(Files.exists(src));
+        Files.move(src, dest);
+        assertFalse(Files.exists(src));
+        assertTrue(Files.exists(dest));
         ImmutableSettings.Builder builder = ImmutableSettings.builder()
                 .put(settings)
                 .put("gateway.type", "local") // this is important we need to recover from gateway
-                .put("path.data", dataDir.getPath());
+                .put("path.data", dataDir.toAbsolutePath());
 
-        File configDir = new File(indexDir, "config");
-        if (configDir.exists()) {
-            builder.put("path.conf", configDir.getPath());
+        Path configDir = indexDir.resolve("config");
+        if (Files.exists(configDir)) {
+            builder.put("path.conf", configDir.toAbsolutePath());
         }
         return builder.build();
     }

+ 34 - 14
src/test/java/org/elasticsearch/test/ElasticsearchTestCase.java

@@ -18,11 +18,13 @@
  */
 package org.elasticsearch.test;
 
+import com.carrotsearch.randomizedtesting.LifecycleScope;
 import com.carrotsearch.randomizedtesting.RandomizedTest;
 import com.carrotsearch.randomizedtesting.annotations.*;
 import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;
 import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
+
 import org.apache.lucene.store.MockDirectoryWrapper;
 import org.apache.lucene.store.SimpleFSDirectory;
 import org.apache.lucene.util.AbstractRandomizedTest;
@@ -195,19 +197,6 @@ public abstract class ElasticsearchTestCase extends AbstractRandomizedTest {
         return numericTypes[random.nextInt(numericTypes.length)];
     }
 
-    /**
-     * Returns a {@link File} pointing to the class path relative resource given
-     * as the first argument. In contrast to
-     * <code>getClass().getResource(...).getFile()</code> this method will not
-     * return URL encoded paths if the parent path contains spaces or other
-     * non-standard characters.
-     */
-    @Deprecated
-    public File getResource(String relativePath) {
-        URI uri = URI.create(getClass().getResource(relativePath).toString());
-        return new File(uri);
-    }
-
     /**
      * Returns a {@link java.nio.file.Path} pointing to the class path relative resource given
      * as the first argument. In contrast to
@@ -550,6 +539,37 @@ public abstract class ElasticsearchTestCase extends AbstractRandomizedTest {
     public static boolean terminate(ThreadPool service) throws InterruptedException {
         return ThreadPool.terminate(service, 10, TimeUnit.SECONDS);
     }
+    
+    // TODO: these method names stink, but are a temporary solution.
+    // see https://github.com/carrotsearch/randomizedtesting/pull/178
+
+    /**
+     * Returns a temporary file
+     */
+    public Path newTempFilePath() {
+        return newTempFile().toPath();
+    }
+    
+    /**
+     * Returns a temporary directory
+     */
+    public Path newTempDirPath() {
+        return newTempDir().toPath();
+    }
+    
+    /**
+     * Returns a temporary directory
+     */
+    public static Path newTempDirPath(LifecycleScope scope) {
+        return newTempDir(scope).toPath();
+    }
+    
+    /**
+     * Returns 'global' temp dir (seems like a bad idea)
+     */
+    public static Path globalTempDirPath() {
+        return globalTempDir().toPath();
+    }
 
     /**
      * Returns a random number of temporary paths.
@@ -558,7 +578,7 @@ public abstract class ElasticsearchTestCase extends AbstractRandomizedTest {
         final int numPaths = randomIntBetween(1, 3);
         final String[] absPaths = new String[numPaths];
         for (int i = 0; i < numPaths; i++) {
-            absPaths[i] = newTempDir().getAbsolutePath();
+            absPaths[i] = newTempDirPath().toAbsolutePath().toString();
         }
         return absPaths;
     }

+ 10 - 7
src/test/java/org/elasticsearch/test/ExternalNode.java

@@ -19,6 +19,7 @@
 package org.elasticsearch.test;
 
 import com.google.common.base.Predicate;
+
 import org.apache.lucene.util.Constants;
 import org.elasticsearch.Version;
 import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
@@ -35,8 +36,10 @@ import org.elasticsearch.discovery.DiscoveryModule;
 import org.elasticsearch.transport.TransportModule;
 
 import java.io.Closeable;
-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.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -57,7 +60,7 @@ final class ExternalNode implements Closeable {
             .put("node.mode", "network") // we need network mode for this
             .put("gateway.type", "local").build(); // we require local gateway to mimic upgrades of nodes
 
-    private final File path;
+    private final Path path;
     private final Random random;
     private final SettingsSource settingsSource;
     private Process process;
@@ -69,12 +72,12 @@ final class ExternalNode implements Closeable {
     private Settings externalNodeSettings;
 
 
-    ExternalNode(File path, long seed, SettingsSource settingsSource) {
+    ExternalNode(Path path, long seed, SettingsSource settingsSource) {
         this(path, null, seed, settingsSource);
     }
 
-    ExternalNode(File path, String clusterName, long seed, SettingsSource settingsSource) {
-        if (!path.isDirectory()) {
+    ExternalNode(Path path, String clusterName, long seed, SettingsSource settingsSource) {
+        if (!Files.isDirectory(path)) {
             throw new IllegalArgumentException("path must be a directory");
         }
         this.path = path;
@@ -127,11 +130,11 @@ final class ExternalNode implements Closeable {
             params.add("-Des." + entry.getKey() + "=" + entry.getValue());
         }
 
-        params.add("-Des.path.home=" + new File("").getAbsolutePath());
+        params.add("-Des.path.home=" + Paths.get(".").toAbsolutePath());
         params.add("-Des.path.conf=" + path + "/config");
 
         ProcessBuilder builder = new ProcessBuilder(params);
-        builder.directory(path);
+        builder.directory(path.toFile());
         builder.inheritIO();
         boolean success = false;
         try {

+ 3 - 1
src/test/java/org/elasticsearch/test/InternalTestCluster.java

@@ -29,6 +29,7 @@ import com.google.common.collect.*;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
+
 import org.apache.lucene.store.Lock;
 import org.apache.lucene.store.NativeFSLockFactory;
 import org.apache.lucene.util.AbstractRandomizedTest;
@@ -108,6 +109,7 @@ import java.nio.file.FileVisitResult;
 import java.nio.file.FileVisitor;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.util.*;
 import java.util.concurrent.ExecutorService;
@@ -277,7 +279,7 @@ public final class InternalTestCluster extends TestCluster {
             if (numOfDataPaths > 0) {
                 StringBuilder dataPath = new StringBuilder();
                 for (int i = 0; i < numOfDataPaths; i++) {
-                    dataPath.append(new File("data/d" + i).getAbsolutePath()).append(',');
+                    dataPath.append(Paths.get("data/d" + i).toAbsolutePath()).append(',');
                 }
                 builder.put("path.data", dataPath.toString());
             }

+ 4 - 16
src/test/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java

@@ -23,6 +23,7 @@ import com.google.common.base.Predicate;
 import com.google.common.base.Predicates;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.Iterables;
+
 import org.apache.lucene.search.BooleanQuery;
 import org.apache.lucene.search.Query;
 import org.elasticsearch.ElasticsearchException;
@@ -70,10 +71,10 @@ import org.hamcrest.Matcher;
 import org.hamcrest.Matchers;
 import org.junit.Assert;
 
-import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
@@ -784,25 +785,11 @@ public class ElasticsearchAssertions {
         }
     };
 
-    /**
-     * Check if a file exists
-     */
-    public static void assertFileExists(File file) {
-        assertThat("file/dir [" + file + "] should exist.", file.exists(), is(true));
-    }
-
     /**
      * Check if a file exists
      */
     public static void assertFileExists(Path file) {
-        assertFileExists(file.toFile());
-    }
-
-    /**
-     * Check if a directory exists
-     */
-    public static void assertDirectoryExists(File dir) {
-        assertFileExists(dir);
+        assertThat("file/dir [" + file + "] should exist.", Files.exists(file), is(true));
     }
 
     /**
@@ -810,5 +797,6 @@ public class ElasticsearchAssertions {
      */
     public static void assertDirectoryExists(Path dir) {
         assertFileExists(dir);
+        assertThat("file [" + dir + "] should be a directory.", Files.isDirectory(dir), is(true));
     }
 }

+ 5 - 3
src/test/java/org/elasticsearch/test/rest/ElasticsearchRestTests.java

@@ -25,6 +25,7 @@ import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;
 import com.carrotsearch.randomizedtesting.annotations.TestGroup;
 import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;
 import com.google.common.collect.Lists;
+
 import org.apache.lucene.util.AbstractRandomizedTest;
 import org.apache.lucene.util.TimeUnits;
 import org.elasticsearch.Version;
@@ -47,6 +48,7 @@ import org.junit.Test;
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.FileSystems;
+import java.nio.file.Path;
 import java.nio.file.PathMatcher;
 import java.nio.file.Paths;
 import java.util.*;
@@ -129,14 +131,14 @@ public class ElasticsearchRestTests extends ElasticsearchIntegrationTest {
 
     private static List<RestTestCandidate> collectTestCandidates() throws RestTestParseException, IOException {
         String[] paths = resolvePathsProperty(REST_TESTS_SUITE, DEFAULT_TESTS_PATH);
-        Map<String, Set<File>> yamlSuites = FileUtils.findYamlSuites(DEFAULT_TESTS_PATH, paths);
+        Map<String, Set<Path>> yamlSuites = FileUtils.findYamlSuites(DEFAULT_TESTS_PATH, paths);
 
         List<RestTestCandidate> testCandidates = Lists.newArrayList();
         RestTestSuiteParser restTestSuiteParser = new RestTestSuiteParser();
         //yaml suites are grouped by directory (effectively by api)
         for (String api : yamlSuites.keySet()) {
-            List<File> yamlFiles = Lists.newArrayList(yamlSuites.get(api));
-            for (File yamlFile : yamlFiles) {
+            List<Path> yamlFiles = Lists.newArrayList(yamlSuites.get(api));
+            for (Path yamlFile : yamlFiles) {
                 //tests distribution disabled for now since it causes reporting problems,
                 // due to the non unique suite name
                 //if (mustExecute(yamlFile.getAbsolutePath())) {

+ 14 - 16
src/test/java/org/elasticsearch/test/rest/parser/RestTestSuiteParser.java

@@ -18,29 +18,30 @@
  */
 package org.elasticsearch.test.rest.parser;
 
-import org.apache.lucene.util.IOUtils;
 import org.elasticsearch.common.xcontent.XContentParser;
 import org.elasticsearch.common.xcontent.yaml.YamlXContent;
 import org.elasticsearch.test.rest.section.RestTestSuite;
 import org.elasticsearch.test.rest.section.TestSection;
 
-import java.io.File;
-import java.io.FileInputStream;
 import java.io.IOException;
-import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 
 /**
  * Parser for a complete test suite (yaml file)
  */
 public class RestTestSuiteParser implements RestTestFragmentParser<RestTestSuite> {
 
-    public RestTestSuite parse(String api, File file) throws IOException, RestTestParseException {
+    public RestTestSuite parse(String api, Path file) throws IOException, RestTestParseException {
 
-        if (!file.isFile()) {
-            throw new IllegalArgumentException(file.getAbsolutePath() + " is not a file");
+        if (!Files.isRegularFile(file)) {
+            throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file");
         }
 
-        String filename = file.getName();
+        String filename = file.getFileName().toString();
         //remove the file extension
         int i = filename.lastIndexOf('.');
         if (i > 0) {
@@ -48,18 +49,15 @@ public class RestTestSuiteParser implements RestTestFragmentParser<RestTestSuite
         }
 
         //our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break.
-        RandomAccessFile randomAccessFile = null;
-        try {
-            randomAccessFile = new RandomAccessFile(file, "r");
-            randomAccessFile.skipBytes((int)randomAccessFile.length() - 1);
-            if (randomAccessFile.read() != 10) {
+        try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
+            ByteBuffer bb = ByteBuffer.wrap(new byte[1]);
+            channel.read(bb, channel.size() - 1);
+            if (bb.get(0) != 10) {
                 throw new RestTestParseException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)");
             }
-        } finally {
-            IOUtils.close(randomAccessFile);
         }
 
-        XContentParser parser = YamlXContent.yamlXContent.createParser(new FileInputStream(file));
+        XContentParser parser = YamlXContent.yamlXContent.createParser(Files.newInputStream(file));
         try {
             RestTestSuiteParseContext testParseContext = new RestTestSuiteParseContext(api, filename, parser);
             return parse(testParseContext);

+ 7 - 3
src/test/java/org/elasticsearch/test/rest/spec/RestSpec.java

@@ -19,6 +19,7 @@
 package org.elasticsearch.test.rest.spec;
 
 import com.google.common.collect.Maps;
+
 import org.elasticsearch.common.xcontent.XContentParser;
 import org.elasticsearch.common.xcontent.json.JsonXContent;
 import org.elasticsearch.test.rest.support.FileUtils;
@@ -26,6 +27,9 @@ import org.elasticsearch.test.rest.support.FileUtils;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Map;
 
 /**
@@ -51,9 +55,9 @@ public class RestSpec {
     public static RestSpec parseFrom(String optionalPathPrefix, String... paths) throws IOException {
         RestSpec restSpec = new RestSpec();
         for (String path : paths) {
-            for (File jsonFile : FileUtils.findJsonSpec(optionalPathPrefix, path)) {
-                try {
-                    XContentParser parser = JsonXContent.jsonXContent.createParser(new FileInputStream(jsonFile));
+            for (Path jsonFile : FileUtils.findJsonSpec(optionalPathPrefix, path)) {
+                try (InputStream stream = Files.newInputStream(jsonFile)) {
+                    XContentParser parser = JsonXContent.jsonXContent.createParser(stream);
                     RestApi restApi = new RestApiParser().parse(parser);
                     restSpec.addApi(restApi);
                 } catch (Throwable ex) {

+ 52 - 49
src/test/java/org/elasticsearch/test/rest/support/FileUtils.java

@@ -20,13 +20,23 @@ package org.elasticsearch.test.rest.support;
 
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
+
 import org.elasticsearch.common.Strings;
 
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.net.URI;
 import java.net.URL;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileSystems;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.NotDirectoryException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
 
@@ -43,25 +53,27 @@ public final class FileUtils {
      * Returns the json files found within the directory provided as argument.
      * Files are looked up in the classpath first, then outside of it if not found.
      */
-    public static Set<File> findJsonSpec(String optionalPathPrefix, String path) throws FileNotFoundException {
-        File dir = resolveFile(optionalPathPrefix, path, null);
+    public static Set<Path> findJsonSpec(String optionalPathPrefix, String path) throws IOException {
+        Path dir = resolveFile(optionalPathPrefix, path, null);
 
-        if (!dir.isDirectory()) {
-            throw new FileNotFoundException("file [" + path + "] is not a directory");
+        if (!Files.isDirectory(dir)) {
+            throw new NotDirectoryException(path);
         }
 
-        File[] jsonFiles = dir.listFiles(new FileFilter() {
-            @Override
-            public boolean accept(File pathname) {
-                return pathname.getName().endsWith(JSON_SUFFIX);
+        Set<Path> jsonFiles = new HashSet<>();
+        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
+            for (Path item : stream) {
+                if (item.toString().endsWith(JSON_SUFFIX)) {
+                    jsonFiles.add(item);
+                }
             }
-        });
+        }
 
-        if (jsonFiles == null || jsonFiles.length == 0) {
-            throw new FileNotFoundException("no json files found within [" + path + "]");
+        if (jsonFiles.isEmpty()) {
+            throw new NoSuchFileException(path, null, "no json files found");
         }
 
-        return Sets.newHashSet(jsonFiles);
+        return jsonFiles;
     }
 
     /**
@@ -69,15 +81,15 @@ public final class FileUtils {
      * Each input path can either be a single file (the .yaml suffix is optional) or a directory.
      * Each path is looked up in the classpath first, then outside of it if not found yet.
      */
-    public static Map<String, Set<File>> findYamlSuites(final String optionalPathPrefix, final String... paths) throws FileNotFoundException {
-        Map<String, Set<File>> yamlSuites = Maps.newHashMap();
+    public static Map<String, Set<Path>> findYamlSuites(final String optionalPathPrefix, final String... paths) throws IOException {
+        Map<String, Set<Path>> yamlSuites = Maps.newHashMap();
         for (String path : paths) {
             collectFiles(resolveFile(optionalPathPrefix, path, YAML_SUFFIX), YAML_SUFFIX, yamlSuites);
         }
         return yamlSuites;
     }
 
-    private static File resolveFile(String optionalPathPrefix, String path, String optionalFileSuffix) throws FileNotFoundException {
+    private static Path resolveFile(String optionalPathPrefix, String path, String optionalFileSuffix) throws IOException {
         //try within classpath with and without file suffix (as it could be a single test suite)
         URL resource = findResource(path, optionalFileSuffix);
         if (resource == null) {
@@ -85,16 +97,16 @@ public final class FileUtils {
             String newPath = optionalPathPrefix + "/" + path;
             resource = findResource(newPath, optionalFileSuffix);
             if (resource == null) {
-                //if it wasn't on classpath we look outside ouf the classpath
-                File file = findFile(path, optionalFileSuffix);
-                if (!file.exists()) {
-                    throw new FileNotFoundException("file [" + path + "] doesn't exist");
+                //if it wasn't on classpath we look outside of the classpath
+                Path file = findFile(path, optionalFileSuffix);
+                if (!Files.exists(file)) {
+                    throw new NoSuchFileException(path);
                 }
                 return file;
             }
         }
 
-        return new File(URI.create(resource.toString()));
+        return Paths.get(URI.create(resource.toString()));
     }
 
     private static URL findResource(String path, String optionalFileSuffix) {
@@ -108,38 +120,29 @@ public final class FileUtils {
         return resource;
     }
 
-    private static File findFile(String path, String optionalFileSuffix) {
-        File file = new File(path);
-        if (!file.exists()) {
-            file = new File(path + optionalFileSuffix);
+    private static Path findFile(String path, String optionalFileSuffix) {
+        Path file = Paths.get(path);
+        if (!Files.exists(file)) {
+            file = Paths.get(path + optionalFileSuffix);
         }
         return file;
     }
 
-    private static void collectFiles(final File file, final String fileSuffix, final Map<String, Set<File>> files) {
-        if (file.isFile()) {
-            String groupName = file.getParentFile().getName();
-            Set<File> filesSet = files.get(groupName);
-            if (filesSet == null) {
-                filesSet = Sets.newHashSet();
-                files.put(groupName, filesSet);
-            }
-            filesSet.add(file);
-        } else if (file.isDirectory()) {
-            walkDir(file, fileSuffix, files);
-        }
-    }
-
-    private static void walkDir(final File dir, final String fileSuffix, final Map<String, Set<File>> files) {
-        File[] children = dir.listFiles(new FileFilter() {
+    private static void collectFiles(final Path dir, final String fileSuffix, final Map<String, Set<Path>> files) throws IOException {
+        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
             @Override
-            public boolean accept(File pathname) {
-                return pathname.isDirectory() || pathname.getName().endsWith(fileSuffix);
+            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+                if (file.toString().endsWith(fileSuffix)) {
+                    String groupName = file.toAbsolutePath().getParent().getFileName().toString();
+                    Set<Path> filesSet = files.get(groupName);
+                    if (filesSet == null) {
+                        filesSet = Sets.newHashSet();
+                        files.put(groupName, filesSet);
+                    }
+                    filesSet.add(file);
+                }
+                return FileVisitResult.CONTINUE;
             }
         });
-
-        for (File file : children) {
-            collectFiles(file, fileSuffix, files);
-        }
     }
 }

+ 18 - 17
src/test/java/org/elasticsearch/test/rest/test/FileUtilsTests.java

@@ -22,7 +22,8 @@ import org.elasticsearch.test.ElasticsearchTestCase;
 import org.elasticsearch.test.rest.support.FileUtils;
 import org.junit.Test;
 
-import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Map;
 import java.util.Set;
 
@@ -34,7 +35,7 @@ public class FileUtilsTests extends ElasticsearchTestCase {
 
     @Test
     public void testLoadSingleYamlSuite() throws Exception {
-        Map<String,Set<File>> yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "/rest-api-spec/test/get/10_basic");
+        Map<String,Set<Path>> yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "/rest-api-spec/test/get/10_basic");
         assertSingleFile(yamlSuites, "get", "10_basic.yaml");
 
         //the path prefix is optional
@@ -49,7 +50,7 @@ public class FileUtilsTests extends ElasticsearchTestCase {
     @Test
     public void testLoadMultipleYamlSuites() throws Exception {
         //single directory
-        Map<String,Set<File>> yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get");
+        Map<String,Set<Path>> yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get");
         assertThat(yamlSuites, notNullValue());
         assertThat(yamlSuites.size(), equalTo(1));
         assertThat(yamlSuites.containsKey("get"), equalTo(true));
@@ -75,42 +76,42 @@ public class FileUtilsTests extends ElasticsearchTestCase {
         assertThat(yamlSuites.get("index").size(), greaterThan(1));
 
         //files can be loaded from classpath and from file system too
-        File dir = newTempDir();
-        File file = new File(dir, "test_loading.yaml");
-        assertThat(file.createNewFile(), equalTo(true));
+        Path dir = newTempDirPath();
+        Path file = dir.resolve("test_loading.yaml");
+        Files.createFile(file);
 
         //load from directory outside of the classpath
-        yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get/10_basic", dir.getAbsolutePath());
+        yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get/10_basic", dir.toAbsolutePath().toString());
         assertThat(yamlSuites, notNullValue());
         assertThat(yamlSuites.size(), equalTo(2));
         assertThat(yamlSuites.containsKey("get"), equalTo(true));
         assertThat(yamlSuites.get("get").size(), equalTo(1));
         assertSingleFile(yamlSuites.get("get"), "get", "10_basic.yaml");
-        assertThat(yamlSuites.containsKey(dir.getName()), equalTo(true));
-        assertSingleFile(yamlSuites.get(dir.getName()), dir.getName(), file.getName());
+        assertThat(yamlSuites.containsKey(dir.getFileName().toString()), equalTo(true));
+        assertSingleFile(yamlSuites.get(dir.getFileName().toString()), dir.getFileName().toString(), file.getFileName().toString());
 
         //load from external file (optional extension)
-        yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get/10_basic", dir.getAbsolutePath() + File.separator + "test_loading");
+        yamlSuites = FileUtils.findYamlSuites("/rest-api-spec/test", "get/10_basic", dir.resolve("test_loading").toAbsolutePath().toString());
         assertThat(yamlSuites, notNullValue());
         assertThat(yamlSuites.size(), equalTo(2));
         assertThat(yamlSuites.containsKey("get"), equalTo(true));
         assertThat(yamlSuites.get("get").size(), equalTo(1));
         assertSingleFile(yamlSuites.get("get"), "get", "10_basic.yaml");
-        assertThat(yamlSuites.containsKey(dir.getName()), equalTo(true));
-        assertSingleFile(yamlSuites.get(dir.getName()), dir.getName(), file.getName());
+        assertThat(yamlSuites.containsKey(dir.getFileName().toString()), equalTo(true));
+        assertSingleFile(yamlSuites.get(dir.getFileName().toString()), dir.getFileName().toString(), file.getFileName().toString());
     }
 
-    private static void assertSingleFile(Map<String, Set<File>> yamlSuites, String dirName, String fileName) {
+    private static void assertSingleFile(Map<String, Set<Path>> yamlSuites, String dirName, String fileName) {
         assertThat(yamlSuites, notNullValue());
         assertThat(yamlSuites.size(), equalTo(1));
         assertThat(yamlSuites.containsKey(dirName), equalTo(true));
         assertSingleFile(yamlSuites.get(dirName), dirName, fileName);
     }
 
-    private static void assertSingleFile(Set<File> files, String dirName, String fileName) {
+    private static void assertSingleFile(Set<Path> files, String dirName, String fileName) {
         assertThat(files.size(), equalTo(1));
-        File file = files.iterator().next();
-        assertThat(file.getName(), equalTo(fileName));
-        assertThat(file.getParentFile().getName(), equalTo(dirName));
+        Path file = files.iterator().next();
+        assertThat(file.getFileName().toString(), equalTo(fileName));
+        assertThat(file.toAbsolutePath().getParent().getFileName().toString(), equalTo(dirName));
     }
 }

+ 41 - 31
src/test/java/org/elasticsearch/watcher/FileWatcherTest.java

@@ -19,19 +19,20 @@
 package org.elasticsearch.watcher;
 
 import com.carrotsearch.randomizedtesting.LifecycleScope;
+
 import org.apache.lucene.util.IOUtils;
 import org.elasticsearch.test.ElasticsearchTestCase;
 import org.junit.Test;
 
-import java.io.File;
+import java.io.BufferedWriter;
 import java.io.IOException;
 import java.nio.charset.Charset;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
 import java.util.List;
 
 import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.io.Files.*;
 import static org.hamcrest.Matchers.*;
 
 /**
@@ -95,10 +96,10 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testSimpleFileOperations() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testFile = tempDir.resolve("test.txt");
-        touch(testFile.toFile()); // TODO fix this to use path
+        touch(testFile);
         FileWatcher fileWatcher = new FileWatcher(testFile);
         fileWatcher.addListener(changes);
         fileWatcher.init();
@@ -108,7 +109,7 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), hasSize(0));
 
-        append("Test", testFile.toFile(), Charset.defaultCharset());
+        append("Test", testFile, Charset.defaultCharset());
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(equalTo("onFileChanged: test.txt")));
 
@@ -124,12 +125,12 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testSimpleDirectoryOperations() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testDir = tempDir.resolve("test-dir");
         Files.createDirectories(testDir);
-        touch(testDir.resolve("test.txt").toFile());
-        touch(testDir.resolve("test0.txt").toFile());
+        touch(testDir.resolve("test.txt"));
+        touch(testDir.resolve("test0.txt"));
 
         FileWatcher fileWatcher = new FileWatcher(testDir);
         fileWatcher.addListener(changes);
@@ -145,10 +146,10 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         assertThat(changes.notifications(), hasSize(0));
 
         for (int i = 0; i < 4; i++) {
-            touch(testDir.resolve("test" + i + ".txt").toFile());
+            touch(testDir.resolve("test" + i + ".txt"));
         }
         // Make sure that first file is modified
-        append("Test", testDir.resolve("test0.txt").toFile(), Charset.defaultCharset());
+        append("Test", testDir.resolve("test0.txt"), Charset.defaultCharset());
 
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
@@ -176,8 +177,8 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         assertThat(changes.notifications(), hasSize(0));
 
         Files.delete(testDir.resolve("test0.txt"));
-        touch(testDir.resolve("test2.txt").toFile());
-        touch(testDir.resolve("test4.txt").toFile());
+        touch(testDir.resolve("test2.txt"));
+        touch(testDir.resolve("test4.txt"));
         fileWatcher.checkAndNotify();
 
         assertThat(changes.notifications(), contains(
@@ -214,13 +215,13 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testNestedDirectoryOperations() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testDir = tempDir.resolve("test-dir");
         Files.createDirectories(testDir);
-        touch(testDir.resolve("test.txt").toFile());
+        touch(testDir.resolve("test.txt"));
         Files.createDirectories(testDir.resolve("sub-dir"));
-        touch(testDir.resolve("sub-dir/test0.txt").toFile());
+        touch(testDir.resolve("sub-dir/test0.txt"));
 
         FileWatcher fileWatcher = new FileWatcher(testDir);
         fileWatcher.addListener(changes);
@@ -237,7 +238,7 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         assertThat(changes.notifications(), hasSize(0));
 
         // Create new file in subdirectory
-        touch(testDir.resolve("sub-dir/test1.txt").toFile());
+        touch(testDir.resolve("sub-dir/test1.txt"));
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
                 equalTo("onFileCreated: test-dir/sub-dir/test1.txt")
@@ -249,9 +250,9 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
         // Create new subdirectory in subdirectory
         Files.createDirectories(testDir.resolve("first-level"));
-        touch(testDir.resolve("first-level/file1.txt").toFile());
+        touch(testDir.resolve("first-level/file1.txt"));
         Files.createDirectories(testDir.resolve("first-level/second-level"));
-        touch(testDir.resolve("first-level/second-level/file2.txt").toFile());
+        touch(testDir.resolve("first-level/second-level/file2.txt"));
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
                 equalTo("onDirectoryCreated: test-dir/first-level/"),
@@ -280,14 +281,14 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testFileReplacingDirectory() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testDir = tempDir.resolve("test-dir");
         Files.createDirectories(testDir);
         Path subDir = testDir.resolve("sub-dir");
         Files.createDirectories(subDir);
-        touch(subDir.resolve("test0.txt").toFile());
-        touch(subDir.resolve("test1.txt").toFile());
+        touch(subDir.resolve("test0.txt"));
+        touch(subDir.resolve("test1.txt"));
 
         FileWatcher fileWatcher = new FileWatcher(testDir);
         fileWatcher.addListener(changes);
@@ -304,7 +305,7 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         if (Files.exists(subDir)) {
             IOUtils.rm(subDir);
         }
-        touch(subDir.toFile());
+        touch(subDir);
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
                 equalTo("onFileDeleted: test-dir/sub-dir/test0.txt"),
@@ -327,12 +328,12 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testEmptyDirectory() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testDir = tempDir.resolve("test-dir");
         Files.createDirectories(testDir);
-        touch(testDir.resolve("test0.txt").toFile());
-        touch(testDir.resolve("test1.txt").toFile());
+        touch(testDir.resolve("test0.txt"));
+        touch(testDir.resolve("test1.txt"));
 
         FileWatcher fileWatcher = new FileWatcher(testDir);
         fileWatcher.addListener(changes);
@@ -350,7 +351,7 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testNoDirectoryOnInit() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testDir = tempDir.resolve("test-dir");
 
@@ -361,8 +362,8 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         changes.notifications().clear();
 
         Files.createDirectories(testDir);
-        touch(testDir.resolve("test0.txt").toFile());
-        touch(testDir.resolve("test1.txt").toFile());
+        touch(testDir.resolve("test0.txt"));
+        touch(testDir.resolve("test1.txt"));
 
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
@@ -374,7 +375,7 @@ public class FileWatcherTest extends ElasticsearchTestCase {
 
     @Test
     public void testNoFileOnInit() throws IOException {
-        Path tempDir = newTempDir(LifecycleScope.TEST).toPath();
+        Path tempDir = newTempDirPath(LifecycleScope.TEST);
         RecordingChangeListener changes = new RecordingChangeListener(tempDir);
         Path testFile = tempDir.resolve("testfile.txt");
 
@@ -384,12 +385,21 @@ public class FileWatcherTest extends ElasticsearchTestCase {
         assertThat(changes.notifications(), hasSize(0));
         changes.notifications().clear();
 
-        touch(testFile.toFile());
+        touch(testFile);
 
         fileWatcher.checkAndNotify();
         assertThat(changes.notifications(), contains(
                 equalTo("onFileCreated: testfile.txt")
         ));
     }
-
+    
+    static void touch(Path path) throws IOException {
+        Files.newOutputStream(path).close();
+    }
+    
+    static void append(String string, Path path, Charset cs) throws IOException {
+        try (BufferedWriter writer = Files.newBufferedWriter(path, cs, StandardOpenOption.APPEND)) {
+            writer.append(string);
+        }
+    }
 }