Saturday, 5 September 2015

Return a Java object as JSON response from Spring MVC controller

To return an java object in JSON form from an spring objects requires two configurations:
1) Adding 'jackson-mapper-asl' dependency to the classpath
2) Add @ResponseBody annotation to the controller's method

Use in spring configuration file, to detect the spring annotations.


<mvc:annotation-driven />


1) Adding 'jackson-mapper-asl' dependency to the classpath
In a spring mvc project we need to add a 'jackson-mapper-asl' dependency to the pom.xml file, and object to json conversion is done bydefault.

<dependency>
       <groupId>org.codehaus.jackson</groupId>
       <artifactId>jackson-mapper-asl</artifactId>
       <version>1.9.10</version>
</dependency>

2) Add @ResponseBody annotation to the controller's method
Second thing we need to do is to use '@ResponseBody' annotation against the controller's method. 

This will make spring understand that method return value should be bound to the web response body.

If you annotate a method with @ResponseBody, spring will try to convert its return value and write it to the http response automatically. If you annotate a methods parameter with @RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.

package com.abusecore.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abusecore.model.Count;
import com.abusecore.services.IDataServices;

@Controller
@RequestMapping("/AbuseCore-1")
public class AbuseController {

       @Autowired
       IDataServices dataServices;
             
       /** Logger class to display logs. */
       static final Logger logger = Logger.getLogger(AbuseController.class);

       @RequestMapping(value="/count-tickets.json",method=RequestMethod.GET)
       public @ResponseBody Count getTicketsCount() {
              Count count = dataServices.getTicketsCount();
              logger.info("total tickets :" + count);
              return count;
       }
}

public @interface ResponseBody

Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.

As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.

Benefits of Spring Framework

Lightweight:
Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
IoC containers tend to be lightweight, especially when compared to EJB containers.
This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.

Inversion of control (IOC):
Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
With the Dependency Injection (DI) approach, dependencies are explicit and evident in constructor or JavaBean properties.

Aspect oriented (AOP):
Spring supports Aspect oriented programming and separates application business logic from system services.

Container:
Spring contains and manages the life cycle and configuration of application objects.

MVC Framework:
Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.

Transaction Management:
Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).

Exception Handling:
Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

Testing:
Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.

Spring does not reinvent the wheel instead; it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

Thursday, 3 September 2015

Stack vs. Heap Memory

Java Heap Memory

Heap memory is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space.

Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.

Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.

Difference between Heap and Stack Memory

Heap memory
Stack memory
Heap memory is used by all the parts of the application.
whereas stack memory is used only by one thread of execution.

Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it.

Stack memory only contains local primitive variables and reference variables to objects in heap space.
Objects stored in the heap are globally accessible.

Stack memory can’t be accessed by other threads.
Heap memory is more complex because it’s used globally and  Heap memory is divided into Young-Generation, Old-Generation etc.

Memory management in stack is done in LIFO manner.
We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory.

We can use -Xss to define the stack memory size.
If heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.

When stack memory is full, Java runtime throws java.lang.StackOverFlowError.

Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

Heap memory lives from the start till the end of application execution.

Stack memory is short-lived.
Stack memory size is very less when compared to Heap memory.


Tuesday, 1 September 2015

Method Overloading

Method Overloading

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type.

It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on.

Alternatively, we can use four methods named draw with different parameter list.

Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list.

public class DataArtist {
    ...
    public void draw(String s) {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(double f) {
        ...
    }
    public void draw(int i, double f) {
        ...
    }
}

static String valueOf(boolean b)
       static String valueOf(char c)
       static String valueOf(char[] data)
       static String valueOf(char[] data, int offset, int count)
       static String valueOf(double d)
       static String valueOf(float f)
       static String valueOf(int i)
       static String valueOf(long l)
       static String valueOf(Object obj)

This means that if we have any type of variable, we can get a String representation of it by using String.valueOf(variable).


draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.
Related Posts Plugin for WordPress, Blogger...