Sample Spring MVC Web Project (Annotation based)



Project architecture :







Web.xml :

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

  <display-name>Spring MVC Tutorial</display-name>
  <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>SpringMVCTutorial.root</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/project-config.xml</param-value>
  </context-param>
  <filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <session-config>
        <session-timeout>60</session-timeout>
  </session-config>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
      <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
  </listener> 
  <servlet>
    <servlet-name>MainController</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mainServlet/MainController-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>MainController</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>
      /WEB-INF/views/index.jsp
    </welcome-file>
  </welcome-file-list>
  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/WEB-INF/views/errorPage.jsp</location>
  </error-page>
</web-app>

Main Controller servlet xml file :

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
   
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    <beans:bean id="applicationContextProvider" class="com.mz.it.context.ApplicationContextProvider"/>
   
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
   
    <context:component-scan base-package="com.mz.it.web" />
   
</beans:beans>

project-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
   
    <!-- Root Context: defines shared resources visible to all other web components -->
    <bean id="applicationProperties" class="org.springframework.beans.factory.config.MapFactoryBean">
        <property name="sourceMap">
            <map>
                <entry key="appName" value="Spring MVC Template Project" />
                <entry key="version" value="1.0.0" />
            </map>
        </property>
    </bean>
    <bean id="product" class="com.mz.it.object.Product" init-method="init" destroy-method="destroy">
       <property name="name" value="Hello World!"/>
    </bean>
</beans>


Include.jsp :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page session="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>



Index.jsp :

<%@ include file="/WEB-INF/views/include.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index Page</title>
</head>
<body>
<c:redirect url="main/displayProductInfo.htm/45?num=101"/>
</body>
</html>

errorPage.jsp :

<%@ page isErrorPage="true" %>
<%@ include file="/WEB-INF/views/include.jsp"%>
<%@page import="com.oracle.ondemand.crm.framework.logging.Log" %>
<%@page import="com.oracle.ondemand.crm.framework.logging.LogFactory"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <%! private Log logger = LogFactory.getLog(getClass()); %>
    <body style="background-color: rgb(238,238,238);">  
        <table border = "0" cellpadding = "0" cellspacing = "0" width = "100%">
            <tr>
                <td style="margin-left:50px;">                   
                    <font color="red"><b><i>Error :</i></b><br>
                    <table border=2>
                        <tr>
                            <td>
                            <%= exception.getMessage() %>
                            <% logger.error(exception.getMessage(), exception); %>
                            </td>
                        </tr>
                    </table>
                   
                    </font>               
                </td>               
            </tr>           
        </table>
       
    </body>
</html>

content.jsp:

<%@ include file="/WEB-INF/views/include.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Content Page</title>
</head>
<body>
<p>${appName} - ${version}</p>
<hr>
<b>NAME  :${productName}</b><br>
<b>FIELD :${productField}</b><br>
<b>ID    :${productId}</b><br>
<b>Session Id : <%= session.getId().toString() %></b>
<hr>
</body>
</html>


MainController.java:

package com.mz.it.web;

/**
 * @author Metin ZAFER
 *
 */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mz.it.constants.ConstantValues;
import com.mz.it.context.AppContext;
import com.mz.it.framework.util.XMLConfigUtil;
import com.mz.it.object.Product;
import com.oracle.ondemand.crm.framework.logging.Log;
import com.oracle.ondemand.crm.framework.logging.LogFactory;

@Controller
@RequestMapping("main")
public class MainController {

  private Log logger = LogFactory.getLog(this.getClass());
  protected HttpSession session;
 
  @RequestMapping(value = "index.htm", method = RequestMethod.GET)
  public String doGet(Model model) {
   
      String message = "Hi Zafer!";
      model.addAttribute("message", message);
     
      return "content";
  }
 
  @RequestMapping(value = "search.htm", method = RequestMethod.POST)
  public String doPost(Model model) {
   
      String message = "Hi Zafer!";
      model.addAttribute("message", message);
     
      return "content";
  }
 
  @RequestMapping(value = "displayProductInfo.htm/{id}")
  public String displayProductInfo(@PathVariable("id") int id, Model model, @RequestParam("num") int num, HttpServletRequest request, HttpServletResponse response)  {

    String version = "";
    String appName = "";
    version = XMLConfigUtil.getInstance().getPropertyValue(ConstantValues.APP, "version");
    appName = XMLConfigUtil.getInstance().getPropertyValue(ConstantValues.APP, "appName");
   
    ApplicationContext appContext = AppContext.getApplicationContext();
   
    Product pro2 = (Product) appContext.getBean("product");
   
    System.out.println("pro2 - name : " + pro2.getName());
    //session management
    manageSession(request);
   
    String message = "Product Page";
    model.addAttribute("message", message);
    model.addAttribute("version", version);
    model.addAttribute("appName", appName);
   
    if(String.valueOf(num)!=null)
        System.out.println("URL Parameter Num : " + String.valueOf(num));
   
    Product pro = generateProduct();
    pro.setField("it");
    pro.setId(String.valueOf(id));
    pro.setName("web project");
   
    model.addAttribute("productName", pro.getName());
    model.addAttribute("productId", pro.getId());
    model.addAttribute("productField", pro.getField());
   
    ModelMap modelMap = new ModelMap();
    modelMap.put("product", pro);
   
    return "content";
  }
 
  //new instance of product
  private Product generateProduct(){
     
      return new Product();
  }
 
  private void manageSession(HttpServletRequest request){
       
        if (this.session == null){
           
            this.session = request.getSession(true);
        }
       
        if (!request.isRequestedSessionIdValid()){
           
            this.session = request.getSession(true);
        }
       
        if(this.session.isNew()){
           
            cleaner();
            session.setAttribute("sessionId", this.session.getId());
            System.out.println("<manageSession()> The new session id : " + this.session.getId());
            System.out.println("<manageSession()> Entrance to controller : New page session has been initialized" );
            logger.info("<manageSession()> The new session id : " + this.session.getId());
            logger.info("<manageSession()> Entrance to controller : New page session has been initialized" );
        }else{
            System.out.println("<manageSession()> The session has been already initialized!");
            System.out.println("<manageSession()> The session id : " + this.session.getId());
            logger.info("<manageSession()> The session has been already initialized!");
            logger.info("<manageSession()> The session id : " + this.session.getId());
        }
       
  }
 
  private void cleaner() {
       
        this.session.setAttribute("OBJID", "");
        this.session.setAttribute("htmlOfResults", "");
        this.session.setAttribute("html", "");
        this.session.setAttribute("name", "Company : "+ "");
        this.session.setAttribute("errorMessage", "");
        //it sets the loading page
        session.setAttribute("loadingPageChecker", "true");
        logger.info("<cleaner()> The session has been cleaned...");
       
    }

}



DAOController.java:

package com.mz.it.web;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oracle.ondemand.crm.framework.logging.Log;
import com.oracle.ondemand.crm.framework.logging.LogFactory;

/**
 * @author Metin ZAFER
 *
 */
@Controller
@RequestMapping("product")
public class DAOController {

      private Log logger = LogFactory.getLog(this.getClass());
      protected HttpSession session;
     
      @RequestMapping(value = "search.htm", method = RequestMethod.GET)
      public String doGet(Model model) {
       
          String message = "Product Data Base Section";
          model.addAttribute("title", message);
         
          return "database";
      }
}

AppContext.java:

/**
 *
 */
package com.mz.it.context;

import org.springframework.context.ApplicationContext; 

/**
 * @author Metin ZAFER
 *
 */
 
public class AppContext { 
 
    private static ApplicationContext ctx; 
 
    /**
     * Injected from the class "ApplicationContextProvider" which is automatically loaded during Spring-Initialization.
     */ 
    public static void setApplicationContext(ApplicationContext applicationContext) { 
       
        ctx = applicationContext; 
    } 
 
    /**
     * Get access to the Spring ApplicationContext from everywhere in your Application.
     * 
     * @return
     */ 
    public static ApplicationContext getApplicationContext() { 
       
        return ctx; 
    } 
 




ApplicationContextProvider.java:

/**
 *
 */
package com.mz.it.context;


import org.springframework.beans.BeansException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 

import com.mz.it.framework.util.XMLConfigUtil;
/**
 * @author Metin ZAFER
 *
 */
public class ApplicationContextProvider implements ApplicationContextAware { 
 
    public void setApplicationContext(ApplicationContext ctx) throws BeansException { 
        // Wiring the ApplicationContext into a static method 
        AppContext.setApplicationContext(ctx); 
        XMLConfigUtil.init(ctx);
    } 


Utils.java:

/*********************************************************************/
/*                  FILE HEADER                                      */
/*********************************************************************/
/*                                                                   */
/*  FileName    :  Utils.java                                        */
/*                                                                   */
/*  Author      :  Guru (OSSI)                                       */
/*                                                                   */
/*  Date        :  Dec 11, 2008                                      */
/*                                                                   */
/*  Description : Utilities class providing common functionality     */
/*                  used across the project.                         */
/*                                                                   */
/*********************************************************************/
/* Date        Who     Version      Comments                          */
/*-------------------------------------------------------------------*/
/* 11/12/2008  Guru     1.0         Initial version created             */
/*********************************************************************/
//package name
package com.mz.it.framework.util;

//Java releted imports
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.oracle.ondemand.crm.framework.logging.Log;
import com.oracle.ondemand.crm.framework.logging.LogFactory;

/**
 * Utilities class providing common functionality which can be used across the
 * project.
 *
 * @author Guru
 * @author VinayV
 *
 * @version 1.0
 */
public final class Utils {

    /**
     * The one and only instance of this class.
     */
    private static Utils myself;

    /** Logger for this class and subclasses */
    private Log logger = LogFactory.getLog(this.getClass());

    // ===============================
    // Constructor
    // ===============================

    /**
     * Default constructor
     */
    private Utils() {

    }/* end constructor */

    /**
     * Returns the one and only instance of this class.
     *
     * @return The one and only instance of <code>Utils</code> class.
     */
    public static Utils getInstance() {

        if (myself == null) {

            myself = new Utils();

        }

        return myself;

    }

    /**
     * This method is used to construct the getter method name for the given
     * property.
     * <p>
     * Examples: <blockquote>
     *
     * <pre>
     * Utils.getMethodName("age") returns "getAge"
     * Utils.getMethodName("username") returns "getUsername"
     * </pre>
     *
     * </blockquote>
     *
     * @param property
     *            String containing the property whose getter method needs to be
     *            constructed.
     *
     * @return String containing the getter method name for the given property.
     */
    public static String getMethodName(String property) {

        String methodName = "get";
        char[] firstChar = new char[1];
        firstChar[0] = property.charAt(0);
        String character = new String(firstChar);
        methodName = methodName + character.toUpperCase()
                + property.substring(1);

        System.out.println(methodName);

        return methodName;

    }

    /**
     * Loads the given file from the classpath.
     *
     * @param fileName
     *            a string containing the file name.
     *
     * @return an <code>InputStream</code> object corresponding to the loaded
     *         input file.
     *
     * @exception RuntimeException
     *                in case of failure to load a resource.
     */
    public static InputStream loadFromClasspath(String fileName)
            throws RuntimeException {

        InputStream is = Utils.class.getResourceAsStream("/" + fileName);

        if (is == null) {
            throw new RuntimeException("Failed to load " + fileName
                    + " from CLASSPATH.");

        }/* end if */

        return is;

    }/* end method loadFromClasspath */

    public static Document loadDocument(File fileName) throws Exception {

        DocumentBuilder builder = null;
        Document doc = null;
        DocumentBuilderFactory domFactory = null;

        try {

            domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            builder = domFactory.newDocumentBuilder();
            doc = builder.parse(fileName);

        } catch (SAXException e) {

            System.err.println("System Error : " + e.getMessage());

        } catch (IOException e) {

            System.err.println("System Error : " + e.getMessage());

        } catch (ParserConfigurationException e) {

            System.err.println("System Error : " + e.getMessage());

        }

        return doc;

    }

    /**
     * Determines whether the characters of the input string are all digits.
     *
     * @param input
     *            the string to be tested.
     *
     * @return true, if all the characters are digits,false otherwise.
     */
    public boolean isNumeric(String input) {
        char[] chars = input.toCharArray();

        for (int i = 0; i < chars.length; ++i) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }

        return true;
    }

    /**
     * Determines whether the given date is <i>n</i> days old. The value of
     * <i>n</i> is provided as the second parameter to this method.
     * <p>
     * The method performs a date difference between the current date and the
     * input date. If the difference is greater than the number days specified
     * by the second parameter then true is returned, false otherwise.
     *
     * @param input
     *            the date to be tested.
     *
     * @param days
     *            an integer containing the number of days
     *
     * @return true if the specified date is <i>n</i> days behind the current
     *         date, false otherwise.
     */
    public boolean isDateNDaysOld(Date input, int days) {
        if (input == null) {
            throw new NullPointerException("Input date is null");

        }/* end if */

        Calendar today = Calendar.getInstance();

        Calendar inputDate = Calendar.getInstance();

        inputDate.setTime(input);

        // add days to the input date.
        inputDate.add(Calendar.DATE, days);

        // Still today after the input date
        // then the given date is very much
        // behind the number of days given.
        return today.after(inputDate);
    }

    /**
     * Replaces the question marks in the text provided as first parameter, with
     * values in the array of strings provided as the second parameter.
     * <p>
     * <u>Example:</u><br>
     * <blockquote> Input: <code>" a b ? d e ?", {"c","f"}</code>
     * <p>
     * Output: <code>a b c d e f</code> </blockquote>
     *
     * @param text
     *            a string containing the text with question marks to be
     *            replaced.
     *
     * @param params
     *            an array of strings containing the values to be used to
     *            replace question marks.
     *
     * @return the input string with question marks substituted with the values.
     */
    public String replaceQMarks(String text, String[] params) {
       
        final String Q_MARK = "?";

        // resultant text
        String resText = "";

        int prevQpos = 0, nextQpos = 0;

        nextQpos = text.indexOf(Q_MARK, prevQpos);

        // We need to replace all ? with the values in the params.
        for (int i = 0; nextQpos != -1 && i < params.length; ++i) {
           
            resText += text.substring(prevQpos, nextQpos) + params[i];

            prevQpos = nextQpos + 1;

            nextQpos = text.indexOf(Q_MARK, prevQpos);
        }/* end for */

        return resText + text.substring(prevQpos);
    }

    /**
     * Returns the value of the given boolean in string form.
     *
     * @param value
     *            an boolean containing the value to be converted to string.
     *
     * @return the value of the given boolean in string form.
     */
    public static String valueOf(boolean value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given integer in string form.
     * <p>
     * Returns <code>&lt;null&gt;</code> if the input value is the
     * <code>Constants.DEFAULT_INT_VALUE</code>, string version of the given
     * value otherwise.
     *
     * @param value
     *            an integer containing the value to be converted to string.
     *
     * @return the value of the given integer in string form.
     */
    public static String valueOf(int value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given long number in string form.
     * <p>
     * Returns <code>&lt;null&gt;</code> if the input value is the
     * <code>Constants.DEFAULT_LONG_VALUE</code>, string version of the given
     * value otherwise.
     *
     * @param value
     *            a long containing the value to be converted to string.
     *
     * @return the value of the given long number in string form.
     */
    public static String valueOf(long value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given character in string form.
     * <p>
     * Returns the string version of the given value.
     *
     * @param value
     *            a character containing the value to be converted to string.
     *
     * @return the value of the given character in string form.
     */
    public static String valueOf(char value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given double in string form.
     * <p>
     * Returns the string version of the given value.
     *
     * @param value
     *            a double containing the value to be converted to string.
     *
     * @return the value of the given double in string form.
     */
    public static String valueOf(double value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given float in string form.
     * <p>
     * Returns the string version of the given value.
     *
     * @param value
     *            a float containing the value to be converted to string.
     *
     * @return the value of the given float in string form.
     */
    public static String valueOf(float value) {
       
        return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given date in string form.
     * <p>
     * Returns <code>&lt;null&gt;</code> if the input value is the
     * <code>null</code>, string version of the given value otherwise.
     *
     * @param value
     *            a date containing the value to be converted to string.
     *
     * @return the value of the given date in string form.
     *
     */
    public static String valueOf(Date value) {
       
        if (value == null)
            return null;
        else
            return "" + value;

    }/* end method valueOf */

    /**
     * Returns the value of the given calendar in string form.
     * <p>
     * Returns <code>&lt;null&gt;</code> if the input value is the
     * <code>null</code>, string version of the given value otherwise.
     *
     * @param value
     *            A {@link Calendar} containing the value to be converted to
     *            string.
     *
     * @return the value of the given {@link Calendar} in string form.
     *
     */
    public static String valueOf(Calendar value) {
       
        if (value == null)
            return null;
        else
            return "" + value;

    }/* end method valueOf */

    /**
     * Converts a String representation of date into java.util.Date object
     * depending on the date format specified.
     * <P>
     * Returns null if parsing date fails or input String is empty or null.
     *
     * @param sDate
     *            String representation of date
     *
     * @param format
     *            Input date format
     *
     * @return Date object constructed using input string.
     */
    public Date formatStringToDate(String sDate, String format) {
       
        Date formatedDate = null;

        if (sDate != null && !("".equals(sDate))) {
           
            SimpleDateFormat df = new SimpleDateFormat(format);
            df.setLenient(false);

            try {

                formatedDate = df.parse(sDate);

            } catch (ParseException ex) {

                ex.printStackTrace();

            }

        }
        return formatedDate;
    }

    /**
     * Converts a java.util.Date object to String representation of date
     * depending on the date format specified.
     * <P>
     * Returns null if input Date object is null.
     *
     * @param date
     *            object constructed using input string.
     *
     * @param format
     *            Input date format
     *
     * @return sDate String representation of date
     */
    public String formatDateToString(Date date, String format) {
       
        String formatedDate = null;

        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(format);
            df.setLenient(false);
            formatedDate = df.format(date);

        }
        return formatedDate;
    }

    /**
     * The method checks if the <code>date1</code> is after <code>date2</code>
     * supplied as input.
     * <p>
     * Returns true if date1 is after date2. This method ignores the time of the
     * day.
     *
     * @param date1
     *            an instance of <code>Date</code>.
     *
     * @param date2
     *            an instance of <code>Date</code>.
     *
     * @return a boolean containing the result.
     */
    public boolean dateAfter(Date date1, Date date2) {
       
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        cal2.set(Calendar.HOUR_OF_DAY, 0);
        cal2.set(Calendar.MINUTE, 0);
        cal2.set(Calendar.SECOND, 0);
        cal2.set(Calendar.MILLISECOND, 0);

        return cal1.after(cal2);
    }

    /**
     * The method checks if the <code>date1</code> is before <code>date2</code>
     * supplied as input.
     * <p>
     * Returns true if date1 is before date2. This method ignores the time of
     * the day.
     *
     * @param date1
     *            an instance of <code>Date</code>.
     *
     * @param date2
     *            an instance of <code>Date</code>.
     *
     * @return a boolean containing the result.
     */
    public boolean dateBefore(Date date1, Date date2) {
       
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        cal2.set(Calendar.HOUR_OF_DAY, 0);
        cal2.set(Calendar.MINUTE, 0);
        cal2.set(Calendar.SECOND, 0);
        cal2.set(Calendar.MILLISECOND, 0);

        return cal1.before(cal2);
    }

    /**
     * The method checks if the <code>date1</code> is equal <code>date2</code>
     * supplied as input.
     * <p>
     * Returns true if date1 is equal date2. This method ignores the time of the
     * day.
     *
     * @param date1
     *            an instance of <code>Date</code>.
     *
     * @param date2
     *            an instance of <code>Date</code>.
     *
     * @return a boolean containing the result.
     */
    public boolean dateEquals(Date date1, Date date2) {
       
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        cal1.set(Calendar.HOUR_OF_DAY, 0);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        cal2.set(Calendar.HOUR_OF_DAY, 0);
        cal2.set(Calendar.MINUTE, 0);
        cal2.set(Calendar.SECOND, 0);
        cal2.set(Calendar.MILLISECOND, 0);

        return cal1.equals(cal2);
    }

    /**
     * The method adds specified number of days to the given date and returns
     * the updated <code>Date</code> object.
     *
     * @param noOfDays
     *            the number of days.
     *
     * @param date
     *            an instance of <code>Date</code>
     *
     * @return the <code>Date</code> object .
     */
    public Date addDays(Date date, int noOfDays) {
       
        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        cal.add(Calendar.DAY_OF_MONTH, noOfDays);

        return cal.getTime();
    }

    /**
     * This method is used to convert a Date object to a
     * {@link GregorianCalendar} object.
     *
     * @param newDate
     *            Date object to be converted.
     *
     * @return An object of {@link GregorianCalendar}
     */
    public GregorianCalendar convertUtilDateToCalendar(Date newDate) {

        if (newDate == null) {

            return null;

        }

        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(newDate);

        return calendar;

    }

    /**
     * This method is used to convert a java.sql.Date object to a
     * {@link GregorianCalendar} object.
     *
     * @param newDate
     *            The java.sql.Date object to be converted.
     *
     * @return An object of {@link GregorianCalendar}
     */
    public GregorianCalendar convertSQLDateToCalender(java.sql.Date newDate) {

        if (newDate == null) {

            return null;

        }

        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(newDate);

        return gregorianCalendar;

    }

} // end of class Utils


XMLConfigUtil.java:

package com.mz.it.framework.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import org.springframework.context.ApplicationContext;

import com.oracle.ondemand.crm.constants.Global;
import com.oracle.ondemand.crm.util.ObjectListSettings;
import com.oracle.ondemand.crm.util.ObjectSettings;
import com.oracle.ondemand.crm.framework.logging.Log;
import com.oracle.ondemand.crm.framework.logging.LogFactory;
/**
 * This class is used for retrieving the properties defined in the XML config
 * file.
 *
 * <p>
 *
 *
 * @author: Guru
 * @author: Rajkumar
 *
 */
public class XMLConfigUtil {

    /** Logger for this class and subclasses */
    private static Log logger = LogFactory.getLog(XMLConfigUtil.class);

    /**
     * The one and only instance of this class.
     */
    private static XMLConfigUtil myself;

    /**
     *
     */
    private ObjectListSettings objectListSettings;

    /**
     * Spring Application Context
     */
    private static ApplicationContext context = null;

    /**
     * The map to store the remote home interfaces.
     */
    private Map<String, ObjectSettings> objectListMap;

    /**
     * Lock object for synchronization.
     */
    private static final Object LOCK = new Object();

    /**
     * Default constructor
     */
    private XMLConfigUtil() {
       
        this.objectListMap = new HashMap<String, ObjectSettings>();
        logger.debug("Object List HashMap initialised");
    }

    /**
     * Constructor used in initialising the {@link ApplicationContext} using the
     * given list of files.
     *
     * @param configPaths
     *            String array containing the absolute path of the spring config
     *            files.
     */
    private XMLConfigUtil(ApplicationContext applicationContext) {

        logger.debug("In XMLConfigUtil constructor");

        context = applicationContext;
        logger.debug("ApplicationContext initialised");

        this.objectListMap = new HashMap<String, ObjectSettings>();
        logger.debug("Object List HashMap initialised");

    }

    /**
     * This method is used to initialise the XMLConfigUtil class with the given
     * list of config files path.
     * <p>
     * This method is invoked by the {@link InitListener} during start up. If
     * this method is invoked for the second time, it would throw an
     * {@link IllegalStateException}.
     *
     * @param configPaths
     *            String array containing the absolute path of the spring config
     *            files.
     */
    public static void init(ApplicationContext applicationContext) {

        logger.debug("In XMLConfigUtil.init()");

        try {
           
            if (myself == null) {

                logger.debug("Initialising the XMLConfigUtil with the given application context");

                myself = new XMLConfigUtil(applicationContext);

            } else {

                throw new IllegalStateException("XMLConfigUtil is already initialised");

            }

        } catch (Exception e) {

            System.out.println("Error : " + e.getMessage());
        }
       
    }

    /**
     * This method is used to retrieve the one and only instance of
     * <code>{@link XMLConfigUtil}</code> class.
     *
     * @return The one and only instance of <code>{@link XMLConfigUtil}</code>
     *         class.
     */
    public static XMLConfigUtil getInstance() {

        if (myself == null) {

            throw new IllegalStateException(
                    "XMLConfigUtil is not "
                            + "initialised, please check if the ApplicationContextProvider is "
                            + "configured correctly.");

        }

        return myself;

    }

    /**
     * This method is used for get the value of key entry. Developer has to use
     * like this CRMConfigurer.getValue("BeanId", "key");
     *
     * @param beanId
     * @param key
     * @return String
     */
    public String getPropertyValue(String mapBeanId, String key) {
       
        String value = null;
        LinkedHashMap<?, ?> linkedHashMap = null;
        try {
           
            if (context != null) {
                Object mapObject = context.getBean(mapBeanId);
                if (mapObject instanceof LinkedHashMap) {
                    linkedHashMap = (LinkedHashMap<?, ?>) mapObject;
                }
                if (linkedHashMap != null) {
                    Object objectValue = linkedHashMap.get(key);
                    if (objectValue instanceof String) {
                        value = (String) objectValue;
                    }
                }
            }
        } catch (Exception e) {
           
            System.out.println("Error : " + e.getMessage());
            logger.error(e.getMessage());
        }

        // Added to decrypt the password
        if (key != null && key.trim().length() != 0
                && key.equalsIgnoreCase("password")) {
            value = (String) com.oracle.ondemand.crm.consulting.encryption.Base64
                    .decodeToObject(value);
        }

        return value;
    }

    /**
     * This method is used for retrieving the properties of the object list.
     *
     * @param type
     *            String indicating the object type.
     * @param key
     *            String indicating the key to be retrieved from the object
     *            list.
     *
     * @return String Property value
     */
    public Object getObjectListPropertyValue(String type, String key) throws Exception {

        ObjectSettings objectSettings;
        Object propertyValue = null;

        synchronized (XMLConfigUtil.LOCK) {
           
            objectSettings = (ObjectSettings) this.objectListMap.get(type);
            if (objectSettings == null) {
                this.objectListSettings = (ObjectListSettings) context.getBean(Global.OBJECT_LIST_BEAN_ID);
                ObjectSettings[] objectList = this.objectListSettings.getObjects();

                for (int i = 0; i < objectList.length; i++) {
                   
                    ObjectSettings objectSetting = objectList[i]; // get the
                    // current
                    // object settings.
                    String objectName = objectSetting.getType();
                    objectListMap.put(objectName, objectSetting);

                }
                objectSettings = (ObjectSettings) this.objectListMap.get(type);
            }

        }

        try {

            Class<? extends ObjectSettings> clz = objectSettings.getClass();
            Method method = clz.getMethod(Utils.getMethodName(key), null);
            propertyValue = method.invoke(objectSettings, (Object[]) null);

        } catch (SecurityException e) {
           
            System.err.println("System Error : " + e.getMessage());

        } catch (IllegalArgumentException e) {
           
            System.err.println("System Error : " + e.getMessage());
        } catch (NoSuchMethodException e) {
           
            System.err.println("System Error : " + e.getMessage());
        } catch (IllegalAccessException e) {
           
            System.err.println("System Error : " + e.getMessage());
        } catch (InvocationTargetException e) {
           
            System.err.println("System Error : " + e.getMessage());
        }

        return propertyValue;

    }

    /**
     * This method will return bean object based on beanId which user passed on
     * method.
     *
     * @param beanId
     * @return Object
     */
    public Object getBeanObject(String beanId) {
       
        Object object = null;
        try {
            if (context != null) {
           
                object = context.getBean(beanId);
            }
        } catch (Exception e) {
           
            System.out.println("Error : " + e.getMessage());
            logger.error(e.getMessage());
        }
        return object;
    }

    /**
     * This method is used for try to resolve the message. Return default
     * message if no message was found
     *
     * @param code
     * @param args
     * @param defaultMessage
     * @param locale
     * @return String
     */
    public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
       
        return context.getMessage(code, args, defaultMessage, locale);
    }

    /**
     * This method is used for try to resolve the message. Treat as an error if
     * the message can't be found.
     *
     * @param code
     * @param args
     * @param locale
     * @return String
     */
    public String getMessage(String code, Object[] args, Locale locale) {
       
        return context.getMessage(code, args, locale);
    }

}

Note : Spring framework 3.2.4 is used in this project

Sample ScreenShot :


The Happy End  :))












Comments

Popular Posts