Showing posts with label jsr203. Show all posts
Showing posts with label jsr203. Show all posts

Wednesday, October 31, 2012

Java 7: File Filtering using NIO.2 - Part 2

Hello all. This is Part 2 of the File Filtering using NIO.2 series. For those of you who haven't read Part 1, here's a recap.

NIO.2 is a new API for I/O operations included in the JDK since Java 7. With this new API, you can perform the same operations performed with java.io plus a lot of great functionalities such as: Accessing file metadata and watching for directory changes, among others. Obviously, the java.io package is not going to disappear because of backward compatibility, but we are encouraged to start using NIO.2 for our new I/O requirements. In this post, we are going to see how easy it is to filter the contents of a directory using this API. There are 3 ways in order to do so, we already review one way in Part 1 and now we are going to see  another approach.

What you need
NetBeans 7+ or any other IDE that supports Java 7

Filtering content of a directory is a common task in some applications and NIO.2 makes it really easy. The classes and Interfaces we are going to use are described next:
  • java.nio.file.Path: Interface whose objects may represent files or directories in a file system. It's like the java.io.File but in NIO.2. Whatever I/O operation you want to perform, you need an instance of this interface.
  • java.nio.file.PathMatcher: Interface that allows objects to perform match operations on paths.
  • java.nio.file.DirectoryStream: Interface whose objects iterate over the content of a directory.
  • java.nio.file.Files: Class with static methods that operates on files, directories, etc.

The way we are going to filter the contents of a directory is by using objects that implement the java.nio.file.PathMatcher interface. We can get one of these objects with the help of the java.nio.file.Files class, using the method +getPathMatcher(String):PathMatcher. This method supports both "glob" and "regex" patterns. You can check Part 1 of File Filtering using NIO.2 for more information about "glob" and for "regex" visit the java.util.regex.Pattern class. The pattern is matched against the name of the files, directories, etc. That live inside the directory. This is important to remember, using this method you can only filter by the name of the file, directory, etc.

For example, if you want to filter .png and .jpg images, you should use one of the following syntax and pattern (notice the colon between the syntax and the pattern):
  • "glob:*.{png,jpg}"
  • "regex:([^\s]+(\.(?i)(png|jpg))$)"

Of course, "glob" syntax is much simpler, but you have the option of using regular expressions for a more detailed match. Anyway, you may be wondering why you should use this approach if the java.nio.files.DirectoryStream interface allows you to filter directly using "glob"... Well, let's suppose that you already have a filter, but you need to perform more than one filtering operation, that's when you need to use this approach.

The following piece of code defines a method which scans a directory using different patterns:

//in a class...
    
    /**
     * Scans the directory using the patterns passed 
     * as parameters. 
     * Only 3 patterns will be used.
     * @param folder directory to scan
     * @param patterns The first pattern will be used
     * as the glob pattern for the DirectoryStream.     
     */
    private static void scan(String folder, String... patterns) {
        //obtains the Images directory in the app directory
        Path dir = Paths.get(folder);
        //the Files class offers methods for validation
        if (!Files.exists(dir) || !Files.isDirectory(dir)) {
            System.out.println("No such directory!");
            return;
        }
        //validate at least the glob pattern
        if (patterns == null || patterns.length < 1) {
            System.out.println(
                "Please provide at least the glob pattern.");
            return;
        }

        //obtain the objects that implements PathMatcher
        PathMatcher extraFilterOne = null;
        PathMatcher extraFilterTwo = null;
        if (patterns.length > 1 && patterns[1] != null) {
            extraFilterOne = FileSystems.getDefault().
                                 getPathMatcher(patterns[1]);
        }
        if (patterns.length > 2 && patterns[2] != null) {
            extraFilterTwo = FileSystems.getDefault().
                                 getPathMatcher(patterns[2]);
        }

        //Try with resources... so nice!
        try (DirectoryStream ds = 
                  Files.newDirectoryStream(dir, patterns[0])) {
            //iterate over the content of the directory and apply 
            //any other extra pattern
            int count = 0;
            for (Path path : ds) {
                System.out.println(
                          "Evaluating " + path.getFileName());

                if (extraFilterOne != null && 
                    extraFilterOne.matches(path.getFileName())) {
                    System.out.println(
                                  "Match found Do something!");
                }

                if (extraFilterTwo != null && 
                    extraFilterTwo.matches(path.getFileName())) {
                    System.out.println(
                             "Match found Do something else!");
                }

                count++;
            }
            System.out.println();
            System.out.printf(
                 "%d Files match the global pattern\n", count);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

You can try invoking the last method with the following parameters:

  • C:\Images or /Images depending on your OS.
  • ?_*.jpg This pattern specifies that you want all .jpg images whose name starts with one digit followed by an underscore.
  • glob:2_* Specifies another filter (using glob syntax) where you only want items whose name starts with the number two followed by an underscore.
  • glob:3_* Specifies another filter (using glob syntax) where you only want items whose name starts with the number three followed by an underscore.

Having several filters allows you to take different actions for matched items.
Following is the result of the execution on my windows machine:



And on my Linux virtual machine:



Again, Write once, run everywhere! However, notice that the ordering of the items is system dependent, so do not ever hardcode the position of a file or directory.

I hope you enjoyed this post, there is another more powerful way to filter the content of a directory and we'll explore it in Part 3.

Click here to download the source code.


See ya!

References:

Reese Richard and Reese Jennifer (2012). Java 7 New Features Cookbook. United Kingdom: Packt Publishing Ltd.

Friday, October 19, 2012

Java 7: File Filtering using NIO.2 - Part 1

Hello all. NIO.2 is a new API for I/O operations included in the JDK since Java 7. With this new API, you can perform the same operations performed with java.io plus a lot of great functionalities such as: Accessing file metadata and watching for directory changes, among others. Obviously, the java.io package is not going to disappear because of backward compatibility, but we are encouraged to start using NIO.2 for our new I/O requirements. In this post, we are going to see how easy it is to filter the contents of a directory using this API. There are 3 ways in order to do so, that's why this post is Part 1.

What you need
NetBeans 7+ or any other IDE that supports Java 7
JDK 7+

Filtering content of a directory is a common task in some applications and NIO.2 makes it really easy. The classes and Interfaces we are going to use are described next:
  • java.nio.file.Path: Interface whose objects may represent files or directories in a file system. It's like the java.io.File but in NIO.2. Whatever I/O operation you want to perform, you need an instance of this interface.
  • java.nio.file.DirectoryStream: Interface whose objects iterate over the content of a directory.
  • java.nio.file.Files: Class with static methods that operates on files, directories, etc.

The way we are going to filter the contents of a directory is by using glob patterns, which are like regular expressions but simpler. The pattern is matched against the name of the files, directories, etc. That live inside the directory. This is important to remember, using this method you can only filter by the name of the file, directory, etc.
For more information about globbing, check this wiki. Also, there is some documentation about globbing patterns in the Java Docs.

So, let's suppose that we have a directory called Images, and we need to iterate over the files inside this directory, but we only need the .png files. We have to follow this steps in order to do so:
  1. Obtain a java.nio.file.Path instance which points to the directory Images.
  2. Open a new java.nio.file.DirectoryStream using the java.nio.file.Files class and passing the directory and the pattern (*.png) as parameters.
  3. Iterate over the content of the directory using the java.nio.file.DirectoryStream instance.
Next is the source code of a method that scans a directory using the pattern passed as parameter:

//in a class...
    
    /**
     * Scans the directory using the glob pattern passed 
     * as parameter. 
     * @param folder directory to scan
     * @param pattern glob pattern (filter)
     */
    private static void scan(String folder, String pattern) {
        //obtains the Images directory in the app directory
        Path dir = Paths.get(folder);
        //the Files class offers methods for validation
        if (!Files.exists(dir) || !Files.isDirectory(dir)) {
            System.out.println("No such directory!");
        }
        //Try with resources... so nice!
        try (DirectoryStream<path> ds = 
                    Files.newDirectoryStream(dir, pattern)) {
            //iterate over the content of the directory
            int count = 0;
            for (Path path : ds) {
                System.out.println(path.getFileName());
                count++;
            }
            System.out.println();
            System.out.printf("%d Files match the pattern"
                                                     , count);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


Following is the result of the execution on my windows machine:



And on my Linux virtual machine:


That's something I love from Java, Write once, run everywhere! I hope you enjoyed this post, there are more ways to filter the content of a directory and we'll explore them in future posts.

Click here to download the complete source code.

See ya!

References:

Reese Richard and Reese Jennifer (2012). Java 7 New Features Cookbook. United Kingdom: Packt Publishing Ltd.

Tuesday, September 25, 2012

Java 7 conference at UAO - Summary

Hello again. My participation at UAO's event "Día de la Informática y la Multimedia" was a success, I had my talk about Java 7 on Thursday September 20 and it went pretty well. It was a lot of fun, we had about 50-60 assistants, most of them students and some teachers. Few questions were asked at the end of the presentation, I post some of them here giving further explanation:


Q: What happens if there are exceptions when the try with resources automatically calls the close method?
A: The new Interface java.lang.AutoCloseable defines only one method: close():void which throws a java.lang.Exception. So when you define your resources in a try with resources structure, the compiler will warn you about catching the exception. So, whichever exception is thrown during the execution of the close():void method, you will be able to catch it in your try with resources structure.
Something I didn't mention during the presentation, is that there are new methods in the java.lang.Throwable class that allows you to keep track of all the exceptions that were suppressed in order to deliver a specific exception. The methods are:


Q: What about IPv6 support in Java 7?
A: According to this documentation, Java began supporting IPv6 since J2SE 1.4 back in February 2002, but only Solaris and Linux OS were supported. Since version J2SE 1.5 Windows OS is also supported. Even though, there are some considerations you should be aware of if you want your java IPv4 applications running on IPv6, for example:


Q: Any support for 3D?
A: Java 3D is a special API that enables the creation of three-dimensional graphics applications and Internet-based 3D applets. It is not part of the Java SE so you have to download it and add it to your application libraries. For more information about this API, check its official home page.

Q: What else has Java for developers?
A: The Java platform offers a lot to developers, it allows them to build cross-platform applications. "Write once, run everywhere" is a serious thing to Java. It is everywhere from PCs, to TVs, phones, mobile devices, bluerays,  kindles... etc. The features that every release of Java SE offers are the base of the Java platform.


Java 7, 1+ año después
That was the name of my presentation and you can download it using the following link: Download PDF File
More info about the event can be found here (spanish).

See ya!

Saturday, September 22, 2012

Java 7 conference for ASUOC - Summary

Colombia Oracle Users Group
Hello again. My participation at ASUOC's meeting was a success, I had my talk about Java 7 on Thursday September 13, and it went pretty well. It was a lot of fun, we had about 30 assistants on site and 1027 visitors online (according to the streaming stats). Few questions were asked at the end of the presentation, I post some of them here, giving further explanation:

Q: Is there really any difference in performance when migrating if-else structures to switch structures?
A: There are a lot of discussions about this topic, but if you look at the decompiled code, you will notice that a switch with String cases is translated into two switches at compile time. In the first one, every case is an if statement and if there are Strings with the same hash code, then you'll get an if-else-if statement. So what if many of your String objects have the same hash code?... You will get a long (depending in your cases)  if-else-if statement inside a switch statement and then, the performance of the application may not be the best (but not the worst).
Anyway, I think it is hard to get many String objects with the same hash code in a real scenario, this is a good feature and I'm pleased we have it now.

Q: Do you know if there have been issues with applications compiled for previous versions of Java when running in Java 7?
A: There is a list of Deprecated API that you should be aware of, so you don't use it in your code: Java 7 Deprecated API
On the other hand, some companies publish something called "certification matrix" for their products, so you can know if they can work with some technology, like Java 7. For example, Oracle E-Business Suite is not yet certified to be used with Java 7.

Q: Did you make any change to the NIO.2 example in order to run it in Linux OS?
A: The NIO.2 example was the same for Windows OS as for Linux OS. In Java there's a saying "write once, run everywhere" so you can run the same code in a Windows or Linux machine. Nevertheless, you should know that different file systems have different notions about which attributes should be tracked for a file, as noted in the Managing Metadata (File and File Store Attributes) Tutorial.

Java 7, 1+ año después
That was the name of my presentation and you can download it using this link (in spanish): Download PDF File.

The presentation was also recorded but is not uploaded yet. I will update this post as soon as the presentation is available.
Following you will find the links to the conference (spanish, 01:30 aprox.):



See ya!

Wednesday, September 19, 2012

Java 7 conference at UAO

Hello all, continuing with the Java 7 conference series, I've been invited to talk about Java 7 at Universidad Autónoma during its event: "Día de la Informática y la Multimedia", so if you are around and want to learn the new features that Java 7 has for you, please come and join us. I will be presenting Project Coin, NIO.2 and the Fork/Join Framework. Pretty much the same content as the conference at Universidad Icesi last week.

The information of my presentation is as follows:

LanguageSpanish
WhereUniversidad Autónoma
Aulas 4 Torreon 1A
Cali, Colombia
WhenSeptember 20th 2012
14:00 - 15:30 (GMT-5)

More info (in spanish):
Universidad Autonóma

See ya!


Monday, September 10, 2012

Java 7 conference for ASUOC

Colombia Oracle Users Group
Hello all, I'm attending a Colombia Oracle Users Group meeting this week and I'll be speaking at it about Java 7, so if you are around, please come and join us. You can also watch the event via streaming at ASUOC's web site. I will be speaking at the event presenting Project Coin, NIO.2 and the Fork/Join Framework.

The information of my presentation is as follows:

LanguageSpanish
WhereICESI University
Auditorio Varela S.A.
Cali, Colombia
WhenSeptember 13th 2012
16:00 - 17:30 (GMT-5)

More info (in spanish):

Colombia Oracle Users Group
ICESI University

See ya!


Friday, June 29, 2012

Campus Party Colombia 2012 - CPCO5 - Second Part

Hello again. My first participation in Campus Party Colombia 2012 is over, I had my talk about Java 7 yesterday,  Thursday June 29, and it went pretty well. It was a lot of fun and networking, not like the Java One though, but there were so many things to see rather than just conferences about technology. There were gaming contests, programming contests, robots exhibitions, music, etc..

I liked it that conferences are not given in rooms, but in open spaces, so assistants can stop and listen to you. I also enjoyed surfing the web at 16 mbs... nice! There were three great speakers that day: Jon Hall Maddog (yes... the Executive Director of Linux International... omg!), Andrés Velásquez (computers CSI) and, of course... ME!!

Some things to improve in the logistics, I missed the way JavaOne (Oracle) treats speakers with food/drinks and spaces to interact with each other, but in the end, it was a lot of fun, I'm not sure how the asistants can stay the whole week in the arena... camping with temperatures of 50-60 °F, but I can say they don't sleep a lot with those fights in starcraft or many other video games.


Y tú ¿ya Javas 7?
That's the name of my presentation and you can download it using this link: Download PDF File
The presentation is also recorded and uploaded at YouTube (in spanish):



I also took some pictures:



Official Information
If you are looking for official information about Campus Party Colombia CPCO5, check the following links:
Official pics of the event 
Official web site of the event

see ya!!

Tuesday, June 26, 2012

Campus Party Colombia 2012 - CPCO5

Hello all, Campus Party Colombia (#CPCO5) is ON!! and I'm having a Java 7 presentation at this event, so if you are around, please come and join us. I will be speaking at the event presenting the Colombia Java Users Group and talking about Project Coin and NIO.2.

The information of my presentation is as follows:

LanguageSpanish
WhereCorferias
Innovation/Development Section
Bogotá, Colombia
WhenJune 28th 2012
9pm-10pm (GMT-5)

More info (in spanish):

Colombia Java Users Group official web site
Campus Party Colombia

See ya!


Tuesday, May 1, 2012

Java 7 New Features Cookbook Review Part 1

Portada del libro tomada de
http://www.packtpub.com
Wondering what new features Java 7 has for you, but you don't know where to start? Well, in this post I'm going to start my review of the book "Java 7 New Features Cookbook", written by Richard M. Reese and Jennifer L. Reese, and published by PACKT.

By now I have read the first and second chapters of the book and can tell you how easy it is to read and understand the recipes. The recipes are written in the form "Getting ready - How to do it - How it works - There's more..." which allows you to start using the new features very fast and avoid pitfalls.

Looking at the table of contents you realize that the book covers all major improvements done for Java 7:
  • Chapter 1 is dedicated to Project Coin (JSR334), those small changes to the language that as developers, we'll love.
  • Chapters 2, 3, 4, 5 and 6 are deeply dedicated to the new Java IO named NIO.2 (JSR203).
  • Chapter 7 and 8 explain the graphical user interface and event handling improvements.
  • Chapter 9 is about database, security and system enhancements.
  • Chapter 10 is dedicated to the fork/join framework (JSR166).
As you can see, the major improvements of Java 7 (Project Coin, NIO.2 and the fork/join framework) are being covered in this book, that's why I recommend it if you want to upgrade your knowledge of Java to it's latest version.

One more thing, the book is published in a lot of formats: printed book, kindle, PDF, ePub, so you have many options to read it. I have the kindle edition and it looks great on my kindle, paragraphs are well formatted and the source code is easy to read.

For more information about  this book go to:
http://www.packtpub.com/java-7-new-features-cookbook/book

See ya!