Sunday, 6 September 2015

Spring Annotation Based Controllers


@Controller Annotation

For the @Controller annotation spring gives a feature of autodetection. Adding “component-scan”in spring-context and provide the base-package.

       <!-- Controller package -->
       <context:component-scan base-package="com.abusecore.controller" />
       <mvc:annotation-driven />

The dispatcher will start from the base-package and scan for beans that are annotated with @Controller annotation and look for @RequestMapping.

@Controller annotation just tells the container that this bean is a designated controller class.



@RequestMapping Annotation

@RequestMappingannotation is used to map a particular HTTP request method (GET/POST) to a specific class/method in controller which will handle the respective request.

@RequestMapping annotation can be applied both at class and method level. In class level we can map the URL of the request and in method we can map the URL as well as HTTP request method (GET/POST).

We can use wildcard characters like * for path pattern matching.

In the following example, @RequestMapping(“/AbuseCore-1”)annotated at class level maps the request URLand at again at lower level method level mapping is used for HTTP request mapping.

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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.abusecore.model.Count;
import com.abusecore.model.Status;
import com.abusecore.model.Ticket;
import com.abusecore.services.IDataServices;

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

       @Autowired
       IDataServices dataServices;

       /** Logger class to display logs. */
       static final Logger logger = Logger.getLogger(RestController.class);


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

       @RequestMapping(value = "/create", method = RequestMethod.POST,
                     consumes = MediaType.APPLICATION_JSON_VALUE)
       public @ResponseBody Status addEmployee(@RequestBody Ticket ticket) {
              try {
                     dataServices.addEntity(ticket);
                     return new Status(1, "Ticket added Successfully !");
              } catch (Exception e) {
                     // e.printStackTrace();
                     return new Status(0, e.toString());
              }
       }
}

Multi-action Controller

In a multi-action controller URLs are mapped at method level since the controller services multiple URLs.

In given code, two URLs are serviced by the controller and they are mapped to separate methods.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

       @RequestMapping("/")
       public String hello() {
              return "hello";
       }

       @RequestMapping(value = "/hi", method = RequestMethod.GET)
       public String hi(@RequestParam("name") String name, Model model) {
              String message = "Hi " + name + "!";
              model.addAttribute("message", message);
              return "hi";
       }
}


When we use multi-action form controller there is a possibility of creating ambiguity in mapping the URLs to methods.

In that case, org.springframework.web.servlet.mvc.multiaction.MethodNameResolverhelps us to resolve the ambiguity method mapping.

If MethodNameResolver is not specified then by default org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolveris used.

This default implementation does not support wildcard characters.

When a matching method is not found, action will be mapped to a default method in the controller which does not have any @RequestMappingspecified.

If there are more such methods in the controller, then method name will be taken into consideration.

<beans>
       <bean class="org.springframework.web.servlet.mvc.support.
                   ControllerClassNameHandlerMapping"/>
       <bean class="com.spring.mvc.controller.HelloWorldController">
              <property name="methodNameResolver">
                     <bean class="org.springframework.web.servlet.mvc.multiaction.
                                PropertiesMethodNameResolver">
                           <property name="mappings">
                                  <props>
                                         <prop key="/">hello</prop>
                                         <prop key="/hi">hi</prop>
                                  </props>
                           </property>
                     </bean>
              </property>
       </bean>
</beans>



@RequestParam Annotation

org.springframework.web.bind.annotation.RequestParam

Annotation which indicates that a method parameter should be bound to a web request parameter.

Supported for annotated handler methods in Servlet and Portlet environments.

If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

@RequestMapping(value = "/ticket.json", method = RequestMethod.GET)
public @ResponseBody Ticket getTicket 
     (@RequestParam(value="ticket_id",required=false,defaultValue="0")int ticketId) {
       Ticket ticket = null;
       ticket = dataServices.getEntityById(ticketId);
       if(ticket!=null) {
              logger.info("ticket #" +ticketId+ "load successfully");
       }
       return ticket;
}



@SessionAttributes

@SessionAttributes annotation is used on the class level to:

1.    Mark a model attribute should be persisted to HttpSession after handler methods are executed

2.    Populate your model with previously saved object from HttpSession before handler methods are executed -- if one do exists.

So you can use it alongside your @ModelAttribute annotation like in this example:

@Controller
@RequestMapping("/counter")
@SessionAttributes("mycounter")
public class CounterController {

  // Checks if there's a model attribute 'mycounter', if not create a new one.
  // Since 'mycounter' is labelled as session attribute it will be persisted to
  // HttpSession
  @RequestMapping(method = GET)
  public String get(Model model) {
    if(!model.containsAttribute("mycounter")) {
      model.addAttribute("mycounter", new MyCounter(0));
    }
    return "counter";
  }

  // Obtain 'mycounter' object for this user's session and increment it
  @RequestMapping(method = POST)
  public String post(@ModelAttribute("mycounter") MyCounter myCounter) {
    myCounter.increment();
    return "redirect:/counter";
  }
}
 Make sure you make your session objects Serializable.

@CookieValue

@CookieValue annotation is used to bind a method parameter to a HTTP cookie. In below example, a cookie with key “username” value will be bound to method variable name.

@RequestMapping("/hi")
public void userInfo(@CookieValue("username") String name)  {
       // code
}

@RequestHeader

@RequestMapping("/hi")
public void hostInfo(@RequestHeader("Host") String host)  {

       //...
}

Very similar to cookie binding, @RequestHeader is used to bind a header value to a method parameter.

Assume we have the following header value, and the following annotation in controller will bind the host variable to the value.

Host: localhost: 8080


Inject a java.util.Properties into a Spring Bean


Hard Coded

<bean id="adminUser"class="com.spring.InjectProperties">
       <!-- java.util.Properties -->
       <property name="emails">
              <props>
                     <prop key="admin">admin@nospam.com</prop>
                     <prop key="support">support@nospam.com</prop>
              </props>
       </property>
</bean>


From properties file

You can use “util:” namespace as well to create properties bean from properties file, and use bean reference for setter injection.

<util:properties id="emails" location="classpath:com/foo/emails.properties"/>

Inject a property value into a Spring Bean using XML configurations

<util:properties id="serverProperties" location="file:./applications/MyApplication/server.properties"/>
<util:properties id="someConfig" location="file:./applications/MyApplication/config.properties"/>

Inject a property value into a Spring Bean using annotations

@Autowired+@Qualifiercan double as by-name autowiring, but it's really meant for by-type autowiring with the ability to fine-tune the type.

Typically, @Autowired is used for by-type autowiring in Spring, and @Resource is used for by-name.

package com.abusecore.controller;
@Autowired
@Qualifier("serverProperties")
private Properties serverProperties;
@Autowired
@Qualifier("someConfig")
private Properties otherProperties;


OR

@Resource(name = "serverProperties")
private Properties serverProperties;
@Resource(name = "someConfig")
private Properties otherProperties;

Saturday, 5 September 2015

Inject Java Collection in Spring


<list> : This helps in wiring i.e. injecting a list of values, allowing duplicates.

<set> : This helps in wiring a set of values but without any duplicates.

<map> : This can be used to inject a collection of name-value pairs where name and value can be of any type.

<props> : This can be used to inject a collection of name-value pairs where the name and value are both Strings.

<beans>
       <!-- Definition for javaCollection -->
       <bean id="myCollection"class="com.MyCollection">
             
             <!-- java.util.List -->
              <property name="stdList">
                     <list>
                           <value>INDIA</value>
                           <value>Pakistan</value>
                           <value>USA</value>
                           <value>UK</value>
                     </list>
              </property>

             <!-- java.util.Set -->
              <property name="dataSet">
                     <set>
                           <value>INDIA</value>
                           <value>Pakistan</value>
                           <value>USA</value>
                           <value>UK</value>
                     </set>
              </property>

             <!-- java.util.Map -->
              <property name="stdMap">
                     <map>
                           <entry key="1"value="INDIA" />
                           <entry key="2"value="Pakistan" />
                           <entry key="3"value="USA" />
                           <entry key="4"value="UK" />
                     </map>
              </property>

             <!-- java.util.Properties -->
              <property name="loginProperies">
                     <props>
                           <prop key="admin">admin@gmail.com</prop>
                           <prop key="support">support@gmail.com</prop>
                     </props>
              </property>
       </bean>

</beans>


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.


Related Posts Plugin for WordPress, Blogger...