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 Project: jimfs   Author: google   File: JimfsUnixLikeFileSystemTest.java    License: 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 Project: datacollector   Author: streamsets   File: TestDataStore.java    License: 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 #3
Source Project: jimfs   Author: google   File: JimfsUnixLikeFileSystemTest.java    License: 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 #4
Source Project: aCute   Author: eclipse   File: DebuggersRegistry.java    License: 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 #5
Source Project: copybara   Author: google   File: HgOriginTest.java    License: 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 Project: consulo   Author: consulo   File: FileSystemUtil.java    License: 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 #7
Source Project: copybara   Author: google   File: FileUtil.java    License: 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 #8
Source Project: datacollector   Author: streamsets   File: TestRuntimeEL.java    License: 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 #9
Source Project: zeppelin   Author: apache   File: FileSystemStorage.java    License: 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 #10
Source Project: appengine-plugins-core   Author: GoogleCloudPlatform   File: FileUtilTest.java    License: 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 #11
Source Project: datacollector   Author: streamsets   File: TestStandalonePipelineManager.java    License: 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 #12
Source Project: celos   Author: collectivemedia   File: TestTaskTest.java    License: 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 #13
Source Project: presto   Author: prestosql   File: TestFileSingleStreamSpillerFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDistributesSpillOverPathsBadDisk()
        throws Exception
{
    List<Type> types = ImmutableList.of(BIGINT);
    List<Path> spillPaths = ImmutableList.of(spillPath1.toPath(), spillPath2.toPath());
    FileSingleStreamSpillerFactory spillerFactory = new FileSingleStreamSpillerFactory(
            executor, // executor won't be closed, because we don't call destroy() on the spiller factory
            blockEncodingSerde,
            new SpillerStats(),
            spillPaths,
            1.0,
            false,
            false);

    assertEquals(listFiles(spillPath1.toPath()).size(), 0);
    assertEquals(listFiles(spillPath2.toPath()).size(), 0);

    // Set first spiller path to read-only after initialization to emulate a disk failing during runtime
    setPosixFilePermissions(spillPath1.toPath(), ImmutableSet.of(PosixFilePermission.OWNER_READ));

    Page page = buildPage();
    List<SingleStreamSpiller> spillers = new ArrayList<>();
    int numberOfSpills = 10;
    for (int i = 0; i < numberOfSpills; ++i) {
        SingleStreamSpiller singleStreamSpiller = spillerFactory.create(types, bytes -> {}, newSimpleAggregatedMemoryContext().newLocalMemoryContext("test"));
        getUnchecked(singleStreamSpiller.spill(page));
        spillers.add(singleStreamSpiller);
    }

    // bad disk should receive no spills, with the good disk taking the remainder
    assertEquals(listFiles(spillPath1.toPath()).size(), 0);
    assertEquals(listFiles(spillPath2.toPath()).size(), numberOfSpills);

    spillers.forEach(SingleStreamSpiller::close);
    assertEquals(listFiles(spillPath1.toPath()).size(), 0);
    assertEquals(listFiles(spillPath2.toPath()).size(), 0);
}
 
Example #14
Source Project: Flink-CEPplus   Author: ljygz   File: JarDeleteHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void makeJarDirReadOnly() {
	try {
		Files.setPosixFilePermissions(jarDir, new HashSet<>(Arrays.asList(
			PosixFilePermission.OTHERS_READ,
			PosixFilePermission.GROUP_READ,
			PosixFilePermission.OWNER_READ,
			PosixFilePermission.OTHERS_EXECUTE,
			PosixFilePermission.GROUP_EXECUTE,
			PosixFilePermission.OWNER_EXECUTE)));
	} catch (final Exception e) {
		Assume.assumeNoException(e);
	}
}
 
Example #15
Source Project: ParallelGit   Author: beijunyi   File: PosixFileAttributesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getPermissionOfFile_shouldContainOwnerWrite() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  PosixFileAttributes attributes = readPosixAttributes("/file.txt");
  Collection permissions = (Collection) attributes.permissions();
  assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE));
}
 
Example #16
Source Project: hadoop   Author: naver   File: LocalJavaKeyStoreProvider.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<PosixFilePermission> modeToPosixFilePermission(
    int mode) {
  Set<PosixFilePermission> perms = EnumSet.noneOf(PosixFilePermission.class);
  if ((mode & 0001) != 0) {
    perms.add(PosixFilePermission.OTHERS_EXECUTE);
  }
  if ((mode & 0002) != 0) {
    perms.add(PosixFilePermission.OTHERS_WRITE);
  }
  if ((mode & 0004) != 0) {
    perms.add(PosixFilePermission.OTHERS_READ);
  }
  if ((mode & 0010) != 0) {
    perms.add(PosixFilePermission.GROUP_EXECUTE);
  }
  if ((mode & 0020) != 0) {
    perms.add(PosixFilePermission.GROUP_WRITE);
  }
  if ((mode & 0040) != 0) {
    perms.add(PosixFilePermission.GROUP_READ);
  }
  if ((mode & 0100) != 0) {
    perms.add(PosixFilePermission.OWNER_EXECUTE);
  }
  if ((mode & 0200) != 0) {
    perms.add(PosixFilePermission.OWNER_WRITE);
  }
  if ((mode & 0400) != 0) {
    perms.add(PosixFilePermission.OWNER_READ);
  }
  return perms;
}
 
Example #17
Source Project: dragonwell8_jdk   Author: alibaba   File: DflCache.java    License: 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 #18
Source Project: jimfs   Author: google   File: PosixAttributeProvider.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Attributes(File file) {
  super(file);
  this.owner = (UserPrincipal) file.getAttribute("owner", "owner");
  this.group = (GroupPrincipal) file.getAttribute("posix", "group");
  this.permissions =
      (ImmutableSet<PosixFilePermission>) file.getAttribute("posix", "permissions");
}
 
Example #19
Source Project: pnc   Author: project-ncl   File: IoUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void setUnixPermissions(Path path) throws IOException {
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    if (isDirectory(path)) {
        perms.add(PosixFilePermission.OWNER_EXECUTE);
    }
    Files.setPosixFilePermissions(path, perms);
}
 
Example #20
Source Project: ParallelGit   Author: beijunyi   File: PosixFileAttributeViewTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getPermissionOfFile_shouldContainOwnerWrite() throws IOException {
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();

  GfsFileAttributeView.Posix view = provider.getFileAttributeView(gfs.getPath("/file.txt"), GfsFileAttributeView.Posix.class);
  assertNotNull(view);
  Collection permissions = (Collection) readAttribute(view, GfsFileAttributeView.Posix.PERMISSIONS_NAME);
  assertNotNull(permissions);
  assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE));
}
 
Example #21
Source Project: zip4j   Author: srikanth-lingala   File: FileUtilsTestLinuxAndMac.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyAllPermissionSet(Set<PosixFilePermission> permissions) {
  assertThat(permissions).contains(
      PosixFilePermission.OWNER_READ,
      PosixFilePermission.OWNER_WRITE,
      PosixFilePermission.OWNER_EXECUTE,
      PosixFilePermission.GROUP_READ,
      PosixFilePermission.GROUP_WRITE,
      PosixFilePermission.GROUP_EXECUTE,
      PosixFilePermission.OTHERS_READ,
      PosixFilePermission.OTHERS_WRITE,
      PosixFilePermission.OTHERS_EXECUTE
  );
}
 
Example #22
Source Project: vespa   Author: vespa-engine   File: ProcessFactoryImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSpawnWithPersistentOutputFile() {

    class TemporaryFile implements AutoCloseable {
        private final Path path;
        private TemporaryFile() {
            String outputFileName = ProcessFactoryImplTest.class.getSimpleName() + "-temporary-test-file.out";
            FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions.asFileAttribute(
                    PosixFilePermissions.fromString("rw-------"));
            path = uncheck(() -> Files.createTempFile(outputFileName, ".out", fileAttribute));
        }
        @Override public void close() { uncheck(() -> Files.deleteIfExists(path)); }
    }

    try (TemporaryFile outputPath = new TemporaryFile()) {
        CommandLine commandLine = mock(CommandLine.class);
        when(commandLine.getArguments()).thenReturn(List.of("program"));
        when(commandLine.programName()).thenReturn("program");
        when(commandLine.getOutputFile()).thenReturn(Optional.of(outputPath.path));
        try (ChildProcess2Impl child = processFactory.spawn(commandLine)) {
            assertEquals(outputPath.path, child.getOutputPath());
            assertTrue(Files.exists(outputPath.path));
            assertEquals("rw-------", new UnixPath(outputPath.path).getPermissions());
        }

        assertTrue(Files.exists(outputPath.path));
    }

}
 
Example #23
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: ZipFSPermissionsTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate that the Zip file permissions are as expected after updating the
 * Zip file
 * @param newPerms The permissions to set on the Zip File before updating the
 *                 file
 * @throws Exception If an error occurs
 */
@Test(dataProvider = "posixPermissions")
public void testZipPerms(Set<PosixFilePermission> newPerms) throws Exception {
    if (DEBUG) {
        System.out.printf("Test Run with perms= %s%n", newPerms);
    }

    PosixFileAttributes attrs = getPosixAttributes(zipFile);

    // Permissions used to verify the results of updating the Zip file
    if (newPerms == null) {
        // Use current Zip File permissions;
        newPerms = attrs.permissions();
    }
    displayPermissions("Original permissions", zipFile);

    // Now set the new permissions
    Files.setPosixFilePermissions(zipFile, newPerms);
    displayPermissions("Revised permissions", zipFile);

    // Update the Zip file
    zip(zipFile, Collections.emptyMap(), entry1);

    // Validate that the permissions are as expected after updating the
    // Zip file
    PosixFileAttributes afterAttrs = getPosixAttributes(zipFile);
    displayPermissions("Permissions after updating the Zip File", zipFile);
    assertEquals(afterAttrs.permissions(), newPerms,
            "Permissions were not updated as expected!");
}
 
Example #24
Source Project: lancoder   Author: jdupl   File: FileUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets permissions to file or directory given. Fails silently and returns false if an exception occurred at some
 * point.
 * 
 * @param f
 *            The file or directory
 * @param perms
 *            The set of POSIX permissions
 * @param recursive
 *            Change permissions recursively for directory
 * @return True if all files/directory were set to permissions
 */
public static boolean givePerms(File f, Set<PosixFilePermission> perms, boolean recursive) {
	boolean success = givePerm(f, perms);
	if (f.isDirectory() && recursive) {
		File[] files = f.listFiles();
		for (File file : files) {
			if (!givePerms(file, perms, recursive)) {
				success = false;
			}
		}
	}
	return success;
}
 
Example #25
Source Project: initializr   Author: spring-io   File: AbstractInitializrIntegrationTests.java    License: Apache License 2.0 5 votes vote down vote up
private void applyPermissions(Path target, Set<PosixFilePermission> permissions) throws IOException {
	if (isWindows()) {
		File file = target.toFile();
		applyPermission(file::setReadable, permissions, PosixFilePermission.OWNER_READ,
				PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ);
		applyPermission(file::setWritable, permissions, PosixFilePermission.OWNER_WRITE,
				PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_WRITE);
		applyPermission(file::setExecutable, permissions, PosixFilePermission.OWNER_EXECUTE,
				PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_EXECUTE);
	}
	else {
		Files.setPosixFilePermissions(target, permissions);
	}
}
 
Example #26
Source Project: copybara   Author: google   File: FileUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMaterializedSymlinksAreWriteable() throws Exception {
  Path one = Files.createDirectory(temp.resolve("one"));
  Path two = Files.createDirectory(temp.resolve("two"));
  Path absolute = touch(Files.createDirectory(temp.resolve("absolute")).resolve("absolute"));
  FileUtil.addPermissions(absolute, ImmutableSet.of(PosixFilePermission.OWNER_READ));

  Path absoluteTarget = one.relativize(absolute);
  Files.createSymbolicLink(one.resolve("absolute"), absoluteTarget);

  FileUtil.copyFilesRecursively(one, two, CopySymlinkStrategy.MATERIALIZE_OUTSIDE_SYMLINKS);
  assertThat(Files.isSymbolicLink(two.resolve("absolute"))).isFalse();
  assertThat(Files.isWritable(two.resolve("absolute"))).isTrue();
}
 
Example #27
Source Project: appengine-plugins-core   Author: GoogleCloudPlatform   File: PosixUtil.java    License: 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 #28
Source Project: rug-cli   Author: atomist-attic   File: FileUtils.java    License: 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 #29
Source Project: connect-utils   Author: jcustenborder   File: ValidFileWritableTest.java    License: 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 #30
Source Project: ParallelGit   Author: beijunyi   File: PosixFileAttributesTest.java    License: 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));
}