Wednesday, December 25, 2013

Visitor Pattern

Visitor Pattern

I was doing a bit of research on visitor pattern. It was quite confusing at first as various sites were focusing on different points of this pattern. Following is my understanding of visitor pattern.

  • Allows new operations to be defined and used on element of an object structure without changing the contents of those elements.(Actual reason)
  • Visitor design pattern is a way of separating an algorithm from an object structure on which it operates.(Its just the result of what happens when you implement previous point)
  • Double dispatch(It is how visitor pattern internally work)

UML Diagram

Element :- Interface containing Accept method taking Visitor type as parameter.

Concrete Element :- Classes in which we intend to add functionality in future

Object Structure :- Collection of objects or composite object. It should have provision to iterate over each concrete element so that Accept method can be called.

Visitor :- Interface containing function for each Concrete element taking same as paramater. If we have 10 concrete elements then Visit interface will have 10 functions.

Concrete Visitor :- Concrete class implementing Visitor interface. We can have n number of concrete visitors depending on the number of functionality we need to add.


  • Extending the functionality of a class hierarchy by an external class.
  • Adding new operations is easy.
  • Related behavior isn't spread over classes defining the object structure, its localized in visitor.
  • Unrelated set of behavior are partitioned in own visitor subclass.
  • Simulate double dispatch.

  • Adding new ConcreteElement class is difficult as each new ConcreteElement gives rise to new abstract operation on visitor and corresponding implementation in every ConcreteVisitor class.
  • The ConcreteElement interface must be powerful enough to let visitor do their job. You may be forced to provide public operations that access an elements internal state, which may compromise its encapsulation.
  • Breaks Dependency Inversion Principle (DIP) : DIP states that a class should depend upon abstract classes and not concrete classes (Martin 2000). It is one of the object oriented class design principles which help in managing the module dependencies and thus preventing the rotting of design. The Visitor interface depends upon the ConcreteVisitable classes thus breaking the DIP (Xiao‐Peng and Yuan‐Wei 2010). 

Sample code link :



Thursday, October 3, 2013

Spring AOP

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns in AOP literature.)

AOP concepts

Let us begin by defining some central AOP concepts and terminology. These terms are not Spring-specific... unfortunately, AOP terminology is not particularly intuitive; however, it would be even more confusing if Spring used its own terminology.
  • Aspect: a modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
  • Advice: action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. (Advice types are discussed below.) Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors around the join point.
  • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
  • Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
  • Target object: object being advised by one or more aspects. Also referred to as the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
  • AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
  • Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
Types of advice:
  • Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
  • After throwing advice: Advice to be executed if a method exits by throwing an exception.
  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

    Example :-

    Simple class
    package com.deepak.pojo;
     * @author deepak
    public class Student {
     private int roll;
     private String name;
     public int getRoll() {
      return roll;
     public void setRoll(int roll) {
      this.roll = roll;
     public String getName() {
      return name;
     public void setName(String name) { = name;
     public void printName(String name) {
      System.out.println("Name is : " +;
     public void printRoll() {
      System.out.println("Roll is : " + this.roll);
     public void throwExcetion() {
      throw new IllegalArgumentException("Checking the exception");
     public String toString() {
      return "name = " + + " roll = " + this.roll;

Around Advice
package com.deepak.advice;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

 * @author deepak
public class MethodAround implements MethodInterceptor {

 public Object invoke(MethodInvocation method) throws Throwable {
  System.out.println("Method name : " + method.getMethod().getName());
  System.out.println("Method arguments : "
    + Arrays.toString(method.getArguments()));
  System.out.println("Called before method call");
  try {
   Object result = method.proceed();
   System.out.println("Called after method call");
   return result;
  } catch (Exception e) {
   System.out.println("Called before exception handeling");
   throw e;
Main Class
package com.deepak.main;


import com.deepak.pojo.Student;

public class Main {

  * @param args
 public static void main(String[] args) {
  ClassPathXmlApplicationContext appcontext = new ClassPathXmlApplicationContext(
  Student s1 = (Student) appcontext.getBean("studentProxy");
  s1.printName("Argument to function");

Spring configuration file


Download source code :

Wednesday, September 4, 2013

Monitoring and Managing Amazon RDS Databases using MySQL Workbench

In order to connect to Amazon RDS instance to fire some queries the procedure we followed were
  • Connect to EC2 instance via SSH
  • Connect to RDS from there.
We can fire queries from the SQL prompt but the issue with it is that the view gets distorted when the data on one column is very large. Also there is no support for exporting that result.

On my local I was using MySQL workbench which had solution to above problem so I thought of using that tool to connect to RDS.

On doing some research on same I found the following link which was very helpful in configuring same.

However the link provided is for MySQL workbench 5.5 and I had version 6 locally. Posting the corresponding  screenshot for version 6 here.

Rest of the configurations remains same.

Monday, September 2, 2013

Tomcat performance tuning

A tomcat with default configuration can handle max 300req/sec
I was unaware of that until I had to tweak the tomcat to improve the performance of my webapp.
In this blog I am going to list few of the tomcat connector parameters which helped us in improving the tomcat performance.

acceptCountThe maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.
acceptorThreadCountThe number of threads to be used to accept connections. Increase this value on a multi CPU machine, although you would never really need more than 2. Also, with a lot of non keep alive connections, you might want to increase this value as well. Default value is 1.
maxConnectionsThe maximum number of connections that the server will accept and process at any given time. When this number has been reached, the server will not accept any more connections until the number of connections falls below this value. The operating system may still accept connections based on the acceptCount setting. Default value is the value of maxThreads
maxThreadsThe maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
minSpareThreadsThe minimum number of threads always kept running. If not specified, the default of 10 is used.
processorCacheThe protocol handler caches Processor objects to speed up performance. This setting dictates how many of these objects get cached. -1 means unlimited, default is 200. If not using Servlet3.0 asynchronous processing, a good default is to use the same as the maxThreads setting. If using Servlet 3.0 asynchronous processing, a good default is to use the larger of maxThreads and the maximum number of expected concurrent requests (synchronous and asynchronous).
Out of these parameters maxThreads plays a very important role. The optimal value of it varies with the response time for single request. For our project it was around 75.

Few hit and trial can easily give you a value which performs better than the default one.

After tweaking the parameters the tomcat should be tested for different load ranges to ensure that it is working as expected.

Comparing it with tomcat having default configuration gives you a very good metric to calculate the performance gain.

Sample Config in server.xml
<Connector port="8090" protocol="HTTP/1.1"
redirectPort="8443" />
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" maxConnections="500" maxThreads="75" acceptorThreadCount="2"/>

Reference :

Note : The parameters mentioned are valid for tomcat version 5, 6 and 7. Future versions can modify/remove the mentioned parameters.

Basic and Simple SpringMVC application download

Download link :

At the bottom right of the page you will see download zip option.

The code is very simple. It exposes one REST API : /hello
e.g. http://localhost:9090/mvctutorial/hello

Migration from legacy logging API like JCL or log4j to logback(slf4j)

While working with a large source code it often happens that you come across some components which rely on some legacy logging API's rather than slf4j or logback. It's very difficult if not nightmare to keep track of such components and assign appropriate logging level for those components through various configuration files.
The question now arises that is there a way to bridge those legacy logging API to logback ?
Answer is YES.

Logback provides certain jars to do so :

All the corresponding jars can be downloaded from :

IMP : The version of corresponding jars and the logback jars present in the project should be same.

Monday, August 26, 2013

Log SQL queris to table in MySQL(>5.1.12)

FIre the following in the given order in you MySQL AB

  1. Execute SET GLOBAL log_output = 'TABLE';
  2. Execute SET GLOBAL general_log = 'ON';
  3. select * from  mysql.general_log 

mysql.general_log : This table contains following columns

  • event_time
  • user_host
  • thread_id
  • server_id
  • command_type
  • argument

argument column stores the query fired in database.

If you want the output to be stored in file then you can use the following
  1. SET GLOBAL log_output = "FILE";
  2. SET GLOBAL general_log_file = "/path/to/your/logfile.log"
  3. SET GLOBAL general_log = 'ON';