Example usage for java.nio.file.attribute PosixFilePermissions fromString

List of usage examples for java.nio.file.attribute PosixFilePermissions fromString

Introduction

In this page you can find the example usage for java.nio.file.attribute PosixFilePermissions fromString.

Prototype

public static Set<PosixFilePermission> fromString(String perms) 

Source Link

Document

Returns the set of permissions corresponding to a given String representation.

Usage

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

@Test
public void testChangeAttributes() throws Exception {
    // Setup /* w  w w  .  j a v a  2 s. c om*/
    TransferSettings testConnection = TestConfigUtil.createTestLocalConnection();
    TestClient clientA = new TestClient("A", testConnection);
    TestClient clientB = new TestClient("B", testConnection);

    // Run 
    clientA.createNewFile("file1.jpg");
    clientA.upWithForceChecksum();

    clientB.down();

    File bFile = clientB.getLocalFile("file1.jpg");
    Path bFilePath = Paths.get(bFile.getAbsolutePath());

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

    StatusOperationResult statusResult = clientB.status();
    assertNotNull(statusResult);

    ChangeSet changes = statusResult.getChangeSet();

    assertTrue("Status-Operation should return changes.", changes.hasChanges());
    UpOperationResult upResult = clientB.up();
    StatusOperationResult statusResultFromUp = upResult.getStatusResult();

    // Test 1: Check result sets for inconsistencies
    assertTrue("Status should return changes.", statusResultFromUp.getChangeSet().hasChanges());
    assertTrue("File should be uploaded.", upResult.getChangeSet().hasChanges());

    // Test 2: Check database for inconsistencies
    SqlDatabase database = clientB.loadLocalDatabase();

    assertEquals("File should be uploaded.", 1,
            database.getFileList("file1.jpg", null, false, false, false, null).size());
    assertEquals("There should be a new database version, because file should not have been added.", 2,
            database.getLocalDatabaseBranch().size());

    // B down
    clientA.down();

    // Test 1: file1.jpg permissions
    File aFile = clientA.getLocalFile("file1.jpg");
    Path aFilePath = Paths.get(aFile.getAbsolutePath());

    if (EnvironmentUtil.isWindows()) {
        Object readOnlyAttribute = Files.getAttribute(aFilePath, "dos:readonly");
        assertTrue("Read-only should be true.", (Boolean) readOnlyAttribute);
    } else if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
        Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(aFilePath);
        assertEquals("Should be rwxrwxrwx.", "rwxrwxrwx", PosixFilePermissions.toString(posixFilePermissions));
    }

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

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

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;//w w w. jav  a2 s .c  o m
    if (!f.exists()) {
        read = true;
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()),
                    PosixFilePermissions.fromString("rw-------"));
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error writing empty config.yml!");
        }
    }

    Map<String, Object> config;

    if (read) {
        Console console = System.console();
        console.printf("Nick: \n->");
        nick = console.readLine();
        console.printf("\nPassword: \n-|");
        pass = new String(console.readPassword());
        console.printf("\nServer: \n->");
        server = console.readLine();
        console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->");
        channels = Arrays.asList(console.readLine().split(","));
        System.out.println("Fetching max XKCD...");
        maxXKCD = fetchMaxXKCD();
        System.out.println("Fetched.");
        cachedUTC = System.currentTimeMillis();

        dadLeaveTimes = new HashMap<>();
        noVoiceNicks = new HashSet<>();

        writeConfig();
        System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath());

    } else {
        try (FileInputStream fis = new FileInputStream(f)) {
            Yaml y = new Yaml();
            config = y.loadAs(fis, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error parsing config!");
            return;
        }

        nick = (String) config.get("nick");
        pass = (String) config.get("password");
        server = (String) config.get("server");
        channels = (List<String>) config.get("channels");
        maxXKCD = (Integer) config.get("cachedMaxXKCD");
        cachedUTC = (Long) config.get("cachedUTC");
        noVoiceNicks = (Set<String>) config.get("noVoiceNicks");
        masters = (Set<String>) config.get("masters");
        if (masters == null) {
            masters = new HashSet<>();
            masters.add("Everdras");
        }

        if (noVoiceNicks == null)
            noVoiceNicks = new HashSet<>();

        noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s));
        masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s));

        if (checkXKCDUpdate())
            writeConfig();
        else
            System.out.println("Loaded cached XKCD.");

        Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes");
        dadLeaveTimes = new HashMap<>();
        if (serialDadLeaveTimes != null)
            serialDadLeaveTimes.keySet().stream().forEach((time) -> {
                dadLeaveTimes.put(LocalDate.parse(time),
                        LocalTime.parse((String) serialDadLeaveTimes.get(time)));
            });

    }
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();//from   ww  w.  ja  v a 2 s  .  com
    this.executor = Executors.newCachedThreadPool();
    this.clients = new ConcurrentLinkedDeque<>();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.idleTimeout = new AtomicReference<>();
}

From source file:com.kamike.misc.FsUtils.java

public static void createDirectory(String dstPath) {

    Properties props = System.getProperties(); //    
    String osName = props.getProperty("os.name"); //???   
    Path newdir = FileSystems.getDefault().getPath(dstPath);

    boolean pathExists = Files.exists(newdir, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
    if (!pathExists) {
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
        try {//from   w w  w  . j ava2s  . co  m
            if (!osName.contains("Windows")) {
                Files.createDirectories(newdir, attr);
            } else {
                Files.createDirectories(newdir);
            }
        } catch (Exception e) {
            System.err.println(e);

        }
    }
}

From source file:com.athena.peacock.common.core.action.FileWriteAction.java

@Override
public String perform() {
    String result = fileName;/*from w  w  w  . ja v a  2  s  .co m*/

    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:com.dowdandassociates.gentoo.bootstrap.DefaultKeyPairInformation.java

@PostConstruct
private void setup() {
    boolean nameSet = (null != name);
    boolean filenameSet = (null != filename);
    boolean keyExists = false;
    if (nameSet) {
        log.info("Checking if key pair \"" + name + "\" exists");
        keyExists = !(ec2Client//w w  w .  ja va2 s . com
                .describeKeyPairs(new DescribeKeyPairsRequest()
                        .withFilters(new Filter().withName("key-name").withValues(name)))
                .getKeyPairs().isEmpty());
    }

    if (keyExists && !filenameSet) {
        log.warn("Key pair \"" + name + "\" exists, but private key location is not specified");
        keyExists = false;
    }

    if (!keyExists) {
        if (!nameSet) {
            name = "gentoo-bootstrap-"
                    + DateFormatUtils.formatUTC(System.currentTimeMillis(), "yyyyMMdd'T'HHmmssSSS'Z'");
        }

        if (!filenameSet) {
            try {
                filename = Files
                        .createTempFile(name, ".pem",
                                PosixFilePermissions
                                        .asFileAttribute(PosixFilePermissions.fromString("rw-------")))
                        .toString();
            } catch (IOException ioe) {
                log.warn("Cannot create temp file", ioe);
                filename = name + ".pem";
            }
        }

        log.info("Creating key pair \"" + name + "\"");

        CreateKeyPairResult createResult = ec2Client
                .createKeyPair(new CreateKeyPairRequest().withKeyName(name));

        try {
            log.info("Saving pem file to \"" + filename + "\"");

            BufferedWriter outfile = new BufferedWriter(new FileWriter(filename));

            try {
                outfile.write(createResult.getKeyPair().getKeyMaterial());
            } catch (IOException ioe) {
                String message = "Error writing to file \"" + filename + "\"";
                log.error(message, ioe);
                throw new RuntimeException(message, ioe);
            } finally {
                outfile.close();
            }
        } catch (IOException ioe) {
            String message = "Error opening file \"" + filename + "\"";
            log.error(message, ioe);
            throw new RuntimeException(message, ioe);
        }

        builtKeyPair = true;

        log.info("Key pair \"" + name + "\" built");
    } else {
        builtKeyPair = false;
        log.info("Key pair \"" + name + "\" exists");
    }

    if (filename.startsWith("~" + File.separator)) {
        filename = System.getProperty("user.home") + filename.substring(1);
    }
}

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

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    final long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // 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("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);/*from  ww  w  .  j a va 2 s  .  c  o m*/
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:com.cloudera.livy.rsc.driver.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();/*from  ww  w . j a va2  s. co m*/
    this.executor = Executors.newCachedThreadPool();
    this.jobQueue = new LinkedList<>();
    this.clients = new ConcurrentLinkedDeque<>();
    this.serializer = new Serializer();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.activeJobs = new ConcurrentHashMap<>();
    this.bypassJobs = new ConcurrentLinkedDeque<>();
    this.idleTimeout = new AtomicReference<>();
}

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

@Test
public void testIssue76() throws Exception {
    /*//from w w w  . ja  v a 2s . co  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();
}

From source file:jenkins.plugins.pbs.tasks.Qsub.java

public Boolean call() {
    final String myLogBasename = (logBasename.length() > 0) ? logBasename : System.getenv("java.io.tmpdir");

    try {/*from ww w  .  j  a v  a 2  s  .c  o  m*/
        // If we are running as another user, we are going to make sure we
        // set permissions more loosely
        Path tmpDir = Files.createTempDirectory(Paths.get(myLogBasename), "jenkinsPBS_");
        File tmpDirFile = tmpDir.toFile();
        if (!tmpDirFile.exists()) {
            if (!tmpDirFile.mkdirs()) {
                listener.getLogger().println("Failed to create working directory: " + tmpDir.toString());
                throw new PBSException("Failed to create working directory: " + tmpDir.toString());
            }
        }

        this.executionDirectory = tmpDir.toString();
        if (this.runUser.length() > 0) {
            Files.setPosixFilePermissions(Paths.get(this.executionDirectory),
                    PosixFilePermissions.fromString("rwxrwxrwx"));
        }
        listener.getLogger()
                .println(String.format("Created working directory '%s' with permissions '%s'",
                        this.executionDirectory, PosixFilePermissions
                                .toString(Files.getPosixFilePermissions(Paths.get(this.executionDirectory)))));
    } catch (IOException e) {
        listener.fatalError(e.getMessage(), e);
        throw new PBSException("Failed to create working directory: " + e.getMessage(), e);
    }

    if (StringUtils.isNotBlank(logHostname)) {
        this.errFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "err"));
        this.outFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "out"));
    } else {
        this.errFileName = Paths.get(this.executionDirectory, "err").toString();
        this.outFileName = Paths.get(this.executionDirectory, "out").toString();
    }

    OutputStream tmpScriptOut = null;
    try {
        Path tmpScript = Paths.get(this.executionDirectory, "script");
        tmpScriptOut = Files.newOutputStream(tmpScript);
        tmpScriptOut.write(script.getBytes());
        tmpScriptOut.flush();

        listener.getLogger().println("PBS script: " + tmpScript.toString());
        String[] argList;
        if (this.runUser.length() > 0) {
            argList = new String[] { "-P", this.runUser, "-e", this.errFileName, "-o", this.outFileName,
                    tmpScript.toString(), "-W", "umask=022" };
        } else {
            argList = new String[] { "-e", this.errFileName, "-o", this.outFileName, tmpScript.toString() };
        }
        String jobId = PBS.qsub(argList, this.environment);

        listener.getLogger().println("PBS Job submitted: " + jobId);

        return this.seekEnd(jobId, numberOfDays, span);
    } catch (IOException e) {
        e.printStackTrace(listener.getLogger());
        throw new PBSException("Failed to create temp script");
    } finally {
        IOUtils.closeQuietly(tmpScriptOut);
    }
}