Wednesday, February 26, 2014

Spring JARX-RS: How to validate PayLoad [ PayLoadValidator ]

Hi all,
- Today, i have a new post . How to validate an object with annotations @NotNull, @Valid, any validations annotations.
- This post will help you understand using spring jersey + validation annotations.

Create Class PayLoadValidator:

package com.sample.common.util;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sample.common.domain.User;
/**
 *
 * validate object has annotation @Valid@NotNull

 *
 * @author HieuNT29
 *
 */

@Component
public class PayloadValidator {
    private javax.validation.Validator validator = null;
    private static final Logger LOGGER = LoggerFactory
            .getLogger(PayloadValidator.class);

    PayloadValidator() {
    };

    @PostConstruct
    public void setup() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }
    @SuppressWarnings("unchecked")

    public Error validate(List< ? extends User> requestEntries, Error errorResponse) {
        Iterator vIterator = (Iterator) requestEntries.iterator();
        int failureCount = 0;
        while (vIterator.hasNext()) {
            User userReqEntry = vIterator.next();
            Set errorSet = validator.validate(userReqEntry);
            if (errorSet.size() > 0) {
                StringBuffer errorMessage = new StringBuffer();
                for (ConstraintViolation error : errorSet) {
                    System.out.println(error);
                }  
                LOGGER.debug("Error message {}", errorMessage.toString());
                vIterator.remove();
                errorResponse.setFailureCount(++failureCount);
            }
        }
        return errorResponse;
    }
}


Source Code

Thursday, December 19, 2013

Spring MVC: Apply Mockito Framework at Controller.

Hi !!! Today, i have a new post. How to apply Mockito Framework for Spring MVC at Controller layer.

What is Mockito?
Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors: Read more https://code.google.com/p/mockito/

I) Add Mockito Maven Dependency:         
II) Controller Layer:
package com.fpt.controller;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.fpt.domain.Person;
import com.fpt.service.PersonService;

@Controller
public class RestController {
    protected static Logger logger = Logger.getLogger(RestController.class);

    @Autowired
    private PersonService personService;

    // http://localhost:8080/spring-mvc-mokito/mvc/all/persons

    @RequestMapping(value = "/all/persons", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")

    public String getAllPerson(ModelMap model) {
        logger.debug("Provider has received request to get all persons");
        List result = personService.getAllPerson();
        model.addAttribute("model_get_all_person", result);
        return "get_all_person";
    }
}

III) Unit test for Controller layer applying Mockito:
package com.fpt.controller.test;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fpt.controller.RestController;
import com.fpt.domain.Person;
import com.fpt.service.PersonService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class RestControllerAnnoTest {

    @Configuration
    static class ContextConfiguration {

        @Bean
        public PersonService personService() {
            return Mockito.mock(PersonService.class);
        }

        @Bean
        public RestController loginController() {
            return new RestController();
        }
    }

    @Autowired
    private RestController restController;

    @Autowired
    private PersonService personService;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(this.restController).build();
    }

    @After
    public void teardown() {
        mockMvc = null;
    }

    @Test
    public void testGetAllPerson() throws Exception {
        Person p1 = new Person();
        p1.setFirstName("firstName01");
        p1.setLastName("lastName01");
        p1.setId(123l);
        p1.setMoney(321d);

        Person p2 = new Person();
        p2.setFirstName("firstName02");
        p2.setLastName("lastName02");
        p2.setId(123l);
        p2.setMoney(321d);

        List expectedPeople = new ArrayList();
        expectedPeople.add(p1);
        expectedPeople.add(p2);

        when(personService.getAllPerson()).thenReturn(expectedPeople);

        this.mockMvc
                .perform(get("/all/persons"))
                .andExpect(status().isOk())
                .andExpect(
                        model().attribute("model_get_all_person",
                                expectedPeople))
                .andExpect(view().name("get_all_person"));
        ;
    }
}

IV) Create a new file ApplicationContent_Test.xml at src/test/resources:
 
V) Unit test for Controller layer without Mockito:
package com.fpt.controller.test;

import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.ModelMap;
import com.fpt.controller.RestController;
import com.fpt.domain.Person;
import com.fpt.service.PersonService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_TEST.xml" })
public class RestControllerXmlTest {

    @Autowired
    private RestController restController;

    @Autowired
    private PersonService personService;

    @Test
    public void testGetAllPerson() throws Exception {
        Person p1 = new Person();
        p1.setFirstName("firstName01");
        p1.setLastName("lastName01");
        p1.setId(123l);
        p1.setMoney(321d);

        Person p2 = new Person();
        p2.setFirstName("firstName02");
        p2.setLastName("lastName02");
        p2.setId(123l);
        p2.setMoney(321d);

        List expectedPeople = personService.getAllPerson();
        expectedPeople.add(p1);
        expectedPeople.add(p2);

        ModelMap modelMap = new ModelMap();
        String viewName = restController.getAllPerson(modelMap);
        assertEquals("get_all_person", viewName);

        @SuppressWarnings("unchecked")
        List listPersons = (List) modelMap             .get("model_get_all_person");


        assertEquals("There are 2 objects",2, listPersons.size());     
        assertEquals("firstName01", listPersons.get(0).getFirstName());
        assertEquals(Long.valueOf(123), listPersons.get(0).getId());
        assertEquals("lastName01", listPersons.get(0).getLastName());
        assertEquals(Double.valueOf(321.0), listPersons.get(0).getMoney());
    }
}

Source Code

Thursday, November 21, 2013

Spring AOP + AspectJ: Before and After

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.
In Spring AOP, 4 type of advices are supported :
  • Before advice – Run before the method execution
  • After returning advice – Run after the method returns a result
  • After throwing advice – Run after the method throws an exception
  • Around advice – Run around the method execution, combine all three advices above.

Spring AOP Advices

package com.fpt.aop.pointcut;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SearchEngineeAfterPointcut{
    private static final org.slf4j.Logger LOGGER = LoggerFactory
            .getLogger(SearchEngineeAfterPointcut.class);


    /**
     * Define pointcut inline for any of the advices
     * 

     * http://www.tutorialspoint.com/spring/aspectj_based_aop_appoach.htm
     * 

     * @param joinPoint
     * @throws Throwable
     */

    @After("within(com.fpt.controller..*) && execution(* *(..,@org.springframework.web.bind.annotation.PathVariable (*),..))")
    public void checkAfterPointCut(JoinPoint joinPoint) throws Throwable {
        // get method arguments

        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            LOGGER.debug("AFTER: checkAfterPointCut:{}",i);
        }
    }
}


package com.fpt.aop.pointcut;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SearchEngineeBeforePointcut{

    private static final org.slf4j.Logger LOGGER = LoggerFactory
            .getLogger(SearchEngineeBeforePointcut.class);

    /**
     * Define pointcut inline for any of the advices
     * 

     * http://www.tutorialspoint.com/spring/aspectj_based_aop_appoach.htm
     * 

     * @param joinPoint
     * @throws Throwable
     */


    @Before("within(com.fpt.controller..*) && execution(* *(..,@org.springframework.web.bind.annotation.PathVariable (*),..))")
    public void checkBeforePointCut(JoinPoint joinPoint) throws Throwable {    

        // get method arguments

        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            LOGGER.debug("BEFORE: checkBeforePointCut:{}",i);
        }
    }
}


Spring MVC

package com.fpt.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fpt.domain.Person;
import com.fpt.domain.PersonList;
import com.fpt.service.PersonService;

@Controller
public class RestController {
    protected static Logger logger = Logger.getLogger(RestController.class);

    @Autowired
    private PersonService personService;

    // http://localhost:8080/spring-aop-search/mvc/persons

    @RequestMapping(value = "/persons", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
    public @ResponseBody
    PersonList getPerson() {
        logger.debug("Provider has received request to get all persons");
        PersonList result = new PersonList();
        result.setData(personService.getAllPerson());
        return result;
    }

    // http://localhost:8080/spring-aop-search/mvc/person/1

    @RequestMapping(value = "/person/{id}", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
    public @ResponseBody
    Person getPerson(@PathVariable("id") Long id) {
        logger.debug("Provider has received request to get person with id: "
                + id);
        return personService.getPerson(id);
    }

    // http://localhost:8080/spring-aop-search/mvc/person

    @RequestMapping(value = "/person", method = RequestMethod.POST, headers = "Accept=application/xml, application/jsonp")
    public @ResponseBody
    Person addPerson(@RequestBody Person person) {
        logger.debug("Provider has received request to add new person");
        if (person.getFirstName() == null)
            throw new NullPointerException("First Name can not be null");
        return personService.addPerson(person);
    }
}


Source Code

Friday, October 25, 2013

Coupling and Cohesion

What is Coupling ?
- Coupling indicates the degree of dependence among components. Higher coupling tends to indicate poor design of classes, since it makes modifying parts of the system difficult, as modifying a component affects all the components to which the component is connected.
- Class A has behaviourA and propertiesA, and Class B has behaviourB and propertiesB. Class A uses the properties and behaviours in Class B, and Class B also uses the properties and behaviours in Class A.
- We call High Coupling (Tighly Coupling)

What is the solution ?
- Lower Coupling is better .

Problem: Sample code High Coupling
package com.scjp6.oop.coupling;
public class CalculateTaxes {
    float rate;
    float doIndia() {
    TaxRatesInIndia str = new TaxRatesInIndia();
    return rate = str.salesRate; // ouch again
    }
}

package com.scjp6.oop.coupling;

public class TaxRatesInIndia {
    public float salesRate; // should be private

    public float adjustedSalesRate; // should be private
    public float getSalesTaxRates() {
        adjustedSalesRate = new CalculateTaxes().doIndia();
        return adjustedSalesRate;
    }
}
package com.scjp6.oop.coupling;


public class LowCoupling {


    public static void main(String[] args) {
    // TODO Auto-generated method stub

    Calculate calculate = new CalculateTaxeRateIndiaImpl();
    System.out.println(calculate.doIndia());
    System.out.println(calculate.getSalesTaxRates());
    }
}
Solution: Sample code Low/ Tigh Coupling

package com.scjp6.oop.coupling;

public interface Calculate {
    float doIndia();
    float getSalesTaxRates();   
}


package com.scjp6.oop.coupling;
public class CalculateTaxeRateIndiaImpl implements Calculate {
    @Override
    public float doIndia() {
       return 0;
    }


    @Override
    public float getSalesTaxRates() {
      return 0;
    }
}


package com.scjp6.oop.coupling;

public class LowCoupling {

    public static void main(String[] args) {
     Calculate calculate = new CalculateTaxeRateIndiaImpl();
     System.out.println(calculate.doIndia());
     System.out.println(calculate.getSalesTaxRates());
    }
}


What is Cohesion
- Cohesion is the extent to which methods in a class are related. It means, a class has many methods are related.
- We can call Low Cohesion

What is the solution ?
- High Cohesion is better .

Problem: Sample code Low Cohesion
package com.scjp6.oop.cohesion;

public class ReportGrade {
    Student getStudent() {
      return new Student();
    }

    Subject getSubject() {
      return new Subject();
    } 

    Grade getGrade(){
      return new Grade();
    }
}

package com.scjp6.oop.cohesion;

public class RunLowerCohesion {

    public static void main(String[] args) {
      ReportGrade reportGrade = new ReportGrade();
      reportGrade.getGrade();
      reportGrade.getStudent();
      reportGrade.getSubject();
    }
}

Solution: Sample code High Cohesion

public class Grade {
    String studentID;
    String subjectID;
    float grade01;
    float grade02;
}

package com.scjp6.oop.cohesion;
public class Student {
    String studentID;
    String name;
    int age;
}


package com.scjp6.oop.cohesion;
public class Subject {
    String subjectID;
    String subjectName;
}


package com.scjp6.oop.cohesion;
public class ReportGradeHighCohesion {   
     Grade getGrade(){
       return new Grade();
    }
}


package com.scjp6.oop.cohesion;
public class ReportStudentHighCohesion {
    Student getStudent() {
      return new Student();
    }   
}


package com.scjp6.oop.cohesion;
public class ReportSubjectHighCohesion {
    Subject getSubject() {
      return new Subject();
    }
}


package com.scjp6.oop.cohesion;
public class RunHighCohesion {


    public static void main(String[] args) {
    ReportGradeHighCohesion reportGradeHighCohesion = new ReportGradeHighCohesion();
    reportGradeHighCohesion.getGrade();

    ReportStudentHighCohesion reportStudentHighCohesion = new ReportStudentHighCohesion();
    reportStudentHighCohesion.getStudent();

    ReportSubjectHighCohesion reportSubjectHighCohesion = new ReportSubjectHighCohesion();
    reportSubjectHighCohesion.getSubject();
    }
}




Wednesday, October 23, 2013

MDC Logger

What is MDC?
- MDC stands for Mapped Diagnostic Context.
- It is a map which stores the context data of the particular thread where the context is running
Where do we use it ?
- For Jersey: ContainerRequestFilter, ContainerResponseFilter
- For Spring MVC : HttpServletRequest, HttpServletResponse
Why do we use it ?
- It helps you to distinguish inter-leaving logs from multiple sources.
- When we have multiple user-requests coming in for a given servlet, each request of an user is serviced using a thread. This leaves multiple users logging to the same log file and the log statements get inter-mixed.
- Now, to filter out logs of a particular user, we need to append the user-id to the log statements so that we can search them in the log file easily.
- An obvious way of logging, is to append the user-id in the log statements i.e. log.info(userId+” logged something “);
- A non-invasive way of logging is to use MDC.
- With MDC, you put the user-id in a context-map which is attached to the thread (of each user request) by the logger.

public class SimpleMDC {
    static public void main(String[] args) throws Exception {
    // You can put values in the MDC at any time. Before anything else

    // we put the USER-ID

    MDC.put("USER-ID""DirecTV");
    Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
    // We now put the IP-ADDRESS
    MDC.put("IP-ADDRESS""10.88.68.11");
  
    logger.info("Start Logging");
    logger.debug("Mapped Diagnostic Context");
    logger.error("One of the design goals of logback is to audit and debug complex distributed applications");
    logger.error("Most real-world distributed systems need to deal with multiple clients simultaneously. ");
    logger.error("In a typical multithreaded implementation of such a system");
    MDC.put("USER-ID""FPT");
    MDC.put("IP-ADDRESS""100.888.688.111");
  
    logger.info("Start Logging");
    logger.debug("Mapped Diagnostic Context");
    logger.error("One of the design goals of logback is to audit and debug complex distributed applications");
    logger.error("Most real-world distributed systems need to deal with multiple clients simultaneously. ");
    logger.error("In a typical multithreaded implementation of such a system");
    }
}

Source Code

Saturday, August 3, 2013

Rest Spring 3.1: Using RestTemplate For Get/Add/Update/Delete

Hi All,

I posted Sample with using RestTemplate, it is quite simple Example.
I have just implemented for Get, but Add,Update, Delete not yet.
Dowload Source code

-------------------------------------------------

package com.fpt.family.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.fpt.family.dto.Father;
import com.jaxb.family.Family;

@Controller
public class FamilyController {

    private static RestTemplate restTemplate = new RestTemplate();

    private static final String serviceURL1 = "http://localhost:8080/springrestfuljaxb/ws/fpt/family/get";
    private static final String serviceURL2 = "http://localhost:8080/springrestfuljaxb/ws/fpt/family/get/";

    /**
     * Get All Family. You can implement for Mother, Children
     * 
     * @return
     */


    // http://localhost:8080/springrestful-client/getall
    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    public @ResponseBody
    com.fpt.family.dto.Family getAll() {

    Family result = null;
    result = restTemplate.getForObject(serviceURL1, Family.class);

    Father father = new Father();
    father.setFatherName(result.getFather().getFatherName());
    father.setCompany(result.getFather().getCompany());

    com.fpt.family.dto.Family familyDto = new com.fpt.family.dto.Family();
    familyDto.setFather(father);

    return familyDto;
    }

    /**
     * 
     * Get family with flag.
     * 
     * @param flag
     * @return
     */

    // http://localhost:8080/springrestful-client/get/false
    // http://localhost:8080/springrestful-client/get/true
    @RequestMapping(value = "/get/{flag}", method = RequestMethod.GET)
    public @ResponseBody
    com.fpt.family.dto.Family getFamily(@PathVariable("flag") Boolean flag) {

    Family result = null;
    result = restTemplate.getForObject(serviceURL2 + flag, Family.class);
    if (flag) {
        Father father = new Father();
        father.setFatherName(result.getFather().getFatherName());
        father.setCompany(result.getFather().getCompany());

        com.fpt.family.dto.Family familyDto = new com.fpt.family.dto.Family();
        familyDto.setFather(father);
        return familyDto;
    } else {
        // Implelement
    }

    return null;
    }

}
Source Code

Friday, July 26, 2013

Using SOAP UI vs RestClient

I-Using RestClient tool:
II-Using SOAP UI tool:
- I have just uploaded TestCases for using SOAP UI. And, i have added GET/POST testCases,but not DELETE/PUT method.
- Dowload SOAP UI tool
- File/Import Project
- Hopefully, you enjoy.
SOAP UI Test Cases