下面列出了怎么用java.nio.file.attribute.PosixFileAttributeView的API类实例代码及写法,或者点击链接到github查看源代码。
private static byte[] getPosixFileAttributes(Path file) {
byte[] fileAttributes = new byte[4];
try {
PosixFileAttributeView posixFileAttributeView = Files.getFileAttributeView(file, PosixFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS);
Set<PosixFilePermission> posixFilePermissions = posixFileAttributeView.readAttributes().permissions();
fileAttributes[3] = setBitIfApplicable(Files.isRegularFile(file), fileAttributes[3], 7);
fileAttributes[3] = setBitIfApplicable(Files.isDirectory(file), fileAttributes[3], 6);
fileAttributes[3] = setBitIfApplicable(Files.isSymbolicLink(file), fileAttributes[3], 5);
fileAttributes[3] = setBitIfApplicable(posixFilePermissions.contains(OWNER_READ), fileAttributes[3], 0);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(OWNER_WRITE), fileAttributes[2], 7);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(OWNER_EXECUTE), fileAttributes[2], 6);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(GROUP_READ), fileAttributes[2], 5);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(GROUP_WRITE), fileAttributes[2], 4);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(GROUP_EXECUTE), fileAttributes[2], 3);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(OTHERS_READ), fileAttributes[2], 2);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(OTHERS_WRITE), fileAttributes[2], 1);
fileAttributes[2] = setBitIfApplicable(posixFilePermissions.contains(OTHERS_EXECUTE), fileAttributes[2], 0);
} catch (IOException e) {
// Ignore
}
return fileAttributes;
}
@Override
public void setPosixFilePermissions(Path path, Set<PosixFilePermission> permissions) throws XenonException {
if (permissions == null) {
throw new IllegalArgumentException("Permissions is null!");
}
Path absPath = toAbsolutePath(path);
assertPathExists(absPath);
try {
PosixFileAttributeView view = Files.getFileAttributeView(javaPath(absPath), PosixFileAttributeView.class);
view.setPermissions(javaPermissions(permissions));
} catch (IOException e) {
throw new XenonException(ADAPTOR_NAME, "Failed to set permissions " + absPath, e);
}
}
private void testGetFileAttributesGetsAsDefined(boolean isDirectory) throws IOException {
File file = mock(File.class);
Path path = mock(Path.class);
when(file.toPath()).thenReturn(path);
when(file.exists()).thenReturn(true);
PosixFileAttributeView posixFileAttributeView = mockPosixFileAttributeView(path, isDirectory);
PosixFileAttributes posixFileAttributes = mock(PosixFileAttributes.class);
Set<PosixFilePermission> posixFilePermissions = getAllPermissions();
when(posixFileAttributes.permissions()).thenReturn(posixFilePermissions);
when(posixFileAttributeView.readAttributes()).thenReturn(posixFileAttributes);
byte[] fileAttributes = FileUtils.getFileAttributes(file);
assertThat(fileAttributes).hasSize(4);
assertThat(fileAttributes[0]).isEqualTo((byte) 0);
assertThat(fileAttributes[1]).isEqualTo((byte) 0);
assertThat(fileAttributes[2]).isEqualTo((byte) -1);
if (isDirectory) {
assertThat(fileAttributes[3]).isEqualTo((byte) 65);
} else {
assertThat(fileAttributes[3]).isEqualTo((byte) -127);
}
}
private void makeWritable(Path file) throws IOException {
FileStore fileStore = Files.getFileStore(file);
if (IS_WINDOWS && fileStore.supportsFileAttributeView(DosFileAttributeView.class)) {
DosFileAttributeView dosAttribs =
Files.getFileAttributeView(file, DosFileAttributeView.class);
if (dosAttribs != null) {
dosAttribs.setReadOnly(false);
}
} else if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) {
PosixFileAttributeView posixAttribs =
Files.getFileAttributeView(file, PosixFileAttributeView.class);
if (posixAttribs != null) {
posixAttribs.setPermissions(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE));
}
}
}
@Test
public void testOnCreateValidationForNonWritableStorePath() throws Exception
{
if (Files.getFileAttributeView(_workDir.toPath(), PosixFileAttributeView.class) != null)
{
File file = new File(_workDir, getTestName());
file.mkdirs();
if (file.setWritable(false, false))
{
String nodeName = getTestName();
Map<String, Object> nodeData = new HashMap<>();
nodeData.put(VirtualHostNode.NAME, nodeName);
nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE);
nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath());
try
{
_broker.createChild(VirtualHostNode.class, nodeData);
fail("Cannot create store for the non writable store path");
}
catch (IllegalConfigurationException e)
{
// pass
}
}
}
}
public static void assertFilePermissions(Path testRoot) throws IOException {
Path file1 = testRoot.resolve(FILE_1); // mode 664
PosixFileAttributeView allAttributesFile1 =
Files.getFileAttributeView(file1, PosixFileAttributeView.class);
MatcherAssert.assertThat(
allAttributesFile1.readAttributes().permissions(),
Matchers.containsInAnyOrder(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.GROUP_READ));
Path file2 = testRoot.resolve(FILE_2); // mode 777
PosixFileAttributeView allAttributesFile2 =
Files.getFileAttributeView(file2, PosixFileAttributeView.class);
MatcherAssert.assertThat(
allAttributesFile2.readAttributes().permissions(),
Matchers.containsInAnyOrder(PosixFilePermission.values()));
}
/**
* Get POSIX attributes for file.
*
* @param file File.
* @return PosixFileAttributes.
*/
@Nullable public static PosixFileAttributes posixAttributes(File file) {
PosixFileAttributes attrs = null;
try {
PosixFileAttributeView view = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class);
if (view != null)
attrs = view.readAttributes();
}
catch (IOException e) {
throw new IgfsException("Failed to read POSIX attributes: " + file.getAbsolutePath(), e);
}
return attrs;
}
/**
* Test: File and FileStore attributes
*/
@Test
public void testFileStoreAttributes() throws URISyntaxException, IOException {
URI uri = clusterUri.resolve("/tmp/testFileStore");
Path path = Paths.get(uri);
if (Files.exists(path))
Files.delete(path);
assertFalse(Files.exists(path));
Files.createFile(path);
assertTrue(Files.exists(path));
FileStore store1 = Files.getFileStore(path);
assertNotNull(store1);
assertTrue(store1.supportsFileAttributeView("basic"));
assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("posix") == store1
.supportsFileAttributeView(PosixFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("dos") == store1
.supportsFileAttributeView(DosFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("acl") == store1
.supportsFileAttributeView(AclFileAttributeView.class));
assertTrue(store1.supportsFileAttributeView("user") == store1
.supportsFileAttributeView(UserDefinedFileAttributeView.class));
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}
@Test
public void testSetFileAttributesWhenNoAttributesSetDoesNothing() throws IOException {
Path path = mock(Path.class);
PosixFileAttributeView posixFileAttributeView = mockPosixFileAttributeView(path, false);
FileUtils.setFileAttributes(path, new byte[4]);
verifyZeroInteractions(posixFileAttributeView);
}
private PosixFileAttributeView mockPosixFileAttributeView(Path path, boolean isDirectory) throws IOException {
FileSystemProvider fileSystemProvider = mock(FileSystemProvider.class);
FileSystem fileSystem = mock(FileSystem.class);
PosixFileAttributeView posixFileAttributeView = mock(PosixFileAttributeView.class);
when(path.getFileSystem()).thenReturn(fileSystem);
when(fileSystemProvider.getFileAttributeView(path, PosixFileAttributeView.class)).thenReturn(posixFileAttributeView);
when(fileSystemProvider.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS))
.thenReturn(posixFileAttributeView);
when(path.getFileSystem().provider()).thenReturn(fileSystemProvider);
mockRegularFileOrDirectory(fileSystemProvider, path, isDirectory);
return posixFileAttributeView;
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}
@Override
public PosixFileAttributeView view(
FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) {
return new View(
lookup,
(BasicFileAttributeView) inheritedViews.get("basic"),
(FileOwnerAttributeView) inheritedViews.get("owner"));
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (fixLib && Files.getFileAttributeView(file, PosixFileAttributeView.class) != null)
Files.setPosixFilePermissions(file, DPERMS);
if (file.toFile().getName().endsWith(".jar"))
inst.appendToSystemClassLoaderSearch(new JarFile(file.toFile()));
return super.visitFile(file, attrs);
}
private static void verifyFile(File repo, int staticPerm) throws IOException {
String fileName = String.format("git-%03o.txt", staticPerm);
File file = new File(repo, fileName);
assertTrue("Missing " + file.getAbsolutePath(), file.exists());
String content = FileUtils.readFileToString(file, "UTF-8");
assertTrue(fileName + " wrong content: '" + content + "'", content.contains(fileName));
String rwx = permString(staticPerm);
Set<PosixFilePermission> expected = PosixFilePermissions.fromString(rwx);
Path path = FileSystems.getDefault().getPath(file.getPath());
PosixFileAttributes attrs = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes();
assertEquals(fileName + " OWNER_EXECUTE (execute) perm mismatch, expected: " + expected + ", was actually: " + attrs.permissions(),
expected.contains(PosixFilePermission.OWNER_EXECUTE),
attrs.permissions().contains(PosixFilePermission.OWNER_EXECUTE)
);
}
/**
* Display the permissions for the specified Zip file when {@code DEBUG}
* is set to {@code true}
*
* @param msg String to include in the message
* @param zipFile Path to the Zip File
* @throws IOException If an error occurs obtaining the permissions
*/
public void displayPermissions(String msg, Path zipFile) throws IOException {
if (DEBUG) {
PosixFileAttributeView view = Files.getFileAttributeView(zipFile,
PosixFileAttributeView.class);
if (view == null) {
System.out.println("Could not obtain a PosixFileAttributeView!");
return;
}
PosixFileAttributes attrs = view.readAttributes();
System.out.printf("%s: %s, Owner: %s, Group:%s, permissions: %s%n", msg,
zipFile.getFileName(), attrs.owner().getName(),
attrs.group().getName(), PosixFilePermissions.toString(attrs.permissions()));
}
}
/**
* Returns a file's POSIX file attributes.
*
* @param path The path to the Zip file
* @return The POSIX file attributes for the specified file or
* null if the POSIX attribute view is not available
* @throws IOException If an error occurs obtaining the POSIX attributes for
* the specified file
*/
public PosixFileAttributes getPosixAttributes(Path path) throws IOException {
PosixFileAttributes attrs = null;
PosixFileAttributeView view =
Files.getFileAttributeView(path, PosixFileAttributeView.class);
// Return if the attribute view is not supported
if (view == null) {
return null;
}
attrs = view.readAttributes();
return attrs;
}
@Test
public void testView() throws IOException {
file.setAttribute("owner", "owner", createUserPrincipal("user"));
PosixFileAttributeView view =
provider.view(
fileLookup(),
ImmutableMap.of(
"basic", new BasicAttributeProvider().view(fileLookup(), NO_INHERITED_VIEWS),
"owner", new OwnerAttributeProvider().view(fileLookup(), NO_INHERITED_VIEWS)));
assertNotNull(view);
assertThat(view.name()).isEqualTo("posix");
assertThat(view.getOwner()).isEqualTo(createUserPrincipal("user"));
PosixFileAttributes attrs = view.readAttributes();
assertThat(attrs.fileKey()).isEqualTo(0);
assertThat(attrs.owner()).isEqualTo(createUserPrincipal("user"));
assertThat(attrs.group()).isEqualTo(createGroupPrincipal("group"));
assertThat(attrs.permissions()).isEqualTo(PosixFilePermissions.fromString("rw-r--r--"));
view.setOwner(createUserPrincipal("root"));
assertThat(view.getOwner()).isEqualTo(createUserPrincipal("root"));
assertThat(file.getAttribute("owner", "owner")).isEqualTo(createUserPrincipal("root"));
view.setGroup(createGroupPrincipal("root"));
assertThat(view.readAttributes().group()).isEqualTo(createGroupPrincipal("root"));
assertThat(file.getAttribute("posix", "group")).isEqualTo(createGroupPrincipal("root"));
view.setPermissions(PosixFilePermissions.fromString("rwx------"));
assertThat(view.readAttributes().permissions())
.isEqualTo(PosixFilePermissions.fromString("rwx------"));
assertThat(file.getAttribute("posix", "permissions"))
.isEqualTo(PosixFilePermissions.fromString("rwx------"));
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}
@Override
public void setUnixGroup(final Path file, final String group) throws BackgroundException {
try {
final GroupPrincipal principal = session.getClient().getUserPrincipalLookupService().lookupPrincipalByGroupName(group);
Files.getFileAttributeView(session.toPath(file),
PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(principal);
}
catch(IOException e) {
throw new LocalExceptionMappingService().map("Failure to write attributes of {0}", e, file);
}
}
@Override
@SuppressWarnings("unchecked")
public <V extends FileAttributeView> V getFileAttributeView( Path path, Class<V> type, LinkOption... linkOptions ) {
if ( type == BasicFileAttributeView.class ) {
return (V)getFileAttributeView( path, "basic", linkOptions );
}
if ( type == PosixFileAttributeView.class ) {
return (V)getFileAttributeView( path, "posix", linkOptions );
}
if ( type == null ) {
throw new NullPointerException();
}
return (V)null;
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}
static final String getFileAttributes(File file) {
try {
PosixFileAttributes attrs = Files.getFileAttributeView(
file.toPath(), PosixFileAttributeView.class, new LinkOption[0]).readAttributes();
String s = String.format("%s: %s %s %s%n",
file.getPath(),
attrs.owner().getName(),
attrs.group().getName(),
PosixFilePermissions.toString(attrs.permissions()));
return s;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public boolean isPosixFileSystem(Path path) throws IOException
{
while (!Files.exists(path))
{
path = path.getParent();
if (path == null)
{
return false;
}
}
return Files.getFileAttributeView(path, PosixFileAttributeView.class) != null;
}
@Test
public void testCreateNewFile() throws Exception
{
assertFalse("File should not exist", _testFile.exists());
Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS);
assertTrue("File was not created", path.toFile().exists());
if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null)
{
assertPermissions(path);
}
}
@Test
public void testCreateNewFileUsingRelativePath() throws Exception
{
_testFile = new File("./tmp-" + System.currentTimeMillis());
assertFalse("File should not exist", _testFile.exists());
Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS);
assertTrue("File was not created", path.toFile().exists());
if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null)
{
assertPermissions(path);
}
}
@Test
public void testGetFileAttributeView_isNullForUnsupportedView() {
final File file = Directory.create(0);
FileLookup fileLookup =
new FileLookup() {
@Override
public File lookup() throws IOException {
return file;
}
};
assertThat(service.getFileAttributeView(fileLookup, PosixFileAttributeView.class)).isNull();
}
private static List<FileAttribute<Set<PosixFilePermission>>> getPosixAttributes(Path file) throws IOException {
if (Files.exists(file) && supportsFileOwnerAttributeView(file, PosixFileAttributeView.class)) {
PosixFileAttributeView posixView = Files.getFileAttributeView(file, PosixFileAttributeView.class);
if (posixView != null) {
return Collections.singletonList(PosixFilePermissions.asFileAttribute(posixView.readAttributes().permissions()));
}
}
return Collections.emptyList();
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}
@Test
public void testDumpDirNotWritable() throws IOException {
if (! Files.getFileStore(Paths.get("."))
.supportsFileAttributeView(PosixFileAttributeView.class)) {
// No easy way to setup readonly directory without POSIX
// We would like to skip the test with a cause with
// throw new SkipException("Posix not supported");
// but jtreg will report failure so we just pass the test
// which we can look at if jtreg changed its behavior
return;
}
Files.createDirectory(Paths.get("readOnly"),
asFileAttribute(fromString("r-xr-xr-x")));
TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
"-cp", ".",
"-Djdk.internal.lambda.dumpProxyClasses=readOnly",
"-Djava.security.manager",
"com.example.TestLambda");
assertEquals(tr.testOutput.stream()
.filter(s -> s.startsWith("WARNING"))
.peek(s -> assertTrue(s.contains("not writable")))
.count(),
1, "only show error once");
tr.assertZero("Should still return 0");
TestUtil.removeAll(Paths.get("readOnly"));
}