Showing posts with label converter. Show all posts
Showing posts with label converter. Show all posts

Wednesday, September 30, 2009

Java Video to FLV (Flash Video) converter using FFmpeg

This post should have been written one or two years ago, with the Exit of YouTube and the big promise of the video content on the internet. But, as with every big buzz, the world has already taken it's next step towards smart phones and social networks.
YouTube and all the other video web sites allow uploading a video file. This video file can be shown on the web using a Flash based video player. The Flash video player can play FLV files. FLV file stands for: Flash Video File, which is a video file quite similar to WMV, MPG, AVI etc'.
So, as you can understand, the basic step towards building your own video site, is knowing to convert uploaded video files from all kinds to FLV. Doing the video conversion is a very complex job, requiring a great knowledge. Luckily for us, there is a great open source project named: FFmpeg, which, among the rest, allows us to convert almost any video from any type to any type. FFmpeg is a cross platform project. Whether you have Linux servers or Windows server (or any other popular operating system), FFmpeg will be available for you.
First, in order to do video conversion, we will have to download FFmpeg. If you are using Windows, you can find on the web compiled version ready for use. I found mine here.
FFmpeg is command line application. It has many options and parameters. In general, in order to convert a video file from any type to FLV we have to run FFmpeg with the following parameters:
ffmpeg -i "C:\filein.mp4" -ar 44100 -s 320x200 -qscale 5 "C:\fileout.flv"

This command takes a file named “filein.mp4” and converts it to FLV video file named: “fileout.flv”. The out video file dimensions is: 320x200. The parameter “qscale” defines the quality of the resulted video. Lower values give better quality. This parameter is not mandatory. Of course that the higher the quality of the video the higher the weight of the resulted file.

We will wrap the FFmpeg command line tool with Java code. We do it by simply executing the above command from Java. This will enable us to convert video to FLV file. These FLV files could be later played by some Flash Video Player (for example , to show the video on the web). A great free Flash based video player is: JW FLV Media Player. It supports many modern features required from a flash player. Some of them are:

  • Full events support allowing to control the video and get notifications from JavaScrip.
  • It allows using plugins.
  • It supports playing a video from any point (just like YouTube).
  • It can play videos directly from YouTube.

These are only some of the features this player has.

Let have a look at out Java Video to FLV converter. It’s code is very simple and straight forward:

package com.bashan.blog.video;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FLVConverter {
    private String ffmpegApp;
    public FLVConverter(String ffmpegApp) {
        this.ffmpegApp = ffmpegApp;
    }
    public void convert(String filenameIn, String filenameOut, int width, int height) throws IOException, InterruptedException {
        convert(filenameIn, filenameOut, width, height, -1);
    }
    public int convert(String filenameIn, String filenameOut, int width, int height, int quality)
            throws IOException, InterruptedException {
        ProcessBuilder processBuilder;
        if (quality > -1) {
            processBuilder = new ProcessBuilder(ffmpegApp, "-i", filenameIn, "-ar", "44100",
                    "-s", width + "*" + height, "-qscale", quality + "", filenameOut);
        } else {
            processBuilder = new ProcessBuilder(ffmpegApp, "-i", filenameIn, "-ar", "44100",
                    "-s", width + "*" + height, filenameOut);
        }
        Process process = processBuilder.start();
        InputStream stderr = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) ;
        {
        }
        return process.waitFor();
    }
}

And here is a small test program that does exactly what the above command line example is doing:

    public static void main(String[] args) throws Exception {
        FLVConverter FLVConverter = new FLVConverter("C:\\Users\\merdok\\IdeaProjects\\dev\\tools\\ffmpeg\\ffmpeg.exe");
        FLVConverter.convert("C:\\filein.mp4", "C:\\fileout.flv", 320, 200, 5);
    }
You can also download the converter here.

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"));
  }

Monday, May 18, 2009

JSF input - empty value converted to Zero

When running a JSF application under Tomcat, you might encounter a weird case in which an empty value of a field bidden with numeric property (like Integer) is converted to zero instead of remaining "null".

Consider the following case, in which text field is used to input Integer value:

<h:inputText id="myInput" value="#{myBean.myInteger}" converter="IntegerConverter" />

And the bean holding the value:

package com.bashan.blog.jsf;
public class MyBean {
  private Integer myInteger;
  public Integer getMyInteger() {
    return myInteger;
  }
  public void setMyInteger(Integer myInteger) {
    this.myInteger = myInteger;
  }
}
Apparently, Tomcat is coercing “null” values to zeroes. This behavior can be disabled by setting the following JVM parameter to "false":
-Dorg.apache.el.parser.COERCE_TO_ZERO=false

By default the “true” value is used. By setting this value to “false” Tomcat will no longer try to coerce value expressions.

You can also set this parameter in Java code. This may be a better idea, if you don’t want to remember to set this parameter on each new environment you deploy your web application. Here is how it can be done:

System.getProperties().put("org.apache.el.parser.COERCE_TO_ZERO", "false");

You can run this code when your server first loads in some initialization Servlet.

If I recall correct, this behavior was changed sometime along the development of Tomcat. That means you can experience different behaviors on different environments of Tomcat. For example, Production environment behaves differently from Development environment, since there are 2 distinct versions of Tomcat. This may cause a bit confusion, when trying to identify the problem.

Monday, March 23, 2009

Java Currency Converter using Yahoo Finance API – Currency Matrix

On the post Basic Java Currency converter using Yahoo Finance API I showed how currency exchange rate information can be easily acquired.

Getting a single exchange rate between two currencies is a nice thing, but it can be inefficient, if one would like to get several currencies exchange rate information. Since the Acquiring the information requires a request to Yahoo servers, making multiple requests in order to get several exchange rates is an expensive operation. Luckily, Yahoo API allows getting more than one exchange rate information on a single request.

The structure for getting more than one currency information at a single request is pretty straight forward and can be easily deduced from the basic request I was showing on the previous post:

http://download.finance.yahoo.com/d/quotes.csv?s=[From Currency][To Currency]=X&...&s=[From Currency][To Currency]=X&f=l1&e=.cs

For example, getting 3 currencies information on a single request for the following currency pairs:

  • USD, ILS
  • USD, JPY
  • USD, GBP

Looks like:

http://download.finance.yahoo.com/d/quotes.csv?s=USDILS=X&s=USDJPY=X&s=USDGBP=X&f=l1&e=.cs

Extending our YahooCurrencyConverter from the previous post, to get currency information of more than one currency pair, is quite easy and therefore, I will jump directly to the main goal of this post: Getting currencies matrix information. Currency matrix information is a neat way of showing currency exchange rates of several currencies on a single table. Currency matrix can be illustrated easily by example. Currency matrix for the currencies: ILS, USD, GBP looks like:

         ILS     USD     GBP
ILS            0.247   0.170
USD    4.044           0.686
GBP    5.893   1.457        
In order to add currency matrix information, we will first do 2 things:
  • Add a new class named: CurrencyPair. This class represents the relation between 2 currencies.
  • Add a new method to the interface CurrencyConverter. This method defines a way of getting exchange rate information for several currencies.

Note, that the code in this post relies on the code from the post: Basic Java Currency converter using Yahoo Finance API.

This is the code of CurrencyPair class:
public class CurrencyPair {
    private String from;
    private String to;
    float price;
    public CurrencyPair(String from, String to)
    {
      this.from = from;
      this.to = to;
    }
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public String getTo() {
        return to;
    }
    public void setTo(String to) {
        this.to = to;
    }
    public float getPrice()
    {
        return price;
    }
}

This is the code of CurrencyConverter interface:
public interface CurrencyConverter {
    public float convert(String currencyFrom, String currencyTo) throws Exception;
    public void convert(CurrencyPair[] currencyPairs) throws Exception;
}


Now, we will add a new abstract class that will do the currency matrix calculations. Note that the currency matrix calculations relays on the new convert method added to CurrencyConverter interface:

public abstract class BaseCurrencyConverter implements CurrencyConverter {
    public CurrencyPair[][] getConversionMatrix(String... currencies) throws Exception {
        // Build pair combinations
        int size = currencies.length;
        CurrencyPair[] currencyPairs = new CurrencyPair[size * size];
        int index = 0;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                currencyPairs[index++] = new CurrencyPair(currencies[i], currencies[j]);
            }
        }
        // Get currencies information
        convert(currencyPairs);
        // Build matrix
        CurrencyPair[][] matrix = new CurrencyPair[size][size];
        index = 0;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                matrix[i][j] = i != j ? currencyPairs[index] : null;
                index++;
            }
        }
        return matrix;
    }
}

The method getConversionMatrix in the abstract class BaseCurrencyConverter builds currency matrix information for any class implementing the convert method. It does not care about how the convert method is implemented. The method receives a list of currencies for which we would like to build the matrix. From the list it builds all combinations between any 2 currencies. After building list of combinations, the abstract convert method is activated, to get the actual currency information. The final part of the class arranges the results in a 2 dimensional array, for easier data access.


Finally, after laying the structure, we can go back to the main implementing class: YahooCurrencyConverter. We don’t really have much more work to do, since the matrix creation is done on the abstract class. We just have to implement the new added convert method, to allow getting currency information for several currencies at a single request. In addition the class contains a small main program showing how the currency matrix can be used:
public class YahooCurrencyConverter extends BaseCurrencyConverter {
    public float convert(String currencyFrom, String currencyTo) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpGet, responseHandler);
        httpclient.getConnectionManager().shutdown();
        return Float.parseFloat(responseBody);
    }
    public void convert(CurrencyPair[] currencyPairs) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer();
        for (CurrencyPair currencyPair : currencyPairs) {
            sb.append("s=").append(currencyPair.getFrom()).append(currencyPair.getTo()).append("=X&");
        }
        HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?" + sb + "f=l1&e=.csv");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpGet, responseHandler);
        httpclient.getConnectionManager().shutdown();
        String[] lines = responseBody.split("\n");
        if (lines.length != currencyPairs.length) {
            throw new IllegalStateException("Currency data mismatch");
        }
        int i = 0;
        for (String line : lines) {
            CurrencyPair currencyPair = currencyPairs[i++];
            currencyPair.price = Float.parseFloat(line);
        }
    }
    public static void main(String[] args) {
        YahooCurrencyConverter ycc = new YahooCurrencyConverter();
        try {
            String[] currencies = new String[] { "USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "MXN", "ILS" };
            CurrencyPair[][] currencyPairs = ycc.getConversionMatrix(currencies);
            System.out.print("    ");
            for (int i = 0; i < currencyPairs.length; i++)
            {
                System.out.print("     " + currencies[i]);
            }
            System.out.println();
            for (int i = 0; i < currencyPairs.length; i++)
            {
                for (int j = 0; j < currencyPairs.length; j++)
                {
                    if (j == 0)
                    {
                        System.out.print(currencies[i] + " ");
                    }
                    CurrencyPair currencyPair = currencyPairs[i][j];
                    if (currencyPair != null)
                    {
                        System.out.printf("%8.3f", currencyPair.price);
                    }
                    else
                    {
                        System.out.print("        ");
                    }
                }
                System.out.println();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This is how the output for the currency matrix looks like:

         USD     EUR     GBP     JPY     CHF     CAD     AUD     MXN     ILS
USD            0.733   0.686  96.940   1.125   1.223   1.419  14.275   4.041
EUR    1.363           0.936 132.178   1.534   1.668   1.935  19.464   5.510
GBP    1.457   1.069         141.246   1.639   1.782   2.068  20.799   5.888
JPY    0.010   0.008   0.007           0.012   0.013   0.015   0.147   0.042
CHF    0.889   0.652   0.610  86.177           1.087   1.262  12.690   3.592
CAD    0.817   0.600   0.561  79.245   0.920           1.160  11.669   3.303
AUD    0.705   0.517   0.484  68.309   0.793   0.862          10.059   2.848
MXN    0.070   0.051   0.048   6.791   0.079   0.086   0.099           0.283
ILS    0.248   0.182   0.170  23.989   0.278   0.303   0.351   3.533        

I hope this code will help you to easily build your own custom currency matrices. This information may be useful to currency traders or applications that need to show the latest exchange rate between currencies.

As stated for the previous post, this class is making use of the Apache open source project: Http Client. You will need to put in your project the proper jar files for this class to work properly.