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.athena.peacock.common.core.action.FileWriteAction.java

@Override
public String perform() {
    String result = fileName;//w w  w .  jav  a 2s  .  c om

    try {
        String separator = File.separator;

        fileName = fileName.replaceAll("\\\\", separator);

        String path = fileName.substring(0, fileName.lastIndexOf(separator));
        String name = fileName.substring(fileName.lastIndexOf(separator) + 1);

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream fos = new FileOutputStream(new File(path, name));

        if (StringUtils.isNotEmpty(permission)) {
            Files.setPosixFilePermissions(Paths.get(fileName), PosixFilePermissions.fromString(permission));
        }

        IOUtils.write(contents, fos, "UTF-8");
        IOUtils.closeQuietly(fos);

        result += " saved.\n";
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException has occurred. : ", e);
        result += " does not saved.\n";
    } catch (IOException e) {
        logger.error("IOException has occurred. : ", e);
        result += " does not saved.\n";
    }

    return result;
}

From source file:net.spinetrak.rpitft.command.Command.java

private String init(final String script_) {
    final String VAR_TMP = "/var/tmp";
    InputStream scriptIn = null;/*from  w  w  w .  j a va 2s . co m*/
    OutputStream scriptOut = null;
    final File script = new File(VAR_TMP + script_);
    final String dir = script.getParent();
    if (null != dir) {
        if (!new File(dir).mkdirs()) {
            LOGGER.error("Unable to create dirs for " + dir);
        }
    }
    try {
        scriptIn = Command.class.getResourceAsStream(script_);
        scriptOut = new FileOutputStream(script);

        IOUtils.copy(scriptIn, scriptOut);

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

        Files.setPosixFilePermissions(Paths.get(script.getAbsolutePath()), perms);
    } catch (final IOException ex_) {
        LOGGER.error(ex_.getMessage());
    } finally {
        if (scriptIn != null) {
            try {
                scriptIn.close();
            } catch (final IOException ex_) {
                LOGGER.error(ex_.getMessage());
            }
        }
        if (scriptOut != null) {
            try {
                scriptOut.close();
            } catch (final IOException ex_) {
                LOGGER.error(ex_.getMessage());
            }
        }
    }
    return script.getAbsolutePath();
}

From source file:net.sourceforge.jencrypt.FileEncrypter.java

/**
 * Modify file/folder permissions.//from   w  w w .j  a v  a2s . com
 * 
 * @param file
 * @param permissions
 * @throws IOException
 */
private void setPosixFilePermissions(File file, Set<PosixFilePermission> permissions) throws IOException {
    // Convert File object to Path and call Files.setPosixFilePermissions().
    Files.setPosixFilePermissions(Paths.get(file.getAbsolutePath()), permissions);
}

From source file:net.krotscheck.util.ResourceUtilTest.java

/**
 * Assert that we can read a resource as a string.
 *
 * @throws Exception Should not be thrown.
 *///from  w  w w.  j  a va 2s.c  o  m
@Test
public void testGetResourceAsString() throws Exception {
    String name = "/valid-resource-file.txt";
    String content = ResourceUtil.getResourceAsString(name);

    Assert.assertEquals("valid resource content", content);

    String invalidName = "/invalid-resource-file.txt";
    String invalidContent = ResourceUtil.getResourceAsString(invalidName);

    Assert.assertEquals("", invalidContent);

    // Make the file write only
    File resource = ResourceUtil.getFileForResource(name);
    Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(resource.toPath());
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    // Write only...
    Files.setPosixFilePermissions(resource.toPath(), perms);
    String writeOnlyName = "/valid-resource-file.txt";
    String writeOnlyContent = ResourceUtil.getResourceAsString(writeOnlyName);
    Assert.assertEquals("", writeOnlyContent);

    Files.setPosixFilePermissions(resource.toPath(), oldPerms);

}

From source file:org.springframework.boot.loader.tools.JarWriter.java

private void setExecutableFilePermission(File file) {
    try {/*from   w w  w  . j av a  2  s.c  om*/
        Path path = file.toPath();
        Set<PosixFilePermission> permissions = new HashSet<>(Files.getPosixFilePermissions(path));
        permissions.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(path, permissions);
    } catch (Throwable ex) {
        // Ignore and continue creating the jar
    }
}

From source file:com.twosigma.beaker.r.rest.RShellRest.java

private 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 (!windows()) {
        Set<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(tmp.toPath(), perms);
    }// w w w.j av a  2 s . c  o m
    return tmp.getAbsolutePath();
}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void chmodReadOnly(@Nonnull Path path) throws RuntimeIOException {

    SimpleFileVisitor<Path> setReadOnlyFileVisitor = new SimpleFileVisitor<Path>() {
        @Override/*from   w w  w.j av  a2  s.  co m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (Files.isDirectory(file)) {
                throw new IllegalStateException("no dir expected here");
            } else {
                Files.setPosixFilePermissions(file, PERMISSION_R);
            }
            return super.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Files.setPosixFilePermissions(dir, PERMISSION_RX);
            return super.preVisitDirectory(dir, attrs);
        }
    };
    try {
        Files.walkFileTree(path, setReadOnlyFileVisitor);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception changing permissions to readonly for " + path, e);
    }
}

From source file:net.krotscheck.jersey2.configuration.Jersey2ToolkitConfigTest.java

/**
 * Assert that an unreadable file does not throw an error.
 *
 * @throws java.io.IOException File operation errors.
 *///from  w ww .  j a v  a 2s .  com
@Test
public void testUnreadableFile() throws IOException {
    // Get the prop file and store the old permissions.
    File propFile = ResourceUtil.getFileForResource("jersey2-toolkit.properties");

    Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(propFile.toPath());

    // Apply writeonly permission set.
    Set<PosixFilePermission> writeonly = new HashSet<>();
    writeonly.add(PosixFilePermission.OWNER_WRITE);
    writeonly.add(PosixFilePermission.GROUP_WRITE);
    Files.setPosixFilePermissions(propFile.toPath(), writeonly);

    // Add something to check
    System.setProperty("property3", "override3");

    // If this throws an error, we've got a problem.
    Configuration config = new Jersey2ToolkitConfig();
    Assert.assertFalse(config.containsKey("property1"));
    Assert.assertFalse(config.containsKey("property2"));
    Assert.assertTrue(config.containsKey("property3"));

    // Apply the correct permissions again
    Files.setPosixFilePermissions(propFile.toPath(), oldPerms);
}

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

@Benchmark
public void createFileJava7SetDefaultPermission(Blackhole blackhole) throws IOException {
    Path file = Files.createFile(tempDirPath.resolve("file-" + counter.incrementAndGet()));
    Files.setPosixFilePermissions(file, DEFAULT_JAVA7_FILE_PERMISSIONS);
    blackhole.consume(file);//ww  w .j  a  v a 2 s .  c  o m
}

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

@Test
public void testIssue76() throws Exception {
    /*//from   w w w .  ja v a 2 s . c  o  m
     * If two clients create the same file at the same time, different multichunks will contain the same chunks. This lead to issue 76.
     */

    // Setup
    LocalTransferSettings testConnection = (LocalTransferSettings) TestConfigUtil.createTestLocalConnection();

    TestClient clientA = new TestClient("A", testConnection);
    TestClient clientB = new TestClient("B", testConnection);

    UpOperationOptions upOperationOptionsWithForce = new UpOperationOptions();
    upOperationOptionsWithForce.setForceUploadEnabled(true);

    // Client A creates some files
    clientA.getLocalFile("sphinxbase-0.8").mkdirs();
    clientA.getLocalFile("sphinxbase-0.8/win32/sphinx_jsgf2fsg").mkdirs();
    clientA.getLocalFile("sphinxbase-0.8/src/sphinx_adtools").mkdirs();

    clientA.createNewFile("sphinxbase-0.8/config.sub");
    clientA.createNewFile("sphinxbase-0.8/win32/sphinx_jsgf2fsg/sphinx_jsgf2fsg.vcxproj");
    clientA.createNewFile("sphinxbase-0.8/src/sphinx_adtools/sphinx_pitch.c");

    // Client B creates the exact SAME FILES (here: copies the file tree from A)
    FileUtils.copyDirectory(clientA.getLocalFile("sphinxbase-0.8"), clientB.getLocalFile("sphinxbase-0.8"),
            true);

    // Now, both upload that
    UpOperationResult upResultA = clientA.upWithForceChecksum(); // (A1)
    assertEquals(UpResultCode.OK_CHANGES_UPLOADED, upResultA.getResultCode());
    assertEquals(8, upResultA.getChangeSet().getNewFiles().size());

    UpOperationResult upResultB = clientB.up(upOperationOptionsWithForce); // (B1)
    assertEquals(UpResultCode.OK_CHANGES_UPLOADED, upResultB.getResultCode());
    assertEquals(8, upResultB.getChangeSet().getNewFiles().size());

    DownOperationResult downResultA = clientA.down();
    assertEquals(DownResultCode.OK_NO_REMOTE_CHANGES, downResultA.getResultCode());
    assertEquals(0, downResultA.getDirtyDatabasesCreated().size());
    assertEquals(false, downResultA.getChangeSet().hasChanges());

    // For peaking (does NOT affect the test)
    FileUtils.copyFile(new File(testConnection.getPath(), "databases/database-B-0000000001"),
            new File(testConnection.getPath(), "databases/TEMP_db-B-0000000001"));

    DownOperationResult downResultB = clientB.down(); // creates DIRTY; deletes (B1)
    assertEquals(DownResultCode.OK_WITH_REMOTE_CHANGES, downResultB.getResultCode());
    assertEquals(1, downResultB.getDirtyDatabasesCreated().size());
    assertEquals(false, downResultB.getChangeSet().hasChanges()); // TODO [low] Shouldn't this be 'true'?

    // For peaking (does NOT affect the test)
    FileUtils.copyDirectory(clientB.getLocalFile(".syncany/db"),
            clientB.getLocalFile(".syncany/db_WITH_DIRTY_B1"));

    Files.setPosixFilePermissions(clientB.getLocalFile("sphinxbase-0.8").toPath(),
            PosixFilePermissions.fromString("rwxrwxrwx"));
    UpOperationResult upResultB2 = clientB.up(); // (B2)
    assertEquals(UpResultCode.OK_CHANGES_UPLOADED, upResultB2.getResultCode());
    assertEquals(1, upResultB2.getChangeSet().getChangedFiles().size());

    // For peaking (does NOT affect the test)
    FileUtils.copyDirectory(clientB.getLocalFile(".syncany/db"),
            clientB.getLocalFile(".syncany/db_DELETED_B1_WITH_B2"));

    clientA.down();

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