Monday, February 16, 2009

Apache Poi Turkish Character Support

Apache POI version 3.1 has got support for Turkish characters such as ('ş', 'ğ', 'İ', 'Ş', 'Ğ', 'ü', 'ç').

When I wanted to write a word into Excel file that is containing some of these characters, version 2.5.1 was not displaying it properly.

I updated the version of POI and the display problem resolved.


HSSFCell.ENCODING_UTF_16 includes required character support.
HSSFRow newRow = sheet.createRow((short)1);
newRow.createCell((short) 0).setCellValue("Başvuru Numarası");
HSSFCell cell0 = row.getCell((short) 0);
cell0.setCellType(HSSFCell.CELL_TYPE_STRING);
cell0.setEncoding(HSSFCell.ENCODING_UTF_16);

Required dependency for pom.xml file is :

 
   org.apache.poi
   poi
   3.1-FINAL
 

File Upload/Retrieve From Ftp With Jakarta Commons Net

Sometimes it is required to read and store files from Ftp file servers. For these operations Jakarta Commons Net library provides easy to implement functions.

In order to start working with Commons Net library add following lines into your Maven enabled project's pom.xml file.
 
   commons-net
   commons-net
   1.0.0
 

General procedure to start with ftp server is as follows:

1- connect to server
2- login with userName and Password
3- retrieve list of files from specified ftp folder
4- save the file from ftp to local
5- save the file from local to ftp
6- sometimes it is required to check for response codes from ftp
7- complete operations and disconnect

FtpConnect() method connects to remote ftp server, reads file content, save it to local director, then save a copy of it to another remote ftp location.


package apache.commons.net.ftpclient;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpClientService {
 
 public FtpClientService(){  
 }
 
 public static void FtpConnect(){
  String userName="ftpLoginUserName";
  String passWord = "ftppass";
  String ftpAddress = "ftp.somedomain.com";
  String retrieveFromFTPFolder = "RemoteFolderName/";
  String saveToLocalFolder = "/LocalFolder/";
  String saveToFtpFolder = "/ftpUploadFolder/";
  String strLine;
  DataInputStream inputStream = null;
  BufferedReader bufferedReader = null;
  FTPClient client = null;
  FTPFile[] ftpFiles = null;
  int reply;
 
  try{
   client = new FTPClient();
   client.connect(ftpAddress);
   client.login(userName, passWord);
   ftpFiles = client.listFiles(retrieveFromFTPFolder);  //retrieve list of files from ftp server
   if (ftpFiles != null && ftpFiles.length > 0) {
    for (FTPFile file : ftpFiles) {  // get specified file from folder
     if(file.isFile() && file.getName().equals("PrivateFile")){
      //read content of specific file from ftp
      inputStream = new DataInputStream(client.retrieveFileStream(retrieveFromFTPFolder+file.getName()));
      bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
      //save file from ftp to local directory
      File fileToWrite = new File(saveToLocalFolder+file.getName());
      DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileToWrite)));
      while ((strLine = bufferedReader.readLine()) != null) {
       out.writeBytes(strLine);
          out.writeBytes("\n");
      }
      out.close();
      //check for reply code of ftp server if required then relogin
      reply = client.getReplyCode();
               if (!FTPReply.isPositiveCompletion(reply))
               {
                System.err.println("FTP server refused connection.");
                client.disconnect();
                client = new FTPClient();
                client.connect(ftpAddress);
                client.login(userName, passWord);                    
               }  
               //save file from local to remote ftp file server
      File fileToUpload = new File(saveToLocalFolder + file.getName());
      FileInputStream fileInputStream = new FileInputStream(fileToUpload);
      client.storeFile(saveToFtpFolder + file.getName(), fileInputStream); 
      break;
     }
    }
   }
  }
  catch (Exception e) {
   if (client.isConnected()) {
    try {
     client.logout();  
     client.disconnect();  
    } catch (IOException f) {
     // do nothing
    }
   }
  }
  finally{
   if (client.isConnected())
            {
                try
                {
                 client.logout();
                 client.disconnect();
                }
                catch (IOException f)
                {
                }
            }
  }  
 }
 
 public static void main(String[] args) {
  FtpConnect();
 }
}

Wednesday, February 11, 2009

Writing Test Cases with JUnit

JUnit is one of the most famous test case development frameworks for Java programmers.

It is also easy to integrate into Eclipse IDE.

If your projest is Maven enabled, then just by adding JUnit dependencies in your project's pom.xml file, you will be able to start generating test cases for your project. Add this dependency in your project's pom.xml file.
 
   junit
   junit
   3.8.2 
 

Save your pom.xml file and it will start downloading JUnit jar file into your Maven repository.

It is a good practice to place your test cases into the same project with your classes to be tested.

So create a folder named with "src/test/java" into your project and create a new package into it which is going to contain your JUnit test cases.

After adding Junit jar file and creating a folder which is going to contain your test cases, your directory structure is going to look like in Eclipse as follows.

eclipse project with junit dependency


Now add your class to be tested into org.junit.sample package.

Assume that, you are reading a flat file from your local disk containing mobilePhone number, id number and startDate of Employees separated by semicolon ";" .

Your simple Employee.java class contains:
package org.junit.sample;
import java.util.Date;
public class Employee {

 public Employee(){
 }
 String mobilePhone;
 String IdNumber;
 Date startDate;
 public String getMobilePhone() {
  return mobilePhone;
 }
 public void setMobilePhone(String mobilePhone) {
  this.mobilePhone = mobilePhone;
 }
 public String getIdNumber() {
  return IdNumber;
 }
 public void setIdNumber(String idNumber) {
  IdNumber = idNumber;
 }
 public Date getStartDate() {
  return startDate;
 }
 public void setStartDate(Date startDate) {
  this.startDate = startDate;
 } 
}


Sample file (Employee_Data) content is as follows, each line contains 3 significant parts separated by ";" :

3452701678;44522445566;12.09.2008 09:34:10
2133223914;56705003122;12.09.2008 10:36:31

and it is located at your home folder.

Java class that is required to be tested is a class that reads contents of the above text file and parses it to store each element of it's lines in an Employee object.

Simple FileService.java class which is located in the same package with Employee.java is as follows :
package org.junit.sample;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileService {

 public FileService(){
 }
 
 public Boolean parseTextFile(){
  String readFileFrom = "Employee_Data";
  String strLine,dateTime;
  String[] strArr= new String[3];
  
  File file = null;
  FileInputStream fstream = null;
  DataInputStream dataInputStream = null;
  BufferedReader br = null;
  
  Employee employee = null;
  List<Employee> list = null;
  DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
  Date date;
  try {
   file = new File(readFileFrom);   
   fstream = new FileInputStream(file);
   dataInputStream = new DataInputStream(fstream);
   br = new BufferedReader(new InputStreamReader(dataInputStream));
   list = new ArrayList<Employee>();
   while ((strLine = br.readLine()) != null) {
         System.out.println (strLine);
         strArr = strLine.split(";");
         employee = new Employee();
         employee.setMobilePhone(strArr[0]);
         employee.setIdNumber(strArr[1]);
         dateTime = strArr[2];
         date = (Date)formatter.parse(dateTime);
         employee.setStartDate(date);
         list.add(employee);
         employee = null;
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }
  if(list != null && list.size() > 0)
   return true;
  else
   return false;
 }
}

Related test case is located in the same Maven enabled project under "/src/test/java" folder. 


FileServiceTest.java class extends from junit framework's TestCase class. testparseTextFile() method in FileServiceTest.java class is used to test FileService.java class's parseTextFile() method.



package org.junit.sample.test;
import org.junit.sample.FileService;
import junit.framework.TestCase;

public class FileServiceTest extends TestCase {
 public FileServiceTest(){
 }
 public void testparseTextFile() throws Exception {
         Boolean readFileResult = false;
  FileService fileService = new FileService();
  readFileResult = fileService.parseTextFile();
  assertTrue(readFileResult);
 }
}



In order to start debugging your FileServiceTest.java class, right click on the name of the test method that you want to run from Outline view of Eclipse and then from the context menu choose :
Debug As -> JUnit Test.


eclipse run junit test case in debug mode



It is not taking long time to prepare Eclipse for JUnit test case development. 

Writing test cases efficiently decreases the amount of time spent for development and testing of your application.

Tuesday, February 10, 2009

Why to use Hibernate for persistence layer

Instead of working directly with JDBC, Hibernate can be selected for ORM tool for your application's persistence needs.

When your application becomes larger and your requirements are not met by using JDBC, Hibernate comes to play.

Although there are many other benefits of using Hibernate, main sophisticated properties that a JDBC programmer encounters when working for the first time with Hibernate can be stated as follows:

Lazy loading : Most of the objects contain another objects in itself.

Consider, you have got a CreditCardApplication object which contains ApplicationRequestOwnerData and AdditionalInfo objects.

Assume that, you are retrieving a CreditCardApplication object, but you are not interested in the details of the ApplicationRequestOwnerData and AdditionalInfo objects in itself.

If it is unnecessary to fetch the whole object with its related objects, then lazy-loading brings a great effectiveness for your application.

Lazy-loading enables you to retrieve data as it is required.

Eager fetching : In opposite to lazy-loading, sometimes it is required to retrieve the whole object at a time. This decreases the cost of round trips.

Cascading : Support for cascading is another main benefit that you can design in your related hbm.xml file or annotations.

Generally speaking, using an ORM tool for persistence layer helps you to write less code in a shorter time period, if you use it effectively in your application.


hibernate.org is a great resource for new starters.