Tag Archives: Java

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.

Checked vs Unchecked exceptions

Exceptions in Java can be broadly categorized into checked and unchecked exceptions. A checked exception is one for which compiler will force you to handle it (either catch it, or throw it back), whereas for an unchecked exception you are not forced to provide handler. So when you are creating a new exception, you can decide whether it is a checked (extending a checked exception) or unchecked exception (extending unchecked exception).

Now the challenge is, how to decide if an excpetion should be checked or unchecked. That is tricky.

“Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.”

And to sum it up

“Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.”

Text Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

Split a String in controlled manner

You must have used String’s split method a lot of time to split based on a regex or a simple character or sub-string. But did you know that you can apply the split function in controlled manner. i.e. you can specify how many time split should occur or number of max sub-strings you can expect.

Example if I have string boo:and:foo and I will control number of splits to 2 like str.split(“:”,2), I will get 2 substrings, “boo” and “and:foo”.

Read more – http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29

JPA- Java Persistence API

From the very beginning of software development and more so with web applications, the need for storing state and details of objects have been there. The most used manner to store information has been databases. And with storing data into database, need for a standardized way to store this data has been felt.

The most common way to persist data into database is JDBC, i.e. Java Database connectivity. JDBC is Java Specific implementation of ODBC (Open Database Connectivity). It allows simple way for Java to execute SQL commands and interact with Database. Though it is easy to use, JDBC has a major challenge of SQL portability across Database vendors. The SQL command which works fine for oracle might now work for mysql or ms-sql.

Another popular approach for data persistence is ORM or object relational mapping. The idea is to map Java objects (POJOs) directly to a table in database. There are many strong players like Toplink (now eclipse link) and hibernate in this space.

Then came another important player EJB- entity beans. With EJB 2.0, support for persistence was good, but at cost of implementing complex EJBs.

There is another specification for persistence, JDO, Java Data Objects, which is mostly used to save Objects directly and hence make a good case for non relational or no-sql database usage.

Because of all the above mentioned options available for persistence in Java, need for standards became very important, which resulted first in JPA 1.0 and later a more complete specification in form of JPA 2.0.