Java 类java.nio.file.attribute.PosixFilePermissions 实例源码

项目:hadoop    文件:LocalJavaKeyStoreProvider.java   
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
项目:SVNAutoMerger    文件:Merger.java   
/**
 * Create localconf folder and properties file necessary to run build task in order to check merge integrity.
 * @param branchName
 */
public void createLocalConfigFile(String branchName) throws Exception {
  String branchPath = SvnUtils.TEMP_FOLDER + "/" + branchName;
  //create localconf directory
  String newDirectoryPath = branchPath + "/localconf";
  if ( !Files.exists( Paths.get(newDirectoryPath))) {
    Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
    FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions
        .asFileAttribute(permissions);
    Files.createDirectory(Paths.get(newDirectoryPath), fileAttributes);
  }
  //copy properties template
  Files.copy(
      Paths.get(branchPath + "/common/conf/worldnettps.properties.template"),
      Paths.get(newDirectoryPath + "/worldnettps.properties"),
      StandardCopyOption.REPLACE_EXISTING);
  //setting glassfish directory in properties file
  String appServerDir = PropertiesUtil.getString("appserver.dir");
  String sedCommand = String.format(
      "sed -i '/glassfish.dir/c\\glassfish.dir=%s' localconf/worldnettps.properties", appServerDir);
  CommandExecutor.run( sedCommand, branchPath);
  logger.info("worldnettps.properties file has been created in localconf folder.");
}
项目:incubator-servicecomb-java-chassis    文件:FilePerm.java   
/**
 * 获取Posix权限
 */
public static Set<PosixFilePermission> getPosixPerm(int perm) {
  StringBuilder permStr = new StringBuilder();

  permStr.append(uCanRead(perm) ? "r" : "-");
  permStr.append(uCanWrite(perm) ? "w" : "-");
  permStr.append(uCanExec(perm) ? "x" : "-");
  permStr.append(gCanRead(perm) ? "r" : "-");
  permStr.append(gCanWrite(perm) ? "w" : "-");
  permStr.append(gCanExec(perm) ? "x" : "-");
  permStr.append(oCanRead(perm) ? "r" : "-");
  permStr.append(oCanWrite(perm) ? "w" : "-");
  permStr.append(oCanExec(perm) ? "x" : "-");

  return PosixFilePermissions.fromString(permStr.toString());
}
项目:hadoop-oss    文件:LocalJavaKeyStoreProvider.java   
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
项目:hadoop-oss    文件:LocalJavaKeyStoreProvider.java   
@Override
public void flush() throws IOException {
  super.flush();
  if (LOG.isDebugEnabled()) {
    LOG.debug("Reseting permissions to '" + permissions + "'");
  }
  if (!Shell.WINDOWS) {
    Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()),
        permissions);
  } else {
    // FsPermission expects a 10-character string because of the leading
    // directory indicator, i.e. "drwx------". The JDK toString method returns
    // a 9-character string, so prepend a leading character.
    FsPermission fsPermission = FsPermission.valueOf(
        "-" + PosixFilePermissions.toString(permissions));
    FileUtil.setPermission(file, fsPermission);
  }
}
项目:fuse-nio-adapter    文件:ReadWriteAdapter.java   
@Override
public int create(String path, @mode_t long mode, FuseFileInfo fi) {
    try {
        Set<OpenFlags> flags = bitMaskUtil.bitMaskToSet(OpenFlags.class, fi.flags.longValue());
        LOG.info("createAndOpen {} with openOptions {}", path, flags);
        Path node = resolvePath(path);
        if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) {
            FileAttribute<?> attrs = PosixFilePermissions.asFileAttribute(attrUtil.octalModeToPosixPermissions(mode));
            return fileHandler.createAndOpen(node, fi, attrs);
        } else {
            return fileHandler.createAndOpen(node, fi);
        }
    } catch (RuntimeException e) {
        LOG.error("create failed.", e);
        return -ErrorCodes.EIO();
    }
}
项目:setra    文件:SecureTransferConfiguration.java   
@PostConstruct
public void init() {
    if (!createBaseDir) {
        // Don't create dir in tests
        return;
    }

    LOG.info("Initialize base directory {}", baseDir);

    if (!Files.isDirectory(baseDir)) {
        try {
            Files.createDirectories(baseDir,
                PosixFilePermissions.asFileAttribute(
                    PosixFilePermissions.fromString("rwx------")));
        } catch (final IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
项目:AptSpring    文件:TestResourceLoader.java   
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void testBrokenEnvironment() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  DefinitionModel model = new DefinitionModel(SIMPLE_MODEL);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));
  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    TestFileStore fileStore = new TestFileStore(root);
    assertThatThrownBy(() -> fileStore.store(model)).isInstanceOf(IOException.class)
      .hasMessage("could not write directories for model storage");
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
项目:AptSpring    文件:TestResourceLoader.java   
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void failedStorage() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));

  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    DefinitionModel model1 = new DefinitionModel(SIMPLE_MODEL);
    TestErrorListener el = new TestErrorListener();

    TestFileStore fileStore = new TestFileStore(workingDir);
    ResourceLoader loader = new ClasspathUrlResourceLoader(workingDir);
    DefinitionModelStore store = new GsonDefinitionModelStore(loader, fileStore);
    Set<DefinitionModel> models = new HashSet<>();
    models.add(model1);
    new DefinitionContentInspector()
      .inspectDefinitionGraph(models, el, new ReflectionAssignabilityUtils(), store);
    assertThat(el.getErrors()).hasSize(1);
    assertThat(el.getErrors().get(0).getMessage()).isEqualTo(ErrorType.COULD_NOT_STORE);
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
项目:cyberduck    文件:LocalAttributesFinderFeatureTest.java   
@Test
public void testConvert() throws Exception {
    final LocalSession session = new LocalSession(new Host(new LocalProtocol(), new LocalProtocol().getDefaultHostname()));
    if(session.isPosixFilesystem()) {
        session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
        session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
        final Path file = new Path(new LocalHomeFinderFeature(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
        new LocalTouchFeature(session).touch(file, new TransferStatus());
        final java.nio.file.Path local = session.toPath(file);
        final PosixFileAttributes posixAttributes = Files.readAttributes(local, PosixFileAttributes.class);
        final LocalAttributesFinderFeature finder = new LocalAttributesFinderFeature(session);
        assertEquals(PosixFilePermissions.toString(posixAttributes.permissions()), finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-------"));
        assertEquals("rw-------", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rwxrwxrwx"));
        assertEquals("rwxrwxrwx", finder.find(file).getPermission().getSymbol());
        Files.setPosixFilePermissions(local, PosixFilePermissions.fromString("rw-rw----"));
        assertEquals("rw-rw----", finder.find(file).getPermission().getSymbol());
        assertEquals(posixAttributes.size(), finder.find(file).getSize());
        assertEquals(posixAttributes.lastModifiedTime().toMillis(), finder.find(file).getModificationDate());
        assertEquals(posixAttributes.creationTime().toMillis(), finder.find(file).getCreationDate());
        assertEquals(posixAttributes.lastAccessTime().toMillis(), finder.find(file).getAccessedDate());
        new LocalDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
    }
}
项目:openjdk-jdk10    文件:TestVMOptionsFile.java   
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
项目:openjdk9    文件:TestVMOptionsFile.java   
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
项目:aliyun-oss-hadoop-fs    文件:LocalJavaKeyStoreProvider.java   
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
项目:aliyun-oss-hadoop-fs    文件:LocalJavaKeyStoreProvider.java   
@Override
public void flush() throws IOException {
  super.flush();
  if (LOG.isDebugEnabled()) {
    LOG.debug("Reseting permissions to '" + permissions + "'");
  }
  if (!Shell.WINDOWS) {
    Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()),
        permissions);
  } else {
    // FsPermission expects a 10-character string because of the leading
    // directory indicator, i.e. "drwx------". The JDK toString method returns
    // a 9-character string, so prepend a leading character.
    FsPermission fsPermission = FsPermission.valueOf(
        "-" + PosixFilePermissions.toString(permissions));
    FileUtil.setPermission(file, fsPermission);
  }
}
项目:big-c    文件:LocalJavaKeyStoreProvider.java   
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
项目:iofabric    文件:Start.java   
/**
 * creates and grants permission to daemon files directory
 */
private static void setupEnvironment() {
    final File daemonFilePath = new File("/var/run/iofabric");
    if (!daemonFilePath.exists()) {
        try {
            daemonFilePath.mkdirs();

            UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();
            final GroupPrincipal group = lookupservice.lookupPrincipalByGroupName("iofabric");
            Files.getFileAttributeView(daemonFilePath.toPath(), PosixFileAttributeView.class,
                    LinkOption.NOFOLLOW_LINKS).setGroup(group);
            Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwx---");
            Files.setPosixFilePermissions(daemonFilePath.toPath(), perms);
        } catch (Exception e) {
        }
    }

}
项目:Camel    文件:FileProducerChmodOptionTest.java   
private void runChmodCheck(String routeSuffix, String expectedPermissions) throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:chmod" + routeSuffix);
    mock.expectedMessageCount(1);
    String testFileName = "chmod" + routeSuffix + ".txt";
    String fullTestFileName = TEST_DIRECTORY + testFileName;
    String testFileContent = "Writing file with chmod " + routeSuffix + " option at " + new Date();
    mock.expectedFileExists(fullTestFileName, testFileContent);

    template.sendBodyAndHeader("direct:write" + routeSuffix, testFileContent, Exchange.FILE_NAME, testFileName);

    File f = new File(fullTestFileName);
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(f.toPath(), LinkOption.NOFOLLOW_LINKS);
    assertEquals(expectedPermissions, PosixFilePermissions.toString(permissions));
    assertEquals(expectedPermissions.replace("-", "").length(), permissions.size());

    assertMockEndpointsSatisfied();
}
项目:Mavkit    文件:XDGDirectories.java   
/**
 * @return The single base directory relative to which user-specific
 *      non-essential runtime files and other file objects (such as sockets,
 *      named pipes, ...) should be stored.
 */
@Override
@NonNull
@EnsuresNonNull("this.runtimeDir")
public File getRuntimeDir() {
    if (runtimeDir != null) return runtimeDir;
    File dir = getBaseDir("XDG_RUNTIME_DIR", null);
    if (dir == null) {
        log.warn("Synthesizing runtime directory, as $XDG_RUNTIME_DIR is unset");
        dir = new File(System.getProperty("java.io.tmpdir"));
        dir = new File(dir, appName+"-"+System.getProperty("user.name"));
        dir.mkdirs();
    }
    try {
        Files.setPosixFilePermissions(dir.toPath(), PosixFilePermissions.fromString("rwx------"));
    } catch (IOException | UnsupportedOperationException e) {
        log.warn("Failed to set directory permissions on {} to owner-only", dir, e);
    }
    runtimeDir = dir;
    Directories.deleteOnExit(dir);
    return dir;
}
项目:spike.x    文件:Files.java   
public static void createUnixDirectories(
        final Permission perm,
        final Path... dirs) throws IOException {

    FileAttribute<Set<PosixFilePermission>> attr
            = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx);

    switch (perm) {
        case OWNER_FULL_GROUP_EXEC:
            attr = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx_GRPr_x);
            break;
        case OWNER_FULL_GROUP_EXEC_OTHER_EXEC:
            attr = PosixFilePermissions.asFileAttribute(POSIX_OWNrwx_GRPr_x_OTHr_x);
            break;
    }

    for (Path dir : dirs) {
        if (!java.nio.file.Files.exists(dir, LinkOption.NOFOLLOW_LINKS)) {
            m_logger.debug("Creating directory: {} with permissions: {}", dir, perm);
            java.nio.file.Files.createDirectories(dir, attr);
        } else {
            m_logger.debug("Directory exists: {}", dir);
        }
    }
}
项目:hops    文件:LocalJavaKeyStoreProvider.java   
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
项目:hops    文件:LocalJavaKeyStoreProvider.java   
@Override
public void flush() throws IOException {
  super.flush();
  if (LOG.isDebugEnabled()) {
    LOG.debug("Resetting permissions to '" + permissions + "'");
  }
  if (!Shell.WINDOWS) {
    Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()),
        permissions);
  } else {
    // FsPermission expects a 10-character string because of the leading
    // directory indicator, i.e. "drwx------". The JDK toString method returns
    // a 9-character string, so prepend a leading character.
    FsPermission fsPermission = FsPermission.valueOf(
        "-" + PosixFilePermissions.toString(permissions));
    FileUtil.setPermission(file, fsPermission);
  }
}
项目:ipp    文件:FileOutput.java   
@Override
public void outputScore(Score score) {
    Path tmpFile = null;
    try {
        if (tmpDir.isPresent()) {
            tmpFile = Files.createTempFile(tmpDir.get(), "score-", ".json", PosixFilePermissions.asFileAttribute(defaultPerms));
        } else {
            tmpFile = Files.createTempFile("score-", ".json", PosixFilePermissions.asFileAttribute(defaultPerms));
        }
        BufferedWriter writer = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8);
        Serialization.getJsonMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, score);
        Files.move(tmpFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Error writing score to file!", e);
    } finally {
        try {
            if (tmpFile != null) Files.deleteIfExists(tmpFile);
        } catch (IOException ignored) {
        }
    }
}
项目:ephemeralfs    文件:BasicFileAttributesTest.java   
@IgnoreIf(FsType.WINDOWS)
@Test
public void testCheckAccessCopyOfExecutableFileWindows() throws Exception {
    Path path = root.resolve("path");
    Files.createFile(path, PosixFilePermissions.asFileAttribute(
            EnumSet.allOf(PosixFilePermission.class))
            );
    Path copy = root.resolve("copy");
    Files.copy(path, copy);

    assertTrue(Files.isReadable(copy));
    assertTrue(Files.isWritable(copy));
    assertTrue(Files.exists(copy));
    assertTrue(Files.exists(copy, LinkOption.NOFOLLOW_LINKS));
    assertTrue(Files.isExecutable(copy));
}
项目:ephemeralfs    文件:BasicFileAttributesTest.java   
@IgnoreIf(FsType.WINDOWS)
@Test
public void testCheckAccessCopyOfReadOnlyFile() throws Exception {
    Path path = root.resolve("path");
    Files.createFile(path, PosixFilePermissions.asFileAttribute(
            EnumSet.of(PosixFilePermission.OWNER_READ))
            );
    Path copy = root.resolve("copy");
    Files.copy(path, copy);

    assertTrue(Files.isReadable(copy));
    assertFalse(Files.isWritable(copy));
    assertTrue(Files.exists(copy));
    assertTrue(Files.exists(copy, LinkOption.NOFOLLOW_LINKS));
    assertFalse(Files.isExecutable(copy));
}
项目:EclipseCommander    文件:PathUtils.java   
/**
 * @param path
 * @return
 */
public static String getPosixAttributesString(Path path) {
    PosixFileAttributeView posixView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    StringBuilder attrs = new StringBuilder();

    try {
        // + all basic attributes
        PosixFileAttributes posixAttrs = posixView.readAttributes();

        if (posixAttrs != null) {
            attrs.append(PosixFilePermissions.toString(posixAttrs.permissions()));
        }
    }
    catch (IOException e) {
        log.warn("unable to read Posix file attributes.", e); //$NON-NLS-1$
    }
    return attrs.toString();
}
项目:bifroest    文件:JSONMetricStorageInFile.java   
@Override
public void finishStoringTheMetrics() throws IOException {
    // We need to be careful with replacing the existing file, since we have
    // no information if and how a client is reading this file. Basically,
    // someone might be reading this file at every point in time and
    // whenever we try to touch it. Merely truncating the file or appending
    // to the file might result in funny but unproductive results. Thus we
    // write to a temporary file first and atomically replace the old file
    // with the new file.
    Path tempFile = Files.createTempFile( "gatherer_performance_file", ".json",
            PosixFilePermissions.asFileAttribute( PosixFilePermissions.fromString( "rw-r--r--" ) ) );
    try ( BufferedWriter tempFileWriter = Files.newBufferedWriter( tempFile, Charset.forName( "UTF-8" ), StandardOpenOption.WRITE ) ) {
        storage().write( tempFileWriter );
    }

    Files.move( tempFile, fileOnDisk, StandardCopyOption.REPLACE_EXISTING );
}
项目:kamike.fast    文件:MiscUtils.java   
public void createDir(String dstPath) {

        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 {
                if (osName.indexOf("Windows") == -1) {
                    Files.createDirectories(newdir, attr);
                } else {
                    Files.createDirectories(newdir);
                }
            } catch (Exception e) {
                System.err.println(e);

            }
        }
    }
项目:jsr203-hadoop    文件:TestPosixFilePermissions.java   
/**
 * Simple test to check posix file permission on createFile().
 * 
 * @throws IOException
 */
@Test
public void testWriteBuffered() throws IOException {
    Path rootPath = Paths.get(clusterUri);

    Path pathToTest = rootPath.resolve("tmp/out6.txt");

    Path path = pathToTest;
    Set<PosixFilePermission> perms = EnumSet.of(
            PosixFilePermission.OWNER_READ,
            PosixFilePermission.OWNER_WRITE,
            PosixFilePermission.GROUP_READ,
            PosixFilePermission.GROUP_WRITE);
    Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));

    Set<PosixFilePermission> perms2 = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS);
    assertNotNull(perms2);

    assertTrue(perms2.contains(PosixFilePermission.OWNER_READ));
}
项目:wildfly-core    文件:FilePermissionTestCase.java   
@Test
@Ignore("Un-ignore when WFCORE-3559 is fixed")
public void testFileDefaultPermissions() throws Exception {
    // This is unix test only
    if (!Util.isWindows()) {
        CommandContext ctx = CLITestUtil.getCommandContext(TestSuiteEnvironment.getServerAddress(),
                TestSuiteEnvironment.getServerPort(), System.in, System.out);

        String tmpFile = "tmpFile";
        Path path = Paths.get(tmpFile);

        try {
            ctx.handle("echo \"aaa\" >> " + tmpFile);

            Set<PosixFilePermission> set = Files.getPosixFilePermissions(path);
            assertThat("The test file has unexpected permissions: " + PosixFilePermissions.toString(set),
                    PosixFilePermissions.toString(set), CoreMatchers.is(CoreMatchers.equalTo("rw-rw-r--")));
        } finally {
            ctx.terminateSession();
            Files.delete(path);
        }
    }
}
项目:airavata    文件:LocalRemoteCluster.java   
@Override
public void makeDirectory(String directoryPath) throws GFacException {
    Path dirPath = Paths.get(directoryPath);
    Set<PosixFilePermission> perms = new HashSet<>();
    // add permission as rwxr--r-- 744
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.OTHERS_READ);
    FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(perms);
    try {
        Files.createDirectory(dirPath, fileAttributes);
    } catch (IOException e) {
        throw new GFacException("Error making directory", e);
    }

}
项目:DotCi    文件:WorkspaceFileExporter.java   
@Override
public String invoke(final File dir, final VirtualChannel channel) throws IOException {
    dir.mkdirs();
    File f;
    Writer w = null;
    try {
        f = new File(dir.getAbsolutePath() + "/" + this.workspaceFile.fileName);
        f.createNewFile();
        w = new FileWriter(f);
        w.write(this.workspaceFile.contents);
        Files.setPosixFilePermissions(f.toPath(), PosixFilePermissions.fromString(this.workspaceFile.permissions));
    } finally {
        if (w != null) {
            w.close();
        }
    }
    return f.getAbsolutePath();
}
项目:buck-cutom    文件:ProjectFilesystemTest.java   
@Test
public void testCreateReadOnlyFileSetsPermissions() throws IOException {
  Path path = Paths.get("hello.txt");
  ImmutableSet<PosixFilePermission> permissions =
    ImmutableSet.<PosixFilePermission>of(
        PosixFilePermission.OWNER_READ,
        PosixFilePermission.GROUP_READ,
        PosixFilePermission.OTHERS_READ);

  filesystem.writeContentsToPath(
      "hello world",
      path,
      PosixFilePermissions.asFileAttribute(permissions));
  // The umask may restrict the actual permissions on the filesystem:
  // https://fburl.com/26569549
  // So the best we can do is to check that the actual permissions are a
  // strict subset of the expected permissions.
  PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class);
  assertTrue(permissions.containsAll(attrs.permissions()));
}
项目:buck-cutom    文件:FakeProjectFilesystemTest.java   
@Test
public void testWriteContentsWithSpecifiedFileAttributes() {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  ImmutableSet<PosixFilePermission> permissions =
    ImmutableSet.of(
        PosixFilePermission.OWNER_READ,
        PosixFilePermission.GROUP_READ,
        PosixFilePermission.OTHERS_READ);
  FileAttribute<?> attribute = PosixFilePermissions.asFileAttribute(permissions);

  Path path = Paths.get("hello.txt");
  filesystem.writeContentsToPath(
      "hello world",
      Paths.get("hello.txt"),
      attribute);
  assertEquals(ImmutableSet.of(attribute), filesystem.getFileAttributesAtPath(path));
}
项目:buck    文件:XcodeToolFinderTest.java   
@Test
public void picksFirstMatchingEntry() throws Exception {
  Path searchRoot1 = tempPath.newFolder("SEARCH_ROOT1");
  Files.createFile(
      searchRoot1.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  Path searchRoot2 = tempPath.newFolder("SEARCH_ROOT2");
  Files.createFile(
      searchRoot2.resolve("clang"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));

  XcodeToolFinder finder = new XcodeToolFinder();
  assertEquals(
      Optional.of(searchRoot1.resolve("clang")),
      finder.getToolPath(ImmutableList.of(searchRoot1, searchRoot2), "clang"));
  assertEquals(
      Optional.of(searchRoot2.resolve("clang")),
      finder.getToolPath(ImmutableList.of(searchRoot2, searchRoot1), "clang"));
}
项目:buck    文件:XcodeToolFinderTest.java   
@Test
public void rejectsInvalidPathsUsingCache() throws Exception {
  Path searchRoot = tempPath.newFolder("SEARCH_ROOT");
  XcodeToolFinder finder = new XcodeToolFinder();
  assertFalse(
      "First search should not find the executable.",
      finder.getToolPath(ImmutableList.of(searchRoot), "exe").isPresent());
  Files.createFile(
      searchRoot.resolve("exe"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  assertFalse(
      "Second search should still not find the executable, since it's cached.",
      finder.getToolPath(ImmutableList.of(searchRoot), "exe").isPresent());
  Files.createFile(
      searchRoot.resolve("bob"),
      PosixFilePermissions.asFileAttribute(
          EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)));
  assertFalse(
      "The entire directory is cached, any other executables would also be not found.",
      finder.getToolPath(ImmutableList.of(searchRoot), "bob").isPresent());
  assertTrue(
      "A new instance would find the entries again.",
      new XcodeToolFinder().getToolPath(ImmutableList.of(searchRoot), "bob").isPresent());
}
项目:buck    文件:ProjectGeneratorTest.java   
@Test
public void testGeneratedProjectIsReadOnlyIfOptionSpecified() throws IOException {
  ProjectGenerator projectGenerator =
      createProjectGeneratorForCombinedProject(
          ImmutableSet.of(), ImmutableSet.of(ProjectGenerator.Option.GENERATE_READ_ONLY_FILES));

  projectGenerator.createXcodeProjects();

  ImmutableSet<PosixFilePermission> permissions =
      ImmutableSet.of(
          PosixFilePermission.OWNER_READ,
          PosixFilePermission.GROUP_READ,
          PosixFilePermission.OTHERS_READ);
  FileAttribute<?> expectedAttribute = PosixFilePermissions.asFileAttribute(permissions);
  // This is lame; Java's PosixFilePermissions class doesn't
  // implement equals() or hashCode() in its FileAttribute anonymous
  // class (http://tinyurl.com/nznhfhy).  So instead of comparing
  // the sets, we have to pull out the attribute and check its value
  // for equality.
  FileAttribute<?> actualAttribute =
      Iterables.getOnlyElement(
          fakeProjectFilesystem.getFileAttributesAtPath(OUTPUT_PROJECT_FILE_PATH));
  assertEquals(expectedAttribute.value(), actualAttribute.value());
}
项目:buck    文件:DefaultProjectFilesystemTest.java   
@Test
public void testCreateReadOnlyFileSetsPermissions() throws IOException {
  Assume.assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
  Path path = Paths.get("hello.txt");
  ImmutableSet<PosixFilePermission> permissions =
      ImmutableSet.of(
          PosixFilePermission.OWNER_READ,
          PosixFilePermission.GROUP_READ,
          PosixFilePermission.OTHERS_READ);

  filesystem.writeContentsToPath(
      "hello world", path, PosixFilePermissions.asFileAttribute(permissions));
  // The umask may restrict the actual permissions on the filesystem:
  // https://fburl.com/26569549
  // So the best we can do is to check that the actual permissions are a
  // strict subset of the expected permissions.
  PosixFileAttributes attrs = filesystem.readAttributes(path, PosixFileAttributes.class);
  assertTrue(permissions.containsAll(attrs.permissions()));
}
项目:skid-road    文件:CSVWritingWorkerTest.java   
@Test
public void testCannotOpenFile() throws IOException, InterruptedException {
    Path path = Files.createTempFile(name.getMethodName(),".1", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------")));
    try {
        queue.addAll(Arrays.asList(
                new Pair<>("foo","bar"),
                new Pair<>("biz","baz"),
                new Pair<>("fnarf","blarf")
        ));
        record.setOriginPath(path);
        thread.start();
        assertExit(thread, "detected detected that it cannot write to output file");
        assertEquals("Worker should have detected that it cannot write to output file and not consumed any items.", 3, queue.size());
        verify(tracker,times(1)).writeError((LogFile) anyObject());
        verify(tracker,never()).written((LogFile) anyObject());
    } finally {
        Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-rw-rw-"));
        Files.delete(path);
    }
}
项目:skid-road    文件:FileWritingWorkerTest.java   
@Test
public void testCannotOpenFile() throws IOException, InterruptedException {
    Path path = Files.createTempFile(name.getMethodName(),".1", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("---------")));
    try {
        queue.addAll(Arrays.asList("foo", "bar", "baz"));
        record.setOriginPath(path);
        thread.start();
        assertExit(thread, "detected detected that it cannot write to output file");
        assertEquals("Worker should have detected that it cannot write to output file and not consumed any items.", 3, queue.size());
        verify(tracker,times(1)).writeError((LogFile) anyObject());
        verify(tracker,never()).written((LogFile) anyObject());
    } finally {
        Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-rw-rw-"));
        Files.delete(path);
    }
}
项目:logging-log4j2    文件:PosixViewAttributeAction.java   
@Override
public PosixViewAttributeAction build() {
    if (Strings.isEmpty(basePath)) {
        LOGGER.error("Posix file attribute view action not valid because base path is empty.");
        return null;
    }

    if (filePermissions == null && Strings.isEmpty(filePermissionsString)
                && Strings.isEmpty(fileOwner) && Strings.isEmpty(fileGroup)) {
        LOGGER.error("Posix file attribute view not valid because nor permissions, user or group defined.");
        return null;
    }

    if (!FileUtils.isFilePosixAttributeViewSupported()) {
        LOGGER.warn("Posix file attribute view defined but it is not supported by this files system.");
        return null;
    }

    return new PosixViewAttributeAction(basePath, followLinks, maxDepth, pathConditions,
            subst != null ? subst : configuration.getStrSubstitutor(),
            filePermissions != null ? filePermissions :
                        filePermissionsString != null ? PosixFilePermissions.fromString(filePermissionsString) : null,
            fileOwner,
            fileGroup);
}