Monday, August 11, 2014

Using Labmda Expression in File Filtering

Java 8 makes it so easy to write the anonymous functions which can be understood using the following file filtering example:

Before Java 8:
    public static List fileList(String directory) {
        List fileNames = new ArrayList<>();
        
        DirectoryStream.Filter filter = 
              new DirectoryStream.Filter() {
         @Override
         public boolean accept(Path file) throws IOException {
           return (Files.size(file) > 8192L);
         }
        };
        
        try (DirectoryStream directoryStream = 
          Files.newDirectoryStream(Paths.get(directory), filter)) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }
With Java 8:
    public static List fileListWithLambda(String directory) {
        List fileNames = new ArrayList<>();
        
        DirectoryStream.Filter filter = 
          (Path file) -> (Files.size(file) > 8192L);
        
        try (DirectoryStream directoryStream = 
          Files.newDirectoryStream(Paths.get(directory), filter)) {
            for (Path path : directoryStream) {
                fileNames.add(path.toString());
            }
        } catch (IOException ex) {}
        return fileNames;
    }

Converting PPT to Png

public class PptToPng {

    public static void main(String[] args) throws Exception {
        FileInputStream is = new FileInputStream("example.pptx");
        XMLSlideShow ppt = new XMLSlideShow(is);
        is.close();

        double zoom = 2; // magnify it by 2
        AffineTransform at = new AffineTransform();
        at.setToScale(zoom, zoom);

        Dimension pgsize = ppt.getPageSize();

        XSLFSlide[] slide = ppt.getSlides();
        for (int i = 0; i < 2; i++) {
          BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), 
                    (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
          Graphics2D graphics = img.createGraphics();
          graphics.setTransform(at);

          graphics.setPaint(Color.white);
          graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
          slide[i].draw(graphics);
          FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
          javax.imageio.ImageIO.write(img, "png", out);
          out.close();
        }
    }
}