Search in sources :

Example 56 with PosixFilePermission

use of java.nio.file.attribute.PosixFilePermission in project cloudconductor-agent-redhat by cinovo.

the class FileHelper method chmod.

/**
 * @param localFile the local file to use chmod on
 * @param fileMode the filemode to set in PosixFilePermissions string type - 764 = rwxrw-r--
 * @throws IOException if chmod couldn't be edited
 */
public static void chmod(File localFile, String fileMode) throws IOException {
    PosixFileAttributeView view = FileHelper.getFileAttributes(localFile);
    Set<PosixFilePermission> fileModeSet = PosixFilePermissions.fromString(fileMode);
    view.setPermissions(fileModeSet);
}
Also used : PosixFilePermission(java.nio.file.attribute.PosixFilePermission) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Example 57 with PosixFilePermission

use of java.nio.file.attribute.PosixFilePermission in project coprhd-controller by CoprHD.

the class DbCheckerFileWriter method init.

private static BufferedWriter init(String fileName, String usage) throws IOException {
    deleteIfExists(fileName);
    final Path filePath = FileSystems.getDefault().getPath(fileName);
    BufferedWriter writer = Files.newBufferedWriter(filePath, Charset.defaultCharset());
    Set<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
    setFilePermissions(filePath, owner, group, perms);
    writeln(writer, usage);
    return writer;
}
Also used : Path(java.nio.file.Path) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) BufferedWriter(java.io.BufferedWriter)

Example 58 with PosixFilePermission

use of java.nio.file.attribute.PosixFilePermission in project coprhd-controller by CoprHD.

the class DBClient method updateFilePermissions.

private void updateFilePermissions(String dumpFileName) {
    File dumpFile = new File(dumpFileName);
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    try {
        Files.setPosixFilePermissions(dumpFile.toPath(), perms);
    } catch (Exception e) {
        if (dumpFile.exists()) {
            dumpFile.delete();
        }
        System.err.println(String.format("Failed to update file permission, Exception=%s", e));
        log.error("Failed to update file permission", e);
    }
}
Also used : PosixFilePermission(java.nio.file.attribute.PosixFilePermission) File(java.io.File) ZipFile(java.util.zip.ZipFile) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConnectionException(com.netflix.astyanax.connectionpool.exceptions.ConnectionException) IOException(java.io.IOException) DatabaseException(com.emc.storageos.db.exceptions.DatabaseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HashSet(java.util.HashSet)

Example 59 with PosixFilePermission

use of java.nio.file.attribute.PosixFilePermission in project che by eclipse.

the class JGitConnection method writePrivateKeyFile.

/**
     * Writes private SSH key into file.
     *
     * @return file that contains SSH key
     * @throws GitException
     *         if other error occurs
     */
private File writePrivateKeyFile(String url, File keyDirectory) throws GitException {
    final File keyFile = new File(keyDirectory, "identity");
    try (FileOutputStream fos = new FileOutputStream(keyFile)) {
        byte[] sshKey = sshKeyProvider.getPrivateKey(url);
        fos.write(sshKey);
    } catch (IOException | ServerException exception) {
        String errorMessage = "Can't store ssh key. ".concat(exception.getMessage());
        LOG.error(errorMessage, exception);
        throw new GitException(errorMessage, ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
    }
    Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
    try {
        java.nio.file.Files.setPosixFilePermissions(keyFile.toPath(), permissions);
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    return keyFile;
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) GitException(org.eclipse.che.api.git.exception.GitException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Example 60 with PosixFilePermission

use of java.nio.file.attribute.PosixFilePermission in project buck by facebook.

the class Unzip method extractZipFile.

/**
   * Unzips a file to a destination and returns the paths of the written files.
   */
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);
            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();
}
Also used : Path(java.nio.file.Path) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) ImmutableList(com.google.common.collect.ImmutableList) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) PosixFilePermission(java.nio.file.attribute.PosixFilePermission)

Aggregations

PosixFilePermission (java.nio.file.attribute.PosixFilePermission)139 Path (java.nio.file.Path)69 IOException (java.io.IOException)41 File (java.io.File)40 HashSet (java.util.HashSet)40 Test (org.junit.Test)35 Set (java.util.Set)22 FileOutputStream (java.io.FileOutputStream)17 PosixFileAttributeView (java.nio.file.attribute.PosixFileAttributeView)14 PosixFileAttributes (java.nio.file.attribute.PosixFileAttributes)11 FileNotFoundException (java.io.FileNotFoundException)8 ArrayList (java.util.ArrayList)7 RandomAccessFile (java.io.RandomAccessFile)6 UserPrincipal (java.nio.file.attribute.UserPrincipal)6 OutputStream (java.io.OutputStream)5 SimpleDateFormat (java.text.SimpleDateFormat)5 BufferedWriter (java.io.BufferedWriter)4 InputStream (java.io.InputStream)4 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)4 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)4