Thursday, 31 July 2014

JAVA 8 - PART1

I was just started looking Java8 and was impressed with the features it has.

Bought the book 'Java 8 IN ACTION' , which is very good to start with.

I would share some important points from this book and add the more information as and when I get time to read this.

Let's Start

LAMBDA EXPRESSIONS
It’s an Anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown

Good and precise way to represent Behaviour Parameterisation

BEFORE:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};
AFTER (WITH LAMBDA EXPRESSIONS):
Comparator<Apple>  byWeight  = 
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

With Type inference - No explicit type on the parameters a1,a2
Comparator<Apple>  byWeight  = 
(a1, a2) -> a1.getWeight().compareTo(a2.getWeight());

Syntax:
(parameters) -> expression

or (note the curly braces for statements)

(parameters) -> { statements; }



Has to be used in conjunction with Functional Interfaces.
To demonstrate, for ex- we have the below process method which accepts Runnable Functional Interface
   public void process(Runnable r) {
        r.run();
    }

Various ways we can call using Lambda expressions... Old Style
  Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Using Anonymous class");
            }
        };
        process(r1);
        Runnable r2 = () -> System.out.println("Using Lambda Expressions");
        process(r2);

        process(() -> System.out.println("With Lambda Expression Passed Directly"));

a functional interface is an interface that specifies exactly one abstract method, which are annotated with @FunctionalInterface
Ex:- Comparator, Runnable, Callable, Predicate, Consumer, Function

The signature of the abstract method of the functional interface essentially describes the
signature of the lambda expression. We call this abstract method a function descriptor.

Ex:- Runnable – Functional Interface
      run()  - Function Descriptor




Listing 1 - Filter method which takes the List and a Predicate, which the filters the list based on the type of Predicate it has passed.
 public static <T> List<T> filter(List<T> list, Predicate<T> predicate) {  
     List<T> result = new ArrayList<>();  
     for (T e : list) {  
       if(predicate.test(e)) {  
         result.add(e);  
       }  
     }  
     return result;  
   }  
Here's some examples to call the filter:
Filter by Apple color
  List blueapples = filter(getAppleInventory(), (Apple apple) -> "blue".equalsIgnoreCase(apple.getColor()));

Filter by Even numbers:
  List evenNums = filter(getNumbers(), (Integer i) -> i % 2 == 0);


Predicate nonEmptyStringPredicate = (String s) -> !s.isEmpty();
List nonEmpt = filter(listOfStrings, nonEmptyStringPredicate);

Using Consumer functional Interface
public interface Consumer<T>{  
   public void accept(T t);  
 } 
You might use this interface when you need to access an object of type T and perform some operations on it.
public static <T> void forEach(List<T> list, Consumer<T> consumer) {  
     for (T i : list)  
       consumer.accept(i);  
   }
we can call forEach using Lambda expressions... - The below will compute the sum of the integerList
   private static int sum = 0;
   forEach(integerList, (Integer i) -> {       
            sum = sum + i;
            System.out.println("Sum :: " + sum);
         });
Using Function functional Interface
public interface Function<T, R>{  
   public R apply(T t);  
 } 
You might use this interface when you need to define a lambda that can extract information from the input object (for example, extracting the weight of an apple) or transform the input (for example, a string to its length).
   public static <T,R> List<R> map(List<T> list, Function<T,R> function) {  
     List<R> resultType = new ArrayList<>();  
     for (T s : list)  
       resultType.add(function.apply(s));  
     return resultType;  
   }  
we can call map() using Lambda expressions to transform the output from String to Integer...
 List<Integer> integerList = map(Arrays.asList("convert", "String", "to", "respective", "Integer", "length"), (String s) -> s.length());


Method References
 Method references let you reuse existing method definitions and pass them just like lambdas.

BEFORE:
appleList.sort((Apple a1, Apple a2)
-> a1.getWeight().compareTo(a2.getWeight()));

AFTER (USING A METHOD REFERENCE AND JAVA.UTIL.COMPARATORS.COMPARING):
appleList.sort(comparing(Apple::getWeight));

For example, Apple::getWeight is a method reference to getWeight() defined in the Apple
class. It can be seen as a shorthand for the lambda expression (Apple a) ->
a.getWeight().

RECIPE FOR CONSTRUCTING METHOD REFERENCES
There are three main kinds of method references.
1. A method reference to a static method (for example, the method parseInt of Integer,
written Integer::parseInt)
2. A method reference to an instance method of an arbitrary type (for example, the
method length of a String, written String::length)
3. A method reference to an instance method of a specific object (for example, suppose
you have an object expensiveTransaction from class Transaction with an instance
method getValue(), you can write expensiveTransaction::getValue)

Composing Comparators

Reverse order - to sort in decreasing weight
appleList.sort(comparing(Apple :: getWeight).reverse());

Chaining Comparators - multiple Comparators to further refine the comparisions
appleList.sort(comparing(Apple :: getWeight)
                      .reverse()
                      .thenComparing(Apple :: getCountry));


Composing Functions
The Function interfaces comes with two default methods: andThen and compose that both
return an instance of Function.

The method andThen returns a function that applies a given function first to an input, and
then applies another function to the result of that application.
Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> x * 2;
Function<Integer, Integer> h = f.andThen(g); 
int result = h.apply(1);  // 4

The method compose will first apply the function given as argument to compose and then apply the function to the result. It works opposite to andThen
Function<Integer, Integer> h = f.compose(g); 
int result = h.apply(1); // 3


In the next part, I will cover another interesting feature 'Processing Data with Streams'



Wednesday, 30 July 2014

EhCache

Here's a simple example to demonstrate the usage of EhCache

ehcache.xml
 
 <?xml version="1.0" encoding="UTF-8"?>
 <ehcache>
  <defaultCache maxElementsInMemory="10000" eternal="false"
  timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
  diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
  diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
  memoryStoreEvictionPolicy="LRU" />
  <cache name="newsCache" maxElementsInMemory="1"
  maxElementsOnDisk="1" eternal="false" overflowToDisk="true"
  diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600"
  memoryStoreEvictionPolicy="LRU" />
 </ehcache>
TestEhCache.java
 import com.newslive.actions.cache.EChache.EHCacheManger;  
 import net.sf.ehcache.Cache;  
 import net.sf.ehcache.CacheManager;  
 import net.sf.ehcache.Element;  
 import java.net.URL;  
 import java.util.Iterator;  
 import java.util.List;  
 /**  
  * Created by mami01 on 11/03/14.  
  */  
 public class TestEhCache {  
   public static void main(String[] args) {  
     CacheManager manager = new CacheManager("ehcache.xml");  
     Cache newsCache = manager.getCache("newsCache");  
     newsCache.put(new Element("2","Hello"));  
     newsCache.put(new Element("3", "Bye"));  
     displayElementInCache(newsCache);  
     getElementFromCache(newsCache, "3");  
     displayElementInCache(newsCache);  
     getElementFromCache(newsCache, "4");  
     displayElementInCache(newsCache);  
     getElementFromCache(newsCache, "3");  
     getElementFromCache(newsCache, "4");  
     getElementFromCache(newsCache, "3");  
   }  
   private static void displayElementInCache(Cache newsCache) {  
     System.out.println("Elements in the Cache");  
     List<String> list = newsCache.getKeys();  
     Iterator<String> itr = list.iterator();  
     while (itr.hasNext()) {  
       String key = itr.next();  
       Element ele = newsCache.get(key);  
       System.out.println(ele.getObjectKey() + " " + ele.getObjectValue());  
     }  
   }  
   private static void getElementFromCache(Cache newsCache, String key) {  
     Element element = newsCache.get(key);  
     if (null != element) { // Cache Hit  
       System.out.println("Cache Hit - " + element.getObjectValue());  
     } else { // Cache Miss  
       // Retreive from DB and add this to cache  
       System.out.println("Cache Miss - Fetching from DB ...");  
       newsCache.put(new Element(key,"default"));  
     }  
   }  
 }  

Spring Notes


Spring uses Factory Pattern - as the creation of objects is done through Bean Factory

Setter Injection - using property tag
Constructor Injection - using constructor-arg -- we use type and index to solve ambiguity

Inner Beans - A bean defined within another bean for a property
Aliases - alternate bean name - can be specified using <alias> tag and also using the name attribute of <bean>
idref - validating to ensure the bean referenced using only the id attribute

we can use autowire = "byName/byType/constructor"

Bean Scopes
1. Singleton - default, can have only instance at any point of time for a given spring container
2. Prototype - each call will a separate bean
The below are used in web-context
3. request - each request will have a new bean
4. session - the bean will be reused within the session
5. global session - used in the context of portlets


ApplicationContextAware - need to override setApplicationContext()
BeanNameAware - need to override setBeanName()

Bean Definition Inheritance
--> One bean can use re-use the other bean's properties - we have to use 'parent' attribute

-----------------------------------------------------------------
Life Cycle Methods
------------------------------------------------------------------
--> use ctx.registerShutdownHook() to close/destroy all the beans tht hv been configured
InitializingBean - need to implement afterPropertiesSet() - will execute once bean has finished initialisation
DisposableBean - need to implement destroy() - will execute before destroying the bean
-----------------------Alternative --------------------------
write custom methods initCustom() and destroyCustom()
In the spring config, declare in the bean definition as follows:
init-method="initCustom"
destroy-method ="destroyCustom"
------------------Alternative - we can define globally for all beans ----------------
In the spring config, declare in the root <beans> tag
default-init-method="initCustom"
default-destroy-method ="destroyCustom"

BeanPostProcessor
-> Executes after every bean is initialised
--> Need to implement the below callback methods:
 postProcessBeforeInitialization(Object bean, String nameOfTheBean)
 postProcessAfterInitialization(Object bean, String nameOfTheBean)
--> Need to declare the bean which implements BeanPostProcessor in the config file

BeanFactoryPostProcessor
--> Executes when the beanFactory is initialized, then only the singleton's for the beans are initialized
--> Need to implement the postProcessBeanFactory(ConfigurableListBeanFactory beanFactory)
-->Ex:- provided by spring out-of-the box PropertyPlaceHolderConfigurer
   <bean class="org.springframework.beans.factory.config.PropertyPlaceHolderConfigurer >
        <property name="locations" value="xyz.properties" />
   </bean>




Tuesday, 29 July 2014

MICROSERVICES

I was inspired by the article from Martin Flower on microservices , here's some important short notes from his article.

The Microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. 
These services are built around business capabilities and independently deployable by fully automated deployment machinery. 
There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.

comparing Monolithic applications with Microservices:

Figure 1




Other useful references:
http://www.infoq.com/articles/microservices-intro
https://michaelfeathers.silvrback.com/







Monday, 28 July 2014

Springboot - simple RESTFul webservice implementation using JSON



Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that can you can "just run". 

Features

  • Create stand-alone Spring applications
  • Embed Tomcat or Jetty directly (no need to deploy WAR files)
  • Provide opinionated 'starter' POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration
I was inspired the talk @SpringeXchange Nov-2014 on Developing Bootiful applications using Spring Boot. I have created a sample project created for reference on the features explained .
https://github.com/prashanthmamidi/SpringBootSamples

Here's an example which I have used to create a simple RESTFul webservice implementation using JSON message

pom. xml

 <pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
                color: #000000; background-color: #eee;
                font-size: 12px; border: 1px dashed #999999;
                line-height: 14px; padding: 5px; 
                overflow: auto; width: 100%">
       <code style="color:#000000;word-wrap:normal;">

           <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>msdemo</name>
    <description>Demo project</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


       </code>
 </pre>
EmployeeController.java
import com.biomedcentral.demo.domain.Employee;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by mami01 on 28/07/14.
 */

@RestController
public class EmployeeController {

    //Map to store employees, ideally we should use database
    Map<Integer, Employee> empData = new HashMap<Integer, Employee>();

    @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
    public Employee getDummyEmployee() {
        Employee emp = new Employee();
        emp.setId(9999);
        emp.setName("Dummy");
        emp.setCreateDate(new Date());
        empData.put(9999, emp);
        return emp;
    }

    @RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
    public Employee getEmployee(@PathVariable("id") int empId) {
        return empData.get(empId);
    }


    @RequestMapping(value = EmpRestURIConstants.GET_ALL_EMP, method = RequestMethod.GET)
    public List<Employee> getAllEmployees() {
        List<Employee> employeeList = new ArrayList<Employee>();
        Set<Integer> empIds = empData.keySet();
        for (Integer i : empIds)
            employeeList.add(empData.get(i));
        return  employeeList;
    }


    @RequestMapping(value = EmpRestURIConstants.CREATE_EMP, method = RequestMethod.POST)
    public Employee createEmployee(@RequestBody Employee emp) {
        emp.setCreateDate(new Date());
        empData.put(emp.getId(), emp);
        return emp;
    }

    @RequestMapping(value = EmpRestURIConstants.DELETE_EMP, method = RequestMethod.PUT)
    public Employee deleteEmployee(@PathVariable("id") int empId) {
        Employee emp = empData.get(empId);
        empData.remove(empId);
        return emp;
    }

Employee.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by mami01 on 28/07/14.
 */
public class Employee implements Serializable {

    private static final long serialVersionUID = -7788619177798333712L;

    private int id;
    private String name;
    private Date createDate;


    @JsonProperty
    public int getId() {
        return id;
    }

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

    @JsonProperty
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonSerialize(using = DateSerializer.class)
    public Date getCreateDate() { //Date conversion from Java type to JSON format and vice versa
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}