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:com.twosigma.beaker.core.rest.FileIORest.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Path("setPosixFileOwnerAndPermissions")
@Produces(MediaType.TEXT_PLAIN)//ww  w  . jav  a2  s . c  o  m
public Response setPosixFilePermissions(@FormParam("path") String pathString, @FormParam("owner") String owner,
        @FormParam("group") String group, @FormParam("permissions[]") List<String> permissions)
        throws IOException {
    HashSet<PosixFilePermission> filePermissions = getPosixFilePermissions(permissions);
    try {
        java.nio.file.Path path = Paths.get(pathString);

        Files.setPosixFilePermissions(path, filePermissions);

        UserPrincipalLookupService userPrincipalLookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        if (StringUtils.isNoneBlank(owner)) {
            Files.setOwner(path, userPrincipalLookupService.lookupPrincipalByName(owner));
        }
        if (StringUtils.isNoneBlank(group)) {
            Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
                    .setGroup(userPrincipalLookupService.lookupPrincipalByGroupName(group));
        }
        return status(OK).build();
    } catch (FileSystemException e) {
        return status(INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}

From source file:org.springframework.ide.eclipse.boot.wizard.content.CodeSet.java

/**
 * Copies the contents of codeset to a given filesystem location
 *///from w  w  w.  j  av a2  s.c o  m
public void createAt(final File location) throws Exception {
    if (location.exists()) {
        if (!FileUtils.deleteQuietly(location)) {
            throw new IOException("Data already exists at location and it could not be deleted: " + location);
        }
    }
    each(new CodeSet.Processor<Void>() {
        @Override
        public Void doit(CodeSetEntry e) throws Exception {
            IPath path = e.getPath();
            File target = new File(location, path.toString());
            if (e.isDirectory()) {
                target.mkdirs();
            } else {
                IOUtil.pipe(e.getData(), target);
                if (!IS_WINDOWS) {
                    int mode = e.getUnixMode();
                    if (mode > 0) {
                        Files.setPosixFilePermissions(target.toPath(), OsUtils.posixFilePermissions(mode));
                    }
                }
            }
            return null;
        }
    });
}

From source file:com.twosigma.beaker.r.utils.RServerEvaluator.java

protected String makeTemp(String base, String suffix) throws IOException {
    File dir = new File(System.getenv("beaker_tmp_dir"));
    File tmp = File.createTempFile(base, suffix, dir);
    if (!iswindows) {
        Set<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(tmp.toPath(), perms);
    }/*from   w ww  . ja  v  a2  s .  co m*/
    String r = tmp.getAbsolutePath();
    logger.debug("returns {}", r);
    return r;
}

From source file:io.hops.hopsworks.common.dao.jupyter.config.JupyterConfigFilesGenerator.java

private boolean createJupyterDirs(JupyterPaths jp) throws IOException {
    File projectDir = new File(jp.getProjectUserPath());
    projectDir.mkdirs();/* w w  w  .j  a v  a2 s .  c  o  m*/
    File baseDir = new File(jp.getNotebookPath());
    baseDir.mkdirs();
    // Set owner persmissions
    Set<PosixFilePermission> xOnly = new HashSet<>();
    xOnly.add(PosixFilePermission.OWNER_WRITE);
    xOnly.add(PosixFilePermission.OWNER_READ);
    xOnly.add(PosixFilePermission.OWNER_EXECUTE);
    xOnly.add(PosixFilePermission.GROUP_WRITE);
    xOnly.add(PosixFilePermission.GROUP_EXECUTE);

    Set<PosixFilePermission> perms = new HashSet<>();
    //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_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    //add others permissions
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    Files.setPosixFilePermissions(Paths.get(jp.getNotebookPath()), perms);
    Files.setPosixFilePermissions(Paths.get(jp.getProjectUserPath()), xOnly);

    new File(jp.getConfDirPath() + "/custom").mkdirs();
    new File(jp.getRunDirPath()).mkdirs();
    new File(jp.getLogDirPath()).mkdirs();
    new File(jp.getCertificatesDir()).mkdirs();
    return true;
}

From source file:org.gradle.caching.internal.tasks.ChmodBenchmark.java

@Benchmark
public void createFileJava7SetPermissionsWhenNeeded(Blackhole blackhole) throws IOException {
    int incrementAndGet = counter.incrementAndGet();
    Path file = Files.createFile(tempDirPath.resolve("file-" + incrementAndGet));
    Set<PosixFilePermission> originalPermissions = Files.getPosixFilePermissions(file);
    Set<PosixFilePermission> permissionsToSet;
    if (incrementAndGet % 2 == 0) {
        permissionsToSet = DEFAULT_JAVA7_FILE_PERMISSIONS;
    } else {//  ww  w .j a  v  a 2s.  c om
        permissionsToSet = WEIRD_JAVA7_FILE_PERMISSIONS;
    }
    // This should pass 50% of the time
    if (!originalPermissions.equals(permissionsToSet)) {
        Files.setPosixFilePermissions(file, permissionsToSet);
    }
    blackhole.consume(file);
}

From source file:org.apache.storm.daemon.supervisor.AdvancedFSOps.java

/**
 * Set directory permissions to (OWNER)RWX (GROUP)R-X (OTHER)---
 * On some systems that do not support this, it may become a noop
 * @param dir the directory to change permissions on
 * @throws IOException on any error// ww  w .j a v a  2 s.co  m
 */
public void restrictDirectoryPermissions(File dir) throws IOException {
    Set<PosixFilePermission> perms = new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
            PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ,
            PosixFilePermission.GROUP_EXECUTE));
    Files.setPosixFilePermissions(dir.toPath(), perms);
}

From source file:com.streamsets.datacollector.MiniSDCTestingUtility.java

/**
 * Start mini SDC/* w w  w  .  j  a  v  a  2s . c o m*/
 * @param executionMode the Execution mode - could be standalone or cluster
 * @return
 * @throws Exception
 */
public MiniSDC createMiniSDC(ExecutionMode executionMode) throws Exception {
    Properties miniITProps = new Properties();
    File miniITProperties = new File(Resources.getResource("miniIT.properties").toURI());
    InputStream sdcInStream = new FileInputStream(miniITProperties);
    miniITProps.load(sdcInStream);
    String sdcDistRoot = (String) miniITProps.get(SDC_DIST_DIR);
    File sdcDistFile = new File(sdcDistRoot);
    if (!sdcDistFile.exists()) {
        throw new RuntimeException("SDC dist root dir " + sdcDistFile.getAbsolutePath() + "doesn't exist");
    }
    LOG.info("SDC dist root at " + sdcDistFile.getAbsolutePath());
    sdcInStream.close();

    File target = getDataTestDir();
    String targetRoot = target.getAbsolutePath();
    File etcTarget = new File(target, "etc");
    File resourcesTarget = new File(target, "resources");
    FileUtils.copyDirectory(new File(sdcDistRoot + "/etc"), etcTarget);
    FileUtils.copyDirectory(new File(sdcDistRoot + "/resources"), resourcesTarget);
    FileUtils.copyDirectory(new File(sdcDistRoot + "/libexec"), new File(target, "libexec"));
    // Set execute permissions back on script
    Set<PosixFilePermission> set = new HashSet<PosixFilePermission>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    Files.setPosixFilePermissions(new File(target, "libexec" + "/_cluster-manager").toPath(), set);
    File staticWebDir = new File(target, "static-web");
    staticWebDir.mkdir();

    setExecutePermission(new File(target, "libexec" + "/_cluster-manager").toPath());
    File log4jProperties = new File(etcTarget, "sdc-log4j.properties");
    if (log4jProperties.exists()) {
        log4jProperties.delete();
    }
    Files.copy(Paths.get(Resources.getResource("log4j.properties").toURI()), log4jProperties.toPath());

    File sdcProperties = new File(etcTarget, "sdc.properties");
    System.setProperty("sdc.conf.dir", etcTarget.getAbsolutePath());
    System.setProperty("sdc.resources.dir", resourcesTarget.getAbsolutePath());
    System.setProperty("sdc.libexec.dir", targetRoot + "/libexec");
    System.setProperty("sdc.static-web.dir", targetRoot + "/static-web");
    rewriteProperties(sdcProperties, executionMode);
    this.miniSDC = new MiniSDC(sdcDistRoot);
    return this.miniSDC;
}

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

/**
 * Receive ZMQ messages with pilatus-1.0 header type and write the data part
 * to disk/*from w  ww  .  j a  v a 2s  .com*/
 */
public void receive(Integer numImages) {

    try {
        done = false;
        counter = 0;
        counterDropped = 0;
        receive = true;
        context = ZMQ.context(1);
        socket = context.socket(ZMQ.PULL);
        socket.connect("tcp://" + hostname + ":" + port);

        ObjectMapper mapper = new ObjectMapper();
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        String path = "";

        // User lookup service
        UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();

        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);

        while (receive) {
            try {
                byte[] message = socket.recv();
                byte[] content = null;
                if (socket.hasReceiveMore()) {
                    content = socket.recv();
                }
                logger.info("Message received: " + new String(message));

                Map<String, Object> h = mapper.readValue(message, typeRef);

                if (!"pilatus-1.0".equals(h.get("htype"))) {
                    logger.warning("Message type [" + h.get("htype") + "] not supported - ignore message");
                    continue;
                }

                String username = (String) h.get("username");

                // Save content to file (in basedir)
                String p = (String) h.get("path");
                if (!p.startsWith("/")) {
                    p = basedir + "/" + p;
                }
                File f = new File(p);
                // if(!f.exists()){
                if (!path.equals(p)) {
                    if (username == null) {
                        logger.info("Create directory " + p + "");
                        f.mkdirs();
                    } else {
                        logger.info("Create directory " + p + " for user " + username);
                        try {
                            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                            permissions.add(PosixFilePermission.OWNER_READ);
                            permissions.add(PosixFilePermission.OWNER_WRITE);
                            permissions.add(PosixFilePermission.OWNER_EXECUTE);
                            permissions.add(PosixFilePermission.GROUP_READ);
                            permissions.add(PosixFilePermission.GROUP_WRITE);
                            permissions.add(PosixFilePermission.GROUP_EXECUTE);
                            // username and groupname is the same by
                            // convention
                            mkdir(f, lookupservice.lookupPrincipalByName(username),
                                    lookupservice.lookupPrincipalByGroupName(username), permissions);
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to create directory for user " + username + "",
                                    e);
                        }
                    }
                    path = p;
                }

                File file = new File(f, (String) h.get("filename"));
                logger.finest("Write to " + file.getAbsolutePath());

                try (FileOutputStream s = new FileOutputStream(file)) {
                    s.write(content);
                }

                if (username != null) {
                    Files.setOwner(file.toPath(), lookupservice.lookupPrincipalByName(username));
                    // username and groupname is the same by convention
                    Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class,
                            LinkOption.NOFOLLOW_LINKS)
                            .setGroup(lookupservice.lookupPrincipalByGroupName(username));
                    Files.setPosixFilePermissions(file.toPath(), perms);
                }

                counter++;
                if (numImages != null && numImages == counter) {
                    break;
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, "", e);
                counterDropped++;
            }
        }

    } catch (Exception e) {
        if (receive) {
            e.printStackTrace();
        }
    }
}

From source file:org.zaproxy.zap.extension.jxbrowserlinux64.selenium.JxBrowserProvider.java

private static void setExecutable(Path file) throws IOException {
    if (!SystemUtils.IS_OS_MAC && !SystemUtils.IS_OS_UNIX) {
        return;//from w ww.  j a  va 2  s  . co  m
    }

    Set<PosixFilePermission> perms = Files.readAttributes(file, PosixFileAttributes.class).permissions();
    if (perms.contains(PosixFilePermission.OWNER_EXECUTE)) {
        return;
    }

    perms.add(PosixFilePermission.OWNER_EXECUTE);
    Files.setPosixFilePermissions(file, perms);
}

From source file:com.streamsets.datacollector.MiniSDCTestingUtility.java

public static void setExecutePermission(Path path) throws IOException {
    Set<PosixFilePermission> set = new HashSet<PosixFilePermission>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    Files.setPosixFilePermissions(path, set);
}