Tuesday, December 25, 2012


A bean’s life (Spring Bean Life Cycle):


  1. Spring instantiates the bean.
  2. Spring injects values and bean references into the bean’s properties.
  3. If the bean implements BeanNameAware, Spring passes the bean’s ID to the  set-BeanName() method.
  4. If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.
  5. If the bean implements ApplicationContextAware, Spring will call the  set-ApplicationContext() method, passing in a reference to the enclosing  application context.
  6. If any of the beans implement the BeanPostProcessor interface, Spring calls their postProcessBeforeInitialization() method.
  7. If any beans implement the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method will be called.
  8. If there are any beans that implement BeanPostProcessor, Spring will call their postProcessAfterInitialization() method.
  9. At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.
  10. If any beans implement the DisposableBean interface, then Spring will call their destroy() methods. Likewise, if any bean was declared with a destroy-method, then the specified method will be called.

Ref:  Spring in Action By Craig Walls

Tuesday, December 18, 2012

Various ways to create object in java

1. Using new keyword
MyObject object = new MyObject();

2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("package.MyClass").newInstance();

 3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); 
MyObject object = anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
MyObject object = (MyObject) inStream.readObject();

5. Using classloader
this.getClass().getClassLoader().loadClass(“package.MyClass”).newInstance();


Tuesday, September 25, 2012


Dealing with Date in Java:

Get days between two dates:

public static long getDaysBetween(Calendar startDate, Calendar endDate) { 
Calendar date = (Calendar) startDate.clone(); 
      long daysBetween = 0; 
      while (date.before(endDate)) { 
          date.add(Calendar.DAY_OF_MONTH, 1); 
          daysBetween++; 
       } 
       return daysBetween; 


Convert String to Calendar Date Format:

public static Calendar convertStringToCalendarDate(String newDate) {
      Date newParsedDate = new Date();
      //DateFormat dfd = DateFormat.getDateInstance();            DateFormat dfd = new SimpleDateFormat("dd-MM-yyyy");
      try {
           newParsedDate = dfd.parse(newDate);
           System.out.println(newParsedDate);
       }
      catch(ParseException e) {
              System.out.println("Unable to parse " + newParsedDate);
        }

       Calendar cal = Calendar.getInstance();
       cal.setTime(newParsedDate);
           
      return cal;
}


Get the last date of current year (but hard-coding the day and month):

SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
           
Calendar endDateOfYear = Calendar.getInstance();

endDateOfYear.set(Calendar.YEAR, Integer.parseInt(yearFormat.format(Calendar.getInstance().getTime())));
endDateOfYear.set(Calendar.MONTH, 11); // 11 = December
endDateOfYear.set(Calendar.DAY_OF_MONTH, 31);


Converting Date to String:

Date now = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
String s = df.format(now);
System.out.println("Today is " + s);



Addition of dates in Calendar date:

GregorianCalendar warranty = new GregorianCalendar(2012, Calendar.DECEMBER, 9);
warranty.add(GregorianCalendar.DATE, 30);
Date d = warranty.getTime();
String ss = dfc.format(d);
System.out.println("30 days warranty will end on" + ss);
      

Tuesday, September 18, 2012


Highlighting a row in JQuery:




  • Highlighting the row that contains the word site with the css class row_total.

             $("#tableID").find("tr:gt(0):contains('site')").attr("class", "row_total");



  • Highlighting the row that contains the css class named subtotal-header with the css class row_total, useful in case of display tag.

                $('# tableID .subtotal-header').closest('tr').attr("class", "row_total");



  • // on select function for selection and deselection of row.


                  function highlightRow(obj)
                   {
                 /* Add/remove class to a row when clicked on */
                $(obj).closest("tr").toggleClass('row_selected'); 
                   }

Tuesday, August 28, 2012


Combining Display Tag to Jquery Datatable

Scripts to be embed in head of jsp:

We can get these files in the folder of the data tables downloaded from:



<style type="text/css" title="currentStyle">
    @import "media/css/demo_page.css";
    @import "media/css/header.ccss";
      @import "media/css/demo_table_jui.css";
      @import "examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
     
      @import "media/css/demo_page.css";
      @import "media/css/demo_table.css";
</style>
<script type="text/javascript" language="javascript" src="media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
      $(document).ready(function() {
           
            var oTable = $('#tableID).dataTable( {
                  bJQueryUI: true,
                  "bPaginate":true,
            "bLengthChange":true,
            "bFilter":true,
            "bSort":true,
            "bInfo":true,
            "bAutoWidth":true,
            "bStateSave":false,
            sPaginationType: "full_numbers"
           } );
      } );
</script>

Here tableID is the id of the display tag table.

  And we are good to go.

Monday, July 16, 2012

Export to Excel using spring and Apache POI.


First include the poi jar file downloaded from apache poi.

Entry in application-servlet.xml:

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
   
    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
         <property name="location">
             <value>/WEB-INF/spring-excel-views.xml</value>
         </property>
         <property name="order" value="0" />
      </bean>

<bean id="ExcelRevenueSummary"         class="com.application.utility.ExcelRevenueReportView" />


Entry in spring-excel-views.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <bean id="ExcelRevenueSummary"
            class="com.application.utility.ExcelRevenueReportView">
      </bean>
</beans>

RevenueReportController.java class :

package com.application.utility;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

@Controller
@RequestMapping("/exportForClient.htm")
public class RevenueReportController extends AbstractController{

      @Override
      protected ModelAndView handleRequestInternal(HttpServletRequest request,
                  HttpServletResponse response) throws Exception {
           
            //String output = ServletRequestUtils.getStringParameter(request, "output");
           
            //dummy data
            Map<String,String> revenueData = new HashMap<String,String>();
            revenueData.put("Jan/2012", "$10");
            revenueData.put("Feb/2012", "$110,000");
            revenueData.put("Mar/2012", "$130,000");
            revenueData.put("Apr/2012", "$140,000,000");
            revenueData.put("May/2012", "$220,000,000");
           
            System.out.println("RevenueReportController.handleRequestInternal()");
            return new ModelAndView("ExcelRevenueSummary","revenueData",revenueData);
           
      /*    if(output ==null || "".equals(output)){
                  //return normal view
                  return new ModelAndView("RevenueSummary","revenueData",revenueData);
                 
            }else if("EXCEL".equals(output.toUpperCase())){
                  //return excel view
                  return new ModelAndView("ExcelRevenueSummary","revenueData",revenueData);
                 
            }else{
                  //return normal view
                  return new ModelAndView("RevenueSummary","revenueData",revenueData);
                 
            }
      */   
      }
     
}

The commented part can be used to forward your view at different location.

ExcelRevenueReportView.java class :

package com.application.utility;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ExcelRevenueReportView extends AbstractExcelView{
     
      @Override
      protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
                  HttpServletRequest request, HttpServletResponse response)
                  throws Exception {
           
           
            Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
            //create a wordsheet
            HSSFSheet sheet = workbook.createSheet("Data Report");
           
            HSSFRow header = sheet.createRow(0);
            header.createCell(0).setCellValue("Month");
            header.createCell(1).setCellValue("Data");
           
            int rowNum = 1;
            for (Map.Entry<String, String> entry : revenueData.entrySet()) {
                  //create the row data
                  HSSFRow row = sheet.createRow(rowNum++);
                  row.createCell(0).setCellValue(entry.getKey());
                  row.createCell(1).setCellValue(entry.getValue());
                 
        }
      }
}

Call this from your onSubmit method of your controller according to the condition you required.

return "redirect:exportForClient.htm"; 

Monday, July 2, 2012


Scheduling/Scheduler in Spring:


Entry in application-servlet.xml file:

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
      xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.directwebremoting.org/schema/spring-dwr  http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">



<!-- Configuration for Sceduler. The "task" namespace is used here to declare the scheduler and executor.The third line of the XML asks Spring to scan classes for annotations related to scheduled tasks.If you have multiple tasks to run at the same time, you can get them to run in parallel by increasing the pool size.-->
      <task:scheduler id="taskScheduler"/>
      <task:executor id="taskExecutor" pool-size="1"/>
      <task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>



Our Scheduler Class:

@Service
public class Scheduler{
      //@Scheduled(cron = "* * 1 * * ?")
      @Scheduled(fixedRate=60000)
      public void runReport() {
     System.out.println("Generating report/Sending Mail/Performing Check on Db");
      }
}

We can also use cron expression for a definite time:

The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.

Example patterns:

  • "0 0 * * * *" = the top of every hour of every day.
  • "*/10 * * * * *" = every ten seconds.
  • "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
  • "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
  • "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
  • "0 0 0 25 12 ?" = every Christmas Day at midnight

field                    allowed values
 -----                     --------------
 minute               0-59
 hour                    0-23
 day of month    1-31
 month                1-12 (or names, see below)
 day of week       0-7 (0 or 7 is Sun, or use names)

and cron expressions can also be read from the properties file :
using ${cron.expression}
in properties file: cron.expression=*/10 * * * * *

http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html

Java based configuration from Spring 3.1.4.RELEASE, we can eliminate xml configuration by using:

@Configuration
@EnableScheduling

Tuesday, June 26, 2012

org.springframework.web.HttpSessionRequiredException: Session attribute 'user' required - not found in session

This error comes when the default session of spring expires, and we try to fetch user from @SessionAttribute("user").

The solution is to override the session timing in web.xml:

<session-config>
     <session-timeout>60</session-timeout>
 </session-config>

This will increase your session time to 60 minutes, now you will get this error after 60 mins of idle time.

We can also redirect it to the login page by the following entry in web.xml:

<error-page>
  <exception-type>
       org.springframework.web.HttpSessionRequiredException
  </exception-type>
  <location>/redirect.jsp</location>
</error-page>