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:uk.ac.ebi.metabolights.webservice.utils.FileUtil.java

/**
 * Create a private FTP folder for uploading big study files
 *
 * @param folder/*  w w w  .j  ava 2  s. c  o m*/
 * @return a String containing created folder
 * @author jrmacias
 * @date 20151102
 */
@PostConstruct
public static Path createFtpFolder(String folder) throws IOException {

    String privateFTPRoot = PropertiesUtil.getProperty("privateFTPRoot"); // ~/ftp_private/

    // create the folder
    File ftpFolder = new File(privateFTPRoot + File.separator + folder);
    Path folderPath = ftpFolder.toPath();
    if (!ftpFolder.mkdir())
        throw new IOException();

    // set folder owner, group and access permissions
    // 'chmod 770'
    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    // owner permissions
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    // group permissions
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    // apply changes
    Files.getFileAttributeView(folderPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
            .setPermissions(perms);

    return folderPath;
}

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

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);//from   www .  j  a v  a2 s.  com
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiverTest.java

private void setPermissionsTo700() {
    try {/*from   ww  w . j  a v a2  s  .c o  m*/
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(testPermissionsFile.toPath(), perms);
    } catch (Exception e) {
        Assume.assumeNoException("skip test on filesystems that do not support POSIX file permissions", e);
    }
}

From source file:org.springframework.boot.gradle.tasks.bundling.AbstractBootArchiveTests.java

@Test
public void launchScriptCanBePrepended() throws IOException {
    this.task.setMainClassName("com.example.Main");
    this.task.launchScript();
    this.task.execute();
    Map<String, String> properties = new HashMap<>();
    properties.put("initInfoProvides", this.task.getBaseName());
    properties.put("initInfoShortDescription", this.project.getDescription());
    properties.put("initInfoDescription", this.project.getDescription());
    assertThat(Files.readAllBytes(this.task.getArchivePath().toPath()))
            .startsWith(new DefaultLaunchScript(null, properties).toByteArray());
    try {//from  w  w  w  .  j av a  2s.  c om
        Set<PosixFilePermission> permissions = Files
                .getPosixFilePermissions(this.task.getArchivePath().toPath());
        assertThat(permissions).contains(PosixFilePermission.OWNER_EXECUTE);
    } catch (UnsupportedOperationException ex) {
        // Windows, presumably. Continue
    }
}

From source file:com.facebook.buck.zip.Unzip.java

/**
 * Unzips a file to a destination and returns the paths of the written files.
 *//*from w  w  w .ja  va 2 s  .  c o  m*/
public static ImmutableList<Path> extractZipFile(Path zipFile, ProjectFilesystem filesystem, Path relativePath,
        ExistingFileMode existingFileMode) throws IOException {
    // if requested, clean before extracting
    if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) {
        try (ZipFile zip = new ZipFile(zipFile.toFile())) {
            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                filesystem.deleteRecursivelyIfExists(relativePath.resolve(entry.getName()));
            }
        }
    }
    ImmutableList.Builder<Path> filesWritten = ImmutableList.builder();
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = entry.getName();
            Path target = relativePath.resolve(fileName);

            // TODO(bolinfest): Keep track of which directories have already been written to avoid
            // making unnecessary Files.createDirectories() calls. In practice, a single zip file will
            // have many entries in the same directory.

            if (entry.isDirectory()) {
                // Create the directory and all its parent directories
                filesystem.mkdirs(target);
            } else {
                // Create parent folder
                filesystem.createParentDirs(target);

                filesWritten.add(target);
                // 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 {
                        try (OutputStream out = filesystem.newFileOutputStream(target)) {
                            ByteStreams.copy(is, out);
                        }
                    }
                }

                // restore mtime for the file
                filesystem.resolve(target).toFile().setLastModified(entry.getTime());

                // TODO(shs96c): 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)) {
                    MoreFiles.makeExecutable(filesystem.resolve(target));
                }
            }
        }
    }
    return filesWritten.build();
}

From source file:com.ibm.ecm.extension.aspera.AsperaPlugin.java

private Path makeFileExecutable(final Path file) throws AsperaPluginException {
    final Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    try {//from  w w w. ja  va  2 s . c  o  m
        Files.setPosixFilePermissions(file, perms);
    } catch (final IOException e) {
        throw new AsperaPluginException("Failed to make the file executable: " + file, e);
    }

    return file;
}

From source file:org.esa.s2tbx.dataio.gdal.GDALInstaller.java

private static void setExecutablePermissions(Path executablePathName) {
    if (IS_OS_UNIX) {
        Set<PosixFilePermission> permissions = new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE,
                PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE));
        try {//from   w w  w .  java 2s.c o  m
            Files.setPosixFilePermissions(executablePathName, permissions);
        } catch (IOException e) {
            // can't set the permissions for this file, eg. the file was installed as root
            // send a warning message, user will have to do that by hand.
            logger.log(Level.SEVERE,
                    "Can't set execution permissions for executable " + executablePathName.toString()
                            + ". If required, please ask an authorised user to make the file executable.",
                    e);
        }
    }
}

From source file:io.hops.hopsworks.common.security.CertificateMaterializer.java

@PostConstruct
public void init() {
    File tmpDir = new File(settings.getHopsworksTmpCertDir());
    if (!tmpDir.exists()) {
        throw new IllegalStateException(
                "Transient certificates directory <" + tmpDir.getAbsolutePath() + "> does NOT exist!");
    }//from   ww  w  .  j  a  va2  s .  c  om

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

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

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

        // Permissions should be 750
        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(permissions);
            LOG.log(Level.INFO, "Passed permissions check for " + tmpDir.getAbsolutePath() + ". Owner: " + owner
                    + " Group: " + group + " permissions: " + permStr);
        } else {
            throw new IllegalStateException(
                    "Wrong permissions for " + tmpDir.getAbsolutePath() + ", it should be 0750");
        }
    } catch (UnsupportedOperationException ex) {
        LOG.log(Level.WARNING,
                "Associated filesystem is not POSIX compliant. "
                        + "Continue without checking the permissions of " + tmpDir.getAbsolutePath()
                        + " This might be a security problem.");
    } catch (IOException ex) {
        throw new IllegalStateException(
                "Error while getting filesystem " + "permissions of " + tmpDir.getAbsolutePath(), ex);
    }

    try {
        FileUtils.cleanDirectory(tmpDir);
    } catch (IOException ex) {
        LOG.log(Level.WARNING, "Could not clean directory " + tmpDir.getAbsolutePath()
                + " during startup, there might be stale " + "certificates", ex);
    }
    transientDir = tmpDir.getAbsolutePath();
    String delayRaw = settings.getCertificateMaterializerDelay();
    DELAY_VALUE = settings.getConfTimeValue(delayRaw);
    DELAY_TIMEUNIT = settings.getConfTimeTimeUnit(delayRaw);

    try {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        long threadId = Thread.currentThread().getId();
        String lock_identifier = hostAddress + "_" + threadId;
        lock_id = lock_identifier.length() <= 30 ? lock_identifier : lock_identifier.substring(0, 30);
    } catch (UnknownHostException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:io.jmnarloch.cd.go.plugin.gradle.GradleTaskConfigParser.java

/**
 * Adds the executable file permission./* ww  w  .  j  a va2 s. c o m*/
 *
 * @param file the path to the file
 */
private void addExecutablePermission(String file) {
    final Path path = Paths.get(file);
    if (Files.exists(path)) {
        try {
            PosixFileAttributeView attr = Files.getFileAttributeView(path, PosixFileAttributeView.class);
            Set<PosixFilePermission> permissions = attr.readAttributes().permissions();
            if (permissions.add(PosixFilePermission.OWNER_EXECUTE)) {
                logger.info(String.format("Added +x permission to file: %s", file));
            }
            attr.setPermissions(permissions);
        } catch (IOException e) {
            logger.error(String.format("Failed to add the executable permissions to file: %s", file));
        }
    }
}

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