Java Code Examples for java.nio.file.Files.setPosixFilePermissions()

The following are Jave code examples for showing how to use setPosixFilePermissions() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: FilePerm.java   Source Code and License Vote up 7 votes
/**
 * 设置文件权限。前提:必须支持PosixFileAttributeView.
 */
public static void setFilePerm(File file, String perm) {
  if (filePermSupported()) {
    try {
      Set<PosixFilePermission> perms = PosixFilePermissions.fromString(perm);
      PosixFileAttributes attr = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
      attr.permissions().clear();
      Files.setPosixFilePermissions(file.toPath(), perms);
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }
}
 
Example 2
Project: elastest-instrumentation-manager   File: FileTextUtils.java   Source Code and License Vote up 7 votes
public static void setAsExecutable(String filePath) throws IOException {
	
	//using PosixFilePermission to set file permissions 755
       Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
       //add owners permission
       perms.add(PosixFilePermission.OWNER_READ);
       perms.add(PosixFilePermission.OWNER_WRITE);
       perms.add(PosixFilePermission.OWNER_EXECUTE);
       //add group permissions
       perms.add(PosixFilePermission.GROUP_READ);
       perms.add(PosixFilePermission.GROUP_EXECUTE);
       //add others permissions
       perms.add(PosixFilePermission.OTHERS_READ);
       perms.add(PosixFilePermission.OTHERS_EXECUTE);
       
       Files.setPosixFilePermissions(Paths.get(filePath), perms);
       logger.info("Modified as executable " + filePath);
	
}
 
Example 3
Project: ats-framework   File: LocalFileSystemOperations.java   Source Code and License Vote up 6 votes
@Override
public void setFilePermissions(
                                String sourceFile,
                                String permissions ) {

    sourceFile = IoUtils.normalizeFilePath(sourceFile, osType);
    File file = new File(sourceFile);

    checkFileExistence(file);
    checkAttributeOsSupport(FileAttributes.PERMISSIONS);

    try {
        Files.setPosixFilePermissions(new File(sourceFile).getCanonicalFile().toPath(),
                                      getPosixFilePermission(Integer.parseInt(permissions, 8)));
    } catch (IOException ioe) {
        throw new FileSystemOperationException("Could not update permissions for file '" + sourceFile
                                               + "'", ioe);
    }
    log.info("Successfully set permissions of file '" + sourceFile + "' to " + permissions);
}
 
Example 4
Project: AptSpring   File: TestResourceLoader.java   Source Code and License Vote up 6 votes
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void testBrokenEnvironment() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  DefinitionModel model = new DefinitionModel(SIMPLE_MODEL);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));
  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    TestFileStore fileStore = new TestFileStore(root);
    assertThatThrownBy(() -> fileStore.store(model)).isInstanceOf(IOException.class)
      .hasMessage("could not write directories for model storage");
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
 
Example 5
Project: AptSpring   File: TestResourceLoader.java   Source Code and License Vote up 6 votes
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void failedStorage() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));
  
  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    DefinitionModel model1 = new DefinitionModel(SIMPLE_MODEL);
    TestErrorListener el = new TestErrorListener();

    TestFileStore fileStore = new TestFileStore(workingDir);
    ResourceLoader loader = new ClasspathUrlResourceLoader(workingDir);
    DefinitionModelStore store = new GsonDefinitionModelStore(loader, fileStore);
    Set<DefinitionModel> models = new HashSet<>();
    models.add(model1);
    new DefinitionContentInspector()
      .inspectDefinitionGraph(models, el, new ReflectionAssignabilityUtils(), store);
    assertThat(el.getErrors()).hasSize(1);
    assertThat(el.getErrors().get(0).getMessage()).isEqualTo(ErrorType.COULD_NOT_STORE);
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
 
Example 6
Project: cyberduck   File: LocalAttributesFinderFeatureTest.java   Source Code and License Vote up 6 votes
@Test
public void testConvert() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    if(session.isPosixFilesystem()) {
        session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
        session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
        final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
        new LocalTouchFeature(session).touch(file, new TransferStatus());
        final java.nio.file.Path local = session.toPath(file);
        final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class);
        final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session);
        assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------"));
        assertEquals("rw-------", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx"));
        assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----"));
        assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol());
        assertEquals(posixAttributes.size(), finder.find(file).getSize());
        assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate());
        assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate());
        assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate());
        new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    }
}
 
Example 7
Project: openjdk-jdk10   File: TestVMOptionsFile.java   Source Code and License Vote up 6 votes
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
 
Example 8
Project: solr-runner-maven-plugin   File: SOLRRunner.java   Source Code and License Vote up 5 votes
public void fixPermissions() throws IOException {
    try {
        Set<PosixFilePermission> filePermissions = Files.getPosixFilePermissions(executable);
        Stream<PosixFilePermission> requiredPermissions = Stream
            .of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_EXECUTE);

        requiredPermissions.forEach(requiredPermission -> {
            filePermissions.add(requiredPermission);
        });
        Files.setPosixFilePermissions(executable, filePermissions);
    } catch (UnsupportedOperationException e) {
        // windows -.-
    }
}
 
Example 9
Project: hadoop   File: LocalJavaKeyStoreProvider.java   Source Code and License Vote up 5 votes
@Override
public void flush() throws IOException {
  super.flush();
  if (!Shell.WINDOWS) {
    Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()),
        permissions);
  } 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 = FsPermission.valueOf(
        "-" + PosixFilePermissions.toString(permissions));
    FileUtil.setPermission(file, fsPermission);
  }
}
 
Example 10
Project: jdk8u-jdk   File: CustomLauncherTest.java   Source Code and License Vote up 5 votes
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,
               StandardCopyOption.COPY_ATTRIBUTES);
    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 11
Project: openjdk-jdk10   File: AbstractFilePermissionTest.java   Source Code and License Vote up 5 votes
/**
 * Test 1 - SSL config file is secure - VM should start
 */
private void test1() throws Exception {
    final Set<PosixFilePermission> perms_0700 = new HashSet<>();
    perms_0700.add(PosixFilePermission.OWNER_WRITE);
    perms_0700.add(PosixFilePermission.OWNER_READ);
    perms_0700.add(PosixFilePermission.OWNER_EXECUTE);
    Files.setPosixFilePermissions(file2PermissionTest, perms_0700);

    if (doTest() != 0) {
        ++failures;
    }
}
 
Example 12
Project: OpenJSharp   File: DflCache.java   Source Code and License Vote up 5 votes
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 13
Project: FreeCol   File: FreeColDirectories.java   Source Code and License Vote up 5 votes
/**
 * Create the given directory if it does not exist, otherwise expect
 * it to be writable.
 *
 * @param dir The {@code File} specifying the required directory.
 * @return The required directory, or null on failure.
 */
private static File requireDirectory(File dir) {
    if (dir.exists()) {
        if (dir.isDirectory() && dir.canWrite()) return dir;
    } else {
        if (dir.mkdir()) {
            try {
                Files.setPosixFilePermissions(dir.toPath(), mode0700);
            } catch (IOException ioe) { /* ignore */ }
            return dir;
        }
    }
    return null;
}
 
Example 14
Project: openjdk-jdk10   File: CustomLauncherTest.java   Source Code and License Vote up 5 votes
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 15
Project: ats-framework   File: LocalFileSystemOperations.java   Source Code and License Vote up 5 votes
private void extractTar( String tarFilePath, String outputDirPath ) {

        TarArchiveEntry entry = null;
        try (TarArchiveInputStream tis = new TarArchiveInputStream(new FileInputStream(tarFilePath))) {
            while ( (entry = (TarArchiveEntry) tis.getNextEntry()) != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Extracting " + entry.getName());
                }
                File entryDestination = new File(outputDirPath, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(entryDestination));
                    IoUtils.copyStream(tis, out, false, true);
                }
                if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                    // set file/dir permissions, after it is created
                    Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                                  getPosixFilePermission(entry.getMode()));
                }
            }
        } catch (Exception e) {
            String errorMsg = null;
            if (entry != null) {
                errorMsg = "Unable to untar " + entry.getName() + " from " + tarFilePath
                           + ".Target directory '" + outputDirPath + "' is in inconsistent state.";
            } else {
                errorMsg = "Could not read data from " + tarFilePath;
            }
            throw new FileSystemOperationException(errorMsg, e);
        }

    }
 
Example 16
Project: nifi-registry   File: RunNiFiRegistry.java   Source Code and License Vote up 5 votes
private synchronized void writePidFile(final String pid, final Logger logger) throws IOException {
    final File pidFile = getPidFile(logger);
    if (pidFile.exists() && !pidFile.delete()) {
        logger.warn("Failed to delete {}", pidFile);
    }

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

    try {
        final Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.OTHERS_READ);
        Files.setPosixFilePermissions(pidFile.toPath(), perms);
    } catch (final Exception e) {
        logger.warn("Failed to set permissions so that only the owner can read pid 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", pidFile);
    }

    try (final FileOutputStream fos = new FileOutputStream(pidFile)) {
        fos.write(pid.getBytes(StandardCharsets.UTF_8));
        fos.getFD().sync();
    }

    logger.debug("Saved Pid {} to {}", new Object[]{pid, pidFile});
}
 
Example 17
Project: elastic-job-cloud   File: LocalTaskExecutorTest.java   Source Code and License Vote up 5 votes
private static String buildScriptCommandLine() throws IOException {
    if (System.getProperties().getProperty("os.name").contains("Windows")) {
        return Paths.get(LocalTaskExecutorTest.class.getResource("/script/TestScriptJob.bat").getPath().substring(1)).toString();
    }
    Path result = Paths.get(LocalTaskExecutorTest.class.getResource("/script/TestScriptJob.sh").getPath());
    Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
    return result.toString();
}
 
Example 18
Project: bazel-buildfarm   File: CASFileCache.java   Source Code and License Vote up 5 votes
private static void setPermissions(Path path, boolean isExecutable) throws IOException {
  ImmutableSet.Builder<PosixFilePermission> perms = new ImmutableSet.Builder<PosixFilePermission>()
    .add(PosixFilePermission.OWNER_READ);
  if (isExecutable) {
    perms.add(PosixFilePermission.OWNER_EXECUTE);
  }
  Files.setPosixFilePermissions(path, perms.build());
}
 
Example 19
Project: cyberduck   File: LocalAttributes.java   Source Code and License Vote up 5 votes
public void setPermission(final Permission permission) throws AccessDeniedException {
    if(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
        try {
            Files.setPosixFilePermissions(Paths.get(path), PosixFilePermissions.fromString(permission.getSymbol()));
        }
        catch(IllegalArgumentException | IOException e) {
            throw new LocalAccessDeniedException(String.format("Cannot change permissions of %s", path), e);
        }
    }
}
 
Example 20
Project: yacy_grid_mcp   File: OS.java   Source Code and License Vote up 4 votes
public final static void protectPath(Path path) {
    try {
        Files.setPosixFilePermissions(path, securePerm);
    } catch (UnsupportedOperationException | IOException e) {}
}