undefect. CWE-407 — 63 sites patched across 27 ecosystems
Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com Patches, unit tests, benchmarks, whitepaper, and outreach briefs. Public domain — no copyright claimed. Use freely.
This commit is contained in:
commit
0a580b313d
70422 changed files with 17213626 additions and 0 deletions
47
test/jdk/java/nio/file/attribute/AclEntry/EmptySet.java
Normal file
47
test/jdk/java/nio/file/attribute/AclEntry/EmptySet.java
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 7076310
|
||||
* @summary Test AclEntry.Builder setFlags and setPermissions with empty sets
|
||||
*/
|
||||
|
||||
import java.nio.file.attribute.*;
|
||||
import java.util.*;
|
||||
|
||||
/*
|
||||
* Test for bug 7076310 "(file) AclEntry.Builder setFlags throws
|
||||
* IllegalArgumentException if set argument is empty"
|
||||
* The bug is only applies when the given Set is NOT an instance of EnumSet.
|
||||
*
|
||||
* The setPermissions method also has the same problem.
|
||||
*/
|
||||
public class EmptySet {
|
||||
public static void main(String[] args) {
|
||||
Set<AclEntryFlag> flags = new HashSet<>();
|
||||
AclEntry.newBuilder().setFlags(flags);
|
||||
|
||||
Set<AclEntryPermission> perms = new HashSet<>();
|
||||
AclEntry.newBuilder().setPermissions(perms);
|
||||
}
|
||||
}
|
||||
173
test/jdk/java/nio/file/attribute/AclFileAttributeView/Basic.java
Normal file
173
test/jdk/java/nio/file/attribute/AclFileAttributeView/Basic.java
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
/*
|
||||
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 4313887 6838333 6891404
|
||||
* @summary Unit test for java.nio.file.attribute.AclFileAttribueView
|
||||
* @library ../..
|
||||
* @key randomness
|
||||
*/
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.*;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
import static java.nio.file.attribute.AclEntryType.*;
|
||||
import static java.nio.file.attribute.AclEntryPermission.*;
|
||||
import static java.nio.file.attribute.AclEntryFlag.*;
|
||||
|
||||
public class Basic {
|
||||
|
||||
static void printAcl(List<AclEntry> acl) {
|
||||
for (AclEntry entry: acl) {
|
||||
System.out.format(" %s%n", entry);
|
||||
}
|
||||
}
|
||||
|
||||
// sanity check read and writing ACL
|
||||
static void testReadWrite(Path dir) throws IOException {
|
||||
Path file = dir.resolve("foo");
|
||||
if (Files.notExists(file))
|
||||
Files.createFile(file);
|
||||
|
||||
AclFileAttributeView view =
|
||||
Files.getFileAttributeView(file, AclFileAttributeView.class);
|
||||
|
||||
// print existing ACL
|
||||
List<AclEntry> acl = view.getAcl();
|
||||
System.out.println(" -- current ACL --");
|
||||
printAcl(acl);
|
||||
|
||||
// insert entry to grant owner read access
|
||||
UserPrincipal owner = view.getOwner();
|
||||
AclEntry entry = AclEntry.newBuilder()
|
||||
.setType(ALLOW)
|
||||
.setPrincipal(owner)
|
||||
.setPermissions(READ_DATA, READ_ATTRIBUTES)
|
||||
.build();
|
||||
System.out.println(" -- insert (entry 0) --");
|
||||
System.out.format(" %s%n", entry);
|
||||
acl.add(0, entry);
|
||||
view.setAcl(acl);
|
||||
|
||||
// re-ACL and check entry
|
||||
List<AclEntry> newacl = view.getAcl();
|
||||
System.out.println(" -- current ACL --");
|
||||
printAcl(acl);
|
||||
if (!newacl.get(0).equals(entry)) {
|
||||
throw new RuntimeException("Entry 0 is not expected");
|
||||
}
|
||||
|
||||
// if PosixFileAttributeView then repeat test with OWNER@
|
||||
if (Files.getFileStore(file).supportsFileAttributeView("posix")) {
|
||||
owner = file.getFileSystem().getUserPrincipalLookupService()
|
||||
.lookupPrincipalByName("OWNER@");
|
||||
entry = AclEntry.newBuilder(entry).setPrincipal(owner).build();
|
||||
|
||||
System.out.println(" -- replace (entry 0) --");
|
||||
System.out.format(" %s%n", entry);
|
||||
|
||||
acl.set(0, entry);
|
||||
view.setAcl(acl);
|
||||
newacl = view.getAcl();
|
||||
System.out.println(" -- current ACL --");
|
||||
printAcl(acl);
|
||||
if (!newacl.get(0).equals(entry)) {
|
||||
throw new RuntimeException("Entry 0 is not expected");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static FileAttribute<List<AclEntry>> asAclAttribute(final List<AclEntry> acl) {
|
||||
return new FileAttribute<List<AclEntry>>() {
|
||||
public String name() { return "acl:acl"; }
|
||||
public List<AclEntry> value() { return acl; }
|
||||
};
|
||||
}
|
||||
|
||||
static void assertEquals(List<AclEntry> actual, List<AclEntry> expected) {
|
||||
if (!actual.equals(expected)) {
|
||||
System.err.format("Actual: %s\n", actual);
|
||||
System.err.format("Expected: %s\n", expected);
|
||||
throw new RuntimeException("ACL not expected");
|
||||
}
|
||||
}
|
||||
|
||||
// sanity check create a file or directory with initial ACL
|
||||
static void testCreateFile(Path dir) throws IOException {
|
||||
UserPrincipal user = Files.getOwner(dir);
|
||||
AclFileAttributeView view;
|
||||
|
||||
// create file with initial ACL
|
||||
System.out.println("-- create file with initial ACL --");
|
||||
Path file = dir.resolve("gus");
|
||||
List<AclEntry> fileAcl = Arrays.asList(
|
||||
AclEntry.newBuilder()
|
||||
.setType(AclEntryType.ALLOW)
|
||||
.setPrincipal(user)
|
||||
.setPermissions(SYNCHRONIZE, READ_DATA, WRITE_DATA,
|
||||
READ_ATTRIBUTES, READ_ACL, WRITE_ATTRIBUTES, DELETE)
|
||||
.build());
|
||||
Files.createFile(file, asAclAttribute(fileAcl));
|
||||
view = Files.getFileAttributeView(file, AclFileAttributeView.class);
|
||||
assertEquals(view.getAcl(), fileAcl);
|
||||
|
||||
// create directory with initial ACL
|
||||
System.out.println("-- create directory with initial ACL --");
|
||||
Path subdir = dir.resolve("stuff");
|
||||
List<AclEntry> dirAcl = Arrays.asList(
|
||||
AclEntry.newBuilder()
|
||||
.setType(AclEntryType.ALLOW)
|
||||
.setPrincipal(user)
|
||||
.setPermissions(SYNCHRONIZE, ADD_FILE, DELETE)
|
||||
.build(),
|
||||
AclEntry.newBuilder(fileAcl.get(0))
|
||||
.setFlags(FILE_INHERIT)
|
||||
.build());
|
||||
Files.createDirectory(subdir, asAclAttribute(dirAcl));
|
||||
view = Files.getFileAttributeView(subdir, AclFileAttributeView.class);
|
||||
assertEquals(view.getAcl(), dirAcl);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// use work directory rather than system temporary directory to
|
||||
// improve chances that ACLs are supported
|
||||
Path dir = Paths.get("./work" + new Random().nextInt());
|
||||
Files.createDirectory(dir);
|
||||
try {
|
||||
if (!Files.getFileStore(dir).supportsFileAttributeView("acl")) {
|
||||
System.out.println("ACLs not supported - test skipped!");
|
||||
return;
|
||||
}
|
||||
testReadWrite(dir);
|
||||
|
||||
// only currently feasible on Windows
|
||||
if (System.getProperty("os.name").startsWith("Windows"))
|
||||
testCreateFile(dir);
|
||||
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,157 @@
|
|||
/*
|
||||
* Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 4313887 6838333 8364277
|
||||
* @summary Unit test for java.nio.file.attribute.BasicFileAttributeView
|
||||
* @library ../.. /test/lib
|
||||
* @build jdk.test.lib.Platform
|
||||
* jdk.test.lib.util.FileUtils
|
||||
* @run main/othervm --enable-native-access=ALL-UNNAMED Basic
|
||||
*/
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.io.*;
|
||||
|
||||
import jdk.test.lib.Platform;
|
||||
import jdk.test.lib.util.FileUtils;
|
||||
|
||||
public class Basic {
|
||||
|
||||
static void check(boolean okay, String msg) {
|
||||
if (!okay)
|
||||
throw new RuntimeException(msg);
|
||||
}
|
||||
|
||||
static void checkAttributesOfDirectory(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
BasicFileAttributes attrs = Files.readAttributes(dir, BasicFileAttributes.class);
|
||||
check(attrs.isDirectory(), "is a directory");
|
||||
check(!attrs.isRegularFile(), "is not a regular file");
|
||||
check(!attrs.isSymbolicLink(), "is not a link");
|
||||
check(!attrs.isOther(), "is not other");
|
||||
|
||||
// last-modified-time should match java.io.File in seconds
|
||||
File f = new File(dir.toString());
|
||||
check(f.lastModified()/1000 == attrs.lastModifiedTime().to(TimeUnit.SECONDS),
|
||||
"last-modified time should be the same");
|
||||
}
|
||||
|
||||
static void checkAttributesOfFile(Path dir, Path file)
|
||||
throws IOException
|
||||
{
|
||||
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
|
||||
check(attrs.isRegularFile(), "is a regular file");
|
||||
check(!attrs.isDirectory(), "is not a directory");
|
||||
check(!attrs.isSymbolicLink(), "is not a link");
|
||||
check(!attrs.isOther(), "is not other");
|
||||
|
||||
// size and last-modified-time should match java.io.File in seconds
|
||||
File f = new File(file.toString());
|
||||
check(f.length() == attrs.size(), "size should be the same");
|
||||
check(f.lastModified()/1000 == attrs.lastModifiedTime().to(TimeUnit.SECONDS),
|
||||
"last-modified time should be the same");
|
||||
|
||||
// copy last-modified time from directory to file,
|
||||
// re-read attribtues, and check they match
|
||||
BasicFileAttributeView view =
|
||||
Files.getFileAttributeView(file, BasicFileAttributeView.class);
|
||||
BasicFileAttributes dirAttrs = Files.readAttributes(dir, BasicFileAttributes.class);
|
||||
view.setTimes(dirAttrs.lastModifiedTime(), null, null);
|
||||
|
||||
attrs = view.readAttributes();
|
||||
check(attrs.lastModifiedTime().equals(dirAttrs.lastModifiedTime()),
|
||||
"last-modified time should be equal");
|
||||
|
||||
// security tests
|
||||
check (!(attrs instanceof PosixFileAttributes),
|
||||
"should not be able to cast to PosixFileAttributes");
|
||||
}
|
||||
|
||||
static void checkAttributesOfLink(Path link)
|
||||
throws IOException
|
||||
{
|
||||
BasicFileAttributes attrs =
|
||||
Files.readAttributes(link, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
check(attrs.isSymbolicLink(), "is a link");
|
||||
check(!attrs.isDirectory(), "is a directory");
|
||||
check(!attrs.isRegularFile(), "is not a regular file");
|
||||
check(!attrs.isOther(), "is not other");
|
||||
}
|
||||
|
||||
static void checkAttributesOfJunction(Path junction)
|
||||
throws IOException
|
||||
{
|
||||
BasicFileAttributes attrs =
|
||||
Files.readAttributes(junction, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
|
||||
check(!attrs.isSymbolicLink(), "is a link");
|
||||
check(!attrs.isDirectory(), "is a directory");
|
||||
check(!attrs.isRegularFile(), "is not a regular file");
|
||||
check(attrs.isOther(), "is other");
|
||||
}
|
||||
|
||||
static void attributeReadWriteTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
// create file
|
||||
Path file = dir.resolve("foo");
|
||||
try (OutputStream out = Files.newOutputStream(file)) {
|
||||
out.write("this is not an empty file".getBytes("UTF-8"));
|
||||
}
|
||||
|
||||
// check attributes of directory and file
|
||||
checkAttributesOfDirectory(dir);
|
||||
checkAttributesOfFile(dir, file);
|
||||
|
||||
// symbolic links may be supported
|
||||
Path link = dir.resolve("link");
|
||||
try {
|
||||
Files.createSymbolicLink(link, file);
|
||||
checkAttributesOfLink(link);
|
||||
} catch (IOException | UnsupportedOperationException x) {
|
||||
if (!Platform.isWindows())
|
||||
return;
|
||||
}
|
||||
|
||||
// NTFS junctions are Windows-only
|
||||
if (Platform.isWindows()) {
|
||||
Path junction = dir.resolve("junction");
|
||||
FileUtils.createWinDirectoryJunction(junction, dir);
|
||||
checkAttributesOfJunction(junction);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// create temporary directory to run tests
|
||||
Path dir = TestUtil.createTemporaryDirectory();
|
||||
try {
|
||||
attributeReadWriteTests(dir);
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
/*
|
||||
* Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test id=tmp
|
||||
* @bug 8011536 8151430 8316304 8334339
|
||||
* @summary Basic test for creationTime attribute on platforms/file systems
|
||||
* that support it, tests using /tmp directory.
|
||||
* @library ../.. /test/lib /java/foreign
|
||||
* @build jdk.test.lib.Platform NativeTestHelper
|
||||
* @run main/othervm/native --enable-native-access=ALL-UNNAMED CreationTime
|
||||
*/
|
||||
|
||||
/* @test id=cwd
|
||||
* @summary Basic test for creationTime attribute on platforms/file systems
|
||||
* that support it, tests using the test scratch directory, the test
|
||||
* scratch directory maybe at diff disk partition to /tmp on linux.
|
||||
* @library ../.. /test/lib /java/foreign
|
||||
* @build jdk.test.lib.Platform NativeTestHelper
|
||||
* @run main/othervm/native --enable-native-access=ALL-UNNAMED CreationTime .
|
||||
*/
|
||||
|
||||
import java.lang.foreign.Linker;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.attribute.*;
|
||||
import java.time.Instant;
|
||||
import java.io.IOException;
|
||||
|
||||
import jdk.test.lib.Platform;
|
||||
import jtreg.SkippedException;
|
||||
|
||||
public class CreationTime {
|
||||
|
||||
/**
|
||||
* Reads the creationTime attribute
|
||||
*/
|
||||
private static FileTime creationTime(Path file) throws IOException {
|
||||
return Files.readAttributes(file, BasicFileAttributes.class).creationTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the creationTime attribute
|
||||
*/
|
||||
private static void setCreationTime(Path file, FileTime time) throws IOException {
|
||||
BasicFileAttributeView view =
|
||||
Files.getFileAttributeView(file, BasicFileAttributeView.class);
|
||||
view.setTimes(null, null, time);
|
||||
}
|
||||
|
||||
static void test(Path top) throws IOException {
|
||||
Path file = Files.createFile(top.resolve("foo"));
|
||||
|
||||
/**
|
||||
* Check that creationTime reported
|
||||
*/
|
||||
FileTime creationTime = creationTime(file);
|
||||
Instant now = Instant.now();
|
||||
if (Math.abs(creationTime.toMillis()-now.toEpochMilli()) > 10000L) {
|
||||
System.err.println("creationTime.toMillis() == " + creationTime.toMillis());
|
||||
System.err.println("File creation time reported as: " + creationTime);
|
||||
throw new RuntimeException("Expected to be close to: " + now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the creationTime attribute supported here?
|
||||
*/
|
||||
boolean supportsCreationTimeRead = false;
|
||||
boolean supportsCreationTimeWrite = false;
|
||||
if (Platform.isOSX()) {
|
||||
String type = Files.getFileStore(file).type();
|
||||
if (type.equals("apfs") || type.equals("hfs")) {
|
||||
supportsCreationTimeRead = true;
|
||||
supportsCreationTimeWrite = true;
|
||||
}
|
||||
} else if (Platform.isWindows()) {
|
||||
String type = Files.getFileStore(file).type();
|
||||
if (type.equals("NTFS") || type.equals("FAT")) {
|
||||
supportsCreationTimeRead = true;
|
||||
supportsCreationTimeWrite = true;
|
||||
}
|
||||
} else if (Platform.isLinux()) {
|
||||
// Creation time read depends on statx system call support
|
||||
try {
|
||||
supportsCreationTimeRead = CreationTimeHelper.
|
||||
linuxIsCreationTimeSupported(file.toAbsolutePath().toString());
|
||||
} catch (Throwable e) {
|
||||
supportsCreationTimeRead = false;
|
||||
}
|
||||
// Creation time updates are not supported on Linux
|
||||
supportsCreationTimeWrite = false;
|
||||
}
|
||||
System.out.println(top + " supportsCreationTimeRead == " + supportsCreationTimeRead);
|
||||
|
||||
/**
|
||||
* If the creation-time attribute is supported then change the file's
|
||||
* last modified and check that it doesn't change the creation-time.
|
||||
*/
|
||||
if (supportsCreationTimeRead) {
|
||||
// change modified time by +1 hour
|
||||
Instant plusHour = Instant.now().plusSeconds(60L * 60L);
|
||||
Files.setLastModifiedTime(file, FileTime.from(plusHour));
|
||||
FileTime current = creationTime(file);
|
||||
if (!current.equals(creationTime)) {
|
||||
System.err.println("current = " + current);
|
||||
System.err.println("creationTime = " + creationTime);
|
||||
throw new RuntimeException("Creation time should not have changed");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the creation-time attribute is supported and can be changed then
|
||||
* check that the change is effective.
|
||||
*/
|
||||
if (supportsCreationTimeWrite) {
|
||||
// change creation time by -1 hour
|
||||
Instant minusHour = Instant.now().minusSeconds(60L * 60L);
|
||||
creationTime = FileTime.from(minusHour);
|
||||
setCreationTime(file, creationTime);
|
||||
FileTime current = creationTime(file);
|
||||
if (Math.abs(creationTime.toMillis()-current.toMillis()) > 1000L)
|
||||
throw new RuntimeException("Creation time not changed");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// create temporary directory to run tests
|
||||
Path dir;
|
||||
if (args.length == 0) {
|
||||
dir = TestUtil.createTemporaryDirectory();
|
||||
} else {
|
||||
dir = TestUtil.createTemporaryDirectory(args[0]);
|
||||
}
|
||||
try {
|
||||
test(dir);
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
* Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.FunctionDescriptor;
|
||||
import java.lang.foreign.Linker;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.SymbolLookup;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
|
||||
public class CreationTimeHelper extends NativeTestHelper {
|
||||
|
||||
static {
|
||||
System.loadLibrary("CreationTimeHelper");
|
||||
}
|
||||
|
||||
final static Linker abi = Linker.nativeLinker();
|
||||
static final SymbolLookup lookup = SymbolLookup.loaderLookup();
|
||||
final static MethodHandle methodHandle = abi.
|
||||
downcallHandle(lookup.findOrThrow("linuxIsCreationTimeSupported"),
|
||||
FunctionDescriptor.of(C_BOOL, C_POINTER));
|
||||
|
||||
// Helper so as to determine birth time support or not on Linux.
|
||||
// Support is determined in a two-step process:
|
||||
// 1. Determine if `statx` system call is available. If available proceed,
|
||||
// otherwise return false.
|
||||
// 2. Perform an actual `statx` call on the given file and check for birth
|
||||
// time support in the mask returned from the call. This is needed,
|
||||
// since some file systems, like nfs/tmpfs etc., don't support birth
|
||||
// time even though the `statx` system call is available.
|
||||
static boolean linuxIsCreationTimeSupported(String file) throws Throwable {
|
||||
if (!abi.defaultLookup().find("statx").isPresent()) {
|
||||
return false;
|
||||
}
|
||||
try (var arena = Arena.ofConfined()) {
|
||||
MemorySegment s = arena.allocateFrom(file);
|
||||
return (boolean)methodHandle.invokeExact(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 8181493 8231174 8343417
|
||||
* @summary Verify that nanosecond precision is maintained for file timestamps
|
||||
* @library ../.. /test/lib
|
||||
* @build jdk.test.lib.Platform
|
||||
* @modules java.base/sun.nio.fs:+open
|
||||
* @run main SetTimesNanos
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.FileStore;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.BasicFileAttributeView;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static java.nio.file.LinkOption.*;
|
||||
import static java.util.concurrent.TimeUnit.*;
|
||||
|
||||
import jdk.test.lib.Platform;
|
||||
import jtreg.SkippedException;
|
||||
|
||||
public class SetTimesNanos {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dirPath = Path.of("test");
|
||||
Path dir = Files.createDirectory(dirPath);
|
||||
FileStore store = Files.getFileStore(dir);
|
||||
System.out.format("FileStore: \"%s\" on %s (%s)%n",
|
||||
dir, store.name(), store.type());
|
||||
|
||||
Set<String> testedTypes = Platform.isWindows() ?
|
||||
Set.of("NTFS") : Set.of("apfs", "ext4", "xfs", "zfs");
|
||||
if (!testedTypes.contains(store.type())) {
|
||||
throw new SkippedException(store.type() + " not in " + testedTypes);
|
||||
}
|
||||
|
||||
testNanos(dir);
|
||||
|
||||
Path file = Files.createFile(dir.resolve("test.dat"));
|
||||
testNanos(file);
|
||||
|
||||
if (TestUtil.supportsSymbolicLinks(Path.of(""))) {
|
||||
testNanosLink(false);
|
||||
testNanosLink(true);
|
||||
}
|
||||
}
|
||||
|
||||
private static void testNanos(Path path) throws IOException {
|
||||
// Set modification and access times
|
||||
// Time stamp = "2017-01-01 01:01:01.123456789";
|
||||
long timeNanos = 1_483_261_261L*1_000_000_000L + 123_456_789L;
|
||||
FileTime pathTime = FileTime.from(timeNanos, NANOSECONDS);
|
||||
BasicFileAttributeView view =
|
||||
Files.getFileAttributeView(path, BasicFileAttributeView.class);
|
||||
view.setTimes(pathTime, pathTime, null);
|
||||
|
||||
// Windows file time resolution is 100ns so truncate
|
||||
if (Platform.isWindows()) {
|
||||
timeNanos = 100L*(timeNanos/100L);
|
||||
}
|
||||
|
||||
// Read attributes
|
||||
BasicFileAttributes attrs =
|
||||
Files.readAttributes(path, BasicFileAttributes.class);
|
||||
|
||||
// Check timestamps
|
||||
String[] timeNames = new String[] {"modification", "access"};
|
||||
FileTime[] times = new FileTime[] {attrs.lastModifiedTime(),
|
||||
attrs.lastAccessTime()};
|
||||
for (int i = 0; i < timeNames.length; i++) {
|
||||
long nanos = times[i].to(NANOSECONDS);
|
||||
if (nanos != timeNanos) {
|
||||
throw new RuntimeException("Expected " + timeNames[i] +
|
||||
" timestamp to be '" + timeNanos + "', but was '" +
|
||||
nanos + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void testNanosLink(boolean absolute) throws IOException {
|
||||
System.out.println("absolute: " + absolute);
|
||||
|
||||
var target = Path.of("target");
|
||||
var symlink = Path.of("symlink");
|
||||
if (absolute)
|
||||
symlink = symlink.toAbsolutePath();
|
||||
|
||||
try {
|
||||
Files.createFile(target);
|
||||
Files.createSymbolicLink(symlink, target);
|
||||
|
||||
long timeNanos = 1730417633157646106L;
|
||||
|
||||
// Windows file time resolution is 100ns so truncate
|
||||
if (Platform.isWindows()) {
|
||||
timeNanos = 100L*(timeNanos/100L);
|
||||
}
|
||||
|
||||
var newTime = FileTime.from(timeNanos, NANOSECONDS);
|
||||
System.out.println("newTime: " + newTime.to(NANOSECONDS));
|
||||
|
||||
for (Path p : List.of(target, symlink)) {
|
||||
System.out.println("p: " + p);
|
||||
|
||||
var view = Files.getFileAttributeView(p,
|
||||
BasicFileAttributeView.class, NOFOLLOW_LINKS);
|
||||
view.setTimes(newTime, newTime, null);
|
||||
var attrs = view.readAttributes();
|
||||
|
||||
if (!attrs.lastAccessTime().equals(newTime))
|
||||
throw new RuntimeException("Last access time "
|
||||
+ attrs.lastAccessTime()
|
||||
+ " != " + newTime);
|
||||
if (!attrs.lastAccessTime().equals(newTime))
|
||||
throw new RuntimeException("Last modified time "
|
||||
+ attrs.lastModifiedTime()
|
||||
+ " != " + newTime);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(target);
|
||||
Files.deleteIfExists(symlink);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 8139133
|
||||
* @summary Verify ability to set time attributes of socket files with no device
|
||||
* @requires os.family == "linux"
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardWatchEventKinds;
|
||||
import java.nio.file.WatchKey;
|
||||
import java.nio.file.WatchService;
|
||||
import java.nio.file.attribute.BasicFileAttributeView;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
|
||||
public class UnixSocketFile {
|
||||
private static final String TEST_SUB_DIR = "UnixSocketFile";
|
||||
private static final String SOCKET_FILE_NAME = "mysocket";
|
||||
private static final String CMD_BASE = "nc -lU";
|
||||
|
||||
public static void main(String[] args)
|
||||
throws InterruptedException, IOException {
|
||||
|
||||
// Use 'which' to verify that 'nc' is available and skip the test
|
||||
// if it is not.
|
||||
Process proc = Runtime.getRuntime().exec("which nc");
|
||||
InputStream stdout = proc.getInputStream();
|
||||
int b = stdout.read();
|
||||
proc.destroy();
|
||||
if (b == -1) {
|
||||
System.err.println("Netcat command unavailable; skipping test.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify that 'nc' accepts '-U' for Unix domain sockets.
|
||||
// Skip the test if it is not.
|
||||
Process procHelp = Runtime.getRuntime().exec(CMD_BASE + " -h");
|
||||
if (procHelp.waitFor() != 0) {
|
||||
System.err.println("Netcat does not accept required options; skipping test.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a new sub-directory of the nominal test directory in which
|
||||
// 'nc' will create the socket file.
|
||||
String testSubDir = System.getProperty("test.dir", ".")
|
||||
+ File.separator + TEST_SUB_DIR;
|
||||
Path socketTestDir = Paths.get(testSubDir);
|
||||
Files.createDirectory(socketTestDir);
|
||||
|
||||
// Set the path of the socket file.
|
||||
String socketFilePath = testSubDir + File.separator
|
||||
+ SOCKET_FILE_NAME;
|
||||
|
||||
// Create a process which executes the nc (netcat) utility to create
|
||||
// a socket file at the indicated location.
|
||||
FileSystem fs = FileSystems.getDefault();
|
||||
try (WatchService ws = fs.newWatchService()) {
|
||||
// Watch the test sub-directory to receive notification when an
|
||||
// entry, i.e., the socket file, is added to the sub-directory.
|
||||
WatchKey wk = socketTestDir.register(ws,
|
||||
StandardWatchEventKinds.ENTRY_CREATE);
|
||||
|
||||
// Execute the 'nc' command.
|
||||
proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);
|
||||
|
||||
// Wait until the socket file is created.
|
||||
WatchKey key = ws.take();
|
||||
if (key != wk) {
|
||||
throw new RuntimeException("Unknown entry created - expected: "
|
||||
+ wk.watchable() + ", actual: " + key.watchable());
|
||||
}
|
||||
wk.cancel();
|
||||
}
|
||||
|
||||
// Verify that the socket file in fact exists.
|
||||
Path socketPath = fs.getPath(socketFilePath);
|
||||
if (!Files.exists(socketPath)) {
|
||||
throw new RuntimeException("Socket file " + socketFilePath
|
||||
+ " was not created by \"nc\" command.");
|
||||
}
|
||||
|
||||
// Retrieve the most recent access and modification times of the
|
||||
// socket file; print the values.
|
||||
BasicFileAttributeView attributeView = Files.getFileAttributeView(
|
||||
socketPath, BasicFileAttributeView.class);
|
||||
BasicFileAttributes oldAttributes = attributeView.readAttributes();
|
||||
FileTime oldAccessTime = oldAttributes.lastAccessTime();
|
||||
FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
|
||||
System.out.println("Old times: " + oldAccessTime
|
||||
+ " " + oldModifiedTime);
|
||||
|
||||
// Calculate the time to which the access and modification times of the
|
||||
// socket file will be changed.
|
||||
FileTime newFileTime =
|
||||
FileTime.fromMillis(oldAccessTime.toMillis() + 1066);
|
||||
|
||||
try {
|
||||
// Set the access and modification times of the socket file.
|
||||
attributeView.setTimes(newFileTime, newFileTime, null);
|
||||
|
||||
// Retrieve the updated access and modification times of the
|
||||
// socket file; print the values.
|
||||
FileTime newAccessTime = null;
|
||||
FileTime newModifiedTime = null;
|
||||
BasicFileAttributes newAttributes = attributeView.readAttributes();
|
||||
newAccessTime = newAttributes.lastAccessTime();
|
||||
newModifiedTime = newAttributes.lastModifiedTime();
|
||||
System.out.println("New times: " + newAccessTime + " "
|
||||
+ newModifiedTime);
|
||||
|
||||
// Verify that the updated times have the expected values.
|
||||
if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
|
||||
|| (newModifiedTime != null
|
||||
&& !newModifiedTime.equals(newFileTime))) {
|
||||
throw new RuntimeException("Failed to set correct times.");
|
||||
}
|
||||
} finally {
|
||||
// Destry the process running netcat and delete the socket file.
|
||||
proc.destroy();
|
||||
Files.delete(socketPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
/*
|
||||
* Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
#include "export.h"
|
||||
#include <stdbool.h>
|
||||
#if defined(__linux__)
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <dlfcn.h>
|
||||
#ifndef STATX_BASIC_STATS
|
||||
#define STATX_BASIC_STATS 0x000007ffU
|
||||
#endif
|
||||
#ifndef STATX_BTIME
|
||||
#define STATX_BTIME 0x00000800U
|
||||
#endif
|
||||
#ifndef RTLD_DEFAULT
|
||||
#define RTLD_DEFAULT RTLD_LOCAL
|
||||
#endif
|
||||
#ifndef AT_SYMLINK_NOFOLLOW
|
||||
#define AT_SYMLINK_NOFOLLOW 0x100
|
||||
#endif
|
||||
#ifndef AT_FDCWD
|
||||
#define AT_FDCWD -100
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* Timestamp structure for the timestamps in struct statx.
|
||||
*/
|
||||
struct my_statx_timestamp {
|
||||
int64_t tv_sec;
|
||||
uint32_t tv_nsec;
|
||||
int32_t __reserved;
|
||||
};
|
||||
|
||||
/*
|
||||
* struct statx used by statx system call on >= glibc 2.28
|
||||
* systems
|
||||
*/
|
||||
struct my_statx
|
||||
{
|
||||
uint32_t stx_mask;
|
||||
uint32_t stx_blksize;
|
||||
uint64_t stx_attributes;
|
||||
uint32_t stx_nlink;
|
||||
uint32_t stx_uid;
|
||||
uint32_t stx_gid;
|
||||
uint16_t stx_mode;
|
||||
uint16_t __statx_pad1[1];
|
||||
uint64_t stx_ino;
|
||||
uint64_t stx_size;
|
||||
uint64_t stx_blocks;
|
||||
uint64_t stx_attributes_mask;
|
||||
struct my_statx_timestamp stx_atime;
|
||||
struct my_statx_timestamp stx_btime;
|
||||
struct my_statx_timestamp stx_ctime;
|
||||
struct my_statx_timestamp stx_mtime;
|
||||
uint32_t stx_rdev_major;
|
||||
uint32_t stx_rdev_minor;
|
||||
uint32_t stx_dev_major;
|
||||
uint32_t stx_dev_minor;
|
||||
uint64_t __statx_pad2[14];
|
||||
};
|
||||
|
||||
typedef int statx_func(int dirfd, const char *restrict pathname, int flags,
|
||||
unsigned int mask, struct my_statx *restrict statxbuf);
|
||||
|
||||
static statx_func* my_statx_func = NULL;
|
||||
#endif //#defined(__linux__)
|
||||
|
||||
// static boolean linuxIsCreationTimeSupported(char* file)
|
||||
EXPORT bool linuxIsCreationTimeSupported(char* file) {
|
||||
#if defined(__linux__)
|
||||
struct my_statx stx = {0};
|
||||
int ret, atflag = AT_SYMLINK_NOFOLLOW;
|
||||
unsigned int mask = STATX_BASIC_STATS | STATX_BTIME;
|
||||
|
||||
my_statx_func = (statx_func*) dlsym(RTLD_DEFAULT, "statx");
|
||||
if (my_statx_func == NULL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file == NULL) {
|
||||
printf("input file error!\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
ret = my_statx_func(AT_FDCWD, file, atflag, mask, &stx);
|
||||
if (ret != 0) {
|
||||
return false;
|
||||
}
|
||||
// On some systems where statx is available but birth time might still not
|
||||
// be supported as it's file system specific. The only reliable way to
|
||||
// check for supported or not is looking at the filled in STATX_BTIME bit
|
||||
// in the returned statx buffer mask.
|
||||
if ((stx.stx_mask & STATX_BTIME) != 0)
|
||||
return true;
|
||||
return false;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
153
test/jdk/java/nio/file/attribute/DosFileAttributeView/Basic.java
Normal file
153
test/jdk/java/nio/file/attribute/DosFileAttributeView/Basic.java
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
/*
|
||||
* Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 4313887 6838333
|
||||
* @summary Unit test for java.nio.file.attribute.DosFileAttributeView
|
||||
* @library ../..
|
||||
*/
|
||||
|
||||
import java.nio.file.*;
|
||||
import static java.nio.file.LinkOption.*;
|
||||
import java.nio.file.attribute.*;
|
||||
import java.util.*;
|
||||
import java.io.IOException;
|
||||
|
||||
public class Basic {
|
||||
|
||||
static void check(boolean okay) {
|
||||
if (!okay)
|
||||
throw new RuntimeException("Test failed");
|
||||
}
|
||||
|
||||
// exercise each setter/getter method, leaving all attributes unset
|
||||
static void testAttributes(DosFileAttributeView view) throws IOException {
|
||||
view.setReadOnly(true);
|
||||
check(view.readAttributes().isReadOnly());
|
||||
view.setReadOnly(false);
|
||||
check(!view.readAttributes().isReadOnly());
|
||||
view.setHidden(true);
|
||||
check(view.readAttributes().isHidden());
|
||||
view.setHidden(false);
|
||||
check(!view.readAttributes().isHidden());
|
||||
view.setArchive(true);
|
||||
check(view.readAttributes().isArchive());
|
||||
view.setArchive(false);
|
||||
check(!view.readAttributes().isArchive());
|
||||
view.setSystem(true);
|
||||
check(view.readAttributes().isSystem());
|
||||
view.setSystem(false);
|
||||
check(!view.readAttributes().isSystem());
|
||||
}
|
||||
|
||||
// set the value of all attributes
|
||||
static void setAll(DosFileAttributeView view, boolean value)
|
||||
throws IOException
|
||||
{
|
||||
view.setReadOnly(value);
|
||||
view.setHidden(value);
|
||||
view.setArchive(value);
|
||||
view.setSystem(value);
|
||||
}
|
||||
|
||||
// read and write FAT attributes
|
||||
static void readWriteTests(Path dir) throws IOException {
|
||||
|
||||
// create "foo" and test that we can read/write each FAT attribute
|
||||
Path file = Files.createFile(dir.resolve("foo"));
|
||||
try {
|
||||
testAttributes(Files.getFileAttributeView(file, DosFileAttributeView.class));
|
||||
|
||||
// Following tests use a symbolic link so skip if not supported
|
||||
if (!TestUtil.supportsSymbolicLinks(dir))
|
||||
return;
|
||||
|
||||
Path link = dir.resolve("link");
|
||||
Files.createSymbolicLink(link, file);
|
||||
|
||||
// test following links
|
||||
testAttributes(Files.getFileAttributeView(link, DosFileAttributeView.class));
|
||||
|
||||
// test not following links
|
||||
try {
|
||||
try {
|
||||
testAttributes(Files
|
||||
.getFileAttributeView(link, DosFileAttributeView.class, NOFOLLOW_LINKS));
|
||||
} catch (IOException x) {
|
||||
// access to link attributes not supported
|
||||
return;
|
||||
}
|
||||
|
||||
// set all attributes on link
|
||||
// run test on target of link (which leaves them all un-set)
|
||||
// check that attributes of link remain all set
|
||||
setAll(Files
|
||||
.getFileAttributeView(link, DosFileAttributeView.class, NOFOLLOW_LINKS), true);
|
||||
testAttributes(Files
|
||||
.getFileAttributeView(link, DosFileAttributeView.class));
|
||||
DosFileAttributes attrs =
|
||||
Files.getFileAttributeView(link, DosFileAttributeView.class, NOFOLLOW_LINKS)
|
||||
.readAttributes();
|
||||
check(attrs.isReadOnly());
|
||||
check(attrs.isHidden());
|
||||
check(attrs.isArchive());
|
||||
check(attrs.isSystem());
|
||||
setAll(Files
|
||||
.getFileAttributeView(link, DosFileAttributeView.class, NOFOLLOW_LINKS), false);
|
||||
|
||||
// set all attributes on target
|
||||
// run test on link (which leaves them all un-set)
|
||||
// check that attributes of target remain all set
|
||||
setAll(Files.getFileAttributeView(link, DosFileAttributeView.class), true);
|
||||
testAttributes(Files
|
||||
.getFileAttributeView(link, DosFileAttributeView.class, NOFOLLOW_LINKS));
|
||||
attrs = Files.getFileAttributeView(link, DosFileAttributeView.class).readAttributes();
|
||||
check(attrs.isReadOnly());
|
||||
check(attrs.isHidden());
|
||||
check(attrs.isArchive());
|
||||
check(attrs.isSystem());
|
||||
setAll(Files.getFileAttributeView(link, DosFileAttributeView.class), false);
|
||||
} finally {
|
||||
TestUtil.deleteUnchecked(link);
|
||||
}
|
||||
} finally {
|
||||
TestUtil.deleteUnchecked(file);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// create temporary directory to run tests
|
||||
Path dir = TestUtil.createTemporaryDirectory();
|
||||
|
||||
try {
|
||||
// skip test if DOS file attributes not supported
|
||||
if (!Files.getFileStore(dir).supportsFileAttributeView("dos")) {
|
||||
System.out.println("DOS file attribute not supported.");
|
||||
return;
|
||||
}
|
||||
readWriteTests(dir);
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
346
test/jdk/java/nio/file/attribute/FileTime/Basic.java
Normal file
346
test/jdk/java/nio/file/attribute/FileTime/Basic.java
Normal file
|
|
@ -0,0 +1,346 @@
|
|||
/*
|
||||
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 6844313 8011647
|
||||
* @summary Unit test for java.nio.file.FileTime
|
||||
* @key randomness
|
||||
*/
|
||||
|
||||
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static java.util.concurrent.TimeUnit.*;
|
||||
import java.util.Random;
|
||||
import java.util.EnumSet;
|
||||
|
||||
public class Basic {
|
||||
|
||||
static final Random rand = new Random();
|
||||
|
||||
public static void main(String[] args) {
|
||||
long now = System.currentTimeMillis();
|
||||
long tomorrowInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) + 1;
|
||||
long yesterdayInDays = TimeUnit.DAYS.convert(now, MILLISECONDS) - 1;
|
||||
|
||||
Instant nowInstant = Instant.ofEpochMilli(now);
|
||||
|
||||
// equals
|
||||
eq(now, MILLISECONDS, now, MILLISECONDS);
|
||||
eq(now, MILLISECONDS, now*1000L, MICROSECONDS);
|
||||
neq(now, MILLISECONDS, 0, MILLISECONDS);
|
||||
neq(now, MILLISECONDS, 0, MICROSECONDS);
|
||||
|
||||
eq(nowInstant, now, MILLISECONDS);
|
||||
eq(nowInstant, now*1000L, MICROSECONDS);
|
||||
neq(nowInstant, 0, MILLISECONDS);
|
||||
neq(nowInstant, 0, MICROSECONDS);
|
||||
|
||||
// compareTo
|
||||
cmp(now, MILLISECONDS, now, MILLISECONDS, 0);
|
||||
cmp(now, MILLISECONDS, now*1000L, MICROSECONDS, 0);
|
||||
cmp(now, MILLISECONDS, now-1234, MILLISECONDS, 1);
|
||||
cmp(now, MILLISECONDS, now+1234, MILLISECONDS, -1);
|
||||
|
||||
cmp(tomorrowInDays, DAYS, now, MILLISECONDS, 1);
|
||||
cmp(now, MILLISECONDS, tomorrowInDays, DAYS, -1);
|
||||
cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1);
|
||||
cmp(now, MILLISECONDS, yesterdayInDays, DAYS, 1);
|
||||
cmp(yesterdayInDays, DAYS, now, MILLISECONDS, -1);
|
||||
|
||||
cmp(Long.MAX_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, 1);
|
||||
cmp(Long.MAX_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, 1);
|
||||
cmp(Long.MIN_VALUE, DAYS, Long.MIN_VALUE, NANOSECONDS, -1);
|
||||
cmp(Long.MIN_VALUE, DAYS, Long.MAX_VALUE, NANOSECONDS, -1);
|
||||
|
||||
cmp(Instant.MIN, Long.MIN_VALUE, DAYS, 1);
|
||||
cmp(Instant.MIN, Long.MIN_VALUE, HOURS, 1);
|
||||
cmp(Instant.MIN, Long.MIN_VALUE, MINUTES, 1);
|
||||
cmp(Instant.MIN, Long.MIN_VALUE, SECONDS, 1);
|
||||
cmp(Instant.MIN, Instant.MIN.getEpochSecond() - 1, SECONDS, 1);
|
||||
cmp(Instant.MIN, Instant.MIN.getEpochSecond() - 100, SECONDS, 1);
|
||||
cmp(Instant.MIN, Instant.MIN.getEpochSecond(), SECONDS, 0);
|
||||
|
||||
cmp(Instant.MAX, Long.MAX_VALUE, DAYS, -1);
|
||||
cmp(Instant.MAX, Long.MAX_VALUE, HOURS, -1);
|
||||
cmp(Instant.MAX, Long.MAX_VALUE, MINUTES, -1);
|
||||
cmp(Instant.MAX, Long.MAX_VALUE, SECONDS, -1);
|
||||
cmp(Instant.MAX, Instant.MAX.getEpochSecond() + 1, SECONDS, -1);
|
||||
cmp(Instant.MAX, Instant.MAX.getEpochSecond() + 100, SECONDS, -1);
|
||||
cmp(Instant.MAX, Instant.MAX.getEpochSecond(), SECONDS, 0);
|
||||
|
||||
cmp(nowInstant, now, MILLISECONDS, 0);
|
||||
cmp(nowInstant, now*1000L, MICROSECONDS, 0);
|
||||
cmp(nowInstant, now-1234, MILLISECONDS, 1);
|
||||
cmp(nowInstant, now+1234, MILLISECONDS, -1);
|
||||
cmp(nowInstant, tomorrowInDays, DAYS, -1);
|
||||
cmp(nowInstant, yesterdayInDays, DAYS, 1);
|
||||
|
||||
// to(TimeUnit)
|
||||
to(MILLISECONDS.convert(1, DAYS) - 1, MILLISECONDS);
|
||||
to(MILLISECONDS.convert(1, DAYS) + 0, MILLISECONDS);
|
||||
to(MILLISECONDS.convert(1, DAYS) + 1, MILLISECONDS);
|
||||
to(1, MILLISECONDS);
|
||||
to(0, MILLISECONDS);
|
||||
to(1, MILLISECONDS);
|
||||
to(MILLISECONDS.convert(-1, DAYS) - 1, MILLISECONDS);
|
||||
to(MILLISECONDS.convert(-1, DAYS) + 0, MILLISECONDS);
|
||||
to(MILLISECONDS.convert(-1, DAYS) + 1, MILLISECONDS);
|
||||
for (TimeUnit unit: TimeUnit.values()) {
|
||||
for (int i=0; i<100; i++) { to(rand.nextLong(), unit); }
|
||||
to(Long.MIN_VALUE, unit);
|
||||
to(Long.MAX_VALUE, unit);
|
||||
}
|
||||
|
||||
// toInstant()
|
||||
int N = 1000;
|
||||
for (TimeUnit unit : EnumSet.allOf(TimeUnit.class)) {
|
||||
for (int i = 0; i < N; i++) {
|
||||
long value = rand.nextLong();
|
||||
FileTime ft = FileTime.from(value, unit);
|
||||
Instant instant = ft.toInstant();
|
||||
if (instant != Instant.MIN && instant != Instant.MAX) {
|
||||
eqTime(value, unit, instant);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (TimeUnit unit : EnumSet.allOf(TimeUnit.class)) {
|
||||
long value = Long.MIN_VALUE;
|
||||
FileTime ft = FileTime.from(value, unit);
|
||||
Instant instant = ft.toInstant();
|
||||
if (unit.compareTo(TimeUnit.SECONDS) < 0) {
|
||||
eqTime(value, unit, instant);
|
||||
} else if (!instant.equals(Instant.MIN)) {
|
||||
throw new RuntimeException("should overflow to MIN");
|
||||
}
|
||||
value = Long.MAX_VALUE;
|
||||
ft = FileTime.from(value, unit);
|
||||
instant = ft.toInstant();
|
||||
if (unit.compareTo(TimeUnit.SECONDS) < 0) {
|
||||
eqTime(value, unit, instant);
|
||||
} else if (!instant.equals(Instant.MAX)) {
|
||||
throw new RuntimeException("should overflow to MAX");
|
||||
}
|
||||
}
|
||||
|
||||
// from(Instant)
|
||||
final long MAX_SECOND = 31556889864403199L;
|
||||
for (int i = 0; i < N; i++) {
|
||||
long v = rand.nextLong();
|
||||
long secs = v % MAX_SECOND;
|
||||
Instant instant = Instant.ofEpochSecond(secs, rand.nextInt(1000_000_000));
|
||||
FileTime ft = FileTime.from(instant);
|
||||
if (!ft.toInstant().equals(instant) || ft.to(SECONDS) != secs) {
|
||||
throw new RuntimeException("from(Instant) failed");
|
||||
}
|
||||
long millis = v;
|
||||
instant = Instant.ofEpochMilli(millis);
|
||||
ft = FileTime.from(instant);
|
||||
if (!ft.toInstant().equals(instant) ||
|
||||
ft.toMillis() != instant.toEpochMilli()) {
|
||||
throw new RuntimeException("from(Instant) failed");
|
||||
}
|
||||
long nanos = v;
|
||||
ft = FileTime.from(nanos, NANOSECONDS);
|
||||
secs = nanos / 1000_000_000;
|
||||
nanos = nanos % 1000_000_000;
|
||||
instant = Instant.ofEpochSecond(secs, nanos);
|
||||
if (!ft.equals(FileTime.from(instant))) {
|
||||
throw new RuntimeException("from(Instant) failed");
|
||||
}
|
||||
}
|
||||
|
||||
// toString
|
||||
ts(1L, DAYS, "1970-01-02T00:00:00Z");
|
||||
ts(1L, HOURS, "1970-01-01T01:00:00Z");
|
||||
ts(1L, MINUTES, "1970-01-01T00:01:00Z");
|
||||
ts(1L, SECONDS, "1970-01-01T00:00:01Z");
|
||||
ts(1L, MILLISECONDS, "1970-01-01T00:00:00.001Z");
|
||||
ts(1L, MICROSECONDS, "1970-01-01T00:00:00.000001Z");
|
||||
ts(1L, NANOSECONDS, "1970-01-01T00:00:00.000000001Z");
|
||||
ts(999999999L, NANOSECONDS, "1970-01-01T00:00:00.999999999Z");
|
||||
ts(9999999999L, NANOSECONDS, "1970-01-01T00:00:09.999999999Z");
|
||||
|
||||
ts(-1L, DAYS, "1969-12-31T00:00:00Z");
|
||||
ts(-1L, HOURS, "1969-12-31T23:00:00Z");
|
||||
ts(-1L, MINUTES, "1969-12-31T23:59:00Z");
|
||||
ts(-1L, SECONDS, "1969-12-31T23:59:59Z");
|
||||
ts(-1L, MILLISECONDS, "1969-12-31T23:59:59.999Z");
|
||||
ts(-1L, MICROSECONDS, "1969-12-31T23:59:59.999999Z");
|
||||
ts(-1L, NANOSECONDS, "1969-12-31T23:59:59.999999999Z");
|
||||
ts(-999999999L, NANOSECONDS, "1969-12-31T23:59:59.000000001Z");
|
||||
ts(-9999999999L, NANOSECONDS, "1969-12-31T23:59:50.000000001Z");
|
||||
|
||||
ts(-62135596799999L, MILLISECONDS, "0001-01-01T00:00:00.001Z");
|
||||
ts(-62135596800000L, MILLISECONDS, "0001-01-01T00:00:00Z");
|
||||
ts(-62135596800001L, MILLISECONDS, "-0001-12-31T23:59:59.999Z");
|
||||
|
||||
ts(253402300799999L, MILLISECONDS, "9999-12-31T23:59:59.999Z");
|
||||
ts(-377642044800001L, MILLISECONDS, "-9999-12-31T23:59:59.999Z");
|
||||
|
||||
// NTFS epoch in usec.
|
||||
ts(-11644473600000000L, MICROSECONDS, "1601-01-01T00:00:00Z");
|
||||
|
||||
ts(Instant.MIN, "-1000000001-01-01T00:00:00Z");
|
||||
ts(Instant.MAX, "1000000000-12-31T23:59:59.999999999Z");
|
||||
|
||||
try {
|
||||
FileTime.from(0L, null);
|
||||
throw new RuntimeException("NullPointerException expected");
|
||||
} catch (NullPointerException npe) { }
|
||||
try {
|
||||
FileTime.from(null);
|
||||
throw new RuntimeException("NullPointerException expected");
|
||||
} catch (NullPointerException npe) { }
|
||||
|
||||
FileTime time = FileTime.fromMillis(now);
|
||||
if (time.equals(null))
|
||||
throw new RuntimeException("should not be equal to null");
|
||||
try {
|
||||
time.compareTo(null);
|
||||
throw new RuntimeException("NullPointerException expected");
|
||||
} catch (NullPointerException npe) { }
|
||||
|
||||
// Instant + toMilli() overflow
|
||||
overflow(Long.MAX_VALUE,
|
||||
FileTime.from(Instant.MAX).toMillis());
|
||||
overflow(Long.MAX_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MAX_VALUE / 1000 + 1))
|
||||
.toMillis());
|
||||
overflow(Long.MIN_VALUE,
|
||||
FileTime.from(Instant.MIN).toMillis());
|
||||
overflow(Long.MIN_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1))
|
||||
.toMillis());
|
||||
|
||||
// Instant + to(TimeUnit) overflow
|
||||
overflow(Long.MAX_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MAX_VALUE / 1000 + 1))
|
||||
.to(MILLISECONDS));
|
||||
overflow(Long.MAX_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MAX_VALUE / 1000,
|
||||
MILLISECONDS.toNanos(1000)))
|
||||
.to(MILLISECONDS));
|
||||
overflow(Long.MIN_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1))
|
||||
.to(MILLISECONDS));
|
||||
overflow(Long.MIN_VALUE,
|
||||
FileTime.from(Instant.ofEpochSecond(Long.MIN_VALUE / 1000,
|
||||
-MILLISECONDS.toNanos(1)))
|
||||
.to(MILLISECONDS));
|
||||
}
|
||||
|
||||
static void overflow(long minmax, long v) {
|
||||
if (v != minmax)
|
||||
throw new RuntimeException("saturates to Long.MIN/MAX_VALUE expected");
|
||||
}
|
||||
|
||||
static void cmp(long v1, TimeUnit u1, long v2, TimeUnit u2, int expected) {
|
||||
int result = FileTime.from(v1, u1).compareTo(FileTime.from(v2, u2));
|
||||
if (result != expected)
|
||||
throw new RuntimeException("unexpected order");
|
||||
}
|
||||
|
||||
static void cmp(Instant ins, long v2, TimeUnit u2, int expected) {
|
||||
int result = FileTime.from(ins).compareTo(FileTime.from(v2, u2));
|
||||
if (result != expected)
|
||||
throw new RuntimeException("unexpected order");
|
||||
}
|
||||
|
||||
static void eq(long v1, TimeUnit u1, long v2, TimeUnit u2) {
|
||||
FileTime t1 = FileTime.from(v1, u1);
|
||||
FileTime t2 = FileTime.from(v2, u2);
|
||||
if (!t1.equals(t2))
|
||||
throw new RuntimeException("not equal");
|
||||
if (t1.hashCode() != t2.hashCode())
|
||||
throw new RuntimeException("hashCodes should be equal");
|
||||
}
|
||||
|
||||
static void eq(Instant ins, long v2, TimeUnit u2) {
|
||||
FileTime t1 = FileTime.from(ins);
|
||||
FileTime t2 = FileTime.from(v2, u2);
|
||||
if (!t1.equals(t2))
|
||||
throw new RuntimeException("not equal");
|
||||
if (t1.hashCode() != t2.hashCode())
|
||||
throw new RuntimeException("hashCodes should be equal");
|
||||
}
|
||||
|
||||
static void eqTime(long value, TimeUnit unit, Instant instant) {
|
||||
long secs = SECONDS.convert(value, unit);
|
||||
long nanos = NANOSECONDS.convert(value - unit.convert(secs, SECONDS), unit);
|
||||
if (nanos < 0) { // normalize nanoOfSecond to positive
|
||||
secs -= 1;
|
||||
nanos += 1000_000_000;
|
||||
}
|
||||
if (secs != instant.getEpochSecond() || (int)nanos != instant.getNano()) {
|
||||
System.err.println(" ins=" + instant);
|
||||
throw new RuntimeException("ft and instant are not the same time point");
|
||||
}
|
||||
}
|
||||
|
||||
static void neq(long v1, TimeUnit u1, long v2, TimeUnit u2) {
|
||||
FileTime t1 = FileTime.from(v1, u1);
|
||||
FileTime t2 = FileTime.from(v2, u2);
|
||||
if (t1.equals(t2))
|
||||
throw new RuntimeException("should not be equal");
|
||||
}
|
||||
|
||||
static void neq(Instant ins, long v2, TimeUnit u2) {
|
||||
FileTime t1 = FileTime.from(ins);
|
||||
FileTime t2 = FileTime.from(v2, u2);
|
||||
if (t1.equals(t2))
|
||||
throw new RuntimeException("should not be equal");
|
||||
}
|
||||
|
||||
static void to(long v, TimeUnit unit) {
|
||||
FileTime t = FileTime.from(v, unit);
|
||||
for (TimeUnit u: TimeUnit.values()) {
|
||||
long result = t.to(u);
|
||||
long expected = u.convert(v, unit);
|
||||
if (result != expected) {
|
||||
throw new RuntimeException("unexpected result");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ts(long v, TimeUnit unit, String expected) {
|
||||
String result = FileTime.from(v, unit).toString();
|
||||
if (!result.equals(expected)) {
|
||||
System.err.format("FileTime.from(%d, %s).toString() failed\n", v, unit);
|
||||
System.err.format("Expected: %s\n", expected);
|
||||
System.err.format(" Got: %s\n", result);
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
|
||||
static void ts(Instant instant, String expected) {
|
||||
String result = FileTime.from(instant).toString();
|
||||
if (!result.equals(expected)) {
|
||||
System.err.format("FileTime.from(%s).toString() failed\n", instant);
|
||||
System.err.format("Expected: %s\n", expected);
|
||||
System.err.format(" Got: %s\n", result);
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,437 @@
|
|||
/*
|
||||
* Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 4313887 6838333 8062795
|
||||
* @summary Unit test for java.nio.file.attribute.PosixFileAttributeView
|
||||
* @library ../..
|
||||
*/
|
||||
|
||||
import java.nio.file.*;
|
||||
import static java.nio.file.LinkOption.*;
|
||||
import java.nio.file.attribute.*;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Unit test for PosixFileAttributeView, passing silently if this attribute
|
||||
* view is not available.
|
||||
*/
|
||||
|
||||
public class Basic {
|
||||
|
||||
/**
|
||||
* Use view to update permission to the given mode and check that the
|
||||
* permissions have been updated.
|
||||
*/
|
||||
static void testPermissions(Path file, String mode) throws IOException {
|
||||
System.out.format("change mode: %s\n", mode);
|
||||
Set<PosixFilePermission> perms = PosixFilePermissions.fromString(mode);
|
||||
|
||||
// change permissions and re-read them.
|
||||
Files.setPosixFilePermissions(file, perms);
|
||||
Set<PosixFilePermission> current = Files.getPosixFilePermissions(file);
|
||||
if (!current.equals(perms)) {
|
||||
throw new RuntimeException("Actual permissions: " +
|
||||
PosixFilePermissions.toString(current) + ", expected: " +
|
||||
PosixFilePermissions.toString(perms));
|
||||
}
|
||||
|
||||
// repeat test using setAttribute/getAttribute
|
||||
Files.setAttribute(file, "posix:permissions", perms);
|
||||
current = (Set<PosixFilePermission>)Files.getAttribute(file, "posix:permissions");
|
||||
if (!current.equals(perms)) {
|
||||
throw new RuntimeException("Actual permissions: " +
|
||||
PosixFilePermissions.toString(current) + ", expected: " +
|
||||
PosixFilePermissions.toString(perms));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the actual permissions of a file match or make it more
|
||||
* secure than requested
|
||||
*/
|
||||
static void checkSecure(Set<PosixFilePermission> requested,
|
||||
Set<PosixFilePermission> actual)
|
||||
{
|
||||
for (PosixFilePermission perm: actual) {
|
||||
if (!requested.contains(perm)) {
|
||||
throw new RuntimeException("Actual permissions: " +
|
||||
PosixFilePermissions.toString(actual) + ", requested: " +
|
||||
PosixFilePermissions.toString(requested) +
|
||||
" - file is less secure than requested");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create file with given mode and check that the file is created with a
|
||||
* mode that is not less secure
|
||||
*/
|
||||
static void createWithPermissions(Path file,
|
||||
String mode)
|
||||
throws IOException
|
||||
{
|
||||
Set<PosixFilePermission> requested = PosixFilePermissions.fromString(mode);
|
||||
FileAttribute<Set<PosixFilePermission>> attr =
|
||||
PosixFilePermissions.asFileAttribute(requested);
|
||||
System.out.format("create file with mode: %s\n", mode);
|
||||
Files.createFile(file, attr);
|
||||
try {
|
||||
checkSecure(requested,
|
||||
Files.getFileAttributeView(file, PosixFileAttributeView.class)
|
||||
.readAttributes()
|
||||
.permissions());
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
|
||||
System.out.format("create directory with mode: %s\n", mode);
|
||||
Files.createDirectory(file, attr);
|
||||
try {
|
||||
checkSecure(requested,
|
||||
Files.getFileAttributeView(file, PosixFileAttributeView.class)
|
||||
.readAttributes()
|
||||
.permissions());
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the setPermissions/permissions methods.
|
||||
*/
|
||||
static void permissionTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("-- Permission Tests --");
|
||||
|
||||
// create file and test updating and reading its permissions
|
||||
Path file = dir.resolve("foo");
|
||||
System.out.format("create %s\n", file);
|
||||
Files.createFile(file);
|
||||
try {
|
||||
// get initial permissions so that we can restore them later
|
||||
PosixFileAttributeView view =
|
||||
Files.getFileAttributeView(file, PosixFileAttributeView.class);
|
||||
Set<PosixFilePermission> save = view.readAttributes()
|
||||
.permissions();
|
||||
|
||||
// test various modes
|
||||
try {
|
||||
testPermissions(file, "---------");
|
||||
testPermissions(file, "r--------");
|
||||
testPermissions(file, "-w-------");
|
||||
testPermissions(file, "--x------");
|
||||
testPermissions(file, "rwx------");
|
||||
testPermissions(file, "---r-----");
|
||||
testPermissions(file, "----w----");
|
||||
testPermissions(file, "-----x---");
|
||||
testPermissions(file, "---rwx---");
|
||||
testPermissions(file, "------r--");
|
||||
testPermissions(file, "-------w-");
|
||||
testPermissions(file, "--------x");
|
||||
testPermissions(file, "------rwx");
|
||||
testPermissions(file, "r--r-----");
|
||||
testPermissions(file, "r--r--r--");
|
||||
testPermissions(file, "rw-rw----");
|
||||
testPermissions(file, "rwxrwx---");
|
||||
testPermissions(file, "rw-rw-r--");
|
||||
testPermissions(file, "r-xr-x---");
|
||||
testPermissions(file, "r-xr-xr-x");
|
||||
testPermissions(file, "rwxrwxrwx");
|
||||
} finally {
|
||||
view.setPermissions(save);
|
||||
}
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
|
||||
if (TestUtil.supportsSymbolicLinks(dir)) {
|
||||
// create link (to file that doesn't exist) and test reading of
|
||||
// permissions
|
||||
Path link = dir.resolve("link");
|
||||
System.out.format("create link %s\n", link);
|
||||
Files.createSymbolicLink(link, file);
|
||||
try {
|
||||
PosixFileAttributes attrs =
|
||||
Files.getFileAttributeView(link,
|
||||
PosixFileAttributeView.class,
|
||||
NOFOLLOW_LINKS)
|
||||
.readAttributes();
|
||||
if (!attrs.isSymbolicLink()) {
|
||||
throw new RuntimeException("not a link");
|
||||
}
|
||||
} finally {
|
||||
Files.delete(link);
|
||||
}
|
||||
|
||||
// test that setting permissions on paths with and without
|
||||
// links succeeds when the NOFOLLOW_LINKS option is set
|
||||
|
||||
// ensure there are no links in the path to test
|
||||
Path realDir = dir.toRealPath();
|
||||
|
||||
// realDir/a/b/c/d
|
||||
Path leaf = realDir.resolve(Path.of("a", "b", "c", "d"));
|
||||
Files.createDirectories(leaf);
|
||||
|
||||
// realDir/a/b/c/d/FUBAR
|
||||
Path sansLinks = Files.createTempFile(leaf, "FU", "BAR");
|
||||
|
||||
PosixFileAttributeView sansView =
|
||||
Files.getFileAttributeView(sansLinks,
|
||||
PosixFileAttributeView.class,
|
||||
LinkOption.NOFOLLOW_LINKS);
|
||||
sansView.setPermissions(Set.of(PosixFilePermission.OWNER_WRITE));
|
||||
sansView.setPermissions(Set.of(PosixFilePermission.OWNER_WRITE));
|
||||
|
||||
// reinstate read permission
|
||||
sansView.setPermissions(Set.of(PosixFilePermission.OWNER_READ,
|
||||
PosixFilePermission.OWNER_WRITE));
|
||||
|
||||
// lien -> realDir/a/b/c
|
||||
Path lien = realDir.resolve(Path.of("a", "lien"));
|
||||
Files.createSymbolicLink(lien,
|
||||
realDir.resolve(Path.of("a", "b", "c")));
|
||||
|
||||
// lien/d/FUBAR
|
||||
Path withLinks = lien.resolve(Path.of("d"),
|
||||
sansLinks.getFileName());
|
||||
|
||||
PosixFileAttributeView withView =
|
||||
Files.getFileAttributeView(withLinks,
|
||||
PosixFileAttributeView.class,
|
||||
LinkOption.NOFOLLOW_LINKS);
|
||||
withView.setPermissions(Set.of(PosixFilePermission.OWNER_WRITE));
|
||||
withView.setPermissions(Set.of(PosixFilePermission.OWNER_WRITE));
|
||||
}
|
||||
|
||||
System.out.println("OKAY");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test creating a file and directory with initial permissios
|
||||
*/
|
||||
static void createTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("-- Create Tests --");
|
||||
|
||||
Path file = dir.resolve("foo");
|
||||
|
||||
createWithPermissions(file, "---------");
|
||||
createWithPermissions(file, "r--------");
|
||||
createWithPermissions(file, "-w-------");
|
||||
createWithPermissions(file, "--x------");
|
||||
createWithPermissions(file, "rwx------");
|
||||
createWithPermissions(file, "---r-----");
|
||||
createWithPermissions(file, "----w----");
|
||||
createWithPermissions(file, "-----x---");
|
||||
createWithPermissions(file, "---rwx---");
|
||||
createWithPermissions(file, "------r--");
|
||||
createWithPermissions(file, "-------w-");
|
||||
createWithPermissions(file, "--------x");
|
||||
createWithPermissions(file, "------rwx");
|
||||
createWithPermissions(file, "r--r-----");
|
||||
createWithPermissions(file, "r--r--r--");
|
||||
createWithPermissions(file, "rw-rw----");
|
||||
createWithPermissions(file, "rwxrwx---");
|
||||
createWithPermissions(file, "rw-rw-r--");
|
||||
createWithPermissions(file, "r-xr-x---");
|
||||
createWithPermissions(file, "r-xr-xr-x");
|
||||
createWithPermissions(file, "rwxrwxrwx");
|
||||
|
||||
System.out.println("OKAY");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test setOwner/setGroup methods - this test simply exercises the
|
||||
* methods to avoid configuration.
|
||||
*/
|
||||
static void ownerTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("-- Owner Tests --");
|
||||
|
||||
Path file = dir.resolve("gus");
|
||||
System.out.format("create %s\n", file);
|
||||
|
||||
Files.createFile(file);
|
||||
try {
|
||||
|
||||
// read attributes of directory to get owner/group
|
||||
PosixFileAttributeView view =
|
||||
Files.getFileAttributeView(file, PosixFileAttributeView.class);
|
||||
PosixFileAttributes attrs = view.readAttributes();
|
||||
|
||||
// set to existing owner/group
|
||||
view.setOwner(attrs.owner());
|
||||
view.setGroup(attrs.group());
|
||||
|
||||
// repeat test using set/getAttribute
|
||||
UserPrincipal owner = (UserPrincipal)Files.getAttribute(file, "posix:owner");
|
||||
Files.setAttribute(file, "posix:owner", owner);
|
||||
UserPrincipal group = (UserPrincipal)Files.getAttribute(file, "posix:group");
|
||||
Files.setAttribute(file, "posix:group", group);
|
||||
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
|
||||
System.out.println("OKAY");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the lookupPrincipalByName/lookupPrincipalByGroupName methods
|
||||
*/
|
||||
static void lookupPrincipalTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("-- Lookup UserPrincipal Tests --");
|
||||
|
||||
UserPrincipalLookupService lookupService = dir.getFileSystem()
|
||||
.getUserPrincipalLookupService();
|
||||
|
||||
// read attributes of directory to get owner/group
|
||||
PosixFileAttributes attrs = Files.readAttributes(dir, PosixFileAttributes.class);
|
||||
|
||||
// lookup owner and check it matches file's owner
|
||||
System.out.format("lookup: %s\n", attrs.owner().getName());
|
||||
try {
|
||||
UserPrincipal owner = lookupService.lookupPrincipalByName(attrs.owner().getName());
|
||||
if (owner instanceof GroupPrincipal)
|
||||
throw new RuntimeException("owner is a group?");
|
||||
if (!owner.equals(attrs.owner()))
|
||||
throw new RuntimeException("owner different from file owner");
|
||||
} catch (UserPrincipalNotFoundException x) {
|
||||
System.out.println("user not found - test skipped");
|
||||
}
|
||||
|
||||
// lookup group and check it matches file's group-owner
|
||||
System.out.format("lookup group: %s\n", attrs.group().getName());
|
||||
try {
|
||||
GroupPrincipal group = lookupService.lookupPrincipalByGroupName(attrs.group().getName());
|
||||
if (!group.equals(attrs.group()))
|
||||
throw new RuntimeException("group different from file group-owner");
|
||||
} catch (UserPrincipalNotFoundException x) {
|
||||
System.out.println("group not found - test skipped");
|
||||
}
|
||||
|
||||
// test that UserPrincipalNotFoundException is thrown
|
||||
String invalidPrincipal = "scumbag99";
|
||||
try {
|
||||
System.out.format("lookup: %s\n", invalidPrincipal);
|
||||
lookupService.lookupPrincipalByName(invalidPrincipal);
|
||||
throw new RuntimeException("'" + invalidPrincipal + "' is a valid user?");
|
||||
} catch (UserPrincipalNotFoundException x) {
|
||||
}
|
||||
try {
|
||||
System.out.format("lookup group: %s\n", invalidPrincipal);
|
||||
lookupService.lookupPrincipalByGroupName("idonotexist");
|
||||
throw new RuntimeException("'" + invalidPrincipal + "' is a valid group?");
|
||||
} catch (UserPrincipalNotFoundException x) {
|
||||
}
|
||||
System.out.println("OKAY");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test various exceptions are thrown as expected
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static void exceptionsTests(Path dir)
|
||||
throws IOException
|
||||
{
|
||||
System.out.println("-- Exceptions --");
|
||||
|
||||
PosixFileAttributeView view =
|
||||
Files.getFileAttributeView(dir,PosixFileAttributeView.class);
|
||||
|
||||
// NullPointerException
|
||||
try {
|
||||
view.setOwner(null);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
try {
|
||||
view.setGroup(null);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
|
||||
UserPrincipalLookupService lookupService = dir.getFileSystem()
|
||||
.getUserPrincipalLookupService();
|
||||
try {
|
||||
lookupService.lookupPrincipalByName(null);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
try {
|
||||
lookupService.lookupPrincipalByGroupName(null);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
try {
|
||||
view.setPermissions(null);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
try {
|
||||
Set<PosixFilePermission> perms = new HashSet<>();
|
||||
perms.add(null);
|
||||
view.setPermissions(perms);
|
||||
throw new RuntimeException("NullPointerException not thrown");
|
||||
} catch (NullPointerException x) {
|
||||
}
|
||||
|
||||
// ClassCastException
|
||||
try {
|
||||
Set perms = new HashSet(); // raw type
|
||||
perms.add(new Object());
|
||||
view.setPermissions(perms);
|
||||
throw new RuntimeException("ClassCastException not thrown");
|
||||
} catch (ClassCastException x) {
|
||||
}
|
||||
|
||||
System.out.println("OKAY");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Path dir = TestUtil.createTemporaryDirectory();
|
||||
try {
|
||||
if (!Files.getFileStore(dir).supportsFileAttributeView("posix")) {
|
||||
System.out.println("PosixFileAttributeView not supported");
|
||||
return;
|
||||
}
|
||||
|
||||
permissionTests(dir);
|
||||
createTests(dir);
|
||||
ownerTests(dir);
|
||||
lookupPrincipalTests(dir);
|
||||
exceptionsTests(dir);
|
||||
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,338 @@
|
|||
/*
|
||||
* Copyright (c) 2008, 2026, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/* @test
|
||||
* @bug 4313887 6838333 8273922
|
||||
* @summary Unit test for java.nio.file.attribute.UserDefinedFileAttributeView
|
||||
* (use -Dseed=X to set PRNG seed)
|
||||
* @library ../.. /test/lib
|
||||
* @key randomness
|
||||
* @build jdk.test.lib.Platform
|
||||
* @build jdk.test.lib.RandomFactory
|
||||
* @build jtreg.SkippedException
|
||||
* @run main Basic
|
||||
*/
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.foreign.Arena;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.UserDefinedFileAttributeView;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import jdk.test.lib.Platform;
|
||||
import jdk.test.lib.RandomFactory;
|
||||
|
||||
import jtreg.SkippedException;
|
||||
|
||||
public class Basic {
|
||||
|
||||
// Must be indeterministic
|
||||
private static final Random rand = RandomFactory.getRandom();
|
||||
|
||||
private static final String ATTR_NAME = "mime_type";
|
||||
private static final String ATTR_VALUE = "text/plain";
|
||||
private static final String ATTR_VALUE2 = "text/html";
|
||||
|
||||
static interface Task {
|
||||
void run() throws Exception;
|
||||
}
|
||||
|
||||
static void tryCatch(Class<? extends Throwable> ex, Task task) {
|
||||
boolean caught = false;
|
||||
try {
|
||||
task.run();
|
||||
} catch (Throwable x) {
|
||||
if (ex.isAssignableFrom(x.getClass())) {
|
||||
caught = true;
|
||||
} else {
|
||||
throw new RuntimeException(x);
|
||||
}
|
||||
}
|
||||
if (!caught)
|
||||
throw new RuntimeException(ex.getName() + " expected");
|
||||
}
|
||||
|
||||
static void expectNullPointerException(Task task) {
|
||||
tryCatch(NullPointerException.class, task);
|
||||
}
|
||||
|
||||
static boolean hasAttribute(UserDefinedFileAttributeView view, String attr)
|
||||
throws IOException
|
||||
{
|
||||
for (String name: view.list()) {
|
||||
if (name.equals(ATTR_NAME))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void test(Path file, LinkOption... options) throws IOException {
|
||||
final UserDefinedFileAttributeView view =
|
||||
Files.getFileAttributeView(file, UserDefinedFileAttributeView.class, options);
|
||||
final ByteBuffer buf = switch (rand.nextInt(3)) {
|
||||
case 0 -> ByteBuffer.allocate(100);
|
||||
case 1 -> ByteBuffer.allocateDirect(100);
|
||||
case 2 -> Arena.ofAuto().allocate(100).asByteBuffer();
|
||||
default -> throw new InternalError("Should not reach here");
|
||||
};
|
||||
|
||||
// Test: write
|
||||
buf.put(ATTR_VALUE.getBytes()).flip();
|
||||
int size = buf.remaining();
|
||||
int nwrote = view.write(ATTR_NAME, buf);
|
||||
if (nwrote != size)
|
||||
throw new RuntimeException("Unexpected number of bytes written");
|
||||
|
||||
// Test: size
|
||||
if (view.size(ATTR_NAME) != size)
|
||||
throw new RuntimeException("Unexpected size");
|
||||
|
||||
// Test: read
|
||||
buf.clear();
|
||||
int nread = view.read(ATTR_NAME, buf);
|
||||
if (nread != size)
|
||||
throw new RuntimeException("Unexpected number of bytes read");
|
||||
buf.flip();
|
||||
String value = Charset.defaultCharset().decode(buf).toString();
|
||||
if (!value.equals(ATTR_VALUE))
|
||||
throw new RuntimeException("Unexpected attribute value");
|
||||
|
||||
// Test: read with insufficient space
|
||||
tryCatch(IOException.class, new Task() {
|
||||
public void run() throws IOException {
|
||||
view.read(ATTR_NAME, ByteBuffer.allocateDirect(1));
|
||||
}});
|
||||
|
||||
// Test: replace value
|
||||
buf.clear();
|
||||
buf.put(ATTR_VALUE2.getBytes()).flip();
|
||||
size = buf.remaining();
|
||||
view.write(ATTR_NAME, buf);
|
||||
if (view.size(ATTR_NAME) != size)
|
||||
throw new RuntimeException("Unexpected size");
|
||||
|
||||
// Test: list
|
||||
if (!hasAttribute(view, ATTR_NAME))
|
||||
throw new RuntimeException("Attribute name not in list");
|
||||
|
||||
// Test: delete
|
||||
view.delete(ATTR_NAME);
|
||||
if (hasAttribute(view, ATTR_NAME))
|
||||
throw new RuntimeException("Attribute name in list");
|
||||
|
||||
// Test: dynamic access
|
||||
String name = "user:" + ATTR_NAME;
|
||||
byte[] valueAsBytes = ATTR_VALUE.getBytes();
|
||||
Files.setAttribute(file, name, valueAsBytes);
|
||||
byte[] actualAsBytes = (byte[])Files.getAttribute(file, name);
|
||||
if (!Arrays.equals(valueAsBytes, actualAsBytes))
|
||||
throw new RuntimeException("Unexpected attribute value");
|
||||
Map<String,?> map = Files.readAttributes(file, name);
|
||||
if (!Arrays.equals(valueAsBytes, (byte[])map.get(ATTR_NAME)))
|
||||
throw new RuntimeException("Unexpected attribute value");
|
||||
map = Files.readAttributes(file, "user:*");
|
||||
if (!Arrays.equals(valueAsBytes, (byte[])map.get(ATTR_NAME)))
|
||||
throw new RuntimeException("Unexpected attribute value");
|
||||
}
|
||||
|
||||
private static void setEA(Path longPath, String s) throws IOException {
|
||||
System.out.println("Setting short EA '" + s +
|
||||
"' on path of length " + longPath.toString().length());
|
||||
Files.setAttribute(longPath, s,
|
||||
ByteBuffer.wrap("ea-value".getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
static void miscTests(final Path dir) throws IOException {
|
||||
final UserDefinedFileAttributeView view =
|
||||
Files.getFileAttributeView(dir, UserDefinedFileAttributeView.class);
|
||||
view.write(ATTR_NAME, ByteBuffer.wrap(ATTR_VALUE.getBytes()));
|
||||
|
||||
// NullPointerException
|
||||
final ByteBuffer buf = ByteBuffer.allocate(100);
|
||||
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.read(null, buf);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.read(ATTR_NAME, null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.write(null, buf);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.write(ATTR_NAME, null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.size(null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
view.delete(null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.getAttribute(dir, null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.getAttribute(dir, "user:" + ATTR_NAME, (LinkOption[])null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.setAttribute(dir, "user:" + ATTR_NAME, null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.setAttribute(dir, null, new byte[0]);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.setAttribute(dir, "user: " + ATTR_NAME, new byte[0], (LinkOption[])null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.readAttributes(dir, (String)null);
|
||||
}});
|
||||
expectNullPointerException(new Task() {
|
||||
public void run() throws IOException {
|
||||
Files.readAttributes(dir, "*", (LinkOption[])null);
|
||||
}});
|
||||
|
||||
// Read-only buffer
|
||||
tryCatch(IllegalArgumentException.class, new Task() {
|
||||
public void run() throws IOException {
|
||||
ByteBuffer buf = ByteBuffer.wrap(ATTR_VALUE.getBytes()).asReadOnlyBuffer();
|
||||
view.write(ATTR_NAME, buf);
|
||||
buf.flip();
|
||||
view.read(ATTR_NAME, buf);
|
||||
}});
|
||||
|
||||
// Zero bytes remaining
|
||||
tryCatch(IOException.class, new Task() {
|
||||
public void run() throws IOException {
|
||||
ByteBuffer buf = buf = ByteBuffer.allocateDirect(100);
|
||||
buf.position(buf.capacity());
|
||||
view.read(ATTR_NAME, buf);
|
||||
}});
|
||||
|
||||
// Long attribute name
|
||||
if (Platform.isWindows()) {
|
||||
Path tmp = Files.createTempDirectory(dir, "ea-length-bug");
|
||||
int len = tmp.toString().length();
|
||||
|
||||
// We need to run up to MAX_PATH for directories,
|
||||
// but not quite go over it.
|
||||
int MAX_PATH = 250;
|
||||
int requiredLen = MAX_PATH - len - 2;
|
||||
|
||||
// Create a really long directory name.
|
||||
Path longPath = tmp.resolve("x".repeat(requiredLen));
|
||||
|
||||
// Make sure the directory exists.
|
||||
Files.createDirectory(longPath);
|
||||
|
||||
try {
|
||||
System.out.println("Testing " + longPath);
|
||||
|
||||
// Try to set absolute path as extended attribute;
|
||||
// expect IAE
|
||||
tryCatch(IllegalArgumentException.class, new Task() {
|
||||
public void run() throws IOException {
|
||||
setEA(longPath, "user:C:\\");
|
||||
}
|
||||
});
|
||||
|
||||
// Try to set an extended attribute on it.
|
||||
setEA(longPath, "user:short");
|
||||
setEA(longPath, "user:reallyquitelonglongattrname");
|
||||
} finally {
|
||||
Files.delete(longPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// create temporary directory to run tests
|
||||
Path dir = TestUtil.createTemporaryDirectory();
|
||||
try {
|
||||
if (!Files.getFileStore(dir).supportsFileAttributeView("user"))
|
||||
throw new SkippedException("UserDefinedFileAttributeView not supported");
|
||||
|
||||
// test access to user defined attributes of regular file
|
||||
Path file = dir.resolve("foo.html");
|
||||
Files.createFile(file);
|
||||
try {
|
||||
test(file);
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
|
||||
// test access to user defined attributes of directory
|
||||
Path subdir = dir.resolve("foo");
|
||||
Files.createDirectory(subdir);
|
||||
try {
|
||||
test(subdir);
|
||||
} finally {
|
||||
Files.delete(subdir);
|
||||
}
|
||||
|
||||
// test access to user defined attributes of sym link
|
||||
if (TestUtil.supportsSymbolicLinks(dir)) {
|
||||
Path target = dir.resolve("doesnotexist");
|
||||
Path link = dir.resolve("link");
|
||||
Files.createSymbolicLink(link, target);
|
||||
try {
|
||||
test(link, LinkOption.NOFOLLOW_LINKS);
|
||||
} catch (IOException x) {
|
||||
// access to attributes of sym link may not be supported
|
||||
} finally {
|
||||
Files.delete(link);
|
||||
}
|
||||
}
|
||||
|
||||
// misc. tests
|
||||
try {
|
||||
file = dir.resolve("foo.txt");
|
||||
Files.createFile(file);
|
||||
miscTests(dir);
|
||||
} finally {
|
||||
Files.delete(file);
|
||||
}
|
||||
|
||||
} finally {
|
||||
TestUtil.removeAll(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue