Java Code Examples for java.nio.file.Files.getFileAttributeView()

The following are Jave code examples for showing how to use getFileAttributeView() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: uavstack   File: ReliableTaildirEventReader.java   View Source Code Vote up 7 votes
private long getInode(File file) throws IOException {

        UserDefinedFileAttributeView view = null;
        // windows system and file customer Attribute
        if (OS_WINDOWS.equals(os)) {
            view = Files.getFileAttributeView(file.toPath(), UserDefinedFileAttributeView.class);// 把文件的内容属性值放置在view里面?
            try {
                ByteBuffer buffer = ByteBuffer.allocate(view.size(INODE));// view.size得到inode属性值大小
                view.read(INODE, buffer);// 把属性值放置在buffer中
                buffer.flip();
                return Long.parseLong(Charset.defaultCharset().decode(buffer).toString());// 返回编码后的inode的属性值

            }
            catch (NoSuchFileException e) {
                long winode = random.nextLong();
                view.write(INODE, Charset.defaultCharset().encode(String.valueOf(winode)));
                return winode;
            }
        }
        long inode = (long) Files.getAttribute(file.toPath(), "unix:ino");// 返回unix的inode的属性值
        return inode;
    }
 
Example 2
Project: openjdk-jdk10   File: TestVMOptionsFile.java   View Source Code Vote up 6 votes
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);
    }
}
 
Example 3
Project: incubator-netbeans   File: FileObjTest.java   View Source Code Vote up 5 votes
/**
 * Test for bug 240953 - Netbeans Deletes User Defined Attributes.
 *
 * @throws java.io.IOException
 */
public void testWritingKeepsFileAttributes() throws IOException {

    final String attName = "User_Attribute";
    final String attValue = "User_Attribute_Value";

    if (Utilities.isWindows()) {
        clearWorkDir();
        File f = new File(getWorkDir(), "fileWithAtts.txt");
        f.createNewFile();
        UserDefinedFileAttributeView attsView = Files.getFileAttributeView(
                f.toPath(), UserDefinedFileAttributeView.class);
        ByteBuffer buffer = Charset.defaultCharset().encode(attValue);
        attsView.write(attName, buffer);

        buffer.rewind();
        attsView.read(attName, buffer);
        buffer.flip();
        String val = Charset.defaultCharset().decode(buffer).toString();
        assertEquals(attValue, val);

        FileObject fob = FileUtil.toFileObject(f);
        OutputStream os = fob.getOutputStream();
        try {
            os.write(55);
        } finally {
            os.close();
        }

        buffer.rewind();
        attsView.read(attName, buffer);
        buffer.flip();
        String val2 = Charset.defaultCharset().decode(buffer).toString();
        assertEquals(attValue, val2);
    }
}
 
Example 4
Project: uavstack   File: DoTestRuleFilterFactory.java   View Source Code Vote up 5 votes
@Test
public void getCustomerAttr() throws IOException {

    Path target = Paths.get("/Users/fathead/temp/file4");
    UserDefinedFileAttributeView view2 = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class);
    ByteBuffer buf = ByteBuffer.allocate(view2.size(name));
    view2.read(name, buf);
    buf.flip();
    String value = Charset.defaultCharset().decode(buf).toString();
    System.out.println("value=" + value);
}
 
Example 5
Project: elasticsearch_my   File: KeyStoreWrapper.java   View Source Code Vote up 5 votes
/** Write the keystore to the given config directory. */
void save(Path configDir) throws Exception {
    char[] password = this.keystorePassword.get().getPassword();

    SimpleFSDirectory directory = new SimpleFSDirectory(configDir);
    // write to tmp file first, then overwrite
    String tmpFile = KEYSTORE_FILENAME + ".tmp";
    try (IndexOutput output = directory.createOutput(tmpFile, IOContext.DEFAULT)) {
        CodecUtil.writeHeader(output, KEYSTORE_FILENAME, FORMAT_VERSION);
        output.writeByte(password.length == 0 ? (byte)0 : (byte)1);
        output.writeString(type);
        output.writeString(secretFactory.getAlgorithm());

        ByteArrayOutputStream keystoreBytesStream = new ByteArrayOutputStream();
        keystore.get().store(keystoreBytesStream, password);
        byte[] keystoreBytes = keystoreBytesStream.toByteArray();
        output.writeInt(keystoreBytes.length);
        output.writeBytes(keystoreBytes, keystoreBytes.length);
        CodecUtil.writeFooter(output);
    }

    Path keystoreFile = keystorePath(configDir);
    Files.move(configDir.resolve(tmpFile), keystoreFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    PosixFileAttributeView attrs = Files.getFileAttributeView(keystoreFile, PosixFileAttributeView.class);
    if (attrs != null) {
        // don't rely on umask: ensure the keystore has minimal permissions
        attrs.setPermissions(PosixFilePermissions.fromString("rw-------"));
    }
}
 
Example 6
Project: elasticsearch_my   File: InstallPluginCommand.java   View Source Code Vote up 5 votes
/**
 * Copies the files from {@code tmpConfigDir} into {@code destConfigDir}.
 * Any files existing in both the source and destination will be skipped.
 */
private void installConfig(PluginInfo info, Path tmpConfigDir, Path destConfigDir) throws Exception {
    if (Files.isDirectory(tmpConfigDir) == false) {
        throw new UserException(ExitCodes.IO_ERROR, "config in plugin " + info.getName() + " is not a directory");
    }

    Files.createDirectories(destConfigDir);
    setFileAttributes(destConfigDir, CONFIG_DIR_PERMS);
    final PosixFileAttributeView destConfigDirAttributesView =
        Files.getFileAttributeView(destConfigDir.getParent(), PosixFileAttributeView.class);
    final PosixFileAttributes destConfigDirAttributes =
        destConfigDirAttributesView != null ? destConfigDirAttributesView.readAttributes() : null;
    if (destConfigDirAttributes != null) {
        setOwnerGroup(destConfigDir, destConfigDirAttributes);
    }

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(tmpConfigDir)) {
        for (Path srcFile : stream) {
            if (Files.isDirectory(srcFile)) {
                throw new UserException(ExitCodes.DATA_ERROR, "Directories not allowed in config dir for plugin " + info.getName());
            }

            Path destFile = destConfigDir.resolve(tmpConfigDir.relativize(srcFile));
            if (Files.exists(destFile) == false) {
                Files.copy(srcFile, destFile);
                setFileAttributes(destFile, CONFIG_FILES_PERMS);
                if (destConfigDirAttributes != null) {
                    setOwnerGroup(destFile, destConfigDirAttributes);
                }
            }
        }
    }
    IOUtils.rm(tmpConfigDir); // clean up what we just copied
}
 
Example 7
Project: elasticsearch_my   File: InstallPluginCommand.java   View Source Code Vote up 5 votes
/**
 * Sets the attributes for a path iff posix attributes are supported
 */
private static void setFileAttributes(final Path path, final Set<PosixFilePermission> permissions) throws IOException {
    PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    if (fileAttributeView != null) {
        Files.setPosixFilePermissions(path, permissions);
    }
}
 
Example 8
Project: neoscada   File: Executables.java   View Source Code Vote up 5 votes
public static void setExecutable ( final Path path, final boolean state ) throws IOException
{
    final UserDefinedFileAttributeView ua = Files.getFileAttributeView ( path, UserDefinedFileAttributeView.class );
    if ( state )
    {
        ua.write ( ATTR_EXECUTE, ByteBuffer.wrap ( marker ) );
    }
    else
    {
        ua.delete ( ATTR_EXECUTE );
    }
}
 
Example 9
Project: neoscada   File: Executables.java   View Source Code Vote up 5 votes
public static boolean getExecutable ( final Path path ) throws IOException
{
    final UserDefinedFileAttributeView ua = Files.getFileAttributeView ( path, UserDefinedFileAttributeView.class );

    if ( !ua.list ().contains ( ATTR_EXECUTE ) )
    {
        // check first, otherwise the size() call with give an exception
        return false;
    }

    final ByteBuffer buf = ByteBuffer.allocate ( ua.size ( ATTR_EXECUTE ) );
    ua.read ( ATTR_EXECUTE, buf );
    buf.flip ();
    return Boolean.parseBoolean ( CHARSET.decode ( buf ).toString () );
}
 
Example 10
Project: loom-installer   File: LoomInstaller.java   View Source Code Vote up 5 votes
private static void chmod(final Path file, final String perms) throws IOException {
    final PosixFileAttributeView view =
        Files.getFileAttributeView(file, PosixFileAttributeView.class);

    if (view == null) {
        // OS (Windows) doesn't support POSIX file attributes
        return;
    }

    view.setPermissions(PosixFilePermissions.fromString("rwxr-xr-x"));
}
 
Example 11
Project: pgcodekeeper   File: FileUtils.java   View Source Code Vote up 5 votes
public static void removeReadOnly(Path path) throws IOException {
    DosFileAttributeView att = Files.getFileAttributeView(path, DosFileAttributeView.class);
    if (att != null) {
        att.setReadOnly(false);
    }
    Files.delete(path);
}
 
Example 12
Project: jdk8u-jdk   File: FaultyFileSystem.java   View Source Code Vote up 5 votes
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path file,
                                                            Class<V> type,
                                                            LinkOption... options)
{
    return Files.getFileAttributeView(unwrap(file), type, options);
}
 
Example 13
Project: uavstack   File: DoTestRuleFilterFactory.java   View Source Code Vote up 5 votes
@Test
public void setCustomerAttr() throws IOException {

    Path target = Paths.get("/Users/fathead/temp/file4");
    UserDefinedFileAttributeView view = Files.getFileAttributeView(target, UserDefinedFileAttributeView.class);
    view.write(name, Charset.defaultCharset().encode("pinelet"));
}
 
Example 14
Project: Reer   File: PosixJdk7FilePermissionHandler.java   View Source Code Vote up 4 votes
@Override
public void chmod(File f, int mode) throws IOException {
    PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(f.toPath(), PosixFileAttributeView.class);
    fileAttributeView.setPermissions(convertToPermissionsSet(mode));
}
 
Example 15
Project: transformenator   File: ExtractIBM8Files.java   View Source Code Vote up 4 votes
public static void setFileCreationDate(String filePath, Date creationDate) throws IOException
{
    BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class);
    FileTime time = FileTime.fromMillis(creationDate.getTime());
    attributes.setTimes(time, time, time);
}
 
Example 16
Project: elasticsearch_my   File: NodeEnvironmentEvilTests.java   View Source Code Vote up 4 votes
@BeforeClass
public static void checkPosix() throws IOException {
    isPosix = Files.getFileAttributeView(createTempFile(), PosixFileAttributeView.class) != null;
}
 
Example 17
Project: elasticsearch_my   File: PosixPermissionsResetter.java   View Source Code Vote up 4 votes
public PosixPermissionsResetter(Path path) throws IOException {
    attributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    Assert.assertNotNull(attributeView);
    permissions = attributeView.readAttributes().permissions();
}
 
Example 18
Project: openjdk-jdk10   File: CreationTime.java   View Source Code Vote up 4 votes
/**
 * Sets the creationTime attribute
 */
private static void setCreationTime(Path file, FileTime time) throws IOException {
    BasicFileAttributeView view =
        Files.getFileAttributeView(file, BasicFileAttributeView.class);
    view.setTimes(null, null, time);
}
 
Example 19
Project: jdk8u-jdk   File: CreationTime.java   View Source Code Vote up 4 votes
/**
 * Sets the creationTime attribute
 */
private static void setCreationTime(Path file, FileTime time) throws IOException {
    BasicFileAttributeView view =
        Files.getFileAttributeView(file, BasicFileAttributeView.class);
    view.setTimes(null, null, time);
}
 
Example 20
Project: lustre-connector-for-hadoop   File: LustreFileSystem.java   View Source Code Vote up 3 votes
/**
  * Set access time of a file
  * @param p The path
  * @param mtime Set the modification time of this file.
  *              The number of milliseconds since Jan 1, 1970. 
  *              A value of -1 means that this call should not set modification time.
  * @param atime Set the access time of this file.
  *              The number of milliseconds since Jan 1, 1970. 
  *              A value of -1 means that this call should not set access time.
  */
 @Override
 public void setTimes(Path path, long mtime, long atime) throws IOException {	  
java.nio.file.Path p = FileSystems.getDefault().getPath(pathToFile(path).getAbsolutePath());
BasicFileAttributeView view = Files.getFileAttributeView(p, BasicFileAttributeView.class);	  
view.setTimes(mtime == -1 ? null : FileTime.fromMillis(mtime),
  atime == -1 ? null : FileTime.fromMillis(atime), null);
 }