java.nio.file.attribute.PosixFilePermission Java Examples

The following examples show how to use java.nio.file.attribute.PosixFilePermission. 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: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 7 votes vote down vote up
@Test
public void testCreateDirectory_withInitialAttributes() throws IOException {
  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));

  Files.createDirectory(path("/foo"), permissions);

  assertThatPath("/foo")
      .isDirectory()
      .and()
      .attribute("posix:permissions")
      .is(permissions.value());

  Files.createDirectory(path("/normal"));

  assertThatPath("/normal")
      .isDirectory()
      .and()
      .attribute("posix:permissions")
      .isNot(permissions.value());
}
 
Example #2
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSymbolicLink_withInitialAttributes() throws IOException {
  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));

  Files.createSymbolicLink(path("/foo"), path("bar"), permissions);

  assertThatPath("/foo", NOFOLLOW_LINKS)
      .isSymbolicLink()
      .and()
      .attribute("posix:permissions")
      .is(permissions.value());

  Files.createSymbolicLink(path("/normal"), path("bar"));

  assertThatPath("/normal", NOFOLLOW_LINKS)
      .isSymbolicLink()
      .and()
      .attribute("posix:permissions")
      .isNot(permissions.value());
}
 
Example #3
Source File: DebuggersRegistry.java    From aCute with Eclipse Public License 2.0 6 votes vote down vote up
public static DebuggerInfo getDefaultDebugger() {
	URL netcoredbgUrl = FileLocator.find(AcutePlugin.getDefault().getBundle(), new Path("netcoredbg")); //$NON-NLS-1$
	if (netcoredbgUrl != null) {
		try {
			netcoredbgUrl = FileLocator.toFileURL(netcoredbgUrl);
			File dbgDir = new File(netcoredbgUrl.toURI().normalize()).getAbsoluteFile();
			if (!dbgDir.canExecute() && dbgDir.canExecute()) {
				Files.setPosixFilePermissions(dbgDir.toPath(), Collections.singleton(PosixFilePermission.OWNER_EXECUTE));
			}
			return new DebuggerInfo(new File(dbgDir,Platform.OS_WIN32.equals(Platform.getOS()) ? "netcoredbg.exe" : "netcoredbg"), Collections.singletonList("--interpreter=vscode")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		} catch (IOException | URISyntaxException ex) {
			AcutePlugin.logError(ex);
		}
	}
	return new DebuggerInfo(new File("/home/mistria/apps/netcoredbg-linux-master/netcoredbg/netcoredbg"), Collections.singletonList("--interpreter=vscode")); //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example #4
Source File: FileSystemUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean clonePermissions(@Nonnull String source, @Nonnull String target, boolean execOnly) throws IOException {
  if (!SystemInfo.isUnix) return false;

  Path sourcePath = Paths.get(source), targetPath = Paths.get(target);
  Set<PosixFilePermission> sourcePermissions = Files.readAttributes(sourcePath, PosixFileAttributes.class).permissions();
  Set<PosixFilePermission> targetPermissions = Files.readAttributes(targetPath, PosixFileAttributes.class).permissions();
  Set<PosixFilePermission> newPermissions;
  if (execOnly) {
    newPermissions = EnumSet.copyOf(targetPermissions);
    for (PosixFilePermission permission : myExecPermissions) {
      if (sourcePermissions.contains(permission)) {
        newPermissions.add(permission);
      }
      else {
        newPermissions.remove(permission);
      }
    }
  }
  else {
    newPermissions = sourcePermissions;
  }
  Files.setAttribute(targetPath, "posix:permissions", newPermissions);
  return true;
}
 
Example #5
Source File: HgOriginTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testHgOriginWithHook() throws Exception {
  Files.write(remotePath.resolve("foo.txt"), "hello".getBytes(UTF_8));
  Files.write(remotePath.resolve("bar.txt"), "hello".getBytes(UTF_8));

  repository.hg(remotePath, "add", "foo.txt");
  repository.hg(remotePath, "add", "bar.txt");
  repository.hg(remotePath, "commit", "-m", "foo");

  Path hook = Files.createTempFile("script", "script");
  Files.write(hook, "touch hook.txt".getBytes(UTF_8));

  Files.setPosixFilePermissions(
      hook,
      ImmutableSet.<PosixFilePermission>builder()
          .addAll(Files.getPosixFilePermissions(hook))
          .add(PosixFilePermission.OWNER_EXECUTE)
          .build());

  options.hgOrigin.originCheckoutHook = hook.toString();
  origin = origin();

  Path checkoutDir = Files.createTempDirectory("checkout");
  newReader().checkout(origin.resolve("tip"), checkoutDir);
  assertThatPath(checkoutDir).containsFile("hook.txt", "");
}
 
Example #6
Source File: FileUtilTest.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyDirectory_posixPermissions() throws IOException {
  assumeTrue(!System.getProperty("os.name").startsWith("Windows"));

  Set<PosixFilePermission> permission = Sets.newHashSet();
  permission.add(PosixFilePermission.OWNER_READ);
  permission.add(PosixFilePermission.GROUP_READ);
  permission.add(PosixFilePermission.OTHERS_READ);
  permission.add(PosixFilePermission.OTHERS_EXECUTE);
  permission.add(PosixFilePermission.OTHERS_WRITE);

  Path src = testDir.newFolder("src").toPath();
  Path dest = testDir.newFolder("dest").toPath();

  Path rootFile = Files.createFile(src.resolve("root1.file"));
  Assert.assertNotEquals(
      "This test is useless - modified permissions are default permissions",
      Files.getPosixFilePermissions(rootFile),
      permission);
  Files.setPosixFilePermissions(rootFile, permission);

  FileUtil.copyDirectory(src, dest);

  Assert.assertEquals(
      permission, Files.getPosixFilePermissions(dest.resolve(src.relativize(rootFile))));
}
 
Example #7
Source File: FileSystemStorage.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void writeFile(final String content, final Path file, boolean writeTempFileFirst, Set<PosixFilePermission> permissions)
    throws IOException {
  FsPermission fsPermission;
  if (permissions == null || permissions.isEmpty()) {
    fsPermission = FsPermission.getFileDefault();
  } else {
    // FsPermission expects a 10-character string because of the leading
    // directory indicator, i.e. "drwx------". The JDK toString method returns
    // a 9-character string, so prepend a leading character.
    fsPermission = FsPermission.valueOf("-" + PosixFilePermissions.toString(permissions));
  }
  callHdfsOperation(new HdfsOperation<Void>() {
    @Override
    public Void call() throws IOException {
      InputStream in = new ByteArrayInputStream(content.getBytes(
          zConf.getString(ZeppelinConfiguration.ConfVars.ZEPPELIN_ENCODING)));
      Path tmpFile = new Path(file.toString() + ".tmp");
      IOUtils.copyBytes(in, fs.create(tmpFile), hadoopConf);
      fs.setPermission(tmpFile, fsPermission);
      fs.delete(file, true);
      fs.rename(tmpFile, file);
      return null;
    }
  });
}
 
Example #8
Source File: TestStandalonePipelineManager.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private static void testKafkaKeytabHelper(String keytabDirStr) throws Exception {
  assertThat(keytabDirStr, not(equalTo(INVALID_KEYTAB_DIR)));
  final Path keytabDir = Paths.get(keytabDirStr);
  assertTrue(Files.exists(keytabDir));
  assertTrue(Files.isDirectory(keytabDir));

  // kafka-keytabs dir should be globally writeable at this point
  final Path kafkaKeytabsDir = keytabDir.resolve(StandaloneAndClusterPipelineManager.KAFKA_KEYTAB_DIR);
  assertTrue(Files.exists(kafkaKeytabsDir));
  assertTrue(Files.isDirectory(kafkaKeytabsDir));
  final Set<PosixFilePermission> topLevelPerms = Files.getPosixFilePermissions(kafkaKeytabsDir);
  assertThat(topLevelPerms, equalTo(StandaloneAndClusterPipelineManager.GLOBAL_ALL_PERM));

  // current user level subdirectory should be restricted to user only
  final Path userLevelDir = kafkaKeytabsDir.resolve(System.getProperty("user.name"));
  assertTrue(Files.exists(userLevelDir));
  assertTrue(Files.isDirectory(userLevelDir));
  final Set<PosixFilePermission> userLevelPerms = Files.getPosixFilePermissions(userLevelDir);
  assertThat(userLevelPerms, equalTo(StandaloneAndClusterPipelineManager.USER_ONLY_PERM));

}
 
Example #9
Source File: TestDataStore.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistingPermission() throws IOException {
  File file = new File(createTestDir(), "x");
  Set<PosixFilePermission> perms = ImmutableSet.of(
      PosixFilePermission.OWNER_READ,
      PosixFilePermission.OWNER_WRITE,
      PosixFilePermission.GROUP_READ
  );
  FileAttribute attribute = PosixFilePermissions.asFileAttribute(perms);
  Files.createFile(file.toPath(), attribute);

  DataStore ds = new DataStore(file);
  try {
    OutputStream outputStream = ds.getOutputStream();
    ds.commit(outputStream);
    ds.release();
  } finally {
    ds.close();
  }
  Set<PosixFilePermission> gotPerms = Files.getPosixFilePermissions(file.toPath());
  Assert.assertEquals(perms, gotPerms);
}
 
Example #10
Source File: FileUtil.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to add the Posix permissions if the file belongs to a Posix filesystem. This is an
 * addition, which means that no permissions are removed.
 *
 * <p>For Windows type filesystems, it uses setReadable/setWritable/setExecutable, which is only
 * supported for the owner, and ignores the rest of permissions.
 */
public static void addPermissions(Path path, Set<PosixFilePermission> permissionsToAdd)
    throws IOException {
  if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path);
    permissions.addAll(permissionsToAdd);
    Files.setPosixFilePermissions(path, permissions);
  } else {
    File file = path.toFile();
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_READ)) {
      if (!file.setReadable(true)) {
        throw new IOException("Could not set 'readable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_WRITE)) {
      if (!file.setWritable(true)) {
        throw new IOException("Could not set 'writable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_EXECUTE)) {
      if (!file.setExecutable(true)) {
        throw new IOException("Could not set 'executable' permission for file: " + path);
      }
    }
  }
}
 
Example #11
Source File: TestRuntimeEL.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadResourceRestrictedSuccess() throws Exception {
  Path fooFile = Paths.get(resourcesDir.getPath(), "foo.txt");
  Files.write(fooFile, "Hello\n".getBytes(StandardCharsets.UTF_8));
  Files.setPosixFilePermissions(fooFile, ImmutableSet.of(
      PosixFilePermission.OWNER_READ,
      PosixFilePermission.OWNER_WRITE)
  );

  RuntimeEL.loadRuntimeConfiguration(runtimeInfo);

  try {
    RuntimeEL.loadResourceRaw("foo.txt", true);
  } finally {
    Files.deleteIfExists(fooFile);
  }
}
 
Example #12
Source File: FolderOriginTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Test
public void testChangesFilePermissions() throws Exception {
  Path localFolder = Files.createTempDirectory("local_folder");
  Path regularFile = localFolder.resolve("foo/regular_file");
  Path cannotWrite = localFolder.resolve("foo/file_cannot_write");
  Path executableCannotWrite = localFolder.resolve("foo/executable_cannot_write");
  touch(regularFile, "one");
  touch(cannotWrite, "two");
  touch(executableCannotWrite, "three");

  // Regular file already has [GROUP_READ, OWNER_WRITE, OWNER_READ, OTHERS_READ]
  // Removing write permissions from the second file
  Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(cannotWrite);
  permissions.removeAll(ImmutableSet.of(OWNER_WRITE, GROUP_WRITE, OTHERS_WRITE));
  Files.setPosixFilePermissions(cannotWrite, permissions);
  // Setting executable and removing write for third one
  Set<PosixFilePermission> secondPermissions =
      Files.getPosixFilePermissions(executableCannotWrite);
  secondPermissions.removeAll(ImmutableSet.of(OWNER_WRITE, GROUP_WRITE, OTHERS_WRITE));
  secondPermissions.add(OWNER_EXECUTE);
  Files.setPosixFilePermissions(executableCannotWrite, secondPermissions);

  FolderOrigin origin = skylark.eval("f", "f = folder.origin()");

  Reader<FolderRevision> reader = origin.newReader(Glob.ALL_FILES, authoring);
  FolderRevision ref = origin.resolve(localFolder.toString());
  reader.checkout(ref, workdir);
  assertThatPath(workdir)
      .containsFile("foo/regular_file","one")
      .containsFile("foo/file_cannot_write","two")
      .containsFile("foo/executable_cannot_write","three")
      .containsNoMoreFiles();
  Path cannotWriteDestination = workdir.resolve("foo/file_cannot_write");
  assertThat(Files.getPosixFilePermissions(cannotWriteDestination))
      .containsAtLeast(OWNER_READ, OWNER_WRITE);
  Path executableCannotWriteDestination = workdir.resolve("foo/executable_cannot_write");
  assertThat(Files.getPosixFilePermissions(executableCannotWriteDestination))
      .containsAtLeast(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
}
 
Example #13
Source File: CustomLauncherTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example #14
Source File: StandardFSCossEndpoint.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public void setBucketAcl(String bucketName, ACL acl) {
	File bucketPath = config.getBucketPath(bucketName);
	Set<PosixFilePermission> posixPermissions = getAclPosixPermissions(acl);
	try {
		Files.setPosixFilePermissions(Paths.get(bucketPath.getAbsolutePath()), posixPermissions);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #15
Source File: PosixAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // only cast after checking each element's type
private static ImmutableSet<PosixFilePermission> toPermissions(Set<?> set) {
  ImmutableSet<?> copy = ImmutableSet.copyOf(set);
  for (Object obj : copy) {
    if (!(obj instanceof PosixFilePermission)) {
      throw new IllegalArgumentException(
          "invalid element for attribute 'posix:permissions': "
              + "should be Set<PosixFilePermission>, found element of type "
              + obj.getClass());
    }
  }

  return Sets.immutableEnumSet((ImmutableSet<PosixFilePermission>) copy);
}
 
Example #16
Source File: DflCache.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void makeMine(Path p) throws IOException {
    // chmod to owner-rw only, otherwise MIT krb5 rejects
    try {
        Set<PosixFilePermission> attrs = new HashSet<>();
        attrs.add(PosixFilePermission.OWNER_READ);
        attrs.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(p, attrs);
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permission. That's OK.
    }
}
 
Example #17
Source File: FilesDelegateTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void setPosixFilePermissions() throws IOException {
    Path somefile = Files.createTempFile("setPosixFilePermissions", ".txt");
    somefile.toFile().deleteOnExit();
    Set<PosixFilePermission> perms = Stream.of(PosixFilePermission.values()).collect(Collectors.toSet());

    Path result = filesDelegate.setPosixFilePermissions(somefile, perms);
    assertThat(Files.getPosixFilePermissions(result)).containsAll(perms);
}
 
Example #18
Source File: DflCache.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void makeMine(Path p) throws IOException {
    // chmod to owner-rw only, otherwise MIT krb5 rejects
    try {
        Set<PosixFilePermission> attrs = new HashSet<>();
        attrs.add(PosixFilePermission.OWNER_READ);
        attrs.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(p, attrs);
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permission. That's OK.
    }
}
 
Example #19
Source File: DflCache.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void makeMine(Path p) throws IOException {
    // chmod to owner-rw only, otherwise MIT krb5 rejects
    try {
        Set<PosixFilePermission> attrs = new HashSet<>();
        attrs.add(PosixFilePermission.OWNER_READ);
        attrs.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(p, attrs);
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permission. That's OK.
    }
}
 
Example #20
Source File: AbstractFilePermissionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test 1 - SSL config file is secure - VM should start
 */
private void test2() throws Exception {
    final Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file2PermissionTest);
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);
    Files.setPosixFilePermissions(file2PermissionTest, perms);

    if (doTest() == 0) {
        ++failures;
    }
}
 
Example #21
Source File: DefaultImageBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * chmod ugo+x file
 */
private void setExecutable(Path file) {
    try {
        Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        perms.add(PosixFilePermission.OTHERS_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}
 
Example #22
Source File: PosixUtil.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
/** Convert integer mode to {@link PosixFilePermission} object. */
static Set<PosixFilePermission> getPosixFilePermissions(int mode) {
  Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class);

  if ((mode & 0400) != 0) {
    result.add(PosixFilePermission.OWNER_READ);
  }
  if ((mode & 0200) != 0) {
    result.add(PosixFilePermission.OWNER_WRITE);
  }
  if ((mode & 0100) != 0) {
    result.add(PosixFilePermission.OWNER_EXECUTE);
  }
  if ((mode & 040) != 0) {
    result.add(PosixFilePermission.GROUP_READ);
  }
  if ((mode & 020) != 0) {
    result.add(PosixFilePermission.GROUP_WRITE);
  }
  if ((mode & 010) != 0) {
    result.add(PosixFilePermission.GROUP_EXECUTE);
  }
  if ((mode & 04) != 0) {
    result.add(PosixFilePermission.OTHERS_READ);
  }
  if ((mode & 02) != 0) {
    result.add(PosixFilePermission.OTHERS_WRITE);
  }
  if ((mode & 01) != 0) {
    result.add(PosixFilePermission.OTHERS_EXECUTE);
  }
  return result;
}
 
Example #23
Source File: FullAccessOutFile.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void closeFile() {
    outFile.close();
    File f=new File(name);
    TreeSet<PosixFilePermission> perms=new TreeSet<>();
    for(PosixFilePermission p:PosixFilePermission.values())
    perms.add(p);
    Path path=f.toPath();
    try{
        Files.setPosixFilePermissions(path, perms);
    }catch(Exception e){
        System.out.println("UNABLE TO CHANGE PERMISSIONS FOR FILE "+name);
    }

}
 
Example #24
Source File: LinkerTest.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private static void assertReadOnly(Path file) throws IOException {
    if (Constants.OS.isPosix()) {
        Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
        assertThat(file.toString(), perms, is(Set.of(PosixFilePermission.OWNER_READ,
                                                     PosixFilePermission.OWNER_WRITE,
                                                     PosixFilePermission.GROUP_READ,
                                                     PosixFilePermission.OTHERS_READ)));
    }
}
 
Example #25
Source File: IOUtils.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
public static void createPrivateDirectories(String directoryPath) throws IOException {
    final File file = new File(directoryPath);
    if (file.exists()) {
        return;
    }

    final Path path = file.toPath();
    try {
        Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE);
        Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));
    } catch (UnsupportedOperationException e) {
        Files.createDirectories(path);
    }
}
 
Example #26
Source File: PosixFileAttributesTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getPermissionOfFile_shouldContainOwnerRead() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  PosixFileAttributes attributes = readPosixAttributes("/file.txt");
  Collection permissions = (Collection) attributes.permissions();
  assertTrue(permissions.contains(PosixFilePermission.OWNER_READ));
}
 
Example #27
Source File: ValidFileWritableTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void notWritable() throws IOException {
  final FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(EnumSet.of(
      PosixFilePermission.OWNER_READ
  ));
  final Path path = createTempFile(attr);

  assertThrows(ConfigException.class, () -> {
    this.validator.ensureValid("testing", path.toString());
  });
}
 
Example #28
Source File: TestTaskTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testTempDirIsWorldReadable() throws IOException {
    File tempDir = TestTask.getTempDir();
    Set<PosixFilePermission> perms = Files.getPosixFilePermissions(tempDir.toPath());
    Assert.assertTrue(perms.contains(PosixFilePermission.OTHERS_READ));
    Assert.assertTrue(perms.contains(PosixFilePermission.OTHERS_EXECUTE));
    Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_READ));
    Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_EXECUTE));
    Assert.assertTrue(perms.contains(PosixFilePermission.OWNER_WRITE));
    tempDir.delete();
}
 
Example #29
Source File: FileUtils.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
public static void setPermissionsToOwnerOnly(File file) {
    if (file == null) {
        return;
    }
    try {
        Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(file.toPath(), perms);
    }
    catch (Exception e) {
        // On some file systems we might get an exception attempting to set permissions
        // Just ignore it
    }
}
 
Example #30
Source File: RunNiFiRegistry.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private synchronized void savePidProperties(final Properties pidProperties, final Logger logger) throws IOException {
    final String pid = pidProperties.getProperty(PID_KEY);
    if (!StringUtils.isBlank(pid)) {
        writePidFile(pid, logger);
    }

    final File statusFile = getStatusFile(logger);
    if (statusFile.exists() && !statusFile.delete()) {
        logger.warn("Failed to delete {}", statusFile);
    }

    if (!statusFile.createNewFile()) {
        throw new IOException("Failed to create file " + statusFile);
    }

    try {
        final Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(statusFile.toPath(), perms);
    } catch (final Exception e) {
        logger.warn("Failed to set permissions so that only the owner can read status file {}; "
                + "this may allows others to have access to the key needed to communicate with NiFi Registry. "
                + "Permissions should be changed so that only the owner can read this file", statusFile);
    }

    try (final FileOutputStream fos = new FileOutputStream(statusFile)) {
        pidProperties.store(fos, null);
        fos.getFD().sync();
    }

    logger.debug("Saved Properties {} to {}", new Object[]{pidProperties, statusFile});
}