Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Thursday, June 28, 2007

Use of serialVersionUID

Whenever i implement a seializable interface to my class it gives me a warning to add a SerialiazableUID. I just add it with default value to make my class looks no warning message in eclibse IDE. I thought that this id will be useful in deserializing. So i tried an example to find out the real purpose for this id.

Consider this basic Employee view Class with one private varialble name..

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {
private String name;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
}


Then i write a class to serialize this class

package Serializable;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerialiaztionTester {

private static String fileName = "SerTest.txt";

public void writer() {
ObjectOutputStream out = null;
FileOutputStream fos = null;
EmployeeView e = new EmployeeView();
e.setName( "bala" + System.currentTimeMillis() );
System.out.println( "In Writer Employee Name is " + e.getName() );
try{
fos = new FileOutputStream( fileName );
out = new ObjectOutputStream( fos );
out.writeObject( e );
out.close();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

public void reader() {
ObjectInputStream in = null;
FileInputStream fis = null;
try{
fis = new FileInputStream( fileName );
in = new ObjectInputStream( fis );
EmployeeView e = ( EmployeeView ) in.readObject();
in.close();
System.out.println( "In reader employee name is "+e.getName() );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
test.writer();
test.reader();
}

}

In writer method just serialize my EmployeeView class to a SerTest.txt file. And in reader method just deserialize my EmployeeView class. Hope you guyz know what is serialization and deserialization. Just for reminder,

Object serialization is the process of saving objects state as a sequence of byte for rebuilding the objects original state at a future time. Rebuilding the object from this sequence of bytes is called deserialization.

when you run the above code you got the following output

In Writer Employee Name is bala1183102973513
In reader employee name is bala1183102973513


Now i am just writing the object,

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
test.writer();
// test.reader();
}


output is
In Writer Employee Name is bala1183103114211


Adding a new variable age and setter , getter methods in employee class

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {
private String name;

private int age;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
public int getAge() {

return age;
}
public void setAge( int age ) {

this.age = age;
}
}


then i call the reader method from the main class without writing. keep in mind that when i serialized my class which consists of only name variable. now it has name as well as age variable

public static void main( String a[] ) {
SerialiaztionTester test = new SerialiaztionTester();
// test.writer();
test.reader();
}

My output for this

java.io.InvalidClassException: Serializable.EmployeeView; local class incompatible: stream classdesc serialVersionUID = 6513632082659324604, local class serialVersionUID = -6641931785738549045
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:459)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1521)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1435)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1626)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1274)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
at Serializable.SerialiaztionTester.reader(SerialiaztionTester.java:35)
at Serializable.SerialiaztionTester.main(SerialiaztionTester.java:47)


From the error itself you can easily have an idea why this error is occured

java.io.InvalidClassException: Serializable.EmployeeView; local class incompatible: stream classdesc serialVersionUID = 6513632082659324604, local class serialVersionUID = -6641931785738549045

Whenever you implement the serialiable it will be assigned a serialVersionUID by default. This unique id should be match when you are deserialzing the object.

To avoid this you can assigned a SerialVersionUID like this

package Serializable;
import java.io.Serializable;
public class EmployeeView implements Serializable {

private static final long serialVersionUID = 1L;

private String name;
private int age;
public String getName() {

return name;
}
public void setName( String name ) {

this.name = name;
}
public int getAge() {

return age;
}
public void setAge( int age ) {

this.age = age;
}
}


Now whenever you change or add a variable it wont throw any exception until unless you remove the implementation Serializable.

Want to know more about Serialization check out this article





Monday, April 16, 2007

Sending Email thru JAVA Mail API

My Application Leave Application System requires to send a mail. So i have decided to use JAVA Mail Api.

Requirement is once the employee apply a leave thru Leave Application system which has to notify about this leave to the reporting authority thru mail.

Here is the code for sending mail.

package org.val.system.la.service.external;

import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.MessagingException;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/* This application checks authentication of the sender */

public class SendApp extends Authenticator {
public static void send( String smtpHost, int smtpPort, String from, String to, String subject, String content ) throws AddressException, MessagingException {

java.util.Properties props = System.getProperties();
props.put( "mail.smtp.host", smtpHost );

props.put( "mail.smtp.port", "" + smtpPort );
props.put( "mail.smtp.auth", "true" );

Session session = Session.getDefaultInstance( props, new SendApp() );

Message msg = new MimeMessage( session );

msg.setFrom( new InternetAddress( from ) );
msg.setRecipient( Message.RecipientType.TO, new InternetAddress( to ) );
msg.setRecipient( Message.RecipientType.CC, new InternetAddress( from ) );
msg.setSubject( subject );
msg.setContent( content, "text/html" );

Transport.send( msg );

}
public static void main( String[] args ) throws Exception {

send( "YOURSMTPHOST", 10, "FromAddress", "ToAddress", "Subject", "MessageContent" );
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( "username", "password" );
}
}

The above code is self explanatory. Now you can send email to dear one :-)

Friday, March 30, 2007

Excel Printing thru JAVA

Excel Printing thru JAVA

I would like to post the code which i have used to print the data's in Excel here..

Requirement :

HR dept would like to generate the XL about who are all taken the leave for the given period ( HR will enter the Month and Year. This should be the file name )

I have used the POI API to print the XL.

Here the code..

HTTPRequest comes from ReportGenerationInput.jsp to this Servlet. Request has two arguments one is month( "mid") and another one is year ( "yid" ). As i already said these two values are feed by HR/User.

package org.val.system.la.action;

import java.io.*;import java.util.ArrayList;
import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.*;import org.apache.struts.util.MessageResources;import org.apache.struts.util.PropertyMessageResources;import org.val.system.la.business.LASException;import org.val.system.la.business.service.form.LeaveVO;import org.val.system.la.controller.LASControllerFactory;


public class ExcelGeneratorServlet extends HttpServlet {

private MessageResources las = PropertyMessageResources.getMessageResources( "LAS" );

public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
try{

String month = request.getParameter( "mid" );
String year = request.getParameter( "yid" );
String fileName = "LeaveReport_" + month + "_" + year + ".xls";


/* Here we are setting that the response should be open as attachment. The attachment file name is for example "LeaveReport_03_2007.xls" */

response.reset();
response.setContentType( "APPLICATION/DOWNLOAD" );

response.setHeader( "Content-disposition", "attachment; filename=" + fileName );


/* Here we are opening a new workbook of POI. This work book consist of only one work sheet and named as "Employee Leave Report" */

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s = wb.createSheet( "Excel" );
wb.setSheetName( 0, "Employee Leave Report" );

/* Here i am getting the collections of leave details that employees had taken during the given period */

ArrayList leaveList = ( ArrayList ) LASControllerFactory.getInstance().getController().getLeaveTransactionByMonth( month, year );

HSSFCellStyle cellStyle = wb.createCellStyle();

cellStyle.setDataFormat( HSSFDataFormat.getBuiltinFormat( "dd/MM/yyyy" ) );

int colSize = leaveList.size();
if ( colSize != 0 ){


/* Here i am printing the Columns name in the first Row in Excel. i.e. the Row named as A in XL */

short zerothRow = 0;
HSSFRow hssfRow = s.createRow( 0 );

HSSFCell cell = hssfRow.createCell( zerothRow );
cell.setCellValue( "Leave Id" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( "Employee Name" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( "Reporting Authority" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( "From Date" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( "Half Day" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( "Leave Status" );

cell = hssfRow.createCell( ++zerothRow );
cell.setCellValue( " Reason" );

/* After printing the headers for each column now we have to print the value for each records */

for ( int row = 0; row <>
short cellCount = 0;
hssfRow = s.createRow( row + 1 );
LeaveVO leave = ( LeaveVO ) leaveList.get( row );

cell = hssfRow.createCell( cellCount );
cell.setCellValue( leave.getLeaveId().toString() );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( leave.getEmployeeVO().getFirstName() );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( leave.getReportingTo() );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( leave.getFromDate() );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( leave.getFromDateHalf() );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( las.getMessage(leave.getLeaveStatus()) );

cell = hssfRow.createCell( ++cellCount );
cell.setCellValue( leave.getReason() );
}
}

/* Now writing the content of XL into temp XL file thru FileoutputStream */

FileOutputStream writer = new FileOutputStream( new File( "/GenerateReport.xls" ) );

wb.write( writer );
writer.close();

/* Now reading the content of temp XL and write into response to show the XL in browser as attachment as i already said */

FileInputStream fis = new FileInputStream( "/GenerateReport.xls" );
OutputStream out = response.getOutputStream();

int i;
while ( (i = fis.read()) != -1 ){

out.write( i );
}

/* we have to close the input stream as well as response writer */

fis.close();

out.close();

}

catch ( LASException la ){
la.printStackTrace();
}

}

/* Request can be post or get. */

public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {

doGet( request, response );
}
}

Now you got the XL as attachment in your browser window.