java.nio.file.attribute.PosixFileAttributeView Java Examples

The following examples show how to use java.nio.file.attribute.PosixFileAttributeView. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DerbyVirtualHostNodeTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@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
            }
        }
    }
}
 
Example #2
Source File: LocalFileSystemUtils.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: FileUtils.java    From zip4j with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: LocalFileSystem.java    From xenon with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #5
Source File: FileUtilsTestLinuxAndMac.java    From zip4j with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #6
Source File: GenericArchivesVerifier.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
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()));
}
 
Example #7
Source File: ScopedTemporaryDirectory.java    From bazel with Apache License 2.0 6 votes vote down vote up
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));
    }
  }
}
 
Example #8
Source File: TestFileStore.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #9
Source File: FilesGetAttributeViewTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getPosixFileAttributeViewFromFile_shouldBeNotNull() throws IOException {
  initRepository();
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();
  assertNotNull(Files.getFileAttributeView(gfs.getPath("/file.txt"), PosixFileAttributeView.class));
}
 
Example #10
Source File: IgfsLocalSecondaryFileSystemTestAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Map<String, String> properties(final String path) throws IOException {
    Path p = path(path);
    PosixFileAttributes attrs = Files.getFileAttributeView(p, PosixFileAttributeView.class).readAttributes();

    Map<String, String> props = new HashMap<>();
    props.put(IgfsUtils.PROP_USER_NAME, attrs.owner().getName());
    props.put(IgfsUtils.PROP_GROUP_NAME, attrs.group().getName());
    props.put(IgfsUtils.PROP_PERMISSION, permissions(path));

    return props;
}
 
Example #11
Source File: UnixPath.java    From vespa with Apache License 2.0 5 votes vote down vote up
public UnixPath setGroup(String group) {
    UserPrincipalLookupService service = path.getFileSystem().getUserPrincipalLookupService();
    GroupPrincipal principal = uncheck(
            () -> service.lookupPrincipalByGroupName(group),
            "while looking up group %s", group);
    uncheck(() -> Files.getFileAttributeView(path, PosixFileAttributeView.class).setGroup(principal));
    return this;
}
 
Example #12
Source File: FileInfo.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void addDetails() throws IOException {
    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
        Path path = Paths.get(this.path);
        PosixFileAttributes attrs = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes();
        permissions = PosixFilePermissions.toString(attrs.permissions());
        UserPrincipal ownerPrincipal = attrs.owner();
        owner = ownerPrincipal.toString();
        UserPrincipal groupPrincipal = attrs.group();
        group = groupPrincipal.toString();
    }
}
 
Example #13
Source File: Dir.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void addDetails() throws IOException {
    Path path = Paths.get(this.path);
    this.absolutePath = path.toAbsolutePath().toString().replace('\\', '/');
    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
        PosixFileAttributes attrs = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes();
        permissions = PosixFilePermissions.toString(attrs.permissions());
        UserPrincipal ownerPrincipal = attrs.owner();
        owner = ownerPrincipal.toString();
        UserPrincipal groupPrincipal = attrs.group();
        group = groupPrincipal.toString();
        size = path.toFile().length();
        numLinks = path.toFile().list().length + 2;
    }
}
 
Example #14
Source File: IgfsLocalSecondaryFileSystemTestAdapter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public String permissions(String path) throws IOException {
    Path p = path(path);
    PosixFileAttributeView attrView = Files.getFileAttributeView(p, PosixFileAttributeView.class);

    if (attrView == null)
        throw new UnsupportedOperationException("Posix file attributes not available");

    int perm = 0;
    for (PosixFilePermission pfp : attrView.readAttributes().permissions())
        perm |= (1 << 8 - pfp.ordinal());

    return '0' + Integer.toOctalString(perm);
}
 
Example #15
Source File: SFTPFileSystemProvider.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a file attribute view of a given type.
 * This method works in exactly the manner specified by the {@link Files#getFileAttributeView(Path, Class, LinkOption...)} method.
 * <p>
 * This provider supports {@link BasicFileAttributeView}, {@link FileOwnerAttributeView} and {@link PosixFileAttributeView}.
 * All other classes will result in a {@code null} return value.
 * <p>
 * Note: if the type is {@link BasicFileAttributeView} or a sub type, the last access time and creation time must be {@code null} when calling
 * {@link BasicFileAttributeView#setTimes(FileTime, FileTime, FileTime)}, otherwise an exception will be thrown.
 * When setting the owner or group for the path, the name must be the UID/GID of the owner/group.
 */
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
    Objects.requireNonNull(type);
    if (type == BasicFileAttributeView.class) {
        return type.cast(new AttributeView("basic", toSFTPPath(path))); //$NON-NLS-1$
    }
    if (type == FileOwnerAttributeView.class) {
        return type.cast(new AttributeView("owner", toSFTPPath(path))); //$NON-NLS-1$
    }
    if (type == PosixFileAttributeView.class) {
        return type.cast(new AttributeView("posix", toSFTPPath(path))); //$NON-NLS-1$
    }
    return null;
}
 
Example #16
Source File: TestFiles.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void getFileAttributeViewPosixFileAttributeView() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  Path path = Files.createTempFile(rootPath, "test", "tmp");
  PosixFileAttributeView view = Files.getFileAttributeView(path,
      PosixFileAttributeView.class);
  Assert.assertNotNull(view);
  Assert.assertEquals("posix", view.name());

  PosixFileAttributes attributes;
  attributes = view.readAttributes();
  Assert.assertNotNull(attributes.group());
  Assert.assertNotNull(attributes.group().getName());
  Assert.assertNotNull(attributes.fileKey());
}
 
Example #17
Source File: LocalFileSystem.java    From simple-nfs with Apache License 2.0 5 votes vote down vote up
private Stat statPath(Path p, long inodeNumber) throws IOException {

        Class<? extends  BasicFileAttributeView> attributeClass =
                IS_UNIX ? PosixFileAttributeView.class : DosFileAttributeView.class;

        BasicFileAttributes attrs = Files.getFileAttributeView(p, attributeClass, NOFOLLOW_LINKS).readAttributes();

        Stat stat = new Stat();

        stat.setATime(attrs.lastAccessTime().toMillis());
        stat.setCTime(attrs.creationTime().toMillis());
        stat.setMTime(attrs.lastModifiedTime().toMillis());

        if (IS_UNIX) {
            stat.setGid((Integer) Files.getAttribute(p, "unix:gid", NOFOLLOW_LINKS));
            stat.setUid((Integer) Files.getAttribute(p, "unix:uid", NOFOLLOW_LINKS));
            stat.setMode((Integer) Files.getAttribute(p, "unix:mode", NOFOLLOW_LINKS));
            stat.setNlink((Integer) Files.getAttribute(p, "unix:nlink", NOFOLLOW_LINKS));
        } else {
            DosFileAttributes dosAttrs = (DosFileAttributes)attrs;
            stat.setGid(0);
            stat.setUid(0);
            int type = dosAttrs.isSymbolicLink() ? Stat.S_IFLNK : dosAttrs.isDirectory() ? Stat.S_IFDIR : Stat.S_IFREG;
            stat.setMode( type |(dosAttrs.isReadOnly()? 0400 : 0600));
            stat.setNlink(1);
        }

        stat.setDev(17);
        stat.setIno((int) inodeNumber);
        stat.setRdev(17);
        stat.setSize(attrs.size());
        stat.setFileid((int) inodeNumber);
        stat.setGeneration(attrs.lastModifiedTime().toMillis());

        return stat;
    }
 
Example #18
Source File: LogGeneratedClassesTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #19
Source File: SFTPFileSystemProviderTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileAttributeViewPosix() throws IOException {

    SFTPFileSystemProvider provider = new SFTPFileSystemProvider();
    try (SFTPFileSystem fs = newFileSystem(provider, createEnv())) {
        SFTPPath path = new SFTPPath(fs, "/foo/bar");

        PosixFileAttributeView view = fs.provider().getFileAttributeView(path, PosixFileAttributeView.class);
        assertNotNull(view);
        assertEquals("posix", view.name());
    }
}
 
Example #20
Source File: LogGeneratedClassesTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #21
Source File: LogGeneratedClassesTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #22
Source File: ArchiveUtils.java    From gradle-golang-plugin with Mozilla Public License 2.0 5 votes vote down vote up
public static void unTarGz(Path file, Path target) throws IOException {
    try (final InputStream is = newInputStream(file)) {
        final InputStream gzip = new GZIPInputStream(is);
        final TarArchiveInputStream archive = new TarArchiveInputStream(gzip);
        TarArchiveEntry entry = archive.getNextTarEntry();
        while (entry != null) {
            final Path entryFile = target.resolve(REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).toAbsolutePath();
            if (entry.isDirectory()) {
                createDirectoriesIfRequired(entryFile);
            } else {
                ensureParentOf(entryFile);
                try (final OutputStream os = newOutputStream(entryFile)) {
                    copy(archive, os);
                }
                final PosixFileAttributeView view = getFileAttributeView(entryFile, PosixFileAttributeView.class);
                if (view != null) {
                    final int mode = entry.getMode();
                    final Set<PosixFilePermission> perms = new HashSet<>();
                    perms.add(PosixFilePermission.OWNER_READ);
                    perms.add(PosixFilePermission.GROUP_READ);
                    perms.add(PosixFilePermission.OTHERS_READ);
                    //noinspection OctalInteger,ResultOfMethodCallIgnored,IncompatibleBitwiseMaskOperation
                    if ((mode | 0001) > 0) {
                        perms.add(PosixFilePermission.OWNER_EXECUTE);
                    }
                    //noinspection OctalInteger,ResultOfMethodCallIgnored,IncompatibleBitwiseMaskOperation
                    if ((mode | 0100) > 0) {
                        perms.add(PosixFilePermission.GROUP_EXECUTE);
                        perms.add(PosixFilePermission.OTHERS_EXECUTE);
                    }
                    view.setPermissions(perms);
                }
            }
            entry = archive.getNextTarEntry();
        }
    }
}
 
Example #23
Source File: LogGeneratedClassesTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #24
Source File: LogGeneratedClassesTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #25
Source File: LogGeneratedClassesTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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"));
}
 
Example #26
Source File: FilePersistenceUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example #27
Source File: AttributeServiceTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #28
Source File: FileHelperTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #29
Source File: FileHelperTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #30
Source File: FileHelper.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
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;
}