Example usage for java.nio.file Files setPosixFilePermissions

List of usage examples for java.nio.file Files setPosixFilePermissions

Introduction

In this page you can find the example usage for java.nio.file Files setPosixFilePermissions.

Prototype

public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) throws IOException 

Source Link

Document

Sets a file's POSIX permissions.

Usage

From source file:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Recursively create directories for given user
 * //from   w  ww.j  a va2s  .c om
 * @param f
 * @param user
 * @param perms
 * @throws IOException
 */
public void mkdir(File f, UserPrincipal user, GroupPrincipal group, Set<PosixFilePermission> perms)
        throws IOException {
    if (!f.getParentFile().exists()) {
        mkdir(f.getParentFile(), user, group, perms);
    }

    logger.info("Create directory: " + f.getPath());
    f.mkdir();
    Files.setOwner(f.toPath(), user);
    Files.getFileAttributeView(f.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
            .setGroup(group);
    Files.setPosixFilePermissions(f.toPath(), perms);
}

From source file:org.syncany.operations.actions.FileSystemAction.java

protected void setFileAttributes(FileVersion reconstructedFileVersion, File reconstructedFilesAtFinalLocation)
        throws IOException {
    if (FileUtil.isWindows()) {
        if (reconstructedFileVersion.getDosAttributes() != null) {
            logger.log(Level.INFO,
                    "     - Setting DOS attributes: " + reconstructedFileVersion.getDosAttributes() + " ...");

            DosFileAttributes dosAttrs = FileUtil
                    .dosAttrsFromString(reconstructedFileVersion.getDosAttributes());
            Path filePath = Paths.get(reconstructedFilesAtFinalLocation.getAbsolutePath());

            Files.setAttribute(filePath, "dos:readonly", dosAttrs.isReadOnly());
            Files.setAttribute(filePath, "dos:hidden", dosAttrs.isHidden());
            Files.setAttribute(filePath, "dos:archive", dosAttrs.isArchive());
            Files.setAttribute(filePath, "dos:system", dosAttrs.isSystem());
        }// w w  w.  ja va2  s  .  c om
    } else if (FileUtil.isUnixLikeOperatingSystem()) {
        if (reconstructedFileVersion.getPosixPermissions() != null) {
            logger.log(Level.INFO, "     - Setting POSIX permissions: "
                    + reconstructedFileVersion.getPosixPermissions() + " ...");

            Set<PosixFilePermission> posixPerms = PosixFilePermissions
                    .fromString(reconstructedFileVersion.getPosixPermissions());

            Path filePath = Paths.get(reconstructedFilesAtFinalLocation.getAbsolutePath());
            Files.setPosixFilePermissions(filePath, posixPerms);
        }
    }
}

From source file:org.gridgain.testsuites.bamboo.GridHadoopTestSuite.java

/**
 *  Downloads and extracts an Apache product.
 *
 * @param appName Name of application for log messages.
 * @param homeVariable Pointer to home directory of the component.
 * @param downloadPath Relative download path of tar package.
 * @param destName Local directory name to install component.
 * @throws Exception If failed./*from  ww  w. j  a  va2 s  .c o  m*/
 */
private static void download(String appName, String homeVariable, String downloadPath, String destName)
        throws Exception {
    String homeVal = GridSystemProperties.getString(homeVariable);

    if (!F.isEmpty(homeVal) && new File(homeVal).isDirectory()) {
        X.println(homeVariable + " is set to: " + homeVal);

        return;
    }

    List<String> urls = F.asList("http://apache-mirror.rbc.ru/pub/apache/", "http://www.eu.apache.org/dist/",
            "http://www.us.apache.org/dist/");

    String tmpPath = System.getProperty("java.io.tmpdir");

    X.println("tmp: " + tmpPath);

    File install = new File(tmpPath + File.separatorChar + "__hadoop");

    File home = new File(install, destName);

    X.println("Setting " + homeVariable + " to " + home.getAbsolutePath());

    System.setProperty(homeVariable, home.getAbsolutePath());

    File successFile = new File(home, "__success");

    if (home.exists()) {
        if (successFile.exists()) {
            X.println(appName + " distribution already exists.");

            return;
        }

        X.println(appName + " distribution is invalid and it will be deleted.");

        if (!U.delete(home))
            throw new IOException("Failed to delete directory: " + install.getAbsolutePath());
    }

    for (String url : urls) {
        if (!(install.exists() || install.mkdirs()))
            throw new IOException("Failed to create directory: " + install.getAbsolutePath());

        URL u = new URL(url + downloadPath);

        X.println("Attempting to download from: " + u);

        try {
            URLConnection c = u.openConnection();

            c.connect();

            try (TarArchiveInputStream in = new TarArchiveInputStream(
                    new GzipCompressorInputStream(new BufferedInputStream(c.getInputStream(), 32 * 1024)))) {

                TarArchiveEntry entry;

                while ((entry = in.getNextTarEntry()) != null) {
                    File dest = new File(install, entry.getName());

                    if (entry.isDirectory()) {
                        if (!dest.mkdirs())
                            throw new IllegalStateException();
                    } else {
                        File parent = dest.getParentFile();

                        if (!(parent.exists() || parent.mkdirs()))
                            throw new IllegalStateException();

                        X.print(" [" + dest);

                        try (BufferedOutputStream out = new BufferedOutputStream(
                                new FileOutputStream(dest, false), 128 * 1024)) {
                            U.copy(in, out);

                            out.flush();
                        }

                        Files.setPosixFilePermissions(dest.toPath(), modeToPermissionSet(entry.getMode()));

                        X.println("]");
                    }
                }
            }

            if (successFile.createNewFile())
                return;
        } catch (Exception e) {
            e.printStackTrace();

            U.delete(install);
        }
    }

    throw new IllegalStateException("Failed to install " + appName + ".");
}

From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java

public void saveToFile() throws IOException {
    String jsonString;/*from ww w .  j  av  a 2  s. co  m*/

    synchronized (interpreterSettings) {
        InterpreterInfoSaving info = new InterpreterInfoSaving();
        info.interpreterBindings = interpreterBindings;
        info.interpreterSettings = interpreterSettings;
        info.interpreterRepositories = interpreterRepositories;

        jsonString = gson.toJson(info);
    }

    if (!Files.exists(interpreterBindingPath)) {
        Files.createFile(interpreterBindingPath);

        Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
        Files.setPosixFilePermissions(interpreterBindingPath, permissions);
    }

    FileOutputStream fos = new FileOutputStream(interpreterBindingPath.toFile(), false);
    OutputStreamWriter out = new OutputStreamWriter(fos);
    out.append(jsonString);
    out.close();
    fos.close();
}

From source file:android.databinding.compilationTest.BaseCompilationTest.java

private void setExecutable() throws IOException {
    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);
    //add others permissions
    perms.add(PosixFilePermission.OTHERS_READ);
    Files.setPosixFilePermissions(Paths.get(new File(testFolder, "gradlew").getAbsolutePath()), perms);
}

From source file:org.syncany.operations.down.actions.FileSystemAction.java

protected void setFileAttributes(FileVersion reconstructedFileVersion, File reconstructedFilesAtFinalLocation)
        throws IOException {
    if (EnvironmentUtil.isWindows()) {
        if (reconstructedFileVersion.getDosAttributes() != null) {
            logger.log(Level.INFO,
                    "     - Setting DOS attributes: " + reconstructedFileVersion.getDosAttributes() + " ...");

            DosFileAttributes dosAttrs = FileUtil
                    .dosAttrsFromString(reconstructedFileVersion.getDosAttributes());
            Path filePath = Paths.get(reconstructedFilesAtFinalLocation.getAbsolutePath());

            try {
                Files.setAttribute(filePath, "dos:readonly", dosAttrs.isReadOnly());
                Files.setAttribute(filePath, "dos:hidden", dosAttrs.isHidden());
                Files.setAttribute(filePath, "dos:archive", dosAttrs.isArchive());
                Files.setAttribute(filePath, "dos:system", dosAttrs.isSystem());
            } catch (IOException e) {
                logger.log(Level.WARNING, "     - WARNING: Cannot set file attributes for " + filePath, e);
            }/*from w  w w  . j av  a2  s.co m*/
        }
    } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
        if (reconstructedFileVersion.getPosixPermissions() != null) {
            logger.log(Level.INFO, "     - Setting POSIX permissions: "
                    + reconstructedFileVersion.getPosixPermissions() + " ...");

            Set<PosixFilePermission> posixPerms = PosixFilePermissions
                    .fromString(reconstructedFileVersion.getPosixPermissions());

            Path filePath = Paths.get(reconstructedFilesAtFinalLocation.getAbsolutePath());

            try {
                Files.setPosixFilePermissions(filePath, posixPerms);
            } catch (IOException e) {
                logger.log(Level.WARNING, "     - WARNING: Cannot set file permissions for " + filePath, e);
            }
        }
    }
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

private static void unpack(File archive, File destionation) throws IOException {
    try (ZipFile zip = new ZipFile(archive)) {
        Map<File, String> symLinks = new LinkedHashMap<>();
        Enumeration<ZipArchiveEntry> iterator = zip.getEntries();
        // Top directory name we are going to ignore
        String parentDirectory = iterator.nextElement().getName();
        // Iterate files & folders
        while (iterator.hasMoreElements()) {
            ZipArchiveEntry entry = iterator.nextElement();
            String name = entry.getName().substring(parentDirectory.length());
            File outputFile = new File(destionation, name);
            if (name.startsWith("interactive_ui_tests")) {
                continue;
            }/* w  w  w. j a v  a 2 s.c  om*/
            if (entry.isUnixSymlink()) {
                symLinks.put(outputFile, zip.getUnixSymlink(entry));
            } else if (!entry.isDirectory()) {
                if (!outputFile.getParentFile().isDirectory()) {
                    outputFile.getParentFile().mkdirs();
                }
                try (FileOutputStream outStream = new FileOutputStream(outputFile)) {
                    IOUtils.copy(zip.getInputStream(entry), outStream);
                }
            }
            // Set permission
            if (!entry.isUnixSymlink() && outputFile.exists())
                try {
                    Files.setPosixFilePermissions(outputFile.toPath(),
                            modeToPosixPermissions(entry.getUnixMode()));
                } catch (Exception e) {
                    // ignore
                }
        }
        for (Map.Entry<File, String> entry : symLinks.entrySet()) {
            try {
                Path source = Paths.get(entry.getKey().getAbsolutePath());
                Path target = source.getParent().resolve(entry.getValue());
                if (!source.toFile().exists())
                    Files.createSymbolicLink(source, target);
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:org.apache.nifi.registry.bootstrap.RunNiFiRegistry.java

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);/*from w ww . j  av a2 s.co  m*/
    }

    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 });
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

public static void setPermissionsOnSecurityFolder(File securityFolder) throws IOException {
    // The security folder should accessible only by the owner
    if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
        Files.setPosixFilePermissions(securityFolder.toPath(), EnumSet.of(PosixFilePermission.OWNER_EXECUTE,
                PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_READ));
    }/*from   w  w w.java  2  s.c  o  m*/
}

From source file:org.kitodo.filemanagement.FileManagementTest.java

private static void setFileExecutable(File file) throws IOException {
    Set<PosixFilePermission> perms = new HashSet<>();

    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);

    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);

    Files.setPosixFilePermissions(file.toPath(), perms);
}