Saturday, February 20, 2016

Introduction to Java Lambda expressions


Lambdas are considered one of the major changes introduced to the Java language constructs since its release. Sooner or later, Java developers will need to get accustomed to using and manipulating lambdas. To put it a simple way, Lambda expressions can be refered to as a method without a name that can be declared anywhere. We know that the essence of Java is object orientation, so normally methods can only live inside an object or an interface. Lambdas were introduced to deal with this shortcoming. They add a flavor of functional programming to one of the most traditional object oriented languages.
In this tutorial, we will go through some use cases where lambda expressions may be useful.

A quick reminder of the lambdas syntax:

Arguments declaration                         Method body
(a, b, c, ....)                             ->         {expressions;...;...;}


Case 1: Implementing an interface with one method (Functional interface)


 public interface Bank {
  double convertAmountFromEuroToDollar(double amount);
 }

     //.....
  Bank bank = (b) ->   b * 1.11;
  
  System.out.println(bank.convertAmountFromEuroToDollar(10));
Result:
 11.100000000000001

Case 2: UI events

  JButton button = new JButton();
  button.addActionListener(
    
    (e) -> {System.out.println("Action performed");
    
     });

Case 3: Streams

  List cars = Arrays.asList("Mercedes","Volvo","Volswagen","Audi","Peugeot");
  cars.stream().
  filter(c -> c.startsWith("V"))
  .forEach(c -> System.out.println(c));
Result:

Volvo
Volswagen

Case 4: Using Java provided functional interfaces


   
 //Takes two String arguments and return one Boolean result
  BiFunction<String, String, Boolean> checkAnagram = (e1, e2) -> { 
      e1.toLowerCase(); e2.toLowerCase();
      char[] e1Chars = e1.toCharArray(); char[] e2Chars = e2.toCharArray(); 
      Arrays.sort(e1Chars);
      Arrays.sort(e2Chars);
     return String.valueOf(e1Chars).equals(String.valueOf(e2Chars));
   };
 
     //Takes one String arguments and return one Boolean result 
    Function<String, Boolean> checkPalindrome = (p) -> { 
 char[] toChar = p.toCharArray();
     CharBuffer buffer = CharBuffer.allocate(toChar.length);
  for(int i = toChar.length - 1; i >= 0; i--)
        buffer.put(toChar[i]);
   
           return p.equals(String.valueOf(buffer.array())); 
  };
  

  System.out.println(checkAnagram.apply("test", "estt"));
  System.out.println(checkPalindrome.apply("rotator"));

Result:

true
true
Full code available at: https://github.com/zak905/java8features/tree/master/src/opencode/java8features/lambdas

 Interesting reads:
http://zeroturnaround.com/rebellabs/java-8-best-practices-cheat-sheet/
http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

Tuesday, February 9, 2016

Unit Testing a Rest API using Spring Test




 After you have designed your Rest API and implemented it successfully, you need to test it. Testing a Rest Api is not easy because of the application context. By default, to be able to run tests, the Spring MVC container needs to be launched as it contains all of the components that the application needs to run properly ( request mapping, exception handling, ...). However, launching the container will take a considerable amount of time slowing down tests. Usually, tests need to run quicker than the application.
To solve this issue, Spring test provides the speed of an out of container context with only the needed infrastructure of Spring MVC. All the infrastructure that we need to run our tests is bootstrapped in an out of container process. That is to say, we get a standalone web application that does not need to run inside a servlet, which allows unit and integration tests to run quicker. In this tutorial, we will go through how to use Spring Test for unit testing a Rest API.

Requirements:

Application buit previously
Eclipse, Maven
Spring dependencies: pom.xml here.


We have the following end points that we want to unit test:

POST: /person
GET: /person/{id}
GET: /person/{id}/profile
GET: /person/{id}/account


Our test class looks like:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:beans.xml"})
public class PersonControllerUnitTest {

  @Autowired
   private volatile WebApplicationContext webApplicationContext;

    @Before
    public void before() {
 this.mockMvc = webAppContextSetup(this.webApplicationContext).build();    
      }
     
     @Test
     public void createPersonTest() throws Exception{
  this.mockMvc.perform(post("/person"))
   .andExpect(status().isCreated());
      }
     
     @Test
    public void getPerson() throws Exception{
 this.mockMvc.perform(get("/person/{id}", 1))
 .andExpect(status().isOk())
 .andExpect(content().contentType("application/json;charset=UTF-8"))
        .andExpect(jsonPath("$.firstname").value("John"));
      }
  
     @Test
     public void getProfile() throws  Exception{
        this.mockMvc.perform(get("/person/{id}/profile", 1))
 .andExpect(status().isOk())
 .andExpect(content().contentType("application/json;charset=UTF-8"))
 .andExpect(jsonPath("$.description").value("Profile description"));
      }
  
     @Test
    public void getAccount() throws Exception{
     this.mockMvc.perform(get("/person/{id}/account", 1))
     .andExpect(status().isOk())
     .andExpect(content().contentType("application/json;charset=UTF-8"))
     .andExpect(jsonPath("$.username").value("johnk"));
     }
}


Before running tests, we have configured the application context and initialized a MockMvc object that mimics a Spring MVC infrastructure. To test a Rest API operation, we made assertions on the return HTTP status, the content type, and also on the data returned.




Full example at: https://github.com/zak905/rest-spring-example