Tuesday, September 18, 2012

JDK7: When Using the SecureDirectoryStream class

The java.nio.file package's SecureDirectoryStream class is designed to be used with applications that depend on tighter security than that provided by other IO classes.

It supports race-free (sequentially consistent) operations on a directory, where the operations are performed concurrently with other applications.

This class requires support from the operating system. An instance of the class is obtained by casting the return value of the Files class' newDirectoryStream method to a SecureDirectoryStream object. If the cast fails, then the underlying operating system does not support this type of stream.

Getting ready
-----------------
To get and use a SecureDirectoryStream object:
  1. Create a Path object representing the directory of interest.

  2. Use the Files class' newDirectoryStream method, and cast the result to a SecureDirectoryStream.

  3. Use this object to affect SecureDirectoryStream operations.

How to do it
-----------------
  1. Create a new console application.
    In the main method, add the following code. We will create a Path object for the docs directory and then obtain a SecureDirectoryStream object for it.
    This will be used to view the POSIX permissions for the directory.

  2. Execute the application on a system that supports the SecureDirectoryStream class.
    The following output was obtained by running the application on an Ubuntu/Mac system:

    GROUP_EXECUTE OWNER_WRITE OWNER_READ OTHERS_EXECUTE GROUP_READ OWNER_EXECUTE OTHERS_READ
How it works
-----------------
A Path object for the docs directory was obtained and then used as the argument of the Files class' newDirectoryStream method.
The result of the method was cast to a SecureDirectoryStream class. The getFileAttributeView method was then executed to obtain a view, which was used to display the POSIX file permissions for the directory.

References
---------------
1- JDK7: Part 1- The power of java 7 NIO.2 (JSR 203) (important concepts)