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:org.kitodo.command.CommandTest.java

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

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

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

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

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

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerSecurityUpdaterTask.java

protected Set<PosixFilePermission> addOwnerWritePermission(Path target) throws IOException {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(target);
    if (permissions.add(PosixFilePermission.OWNER_WRITE)) {
        Files.setPosixFilePermissions(target, permissions);
    }// ww  w . jav a 2 s  .c o  m
    return permissions;
}

From source file:org.verwandlung.voj.judger.core.Preprocessor.java

/**
 * ???.//from   w  w w . j  a v a 2 s. c om
 * Linux, ?UID=1536?, ?Others???.
 * @param workDirectory 
 */
private void setWorkDirectoryPermission(File workDirectory) throws IOException {
    if (!System.getProperty("os.name").contains("Windows")) {
        Set<PosixFilePermission> permissions = new HashSet<>();

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

        permissions.add(PosixFilePermission.OTHERS_READ);
        permissions.add(PosixFilePermission.OTHERS_WRITE);
        permissions.add(PosixFilePermission.OTHERS_EXECUTE);
        Files.setPosixFilePermissions(workDirectory.toPath(), permissions);
    }
}

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;/*  w  w w. ja v a2  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:org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerSecurityUpdaterTask.java

protected void removeOwnerWritePermission(Path target, Set<PosixFilePermission> permissions)
        throws IOException {
    if (permissions.remove(PosixFilePermission.OWNER_WRITE)) {
        Files.setPosixFilePermissions(target, permissions);
    }/*from   ww w. j  a va2s  . c  o  m*/
}

From source file:org.syncany.tests.integration.scenarios.ChangedAttributesScenarioTest.java

@Test
public void testNewFileWithDifferingAttributes() throws Exception {
    // Setup /*from  w w w  . j av a 2 s  .co m*/
    TransferSettings testConnection = TestConfigUtil.createTestLocalConnection();
    TestClient clientA = new TestClient("A", testConnection);
    TestClient clientB = new TestClient("B", testConnection);

    // Create new file with differing attributes
    clientA.createNewFile("file1.jpg");
    FileUtils.copyFile(clientA.getLocalFile("file1.jpg"), clientB.getLocalFile("file1.jpg"));

    File aFile = clientA.getLocalFile("file1.jpg"); // Client B's attributes differ!
    Path aFilePath = Paths.get(aFile.getAbsolutePath());

    Object aReadOnlyAttribute = null;
    Set<PosixFilePermission> aPosixFilePermissions = null;

    File bFile = clientB.getLocalFile("file1.jpg"); // Client B's attributes differ!
    Path bFilePath = Paths.get(bFile.getAbsolutePath());

    if (EnvironmentUtil.isWindows()) {
        aReadOnlyAttribute = Files.getAttribute(aFilePath, "dos:readonly");
        Files.setAttribute(bFilePath, "dos:readonly", true);
    } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
        aPosixFilePermissions = Files.getPosixFilePermissions(aFilePath);
        Files.setPosixFilePermissions(bFilePath, PosixFilePermissions.fromString("rwxrwxrwx"));
    }

    clientA.upWithForceChecksum();
    DownOperationResult downResult = clientB.down(); // This is the key operation 

    // Test 1: Check result sets for inconsistencies
    assertTrue("File should be downloaded.", downResult.getChangeSet().hasChanges());

    // Test 2: file1.jpg permissions (again!
    if (EnvironmentUtil.isWindows()) {
        Object bReadOnlyAttribute = Files.getAttribute(aFilePath, "dos:readonly");
        assertEquals("Read-only should be true.", aReadOnlyAttribute, bReadOnlyAttribute);
    } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
        Set<PosixFilePermission> bPosixFilePermissions = Files.getPosixFilePermissions(aFilePath);
        assertEquals("Should be rwxrwxrwx.", PosixFilePermissions.toString(aPosixFilePermissions),
                PosixFilePermissions.toString(bPosixFilePermissions));
    }

    // Test 3: The rest
    assertFileListEquals(clientA.getLocalFilesExcludeLockedAndNoRead(),
            clientB.getLocalFilesExcludeLockedAndNoRead());
    assertSqlDatabaseEquals(clientA.getDatabaseFile(), clientB.getDatabaseFile());

    // Tear down
    clientA.deleteTestData();
    clientB.deleteTestData();
}

From source file:com.spectralogic.ds3client.metadata.MetadataReceivedListenerImpl_Test.java

@Test
public void testGettingMetadataFailureDoesntThrow() throws IOException, InterruptedException {
    Assume.assumeFalse(Platform.isWindows());

    try {/*  w  ww.j a va 2 s.  c  o  m*/
        final String tempPathPrefix = null;
        final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

        final String fileName = "Gracie.txt";

        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        try {
            // set permissions
            if (!Platform.isWindows()) {
                final PosixFileAttributes attributes = Files.readAttributes(filePath,
                        PosixFileAttributes.class);
                final Set<PosixFilePermission> permissions = attributes.permissions();
                permissions.clear();
                permissions.add(PosixFilePermission.OWNER_READ);
                permissions.add(PosixFilePermission.OWNER_WRITE);
                Files.setPosixFilePermissions(filePath, permissions);
            }

            // get permissions
            final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
            fileMapper.put(filePath.toString(), filePath);
            final Map<String, String> metadataFromFile = new MetadataAccessImpl(fileMapper.build())
                    .getMetadataValue(filePath.toString());

            FileUtils.deleteDirectory(tempDirectory.toFile());

            // put old permissions back
            final Metadata metadata = new MetadataImpl(new MockedHeadersReturningKeys(metadataFromFile));

            new MetadataReceivedListenerImpl(tempDirectory.toString()).metadataReceived(fileName, metadata);
        } finally {
            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    } catch (final Throwable t) {
        fail("Throwing exceptions from metadata est verbotten");
    }
}

From source file:org.apache.hadoop.yarn.server.security.CertificateLocalizationService.java

@Override
protected void serviceInit(Configuration conf) throws Exception {
    parseSuperuserMaterial(conf);//w w w . ja  v  a 2 s .com
    String localizationDir = service.toString() + "_" + LOCALIZATION_DIR_NAME;
    materializeDir = Paths.get(SYSTEM_TMP, localizationDir);
    File fileMaterializeDir = materializeDir.toFile();
    if (!fileMaterializeDir.exists()) {
        fileMaterializeDir.mkdir();
        Set<PosixFilePermission> materializeDirPerm;
        if (service == ServiceType.NM) {
            // the nm user should have full access to the directory, everyone else should have only execute access
            // to traverse the directory
            materializeDirPerm = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
                    PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_EXECUTE,
                    PosixFilePermission.OTHERS_EXECUTE);
        } else {
            // Only the rm user should access to this directory
            materializeDirPerm = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
                    PosixFilePermission.OWNER_EXECUTE);
        }
        Files.setPosixFilePermissions(materializeDir, materializeDirPerm);
    }

    LOG.debug("Initialized at dir: " + materializeDir.toString());

    super.serviceInit(conf);
}

From source file:com.playonlinux.core.utils.archive.Tar.java

/**
 * Uncompress a tar//from  w w w  .j a  va 2s.  c o  m
 *
 * @param countingInputStream
 *            to count the number of byte extracted
 * @param outputDir
 *            The directory where files should be extracted
 * @return A list of extracted files
 * @throws ArchiveException
 *             if the process fails
 */
private List<File> uncompress(final InputStream inputStream, CountingInputStream countingInputStream,
        final File outputDir, long finalSize, Consumer<ProgressEntity> stateCallback) {
    final List<File> uncompressedFiles = new LinkedList<>();
    try (ArchiveInputStream debInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
            inputStream)) {
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                LOGGER.info(String.format("Attempting to write output directory %s.",
                        outputFile.getAbsolutePath()));

                if (!outputFile.exists()) {
                    LOGGER.info(String.format("Attempting to createPrefix output directory %s.",
                            outputFile.getAbsolutePath()));
                    Files.createDirectories(outputFile.toPath());
                }
            } else {
                LOGGER.info(String.format("Creating output file %s (%s).", outputFile.getAbsolutePath(),
                        entry.getMode()));

                if (entry.isSymbolicLink()) {
                    Files.createSymbolicLink(Paths.get(outputFile.getAbsolutePath()),
                            Paths.get(entry.getLinkName()));
                } else {
                    try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) {
                        IOUtils.copy(debInputStream, outputFileStream);

                        Files.setPosixFilePermissions(Paths.get(outputFile.getPath()),
                                com.playonlinux.core.utils.Files.octToPosixFilePermission(entry.getMode()));
                    }
                }

            }
            uncompressedFiles.add(outputFile);

            stateCallback.accept(new ProgressEntity.Builder()
                    .withPercent((double) countingInputStream.getCount() / (double) finalSize * (double) 100)
                    .withProgressText("Extracting " + outputFile.getName()).build());

        }
        return uncompressedFiles;
    } catch (IOException | org.apache.commons.compress.archivers.ArchiveException e) {
        throw new ArchiveException("Unable to extract the file", e);
    }
}