diff options
author | HÃ¥kon Hallingstad <hakon@verizonmedia.com> | 2019-10-16 12:56:42 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-10-16 12:56:42 +0200 |
commit | aa2f001cf82242c8bc51b982f73237d80b9639a1 (patch) | |
tree | 4428b2b42856a6117ec3b21133fa15d3c571c1de | |
parent | 3d675c428a7dd3ea7abbb708c41baf3bbaf19961 (diff) | |
parent | 48d7efe8bf25b597a0313443a1217c90116a7436 (diff) |
Merge pull request #10995 from vespa-engine/mpolden/read-bytes-if-exists
Add readBytesIfExists to UnixPath
2 files changed, 22 insertions, 0 deletions
diff --git a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPath.java b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPath.java index de3555b24a5..20a02e91bce 100644 --- a/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPath.java +++ b/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPath.java @@ -72,6 +72,17 @@ public class UnixPath { return uncheck(() -> Files.readAllBytes(path)); } + /** Reads and returns all bytes contained in this path, if any such path exists. */ + public Optional<byte[]> readBytesIfExists() { + try { + return Optional.of(Files.readAllBytes(path)); + } catch (NoSuchFileException ignored) { + return Optional.empty(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + public UnixPath writeUtf8File(String content, OpenOption... options) { return writeBytes(content.getBytes(StandardCharsets.UTF_8), options); } diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java index 6dfbc258474..802ca43ef56 100644 --- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java +++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java @@ -9,6 +9,7 @@ import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -17,6 +18,7 @@ import static org.junit.Assert.assertTrue; * @author hakonhall */ public class UnixPathTest { + private final FileSystem fs = TestFileSystem.create(); @Test @@ -87,4 +89,13 @@ public class UnixPathTest { UnixPath link = path.createSymbolicLink(fs.getPath("link-to-example.txt")); assertEquals(original, link.readUtf8File()); } + + @Test + public void readBytesIfExists() { + UnixPath path = new UnixPath(fs.getPath("example.txt")); + assertFalse(path.readBytesIfExists().isPresent()); + path.writeBytes(new byte[]{42}); + assertArrayEquals(new byte[]{42}, path.readBytesIfExists().get()); + } + } |