Friday, February 19, 2016

How to make @RequestParam Optional?

A @RequestParam can be set as optional, by simply providing a default value to it as shown in the following example

@Controller
public class MyController {

  @RequestMapping(value = "/myApp", method = { RequestMethod.POST, RequestMethod.GET })
  public String doSomething(@RequestParam(value = "name", defaultValue = "anonymous") final String name) {
  // Do something with the variable: name
  return "viewName";
  }

}

How to get Auto-Generated Key with JdbcTemplate

Spring provides GeneratedKeyHolder class which can be used to retrieve the auto generated values.

The following class shows how to retrieve the auto generated key after a new value is added to the table.

package com.javarewind.examples.spring;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public class ExampleDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public long addNew(final String name) {
    final PreparedStatementCreator psc = new PreparedStatementCreator() {
      @Override
      public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
        final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)",
            Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        return ps;
      }
    };

    // The newly generated key will be saved in this object
    KeyHolder holder = new GeneratedKeyHolder();

    jdbcTemplate.update(psc, holder);

    long newNameId = holder.getKey().longValue();
    return newNameId;
  }
}

Thursday, February 18, 2016

OOPs Concepts


Abstaractions, Encapsulation, Inheritance, Polymorphism and Composition are the important concepts for the object oriented programming/designs.

Abstraction:

Abstraction focuses only on outside view of an object. Helps us to identify which information should be visible and which information should be hidden.

Encapsulation:

Its a mechanism to hide the data, internal structure, and implementation details of an object.

All interaction with the object is through a public interface of operations.

Encapsulation means any kind of hiding:

-- Data Hiding
-- Implementation of Hiding
-- Class Hiding (Behind abstarct class or interface)
-- Design Hiding
-- Instantiation hiding

       Data Hiding: Use private members and appropriate accessors and mutators when possible.

       For example:
      • Replace
                 public float accuracy;
      • With
               private float accuracy;
               public float getAccuracy ( ) {
                  return (accuracy);
              }
              public void setAccuracy (float acc) {
                  accuracy = acc;
             }

                   
Inheritance [IS-A Reletionship]:

Method of reuse in which new functionality is obtained by extending the implementation of an existing object.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

Polymorphism:

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. 

Composition [HAS-A Relationship]:

Method of reuse in which new functionality is obtained by creating an object composed of other objects.

When we say “one object is composed with another object” we mean that they are related by a HAS-A
relationship.


The new functionality is obtained by delegating functionality to one of the objects being composed.
 

Composition encapsulates several objects inside another one.


 

Wednesday, February 3, 2016

What are checked and unchecked exceptions?

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
3) Checked Exception represent scenario with higher failure rate while Unchecked Exception are mostly programming mistakes.

Example of checked Exception 

IOException
DataAccessException
ClassNotFoundException
InvocationTargetException 

Example of unchecked Exception

NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Why synchronized method is throwing error in interface?

Interface methods are abstract and will not have implementation details but synchronization is part of the implementation. So that its throwing compile time error while declaring synchronized methods in interface.

Wednesday, June 24, 2015

IOException parsing XML document from class path resource

I have a Test File in the package com.springt.test and trying to execute this java test file I am getting this below exception.

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource "<path of application context.xml>"

The solution i got it from google search that applicationContext.xml file should be under the src directory instead of any other directory/package. So I  moved applicationContect.xml under src directory and got resolved.

Friday, June 5, 2015

Sample build.xml to create war file based on eclipse directory structure

Yesterday I got a chance to write sample build.xml for one of my colleague. He has default build.xml for his project which is written by someone based on random directories (similar to war directory structure). This build.xml is used to pack the directory sturctures and place it into the tomcat server webapp directory. In this type scenario he did not able to debugging his application from eclipse.

I suggested them to create one more build.xml based on eclipse directory structure for production or uat deployment. For development purpose try to setup a tomcat server and debugging your application in eclipse without worrying about deployment. I provided that sample build.xml below. Please look it and provide your comments.

<?xml version="1.0" encoding="UTF-8"?>
<project name = "tems" basedir = "." default = "war">
   
    <property name="project-name" value="${ant.project.name}" />
    <property name="builder" value="Achappan Mahalingam" />

    <property name="war-file-name" value="${project-name}.war" />
    <property name="source-directory" value="src" />
    <property name="classes-directory" value="build/classes" />
    <property name="web-directory" value="WebContent" />
    <property name="web-xml-file" value="WebContent/WEB-INF/web.xml" />
    <property name="libs-directory" value="WebContent/WEB-INF/lib" />
    <property name="build-directory" value="build" />


    <target name = "info">
          <echo message = ""/>
          <echo message = "${project-name} Build File"/>
          <echo message = "-----------------------------------"/>
          <echo message = "Run by ${builder}"/>
       </target>

    <target name="war" depends="info">
        <mkdir dir="${build-directory}" />
        <delete file="${build-directory}/${war-file-name}" />
        <war warfile="${build-directory}/${war-file-name}" webxml="${web-xml-file}">
            <classes dir="${classes-directory}" />
            <fileset dir="${web-directory}">
                <exclude name="WEB-INF/web.xml" />
            </fileset>
        </war>
    </target>
</project>