Monthly Archives: November 2015

How to Read Post Request data twice in Spring

Hi Readers,

i got requirement to read to HTTP Post Request data twice in spring MVC interceptor but the problem is when am trying read it,am getting this exception in spring controller “java.lang.IllegalStateException: getReader() has already been called for this request

We are getting this exception because request.getInputStream() called twice, once in MVC interceptor and once spring controller.To fix this we need write wrapper on HTTP request but it will not solve our problem because after wrapping request there is no way to hand over same wrapper request to spring controller,to do that we need to write traditional filter.

follow the below steps

Step 1)Write simple wrapper on HTTP request so that it can be used in filter we are going write in Step 2.

package com.myjavarecipes.web;
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
 private String _body;
public MultiReadHttpServletRequest(HttpServletRequest request) throws IOException {
 _body = "";
 BufferedReader bufferedReader = request.getReader();
 String line;
 while ((line = bufferedReader.readLine()) != null){
 _body += line;

public ServletInputStream getInputStream() throws       IOException {
 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
 return new ServletInputStream() {
 public int read() throws IOException {

public BufferedReader getReader() throws IOException {
 return new BufferedReader(new InputStreamReader(this.getInputStream()));

2)Write Traditional J2EE filer,in Filter doFilter method we wrap HTTP request with custom wrapper MultiReadHttpServletRequest and pass it back to filter chain,so that now onward when ever request.getInputStream() get called it will call the overrided method in MultiReadHttpServletRequest class and it returns same ServletInputStream which is already read by wrapper.

 package com.myjavarecipes.web;
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.util.*;

 public class RequestWrapperFilter implements Filter {
 public void init(FilterConfig config)
      throws ServletException{
 // nothing goes here
public void doFilter(ServletRequest request,ServletResponse           response, FilterChain chain)
     throws, ServletException {
MultiReadHttpServletRequest requestWrapper=new      MultiReadHttpServletRequest(request);
 // Pass request back down the filter chain

 public void destroy( ){
 /* Called before the Filter instance is removed
 from service by the web container*/

3)Configure filter in web.xml so that container will call our filter for each HTTP request.


4)Now onward HTTP request object can be read more than once it means we can read it in Spring MVC interceptor and as well as in Spring controller.

Things to do after landing in U.S.A first time

These are  things you needed to after landing in U.S.A

1)Buy prepaid sim so that you can make phones call,to get prepaid sim you really don’t need any thing like id proof or any thing like in India.

check out this carrier

2)Install Google Maps for navigation, set the address and go.
Here no one helps in navigation because this country so big to remember any thing.

3)Install Uber application in mobile to book cab,if you lost just book cab from mobile using Uber app.I personally felt very comfortable with Uber app.

4)Figure out public transport in the place you are going to live just google it.Cabs are expensive public transport is cheap but you should know the routes.

5)Apply for SSN this is the fist thing to do if you are here on H1B/L1 Visa.

documents needed to apply SSN

6)Apply for driving license,you can drive here with India license for couple months but better to apply Learners permit as soon you landed here so that slowly you can get valid driving license.

7)Find nearest Indian grocery store just google it.

8)More importantly Google it for anything before you start doing.

finally Grab beer:)

What are things need to carry to USA fist time check below post:

Things must carry for first time to U.S.A

Hi Reader,

when we travel first time to U.S.A,we like to know what are the best things to carry

First of all i feel you really don’t need to carry any thing specially since you can buy it here cheaply after you get used to places here.Any how you need some of the things needed initially.

1) 2 Good big Travel suitcases that i can fit 23 kg’s each so that you can pack check-in luggage.

2) 1 small suit case which you can carry along with you in flight to keep all your important things like laptop,documents,jewels,clothes.

3)1 Bag pack with lap tap rack,this bag going to be useful when you go office or college to carry books/Laptop.

3) Get some 5 pairs formal clothes,two pair of formal shoes(black/brown),1 Leather Belt and one blazer so that you can wear for any interview otherwise really not needed.Same way carry 2 or 3 pair of casual wear,2 pair of sleep wear and one pair of casual shoes(do not carry many shoes,shoes are really cheap).

4) For winter get one pair of thermal wear and one jacket not more than that because you will get it here cheaper than India with better quality.

5) Coming to inner wear get 7 pair inner wear(why seven pairs because we don’t to need wash every day,we can do washing in washer and dryer only once in week).
6) Don’t get many casual wear,T-Shirts,socks because those are really cheap here.

7)Get spices so that you can start cooking initially.

8)Get some snacks,pickles home made as much as you can,it will be handy.

9)Get some bowls like 1 for rice,1 for curry,1 for tea and tea filter.1 pressure cooker for dal,1 plate,2 small bowls,2 glasses,2 spoons,2 forks,rest you can buy in Indian store.

10)One power Adapter(India to USA) so that you can use charge any Indian gadgets.

11)2 combs,1 soap,1 small shampoo,1 small winter cream,1 Gillette with blades if you really shaves otherwise don’t you can buy good trimmer for 20 dollars,seriously you don’t need to bring all these because you will get all cheaply in wall mart store but just to start day.

12)Get some medicines for cold,fever,body pains and motion control tablets.

13)Bring some shirt buttons,jeans button,threads and stitching pin so that you can stitch if you lost any clothes buttons.Here you hardly find tailors.

14)Bring Smart phone because you can buy prepaid SIM card and start using it.

15)Bring your Indian driving license so that you can rent car drive initially.

That is it.Rest you can buy here very easily.

Thing you must do after landing in USA check out below post:

Spring Profiling/Audit using MVC interceptors

Hi Readers,

recently i got requirement from customer that they want to audit Spring web application services. In simple terms they want to know which of services used more and less. Requirement is simple,just by writing one Spring MVC web interceptor we can scan all the Http requests and write audit logic but here is the actual problem that they want us to audit only few of the services not all other services,it means i have to figure out the methods which need be audited in interceptor.

To achieve i did following  steps

  1. Define custom annotation.
  2. Use this annotation at spring MVC controller method.
  3. Write own interceptor,access called method and class level annotations in it and if expected annotation present then write audit logic

STEP 1:  Define @ApplicationAudit custom annotation.

package com.myjavarecipes.common.controller

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD) //can use in method only.
public @interface AppicationAudit{
	String value();

STEP 2:Add this custom annotation in Spring controller method addAccount().

package com.myjavarecipes.common.controller

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

public class HelloWorldController{

@RequestMapping(value="/addAccount",method = RequestMethod.POST)
public ModelAndView addAccount(){
  ModelAndView model = new ModelAndView("AddAccount");
   return model;

public ModelAndView getAccount(){

 ModelAndView model=new ModelAndView("getAccount");

 //implementation goes here

 return model;

 STEP 3: Add Spring MVC interceptor entry in spring context xml.
  <bean class="com.myjavarecipes.interceptor.AuditInterceptor" />
STEP 4:  write own AuditInterceptor spring web mvc interceptor,in it’s methods preHandle,postHandle,afterCompletion identify called method controller class and method has expected annotation if it present write audit logic.
package com.myjavarecipes.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import com.myjavarecipes.common.controller.ApplicationAudit; 

public class AuditInterceptor implements HandlerInterceptor { 

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
HandlerMethod hm=(HandlerMethod)handler; 
Method method=hm.getMethod(); if(method.getDeclaringClass().isAnnotationPresent(Controller.class)){
return true; 

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod hm=(HandlerMethod)handler;
 Method method=hm.getMethod();

{ System.out.println(method.getAnnotation(ApplicationAudit.class).value()); request.setAttribute("ENDTIME",System.currentTimemillis());  }

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 
System.out.println("After completion handle"); HandlerMethod hm=(HandlerMethod)handler; 
Method method=hm.getMethod(); if(method.isAnnotationPresent(ApplicationAudit.class))
{ System.out.println(method.getAnnotation(ApplicationAudit.class).value()); 
System.out.println("Total Took:"+((Long)request.getAttribute("ENDTIME")-(Long)request.getAttribute("STARTTIME")));  

Java Custom Annotation Example

Hi Readers,

in this post i will explain how custom annotation works.

  1. Annotation works like metadata.
  2. @ means compiler treats it as annotation.
  3. @interface means compiler treats as custom annotation.
  4. @Retention:Retention is used specify annotation if it should be available at runtime.
  5. @Target : We can specify which Java elements your custom annotation can be used to annotate.  In the below example MyFirstAnnotation targeted to use at method level.
package com.myjavarecipes.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD) //can use in method only.
public @interface MyFirstAnnotation {
String value();


Example to show how to use it.

package com.myjavarecipes.examples;

import java.lang.reflect.Method;

import com.myjavarecipes.annotations.MyFirstAnnotation;

public class AnnotationExample{

public void doBatting(){
System.out.println("Batting performed");
public void doBowling(){
System.out.println("Bowling performed");
public static void main(String[] args) throws Exception {
AnnotationExample anExample=new AnnotationExample();
Method[] methodsArray=anExample.getClass().getMethods();
for(int i=0;i<methodsArray.length;i++){
Method method=methodsArray[i];
MyFirstAnnotation myAnnObject=(method.getAnnotation(MyFirstAnnotation.class));
System.out.println("My annotation value:"+myAnnObject.value());
method.invoke(anExample, null);

My annotation value:DOACTION
Batting performed

How to get H1B visa

  1. Find employer who can apply for H1B Visa for every march.
  2. Employer will have attorney  to prepare H1B visa petitions for their employees.
  3. Attorney file visa petition at USCIS in every march month.
  4. USCIS will perform computerized lottery in April to select limited cap visa.
  5. If your petition selected in lottery then USCIS will do verification on your via petitions.
  6. If your petition got approved then your employer will receive H1B approval letter.
  7. Your employer share all necessary documents with H1B approval letter.
  8. Attend Visa interview at nearest USA embassy.
  9. If everything goes well visa officer will keep your passport to stamp it.
  10. You will receive your passport with Visa in 5 working days.

Watch this video for better understanding