Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣

Thursday, March 5, 2015

Object utility with null safety


Java Objects utility class with examples

All of Java developers faced NullPointerException during there development phases.
What we  all developers do to prevent this ?
Simple put a null check before using that object.

Finally Java language feels that it can be done bit smart way. They introduced java.util.Objects class. This class is an object utility class with static methods which are null safe or null tolerant methods for some mostly used basic utility class.

public final class java.util.Objects {
  public static boolean equals(java.lang.Object, java.lang.Object);
  public static boolean deepEquals(java.lang.Object, java.lang.Object);
  public static int hashCode(java.lang.Object);
  public static int hash(java.lang.Object...);
  public static java.lang.String toString(java.lang.Object);
  public static java.lang.String toString(java.lang.Object, java.lang.String);
  public static <T> int compare(T, T, java.util.Comparator<? super T>);
  public static <T> T requireNonNull(T);
  public static <T> T requireNonNull(T, java.lang.String);
  public static boolean isNull(java.lang.Object);
  public static boolean nonNull(java.lang.Object);
  public static <T> T requireNonNull(T, java.util.function.Supplier<java.lang.String>);
}

Lets check-out each methods and see what they really do. Before I start, I want you to know that I'm using JDK 8 for my examples.

Equals and DeepEquals


public static boolean equals(java.lang.Object, java.lang.Object);
public static boolean deepEquals(java.lang.Object, java.lang.Object);

Over here we are not interested in implementation of equals method, what I bring into light is when we use equals method during development we generally write if(obj1 != null && obj1.equals(obj2) or if(obj2 != null && obj2.equals(obj1) kind of code to safe guard from NullPointerException. Here in JDK 1.7 in java.util.Objects we have an static utility method by which we can simple check for equals without go for extra null check before invocation of equals method.

Here in Objects.equals(a,b) equals method is invoked on object 'a'.
EqualsTest.java
  1. import java.util.Objects;
  2. public class EqualsTest {
  3. public static void main(String[] args) {
  4. Object a = new Object();
  5. Object b = null;
  6. System.out.println(Objects.equals(a,b));
  7. }
  8. }
Here is source output

false

Here we have another equals method which look deep into the object. Let's see what deepEquals do, deepEquals compare two objects and figure out whether they are same or not. So there is equals method already do the same why do they have deepEquals doing the same job as equals. Interesting deepEquals and equals methods are not exactly same.
Using deepEquals method we can compare both objects and arrays also. When both the arguments are arrays then it uses Arrays.deepEquals0 method to compare each elements of both the arrays.

DeepEqualsTest.java
  1. import java.util.Objects;
  2. public class DeepEqualsTest {
  3. public static void main(String[] args) {
  4. Object obj1 = new Object();
  5. Object obj2 = null;
  6. Object obj3 = obj1;
  7. Object obj4 = new Object();
  8. System.out.println("Is obj1 is equals to obj2 ? " +Objects.deepEquals(obj1, obj2));
  9. System.out.println("Is obj2 is equals to obj3 ? " +Objects.deepEquals(obj2, obj3));
  10. System.out.println("Is obj1 is equals to obj3 ? " +Objects.deepEquals(obj1, obj3));
  11. System.out.println("Is obj1 is equals to obj4 ? " +Objects.deepEquals(obj1, obj4));
  12. int a[] = {1,2,3};
  13. int b[] = {1,2,3};
  14. int c[] = {1,2,3,4};
  15. int d[] = null;
  16. System.out.println("Is array a is equals to b ? " +Objects.deepEquals(a, b));
  17. System.out.println("Is array a is equals to c ? " +Objects.deepEquals(a, c));
  18. System.out.println("Is array d is equals to c ? " +Objects.deepEquals(d, c));
  19. Object objs1[] = {obj1,obj4};
  20. Object objs2[] = {obj3,obj4};
  21. Object objs3[] = null;
  22. Object objs4[] = {obj4};
  23. System.out.println("Is array objs2 is equals to objs1 ? " +Objects.deepEquals(objs2, objs1));
  24. System.out.println("Is array objs3 is equals to objs2 ? " +Objects.deepEquals(objs3, objs2));
  25. System.out.println("Is array objs4 is equals to objs2 ? " +Objects.deepEquals(objs4, objs2));
  26. }
  27. }


Here is source output.
Is obj1 is equals to obj2 ? false
Is obj2 is equals to obj3 ? false
Is obj1 is equals to obj3 ? true
Is obj1 is equals to obj4 ? false
Is array a is equals to b ? true
Is array a is equals to c ? false
Is array d is equals to c ? false
Is array objs2 is equals to objs1 ? true
Is array objs3 is equals to objs2 ? false
Is array objs4 is equals to objs2 ? false


Hash and HashCode


public static int hashCode(java.lang.Object);
public static int hash(java.lang.Object...);

Here also we have two variant of hash code methods as equals.
hashCode method simply return hash code value of the object where as hash method can return hash code value of array of objects and primitive data types.
HashCodeTest.java
  1. import java.util.Objects;
  2. public class HashCodeTest {
  3. public static void main(String[] args) {
  4. Object obj1 = new Object();
  5. Object obj2 = null;
  6. System.out.println("Hash Code value of obj1 is " +Objects.hashCode(obj1));
  7. System.out.println("Hash Code value of obj2 is " +Objects.hashCode(obj2));
  8. Object objs1[] = {obj1,obj2};
  9. int objs2[] = {1,2,3,4};
  10. System.out.println("Hash Code value of object is " +Objects.hash(obj1));
  11. System.out.println("Hash Code value of array of objects is " +Objects.hash(objs1));
  12. System.out.pr int ln("Hash Code value of array of int is " +Objects.hash(objs2));
  13. }
  14. }

Here is the source output

Hash Code value of obj1 is 366712642
Hash Code value of obj2 is 0
Hash Code value of object is  366712673  [Note :- This is not same as 1st line of output]
Hash Code value of array of objects is  -1516809025
Hash Code value of array of int is  1829164731


ToString


public static java.lang.String toString(java.lang.Object);
public static java.lang.String toString(java.lang.Object, java.lang.String);

Here we have two variant of toString one which simply return the toString value of the object where as toString(Object,String) can be used when we required to set something default string in case of object is null.

ToStringTest.java
  1. public class ToStringTest {
  2. public static void main(String[] args) {
  3. Object obj1 = new Object();
  4. Object obj2 = null;
  5. System.out.println("toString value of obj1 is " +Objects.toString(obj1));
  6. System.out.println("toString value of obj2 is " +Objects.toString(obj2));
  7. System.out.println("toString value of obj2 is " +Objects.toString(obj2, "\'sorry it's null\'"));
  8. }
  9. }

Here is the source output

toString value of obj1 is java.lang.Object@15db9742
toString value of obj2 is null
toString value of obj2 is 'sorry it's null' [See default null is returned]

 

Compare

public static <T> int compare(T, T, java.util.Comparator<? super T>);

This is the only static utility method which I found that this method is not null proof, actually developer have to develop a null proof comparator.
It simple compare the objects using your comparator and return value. Wait a minute what I say in previous line is conflicting, when I had written the comparator I have to make sure that it is null proof. So I have to write a special null proof comparator. Now I try reasoned out why they put this static utility method here in this Objects class, as everything need to be done by developer itself. I didn't find anything special about it, let me know if you have anything. 
CompareTest.java
  1. import java.util.Objects;
  2. import java.util.Comparator;
  3. public class CompareTest {
  4. public static void main(String[] args) {
  5. Integer obj1 = Integer.valueOf(1);
  6. Integer obj2 = null;
  7. Integer obj3 = Integer.valueOf(1);
  8. Integer obj4 = Integer.valueOf(2);
  9. WrapperIntegerComparator comparator = new WrapperIntegerComparator();
  10. System.out.println("compare value of "+ obj2 +" with "+ obj1 +" = " +Objects.compare(obj2, obj1, comparator));
  11. System.out.println("compare value of "+ obj4 +" with "+ obj1 +" = " +Objects.compare(obj4, obj1, comparator));
  12. System.out.println("compare value of "+ obj3 +" with "+ obj1 +" = " +Objects.compare(obj3, obj1, comparator));
  13. }
  14. }
  15. // Null proof comparator
  16. class WrapperIntegerComparator implements Comparator<Integer> {
  17. public int compare(Integer x, Integer y) {
  18. if(x == y) {
  19. return 0;
  20. } else if(y == null) {
  21. return 1;
  22. } else if(( x == null) ||(x < y))
  23. return -1;
  24. else
  25. return ((x == y) ? 0 : 1);
  26. }
  27. }


Here is the source output

compare value of null with 1 = -1
compare value of 2 with 1 = 1
compare value of 1 with 1 = 0


RequiredNonNull

public static <T> T requireNonNull(T);
public static <T> T requireNonNull(T, java.lang.String);

These methods behaviour are same of when we try to insert a null value in not null column, it will complain about null value. These methods throw NullPointerException if the parameter is null and the second method add error message of NullPointerException. Let's blew out some NullPointerException.

RequireNonNullTest.java
  1. import java.util.Objects;
  2. public class RequireNonNullTest {
  3. public static void main(String[] args) {
  4. String name1 = "Andy";
  5. String name2 = null;
  6. System.out.println("1st person name is "+ Objects.requireNonNull(name1));
  7. System.out.println("2nd person name is "+ Objects.requireNonNull(name2,"There is no person of this name"));
  8. }
  9. }

Here is the source output

1st person name is Andy
Exception in thread "main" java.lang.NullPointerException: There is no person of this name
    at java.util.Objects.requireNonNull(Objects.java:228)
    at com.ch1.RequireNonNullTest.main(RequireNonNullTest.java:20)


IsNull and NonNull

public static boolean isNull(java.lang.Object);
public static boolean nonNull(java.lang.Object);

Now without confusing yourself and other developer you can check for object is null or not. I am not really impressed by the 'non' word, they could have used 'not' instead of that don't know what stop them or why they like 'non' instead of 'not'.

isNull method return true if object is null else false.
nonNull methos return true if object is not null else false.

TestForNull.java
  1. import java.util.Objects;
  2. public class TestForNull {
  3. public static void main(String[] args) {
  4. String name1 = "Andy";
  5. String name2 = null;
  6. System.out.println(name1 +" isNull "+ Objects.isNull(name1));
  7. System.out.println(name2 +" isNull "+ Objects.isNull(name2));
  8. System.out.println(name1 +" nonNull "+ Objects.nonNull(name1));
  9. System.out.println(name2 +" nonNull "+ Objects.nonNull(name2));
  10. }
  11. }


Here is the source output

Andy isNull false
null isNull true
Andy nonNull true
null nonNull false



public static <T> T requireNonNull(T, java.util.function.Supplier<java.lang.String>) 

This particular API is added in Java 8 but it does the same job as previous requireNonNull method does.

RequireNonNullWithSupplierTest.java
  1. import java.util.Objects;
  2. import java.util.function.Supplier;
  3. public class RequireNonNullWithSupplierTest {
  4. public static void main(String[] args) {
  5. String name1 = "Andy";
  6. String name2 = null;
  7. MessageSupplier msgSupplier = new MessageSupplier();
  8. System.out.println("1st person name is "+ Objects.requireNonNull(name1, msgSupplier));
  9. System.out.println("2nd person name is "+ Objects.requireNonNull(name2, msgSupplier));
  10. }
  11. }
  12. class MessageSupplier implements Supplier<String> {
  13. @Override
  14. public String get() {
  15. return "\'This person name not found.\'";
  16. }
  17. }

Here is the source output

1st person name is Andy
Exception in thread "main" java.lang.NullPointerException: 'This person name not found.'
    at java.util.Objects.requireNonNull(Objects.java:228)
    at com.ch1.RequireNonNullWithSupplierTest.main(RequireNonNullWithSupplierTest.java:24)

Some regularly used methods with null check, I think developers are going to love it. 

Happy Coding :) 

Monday, September 1, 2014

Using Spring HTTP Invoker


Spring provide features to integrate classes for remoting support using various technologies like Remote Method Invocation (RMI), Hessian, Burlap, JAX-WS,Java Messaging Service (JMS), Advanced Messaging Queuing Protocol (AMQP) and Spring HTTP Invoker.It is recommended that you must have bit of idea about proxy pattern as Spring remoting framework follow the Proxy software pattern. Here we will be looking into Spring HTTP Invoker only. 

Spring HTTP Invoker comes into picture when Spring recognizes the need of HTTP based client server communication and which uses java serialization because RMI  services uses java serialization but it difficult to work with across firewall and on the other side HTTP based services such as Hessian and Burlap work well across firewall but they use there proprietor serialization method not java serialization.  


Spring HTTP Invoker is a special remoting strategy which allows for Java serialization via HTTP, supporting any Java interface clients to communicate with Spring server using HTTP service without client knowledge of implementation. As it is working on HTTP service it will be easy to use it across network with firewall.
 
Spring HTTP Invoker Flow
Fig.1. Spring HTTP Invoker Flow

Spring HTTP Invoker flow steps:-
  • Client invoke the proxy's service method which is being handle by HttpInvokerProxyFactoryBean.
  • The proxy convert the method call to HTTP remote call.
  • The HTTP Service Adapter intercept to remote call and create HttpInvokerServiceExporter.
  • It the forward the method call to Service. 




Dispatcher Flow
Fig. 2. Dispatcher Flow

Spring HTTP invoker remote service is simple and easy. Lets get into the implementation of Spring HTTP Invoker client server model using web container and without web container.

First we start where Spring HTTP Invoker server running in web container.

Step 1. Create interface for the client


Application.java
  1. package andy.blog.spring.remoting.httpinvoker.service;
  2. public interface Application {
  3. String getGreeting(final String name);
  4. }
Step 2. Create the service for client

ApplicationService.java
  1. package andy.blog.spring.remoting.httpinvoker.service;
  2. public class ApplicationService implements Application {
  3. @Override
  4. public String getGreeting(String name) {
  5. return "Hi " + name + " !!";
  6. }
  7. }
Step 3. Create the web.xml
web.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. id="WebApp_ID" version="3.0">
  6. <display-name>Application</display-name>
  7. <welcome-file-list>
  8. <welcome-file>pages/index.jsp</welcome-file>
  9. </welcome-file-list>
  10. <servlet>
  11. <servlet-name>Application</servlet-name>
  12. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  13. <init-param>
  14. <param-name>contextConfigLocation</param-name>
  15. <param-value>/WEB-INF/WebAppContext/SpringServletContext.xml
  16. </init-param>
  17. <load-on-startup>1</load-on-startup>
  18. </servlet>
  19. <servlet-mapping>
  20. <servlet-name>Application</servlet-name>
  21. <url-pattern>*.http</url-pattern>
  22. </servlet-mapping>
  23. </web-app>
Step 4. Create the Spring Servlet Application context. 

This is where we exposing the beans as HTTP service. In case of web application request handler by DispatcherServlet then dispatches to HTTP invoker service. This service translate them into method call in Spring manages beans.  
Here applicationService is the service bean and /greeting.http is Spring HTTP service exporter bean.
      
WEB-INF\WebAppContext\SpringServletContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:beans="http://www.springframework.org/schema/beans"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  9. <annotation-driven />
  10. <context:component-scan base-package="andy.blog.spring.remoting.httpinvoker.controller" />
  11. <beans:bean
  12. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  13. <beans:property name="prefix" value="/pages/" />
  14. <beans:property name="suffix" value=".jsp" />
  15. </beans:bean>
  16. <!-- Application Service -->
  17. <beans:bean id="applicationService" class="andy.blog.spring.remoting.httpinvoker.service.ApplicationService" />
  18. <!-- Exporter -->
  19. <beans:bean name="/greeting.http"
  20. class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
  21. <!-- Application Service reference -->
  22. <beans:property name="service" ref="applicationService" />
  23. <!-- Application interface -->
  24. <beans:property name="serviceInterface" value="andy.blog.spring.remoting.httpinvoker.service.Application" />
  25. </beans:bean>
  26. </beans:beans>
Step 5. Application Context of Spring HTTP Invoker client. Here HttpInvokerProxyFactoryBean is a proxy factory for creating HTTP Invoker service proxies. serviceUrl is the service url where client send the HTTP request and it is create HTTP invoker service exporter object and invokes the actual service method call.
applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <bean id="applicationClient"
  7. class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
  8. <property name="serviceUrl"
  9. value="http://localhost:9090/SpringHttpService/greeting.http" />
  10. <property name="serviceInterface" value="andy.blog.spring.remoting.httpinvoker.service.Application" />
  11. </bean>
  12. </beans>
Step 6. To access service via HTTP create the Client.
ApplicationClient.java
  1. package andy.blog.spring.remoting.httpinvoker.client;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
  5. import andy.blog.spring.remoting.httpinvoker.service.Application;
  6. public class ApplicationClient {
  7. public static void main(String...pram) {
  8. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  9. HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = context.getBean(HttpInvokerProxyFactoryBean.class);
  10. Application application = (Application) httpInvokerProxyFactoryBean.getObject();
  11. System.out.println("Start Application Client ");
  12. System.out.println(application.getGreeting("Tom"));
  13. System.out.println(application.getGreeting("Harry"));
  14. System.out.println(application.getGreeting("James"));
  15. System.out.println(application.getGreeting("Andy"));
  16. System.out.println("End Application Client ");
  17. }
  18. }
Run the Spring HTTP Invoker server side into some web container and the run the client.

Start Application Client
Hi Tom !!
Hi Harry !!
Hi James !!
Hi Andy !!
End Application Client

 
Now we will see how to create Spring HTTP Invoker server running in non-web container and how to write a test case for that.
Repeat Step 1 create an interface for the client.

We will re-write the HTTP service method to distinguishes from above service method. Just changed the return message text.


ApplicationService.java
  1. package andy.blog.spring.remoting.httpinvoker.service;
  2. public class ApplicationService implements Application {
  3. @Override
  4. public String getGreeting(String name) {
  5. return "Hi " + name + " !! This is non web service"; // message is changed
  6. }
  7. }
Simple HTTP server applicationContext.xml here application service & HTTP service exporter are same as above discussed but we here used org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter instead of HttpInvokerServiceExporter. Here
org.springframework.remoting.support.SimpleHttpServerFactoryBean is used to create simple HTTP Server based on the HTTP server that is included in Sun's JRE.
applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xmlns:util="http://www.springframework.org/schema/util">
  8. <context:annotation-config />
  9. <!-- Application Service -->
  10. <bean name="applicationService"
  11. class="andy.blog.spring.remoting.httpinvoker.service.ApplicationService" />
  12. <!-- Exporter -->
  13. <bean name="serviceExporter"
  14. class="org.springframework.remoting.httpinvoker.SimpleHttpInvokerServiceExporter">
  15. <property name="serviceInterface"
  16. value="andy.blog.spring.remoting.httpinvoker.service.Application" />
  17. <property name="service" ref="applicationService" />
  18. </bean>
  19. <!-- Http Web Server -->
  20. <bean id="httpServer"
  21. class="org.springframework.remoting.support.SimpleHttpServerFactoryBean">
  22. <property name="contexts">
  23. <util:map>
  24. <entry key="/SpringHttpService/greeting.http" value-ref="serviceExporter" />
  25. </util:map>
  26. </property>
  27. <property name="port" value="9090" />
  28. </bean>
  29. <!-- For JUnit Test -->
  30. <bean id="remotedApplicationService"
  31. class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
  32. <qualifier value="remoted" />
  33. <property name="serviceUrl"
  34. value="http://localhost:9090/SpringHttpService/greeting.http" />
  35. <property name="serviceInterface"
  36. value="andy.blog.spring.remoting.httpinvoker.service.Application" />
  37. </bean>
  38. </beans>
We have to create a simple HTTP server using Sun's package. This is required to to run the HTTP server for our client application.
ApplicationServer.java
  1. package andy.blog.spring.remoting.httpinvoker.service;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.sun.net.httpserver.HttpServer;
  5. public class ApplicationServer {
  6. public static void main(String[] args) {
  7. ApplicationContext context = new ClassPathXmlApplicationContext("/applicatonContext.xml");
  8. HttpServer appServer = (HttpServer) context.getBean("httpServer");
  9. }
  10. }
Test case to make sure our HTTP invoker service work's fine.
ApplicationServiceTest.java
  1. package andy.blog.spring.remoting.httpinvoker.service;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertTrue;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Qualifier;
  8. import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
  9. import org.springframework.test.context.ContextConfiguration;
  10. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
  11. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(inheritLocations = true, locations = { "/applicatonContext.xml" })
  14. public class ApplicationServiceTest extends AbstractJUnit4SpringContextTests {
  15. @Autowired(required = true)
  16. @Qualifier("remoted")
  17. private Application application;
  18. @Test
  19. public void getGreetingTestUsingConfiguredClient() throws Exception {
  20. String greeting = application.getGreeting("Tom");
  21. assertEquals("Hi Tom !! This is non web service", greeting);
  22. System.out.println(greeting);
  23. assertTrue("Should not be the implementation", !application.getClass().equals(ApplicationService.class));
  24. }
  25. @Test
  26. public void getGreetingTestManually() throws Exception {
  27. HttpInvokerProxyFactoryBean proxy = new HttpInvokerProxyFactoryBean();
  28. proxy.setServiceInterface(Application.class);
  29. proxy.setServiceUrl("http://localhost:9090/SpringHttpService/greeting.http");
  30. proxy.afterPropertiesSet();
  31. Application application = (Application) proxy.getObject();
  32. String greeting = application.getGreeting("tester");
  33. assertEquals("Hi tester !! This is non web service", greeting);
  34. System.out.println(greeting);
  35. assertTrue("Should not be the implementation", !application.getClass().equals(ApplicationService.class));
  36. }
  37. }
If you run the above test or above client you get below output.
Hi tester !! This is non web service
Hi Tom !! This is non web service


Well Spring HTTP Invoker is quite easy to implement you just need a reason to run two application on different JVMs.  

Saturday, August 2, 2014

My weekend trip to Purulia, Chandil Dam, Jayda Temple, Dalma Wildlife Sanctuary and Jamshedpur

My last week end trip (25th July 2014 to 29th July 2014) was at Purulia, Chandil Dam, Dalma Wildlife Sanctuary and  Jamshedpur. 

Purulia

Purulia is also known as "Manbhum" located in West Bengal, India. The  beauty of natural forest, variety of flora and fauna, scattered hills and falls, rivers and streams make this place eye-catching to the nature lovers and these makes ideal place expeditions and enjoyment.

There are many temples in and around Purulia which are archeological asset of this district. Some of these temples are below to 17th century. 

Ayodhya hills is a part of the Dalma mountain range. It is spread accross on the boundary between Purulia district and Jharkhand. Gorshabru, the highest peak of the Ayodhya Hills is situated at a magnificent 2800(+) feet is deep inside the jungle there a forest. There are many watch towers in this jungle, have close watch on road side pillars which have watch tower, fall name direction and other information. There are several dams in and around Ayodhya hills one of them is Purulia Pump Storage Project (or P.P.S.P). Purulia Pump Storage Project is one of the largest stagnant water hydrel project of India, capacity of which is 900 m.w. The project consists of two dam- upper dam & lower dam. Scenic beauty upper dam is very nice to watch.

I heard a folklore from local villager that Ram and Sita had come to Ayodhya Hills and stayed during their exile. During the full moon day in Baisakh (first month in the Bangla Calendar) every year tribal's of nearby areas come and join in the game of hunting wild animals only for one day in year they are allowed to hunt.

Purulia is easily accessible by road and by train from Kolkata, from  Howrah/Santragachi 12827/Howrah - Purulia Superfast Express, 12883/Rupashi Bangla Express, 12152/Samarsata SF Express, 58011/Howrah - Chakradharpur Passenger. It is 295 Km away from Kolkata towards west and 119 Km from Ranchi towards east. The National Highway – 32 and National Highway – 60A passes through the District. SBSTC, CSTC, NBSTC buses and many privately operated buses ply between Kolkata to Purulia.
 


P.P.S.P upper dam

   
Information

Rough Map

View from watch tower

Chandil Dam,Jayda Temple, Dalma Wildlife Sanctuary and  Jamshedpur all places are in Jharkhand ("The Land of Forest")  eastern India state, which have large portion of forest and minerals resources of India. 


Chandil Dam is standing on the Subarnarekha River is 220 meter in height and the height of its water level is 190 meter. This dam is most visited place in Jharkhand. Other that scenic beauty you can enjoy boating. There is parking fee at Chandil Dam for bus/truck Rs.100/-,for TATA Winger Rs.30/-,for car Rs. 20/-, for two wheeler Rs.10/-. Seriously speaking why they have special charge for "TATA Winger" I don't know.

Chandil Dam

Boating Platform

Subarnarekha River
Boating

The nearby Jayda Temple dedicated to Lord Shiva is another popular attraction nearby. A huge fair is held every year at the site on the eve of Makar Sankranti.Situated on the way to Ranchi-Tata road.


Jayda Temple


Jayda Temple history


Dalma Wildlife Sanctuary is a much larger area starting from area of Subarnarekha River and adjoining Purulia District of West Bengal, this wildlife sanctuary with an area of 193.22 Sq. Km. on the National Highway No. 33 near Jamshedpur has undulating terrain with high hillocks (Max. 984 M MSL). This wildlife sanctuary home for Elephant,Leopard, Barking Deer, Mouse Deer, Sloth Bear, Monkey, Giant Squirrel. The sanctuary is very much favored by the Elephants due to availability of water even during summer.At top there is Lord Hanuman Mandir and cave of Lord Shiva. The vast forest land is ideal place spot for trekking expeditions. There are many trekking trails from mild to medium trekking. There is 20 KM drive from foot to top of hill in the forest. There are watch tower from there you can get a view of Jamshedpur City. There are charges to get into the forest.
   

Forest Road

View Of Jamshedpur City from Dalma Forest watch tower

Jamshedpur 

Jamshedpur is the first planned industrial city of India, founded by Jamshedji Nusserwanji Tata. There many interesting place in Jamshedpur but I manage to visit "TATA Steel Zoological Park" and "Jubilee Park (Jayanti Sarovar)" which is one of the biggest park in India apart from this there are 1000 varieties of roses in this garden and in lake you can do boating.
 


Jayanti Sarovar


I went there from Purulia by National Highway-32 which pass through Chandil and Dalma Wildlife Sanctuary from West Bengal to National Highway-33 which leading to Ranchi and Jamshedpur.





Monday, October 28, 2013

OCJP 7 book review



Author's Names: S G Ganesh & Tushar Sharma

Type of Book/Genre: OCPJP 7 Certification

Description/Brief Summary: This book is for OCPJP 7 certification.

Review:
If you are studying for OCPJP 7 examination, then I find this book is very useful. You could be a professional who wants to brush-up on Java APIs, you could be a trainer for Core Java, or you could be someone who just want to pass the exam. This book is very well-organized and it covers all the topics for OCPJP 7 in required depth.

The first chapter contains OCPJP 7 examination FAQs that provides OCPJP 7 certification overview, kinds of questions that come in this certification examination, details about how to prepare for it and the most interesting things as well as very useful information for readers who is going to give this kind of certification examination for the first time, that is how to register, what to do on the examination day, etc.

The second chapter contains a pre-test; this chapter will be useful to check your current-level of knowledge and find your weakness before you start. A new learner can skip this chapter as this chapter required beginners/intermediate knowledge in Java.

Rest of the twelve chapters covers all the topics required for OCPJP 7 with examples to explain the APIs and tricks, this chapters end with a test named "Question Time!" to check reader's learning and most important thing there is a summary section at the end of each chapter which is a great help for quick recap. Apart from this there is a "Points to Remember" section to which highlight the tricky parts covered in that section.

At the end there are two OCPJP 7 mock exams which will help reader for final preparation and check actual preparedness for the examination.

I really enjoyed reading it. I recommend this book for OCPJP 7 certification and as a Core Java book.

Monday, July 1, 2013

NoSQL Overview

Today's internet age data nature, size and query response changes dynamically due to huge user load resulting into data start growing unmanageably.
Wal-Mart: 1 million transactions per hour
Twitter: 250 million tweets a day
Facebook: 1 billion messages a day


RDMS are not design to handle this volume of data since they are generally design to scale on single server, so user need to buy a bigger machine to meet this requirement and it will add huge input cost.  


Now this data is accessed from mobile devices to desktop. (Data is distributed & urgent)
$300 billion potential annual value to US health care. (Data is valued)


To meet the need of  scalability, performance and consistency required in this web era NoSQL databases are schema free, easy replication support, sharding, instead of ACID**  it follow BASE**, following CAP** theorem etc.


** ACID is Atomicity, Consistency, Isolation, Durability. BASE is Basically Available, Soft State, and Eventually Consistent. CAP is Consistency , Availability , Partition tolerance


Schema free: There is no predefined schema for NoSQL databases.


Easy Replication Support: NoSQL databases employ asynchronous replication, which allows write to complete more quickly since they don’t depend on extra network traffic.


Horizontal Scaling: NoSQL databases split tables across different server, but with only instance of the same data.


Sharding: NoSQL can perform sharding. In which records (rows) are distributed across many database server.


BASE instead of ACID: NoSQL databases emphasis on performance and availability.
Basic Availability: NoSQL use replication to reduce the likelihood of data unavailability and use sharding, or partitioning the among many different storage server, to make any remaining failure partial. The result is a system that is always available, even if subsets of the data become unavailable for short period of time.
Soft State: NoSQL systems allow data to be inconsistent and relegate designing around such inconsistencies to application developers.
Eventual Consistency: Although applications must deal with instantaneous consistency, NoSQL systems ensure that at some future point in time the data assumes a consistent state. In NoSQL it guarantees consistency only at some un-define future time.


Here is one important theorem of distributed computer system CAP theorem or Brewer’s theorem, which is followed by NoSQL databases.
Consistency: All database clients see the same data, even with concurrent updates.
Availability: All database clients are able to access some version of the data.
Partition Tolerance: The database can be split over multiple servers & at any moment data must be available even if any node(s) / communication link(s) fails.


NoSQL database come in many form to meet application requirement like key-value store, column family store, document store and graph store are the major forms.


Key-Values Store main idea is the existence of a hash table where there is a unique key and a pointer to a particular item of data. These mappings are usually accompanied by cache mechanisms to maximize performance.


Column Family Store was created to store and process very large amounts of data distributed over many machines. There are still keys but they point to multiple columns.


Document Store model is basically versioned documents that are collections of other key-value collections. The semi-structured documents are stored in formats like XML, JSON (JavaScript Object Notation), YAML (Yet Another Markup Language)& BSON(Binary JSON).


Graph Store is built with nodes, relationships between notes and the properties of nodes. Instead of tables of rows and columns and the rigid structure of SQL, a flexible graph model is used which can scale across many machines.