Tuesday, 24 April 2012

Create Flex Project with Maven

Lately i have been compiling and managing my Flex projects with Flash Builder but it didn't sound like something cool. So decided to go for some build tool to help me build my projects from anywhere without any dependency on Flash Builder. Ant works fine on this but is too old to give a shot. So maven is a natural candidate as i have also been using maven to build my Java Projects.

Here is the maven command to create a Flex Project.
mvn archetype:generate 
-DarchetypeRepository=http://repository.sonatype.org/content/groups/public 
-DarchetypeGroupId=org.sonatype.flexmojos 
-DarchetypeArtifactId=flexmojos-archetypes-library 
-DarchetypeVersion=3.6.1  
-DgroupId=com.bharat.test.projectName 
-DartifactId=my-flex-application 
-DinteractiveMode=false

Change the archetypeVersion if a newer version is available. Check following maven repo and use the latest stable version
https://repository.sonatype.org/content/groups/public/org/sonatype/flexmojos/flexmojos-archetypes/

Build using following maven command. (skip tests if you are not ready with them.)
mvn clean install -Dmaven.test.skip=true

For running unit tests read more here.

https://docs.sonatype.org/display/FLEXMOJOS/Running+unit+tests


Reference
http://www.sonatype.com/books/mvnref-book/reference/flex-dev-sect-creating-with-archetype.html#ex-flex-dev-app-pom

Friday, 20 April 2012

Reading and writing propertis file

Properties file is a simple text file with extension .properties generally used to store projects configurations like database connection details and text labels in case project is a web application.

Here is a sample to read data from a properties file and then write it back to an xml file.

I have a properties file named test.properties with one entry as below.
// test.properties
msg1=hello bharat, this is comming from properties file.

package com.bharat.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.Properties;


public class ReadWritePropertiesFile
{

  public static void main(String... args) throws Exception
  {
    Properties props = new Properties();
    props.load(new FileReader("test.properties"));
    System.out.println(props.get("msg1"));
    
    props.put("msg2", "This was written to properties file from java");
    
    
    OutputStream os = new FileOutputStream(new File("test.xml"));
    props.storeToXML(os, "my test comment");
  }
} 
 
This is the xml file where properties get written to.
// test.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>my test comment</comment>
    <entry key="msg2">This was written to properties file from java</entry>
    <entry key="msg1">hello bharat, this is comming from properties file.</entry>
</properties>

I prefer storing ddl sql statements in a xml properties file as queries are formatted and readable.

Thursday, 19 April 2012

Tomcat Startup Error: Error in dependencyCheck

SEVERE: Error in dependencyCheck
java.util.zip.ZipException: too many length or distance symbols
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:147)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:146)
    at java.util.jar.JarInputStream.read(JarInputStream.java:177)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
    at java.util.jar.JarInputStream.getBytes(JarInputStream.java:88)
    at java.util.jar.JarInputStream.<init>(JarInputStream.java:65)
    at java.util.jar.JarInputStream.<init>(JarInputStream.java:43)
    at org.apache.catalina.util.ExtensionValidator.getManifest(ExtensionValidator.java:378)
    at org.apache.catalina.util.ExtensionValidator.validateApplication(ExtensionValidator.java:189)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4530)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Apr 19, 2012 12:58:21 PM org.apache.catalina.core.StandardContext start
SEVERE: Error getConfigured
Apr 19, 2012 12:58:21 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/rde] startup failed due to previous errors
Apr 19, 2012 12:58:21 PM org.apache.catalina.core.StandardContext stop
INFO: Container org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/rde] has not been started
Apr 19, 2012 12:58:21 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor host-manager.xml
Apr 19, 2012 12:58:21 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor manager.xml
Apr 19, 2012 12:58:21 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive rdt-reference-gui-server.war
Apr 19, 2012 12:58:21 PM org.apache.catalina.core.StandardContext start


I was getting above error while starting tomcat, due to this error my tomcat started but the application was not up.

Resolution
The problem was with the MENIFEST.MF file. I checked my project's menisfest file but it was correct.
I later resolved this error by checking my dependencies, few of the jars were corrupt and i was not able to open their MENIFEST.MF file.

I replaced those jars with the newer ones and also removed a few jars that were really not required. 
Also note that in a MANIFEST.MF file the length of characters per row should not exceed 70.

Friday, 13 April 2012

Read Excel File Using Apache POI

Here is some nice code snippet to read Excel file using Apache POI Api.
Download Apache POI form here
Create a project in eclipse and add following jars in your classpath. (Not all are required for this example)
poi-3.8-20120326.jar
poi-examples-3.8-20120326.jar
poi-excelant-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
commons-logging-1.1.jar
junit-3.8.1.jar
log4j-1.2.13.jar
package com.bharat.poi;

package com.bharat.poi;

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

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile
{
  public static void main(String... args)
  {
    // name of Excel file you want to read.
    String fileName = "bond-2-8.xlsx";
    
    // Read an Excel File and Store in an ArrayList
    ArrayList<ArrayList<XSSFCell>> dataHolder = readExcelFile(fileName);
    
    // Print the data read
    printCellDataToConsole(dataHolder);
  }

  public static ArrayList<ArrayList<XSSFCell>> readExcelFile(String fileName)
  {
    /**
     * --Define a List --Holds List Of Cells
     */
    ArrayList<ArrayList<XSSFCell>> cellListHolder =
        new ArrayList<ArrayList<XSSFCell>>();

    try
    {
      /* Creating Input Stream */
      FileInputStream myInput = new FileInputStream(fileName);

      /* Create a workbook using Stream */
      XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);

      /* Get the first sheet from workbook */
      XSSFSheet mySheet = myWorkBook.getSheetAt(0);

      /* iterate through the cells. */
      
      Iterator rowIter = mySheet.rowIterator();

      while (rowIter.hasNext())
      {
        XSSFRow myRow = (XSSFRow) rowIter.next();
        Iterator cellIter = myRow.cellIterator();
        ArrayList<XSSFCell> cellStoreList = new ArrayList<XSSFCell>();
        while (cellIter.hasNext())
        {
          XSSFCell cell = (XSSFCell) cellIter.next();
          cellStoreList.add(cell);
        }
        cellListHolder.add(cellStoreList);
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return cellListHolder;
  }

  /**
   * prints data to console
   * 
   * @param dataHolder
   */
  private static void printCellDataToConsole(ArrayList<ArrayList<XSSFCell>> dataHolder)
  {

    for(ArrayList<XSSFCell> cellList : dataHolder)
    {
      for(XSSFCell cell: cellList)
      {
        String stringCellValue = cell.toString();
        System.out.print(stringCellValue +"\t");
      }
      System.out.println();
    }

  }
}


Thursday, 16 February 2012

try-with-resources in java 7

Java 7 introduces try-with-resources block in order to avoid resource leak and code blot in the finally block to close the resources you opened in the try block.
Example:

package com.bharat.io;

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

public class TryWithResourceExample
{

  public static void main(String... args)
  {
    try (BufferedReader reader = new BufferedReader(new FileReader("C:\\test.txt")))
    {
      String line;
      while((line = reader.readLine()) != null)
      {
        System.out.println(line);
      }
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }
}

System Properties in java

To obtain properties of system on which your program is running:
import java.util.Map;

class ShowProperties {
    public static void main(String[] args) {
        for (Map.Entry e : System.getProperties().entrySet()) {
            System.out.println(e);
        }
    }
}
You can use following to get the underlying OS name
System.getProperty("os.name")

Wednesday, 1 February 2012

Collections

Important Interfaces and classes in the Collections Framework


Interfaces:
  1. Collections
  2. Set
  3. SortedSet
  4. List
  5. Map
  6. SortedMap
  7. Queue
  8. NavigableSet
  9. NavigableMap
 
Concrete core 13 Implementation Classes

  1. Maps
    1. HashMap
    2. HashTable
    3. TreeMap
    4. LinkedHashMap
  2. Sets
    1. HashSet
    2. LinkedHashSet
    3. TreeSet
  3. Lists
    1. ArrayList
    2. Vector
    3. LinkedList
  4. Queues
    1. PriorityQueue
  5. Utilities
    1. Collections
    2. Arrays

Not all collections implement the Collection interface eg. none of the map related classes and interfaces extend from Collections. Hence they do not pass Is-A relationship test for collections.

so HashMap, HashTable, TreeMap and LinkedHashMap do not implement Collection Interface.

Note: Collection is an interface while Collections is a concrete Utility class with static methods.

Fig. below shows the inheritance hierarchy for the Collections Framework.


There are 4 basic types of collections:
  • Lists - List of items
  • Sets - Unique instances
  • Maps - Key-Value pairs
  • Queues - Maintain an order
 Sorting and Ordering of Collections:
 Sorting is a type of ordering.

Ordered:
When a Collection is ordered you may iterate through the collection in a specific order. An ArrayList is ordered by element's index position however a HashTable collection is not ordered. You won't find any specific order when you iterate over the HashTable.
A LinkedHashSet keeps the order established by insertion, so the the last element inserted is the last element in the LinkedHashSet as opposed to an ArrayList where you can insert an element at any index position.
There are some collection that keep a natural order of the elements. These collections are not only Ordered but sorted.

Sorted:
A sorted collection means that the order in the collection is determined by some rule based on the properties of the object themselves and has nothing to do with when an object was inserted or accessed last time or at what position it was inserted.
You put the object in collection and collection will determine what order to put them in based on the sort order. A collection like any List which maintains an order based on insertion is not called sorted unless it arranges it's elements using some sort order. Mostly the sort order used is something called the natural order.

We know how to sort alphabetically; A comes before B and F comes before G and so on. So for a collection of String the natural order is alphabetical and for collections with integer values the natural order will be numeric ie. 1 comes before 2 and so on... But what if a collection contains an Employee object? there is no way a collection can determine the ordering of an Object unless we provide through an interface called Comparable that determines how instances of a class can be compared to one another.
The developer decides how an Object object should be compared to other using one or more instance variables.
Apart from the order as specified by the Comparable interface you can also define different sort orders using Comparator interface


List Interface
A List cares about index. One thing that Lists have and other collections don't is a set of method related to index position. These key methods include
get(int index), indexOf(Object o), add(int index, Object obj)
All three List implementations are ordered by index positions. A position that you determine either by setting object at a specific index or by adding it without specifying index, in which case the object is added to the end.

ArrayList
ArrayList is a growable array. It provides fast iteration and fast random access. It is an ordered collection (by index) and not sorted. Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.

Vector
Vector is a legacy collection that comes from the earlier days of java not widely used today. It is similar to ArrayList but Vector methods are Synchronized for Thread safety. Prefer using ArrayList as Synchronized methods causes performance hit you might not need. If you need thread safety in your collection use utility methods from Collections. Vector is the only class other than ArrayList to implement random access.

 LinkedList
A LinkedList is ordered by index position like Arrays, except the elements are doubly linked to each other. This linkage gives you new methods for adding and removing form beginning and end which makes it an easy choice for implementing a stack or queue. A LinkedList iterates more slowly than the ArrayList but is a good choice when you need faster insertion and deletion. LinkedList class has been enhanced to implement java.util.Queue Interface thereby implementing common queue methods peek(), poll() and offer()

Set Interface
A set doesn't allow duplicates and the equals() method takes care of determining whether two objects are identical. Following are the three Set implementations.

HashSet
A HashSet is an unsorted, unordered Collection. It uses HashCode of object being inserted, so more efficient your hashcode implementation the better access performance you will get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

LinkedHashSet
A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

TreeSet
The TreeSet is is a sorted collection based on the Red-Black tree structure, and guarantees that the
elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator. As of Java 6, TreeSet implements NavigableSet.

Map Interface
A Map is based on unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are objects. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

HashMap
The HashMap is an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient
your hashCode() implementation, the better access performance you'll get. HashMap allows one null key and multiple null values in a collection.


Hashtable
Like Vector, Hashtable has existed from prehistoric Java times. Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

LinkedHashMap
Like its Set counterpart, LinkedHashSet, the LinkedHashMap collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

TreeMap
TreeMap is a sorted Map "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered. As of Java 6, TreeMap implements NavigableMap.

Queue Interface
A Queue is designed to hold a list of things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

PriorityQueue
This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.

Monday, 16 January 2012

Restful web services using jersey

Introduction

This is a tutorial explaining how to write Restful web services using Jersey on Tomcat.

What is REST

REST is a software architectural style as described by Roy Fielding in his PhD dissertation published in 2000. It stands for REpresentational State Transfer. REST by itself is not an architecture but a set of constraints that, when applied to the design of a system, creates a software architectural style.
Following constraints define a RESTful system:
  • It must be a client-server system
  • It has to be stateless - there should be no need for the service to keep user's sessions, in other words, each request should be independent of others.
  • It has to support a caching system - the network infrastructure should support cache at different levels.
  • It has to be uniformly accessible - each resource must have a unique address and a valid point of access.
  • It has to layered - it must support scalability
  • It should provide code on demand - although this is an optional constraint, application ban be expandable at runtime by allowing the downloading of code on demand, for example, java applets. 
More to follow soon...


Download a Jersey sample application from here

Sample application is an employee service spitting data in xml and html formats
download zip file and import in eclipse ide.
run Main.java, you won't need a server for this, just run it as a java application.

On your favorite browser try following urls: