Monday, March 28, 2011

putting object to MQ and read objects from EJB Messaging Bean

Object putting java code

========================

QueueConnection queueConnection = null;

QueueSession jmsSession = null;



try {

Hashtable hashtable=new Hashtable();

hashtable.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");

hashtable.put("java.naming.provider.url","jnp://localhost:1099");



QueueConnection queueConnection =MessagingServiceMDBUtil.getQueueConnection(hashtable);


jmsSession = queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);

QueueSender sender = jmsSession.createSender(MessagingServiceMDBUtil.getQueue(LookupUtil.lookupMessagingConfig().getJndiProperties()));

// create the message

ObjectMessage message = jmsSession.createObjectMessage();

ArrayList msgList = new ArrayList();

//Object

Student studentObj=new Student();

studentObj.setFristName("Gayan");

studentObj.setLastName("Dissanayake");

msgList.add(studentObj);

message.setObject(msgList);



//send the message

sender.send(message);

sender.close();

log.debug("Message is written to jms queue");

} catch (JMSException e) {

log.error("Sending message via jms failed", e);

} catch (NamingException e) {

log.error("Sending message via jms failed", e);

} catch(ModuleException moduleException) {

log.error("Sending message via jms failed", moduleException);

} finally {

if (queueConnection != null){

try {

queueConnection.close();

log.debug("Closed jms queue connection");

} catch (JMSException e) {

log.error("Closing jms queue connection failed", e);

}

}

if (jmsSession != null){

try {

jmsSession.close();

if (log.isDebugEnabled()) log.debug("Closed jms session");

} catch (JMSException e) {

if (log.isDebugEnabled()) log.error("Closing jms session failed", e);

}

}

}


EJB Messaging Bean

===================


public class MessagingServiceMDB implements MessageDrivenBean, MessageListener {

private static final long serialVersionUID = -6583759698965963589L;

private final Log logger = LogFactory.getLog(getClass());



public void onMessage(Message message){

try {

logger.debug("Entered MessagingServiceMDB.onMessage()");

ObjectMessage objMessage = (ObjectMessage)message;

ArrayList msgProfiles = (ArrayList)objMessage.getObject();

//do business logic here using MQ object

logger.debug("Entered MessagingServiceMDB.onMessage()");

} catch (JMSException jmsException) {

logger.error("Exception in MessagingServiceMDB:onMessage() " + jmsException.getMessage(), jmsException);

} catch (Exception exception) {

logger.error("Exception in MessagingServiceMDB:onMessage() " + exception.getMessage(), exception);

}

}


public void setMessageDrivenContext(MessageDrivenContext cxt) throws EJBException {}

public void ejbRemove() throws EJBException {}

public void ejbCreate() throws EJBException {}

}


add following to ejb-jar.xml

============================


<message-driven >

<description><![CDATA[MessagingServiceMDB Message Driven Bean]]></description>

<display-name>MessagingServiceMDB</display-name>


<ejb-name>MessagingServiceMDB</ejb-name>


<ejb-class>com.isa.holidays.messaging.service.MessagingServiceMDB</ejb-class>


<transaction-type>Container</transaction-type>

<acknowledge-mode>Auto-acknowledge</acknowledge-mode>

<message-driven-destination>

<destination-type>javax.jms.Queue</destination-type>

</message-driven-destination>


<resource-ref >

<res-ref-name>jms/QCF</res-ref-name>

<res-type>javax.jms.QueueConnectionFactory</res-type>

<res-auth>Container</res-auth>

</resource-ref>


</message-driven>

Read/Write excel files using Apache POI - (the Java API for Microsoft Documents)

needed Lib
==========
poi-2.5.1.jar

Sample Code
===========


import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ReadExcelFile
{

public ReadExcelFile()
{
}

public static void main(String args[])
{
String fileName = "C:\\Sample.xls";
Vector dataHolder = ReadCSV(fileName);
printCellDataToConsole(dataHolder);
}

public static synchronized Vector ReadCSV(String fileName)
{
Vector cellVectorHolder = new Vector();
try
{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int noOfsheets = myWorkBook.getNumberOfSheets();
for(int i = 0; i < noOfsheets; i++)
{
HSSFSheet mySheet = myWorkBook.getSheetAt(i);
Vector cellStoreVector;
for(Iterator rowIter = mySheet.rowIterator(); rowIter.hasNext(); cellVectorHolder.addElement(cellStoreVector))
{
HSSFRow myRow = (HSSFRow)rowIter.next();
Iterator cellIter = myRow.cellIterator();
cellStoreVector = new Vector();
HSSFCell myCell;
for(; cellIter.hasNext(); cellStoreVector.addElement(myCell))
myCell = (HSSFCell)cellIter.next();

}

}

}
catch(Exception e)
{
e.printStackTrace();
}
return cellVectorHolder;
}

private static synchronized void printCellDataToConsole(Vector dataHolder)
{
for(int i = 0; i < dataHolder.size(); i++)
{
Vector cellStoreVector = (Vector)dataHolder.elementAt(i);
System.out.println("Start getting rows");
for(int j = 0; j < cellStoreVector.size(); j++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
System.out.println((new StringBuilder()).append("reading column no -").append(myCell.getCellNum()).toString());
String stringCellValue = "";
if(myCell.getCellNum() == 0)//1st column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 1)//2nd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 2)//3rd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 3)//4th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 4)//5th column is Number based cell
stringCellValue = String.valueOf(myCell.getNumericCellValue());
if(myCell.getCellNum() == 5)//6th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
System.out.println((new StringBuilder()).append(stringCellValue).append("\t").toString());
}

System.out.println("end getting rows");
}

}
}

File Upload to server by Servlet(or JSP)

HTML Form
========

<FORM id="upform" name="upform" ENCTYPE='multipart/form-data' action="<URL>" method='POST'>

<INPUT type='file' name='uploadfile'>

<INPUT type='submit' value='upload'>

</FORM>


Needed Lib

===========

commons-fileupload-1.2.2.jar

commons-io-1.4.jar


Needed imports

===============

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


Sample Code Segment

===================

//String fileSavePath="/var/uploaded/"; linux

String fileSavePath="c:\uploaded";

if(ServletFileUpload.isMultipartContent(request))

{

ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

List fileItemsList = null;

try

{

fileItemsList = servletFileUpload.parseRequest(request);

}

catch(FileUploadException e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

}

Iterator iterator = fileItemsList.iterator();

FileItem fi = (FileItem)iterator.next();

String fileName = fi.getName();

fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

String saveFile = (new StringBuilder()).append(fileSavePath).append(fileName).toString();

if("".equalsIgnoreCase(fileName))

throw new Exception("Please choose file to upload");

try

{

fi.write(new File(saveFile));

}

catch(Exception e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

}




}