/* * Copyright (c) 2008, 2022, 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 6917021 7006126 6950237 8006645 8201407 8264744 8267820 * @summary Unit test for java.nio.file.Files copy and move methods (use -Dseed=X to set PRNG seed) * @library .. /test/lib * @build jdk.test.lib.Platform jdk.test.lib.RandomFactory * CopyAndMove PassThroughFileSystem * @run main/othervm CopyAndMove * @key randomness
*/
// Use test.dir to define second directory if possible as it might // be a different volume/file system and so improve test coverage.
String testDir = System.getProperty("test.dir", ".");
Path dir2 = TestUtil.createTemporaryDirectory(testDir);
FileStore fileStore2 = getFileStore(dir2);
printDirInfo("dir2", dir2, fileStore2);
// If different type (format) from dir1, re-do same directory tests if (!fileStore1.type().equals(fileStore2.type())) { try {
testPosixAttributes =
fileStore2.supportsFileAttributeView("posix");
testCopyFileToFile(dir2, dir2, TestUtil.supportsLinks(dir2));
testMove(dir2, dir2, TestUtil.supportsLinks(dir2));
} finally {
TestUtil.removeAll(dir2);
}
}
// Different directories. try { // Recreate dir2 if it was removed above if (notExists(dir2)) {
dir2 = TestUtil.createTemporaryDirectory(testDir);
} boolean testSymbolicLinks =
TestUtil.supportsLinks(dir1) && TestUtil.supportsLinks(dir2);
testPosixAttributes = fileStore1.supportsFileAttributeView("posix") &&
fileStore2.supportsFileAttributeView("posix");
testCopyFileToFile(dir1, dir2, testSymbolicLinks);
testMove(dir1, dir2, testSymbolicLinks);
} finally {
TestUtil.removeAll(dir2);
}
// check last modified time if not a symbolic link if (!attrs1.isSymbolicLink()) { long time1 = attrs1.lastModifiedTime().to(TimeUnit.SECONDS); long time2 = attrs2.lastModifiedTime().to(TimeUnit.SECONDS);
if (time1 != time2) {
System.err.format("File time for %s is %s\n", attrs1.fileKey(), attrs1.lastModifiedTime());
System.err.format("File time for %s is %s\n", attrs2.fileKey(), attrs2.lastModifiedTime());
assertTrue(false);
}
}
// check size if (attrs1.isRegularFile())
assertTrue(attrs1.size() == attrs2.size());
}
static Map<String,ByteBuffer> readUserDefinedFileAttributes(Path file) throws IOException
{
UserDefinedFileAttributeView view =
getFileAttributeView(file, UserDefinedFileAttributeView.class);
Map<String,ByteBuffer> result = new HashMap<>(); for (String name: view.list()) { int size = view.size(name);
ByteBuffer bb = ByteBuffer.allocate(size); int n = view.read(name, bb);
assertTrue(n == size);
bb.flip();
result.put(name, bb);
} return result;
}
// move source to target with verification staticvoid moveAndVerify(Path source, Path target, CopyOption... options) throws IOException
{ // read attributes before file is moved
BasicFileAttributes basicAttributes = null;
PosixFileAttributes posixAttributes = null;
DosFileAttributes dosAttributes = null;
Map<String,ByteBuffer> namedAttributes = null;
// get file attributes of source file if (Platform.isWindows()) {
dosAttributes = readAttributes(source, DosFileAttributes.class, NOFOLLOW_LINKS);
basicAttributes = dosAttributes;
} else {
posixAttributes = readAttributes(source, PosixFileAttributes.class, NOFOLLOW_LINKS);
basicAttributes = posixAttributes;
} if (basicAttributes == null)
basicAttributes = readAttributes(source, BasicFileAttributes.class, NOFOLLOW_LINKS);
// hash file contents if regular file int hash = (basicAttributes.isRegularFile()) ? computeHash(source) : 0;
// record link target if symbolic link
Path linkTarget = null; if (basicAttributes.isSymbolicLink())
linkTarget = readSymbolicLink(source);
// read named attributes if available (and file is not a sym link) if (!basicAttributes.isSymbolicLink() &&
getFileStore(source).supportsFileAttributeView("xattr"))
{
namedAttributes = readUserDefinedFileAttributes(source);
}
// verify source does not exist
assertTrue(notExists(source));
// verify file contents if (basicAttributes.isRegularFile()) { if (computeHash(target) != hash) thrownew RuntimeException("Failed to verify move of regular file");
}
// verify link target if (basicAttributes.isSymbolicLink()) { if (!readSymbolicLink(target).equals(linkTarget)) thrownew RuntimeException("Failed to verify move of symbolic link");
}
// copy source to target with verification staticvoid copyAndVerify(Path source, Path target, CopyOption... options) throws IOException
{
Path result = copy(source, target, options);
assertTrue(result == target);
// get attributes of source and target file to verify copy boolean followLinks = true;
LinkOption[] linkOptions = new LinkOption[0]; boolean copyAttributes = false; for (CopyOption opt : options) { if (opt == NOFOLLOW_LINKS) {
followLinks = false;
linkOptions = new LinkOption[] { NOFOLLOW_LINKS };
} if (opt == COPY_ATTRIBUTES)
copyAttributes = true;
}
BasicFileAttributes basicAttributes =
readAttributes(source, BasicFileAttributes.class, linkOptions);
// check hash if regular file if (basicAttributes.isRegularFile())
assertTrue(computeHash(source) == computeHash(target));
// check link target if symbolic link if (basicAttributes.isSymbolicLink()) assert(readSymbolicLink(source).equals(readSymbolicLink(target)));
// check that attributes are copied if (copyAttributes && followLinks) {
checkBasicAttributes(basicAttributes,
readAttributes(source, BasicFileAttributes.class, linkOptions));
// check POSIX attributes are copied if (!Platform.isWindows() && testPosixAttributes) {
checkPosixAttributes(
readAttributes(source, PosixFileAttributes.class, linkOptions),
readAttributes(target, PosixFileAttributes.class, linkOptions));
}
// verify other attributes when same provider if (source.getFileSystem().provider() == target.getFileSystem().provider()) { // check DOS attributes are copied if (Platform.isWindows()) {
checkDosAttributes(
readAttributes(source, DosFileAttributes.class, linkOptions),
readAttributes(target, DosFileAttributes.class, linkOptions));
}
// check named attributes are copied if (followLinks &&
getFileStore(source).supportsFileAttributeView("xattr") &&
getFileStore(target).supportsFileAttributeView("xattr"))
{
checkUserDefinedFileAttributes(readUserDefinedFileAttributes(source),
readUserDefinedFileAttributes(target));
}
}
}
}
/** * Tests all possible ways to invoke copy to copy a file to a file
*/ staticvoid testCopyFileToFile(Path dir1, Path dir2, boolean supportsLinks) throws IOException
{
Path source, target, link, entry;
/** * Test copy from an input stream to a file
*/ staticvoid testCopyInputStreamToFile() throws IOException {
testCopyInputStreamToFile(0); for (int i=0; i<100; i++) {
testCopyInputStreamToFile(rand.nextInt(32000));
}
// check output stream is open
out.write(0);
assertTrue(out.size() == size+1);
} finally { delete(source);
}
}
staticvoid assertTrue(boolean value) { if (!value) thrownew RuntimeException("Assertion failed");
}
staticvoid assertTrue(boolean value, String format, Object... args) { if (!value) {
System.err.format(format, args); thrownew RuntimeException("Assertion failed");
}
}
// computes simple hash of the given file staticint computeHash(Path file) throws IOException { int h = 0;
try (InputStream in = newInputStream(file)) { byte[] buf = newbyte[1024]; int n; do {
n = in.read(buf); for (int i=0; i<n; i++) {
h = 31*h + (buf[i] & 0xff);
}
} while (n > 0);
} return h;
}
// create file of random size in given directory static Path createSourceFile(Path dir) throws IOException {
String name = "source" + Integer.toString(rand.nextInt());
Path file = dir.resolve(name);
createFile(file); byte[] bytes = newbyte[rand.nextInt(128*1024)];
rand.nextBytes(bytes); try (OutputStream out = newOutputStream(file)) {
out.write(bytes);
}
randomizeAttributes(file); return file;
}
// create directory in the given directory static Path createSourceDirectory(Path dir) throws IOException {
String name = "sourcedir" + Integer.toString(rand.nextInt());
Path subdir = dir.resolve(name);
createDirectory(subdir);
randomizeAttributes(subdir); return subdir;
}
// "randomize" the file attributes of the given file. staticvoid randomizeAttributes(Path file) throws IOException { boolean isDirectory = isDirectory(file, NOFOLLOW_LINKS);
if (Platform.isWindows()) {
DosFileAttributeView view =
getFileAttributeView(file, DosFileAttributeView.class, NOFOLLOW_LINKS); // only set or unset the hidden attribute
view.setHidden(heads());
} else {
Set<PosixFilePermission> perms =
getPosixFilePermissions(file, NOFOLLOW_LINKS);
PosixFilePermission[] toChange = {
PosixFilePermission.GROUP_READ,
PosixFilePermission.GROUP_WRITE,
PosixFilePermission.GROUP_EXECUTE,
PosixFilePermission.OTHERS_READ,
PosixFilePermission.OTHERS_WRITE,
PosixFilePermission.OTHERS_EXECUTE
}; for (PosixFilePermission perm: toChange) { if (heads()) {
perms.add(perm);
} else {
perms.remove(perm);
}
}
setPosixFilePermissions(file, perms);
}
// remove this when copying a direcory copies its named streams if (Platform.isWindows() && isDirectory)
addUserDefinedFileAttributes = false;
if (addUserDefinedFileAttributes) {
UserDefinedFileAttributeView view =
getFileAttributeView(file, UserDefinedFileAttributeView.class); int n = rand.nextInt(16); while (n > 0) { byte[] value = newbyte[1 + rand.nextInt(100)];
view.write("user." + Integer.toString(n), ByteBuffer.wrap(value));
n--;
}
}
}
// create name for file in given directory static Path getTargetFile(Path dir) throws IOException {
String name = "target" + Integer.toString(rand.nextInt()); return dir.resolve(name);
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.