Category Archives: Java

Using Mybatis with Spring

Mybatis is Java Persistence framework, build upn JDBC. I look at it mostly as a bridge between conventional JDBC and an ORM solution like hibernate. The flexibility Mybatis provide is to write queries similar to JDBC, yet takes away all the complexity and boilerplate code for creating and maintaining connections and transactions. It can also map your objects to Tables like ORM solution, without getting into complexities of an ORM fraework, but at a cost of some additional code.

Mappers: Mappers are core of Mybatis implementation. A Mapper class would contain queries to be executed by mybatis. A good practice is to create a mapper for each table in database.

Here is a simple Mapper class

public interface UserMapper {

	/**
	 * This method validates the credentials for any user.
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	@Select("select id from myuser where username=#{userName} and password=#{password}")
	public Integer verifyAdminUser(@Param("userName") String userName,
			@Param("password") String password);

	/**
	 * This method returns list of all users.
	 * 
	 * @return
	 */
	@Select("select username, password from myuser")
	public List getUsers();

In the getUsers method, you can see mybatis will automatically convert the results into a Java List with User objects.

Coming to Setting up Mybatis with Spring, if you are using Java based configuration, all you need to add is

@MapperScan("com.test.mapper")

and tell location of your mappers package(s).

In addition you would want spring to manage transactions for you by

@MapperScan("com.test.mapper")
public class MyConfig implements TransactionManagementConfigurer{

//JNDI lookup for database
private DataSource getDataSource() {
		InitialContext ic;
		DataSource ds = null;
		try {
			ic = new InitialContext();
			String jndiName ="jndi";
			ds = (DataSource) ic.lookup(jndiName);
		} 
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return ds;
	}

	 @Bean
		public SqlSessionFactory sqlSessionFactory() throws Exception {
			org.apache.ibatis.mapping.Environment environment = new org.apache.ibatis.mapping.Environment("",
					new JdbcTransactionFactory(), getDataSource());
			org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(environment);

			return new SqlSessionFactoryBuilder().build(config);
		}

	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return  new DataSourceTransactionManager(getDataSource());
	}

You are all set to use Mappers just by Autowiring in any class.

Spring Security- with Java Configuration

Recently I wrote about getting started with Spring Security. In that, I used XML configurations for spring security. As a Java developer, I normally prefer Java configuration with Spring than XML. So here is how we can move from XML configuration to Java configuration.

Firstly I tell my web.xml that I want to use Java file based configuration and provide configuration class.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>javaee</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.myapp.config.MyConfig</param-value>
    </context-param>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.myapp.config.MyConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

</web-app>

Here is a simple contoller path which I need to secure

package com.myapp.test;

import java.io.IOException;

import javax.servlet.ServletException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/sample")
public class SampleService {
	@RequestMapping(method = RequestMethod.GET, value = "/hello")
	public ModelAndView LepService(@PathVariable("id") String id)
			throws ServletException, IOException {

		ModelAndView mv = new ModelAndView("hello");
		// Do something here
		return mv;
	}
}

As you can see this simply redirects to hello view (hello.jsp).

And here the configuration file.

@Configuration
@EnableWebMvc
@EnableWebSecurity
@ComponentScan(basePackages = "com.myapp.test")
public class MyConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public UrlBasedViewResolver urlBasedViewResolver() {
		UrlBasedViewResolver res = new InternalResourceViewResolver();
		res.setViewClass(JstlView.class);
		res.setPrefix("/WEB-INF/");
		res.setSuffix(".jsp");

		return res;
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**");
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.inMemoryAuthentication().withUser("user").password("password")
				.roles("USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll()
				.antMatchers("/sample/**").hasRole("USER").anyRequest().authenticated()
				.and().formLogin();
	}
}

Spring Security- Getting started

In last post I wrote about implementing a simple authentication and authorization code using filters to provide security to your web application.

Well, Spring security is there to make our life easier.

Lets take a very simple example of hello world application.

Simply create a new web application (in eclipse dynamic web application, cover to maven application to use maven).

Modify Web.xml

<servlet>
<servlet-name>controlServlet</servlet-name>
<servlet-class>com.spring.test.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>controlServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

And create HelloWorld.java

package com.spring.test;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet (urlPatterns ={"/hello" } )
public class HelloWorld extends HttpServlet {

@Override
public void doGet (HttpServletRequest request , HttpServletResponse response){
try {
response.getWriter( ).write( "Hello World" ) ;
} catch(IOException e) {
e.printStackTrace( ) ;
}
}
}

Only dependency added to maven

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

Build using maven and execute on any webserver. The /hello url will show a Hello World Message.

Lets add some security to this application now using Spring Security.

Tell your maven about Spring Jars

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

Add to web.xml

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

And create spring-security.xml inside WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/hello" access="ROLE_ADMIN" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_ADMIN" name="kamal" password="kamal" />
<security:user authorities="ROLE_ADMIN" name="admin" password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>

JVM: Memory management and Garbage collection

If you have looked into server configuration files, you would have seen terms like –

-Xms512m -Xmx1536m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=786m -XX:MaxPermSize=1024m -XX:+UseConcMarkSweepGC

These are parameters we use to set up heap memory use by JVM to store objects in memory and make sure effective usage of garbage collection.

Garbage Collection:
Garbage collection or GC in Java is a way in which JVM reclaims the space in heap occupied by objects no longer in use. This is achived by Java in Mark and Delete approach (Mark objects no longer in use and then delete the marked objects, optionally compacting the survived objects to make all available space together for better usage).

Heap Memory: All the objects created by JVM are added to heap memory. -Xms512m defines the minumum heap memory requested by JVM and -Xmx1536m defines maximum.

Yound and Old Generation: Further heap memory is divided into 2 blocks- young generation and old generation for optimum GC. Young generation memory contains the newly generated objects and old generation contains older objects. The idea is that the newly created objects will be more prone to GC. The objects which have survived a few GC cycles (they are still in use), have more probability of surviving future GC cycles. A minor GC runs frequently which will clean up the young generation heap. The major GC runs less frequently and cleans up whole healp including old generation area.

-XX:NewSize=512m and -XX:MaxNewSize=512m defines memory setting for young generation GC.

Eden and Survivor: Young generation heap area is further divided into Eden space and survivor space. A newly created object is placed in Eden space and moves to survivor space if it survives a GC. A survivor space object which has survived multiple GCs is then moved to Old Generation area.

Stack memory: Apart from Heap memory, JVM also has stack memory which is allocated to a thread of execution and store local primitive variable and reference to variables in heap for that particular thread. Stack memory works in LIFO fashion and is short lived. Normally it is very small in size ~1mb by default, but can be set using -Xss flag.

Error:
OutOfMemoryError is thrown by JVM when it runs out of heap and StackOverFlowError is thrown when stack memory is full.

Permanent Generation:
Perm Gen is area where JVM defines application metadata about classes and methods. This is not part of heap memory. Can be set using -XX:PermSize=786m and -XX:MaxPermSize=1024m

GC Algorithms:
There are various algorithms which can be used by JVM while GC. For example -XX:+UseConcMarkSweepGCin above cofiguration tells JVM to use concurrent mark sweep algo, which helps GC in parallel to application execution, hence low impact visible on application – read here. With Java 7, we have Garbage-First Collector option, which helps further by splitting heap in multiple areas and doing GC with minimum impact on application- read here.

Useful reads

http://pubs.vmware.com/vfabric52/index.jsp?topic=/com.vmware.vfabric.em4j.1.2/em4j/conf-heap-management.html

http://www.journaldev.com/2856/java-jvm-memory-model-and-garbage-collection-monitoring-tuning

https://blog.codecentric.de/en/2014/01/useful-jvm-flags-part-8-gc-logging/

Adding Maven Jars to final war

There might be a requirement to let the war file include all maven dependencies (jars downloaded through maven) to avoid adding them manually to server, especialy while development time.

Right click project -> properties-> Deployment Assembly-> add ->build path entries->maven dependencies

Reference- http://stackoverflow.com/questions/6083501/maven-dependencies-not-visible-in-web-inf-lib

A simple cache utility class in Java

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * This class maintains in memory cache. 
 * @author kamalmeet
 *
 */

public class CommonCache {
	
	//The map that will store the cache
	private static Map<String, Object> cache=null;
	
	private static CommonCache reportCache=new CommonCache();
	
	/**
	 * Make sure the class is singleton so only one instance is shared by all. 
	 */
	private CommonCache()
	{
		cache=Collections.synchronizedMap(new HashMap<String, Object>());
	}
	
	/**
	 * Get the singleton instance.
	 * @return
	 */
	public static CommonCache getInstance()
	{
		return reportCache;
	}
	
	/**
	 * Add new element to cache.
	 * @param key
	 * @param value
	 */
	public void addToCache(String key, Object value)
	{
		cache.put(key, value);
	}
	
	/**
	 * Remove an element from cache.
	 * @param key
	 */
	public void removeFromCache(String key)
	{
		cache.remove(key);
	}
	
	/**
	 * Clean up cache.
	 */
	public void invalidateCache()
	{
		cache=Collections.synchronizedMap(new HashMap<String, Object>());
	}
	
	/**
	 * Get the element from cache.
	 * @param key
	 * @return
	 */
	public Object getFromCache(String key)
	{
		if(cache.containsKey(key))
			return cache.get(key);
		else
			return null;
	}
	
}

Returning auto generated id in spring – mybatis

Faced a problem with returning the autogenerated id for new rows being created for a postgres table through spring – mybatis.

@Insert("insert into user (name) values (#{name})")
public void insertActor(User user);

One solution ofcourse was to simply get nextval from the sequence, but I wanted something cleaner where I need not be worried about multithreading issues.

Solution one Tried: One good solution found for postgres was using “Returning” keyword with Insert statement

insert into user (name) values (#{name}) Returning id;

Somehow that did not work with mybatis.

Solution that worked:

@Options(useGeneratedKeys=true, keyProperty = "userId", keyColumn="id")
@Insert("insert into user (name) values (#{name})")
public void insertActor(User user);

@Options, with useGeneratedKeys flag worked just fine. keyProperty defined the property name in Java and keyColumn name defined name of column in table.

Java- How to read an xlsx file

Here is a sample code to read xlsx file from java

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UploadSchools {

public static void main(String s[])
{
UploadSchools u=new UploadSchools();
u.readExcel(“/home/kamalmeet/schools.xlsx”);
}

public void readExcel(String path)
{
try{

File file = new File(path);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
Row currentRow = rows.next();

Iterator cells = currentRow.cellIterator();
while (cells.hasNext()) {

Cell currentCell = cells.next();
System.out.print(currentCell.toString()+”\t”);
}
System.out.println(“”);
}
workBook.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Note that I am simply printing string value of the cells. You can check the cell type and read the value accordingly. For example, add following utility method

private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + “”;
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + “”;
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + “”;
}
else {
return null;
}
}

References :

http://stackoverflow.com/questions/12526310/returning-decimal-instead-of-string-poi-jar

http://java67.blogspot.in/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html

Understanding Maven

Official definition of Maven states “Apache Maven is a software project management and comprehension tool.” For me, Maven is a build tool, that helps me manage dependencies as well. The advantage I get over Ant tool, is that it not only manages dependencies, but also downloads them automatically. Also I need not worry about transitive depeendies, that is if a jar I need for my project is inturn dependent on other jars, maven will take care of it for me.

Getting started: Using maven with Eclipse is simple. Eclipse comes with embedded maven so you need not worry about downloading or installing.

In New->Project, you can select Maven Project. It will ask you to select Archtype. An Archtype is predefine project templates. For example you can use Spring project, you can choose spring archtype. This will help you getting started by providing a sample template project, on which you can build further.

Once you create a project, you will find a pom.xml. POM stands for Project Object Model. It is fundamental Unit of Work in Maven.

A simple POM file might look like

<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>TEST</groupId>
<artifactId>TEST</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Permission</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Note the dependencies part. This is telling the maven which version of the required dependency is needed by application.