Example usage for java.nio.file.attribute PosixFilePermission OWNER_EXECUTE

List of usage examples for java.nio.file.attribute PosixFilePermission OWNER_EXECUTE

Introduction

In this page you can find the example usage for java.nio.file.attribute PosixFilePermission OWNER_EXECUTE.

Prototype

PosixFilePermission OWNER_EXECUTE

To view the source code for java.nio.file.attribute PosixFilePermission OWNER_EXECUTE.

Click Source Link

Document

Execute/search permission, owner.

Usage

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//ww  w .j av a 2 s .c om
 */
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:io.takari.maven.testing.executor.junit.MavenVersionResolver.java

private void unarchive(File archive, File directory) throws IOException {
    try (TarArchiveInputStream ais = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(archive)))) {
        TarArchiveEntry entry;/*from w  w w  . j a va 2  s .c  om*/
        while ((entry = ais.getNextTarEntry()) != null) {
            if (entry.isFile()) {
                String name = entry.getName();
                File file = new File(directory, name);
                file.getParentFile().mkdirs();
                try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
                    copy(ais, os);
                }
                int mode = entry.getMode();
                if (mode != -1 && (mode & 0100) != 0) {
                    try {
                        Path path = file.toPath();
                        Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path);
                        permissions.add(PosixFilePermission.OWNER_EXECUTE);
                        Files.setPosixFilePermissions(path, permissions);
                    } catch (UnsupportedOperationException e) {
                        // must be windows, ignore
                    }
                }
            }
        }
    }
}

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();// ww  w  .  ja  v a  2s . 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:io.hops.hopsworks.common.security.CertificatesMgmService.java

@PostConstruct
public void init() {
    masterPasswordFile = new File(settings.getHopsworksMasterEncPasswordFile());
    if (!masterPasswordFile.exists()) {
        throw new IllegalStateException("Master encryption file does not exist");
    }// w w  w  .j  a va2s.  co  m

    try {
        PosixFileAttributeView fileView = Files.getFileAttributeView(masterPasswordFile.toPath(),
                PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        Set<PosixFilePermission> filePermissions = fileView.readAttributes().permissions();
        boolean ownerRead = filePermissions.contains(PosixFilePermission.OWNER_READ);
        boolean ownerWrite = filePermissions.contains(PosixFilePermission.OWNER_WRITE);
        boolean ownerExecute = filePermissions.contains(PosixFilePermission.OWNER_EXECUTE);

        boolean groupRead = filePermissions.contains(PosixFilePermission.GROUP_READ);
        boolean groupWrite = filePermissions.contains(PosixFilePermission.GROUP_WRITE);
        boolean groupExecute = filePermissions.contains(PosixFilePermission.GROUP_EXECUTE);

        boolean othersRead = filePermissions.contains(PosixFilePermission.OTHERS_READ);
        boolean othersWrite = filePermissions.contains(PosixFilePermission.OTHERS_WRITE);
        boolean othersExecute = filePermissions.contains(PosixFilePermission.OTHERS_EXECUTE);

        // Permissions should be 700
        if ((ownerRead && ownerWrite && ownerExecute) && (!groupRead && !groupWrite && !groupExecute)
                && (!othersRead && !othersWrite && !othersExecute)) {
            String owner = fileView.readAttributes().owner().getName();
            String group = fileView.readAttributes().group().getName();
            String permStr = PosixFilePermissions.toString(filePermissions);
            LOG.log(Level.INFO, "Passed permissions check for file " + masterPasswordFile.getAbsolutePath()
                    + ". Owner: " + owner + " Group: " + group + " Permissions: " + permStr);
        } else {
            throw new IllegalStateException("Wrong permissions for file " + masterPasswordFile.getAbsolutePath()
                    + ", it should be 700");
        }

    } catch (UnsupportedOperationException ex) {
        LOG.log(Level.WARNING,
                "Associated filesystem is not POSIX compliant. "
                        + "Continue without checking the permissions of " + masterPasswordFile.getAbsolutePath()
                        + " This might be a security problem.");
    } catch (IOException ex) {
        throw new IllegalStateException(
                "Error while getting POSIX permissions of " + masterPasswordFile.getAbsolutePath());
    }

    // Register handlers when master encryption password changes
    MasterPasswordChangeHandler<CertsFacade> psUserCertsHandler = new PSUserCertsMasterPasswordHandler(
            userFacade);
    psUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(UserCerts.class, psUserCertsHandler);

    MasterPasswordChangeHandler<CertsFacade> pgUserCertsHandler = new PGUserCertsMasterPasswordHandler(
            projectFacade);
    pgUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(ProjectGenericUserCerts.class, pgUserCertsHandler);

    MasterPasswordChangeHandler<ClusterCertificateFacade> delaClusterCertsHandler = new DelaCertsMasterPasswordHandler(
            settings);
    delaClusterCertsHandler.setFacade(clusterCertificateFacade);
    registerMasterPasswordChangeHandler(ClusterCertificate.class, delaClusterCertsHandler);
}

From source file:com.facebook.buck.util.unarchive.Unzip.java

private void writeZipContents(ZipFile zip, ZipArchiveEntry entry, ProjectFilesystem filesystem, Path target)
        throws IOException {
    // Write file
    try (InputStream is = zip.getInputStream(entry)) {
        if (entry.isUnixSymlink()) {
            filesystem.createSymLink(target,
                    filesystem.getPath(new String(ByteStreams.toByteArray(is), Charsets.UTF_8)),
                    /* force */ true);
        } else {// w w  w  .  ja  va  2 s  .com
            try (OutputStream out = filesystem.newFileOutputStream(target)) {
                ByteStreams.copy(is, out);
            }
        }
    }

    Path filePath = filesystem.resolve(target);
    File file = filePath.toFile();

    // restore mtime for the file
    file.setLastModified(entry.getTime());

    // TODO(simons): Implement what the comment below says we should do.
    //
    // Sets the file permissions of the output file given the information in {@code entry}'s
    // extra data field. According to the docs at
    // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
    // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
    // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
    //
    // <pre>
    //    The following is the layout of the ASi extra block for Unix.  The
    //    local-header and central-header versions are identical.
    //    (Last Revision 19960916)
    //
    //    Value         Size        Description
    //    -----         ----        -----------
    //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
    //   TSize         Short       total data size for this block
    //   CRC           Long        CRC-32 of the remaining data
    //   Mode          Short       file permissions
    //   SizDev        Long        symlink'd size OR major/minor dev num
    //   UID           Short       user ID
    //   GID           Short       group ID
    //   (var.)        variable    symbolic link filename
    //
    //   Mode is the standard Unix st_mode field from struct stat, containing
    //   user/group/other permissions, setuid/setgid and symlink info, etc.
    // </pre>
    //
    // From the stat man page, we see that the following mask values are defined for the file
    // permissions component of the st_mode field:
    //
    // <pre>
    //   S_ISUID   0004000   set-user-ID bit
    //   S_ISGID   0002000   set-group-ID bit (see below)
    //   S_ISVTX   0001000   sticky bit (see below)
    //
    //   S_IRWXU     00700   mask for file owner permissions
    //
    //   S_IRUSR     00400   owner has read permission
    //   S_IWUSR     00200   owner has write permission
    //   S_IXUSR     00100   owner has execute permission
    //
    //   S_IRWXG     00070   mask for group permissions
    //   S_IRGRP     00040   group has read permission
    //   S_IWGRP     00020   group has write permission
    //   S_IXGRP     00010   group has execute permission
    //
    //   S_IRWXO     00007   mask for permissions for others
    //   (not in group)
    //   S_IROTH     00004   others have read permission
    //   S_IWOTH     00002   others have write permission
    //   S_IXOTH     00001   others have execute permission
    // </pre>
    //
    // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
    // but we'll check and throw if they are.
    //
    // Before we do anything, we should check the header ID. Pfft!
    //
    // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
    // values in the external file attributes of a zip entry (found in the zip's central
    // directory) assuming that the OS creating the zip was one of an enormous list that
    // includes UNIX but not Windows, it first searches for the extra fields, and if not found
    // falls through to a code path that supports MS-DOS and which stores the UNIX file
    // attributes in the upper 16 bits of the external attributes field.
    //
    // We'll support neither approach fully, but we encode whether this file was executable
    // via storing 0100 in the fields that are typically used by zip implementations to store
    // POSIX permissions. If we find it was executable, use the platform independent java
    // interface to make this unpacked file executable.

    Set<PosixFilePermission> permissions = MorePosixFilePermissions
            .fromMode(entry.getExternalAttributes() >> 16);
    if (permissions.contains(PosixFilePermission.OWNER_EXECUTE) && file.getCanonicalFile().exists()) {
        MostFiles.makeExecutable(filePath);
    }
}

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//from  ww w.j  a va2  s.c o 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/*from   w  w  w.j ava2 s  .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: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;/*ww w. j  av  a  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:org.kitodo.services.command.CommandServiceTest.java

public static void setFileExecuteable(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);
}

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