java.nio.file.attribute.UserDefinedFileAttributeView Java Examples

The following examples show how to use java.nio.file.attribute.UserDefinedFileAttributeView. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileSystemProcessInstances.java    From kogito-runtimes with Apache License 2.0 7 votes vote down vote up
public boolean setMetadata(Path file, String key, String value) {

        if (supportsUserDefinedAttributes(file)) {
            UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
            try {
                if (value != null) {
                    view.write(key, Charset.defaultCharset().encode(value));
                } else {
                    view.delete(key);
                }
                return true;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
 
Example #2
Source File: SingularityUploader.java    From Singularity with Apache License 2.0 6 votes vote down vote up
Optional<Long> readFileAttributeAsLong(
  Path file,
  String attribute,
  UserDefinedFileAttributeView view,
  List<String> knownAttributes
) {
  if (knownAttributes.contains(attribute)) {
    try {
      LOG.trace("Attempting to read attribute {}, from file {}", attribute, file);
      ByteBuffer buf = ByteBuffer.allocate(view.size(attribute));
      view.read(attribute, buf);
      buf.flip();
      String value = Charset.defaultCharset().decode(buf).toString();
      if (Strings.isNullOrEmpty(value)) {
        LOG.debug("No attrbiute {} found for file {}", attribute, file);
        return Optional.empty();
      }
      return Optional.of(Long.parseLong(value));
    } catch (Exception e) {
      LOG.error("Error getting extra file metadata for {}", file, e);
      return Optional.empty();
    }
  } else {
    return Optional.empty();
  }
}
 
Example #3
Source File: TestFileStore.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Test: File and FileStore attributes
 */
@Test
public void testFileStoreAttributes() throws URISyntaxException, IOException {
  URI uri = clusterUri.resolve("/tmp/testFileStore");
  Path path = Paths.get(uri);
  if (Files.exists(path))
    Files.delete(path);
  assertFalse(Files.exists(path));
  Files.createFile(path);
  assertTrue(Files.exists(path));
  FileStore store1 = Files.getFileStore(path);
  assertNotNull(store1);
  assertTrue(store1.supportsFileAttributeView("basic"));
  assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class));
  assertTrue(store1.supportsFileAttributeView("posix") == store1
      .supportsFileAttributeView(PosixFileAttributeView.class));
  assertTrue(store1.supportsFileAttributeView("dos") == store1
      .supportsFileAttributeView(DosFileAttributeView.class));
  assertTrue(store1.supportsFileAttributeView("acl") == store1
      .supportsFileAttributeView(AclFileAttributeView.class));
  assertTrue(store1.supportsFileAttributeView("user") == store1
      .supportsFileAttributeView(UserDefinedFileAttributeView.class));
}
 
Example #4
Source File: ReliableTaildirEventReader.java    From uavstack with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 6 votes vote down vote up
/**
 * Set an user extended attribute for the given file.
 *
 * @param attr the attribut consist of the name and the value in the format
 * {@code name=value}
 * @param file the filename for which the attribut should be set
 */
private static void setXattr(String attr, String file) {
    UserDefinedFileAttributeView view = getAttributeView(file);

    String[] xattr = attr.split("=");
    if (xattr.length < 2) {
        System.out.println("the extended attribute and value must follow the format: name=value");
        return;
    }
    String name = xattr[0];
    String value = xattr[1];

    try {
        view.write(name, Charset.defaultCharset().encode(value));
    } catch (Exception ex) {
        System.out.printf("could not set attr '%s=%s' for %s%n%s%n", name, value, file, ex);
    }
}
 
Example #6
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 6 votes vote down vote up
/**
 * Show the value of a user extended attribut stored on the given file.
 *
 * @param name the name of the user extended attribute
 * @param file the filename from which the attribute should be read
 * @throws IOException when the user extended attribute information could
 * not be read
 */
private static void getXattr(String name, String file) {
    UserDefinedFileAttributeView view = getAttributeView(file);

    try {
        Charset defaultCharset = Charset.defaultCharset();
        if (view.list().contains(name)) {
            System.out.printf("# file: %s%n", file);
            String value = getAttrValue(view, name);
            System.out.printf("user.%s=\"%s\"%n", name, value);
        } else {
            System.out.printf("file has no extended attribute [%s]%n", name);
        }
    } catch (IOException ex) {
        System.out.printf("failed to get the extended attribute %s from %s%n", name, file);
    }
}
 
Example #7
Source File: EdenProjectFilesystemDelegateTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void computeSha1ViaXattrForFileUnderMount() throws IOException {
  FileSystem fs =
      Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("user").build());
  Path root = fs.getPath(JIMFS_WORKING_DIRECTORY);
  ProjectFilesystemDelegate delegate = new DefaultProjectFilesystemDelegate(root);

  Path path = fs.getPath("/foo");
  Files.createFile(path);
  UserDefinedFileAttributeView view =
      Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);

  ByteBuffer buf = ByteBuffer.wrap(DUMMY_SHA1.toString().getBytes(StandardCharsets.UTF_8));
  view.write("sha1", buf);
  EdenMount mount = createMock(EdenMount.class);
  Config config = ConfigBuilder.createFromText("[eden]", "use_xattr = true");
  EdenProjectFilesystemDelegate edenDelegate =
      new EdenProjectFilesystemDelegate(mount, delegate, config);
  assertEquals(DUMMY_SHA1, edenDelegate.computeSha1(path));
}
 
Example #8
Source File: EdenProjectFilesystemDelegateTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void computeSha1ViaXattrForFileUnderMountInvalidUTF8() throws IOException {
  FileSystem fs =
      Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("user").build());
  Path root = fs.getPath(JIMFS_WORKING_DIRECTORY);
  ProjectFilesystemDelegate delegate = new DefaultProjectFilesystemDelegate(root);

  Path path = fs.getPath("/foo");
  Files.createFile(path);
  byte[] bytes = new byte[] {66, 85, 67, 75};
  Files.write(path, bytes);
  UserDefinedFileAttributeView view =
      Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);

  ByteBuffer buf = ByteBuffer.allocate(2);
  buf.putChar((char) 0xfffe);
  view.write("sha1", buf);
  EdenMount mount = createMock(EdenMount.class);
  Config config = ConfigBuilder.createFromText("[eden]", "use_xattr = true");
  EdenProjectFilesystemDelegate edenDelegate =
      new EdenProjectFilesystemDelegate(mount, delegate, config);
  assertEquals(
      "EdenProjectFilesystemDelegate.computeSha1() should return the SHA-1 of the contents",
      Sha1HashCode.fromHashCode(Hashing.sha1().hashBytes(bytes)),
      edenDelegate.computeSha1(path));
}
 
Example #9
Source File: SingularityUploader.java    From Singularity with Apache License 2.0 5 votes vote down vote up
UploaderFileAttributes getFileAttributes(Path file) {
  Set<String> supportedViews = FileSystems.getDefault().supportedFileAttributeViews();
  LOG.trace("Supported attribute views are {}", supportedViews);
  if (supportedViews.contains("user")) {
    try {
      UserDefinedFileAttributeView view = Files.getFileAttributeView(
        file,
        UserDefinedFileAttributeView.class
      );
      List<String> attributes = view.list();
      LOG.debug("Found file attributes {} for file {}", attributes, file);
      Optional<Long> maybeStartTime = readFileAttributeAsLong(
        file,
        LOG_START_TIME_ATTR,
        view,
        attributes
      );
      Optional<Long> maybeEndTime = readFileAttributeAsLong(
        file,
        LOG_END_TIME_ATTR,
        view,
        attributes
      );
      return new UploaderFileAttributes(maybeStartTime, maybeEndTime);
    } catch (Exception e) {
      LOG.error("Could not get extra file metadata for {}", file, e);
    }
  }
  return new UploaderFileAttributes(Optional.empty(), Optional.empty());
}
 
Example #10
Source File: DoTestRuleFilterFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@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 #11
Source File: DoTestRuleFilterFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: Executables.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
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 #13
Source File: Executables.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
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 #14
Source File: FileObjTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
/**
 * Delete a user extended attribute from the given file.
 *
 * @param name the name of the attribute which should be deleted
 * @param file the filename from which the attribute should be deleted
 * @throws IOException when the user extended attribute information could
 * not be read
 */
private static void delXattr(String name, String file) {
    UserDefinedFileAttributeView view = getAttributeView(file);
    try {
        view.delete(name);
    } catch (IOException ex) {
        System.out.println("failed to delete the user extended attribute: " + ex.getMessage());
    }
}
 
Example #16
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
/**
 * List all user extended attributes and their related values for the given
 * file.
 *
 * @throws IOException when the user extended attribute information could
 * not be read
 */
private static void dumpAllXattr(String file) {
    UserDefinedFileAttributeView view = getAttributeView(file);

    System.out.printf("# file: %s%n", file);
    try {
        for (String name : view.list()) {
            String value = getAttrValue(view, name);
            System.out.printf("user.%s=\"%s\"%n", name, value);
        }
    } catch (IOException ex) {
        System.out.printf("failed to get the extended attribute informations from %s%n", file);
    }
}
 
Example #17
Source File: FileAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
private static UserDefinedFileAttributeView getAttributeView(String fullPath) {
    UserDefinedFileAttributeView view = Files.getFileAttributeView(Paths.get(fullPath),
            UserDefinedFileAttributeView.class);
    if(view==null){
        throw new RuntimeException("The attribute view type is not available");
    }else {
        return view;
    }
}
 
Example #18
Source File: FileAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
private static String getAttrValue(UserDefinedFileAttributeView view, String name) throws IOException {
    int attrSize = view.size(name);
    ByteBuffer buffer = ByteBuffer.allocateDirect(attrSize);
    view.read(name, buffer);
    buffer.flip();
    return Charset.defaultCharset().decode(buffer).toString();
}
 
Example #19
Source File: FileSystemProcessInstances.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public String getMetadata(Path file, String key) {
    
    if (supportsUserDefinedAttributes(file)) {
        UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
        try {
            ByteBuffer bb = ByteBuffer.allocate(view.size(key));
            view.read(key, bb);
            bb.flip();
            return Charset.defaultCharset().decode(bb).toString();
        } catch (IOException e) {
            return null;
        }
    }
    return null;
}
 
Example #20
Source File: FileAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> getAllXattr(String fullPath) throws IOException {
    Map<String, String> values = Maps.newHashMap();
    UserDefinedFileAttributeView view = getAttributeView(fullPath);
    for (String name : view.list()) {
        String value = getAttrValue(view, name);
        values.put(name, value);
    }
    return values;
}
 
Example #21
Source File: FileAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
public static String getXattr(String name, String fullPath) throws IOException {
    String value = null;
    UserDefinedFileAttributeView view = getAttributeView(fullPath);
    if (view.list().contains(name)) {
        value = getAttrValue(view, name);
    }
    return value;
}
 
Example #22
Source File: FileAttributes.java    From yfs with Apache License 2.0 5 votes vote down vote up
public static void setXattr(Map<String, String> attrs, String fullPath) throws IOException {
    UserDefinedFileAttributeView view = getAttributeView(fullPath);

    for (Map.Entry<String, String> entry : attrs.entrySet()) {
        view.write(entry.getKey(), Charset.defaultCharset().encode(entry.getValue()));
    }
}
 
Example #23
Source File: FileSystemProcessInstances.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected boolean supportsUserDefinedAttributes(Path file) {
    try {
        return Files.getFileStore(file).supportsFileAttributeView(UserDefinedFileAttributeView.class);
    } catch (IOException e) {
        return false;
    }
}
 
Example #24
Source File: UserDefinedAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public Class<UserDefinedFileAttributeView> viewType() {
  return UserDefinedFileAttributeView.class;
}
 
Example #25
Source File: UserDefinedAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public UserDefinedFileAttributeView view(
    FileLookup lookup, ImmutableMap<String, FileAttributeView> inheritedViews) {
  return new View(lookup);
}
 
Example #26
Source File: FileAttributes.java    From yfs with Apache License 2.0 4 votes vote down vote up
public static void delXattr(String name, String file) throws IOException {
    UserDefinedFileAttributeView view = getAttributeView(file);
    view.delete(name);
}
 
Example #27
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 3 votes vote down vote up
/**
 * @param view the attribute view of the extendet attribute for a specific
 * file
 * @param name the name of the attribute for which the value should be
 * returned
 * @return the value of an user extended attribute from the given attribute
 * view
 */
private static String getAttrValue(UserDefinedFileAttributeView view, String name) throws IOException {
    int attrSize = view.size(name);
    ByteBuffer buffer = ByteBuffer.allocateDirect(attrSize);
    view.read(name, buffer);
    buffer.flip();
    return Charset.defaultCharset().decode(buffer).toString();
}
 
Example #28
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the attribute view of the extended attribute for the given file.
 *
 * @param file the filename for which the attribute view should be returned
 * @return
 */
private static UserDefinedFileAttributeView getAttributeView(String file) {
    return Files.getFileAttributeView(Paths.get(file),
            UserDefinedFileAttributeView.class);
}
 
Example #29
Source File: UserExtendedAttributes.java    From yfs with Apache License 2.0 2 votes vote down vote up
/**
 * @return if the passed {@link FileStore} has support for user extended
 * attributes
 */
private static boolean hasUserXattrSupport(FileStore fileStore) {
    return fileStore.supportsFileAttributeView(UserDefinedFileAttributeView.class);
}