Pages

Wednesday, November 27, 2013

Java 7 Tutorial - For beginners

In Java 7, few minor language changes are introduced. It is not a major change like Java 5.

You can use underscores in numeric literals. For example the below is allowed in Java 7

private long reallyLongNumber = 1_000_000_000_000l;
private float entryFee = 10.5_5f;

There are certain rules on where you can use the underscore. 

Also to make the code more compact some un ncessary overheads has been removed. For example one of the overhead with generics is that if you want to define a hash table with Long value as key and ArrayList of Long as value you need to declare like this.

//Normally you have to declare like this
Hashtable<Long, ArrayList<Long>> employeeListByBank = new Hashtable<Long, ArrayList<Long>>();

The new Hashtable part also you need to repeat the samething which makes it bit difficult. In SE 7 you dont have to do that. You can just declare like this.

HashMap<String, ArrayList<String>> employeeListByBankInSE7 = new HashMap<>();

Which makes the program little less complex. I agree this is not a major improvement but reduces bit of coding.

Full example code below.

package com.ravi.java7learning;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;

public class Java7Improvements {

/**
* At the beginning or end of a number
*  Adjacent to a decimal point in a floating point literal
*  Prior to an F or L suffix
*  In positions where a string of digits is expected
*/
private long reallyLongNumber = 1_000_000_000_000l;
private float entryFee = 10.5_5f;
//private float wrongEntryFee = 10._55f; - This will give compilation error because adjacent to dot (.)

public static void main(String a[])
{
Java7Improvements instance = new Java7Improvements();
System.out.println("Long number with underscore allowed :"+instance.reallyLongNumber);
System.out.println("Float value with underscore :"+instance.entryFee);
}

private void lessVerboseForTypeArgumentsExample()
{
//Normally you have to declare like this
Hashtable<Long, ArrayList<Long>> employeeListByBank = new Hashtable<Long, ArrayList<Long>>();

//In SE 7 you can avoid this and declare like this
HashMap<String, ArrayList<String>> employeeListByBankInSE7 = new HashMap<>();

//This make the declaration less verbose. Note that you still need to provide the <> to make it
//generic.

HashMap<String, ArrayList<String>> withoutGenerics = new HashMap();

//Otherwise compiler will throw warning that, we are using raw type of hashmap.
}

}

Java 7 Tutorial - Try with Resources Example

In SE7 try/catch has been improved with the feature called try with resources option.
Normally when we use any resources (like File reader, Input stream etc) we need to close them explicitly to avoid performance penalties. Also you need to use finally block also in case if there are any exception happens before you close them.

For example when you try to read input from a file you normally code like this

/*
 * Normal try/catch block.
 */
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(
"c:\\tutorial\\HelloWorld.txt")));
String output = reader.readLine();
System.out.println("output :"+output);
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try {
if(reader != null)
{
System.out.println("finally block called :");
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

This is too much verbose and you have close the reader. If you forgot to close the reader then it unnecessarily blocks the resources and it will be a big performance bottleneck.

To avoid that SE 7 comes up with a feature called try with resources option. Here you open the resources with in try and once the code with in the try block completes, compiler automatically closes the opened resources so you dont have to close them explicitly.

try (BufferedReader reader1 = new BufferedReader(new FileReader(
new File("c:\\tutorial\\HelloWorld.txt")))) {
String output = reader1.readLine();
System.out.println("output in try with resource :"+output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Complete working example given below.

package com.ravi.java7learning;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Java7TryWithResources {

public static void main(String[] a)
{
Java7TryWithResources sample = new Java7TryWithResources();
sample.tryWithResourcesExample();
}

private void tryWithResourcesExample() {
/*
* Normal try/catch block.
*/
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File(
"c:\\tutorial\\HelloWorld.txt")));
String output = reader.readLine();
System.out.println("output :"+output);
reader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try {
if(reader != null)
{
System.out.println("finally block called :");
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try (BufferedReader reader1 = new BufferedReader(new FileReader(
new File("c:\\tutorial\\HelloWorld.txt")))) {
String output = reader1.readLine();
System.out.println("output in try with resource :"+output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Java 7 Tutorial - Strings in switch statement

In Java 7 you can use String in switch statement which was not possible before.

For example before SE 7 you have to use if, else if statements to compare the string values but now you can use Switch statements.

package com.ravi.java7learning;

public class Java7Feature {

public static void main(String[] a)
{
Java7Feature feature = new Java7Feature();
feature.switchDemo("No 1");
feature.switchDemoBeforeSE7("No 1");
}

private void switchDemoBeforeSE7(String input)
{
if(input.equals("No 1"))
{
System.out.println("You have entered :"+input);
} else if(input.equals("No 2")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 3")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 4")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 5")) {
System.out.println("You have entered :"+input);
} else {
System.out.println("You have entered something different :"+input);
}
}

private void switchDemo(String input)
{
switch(input)
{
case "No 1":
System.out.println("You have entered :"+input);
break;
case "No 2":
System.out.println("You have entered :"+input);
break;
case "No 3":
System.out.println("You have entered :"+input);
break;
case "No 4":
System.out.println("You have entered :"+input);
break;
case "No 5":
System.out.println("You have entered :"+input);
break;
default:
System.out.println("You have entered something different :"+input);
}
}

}



Java 7 Tutorial - Catching Multiple Exceptions

Java 7 allows catching multiple exceptions in the single catch block.
Prior to Java 7 if a method can create multiple exceptions then each
exception has to be handled seperatly.

So it must be
try
{
}
catch(IOException 1)
{
handleException(1);
}
catch(ParseException 2)
{
handleException(2)
}

This will lead to duplicate code in each catch block. Now with SE7 this can be
avoided and it can be handled in the same catch block.

package com.ravi.java7learning;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class SampleExceptionHandler {

public static void main(String a[])
{
try {
FileWriter writer = new FileWriter(new File("c:\\tutorial\\HelloWorld.txt"));
SimpleDateFormat format = new SimpleDateFormat();
Date parsedDate = format.parse("07/10/96 4:5 PM, PDT");
writer.write("HelloWorld");
writer.flush();
writer.close();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Tuesday, November 26, 2013

Spring interview questions

1) How do you use annotations with Spring & How do you instruct Spring to scan the source code to pick up the annotations?

In the spring context file these two elements has to be declared to instruct spring that, the project is using annotations & it needs to scan the packages to pick up those annotations and create objects.

<context:annotation-config />
<context:component-scan base-package="com.ravi" />

2) How do you do jndi lookup with Spring?

The simple way to do this is to use the jndi-lookup that comes with jee namespace. Example as below. You need to declare that name space also in the spring context file.

    <jee:jndi-lookup id="jms_connectionFactory"    resource-ref="true" jndi-name="jms/SAMPLE_CF"/>
   
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"    
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jee
                           http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
                          
3) How do you load property files with Spring?

You have property files in the application which you want to load to use in the application. You should use the property-placeholder element in the context namespace to do this. Example as below.

<context:property-placeholder location="classpath*:example.properties"
        order="1" ignore-unresolvable="true" />
       
log.file.location=c:\logfilelocation
jdbc.dialect=Oracle10g
hibernate.show_sql=true
       
In the application code you can use it like this to get a specific value of the property.
You should use @Value annotation to load the property.

@Service
public class ExamplePropertyLoader
{
@Value(value = "${log.file.location}")
String logFileLocation;
}

Please note for the above approach to work, the class has to be instantiated by spring through component scanning. For example if you create the instance of ExamplePropertyLoader the logFileLocation value will be loaded.  Also for static fields this approach will not work.

To use it in the spring context file itself you can use it like this

<property name="hibernateProperties">
<props>
    <prop key="hibernate.dialect">${jdbc.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>

4) How do you use one spring context file in another context file?

Spring supports a concept called import using which one context file can be imported in to another.For example you define database related spring configurations like data source lookup, property file look up in a separate context file and then import that in the other context file instead of repeating this in every context files.

For example the access-common-db-context.xml contains all the information about database and then you can import it using

<import resource="classpath:access-common-db-context.xml" />

5) Can you declare class level (instance) variables in Spring Controller?

Controllers are by default singleton classes. Meaning there will be only one instance. So if there are class level variables then, the values are shared across multiple requests. For example, if there is a counter variable in the controller and you increase the counter for each call. When user 1 calls the controller the value will be increased by 1 and when next user (user 2) calls the controller the value will be 2 because of this shared nature. So one should avoid declaring class level variables in the Controllers.

6) What are the mostly used annotations in Spring?

@Autowired
@Component
@Qualifier
@Value
@Controller
@RequestMapping

7) How do you configure transactions using Spring?

TBD

8) How do you handle exceptions in Spring MVC?

Spring comes with default exception resolvers. One way of handling exception is to extend the DefaultHandlerExceptionResolver class and override the doResolveException method.

    @Override
    protected ModelAndView doResolveException(final HttpServletRequest request,
            final HttpServletResponse response, final Object handler,
            final Exception ex) {
            ModelAndView mav = null;
            mav = new ModelAndView("error/errorpage");
            return mav;
            }
           
Once this exception resolver configured in the Spring context file, any uncaught exceptions automatically re-directed to this class and here it can be directed to an error page.

9) How do you externalize and configure message labels of screens in Spring MVC?

Use ResourceBundleMessageSource class to externalize the message labels used in your screens. There should be a file called screen_text in the classpath which contains the key and values.

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                   <value>screen_text</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage">
            <value>true</value>
        </property>
</bean>

Contents of screen_text

general.error.title=Sample Error Screen
general.error.message=There is a problem with the application. Contact system admin for further details.

10) How do you configure interceptors in Spring MVC?

Use interceptors tag that comes in the mvc name space to configure interceptors for your application. Once the interceptors configured in the context file, they are automatically invoked for every request.

<mvc:interceptors>      
        <bean class="com.ravi.web.interceptor.AuthInterceptor" />    
</mvc:interceptors>

This interceptor class has to extend HandlerInterceptorAdapter class. This HandlerInterceptorAdapter class provides the default implementation for preHandle, postHandle, afterCompletion, afterConcurrentHandlingStarted etc. If you want to check for example, every request has the logged in, user information you can do that
like this

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
     HttpSession session = request.getSession();
     if(session.get("loggedInUser") == null)
     return true;
}

Saturday, November 16, 2013

Webservices stubbing - generating responses


In certain situations, you need to create huge volume of test data xmls, test data responses. For example if your application is using some web service, to do performance testing of your application, you may need to stub the services. When you are stubbing the services you need large volume of test data responses to be created. Creating this manually is a time consuming process and error prone. Also if you have to change something and going and changing in each location is also a difficult task.

When I confronted with this scenario, I remembered about the Free Marker template (or FTL in short) engine I used in one of my assignments. The FTL template engine is a open source software which can read the templates in any format (normally .ftl format) and generate output files out of it.

A template is a file which has static and dynamic parts. The dynamic parts are marked as variables. For example, this is the response you want from a webservice but the employee id has to be different for each employee. You want to create 1000 employee responses from employee id 1 to 1000. Similarly you want the last name of the employee to be the employee id and the post code should be different.


<Employee>
 <Name>Ravi ${lastname}</Name>
 <Age>25</Age>
 <EmployeeId>${employeeid}</EmployeeId>
 <Address>${postcode}</Address>
</Employee>


Your template should like like above. Now in free marker you can generate this in few minutes.

I used Maven for building this project. So you need to have FTL dependency in your pom file. You can add the dependency to your POM file like this.


<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.20</version>
</dependency>

Now the code which generates this test xmls.


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TestDataGenerator {

public static void main(String[] args) {
 // Freemarker configuration object
 Configuration cfg = new Configuration();
 try {
 // Load template from source folder
 Template template = cfg.getTemplate("src/main/resources/employee.ftl");
 for (int i = 0; i < 1000; i++) {
 // Build the data-model
  Map data = new HashMap();
  data.put("employeeid", i + "");
  data.put("lastname", i + "");
  data.put("postcode", i + " WG");

  // File output
  Writer file = new FileWriter(new File("C:\\stubdata\\" + i+ ".xml"));
  template.process(data, file);
  file.flush();
  file.close();
 }
} catch (IOException e) {
 e.printStackTrace();
} catch (TemplateException e) {
 e.printStackTrace();
}
}
}
Once you run this code, you should be able to see, in the stubdata folder, you can see 1000 test xmls with values replaced.

Friday, November 8, 2013

Top 10 Spring 3 interview questions - Beginners

1) How do you use annotations with Spring & How do you instruct Spring to scan the source code to pick up the annotations?

In the spring context file these two elements has to be declared to instruct spring that, the project is using annotations & it needs to scan the packages to pick up those annotations and create objects.

<context:annotation-config />
<context:component-scan base-package="com.ravi" />


2) How do you do jndi lookup with Spring?

The simple way to do this is to use the jndi-lookup that comes with jee namespace. Example as below. You need to declare that name space also in the spring context file.

    <jee:jndi-lookup id="jms_connectionFactory"    resource-ref="true" jndi-name="jms/SAMPLE_CF"/>
   
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"    
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jee
                           http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
                          
3) How do you load property files with Spring?

You have property files in the application which you want to load to use in the application. You should use the property-placeholder element in the context namespace to do this. Example as below.

<context:property-placeholder location="classpath*:example.properties"
        order="1" ignore-unresolvable="true" />
       
log.file.location=c:\logfilelocation
jdbc.dialect=Oracle10g
hibernate.show_sql=true
       
In the application code you can use it like this to get a specific value of the property.
You should use @Value annotation to load the property.

@Service
public class ExamplePropertyLoader
{
@Value(value = "${log.file.location}")
String logFileLocation;
}

Please note for the above approach to work, the class has to be instantiated by spring through component scanning. For example if you create the instance of ExamplePropertyLoader the logFileLocation value will be loaded.  Also for static fields this approach will not work.

To use it in the spring context file itself you can use it like this

<property name="hibernateProperties">
<props>
    <prop key="hibernate.dialect">${jdbc.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>

4) How do you use one spring context file in another context file?

Spring supports a concept called import using which one context file can be imported in to another.For example you define database related spring configurations like data source lookup, property file look up in a separate context file and then import that in the other context file instead of repeating this in every context files.

For example the access-common-db-context.xml contains all the information about database and then you can import it using

<import resource="classpath:access-common-db-context.xml" />

5) Can you declare class level (instance) variables in Spring Controller?

Controllers are by default singleton classes. Meaning there will be only one instance. So if there are class level variables then, the values are shared across multiple requests. For example, if there is a counter variable in the controller and you increase the counter for each call. When user 1 calls the controller the value will be increased by 1 and when next user (user 2) calls the controller the value will be 2 because of this shared nature. So one should avoid declaring class level variables in the Controllers.

6) What are the mostly used annotations in Spring?

@Autowired
@Component
@Qualifier
@Value
@Controller
@RequestMapping

7) How do you configure transactions using Spring?

TBD

8) How do you handle exceptions in Spring MVC?

Spring comes with default exception resolvers. One way of handling exception is to extend the DefaultHandlerExceptionResolver class and override the doResolveException method.

    @Override
    protected ModelAndView doResolveException(final HttpServletRequest request,
            final HttpServletResponse response, final Object handler,
            final Exception ex) {
            ModelAndView mav = null;
            mav = new ModelAndView("error/errorpage");
            return mav;
            }
           
Once this exception resolver configured in the Spring context file, any uncaught exceptions automatically re-directed to this class and here it can be directed to an error page.

9) How do you externalize and configure message labels of screens in Spring MVC?

Use ResourceBundleMessageSource class to externalize the message labels used in your screens. There should be a file called screen_text in the classpath which contains the key and values.

<bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                   <value>screen_text</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage">
            <value>true</value>
        </property>
</bean>

Contents of screen_text

general.error.title=Sample Error Screen
general.error.message=There is a problem with the application. Contact system admin for further details.

10) How do you configure interceptors in Spring MVC?

Use interceptors tag that comes in the mvc name space to configure interceptors for your application. Once the interceptors configured in the context file, they are automatically invoked for every request.

<mvc:interceptors>      
        <bean class="com.ravi.web.interceptor.AuthInterceptor" />    
</mvc:interceptors>

This interceptor class has to extend HandlerInterceptorAdapter class. This HandlerInterceptorAdapter class provides the default implementation for preHandle, postHandle, afterCompletion, afterConcurrentHandlingStarted etc. If you want to check for example, every request has the logged in, user information you can do that
like this

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
     HttpSession session = request.getSession();
     if(session.get("loggedInUser") == null)
     return true;
}

Thursday, November 7, 2013

Maven in 15 Minutes - Maven Top Interview Questions

What is Maven?

In simple terms, Maven is a build tool

How Maven is different from other build tools?

Maven makes building a project very simple. The complex part of the build process is gathering all the required jar files which maven takes care automatically through a concept called dependency management. Also Maven comes up with pre-defined packaging mechanisms for Jar,War,Ear which makes the build process really simple.

What is a POM file?

Maven needs a configuration file called POM (Project Object Model) to know the information about the project to be build. Maven proposes standard way of storing the source code, test code and configuration files. If the project is structured this way then lot of things are automatically taken care by Maven.

What are the basic elements in a POM file?

POM file is a XML file. The basic POM file contains the GroupId, ArtifactId, Version

<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>com.ravi.sample</groupId>
  <artifactId>my-project</artifactId>
  <version>1.0</version>
</project>

What is the standard maven project structure?

-src
--main
---java
--test
---java
--resources

What is a Maven Plug-in?

Each of the activities in the build process is done through a different components. These components are called plug-ins in Maven terms. For example compiling is done through a plug-in called compiler plug-in.
Creating a war file is done through maven war plug-in.

What is dependency management?

Any java code need or depend on additional Jar files apart from what is availble in JDK. Maven makes building a project really easy by automatically downloading these jar files once the required Jar files are declared in the POM file.

What are the mostly used Maven commands on a day to day basis

Mvn install - Compiles the projects, Run the tests if there are any and generates the build artifacts.

Mvn clean - Cleans the project and removes all the build artifacts created.

How to integrate Maven with Source control system

The SCM tag in the pom file.

<scm>
    <connection>scm:svn:http://somerepository.com/svn_repo/trunk</connection>
    <developerConnection>scm:svn:https://somerepository.com/svn_repo/trunk</developerConnection>
    <url>http://somerepository.com/view.cvs</url>
<scm>

Mvn Release:prepare - Prepares to release the project.

Mvn Release:perform - Uploades the artifacts to the repository

What are the best practices in Maven setup

1) Use Parent POM with out exception and define all the common things there.
Common things here are

- properties
- dependency management
- scm
- distribution management
- repositories

2) Dont explicitly mention the version numbers of the dependency jar files in the POM files
except in the parent pom files. Mention version numbers in the parent POMs.

In the parent pom file the dependency management tag is used to define all the dependency jar files with
version numbers.  If this parent pom file is used in all the other pom files in the project then
you dont have to change the version number in each and every pom file.

 
Blogger Templates