Tuesday, April 24, 2007

Google's Presently

After preparing for Google Docs and SpreadSheets, now google preparing for a presentation tool called Presently....

Would you like this name Presently?..

But I think they will change the name. B'coz Writely has been released and it's called Google Docs.

Will it be a competitor to MS Office?

Check out this
link for more information.

Thursday, April 19, 2007

Earn Money While Surf

I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept.

AGLOCO’s story is simple:

Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE!
AGLOCO thinks you deserve a piece of the action.

AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube’s users did not get paid for!

AGLOCO will work to get its Members their share of this and more.

AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they’re building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share.

What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information.

So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO.

Click Here to earn money.

Thanks

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, April 13, 2007

Lazy Initialization Exception in Hibernate

I am totally frustrated when getting this exception in my Leave Application. B'coz My friend who has done a project in Hibernate using some wrappers said he has never ever come across this kind of problem because of the wrappers. But after googling, i found out this is one of the common problem for those who are new to hibernate.

Finally i got the solution, why this kind of error occured. Would like to share what i have learnt,

If you are declaring lazy=true in .hbm file like below,

<set name="role2Designation" order-by="ROLE_ID" lazy="true">
<key column="ROLE_ID"/>
<one-to-many class="org.val.system.la.business.service.dto.Role2DesignationDTO"/>
</set>


It means you forced the hibernate to initialize the required object on demand i.e. whenever you required.

For this case the hibernate session should be opened when hibernate initalize the object on demand. Then only hibernate can fetch the data from the DB. If you are declaring lazy="false" then hibernate will never do the lazy initlization though session is opened.

try{
Session session = LASHibernateUtil.currentSession();
roleList = session.createCriteria( RoleVO.class ).createCriteria( "role2Designation" ).add( Restrictions.eq( "designationId", designationId ) ).list();
}
catch ( HibernateException hibernateException ){
throw new LASServiceException( ILASErrorCode.TECHNICAL_PROPLEM );
}
finally{
LASHibernateUtil.closeSession(); // Error Because the Hibernate session is closed here.
}


I got LazyInitalizationException because of the closed session.

how can we avoid LazyInitalizationException?

1. Opening the session always
a. Open hibernate session and close at the end ( using servlet filter )
b. Open hibernate session using ThreadLocal ( I preferred this method )


2. Load all required data in business layer and pass the values to presentation layer using Hibernate.initialize()

Here is the code for Hibernate.initialize()

while ( it.hasNext() ){
Role2DesignationDTO role2Desi = ( Role2DesignationDTO ) it.next();
Hibernate.initialize( role2Desi );
}

I have initalized the required objects in business layer itself and it will automatically passed it to the presenation layer because of relationships. Keep in mind that this initalization is done before closing the session.

By this above two methods we can avoid this LazyInitalizationException. Hope it is useful to know the basic ideas.

Here is the code for opening a session using ThreadLocal

public class LASHibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch ( HibernateException hibernateException ){
throw new RuntimeException( "Exception occurs while Building SessionFactory" + hibernateException.getMessage(), hibernateException );
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session s = ( Session ) session.get();
if ( s == null ){
s = sessionFactory.openSession();
}
session.set( s );
return s;
}

public static void closeSession() throws HibernateException {
Session s = ( Session ) session.get();
session.set( null );
if ( s != null ){
s.close();
}
}
}


Tuesday, April 3, 2007

Step By Step AJAX

As i said earlier about my project Applying Leave thru online. I used that opportunity to learn AJAX also.

Requirement for AJAX in that project is, there is a user called Admin who has the rights to do the admin operations like add, modify and delete. What i did is links will be showed based on the designation of the user after successful login. Admin is the person to enable what are all the links to be shown to this designation. If Admin decides to remove a particular link to the designation, he has select the link from the assigned links and submit.

Assume that in Link removal page all the designation is showed in a combo box. By selecting a particular designation, page has to show the assigned links to this designation without refreshing the page.

Here is the code in JSP
<html:form action="removeRoleToDesignation">
<table width="50%" align="CENTER">
<tr>
<td width="36%"> Select Designation </td>
<td width="100%">
<html:select property="designationId" onchange="showRole(this.value)">
<html:option value="NA"> --select--</html:option>
<html:options collection="ALLDESIGNATION" labelProperty="designation" property="id"/>
</html:select>
</tr>
</table>
<div id="roleToRemove"> </div>
<table width="50%" align="CENTER">
<tr>
<td colspan="2" align="center" >
<html:submit styleClass="button"/>
</td>
</tr>
</table>
</html:form>


Here if user change the value it call the function showRole with current value as argument.

Here is the code for ShowRole Javascript function


var xmlHttp;
function showRole(str){
if(str == 'NA'){
document.getElementById("roleToRemove").innerHTML="";
}else{
var url="roleInfo?&desigId="+str+"&amp;amp;amp;amp;amp;amp;amp;ranid="+Math.random();
xmlHttp=GetXmlHttpObject(roleStateChanged)
xmlHttp.open("GET", url , true)
xmlHttp.send(null)
}
}


Here if user selected the --Select-- in Combo box then no roles need to display. So innerHTML set as empty.

In else condition i.e if user selects any one of the designation we have to send the request to fetch the assigned roles for this desingation from DB.

roleInfo is the servlet Mapping in web.xml and desigId is the selected value in combo box.

diffId is the one to differanciate the reqeust by sending the random number. If you are not using this there is a chance of getting the cached information from the browser.

var url="roleInfo?&did="+str+"&amp;amp;amp;amp;amp;amp;amp;diffId="+Math.random();

Javascript communicates with the server thru XMLHttpReqeust object.

xmlHttp=GetXmlHttpObject(roleStateChanged)

Here the code to get the XMLHttpRequest for various browsers..

function GetXmlHttpObject(handler){
var objXmlHttp=null
if (navigator.userAgent.indexOf("Opera")>=0) {
alert("This example doesn't work in Opera")
return
}
if (navigator.userAgent.indexOf("MSIE")>=0){
var strName="Msxml2.XMLHTTP"
if (navigator.appVersion.indexOf("MSIE 5.5")>=0){
strName="Microsoft.XMLHTTP"
}
try {
objXmlHttp=new ActiveXObject(strName)
objXmlHttp.onreadystatechange=handler
return objXmlHttp
}
catch(e){
alert("Error. Scripting for ActiveX might be disabled")
return
}
}
if (navigator.userAgent.indexOf("Mozilla")>=0){
objXmlHttp=new XMLHttpRequest()
objXmlHttp.onload=handler
objXmlHttp.onerror=handler
return objXmlHttp
}
}

Getting XMLHttpRequest is depend on the browser. so i have to use the same code for getting the XMLHttpRequest. The onreadystatechange function will process the response from the server

objXmlHttp.onreadystatechange=handler

here i am passing the roleStateChanged function as the handler to this GetXmlHttpObject function

xmlHttp=GetXmlHttpObject(roleStateChanged)

Here is the code for roleStateChanged function

function roleStateChanged(){
if (xmlHttp.readyState==4 xmlHttp.readyState=="complete") {
var ajaxReturn = xmlHttp.responseText;
if( ajaxReturn == 'NOROLE'){
document.getElementById("roleToRemove").innerHTML="";
document.laForm.designationId.options[0].selected = true;
alert('No Roles to Remove');
}else{
document.getElementById("roleToRemove").innerHTML=ajaxReturn;
}
}
}


look at this code if

(xmlHttp.readyState==4 xmlHttp.readyState=="complete") {

XMLHttpRequest Object has the property readyState. It explains the status of the response of server.

The followings are the possible statevalues
0 = The request is not initialized
1 = The request has been set up
2 = The request has been sent
3 = The request is in process
4 = The request is complete


XMLHttpRequest object has responseText property thru which we can get the information from the response.
var ajaxReturn = xmlHttp.responseText;

Look at the following line in showRole function
xmlHttp.open("GET", url , true)

this open method of XMLHttpRequest has 3 argument. the first one is used to define GET or POST method. second one is the actual URL where action takes place. Third one states that whether this request is executed asynchronusly ( true ) or not ( false ).


Now we will see what happened in the back end ( Servlet )

I have delegated the request from servlet.


public void findRoleByDesignation( HttpServletRequest request, HttpServletResponse response ) throws LASException {

/* Here getting the information passed from request */

String designationId = request.getParameter( "desigId" );
HttpSession session = request.getSession();

/* DesignationVO is the view class which has the setter and getter for Designation properties like id, desc....*/

DesignationVO designationVO = LASControllerFactory.getInstance().getController().getAllRoleByDesignation( new Long( designationId ) );

try{
/* Here writing the Html code in response writer. we can get these information thru XMLHttpRequest.responseText */
PrintWriter out = response.getWriter();
if ( designationVO != null ){

out.println( "<table width=\"50%\" "align=\"CENTER\">" );
out.println( "<tr>" );
out.println( "<td class=\"tdbgrigio\" width=\"36%\"> Enter Designation </td>" );
out.println( "<td class=\"tdbgrigio\" width=\"100%\"> " );
out.println( "<select name=\"roles\" multiple size=12 width=\"100%\">" );

session.setAttribute( "DESIROLETOREMOVE", designationVO );
Collection roleList = new ArrayList();
Set role2DesignationSet = designationVO.getRole2Designation();
Iterator it = role2DesignationSet.iterator();

while ( it.hasNext() ){
Role2DesignationDTO role2DesignationDTO = ( Role2DesignationDTO ) it.next();
roleList.add( role2DesignationDTO.getRole() );

out.println( "<option value=" + role2DesignationDTO.getRole().getId() + ">" + role2DesignationDTO.getRole().getDescription() + "</option>" );

}
out.println( "</select>" );
out.println( "</td>" );
out.println( "</tr>" );
out.println( "</table>" );

}
else{

/* If this designation id has no role to show then it will pass the message NOROLE to responseText. This is just for identification */
session.removeAttribute( "DESIROLETOREMOVE" );
out.print("NOROLE");
}

out.close();
}
catch ( IOException ioException ){
throw new LASException( ILASErrorCode.TECHNICAL_PROPLEM );
}
}

in roleStateChanged function,

var ajaxReturn = xmlHttp.responseText;
if( ajaxReturn == 'NOROLE'){
document.getElementById("roleToRemove").innerHTML=""; document.laForm.designationId.options[0].selected = true;
alert('No Roles to Remove');
}else{
document.getElementById("roleToRemove").innerHTML=ajaxReturn;
}

If response from the server returns NOROLE then i showed a alert box with No Roles to Remove information, else a multiple select box will appear with assigned roles as option values.

Getting the XMLHttpRequest is always same. There are lots custom tld's available in internet. Try with them. Keep in mind that AJAX is not an new technology... It is not a tough to learn... Good Luck.....


kick it on DotNetKicks.com

Session Invalidation in struts

Some point of time i realize the error that if i keep the page idle for some time and i do any action in the page it will throw an error because of session invalidation.

Initially i thought to leave as it is and the user has to login again as i won't be get paid a single rupee for this. Later point of time, i thought it couldn't be a good thing to have a page like that. So i need to code to avoid such kind of error. Better way is redirect to login page or a common page where i can say "Your session is timed out ". i chose the first one that redirect to login page.

Then i googled to find out the solutions. But it is not easy to get the solutions. Finally i managed to get one solution.


First we should know how the request is processed in struts.

ActionServlet is the only servlet in Struts framework, and is responsible for handling all of the requests. Whenever it receives a request, it first tries to find a sub-application for the current request. Once a sub-application is found, it creates a RequestProcessor object for that sub-application and calls its process() method by passing it HttpServletRequest and HttpServletResponse objects.

This RequestProcessor class has so many methods to override. According to your business you can override the specific methods to acheive your goals. Now we have to concentrate on processPreProcess method for the above scenario.

Method Signature :
protected boolean processPreprocess javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

If this method returns false then the request will abort the processing. we can create our own RequestProcessor and implementing those required methods.

Here is the code to use

package org.val.system.la.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.RequestProcessor;


public class LASRequestProcessor extends RequestProcessor {
protected boolean processPreprocess( HttpServletRequest request, HttpServletResponse response ) {


boolean isValid = true;

HttpSession httpSession = request.getSession( false );

/* If the request comes from login or index then it should not block the process as these are the gateways in my project. In my project, the user has to login to proceed. Once the user has successful login then i put the information about him into session */

if ( request.getServletPath().equals( "/login.do" ) request.getServletPath().equals( "/index.do" ) ){
isValid = true;
}
else if ( httpSession != null && httpSession.getAttribute( "EMPLOYEEDETAILS" ) != null ){

/* Here we know that the user has successfully logged in as the session has his details */

isValid = true;
}else{
try{

/* Here you can easily assume that the session has expired or user has not yet logged in. One more case is copy the URL and paste it into another browser window. In these cases i forward the request to login page. You can do whatever you want */


request.getRequestDispatcher( "webapp/jsp/Index.jsp" ).forward( request, response );
isValid = false;
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
return isValid;
}
}

Now we have created our custom class. But how does the Struts know that to use our RequestProcessor class.

Here is code to use

Put the below entry in struts-config.xml after action-mappings tag



<controller>
<set-property property="processorClass" value="org.val.system.la.action.LASRequestProcessor">
</controller>


This tag forced to use our RequestProcessor class.

Now if your session is timed out your application goes to login page......

Note: How to invalidate session thru web.xml


<session-config>
<session-timeout>15</session-timeout>
</session-config>


Here 15 is the minutes to keep the session alive. If the session is idle for 15 minutes then it will be timed out. You can set as 1 to test.

New to STRUTS and HIBERNATE

Last Month i got an opportunity thru my roommate Gopi to do a project. His requirement is to apply leave thru online. So i used this opportunity to learn Struts and Hibernate. He gave me a short time span ( April 1st 2007 is the deadline). So i started coding without reading any documents related to Struts and Hibernate as i have planned to read the documents whenever i get the doubts.

Here i would like to share what i have learned so far in struts and hibernate. Keep in mind that i am new to struts and hibernate. If you find anything wrong please let me know thru comments to update myself.

Sunday, April 1, 2007

File Upload in JSP

Hi,

I would like to post the Code for uploading a file into server.

Requirement
Store the .csv file which is uploading by user in Server.

Here is the code,

1. Display the File upload option in jsp page


<form name="FileUploader" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td width="25%" colspan="1" align="left">File excel:</td>
<td width="75%" colspan="3" align="left"><input type="file" name="DataFile" size="40"></td>
</tr>
</table>
</form>


As i am new to blog, i am not able to display the jsp code in well formated.

Here is the code for reading the uploaded .csv file in back end.

/* Contents of the file will be stored in a String buffer */
StringBuffer fileContents = new StringBuffer( "" );
/* Using getInputStream of request , we can get the file as ServletInputStream*/
ServletInputStream fileInput = request.getInputStream();

/* Contents of the request input stream stored in the fileContent string buffer */
try{
int fileChar = 0;
while ( fileChar > -1 ){
fileChar = fileInput.read();
fileContents.append( ( char ) fileChar );
}

/* keep in mind that all the information about the request along with file information are stored in the fileContent. So we have to remove the unwanted things. Do Sysout to know the information */

String mimeDelimiter = null, fileName = null, temp = null, fileData = null;
StringTokenizer stringTokenizer = new StringTokenizer( fileContents.toString(), "\n" );

int i = 0;
while ( stringTokenizer.hasMoreTokens() ){
temp = stringTokenizer.nextToken();
++i;

if ( i == 1 && temp.startsWith( "---------" ) ){
mimeDelimiter = temp.substring( 0, temp.length() - 1 );
continue;
}

if ( temp.startsWith( "Content-Disposition: form-data; name=\"DataFile\"; filename=\"" ) ){
java.util.StringTokenizer stf = new java.util.StringTokenizer( temp, "\"" );
temp = stf.nextToken();
temp = stf.nextToken();
temp = stf.nextToken();
fileName = stf.nextToken();
break;
}
}

if ( fileName != null && fileName.trim().length() != 0 ){
String fileExtn = fileName.substring( fileName.lastIndexOf( "." ) + 1 );
if ( "csv".equals( fileExtn ) ){
String contents = fileContents.toString();

temp = mimeDelimiter + "\n" + "Content-Disposition: form-data;name=\"DataFile\";
filename=\"" + fileName + "\"" + "\n";

int iStart = contents.indexOf( temp );
iStart = iStart + temp.length() + 3;
temp = mimeDelimiter;

int iEnd = contents.indexOf( temp, iStart );
fileData = contents.substring( iStart, iEnd );

fileData = fileData.substring( fileData.indexOf( "\n" ) + 3 );
fileData = fileData.substring( 0, fileData.length() - 2 );
fileData = fileData.substring( fileData.indexOf( "\n" ) );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );
fileData = fileData.substring( fileData.indexOf( "\n" ) + 1 );

/* Finally we got the file data. now you can do what you want to do.. */
}
}
} catch ( Exception ioe ){
throw new UserDefinedException("Error in File");
}