Friday, September 18, 2009

Extract image Exif information using Java and ExifTool

Exif is: Exchangeable Image File Format. It is a collection of meta information stored in image files taken by cameras. Sometimes we would like to read and present this information. The amount of Exif information stored today by cameras is quite impressive. It even may include the location where the picture was taken. Among all the Exif information stored in the picture, there is a group of parameters that really interests photographers. Parameters like the focal length in which the picture was taken, the Exposure mode, F-Number, Did the Flash fired when the picture was taken? and so on.

Extracting Exif information is a hard task, since there is very big amount of Camera manufactures and image types and there is no unified standard. Luckily for us, there is a great tool written Perl named: ExifTool (written by Harvey). This tool is available as Windows executable file (can be downloaded from the site). If you are using linux Debian (I develop in Windows, but my server runs under Linux) there is a ready package named: libimage-exiftool-perl

You can install it in Debian like this:

apt-get install libimage-exiftool-perl

and use the command like: exiftool in order to run it.

We will write a Java code that will use ExifTool in order to extract important Exif information from images.

The code is constructed from 2 classes:

  • ExifToolExtractor – This class extracts Exif information from an image using ExifTool and produces an ExifInfo class filled with Exif important information.
  • ExifInfo – This class stores image Exif information.

ExifToolExtractor class is very simple. it uses Process class in order to execute the ExifTool. Then it reads the ExifTool output and parses it. The output is a long list if Exif information, ordered in a key-value manner. For example, this is a partial output of ExifTool:

Make                            : NIKON CORPORATION
Camera Model Name               : NIKON D300
Orientation                     : Horizontal (normal)
X Resolution                    : 300
Y Resolution                    : 300
Resolution Unit                 : inches
Software                        : Ver.1.10
Modify Date                     : 2009:04:18 10:15:35
Artist                          :
Y Cb Cr Positioning             : Co-sited
Copyright                       :
Exposure Time                   : 1/1000
F Number                        : 7.1
Exposure Program                : Aperture-priority AE
ISO                             : 200
Exif Version                    : 0221
Date/Time Original              : 2009:04:18 10:15:35
Create Date                     : 2009:04:18 10:15:35
Components Configuration        : Y, Cb, Cr, -
Compressed Bits Per Pixel       : 2
Exposure Compensation           : -1/3
Max Aperture Value              : 4.8
Metering Mode                   : Multi-segment
Light Source                    : Unknown
Flash                           : No Flash
Focal Length                    : 65.0 mm
Maker Note Version              : 2.10
Quality                         : Normal
White Balance                   : Auto
Focus Mode                      : AF-S
Flash Setting                   : Normal
Flash Type                      :
White Balance Fine Tune         : 0 0
WB RB Levels                    : 1.4765625 1.3359375 1 1
Program Shift                   : 0
Exposure Difference             : 0
Compression                     : JPEG (old-style)
Preview Image Start             : 9128

Note, that this is a partial list. The complete list is much longer and changed from camera to camera. The class ExifToolExtractor doesn’t really care what data is outputted. it simply stores all the data to a HashMap. The HashMap doesn’t actually belongs to the class ExifToolExtractor but to the class ExifInfo which is responsible for storing all Exif information. This is how the class ExifToolExtractor looks like:

package com.bashan.blog.exif;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExifToolExtractor {
  private String exifToolApp;
  public ExifToolExtractor(String exifToolApp) {
    this.exifToolApp = exifToolApp;
  }
  public ExifInfo getExifInfo(String image) throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(exifToolApp, image);
    Process process = processBuilder.start();
    BufferedReader stdInput = new BufferedReader(new
        InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new
        InputStreamReader(process.getErrorStream()));
    String line;
    ExifInfo exifInfo = new ExifInfo();
    while ((line = stdInput.readLine()) != null) {
      exifInfo.parseLine(line);
      System.out.println(line);
    }
    while ((line = stdError.readLine()) != null) {
    }
    process.waitFor();
    return exifInfo;
  }
}

As said before, The class ExifInfo stores a map of all Exif information. But, actually, from all the big amount of information, there are several parameters that are a real interest for Photographers. The class ExifInfo has ready methods for getting these specific information. Take a look at the method parseLine of this class. This is the method that is responsible for taking a line of information from ExifTool and convert it to key-value pair. Here is how the class ExifInfo looks like:

package com.bashan.blog.exif;
import java.util.HashMap;
import java.util.Map;
public class ExifInfo {
  private Map<String, String> exifMap = new HashMap<String, String>();
  public static final String COMPANY = "Make";
  public static final String MODEL = "Camera Model Name";
  public static final String EXPOSURE_TIME = "Exposure Time";
  public static final String F_NUMBER = "F Number";
  public static final String ISO = "ISO";
  public static final String EXPOSURE_COMPENSATION = "Exposure Compensation";
  public static final String FOCAL_LENGTH = "Focal Length";
  public static final String EXPOSURE_PROGRAM = "Exposure Program";
  public static final String DATE_TAKEN = "Create Date";
  public static final String METERING_MODE = "Metering Mode";
  public static final String FLASH = "Flash";
  public static final String FLASH_EXPOSURE_COMPENSATION = "Flash Exposure Compensation";
  public static final String LENS = "Lens ID";
  public void parseLine(String line) {
    int pos = line.indexOf(":");
    if (pos != -1) {
      exifMap.put(line.substring(0, pos).trim(), line.substring(pos + 1).trim());
    }
  }
  public String getCompany() {
    return exifMap.get(COMPANY);
  }
  public String getModel() {
    return exifMap.get(MODEL);
  }
  public String getExposureTime() {
    return exifMap.get(EXPOSURE_TIME);
  }
  public String getFNumber() {
    return exifMap.get(F_NUMBER);
  }
  public String getISO() {
    return exifMap.get(ISO);
  }
  public String getExposureCompensation() {
    return exifMap.get(EXPOSURE_COMPENSATION);
  }
  public String getFocalLength() {
    return exifMap.get(FOCAL_LENGTH);
  }
  public String getExposureProgram() {
    return exifMap.get(EXPOSURE_PROGRAM);
  }
  public String getDateTaken() {
    return exifMap.get(DATE_TAKEN);
  }
  public String getMeteringMode() {
    return exifMap.get(METERING_MODE);
  }
  public String getFlash() {
    return exifMap.get(FLASH);
  }
  public String getFlashExposureCompensation() {
    return exifMap.get(FLASH_EXPOSURE_COMPENSATION);
  }
  public String getLens()
  {
    return exifMap.get(LENS);
  }
  public String toString() {
    return "Company: " + getCompany() + "\n" +
        "Model: " + getModel() + "\n" +
        "Exposure Time: " + getExposureTime() + "\n" +
        "Date Taken: " + getDateTaken() + "\n" +
        "F-Number: " + getFNumber() + "\n" +
        "ISO: " + getISO() + "\n" +
        "Exposure Compensation: " + getExposureCompensation() + "\n" +
        "Metering Mode: " + getMeteringMode() + "\n" +
        "Focal Length: " + getFocalLength() + "\n" +
        "Exposure Program: " + getExposureProgram() + "\n" +
        "Flash: " + getExposureProgram() + "\n" +
        "Flash Exposure Compensation: " + getExposureProgram() + "\n" +
        "Lens: " + getLens();
  }
}

Notice, that ExifTool if quite a comprehensive Exif extraction tool and also supplies information of the Lens used to shoot the picture, which is a nice piece of information for photographers.

This is a small program showing how these 2 classes are working together:

  public static void main(String[] args) throws Exception {
    ExifToolExtractor exifToolExtractor = new ExifToolExtractor("C:\\exiftool(-k).exe");
    ExifInfo exifInfo = exifToolExtractor.getExifInfo("C:\\DSC_0001.JPG");
    System.out.println(exifInfo);
  }

An here is an example of the information extracted from a picture:

Company: NIKON CORPORATION
Model: NIKON D300
Exposure Time: 1/1000
Date Taken: 2009:04:18 10:15:35.68
F-Number: 7.1
ISO: 200
Exposure Compensation: -1/3
Metering Mode: Multi-segment
Focal Length: 65.0 mm (35 mm equivalent: 97.0 mm)
Exposure Program: Aperture-priority AE
Flash: Aperture-priority AE
Flash Exposure Compensation: Aperture-priority AE
Lens: Tamron AF 28-300mm f/3.5-6.3 XR Di VC LD Aspherical [IF] MACRO

Friday, September 4, 2009

Converting ResultSet to Excel table in Java using Apache POI

You can make a great reporting system with impressive UI, but there will always be someone that will ask you: Can you export to excel?

Excel offers many ways of easily manipulating and viewing data out of the box. Therefore, no matters how your reporting system is sophisticated, exporting the result to Excel is quite a basic feature.

Using Apache POI Project to produce Excel output is an easy task. This great project offers a wide support for generating Microsoft Format Files. We will use this open source project to dynamically generate Excel file from a ResultSet.

We will construct a class named: ResultSetToExcel. It’s constructor will get: ResultSet and Excel sheet name. A function named: generate will produce Excel sheet to an OutputStream or to a file. The content of the generated Excel sheet will be a table with headers and ResultSet data.

Building the ResultSetToExcel class introduces 2 main issues:

  • From where do we get the titles for the report?
  • How do we format Excel cells?

This is how we will deal with these 2 issues:

  • Report titles will be taken from query columns by using the ResultSetMetaData class. For example, let’s have a look at this query:
    select first_name 'First Name', last_name 'Last Name', age 'Age' from person
    The names that will be used for our report are: First Name, Last Name and Age. If no specific name is given to a column, then the column name itself will be used.
  • We will use 2 ways for formatting Excel columns:
    • Explicit: In the class constructor, In addition to the ResultSet, we supply a parameter named: formatTypes. This parameter is an array of the static inner enum class named: FormatType. It contains all commonly used format types:

      • Text
      • Integer
      • Float
      • Date
      • Money
      Of course, the items in this array should correspond one-to-one to the columns in our ResultSet. We use this array to format Excel cells according to their nature. This makes the resulted Excel file more neat and professional. Note that these are the most commonly and basic types used. You can add more types quite easily.
    • Automatic: If no formatTypes parameter supplied, we try to “guess” the type of the column, by examining the Java class used for every specific column. We do it by using the private method: getFormatType. Pay attention to 2 important things:
      • The getFormatType method is pretty basic, it doesn’t handle all possible java classes, but you can easily refine it.
      • The “automatic guessing” way is less preferable, because it is not able to give us more fine grained control over the way our cell is formatted. For example: we cannot format a cell as Money or Percentage.

2 last things before moving to code is:

  • The method: writeCell. This method is used to write an excel cell in a formatted way. It formats the cell according to the values in the parameter: formatType. Note, that in order to format the cell the class: HSSFCellUtil is used. This class is not at the core of the POI project, but in additional JAR file named: POI Contrib. This class allows formatting Excel cells in a way that existing formats are automatically reused. It prevents from Excel to generate a new format for each cell causing an Excel formatting error in cases of big tables.
  • After writing ResultSet cells we use the method: autoSizeColumn of the class: HSSFSheet. This method automatically sets the size of each column according to the longest (in that column). This makes the resulted Excel file ready to be viewed.

Well, finally, let’s have a look at the code of our ResultSetToExcel class:

package com.bashan.blog.excel;
import org.apache.commons.lang.exception.NestableException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.contrib.HSSFCellUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
public class ResultSetToExcel {
  private HSSFWorkbook workbook;
  private HSSFSheet sheet;
  private HSSFFont boldFont;
  private HSSFDataFormat format;
  private ResultSet resultSet;
  private FormatType[] formatTypes;
  public ResultSetToExcel(ResultSet resultSet, FormatType[] formatTypes, String sheetName) {
    workbook = new HSSFWorkbook();
    this.resultSet = resultSet;
    sheet = workbook.createSheet(sheetName);
    boldFont = workbook.createFont();
    boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    format = workbook.createDataFormat();
    this.formatTypes = formatTypes;
  }
  public ResultSetToExcel(ResultSet resultSet, String sheetName) {
    this(resultSet, null, sheetName);
  }
  private FormatType getFormatType(Class _class) {
    if (_class == Integer.class || _class == Long.class) {
      return FormatType.INTEGER;
    } else if (_class == Float.class || _class == Double.class) {
      return FormatType.FLOAT;
    } else if (_class == Timestamp.class || _class == java.sql.Date.class) {
      return FormatType.DATE;
    } else {
      return FormatType.TEXT;
    }
  }
  public void generate(OutputStream outputStream) throws Exception {
    try {
      ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
      if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
        throw new IllegalStateException("Number of types is not identical to number of resultset columns. " +
            "Number of types: " + formatTypes.length + ". Number of columns: " + resultSetMetaData.getColumnCount());
      }
      int currentRow = 0;
      HSSFRow row = sheet.createRow(currentRow);
      int numCols = resultSetMetaData.getColumnCount();
      boolean isAutoDecideFormatTypes;
      if (isAutoDecideFormatTypes = (formatTypes == null)) {
        formatTypes = new FormatType[numCols];
      }
      for (int i = 0; i < numCols; i++) {
        String title = resultSetMetaData.getColumnName(i + 1);
        writeCell(row, i, title, FormatType.TEXT, boldFont);
        if (isAutoDecideFormatTypes) {
          Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
          formatTypes[i] = getFormatType(_class);
        }
      }
      currentRow++;
      // Write report rows
      while (resultSet.next()) {
        row = sheet.createRow(currentRow++);
        for (int i = 0; i < numCols; i++) {
          Object value = resultSet.getObject(i + 1);
          writeCell(row, i, value, formatTypes[i]);
        }
      }
      // Autosize columns
      for (int i = 0; i < numCols; i++) {
        sheet.autoSizeColumn((short) i);
      }
      workbook.write(outputStream);
    }
    finally {
      outputStream.close();
    }
  }
  public void generate(File file) throws Exception {
    generate(new FileOutputStream(file));
  }
  private void writeCell(HSSFRow row, int col, Object value, FormatType formatType) throws NestableException {
    writeCell(row, col, value, formatType, null, null);
  }
  private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, HSSFFont font) throws NestableException {
    writeCell(row, col, value, formatType, null, font);
  }
  private void writeCell(HSSFRow row, int col, Object value, FormatType formatType,
                         Short bgColor, HSSFFont font) throws NestableException {
    HSSFCell cell = HSSFCellUtil.createCell(row, col, null);
    if (value == null) {
      return;
    }
    if (font != null) {
      HSSFCellStyle style = workbook.createCellStyle();
      style.setFont(font);
      cell.setCellStyle(style);
    }
    switch (formatType) {
      case TEXT:
        cell.setCellValue(value.toString());
        break;
      case INTEGER:
        cell.setCellValue(((Number) value).intValue());
        HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT,
            HSSFDataFormat.getBuiltinFormat(("#,##0")));
        break;
      case FLOAT:
        cell.setCellValue(((Number) value).doubleValue());
        HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT,
            HSSFDataFormat.getBuiltinFormat(("#,##0.00")));
        break;
      case DATE:
        cell.setCellValue((Timestamp) value);
        HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.DATA_FORMAT,
            HSSFDataFormat.getBuiltinFormat(("m/d/yy")));
        break;
      case MONEY:
        cell.setCellValue(((Number) value).intValue());
        HSSFCellUtil.setCellStyleProperty(cell, workbook,
            HSSFCellUtil.DATA_FORMAT, format.getFormat("($#,##0.00);($#,##0.00)"));
        break;
      case PERCENTAGE:
        cell.setCellValue(((Number) value).doubleValue());
        HSSFCellUtil.setCellStyleProperty(cell, workbook,
            HSSFCellUtil.DATA_FORMAT, HSSFDataFormat.getBuiltinFormat("0.00%"));
    }
    if (bgColor != null) {
      HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_FOREGROUND_COLOR, bgColor);
      HSSFCellUtil.setCellStyleProperty(cell, workbook, HSSFCellUtil.FILL_PATTERN, HSSFCellStyle.SOLID_FOREGROUND);
    }
  }
  public enum FormatType {
    TEXT,
    INTEGER,
    FLOAT,
    DATE,
    MONEY,
    PERCENTAGE
  }
}

This class can be downloaded here.

The JARs for this class can be downloaded from: Apache POI Project. Both POI and POI Contrib Jars are needed.

This is a small example of how this class can be used:

  public void createExecl(Connection conn) throws Exception
  {
    PreparedStatement stmt = conn.prepareStatement("select first_name 'First Name', last_name 'Last Name', age 'Age', " +
        "salary 'Salary'");
    ResultSet resultSet = stmt.executeQuery();
    ResultSetToExcel resultSetToExcel = new ResultSetToExcel(resultSet,
        new ResultSetToExcel.FormatType[] { ResultSetToExcel.FormatType.TEXT, ResultSetToExcel.FormatType.TEXT,
            ResultSetToExcel.FormatType.INTEGER, ResultSetToExcel.FormatType.MONEY }, "Employee List");
    resultSetToExcel.generate(new File("c:\\employees.xls"));
  }

Saturday, August 29, 2009

Tracking User Sessions in a web application using Java

Sometimes we would like to keep track after users in our web application. We would like to see how many active sessions we have and even which of the users are guests and which are logged. Java supplied an Interfaces called HttpSessionListener that can help us achieving this goal. This interface supplies 2 methods:

  • sessionCreated – Activated when a new session is created.
  • sessionDestroyed – Activated when session expires and being deleted from server.

Using this 2 methods we can implement our own Session Tracker. We will store all the currently active sessions in a Set.

This is our SessionTracker class implementing HttpSessionListener. The code is pretty straight forward and easy to understand:

package com.bashan.blog.session;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.*;
public class SessionTracker implements HttpSessionListener {
  private static Set<HttpSession> sessions = new HashSet<HttpSession>();
  public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    sessions.add(httpSessionEvent.getSession());
  }
  public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    sessions.remove(httpSessionEvent.getSession());
  }
  public static List<HttpSession> getSessions() {
    List<HttpSession> sessionsList = new ArrayList<HttpSession>(sessions);
    Collections.sort(sessionsList, new SessionComparator());
    return Collections.unmodifiableList(sessionsList);
  }
  public static class SessionComparator implements Comparator<HttpSession> {
    public int compare(HttpSession session1, HttpSession session2) {
      return (int) (session1.getLastAccessedTime() - session2.getLastAccessedTime());
    }
  }
}

Note that we return the currently active sessions as a list sorted according to the last access time. Of course, you can choose another way of sorting the sessions. In addition, note that we are using a static Set member in order to store all the active sessions. You might want to consider synchronization when adding or removing objects to/from the set. I believe that the chances of a synchronization issues in this case are pretty low, but sometimes it is better not taking any chances… ;-)

Our next step is to register our SessionTracker, so the Web Server will be able to use it. This is done in the web.xml file of our Web Server. considering our web server web.xml was empty, after registering the SessionTracker it should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <listener>
    <listener-class>
      com.bashan.blog.session.SessionTracker
    </listener-class>
  </listener>
</web-app>

Now, suppose we would like to see all the active sessions in our web application. We can write a small JSP page that will show a table of all active sessions:

<%@ page import="com.bashan.blog.session.SessionTracker" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Active Sessions</title>
    <style type="text/css">
      .bold
      {
          font-weight:bold;
      }
      .tableBorder
        {
          BORDER-RIGHT: #000000 1px solid;
          BORDER-TOP: 0px;
          BORDER-LEFT: 0px;
          BORDER-BOTTOM: #000000 1px solid
        }
      .tdBorder
        {
          BORDER-RIGHT: 0px;
          BORDER-TOP: #000000 1px solid;
          BORDER-LEFT: #000000 1px solid;
          BORDER-BOTTOM: 0px
        }
    </style>
  </head>
  <body>
  <table class="tableBorder" cellpadding="4" cellspacing="0">
    <tr>
      <td class="tdBorder bold">
        Last Activity
      </td>
      <td class="tdBorder bold">
        Created
      </td>
      <td class="tdBorder bold">
        Session ID
      </td>
    </tr>
    <%
      List<HttpSession> sessions = SessionTracker.getSessions();
      for (HttpSession currentSession : sessions)
      {
    %>
    <tr>
      <td class="tdBorder">
        <%= new Date(currentSession.getLastAccessedTime()) %>
      </td>
      <td class="tdBorder">
        <%= new Date(currentSession.getCreationTime()) %>
      </td>
      <td class="tdBorder">
        <%= currentSession.getId() %>
      </td>
    </tr>
    <%
      }
    %>
  </table>
  </body>
</html>
Assuming your web application allow users to login to the system, you probably store logged user information in the Session. It will be nice adding a column showing logged user details like user name, email or any other important information.