Saturday, February 11, 2012

It's time to move on..

Yes, I am very lazy and to better fight my laziness I decided to switch to Wordpress.
There are a bunch of good reason to remain here on blogspot, but a lot of good reason to switch to Wordpress.

If you like my posts and want to follow more ones, refer to:

Nick's place on wordpress.

Thanks!

Friday, July 8, 2011

A different web design

As a software engineer, I wish a web like this:

Yahoo logo

Very funny, short and hard to develop!!!


Monday, July 4, 2011

AJAX captcha - with jQuery and Java


Hi all,
In this article I show how to develop a jQuery captcha for your forms, using Java and servlets, fully ajaxified.

The result will be:


You can download the source code from here.


These kind of topics, typically are posted by php and web developers, who have to face with a common problem: spammers.

Well, don’t forget that this matter is for Java developers, too.
Captchas let to stop spammers from automatically and repeatidly registering to your site through forms and invading your database of contacts with fake registrations.

I admit that rarely I needed this kind of protection and this is not so very simple to enable with Java.
Furthermore, there is not a wide documentation available on the web and googling leads to several, different solutions.

Maybe jCaptcha is what you are looking for, but googling I found a wonderful jQuery plugin, very user-friendly: sexy-captcha.

It is a drag and drop captcha, full-ajaxified, and very user-friendly (read as “idiot proof”).
For a demo, please visit this page from the plugin’s author: DEMO

Let’s start with code!!!!

The most significant work for me about this was to adapt PHP code to Java code, then I clean code using some design pattern more adequate for this application.

Technologies involved:
  • JSP;
  • Servlet;
  • JSTL;
  • JRE6;
  • Apache Tomcat 7 (but any java application server could be used);
  • jquery and sexy-captcha plugin.


In this case I prefer to use simple and plain Java solution, avoiding frameworks, in order to show only how to perform an AJAX call to check and refresh captcha submission.
Anyway, it is simple to adapt this code to whatever java frameworks you prefer.

As IDE for development I used Eclipse.
First of all create a new Web Dynamic Project, as usual, within Eclipse.
Call it: captcha.
I use default configurations, so jsp will be by default under WebContent folder.

Then we need to import JSTL library that will perform JSP dynamic renderization
You can download them from here.

The configuration is quite stright-forward:
  • Import them by right clicking on project --> properties --> Java build path --> tab: Libraries --> Add External Jars.
  • Additional, mandatory step: copy the jars into /WEB-INF/lib


Now we have the Eclipse project set up and ready to code.

Let’s begin from JSP.

Under WebContent, create a new jsp called index.jsp (that by default is the welcome-file in the WEB.xml).

index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!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>Captcha</title>
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/sexy-captcha/styles.css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.sexy-captcha-0.1.js"></script>
<script>
 $("document").ready(function() {
  $('.myCaptcha').sexyCaptcha('CaptchaServlet');

 });
</script>
</head>
<body>
 <form id="test-form" action="">
  <div class="myCaptcha"></div>
 </form>
</body>
</html>

As you can see there are some javascript libraries imported. I suggest to download the pack from sexy-captcha blog.

Then unpack it and copy the folders and files under WebContent folder of our Eclipse project.

Servlet.

Add a new servlet to project:
right click on project →  new →  Servlet → package name: it.nicogiangregorio.servlets and servlet name: CaptchaServlet.java

Then type the following code:
-------
package it.nicogiangregorio.servlets;

import it.nicogiangregorio.core.CaptchaContext;
import it.nicogiangregorio.core.impl.CaptchaRefreshAction;
import it.nicogiangregorio.core.impl.CaptchaVerifyAction;
import it.nicogiangregorio.utils.WebConstants;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CaptchaServlet
 */
@WebServlet("/CaptchaServlet")
public class CaptchaServlet extends HttpServlet {

 /**
  * 
  */
 private static final long serialVersionUID = -243950967076586170L;

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String forwardJsp = null;
  String action = request.getParameter(WebConstants.PARAM_ACTION);

  CaptchaContext captchaCtx = new CaptchaContext();

  if (WebConstants.ACTION_VERIFY.equals(action)) {

   captchaCtx.setCaptchaAction(new CaptchaVerifyAction());

  } else if (WebConstants.ACTION_REFRESH.equals(action)) {

   captchaCtx.setCaptchaAction(new CaptchaRefreshAction());

  } else {
   System.out.println("Undefined behaviour due to unexpected action.");
  }

  forwardJsp = captchaCtx.processCaptcha(request, response);
  getServletContext().getRequestDispatcher(forwardJsp).forward(request,
    response);
 }
}

The doPost() method let to perform to actions:
  • VERIFY action, to check captcha submitted by user;
  • REFRESH action, to refresh captcha question;

Elaboration is done by classes with some business logic. I’ll show them in a while, again.
And finally redirects output to returned jsp.

I use a bunch of constants all stored into a Java class.


WebConstants.java
-------
package it.nicogiangregorio.utils;

/**
 * 
 * Constants class
 * 
 * @author Nico Giangregorio
 * 
 */
public class WebConstants {
 public static final String NICK_DEMO = "nick_demo";
 public static final String PARAM_ACTION = "action";
 public static final String ACTION_VERIFY = "verify";
 public static final String ACTION_REFRESH = "refresh";
 public static final String ATTR_CAPTCHA_ANSWER = "captchaAnswer";
 public static final String ATTR_CAPTCHA_CODES = "captchaCodes";
 public static final String VERIFY_RESULT = "VerifyResult";
 public static final String PARAM_CAPTCHA = "captcha";
 public static final String PARAM_CAPTCHA_SUBSTR = "draggable_";
 public static final String VERIFY_RESULT_SUCCESS = "success";
 public static final String VERIFY_RESULT_FAILED = "failed";
 public static final String VERIFY_FORWARD_JSP = "/verify.jsp";
 public static final String REFRESH_FORWARD_JSP = "/refresh.jsp";
 public static final String ERROR_FORWARD_JSP = "/error.jsp";
 public static final String ATTR_CAPTCHA_IMAGES = "captchaImages";
 public static final String ATTR_RIGHT_ANSWER = "rightAnswer";

 // Enforce non-istantiability
 private WebConstants() {
 }
}

Note: you can use static import, here I avoided it due to readability.
Now let’s what business logic does.
First of all, the application can do 2 simple things:
  • Verify the captcha;
  • Refresh the captcha;
So, our CaptchaServlet can perform two different actions, depending on what the user wants and finally forwarding the result of this computation to two different JSP, rendering result that will be the AJAX response.

In order to achieve this goal, I think it is better to implement the Strategy design pattern.
With this pattern, the application choose at runtime which algorithm adopt to provide computation required by user.

The strategy interface, package it.nicogiangregorio.core and interface ICaptchaAction.java:
package it.nicogiangregorio.core;

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

public class CaptchaContext {
 private ICaptchaAction captchaAction;

 public void setCaptchaAction(ICaptchaAction captchaAction) {
  this.captchaAction = captchaAction;
 }

 public String processCaptcha(HttpServletRequest request,
   HttpServletResponse response) {
  return captchaAction.process(request, response);
 }
}

The two possible strategies for captcha app are two implementation of this interface.
Let’s start with strategy related to refresh action.

REFRESH.

Refreshing allows to user, to generate a new question for him.
CaptchaRefreshAction.java

-----
package it.nicogiangregorio.core.impl;

import it.nicogiangregorio.core.ICaptchaAction;
import it.nicogiangregorio.utils.CaptchaEnum;
import it.nicogiangregorio.utils.CaptchaGenerator;
import it.nicogiangregorio.utils.WebConstants;

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

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

/**
 * Strategy for Refreshing action: Reset captcha order and right answer to
 * captcha question, then forward to correct jsp otherwise forward to a courtesy
 * jsp
 * 
 * @author Nico Giangregorio
 * 
 */
public class CaptchaRefreshAction implements ICaptchaAction {

 @Override
 public String process(HttpServletRequest request,
   HttpServletResponse response) {

  Map<CaptchaEnum, String> captchaCodes = new HashMap<CaptchaEnum, String>();

  try {
   captchaCodes.put(CaptchaEnum.STAR,
     CaptchaGenerator.createCaptchaCodes());
   captchaCodes.put(CaptchaEnum.HEART,
     CaptchaGenerator.createCaptchaCodes());
   captchaCodes.put(CaptchaEnum.BWM,
     CaptchaGenerator.createCaptchaCodes());
   captchaCodes.put(CaptchaEnum.DIAMOND,
     CaptchaGenerator.createCaptchaCodes());

  } catch (IllegalStateException e) {
   return WebConstants.ERROR_FORWARD_JSP;
  }

  int index = new Random().nextInt(captchaCodes.size());
  CaptchaEnum rightAnswer = CaptchaEnum.values()[index];

  request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_ANSWER,
    captchaCodes.get(rightAnswer));

  request.getSession().setAttribute(WebConstants.ATTR_RIGHT_ANSWER,
    rightAnswer);

  request.getSession().setAttribute(WebConstants.ATTR_CAPTCHA_CODES,
    captchaCodes);

  return WebConstants.REFRESH_FORWARD_JSP;
 }
}

It simply creates a map of images available for captchas and associates for each image a random generated identifier.

The list of images and other CSS data associated with each of them is stored into CaptchaEnum.
Then it elects one the 4 captcha available that will be the “right answer”.

At the end it sends the attributes with results of elaboration to HTTP session.
Please, before writing your own custom implementation remember that object in HttpSession should be serializable as servlet specification requires.

In our case, the enum is CaptchaEnum.java:
----------

package it.nicogiangregorio.utils;

/**
 * Associate CSS info to a given image and enumerate them. This is immutable
 * andserializable. It strongly replaces a bean
 * 
 * @author Nico Giangregorio
 * 
 */
public enum CaptchaEnum {
 STAR("-120px", "-3px", "-120px", "-66px"), HEART("0", "-3px", "0px",
   "-66px"), BWM("-56px", "-3px", "-56px", "-66px"), DIAMOND("-185px",
   "-3px", "-185px", "-66px");

 private final String onTop;
 private final String onLeft;
 private final String offTop;
 private final String offLeft;

 CaptchaEnum(String onTop, String onLeft, String offTop, String offLeft) {
  this.onTop = onTop;
  this.onLeft = onLeft;
  this.offTop = offTop;
  this.offLeft = offLeft;
 }

 public String getOnTop() {
  return onTop;
 }

 public String getOnLeft() {
  return onLeft;
 }

 public String getOffTop() {
  return offTop;
 }

 public String getOffLeft() {
  return offLeft;
 }

}


As every enum it is serializable and immutable, so we don't have to be worried about concurrency and serialization.



The classes that generates this random identifiers is:
package:
it.nicogiangregorio.utils

class:
CaptchaGenerator.java
----------
package it.nicogiangregorio.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import sun.misc.BASE64Encoder;

/**
 * Helper class to generate random code to associate with captcha
 * 
 * @author Nico Giangregorio
 * 
 */
public class CaptchaGenerator {

 private CaptchaGenerator() {
 }

 public static String createCaptchaCodes() {

  MessageDigest digest = null;
  byte[] result = {};

  SecureRandom rand = new SecureRandom();
  BASE64Encoder encoderToBase64 = new BASE64Encoder();

  try {

   digest = MessageDigest.getInstance("SHA-256");
   digest.update(WebConstants.NICK_DEMO.getBytes());

  } catch (NoSuchAlgorithmException e) {
   throw new IllegalStateException(e);
  }

  String randString = "" + rand.nextDouble();
  result = digest.digest(randString.getBytes());

  return encoderToBase64.encode(result);
 }
}


starting from a random generated number from SecureRandom and with a Salt it creates an hashed string, using SHA-256.
It is a singleton..

And now..

VERIFY

The verify strategy checks if user submitted the correct captcha answer.

package:
it.nicogiangregorio.core.impl

class:
CaptchaVerifyAction.java

-----
package it.nicogiangregorio.core.impl;

import it.nicogiangregorio.core.ICaptchaAction;
import it.nicogiangregorio.utils.WebConstants;

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

public class CaptchaVerifyAction implements ICaptchaAction, WebConstants {

 @Override
 public String process(HttpServletRequest request,
   HttpServletResponse response) {
  String hashCaptcha = request.getParameter(PARAM_CAPTCHA).substring(
    PARAM_CAPTCHA_SUBSTR.length());
  String captchaAnswer = (String) request.getSession().getAttribute(
    ATTR_CAPTCHA_ANSWER);
  String result;

  if (captchaAnswer.equals(hashCaptcha))
   
   result = VERIFY_RESULT_SUCCESS;
  else {
   
   request.getSession().setAttribute(ATTR_CAPTCHA_CODES, null);
   request.getSession().setAttribute(ATTR_CAPTCHA_ANSWER, null);
   result = VERIFY_RESULT_FAILED;
  }

  request.getSession().setAttribute(VERIFY_RESULT, result);
  return VERIFY_FORWARD_JSP;
 }
}

Very simple and straight-forward.

Next we need to manage the correct strategy, with a context class:

package:
it.nicogiangregorio.core

class:
CaptchaContext
-------
package it.nicogiangregorio.core;

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

public class CaptchaContext {
 private ICaptchaAction captchaAction;

 public void setCaptchaAction(ICaptchaAction captchaAction) {
  this.captchaAction = captchaAction;
 }

 public String processCaptcha(HttpServletRequest request,
   HttpServletResponse response) {
  return captchaAction.process(request, response);
 }
}

It lets the application to select which strategy to use and finally performs processing.
Note: it returns what single strategies return, i.e. the right JSP to forward.

Each strategy and\or action, need to forward results of elaboration to one dedicated JSP, so create two new jsp:

verify.jsp
refresh.jsp

The names are self-explanatory.

This time we begin with (under WebContent)
verify.jsp:
-----
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" import="it.nicogiangregorio.utils.WebConstants"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="VERIFY_RESULT"
 value="<%=request.getSession().getAttribute(WebConstants.VERIFY_RESULT) %>"></c:set>
 <c:set var="VERIFY_SUCCESS"
 value="success"></c:set>
<c:choose>
<c:when test="${VERIFY_RESULT eq VERIFY_SUCCESS }">
 {'status': 'success'}
</c:when>
<c:otherwise>
 {'status': 'error'}
</c:otherwise> 
</c:choose>
We generate a JSON output that is the response to JQuery sezy-captcha plugin. Next the jsp returning the updated html frame with captcha:
refresh.jsp

----
<%@page import="it.nicogiangregorio.utils.CaptchaEnum"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" import="it.nicogiangregorio.utils.WebConstants"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>










It takes attributes from session and uses them to render a new snippet of HTML with refreshed captcha values.

That’s all.

Here our amazing captcha:



Download source code from github.



UPDATE: I edited some code on github and consequently this post. Now everything looks better and the app is 1.5+ compliant.



References:

Tuesday, May 10, 2011

Fresh new articles...coming soon

It's been a long time since I published last article on this blog. But..As soon as possible I'll be back! I don't know yet what to focus on: I recently studied a lot of technologies on several IT areas, Android, C++, Python, Ruby on Rails, Design Patterns, Performance tweaking, Linux. May be the newxt article will be about design patterns...may be not. Stay tuned!

Wednesday, August 4, 2010

Java Proxy Pattern - Caching proxy



Proxy pattern applied to enable caching - a very simple Web Application



Recently I switched to work for another customer (Bank\Trading) and one of the first activities, in order to offer a more structured and well-designed product to users, was to reduce the overhead and the Database accesses. Considering that I am working on a web portal with 2 millions of contacts per month and hundreds of user accounts, designed and developed more than 10 years ago, it is very difficult to adopt any Java Framework and, in general, to implement whatever big modification. I studied several solutions to optimize the system’s performances. One of the pattern that comes to help in my work is the Proxy Pattern. I’m going to show you some aspects of this pattern, related to caching objects and data. This article is divided into two parts, one for each solution that I found to this issue. We’ll go into a very simple web application: NO dependency injection this time, NO Spring, NO Frameworks, only very simple code. We’ll create a simple web app that on home page will print the timestamp of last created instance of cached object. Consider that this object may be a complex data structure from a database, or a big image or something very painful for server. For our purpose, things are simplified. Well, we can summarize: 1. user requires an object 2. system check: an instance of this object already is created? 3. If no, it create a new instance, otherwise it give back the already made instance. 4. The user, transparently, receives the object. Let’s go! Configure Eclipse. Just create a New Dynamic Web Project, I called proxycacheapp. I used this project for both solutions that I’m going to implement. UML Class Diagram of a classical Proxy pattern from original GoF book, is:



 

And, briefly: the JSP contains the code for execute the request, that is wrapped by Servlet Filter (declared in web.xml as I hope you already know), Servlet Filter calls our ProxyService to achieve what user wants. ProxyService is only a surrogate, if the object required is ready and already created, it give back to user the cached instance, otherwise Proxy calls concrete RealService and require to create a new one. Object (either brand new or cached) is sent to output of ServletFilter, that incapsulate it into HttpRequest and, later Jsp prints it on Web page. Simple. This is a general scenario, but pragmatic implementation, can be made using two different solutions. Solution 1 Plain, classical, proxy pattern applied. This solution uses only diagrams and the previous explanation, no more complication. Domain Object It is very useless here, but I want to show you that it is possible to use any custom Object in this approach. Let’s create a new object, a POJO, with an ID and a timestamp..later we’ll print timestamp on JSP. Create new Java Class on Eclipse and write th wolling code (I use it.nickg.utils package):

package it.nickg.utils;

public class Timestamp {
 private long id;
 private String timestamp;

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public String getTimestamp() {
  return timestamp;
 }

 public void setTimestamp(String timestamp) {
  this.timestamp = timestamp;
 }
}


This is our Domain object. Now let’s implement the Proxy Pattern, first create a new interface (package is it.nickg.services):
package it.nickg.services;

import it.nickg.utils.Timestamp;

public interface TimestampService {

 /**
  * retrieve an istance of Timestamp object
  * 
  * @return Timestamp object
  */
 public Timestamp getTimestamp();

}








Then let’s write the Real implementation of Service, that creates instance of our Domain Object, it implements our previously created interface:
package it.nickg.services;

import it.nickg.utils.Timestamp;

import java.util.Date;

public class TimestampServiceReal implements TimestampService {

 @Override
 public Timestamp getTimestamp() {

  Date time = new Date();
  Timestamp timestamp = new Timestamp();

  timestamp.setId(time.getTime());
  timestamp.setTimestamp(time.toString());

  return timestamp;
 }

}




Not best solution for getting a timestamp, I know, but it is only for a learning purpose. Look at the concept.
package it.nickg.services;

import it.nickg.utils.Timestamp;

public class TimestampServiceProxy implements TimestampService {

 private TimestampServiceReal timestampServiceReal;
 public Timestamp timestamp;

 @Override
 public Timestamp getTimestamp() {

  // Proxy checks if a real instance of service (and of timestamp object)
  // already is created
  if (timestampServiceReal == null) {
   timestampServiceReal = new TimestampServiceReal();
   timestamp = timestampServiceReal.getTimestamp();
  }

  // return required object
  return timestamp;
 }
}



Now, It’s time to code our front-end!
Most of the work is done through a Servlet Filter that wraps request, calls our services and sets a parameter in HttpResponse, with results.

Servlet Filter must be declared in web.xml:
(complete web.xml code)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <filter>
  <filter-name>TimestampFilter</filter-name>
  <filter-class>it.nickg.servlets.TimestampFilter</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>TimestampFilter</filter-name>
  <url-pattern>/index.jsp</url-pattern>
 </filter-mapping>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>


Here Servlet Filter code:
package it.nickg.servlets;

import it.nickg.services.TimestampService;
import it.nickg.services.TimestampServiceProxy;
import it.nickg.utils.Timestamp;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TimestampFilter implements Filter {
 TimestampService tsService = new TimestampServiceProxy();

 public TimestampFilter() {
  // TODO Auto-generated constructor stub
 }

 @Override
 public void destroy() {
  // TODO Auto-generated method stub

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
   ServletException {

  Timestamp timestamp = null;

  // retrieve a timestamp from service
  timestamp = tsService.getTimestamp();
  request.setAttribute("timestamp", timestamp);

  // forward output
  chain.doFilter(request, response);
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  // TODO Auto-generated method stub

 }

}



Last step is about editing index.jsp, and let display the creation’s timestamp of Domain Object:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="it.nickg.utils.Timestamp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Proxy Pattern Example</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
  
  <body>
    <h3>Domain object is created:</h3><br>
    <%
     Timestamp timestamp = (Timestamp)request.getAttribute("timestamp");
     out.print(timestamp.getTimestamp());
     %>
  </body>
</html>




I HATE to use scriplet and Java code in JSPs, use jstl, struts taglib, any other technology. Especially in production code.

That’s all, now run our server inside Eclipse (I use tomcat)
Right click on project -> Run as  -> Server Application.

Now on welcome page, it displays first creation timestamp of the object and if you refresh the page, the timestamp doesn’t change:
It is cached!!







Simple, isn’t?

Well, It’s time for more complicated issues.



Solution 2

A more experienced reader can found my previous solution a bit like “reinventing the wheel” and it’s in part true, because java offers a Proxy class:

java.lang.reflect.Proxy

Using Java reflection it is possible to implement a more elegant representation of Proxy Pattern.

For a cleaner implementation, we define a TimestampServiceFactory:

package it.nickg.services;

import java.lang.reflect.Proxy;

public class TimestampServiceFactory {
 public TimestampService createService() {
  return (TimestampService) Proxy.newProxyInstance(
   TimestampService.class.getClassLoader(),
   new Class[] { TimestampService.class },
   new TimestampReflectProxy(new TimestampServiceReal()));
 }
}



Here we use Proxy.newProxyInstance() to call a proxy. It returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler(TimestampReflectProxy).

And an interface CacheIFace:
package it.nickg.services;

public interface CacheIFace {

 /**
  * Retrieve object from cache
  * 
  * @param key
  * @return cached object
  */
 public Object getCache(Object key);

 /**
  * Put a new object in cache
  * 
  * @param key
  * @param value
  */
 public void putCache(Object key, Object value);
}



and an implementation class Cache:
package it.nickg.services;

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

public class Cache implements CacheIFace {
 private Map<Object, Object> values;

 public Cache() {
  this.values = new HashMap<Object, Object>(8);
 }

 public Object getCache(Object key) {
  return values.get(key);
 }

 public void putCache(Object key, Object value) {
  values.put(key, value);
 }
}



These comes to let us perform caching feature through an HashMap:
HashMap IS the cache.

Create a new Java Class named TimestampReflectProxy that implements InvocationHandler:
package it.nickg.services;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

public class TimestampReflectProxy implements InvocationHandler {

 private final Object obj;
 private CacheIFace caches;
 private static final Object NullKey = new Object();

 public TimestampReflectProxy(Object toProxy) {
  this.obj = toProxy;
  this.caches = new Cache();
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

  CacheIFace cache = (CacheIFace) caches.getCache(method);

  if (cache == null) {
   caches.putCache(method, cache = new Cache());
  }

  Object argsList = args != null ? Arrays.asList(args) : NullKey;
  Object cacheValue = cache.getCache(argsList);

  if (cacheValue == null) {
   cache.putCache(argsList, cacheValue = method.invoke(obj, args));
  }
  return cacheValue;
 }
}



And, finally, here is the ServletFilter modified:
package it.nickg.servlets;

import it.nickg.services.TimestampService;
import it.nickg.services.TimestampServiceFactory;
import it.nickg.utils.Timestamp;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TimestampFilter implements Filter {
 // TimestampService tsService = new TimestampServiceProxy();
 TimestampServiceFactory tsFactory = new TimestampServiceFactory();
 TimestampService tsService = tsFactory.createService();

 public TimestampFilter() {
  // TODO Auto-generated constructor stub
 }

 @Override
 public void destroy() {
  // TODO Auto-generated method stub

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
   ServletException {

  Timestamp timestamp = null;

  // retrieve a timestamp from service
  timestamp = tsService.getTimestamp();
  request.setAttribute("timestamp", timestamp);

  // forward output
  chain.doFilter(request, response);
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  // TODO Auto-generated method stub

 }
}

I try to explain this magic trick.
Our TimestampReflectProxy class has two private attributes, obj and caches.
When user requires the page, the TimestampFilter acts as wrapper, it catches the request and calls TimestampServiceFactory and TimestampService that requires to create the service.

First time, it passes TimestampServiceReal as Object to  TimestampReflectProxy ‘s constructor, so:
- obj is an instance of TimestampServiceReal;
- a new instance of Cache is created;

Then the filter calls getTimestamp() method and this call is caught with reflection:
- it enters in invoke() method,
- it checks if an occurrence of method is already present in caches,
- there isn’t the required occurrence and so cache is null,
- it puts a new entry in cache;
- then retrieve the args list and checks if there is an entry in cache with given key;
- if not, it create a new one invoking method;

From this time, every time the user refreshs the web page, the application using reflection, finds existing entries in cache, skips checks, and gives back to him.

Here the results, if you try to refresh the page, display doesn’t change:







While this second solution seems very interesting, advanced, elegant and cool..there are several drawbacks:
(cut and paste from Sun)

Performance Overhead
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
Security Restrictions
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
Exposure of Internals
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Some interesting discussions are linked above between references.

Enough to avoid it in my particular use case.

Last thing I want to show.
Perhaps more careful of you have observed that when an instance of an object is created, it can live forever!
(Well, I know, it’s impossible, but “undefined” and “forever” are both unacceptable in my opinion).

Best way to give the capability of periodical refresh of object, is implementing a TimeToLive Strategy. (Other possible solutions are LRU and LFU).
I’ll not describe here now, but give you some input:
Into our Cache class, it is necessary to code a thread that periodically cleans the cache and you can use whatever policy you want.

That’s all folks!

Please, feel free to add comment and critics to my article, they are very useful.







References:

About Reflection:

About reflection performances: