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

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

Introduction

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

Prototype

public static String toString(Set<PosixFilePermission> perms) 

Source Link

Document

Returns the String representation of a set of permissions.

Usage

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 {//  ww w. j a v  a2  s . co 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);
    }
}

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

@Test
public void restorePermissions() throws Exception {
    final PosixFileAttributes fileAttributes = Files.readAttributes(file.toPath(), PosixFileAttributes.class);
    final String permissionsOctal = getPermissionInOctal(
            PosixFilePermissions.toString(fileAttributes.permissions()));
    final BasicHeader basicHeader[] = new BasicHeader[1];
    basicHeader[0] = new BasicHeader(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_PERMISSION,
            permissionsOctal);/*from   w  ww . j  a v  a 2s.com*/
    final Metadata metadata = genMetadata(basicHeader);
    final PosixMetadataRestore posixMetadataRestore = new PosixMetadataRestore(metadata, file.getPath(),
            MetaDataUtil.getOS());
    posixMetadataRestore.restorePermissions();
    final PosixFileAttributes fileAttributesAfterRestore = Files.readAttributes(file.toPath(),
            PosixFileAttributes.class);
    Assert.assertEquals(
            getPermissionInOctal(PosixFilePermissions.toString(fileAttributesAfterRestore.permissions())),
            basicHeader[0].getValue());
}

From source file:org.apache.logging.log4j.core.appender.FileAppenderPermissionsTest.java

@Test
public void testFilePermissionsAPI() throws Exception {
    final File file = new File(DIR, "AppenderTest-" + fileIndex + ".log");
    final Path path = file.toPath();
    final Layout<String> layout = PatternLayout.newBuilder()
            .withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build();
    // @formatter:off
    final FileAppender appender = FileAppender.newBuilder().withFileName(file.getAbsolutePath())
            .withName("test").withImmediateFlush(false).withIgnoreExceptions(false).withBufferedIo(false)
            .withBufferSize(1).withLayout(layout).withCreateOnDemand(createOnDemand)
            .withFilePermissions(filePermissions).build();
    // @formatter:on
    try {/*from  w w  w.ja  v a  2 s.c om*/
        appender.start();
        assertTrue("Appender did not start", appender.isStarted());
        Assert.assertNotEquals(createOnDemand, Files.exists(path));
        long curLen = file.length();
        long prevLen = curLen;
        assertTrue("File length: " + curLen, curLen == 0);
        for (int i = 0; i < 100; ++i) {
            final LogEvent event = Log4jLogEvent.newBuilder().setLoggerName("TestLogger") //
                    .setLoggerFqcn(FileAppenderPermissionsTest.class.getName()).setLevel(Level.INFO) //
                    .setMessage(new SimpleMessage("Test")).setThreadName(this.getClass().getSimpleName()) //
                    .setTimeMillis(System.currentTimeMillis()).build();
            try {
                appender.append(event);
                curLen = file.length();
                assertTrue("File length: " + curLen, curLen > prevLen);
                // Give up control long enough for another thread/process to occasionally do something.
                Thread.sleep(25);
            } catch (final Exception ex) {
                throw ex;
            }
            prevLen = curLen;
        }
        assertEquals(filePermissions, PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
    } finally {
        appender.stop();
    }
    assertFalse("Appender did not stop", appender.isStarted());
}

From source file:VOBackupFile.java

/**
 * Wrapper for metadata of backuped file.
 *
 * @param file backuped file//  ww  w .  j ava2  s  .  c o m
 */
public VOBackupFile(File file) {
    this.path = file.getAbsolutePath();
    this.directory = file.isDirectory();
    this.symLink = Files.isSymbolicLink(file.toPath());

    this.size = ((file.isDirectory() || symLink) ? 0 : file.length());
    this.modify = new Date(file.lastModified());

    if (symLink) {
        try {
            symlinkTarget = Files.readSymbolicLink(file.toPath()).toString();
        } catch (IOException e) {
            e.printStackTrace(); //TODO Lebeda - oetit do logu
        }
    } else {
        // advanced attributes

        try {

            owner = Files.getOwner(file.toPath(), LinkOption.NOFOLLOW_LINKS).getName();

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class)) {
                dosAttr = Boolean.TRUE;
                final DosFileAttributes dosFileAttributes = Files.readAttributes(file.toPath(),
                        DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);

                dosArchive = dosFileAttributes.isArchive();
                dosHidden = dosFileAttributes.isHidden();
                dosSystem = dosFileAttributes.isSystem();
                dosReadOnly = dosFileAttributes.isReadOnly();
            } else {
                dosAttr = Boolean.FALSE;
            }

            if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)) {
                posixAttr = Boolean.TRUE;
                final PosixFileAttributes posixFileAttributes = Files.readAttributes(file.toPath(),
                        PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
                posixGroup = posixFileAttributes.group().getName();
                posixPermitions = PosixFilePermissions.toString(posixFileAttributes.permissions());
            } else {
                posixAttr = Boolean.FALSE;
            }

        } catch (IOException e) {
            e.printStackTrace(); //Todo implementovat
        }
    }

}

From source file:org.fim.command.ResetFileAttributesCommand.java

private boolean resetPosixPermissions(Path file, FileState fileState, PosixFileAttributes posixFileAttributes)
        throws IOException {
    String permissions = PosixFilePermissions.toString(posixFileAttributes.permissions());
    String previousPermissions = getAttribute(fileState, FileAttribute.PosixFilePermissions);
    if (previousPermissions != null && !Objects.equals(permissions, previousPermissions)) {
        Set<PosixFilePermission> permissionSet = PosixFilePermissions.fromString(previousPermissions);
        Files.getFileAttributeView(file, PosixFileAttributeView.class).setPermissions(permissionSet);
        System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions,
                previousPermissions);//from   w ww. j  a v  a2 s .c  o  m
        return true;
    }
    return false;
}

From source file:org.application.backupsync.PathName.java

public JSONObject getAttrs() throws IOException, JSONException {
    JSONObject result;/*from www .j  av a 2  s  .c o m*/
    BasicFileAttributes attr;
    DosFileAttributes dosAttr;
    PosixFileAttributes posixAttr;

    result = new JSONObject();
    attr = Files.readAttributes(this.path, BasicFileAttributes.class);

    result.append("ctime", attr.creationTime().toMillis());
    result.append("mtime", attr.lastModifiedTime().toMillis());
    //result.append("symlink", attr.isSymbolicLink()); //Redundant
    result.append("size", attr.size());

    if (System.getProperty("os.name").startsWith("Windows")) {
        dosAttr = Files.readAttributes(this.path, DosFileAttributes.class);

        result.append("dos:archive", dosAttr.isArchive());
        result.append("dos:hidden", dosAttr.isHidden());
        result.append("dos:readonly", dosAttr.isReadOnly());
        result.append("dos:system", dosAttr.isSystem());
    } else {
        posixAttr = Files.readAttributes(this.path, PosixFileAttributes.class);

        result.append("posix:symlink", posixAttr.isSymbolicLink());
        result.append("posix:owner", posixAttr.owner());
        result.append("posix:group", posixAttr.group());
        result.append("posix:permission", PosixFilePermissions.toString(posixAttr.permissions()));
    }

    return result;
}

From source file:org.apache.usergrid.chop.client.ssh.Job.java

private void executeScp(SCPCommand command, Session session, ResponseInfo response) {
    Channel channel = null;/* w  ww .ja v  a 2  s.  co  m*/
    FileInputStream fis = null;
    OutputStream out = null;
    InputStream in = null;
    String message;
    try {
        // exec 'scp -t destFile' remotely
        String exec = "scp -t " + command.getDestinationFilePath();
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(exec);

        // get I/O streams for remote scp
        out = channel.getOutputStream();
        in = channel.getInputStream();

        channel.connect();

        if ((message = Utils.checkAck(in)) != null) {
            response.addErrorMessage(message);
            return;
        }

        File srcFile = new File(command.getSourceFilePath());

        // send "C0<filemode> filesize filename", where filename should not include '/'
        StringBuilder sb = new StringBuilder();
        String fileMode = PosixFilePermissions.toString(Files.getPosixFilePermissions(srcFile.toPath()));
        long filesize = srcFile.length();
        exec = sb.append("C0").append(Utils.convertToNumericalForm(fileMode)).append(" ").append(filesize)
                .append(" ").append(srcFile.getName()).append("\n").toString();

        out.write(exec.getBytes());
        out.flush();

        if ((message = Utils.checkAck(in)) != null) {
            response.addErrorMessage(message);
            return;
        }

        // send the content of source file
        fis = new FileInputStream(command.getSourceFilePath());
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0) {
                break;
            }
            out.write(buf, 0, len);
        }

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();

        if ((message = Utils.checkAck(in)) != null) {
            response.addErrorMessage(message);
        }
    } catch (Exception e) {
        message = "Error while sending file to " + value.getPublicIpAddress();
        LOG.warn(message, e);
        response.addErrorMessage(message);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
        }
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception e) {
        }
    }
}

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

@Test
public void testNewFileWithDifferingAttributes() throws Exception {
    // Setup /*from ww  w . ja v a  2  s. c  o 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:io.hops.hopsworks.common.security.CertificatesMgmService.java

@PostConstruct
public void init() {
    masterPasswordFile = new File(settings.getHopsworksMasterEncPasswordFile());
    if (!masterPasswordFile.exists()) {
        throw new IllegalStateException("Master encryption file does not exist");
    }/*from w ww  .  ja v  a2  s  . co  m*/

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

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

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

        // Permissions should be 700
        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(filePermissions);
            LOG.log(Level.INFO, "Passed permissions check for file " + masterPasswordFile.getAbsolutePath()
                    + ". Owner: " + owner + " Group: " + group + " Permissions: " + permStr);
        } else {
            throw new IllegalStateException("Wrong permissions for file " + masterPasswordFile.getAbsolutePath()
                    + ", it should be 700");
        }

    } catch (UnsupportedOperationException ex) {
        LOG.log(Level.WARNING,
                "Associated filesystem is not POSIX compliant. "
                        + "Continue without checking the permissions of " + masterPasswordFile.getAbsolutePath()
                        + " This might be a security problem.");
    } catch (IOException ex) {
        throw new IllegalStateException(
                "Error while getting POSIX permissions of " + masterPasswordFile.getAbsolutePath());
    }

    // Register handlers when master encryption password changes
    MasterPasswordChangeHandler<CertsFacade> psUserCertsHandler = new PSUserCertsMasterPasswordHandler(
            userFacade);
    psUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(UserCerts.class, psUserCertsHandler);

    MasterPasswordChangeHandler<CertsFacade> pgUserCertsHandler = new PGUserCertsMasterPasswordHandler(
            projectFacade);
    pgUserCertsHandler.setFacade(certsFacade);
    registerMasterPasswordChangeHandler(ProjectGenericUserCerts.class, pgUserCertsHandler);

    MasterPasswordChangeHandler<ClusterCertificateFacade> delaClusterCertsHandler = new DelaCertsMasterPasswordHandler(
            settings);
    delaClusterCertsHandler.setFacade(clusterCertificateFacade);
    registerMasterPasswordChangeHandler(ClusterCertificate.class, delaClusterCertsHandler);
}

From source file:org.apache.logging.log4j.core.appender.FileAppenderPermissionsTest.java

@Test
public void testFileUserGroupAPI() throws Exception {
    final File file = new File(DIR, "AppenderTest-" + (1000 + fileIndex) + ".log");
    final Path path = file.toPath();
    final String user = findAUser();
    assertNotNull(user);/* ww  w.  j ava  2 s . co  m*/
    final String group = findAGroup(user);
    assertNotNull(group);

    final Layout<String> layout = PatternLayout.newBuilder()
            .withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build();
    // @formatter:off
    final FileAppender appender = FileAppender.newBuilder().withFileName(file.getAbsolutePath())
            .withName("test").withImmediateFlush(true).withIgnoreExceptions(false).withBufferedIo(false)
            .withBufferSize(1).withLayout(layout).withFilePermissions(filePermissions).withFileOwner(user)
            .withFileGroup(group).build();
    // @formatter:on
    try {
        appender.start();
        assertTrue("Appender did not start", appender.isStarted());
        long curLen = file.length();
        long prevLen = curLen;
        assertTrue(file + " File length: " + curLen, curLen == 0);
        for (int i = 0; i < 100; ++i) {
            final LogEvent event = Log4jLogEvent.newBuilder().setLoggerName("TestLogger") //
                    .setLoggerFqcn(FileAppenderPermissionsTest.class.getName()).setLevel(Level.INFO) //
                    .setMessage(new SimpleMessage("Test")).setThreadName(this.getClass().getSimpleName()) //
                    .setTimeMillis(System.currentTimeMillis()).build();
            try {
                appender.append(event);
                curLen = file.length();
                assertTrue("File length: " + curLen, curLen > prevLen);
                // Give up control long enough for another thread/process to occasionally do something.
                Thread.sleep(25);
            } catch (final Exception ex) {
                throw ex;
            }
            prevLen = curLen;
        }
        assertEquals(filePermissions, PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
        assertEquals(user, Files.getOwner(path).getName());
        assertEquals(group, Files.readAttributes(path, PosixFileAttributes.class).group().getName());
    } finally {
        appender.stop();
    }
    assertFalse("Appender did not stop", appender.isStarted());
}