Sunday, September 9, 2012

Spring MVC with Ajax

Spring MVC with AJAX implementation using Jackson API and Jquery

The following jar files needed for this ,

commons-logging-1.1.1.jar
jackson-core-asl-1.4.0150249.jar
jackson-mapper-asl-1.4.3.jar

jstl-1.2.jar
spring-asm-3.0.3.RELEASE.jar
spring-beans-3.0.3.RELEASE.jar
spring-context-3.0.3.RELEASE.jar
spring-context-support-3.0.3.RELEASE.jar
spring-core-3.0.3.RELEASE.jar
spring-expression-3.0.3.RELEASE.jar
spring-web-3.0.3.RELEASE.jar
spring-webmvc-3.0.3.RELEASE.jar


Ajax implementation is based on 
 jackson-core-asl-1.4.0150249.jar and jackson-mapper-asl-1.4.3.jar

1) Added this jars in your classpath.

2) Add the following configuration in your context file,

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
          <list>
            <ref bean="
jsonConverter"/>
          </list>
    </property>

</bean>

3) Controller Class(EmployeeController.java)

package com.jijo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmployeeController {

     @RequestMapping(value = "/SaveEmploye.html", method = RequestMethod.POST)
        public @ResponseBody String saveEmployee(@RequestBody Employe employe) {
           if(employe != null){
               System.out.println("*****DATA IS NOT NULL*****: "+employe);
               for(Address address :employe.getAddresses()){
                   System.out.println("Employee Name:"+employe.getFirstName()+" \nHouseName:"+address.getHouseName());
               }
           }
           else{
               System.out.println("employe is null");
           }
            return "done";
        }
}



4) Employe.java

package com.jijo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Employe  implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String employeeId;
    private String firstName;
    private String lastName;
    private String department;
    private List<Address> addresses = new ArrayList<Address>();
    public String getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public List<Address> getAddresses() {
        return addresses;
    }
    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }
   
}




5) Addess.java
 


package com.jijo;

import java.io.Serializable;

public class Address implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private String houseName;
    private String place;
    private String district;
    private String state;
    private String country;
    private String postalCode;

    public String getHouseName() {
        return houseName;
    }

    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }

    public String getPlace() {
        return place;
    }

    public void setPlace(String place) {
        this.place = place;
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }
}



6) Javascript function




function saveEmploye(){
var addresses = [];
var employee = {"employeeId":"10","firstName":"John","lastName":"Smith","department":"IT"};
var address = 

{"houseName":"HouseNo-10",
"place":"PLACE1",
"district":"district1","state":"state1"};
addresses.push(address);
employee.addresses=addresses;

$.ajax({
    type: "post",
    url: "SaveEmploye.html", //your url
    contentType: "application/json",
    data: JSON.stringify(employee),
    success: function(result) {
        alert('Employee saved successfully');
    },
    error: function(){
        alert('
Error occured');
    }
});
}
 

 




Saturday, March 24, 2012

Authentication in Jboss webservice client

URL url = null;
url = new URL("file:/c:/test/test.wsdl");


    PRODGenericDataAccessSoap soap = super.getPort(PRODGenericDataAccessSoap, PRODGenericDataAccessSoap.class);
        BindingProvider bp = (BindingProvider)soap;
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "jijo");

//username is jijo
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "jijo"); 

//passowrd is jijo
        return soap; 


16:12:49,843 WARN  [org.apache.cxf.phase.PhaseInterceptorChain] Interceptor for {http://www.prodml.org/api/200/genericDataAccess}PROD_GenericDataAccess#{http://www.prodml.org/api/200/genericDataAccess}GetData has thrown exception, unwinding now: java.lang.RuntimeException: Can't find input stream in message
    at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:116) [:2.3.1]
    at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:60) [:2.3.1]
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255) [:2.3.1]
    at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:755) [:2.3.1]
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2330) [:2.3.1]
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2192) [:2.3.1]
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:2036) [:2.3.1]
    at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56) [:2.3.1]
    at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:696) [:2.3.1]
    at 16:12:51,765 ERROR [STDERR] javax.xml.ws.soap.SOAPFaultException: Can't find input stream in message


Thursday, December 1, 2011

Get application url using java

/*
If your domain name is http://jijo84.blogspot.com/.
You will get http://jijo84.blogspot.com/ in your application using the following code.
If you are using struts action class, servlet or jsp  , you can use the following code.

*/

import java.net.URL;

public ActionForward checkUrl(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
URL applicationUrl = new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
                        request.getContextPath());
system.out.println(applicationUrl.toString());
return mapping.findForward("success");
}




Saturday, November 19, 2011

Stop the continuous logging in Jboss console log except error

 To stop all logs except error,please
put the below elements in jboss-logging.xml in the deploy folder of Jboss to stop the continuous logging in Jboss console.
 
   <logger category="org.directwebremoting">
      <level name="ERROR"/>
   </logger>
   <logger category="org.apache.mina.filter.logging">
      <level name="ERROR"/>
   </logger>

Thursday, September 29, 2011

Calendar to XMLGregorianCalendar and vice versa

package com.jijo;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Calendar;

 public class DateUtil{

    public    static XMLGregorianCalendar toXMLCalendar(Calendar calandar ){
        XMLGregorianCalendar xmlCalendar =    null;
        try {
            DatatypeFactory dtf = DatatypeFactory.newInstance();
            xmlCalendar = dtf.newXMLGregorianCalendar();
            xmlCalendar.setYear(calandar.get(Calendar.YEAR));
            xmlCalendar.setDay(calandar.get(Calendar.DAY_OF_MONTH));
            xmlCalendar.setMonth(calandar.get(Calendar.MONTH)+ 1);
            xmlCalendar.setHour(calandar.get(Calendar.HOUR_OF_DAY));
            xmlCalendar.setMinute(calandar.get(Calendar.    MINUTE));
            xmlCalendar.setSecond(calandar.get(Calendar.    SECOND));
            xmlCalendar.setMillisecond(calandar.get(Calendar.MILLISECOND));
            int offsetInMinutes = (calandar.get(Calendar.ZONE_OFFSET) + calandar.get(Calendar.DST_OFFSET)) / (60 * 1000);
            xmlCalendar.setTimezone(offsetInMinutes);

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

    }
public static Calendar toCalendar(XMLGregorianCalendar xmlCalendar ){
  return xmlCalendar.toGregorianCalendar();
 }

}

Friday, June 24, 2011

Setting CLOB in Hibernate annotation

Setting CLOB in Hibernate annotation

@Lob @Basic(fetch=FetchType.EAGER)
@Column(name = "news")      
   private String news;

Wednesday, June 22, 2011

Specify username, password and timeout in jboss webservice client

Specify the username, password and timeout ,in a jboss web service client.


In your generated client class , getting Soap instance method ,
eg:


public TESTGenericDataAccessSoap getTESTGenericDataAccessSoap(){
{
TESTGenericDataAccessSoap soap = super.getPort(TESTGenericDataAccessSoap , TESTGenericDataAccessSoap .class);
        BindingProvider bp = (BindingProvider)soap;
         Stub stub = (Stub)soap;
         stub._setProperty(StubExt.PROPERTY_CLIENT_TIMEOUT, 10); //Time out
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "jijo");//Username
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "jijo");//Password
        return soap;
}

The import classes are given,

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Stub;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.Service;
import org.jboss.ws.core.StubExt;

Friday, June 10, 2011

Div is going behind the SWF

When the div is going behind the SWF, give the following paramter 

<param name="wmode" value="transparent" />
eg:
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
            id="Test" width="100%" height="100%"
            codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
            <param name="movie" value="Test.swf" />
            <param name="quality" value="high" />
            <param name="bgcolor" value="#869ca7" />
            <param name="allowScriptAccess" value="sameDomain" />
            <param name="wmode" value="transparent" />
            <embed src="Test.swf" quality="high" bgcolor="#869ca7"
                width="100%" height="100%" name="Test" align="middle"
                play="true"
                loop="false"
                quality="high"
                allowScriptAccess="sameDomain"
                wmode="transparent"
                type="application/x-shockwave-flash"
                pluginspage="http://www.adobe.com/go/getflashplayer">
            </embed>
    </object>

Sunday, May 29, 2011

Change SVN password or remove stored passord from SVN eclipse plugin

In windows;
remove the following folder
C:\Documents and Settings\…..\Application Data\Subversion\auth\
eg: C:\Documents and Settings\jijo\Application Data\Subversion\auth 
Some times 'Application Data' is hidden.Please enable 'show hidden files' in file system.

Then Remove the auth folder.
In the auth folder you can find the following folders,
svn.simple
svn.ssl.client-passphrase
svn.ssl.server
svn.username


In linux :
~/.subversion/auth
This folder is hidden.Please enable the 'show hidden files'  in file system.Then remove the auth folder.

After the next saving from eclipse to SVN , password option will come.

NB: If you are not found the above path, search the auth folder,and check whether is SVN related and then remove that folder.
 







Thursday, February 24, 2011

increment a value using jstl c tag

<c:set var="numberOfRows" value="0"/><c:set var="numberOfRows" value="${numberOfRows+1}"/>
<c:out value="${numberOfRows}"/>

Wednesday, February 16, 2011

Read data from file using apache commons.io

package com.jijo;
import org.apache.commons.io.FileUtils;
import java.io.File;
//use commons-io-1.3.2.jar 
//download the above jar and include that in your class path.

class FileTest{

public String getFileData(String fileName){ //eg: c:/jijo/test.txt
String xmlData = null;
File file = new File(fileName);
        try{
        xmlData = FileUtils.readFileToString(file);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
return xmlData;
}

}

Code Complete: A Practical Handbook of Software Construction

Visualage for Java Enterprise Edition 

Wednesday, April 21, 2010

Html contents using h:outputText

<h:outputText value="#{testBean.htmlText}"
               escape="false" />

 Generate your html contents in testBean.htmlText

Tuesday, April 20, 2010

The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit



If you are using <%@ include file="test.jsp" %>(static include),
replace this to <jsp:include page="test.jsp" /> (dynamic include).

Wednesday, April 14, 2010

jndi configuration in Jboss server

Jijo-ds.xml (put this file in jboss deploy folder)

<datasources>
  <local-tx-datasource>
    <jndi-name>jijoDS</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/jijo</connection-url>

    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password>mysql</password>
    <!-- you can include connection properties that will get passed in

     the DriverManager.getConnection(props) call-->
    <!-- look at your Driver docs to see what these might be -->
    <connection-property name="char.encoding">UTF-8</connection-property>

    <transaction-isolation>TRANSACTION_SERIALIZABLE</transaction-isolation>

    <!--pooling parameters-->
    <min-pool-size>10</min-pool-size>
    <max-pool-size>30</max-pool-size>

    <blocking-timeout-millis>5000</blocking-timeout-millis>
    <idle-timeout-minutes>1</idle-timeout-minutes>
    <!-- sql to call when connection is created -->
    <new-connection-sql>select 1</new-connection-sql>

   

    <!-- sql to call on an existing pooled connection when it is obtained from pool -->
    <check-valid-connection-sql>select 1</check-valid-connection-sql>
   
    <set-tx-query-timeout></set-tx-query-timeout>
    <query-timeout>300</query-timeout> <!-- maximum of 5 minutes for queries -->

  </local-tx-datasource>
</datasources>

in your application WEB-INF/jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
        <security-domain>java:/jaas/jmx-console</security-domain> 
         <resource-ref> 
       <res-ref-name>jijoDS</res-ref-name>
       <jndi-name>java:/jijoDS</jndi-name>
   </resource-ref>    
</jboss-web>

in web.xml

<resource-ref>
        <res-ref-name>jijoDS</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>



in applicationContext.xml you are using Spring-Hibernate combination


<bean id="dataSource" class="org.springframework.
jndi.JndiObjectFactoryBean" singleton="true">
     <property name="jndiName">
        <value>java:/jijoDS</value>
     </property>
</bean>

<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean" >
<property name="properties">
<props>
<prop key="hibernate.dialect">dialect name</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
<prop key="hibernate.connection.datasource">java:/comp/env/jdbc/jijoDS</prop>
</props>
</property>
</bean>

DataBase connection configuration in Spring-Hibernate(applicationContext.xml)

in jdbc.properties  

#for Oracle
#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
#jdbc.url=jdbc:oracle:thin:@192.168.0.69:1521:jijo
#jdbc.username=jijo
#jdbc.password=jijo
#hibernate.dialect=org.hibernate.dialect.Oracle10gDialect


#for MYSQL
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jijo
jdbc.username=root
jdbc.password=jijo
hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.c3p0.initialPoolSize=10
hibernate.c3p0.minPoolSize=5
hibernate.c3p0.maxPoolSize=25
hibernate.c3p0.acquireRetryAttempts=10
hibernate.c3p0.acquireIncrement=5
hibernate.c3p0.idleConnectionTestPeriod=3600
hibernate.c3p0.preferredTestQuery=SELECT 1;
hibernate.c3p0.testConnectionOnCheckin=false
hibernate.c3p0.maxConnectionAge=100
hibernate.c3p0.maxIdleTime=120


in applicationContext.xml

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/> 
<property name="initialPoolSize"><value>${hibernate.c3p0.initialPoolSize}</value></property>
<property name="minPoolSize"><value>${hibernate.c3p0.minPoolSize}</value></property>
<property name="maxPoolSize"><value>${hibernate.c3p0.maxPoolSize}</value></property>
<property name="acquireRetryAttempts"><value>${hibernate.c3p0.acquireRetryAttempts}</value></property>
<property name="acquireIncrement"><value>${hibernate.c3p0.acquireIncrement}</value></property>
<property name="idleConnectionTestPeriod"><value>${hibernate.c3p0.idleConnectionTestPeriod}</value></property>
<property name="maxIdleTime"><value>${hibernate.c3p0.maxIdleTime}</value></property>
<property name="maxConnectionAge"><value>${hibernate.c3p0.maxConnectionAge}</value></property>
<property name="preferredTestQuery"><value>${hibernate.c3p0.preferredTestQuery}</value></property>
<property name="testConnectionOnCheckin"><value>${hibernate.c3p0.testConnectionOnCheckin}</value></property>
</bean>


<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="hibernateProperties">
            <props>

                 <prop key="hibernate.dialect">
                    ${hibernate.dialect}
                </prop>

                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">
                    true
                </prop>
                <prop key="hibernate.cache.provider_class">
                    org.hibernate.cache.HashtableCacheProvider
                </prop>
                <prop key="hibernate.c3p0.acquire_increment">${hibernate.c3p0.acquireIncrement}</prop>
                <prop key="hibernate.c3p0.idle_test_period">${hibernate.c3p0.idleConnectionTestPeriod}</prop>
                <prop key="hibernate.c3p0.timeout">${hibernate.c3p0.maxIdleTime}</prop>
                <prop key="hibernate.c3p0.max_size">${hibernate.c3p0.maxPoolSize}</prop>
                <prop key="hibernate.c3p0.min_size">${hibernate.c3p0.minPoolSize}</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>

Thursday, March 4, 2010

Display the contents of a Zip file

package com.jijo.servlet;

import java.io.*;
import java.util.zip.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipView extends HttpServlet
{
    /**
     * Display the contents of a zip file
     */
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
        try
        {
            String zipFile = request.getParameter("fileNames");//specify the zip file           
            response.setContentType("text/html"); 
            PrintWriter out = response.getWriter();
            out.println("<table><tr><th>File Name</th><th>Size</th><th>Date </th><th>Compressed Size</th></tr>");
            if(zipFile != null && zipFile.trim().length()>0){
               
                //BufferedOutputStream out = null;
                ZipInputStream  in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
                ZipEntry entry;
                while((entry = in.getNextEntry()) != null)
                {
                    out.println("<tr><td>"+ entry.getName()+"</td><td>"+ entry.getSize()+"</td><td>"+ entry.getTime() +" </td><td>"+ entry.getCompressedSize() +" </td></tr>");
                    /*System.out.println(entry.getName());
                    int count;
                    byte data[] = new byte[1000];
                    out = new BufferedOutputStream(new FileOutputStream("C:/pdf/out.txt"),1000);
                    while ((count = in.read(data,0,1000)) != -1)
                    {
                        out.write(data,0,count);
                    }
                    out.flush();
                    out.close();
                    */
                }               
            }
            out.println("</table>");       
            out.flush();
            out.close();           
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    } 
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   }

//Put the servlet entry in web.xml file

Download selected files as Zip

package com.jijo.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author jijo
 * This servlet class is used to download the list files as a zip
 */
public class ZipDownload extends HttpServlet{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        byte[] files = null;
       
        try {
            String random = this.generateRamdomCode(10, 15);
           //Specify the files names seperated by '@!'
            String reqFile = request.getParameter("fileNames");
            if(reqFile != null && reqFile.trim().length()>0){
                String filenames[] = reqFile.split("@!");   
               
                ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(random + ".zip"));
                for (String filename : filenames) {
                    try{
                        filename = filename.trim();
                        if(filename.length()>0){
                            FileInputStream fin = new FileInputStream(filename);
                            File file = new File(filename);
                            zipFile.putNextEntry(new ZipEntry(filename.substring(filename
                                    .lastIndexOf("/") + 1, filename.length())));
                            files = new byte[(int) file.length()];
                            fin.read(files);
                            zipFile.write(files);
                            fin.close();
                            zipFile.closeEntry();
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                zipFile.close();
                FileInputStream zip = new FileInputStream(random + ".zip");
                File f = new File(random + ".zip");
                files = new byte[(int) f.length()];
                zip.read(files);
                zip.close();
                f.delete();           
               
                //response
                response.setContentType("application/zip");
                response.setContentLength(files.length);
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"jijo.zip\"");
                try {
                    response.getOutputStream().write(files);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
           
        }
    }

    private String generateRamdomCode(double min, double max){
        String code = "";
        int totalChars = (int)((Math.random() * min)+max);
        char startChar = 'A';
        for(int i=0;i<totalChars;i++){
            int selNum = (int)(Math.random() * 13.0);
           
            if(selNum <= 4){
                startChar = 'A';
                code += (char)((Math.random()*26.0)+startChar);
            }else if(selNum >=5 && selNum<= 9){
                code += (int)(Math.random() * 10.0);
            }else if(selNum >=10){
                startChar = 'a';
                code += (char)((Math.random()*26.0)+startChar);
            }
        }
        System.out.println(code);
        return code;
    }   
   
}

Put the servlet entry and url mapping in web.xml file.

Display or download Files using servlet

/**
 *
 */
package com.jijo.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jijo
 * This servlet class is used to display or download the file
 *
 */
public class DownloadFile extends HttpServlet{
   
   
   
    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        ServletOutputStream outputStream = null;
        InputStream input = null;
       
        try {
            outputStream = response.getOutputStream();
            String filePath = request.getParameter("fileNames");  //filepath
            if(filePath != null && filePath.trim().length()>0){               
                String download = request.getParameter("download");//download or display
                File prefile = new File(filePath);
                byte buff[] = new byte[8192];
                input = new FileInputStream(prefile);
                String contenttype = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());
                contenttype = contenttype.toLowerCase();
               
                if(download != null && download.trim().length()>0){
                      response.setContentType("application/octet-stream");
                }
                else{
                    if (contenttype != null) {
                        String responseType = getResponseContentType(contenttype);
                        response.setContentType(responseType);                        
                    } else {
                        response.setContentType("application/octet-stream");
                    }
                }          
                response.setHeader("Content-Length", String.valueOf(prefile.length()));          
                if(download != null && download.trim().length()>0){
                    response.setHeader("Content-Disposition","attachment; filename=\""+ prefile.getName()+"\"");
                }
                else{
                    response.setHeader("Content-disposition", (new StringBuilder("inline; filename=")).append(prefile.getName()).toString());
                }
                response.addHeader("Cache-Control", "no-transform, max-age=0");  
                int i = 0;
                while ((i = input.read(buff)) > 0) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (input != null)
                input.close();
            if (outputStream != null)
                outputStream.close();
        }
    }
    private String getResponseContentType(String contenttype){
        String responseType = "";
        if(contenttype.indexOf("doc")>-1){
            responseType = "application/vnd.ms-word";
        }
        if(contenttype.indexOf("rtf")>-1){
            responseType = "application/rtf";
        }
        else if(contenttype.indexOf("xls")>-1){
            responseType = "application/vnd.ms-excel";
        }   
        else if(contenttype.indexOf("ppt")>-1){
            responseType = "application/ppt";
        }
        else if(contenttype.indexOf("xml")>-1){
            responseType = "text/xml";
        }
        else if(contenttype.indexOf("html")>-1){
            responseType = "text/html"; 
        }
        else if(contenttype.indexOf("htm")>-1){
            responseType = "text/htm"; 
        } 
        else if(contenttype.indexOf("txt")>-1 || contenttype.indexOf("log")>-1){
            responseType = "text/plain";
        }   
        else if(contenttype.indexOf("pdf")>-1){
            responseType = "application/pdf";
        }
        else if(contenttype.indexOf("gif")>-1){
            responseType = "image/gif";
        }
        else if(contenttype.indexOf("png")>-1){
            responseType = "image/png";
        }
        else if(contenttype.indexOf("jpg")>-1){
            responseType = "image/jpg";
        }
        else if(contenttype.indexOf("jpeg")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("jpe")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("bmp")>-1){
            responseType = "image/bmp";
        }
        else if(contenttype.indexOf("jpeg")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("tiff")>-1){
            responseType = "image/tiff";
        }
        else if(contenttype.indexOf("tif")>-1){
            responseType = "image/tiff";
        }       
        else if(contenttype.indexOf("html")>-1){
            responseType = "text/html";
        }
        else{
            responseType = "application/octet-stream";
        }
        return responseType;
    }
   
}




in web.xml


<servlet>
        <servlet-name>ViewFile</servlet-name>
        <servlet-class>com.jijo.servlet.DownloadFile</servlet-class>
    </servlet>   
    <servlet-mapping>
        <servlet-name>ViewFile</servlet-name>
        <url-pattern>*.viewfile</url-pattern>
    </servlet-mapping>


    <mime-mapping>
        <extension>pptx</extension>
        <mime-type>
            application/vnd.openxmlformats-officedocument.presentationml.presentation
        </mime-type>
    </mime-mapping>
   
    <mime-mapping> 
        <extension>docx</extension> 
         <mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type> 
     </mime-mapping> 
     <mime-mapping> 
        <extension>xlsx</extension> 
        <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type> 
     </mime-mapping> 




in jsp

<form name='form1' method="post" action="file.viewfile" target="fileframe"/>
<input type='hidden' name='fileNames' id='fileNames' value='C:/jijo/resume.txt'/>
<input type='hidden' name='download' id='download' value='true'/>//set as blank when u want to display
<input type='Submit' name='Submit' id='Submit' value='Display'/>
</form>
<frame name="fileframe" id="fileframe"></frame>

Tuesday, February 2, 2010

Track Session out in DWR

Create a filter class,
package com.jijo;
import java.lang.reflect.Method;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.AjaxFilterChain;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.extend.LoginRequiredException;


public class DwrFilter implements AjaxFilter {


public Object doFilter(Object obj, Method method, Object[] params, AjaxFilterChain chain) throws Exception {

//Check if session has timedout/invalidated
String username = WebContextFactory.get().getSession().getAttribute("username");
if (username != null) {
}
else{
throw new LoginRequiredException( "sessionout" );
//sessionout is a message,access this message in the jsp or html
}

return chain.doFilter( obj, method, params );
}
}

configure this filter class in your bean tage inside the
dwr.xml


filter tag
eg:
<filter class="com.jijo.DwrFilter" >


Also in your dwr.xml file configure,


covert tag starts

<convert match="org.directwebremoting.extend.LoginRequiredException" converter="bean" />

Then in your jsp page inside the javascript tag,
first include the
/dwr/engine.js and also the

//start javascript tag
dwr.engine.setErrorHandler(errorHandler);
function errorHandler(message, exception){

//forwrd to login page
if(message == 'sessionout'){ //'sessionout'- is message from the filter class you configured
window.location = "login.jsp"
}
}
//end of javascript tag

Thursday, January 28, 2010

XML parsing using Castor

Put the castor-1.2.jar in you lib folder.
This is object to xml mapping.
 Example is given,
In this Students object is mapped to an xml.Each tag is mapped to different nodes in the XML.

Students.java
/**
 *
 */
package com.jijo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jijo
 *
 */
public class Students {
    private List<Student> students = new ArrayList<Student>();

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

Student.java

package com.jijo;

public class Student {
    private String rollNo;
    private String name;
    private String className;
    public String getRollNo() {
        return rollNo;
    }
    public void setRollNo(String rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
}







studentmapping.xml

 <?xml version="1.0"?>
<mapping>
    <class name="com.jijo.Students">
        <field name="students" type="com.jijo.Student" collection="collection">
            <bind-xml name="student" />    <!-- bind xml tag name -->
        </field>
    </class>  
  
    <class name="com.jijo.Student">
        <!--
        <field name="regNo" type="string">
            <bind-xml name="regNo" node="attribute" /> attribute parsing
        </field>
        -->
        <field name="rollNo" type="string">
            <bind-xml name="rollno"/>
        </field>
        <field name="name" type="string">
            <bind-xml name="name"/>
        </field>
      
        <field name="className" type="string">
            <bind-xml name="classname" />
        </field>
    </class>
</mapping>



XmlUtil.java
/**
 *
 */
package com.jijo;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.xml.sax.InputSource;



/**
 * @author jijo
 *
 */
public class XmlUtil {
    /**
     * This method will convert the data got from the data source to the appropriate
     * form for the next process.
     *
     * @param className
     * @param xmlFileName
     * @param mappingFileName
     * @throws Exception
     * @throws MappingException
     */
    public Object xmltoObject(String className, String xmlFileName, String mappingFileName) {
        Object obj = null;
        FileReader reader = null;
        try {

            // Load the mapping information from the file                               
            URL mappingURL =  getClass().getClassLoader().getResource(mappingFileName);                                               

            Mapping mapping=new Mapping();                                       
            mapping.loadMapping(mappingURL);                                       

            // Create a Reader to the file to unmarshal from
            reader = new FileReader(xmlFileName);

            // Unmarshal the data
            Unmarshaller unmarshaller = new Unmarshaller(Class
                    .forName(className));
            unmarshaller.setMapping(mapping);

            obj = (Object) unmarshaller.unmarshal(reader);

        } catch (Exception e) {
            e.printStackTrace();                          
           
        }
        finally {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
    /**
     * This method is used to cast the xml-string to object
     * @param className
     * @param xmlString
     * @param mappingFileName
     * @return
     */
    public Object xmlStringtoObject(String className,String xmlString,String mappingFileName) {
        ByteArrayInputStream Bis1=null;
        try {
            Bis1 = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e1) {

        }
        InputSource in = new InputSource();
        Object obj = null;
        try {

            // Load the mapping information from the file                               
            URL mappingURL =  getClass().getClassLoader().getResource(mappingFileName);

            Mapping mapping=new Mapping();
            mapping.loadMapping(mappingURL);
            // Create a Reader to the file to unmarshal from
            in.setByteStream(Bis1);
            // Unmarshal the data
            Unmarshaller unmarshaller = new Unmarshaller(Class
                    .forName(className));
            unmarshaller.setMapping(mapping);

            obj = (Object) unmarshaller.unmarshal(in);

        } catch (Exception e) {                                        
            e.printStackTrace();
        }
        finally {
            try {
                Bis1.close();
                Bis1=null;
                in=null;
            } catch (Exception e) {
                e.printStackTrace();                      
            }
        }
        return obj;
    }
}

Main.java










package com.jijo;

import java.util.List;


public class Main {
    public static void main(String[] args) {
        try{
            XmlUtil xmlUtil = new XmlUtil();
            Students obj = (Students) xmlUtil.xmltoObject("com.jijo.Students", "C:/jijo/xml/students.xml", "com/jijo/studentmapping.xml");
            if(obj != null){
                List<Student> students = obj.getStudents();
                if(students != null){
                    System.out.println("not null");
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}




 students.xml
<students>

<student>
<rollno>1</rollno>
<name>Jijo</name>
<classname>10</classname>
</student>

<student>
<rollno>2</rollno>
<name>Mathew</name>
<classname>10</classname>
</student>

<student>
<rollno>3</rollno>
<name>Ajeesh</name>
<classname>10</classname>
</student>

<student>
<rollno>4</rollno>
<name>Prathyush</name>
<classname>10</classname>
</student>

</students>


For more details visit http://www.castor.org.