dineshonjava

Sorting in collection framework

We can sort the elements of:
  1. String objects
  2. Wrapper class objects
  3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements must be of Comparable type.
Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects-
import java.util.*;
class Simple12{
public static void main(String args[]){

ArrayList al=new ArrayList();
al.add("Dinesh");
al.add("Sweetu");
al.add("Adesh");
al.add("Vinesh");

Collections.sort(al);
Iterator itr=al.iterator();

while(itr.hasNext()){
System.out.println(itr.next());
 }
}

}

Output:
Adesh
Dinesh
Sweetu
Vinesh

Example of Sorting the elements of List that contains Wrapper class objects
import java.util.*;
class Simple12{
public static void main(String args[]){

ArrayList al=new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);//internally will be converted into objects as Integer.valueOf(230)

Collections.sort(al);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
 }
}
}

Output:
101
201
230



<<Previous <<   || Index ||   >>Next >>


Difference between HashMap and HashTable in Java

  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the Hashtable is fail-safe because enumerator for the Hashtable is not throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms


  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
ParameterHashmapHashtable
SynchronizedNot SyncronizedSyncronized
Null key and ValueAllows one null key and any number of null valuesNot allow null keys or values
Fail fastIterator in Hashmap is fail fastEnumeration in Hashtable is not fail fast
ThreadSafeNoYes
ExtendsExtends AbstractMap classExtends Dictionary class
PerformanceFaster then HashtableSlower then Hashmap


Note - You can synchonized a HashMap with the help of Collections.synchonizedMap(hashmap)
Map map=Collections.synchonizedMap(hashmap)
Syncronized →Being synchronized means that operation is thread safe, so only one thread can access the table at a time.

Fail safe - Fail-fast means when you try to modify the content when you are iterating, it will throw ConcurrentModification Exception and fail immediately.

For HashMap Itration:
Set keys = hashMap.keySet();
for (Object key : key) {
    hashMap.put(someObject, someValue); //it will throw the ConcurrentModificationException
}
For HashTable Enumeration:
Enumeration keys = hashTable.keys();
 for (Enumeration e = v.elements() ; e.hasMoreElements() ; e.nextElement()) {
      hashTable.put(someKey, someValue); //it works
 }


<<Previous <<   || Index ||   >>Next >>

Hashtable class in collection framework

  • A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

Constructors:


The Hashtable defines four constructors. The first version is the default constructor:
Hashtable( )
The second version creates a hash table that has an initial size specified by size:
Hashtable(int size)
The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio.

This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward.
Hashtable(int size, float fillRatio)
The fourth version creates a hash table that is initialized with the elements in m.

The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used.
Hashtable(Map m)
Methods:
Apart from the methods defined by Map interface, Hashtable defines following methods:
SNMethods with Description
1void clear( )
Resets and empties the hash table.
2Object clone( )
Returns a duplicate of the invoking object.
3boolean contains(Object value)
Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
4boolean containsKey(Object key)
Returns true if some key equal to key exists within the hash table. Returns false if the key isn't found.
5boolean containsValue(Object value)
Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
6Enumeration elements( )
Returns an enumeration of the values contained in the hash table.
7Object get(Object key)
Returns the object that contains the value associated with key. If key is not in the hash table, a null object is returned.
8boolean isEmpty( )
Returns true if the hash table is empty; returns false if it contains at least one key.
9Enumeration keys( )
Returns an enumeration of the keys contained in the hash table.
10Object put(Object key, Object value)
Inserts a key and a value into the hash table. Returns null if key isn't already in the hash table; returns the previous value associated with key if key is already in the hash table.
11void rehash( )
Increases the size of the hash table and rehashes all of its keys.
12Object remove(Object key)
Removes key and its value. Returns the value associated with key. If key is not in the hash table, a null object is returned.
13int size( )
Returns the number of entries in the hash table.
14String toString( )
Returns the string equivalent of a hash table.

Example of Hashtable:
import java.util.*;
class Simple{
 public static void main(String args[]){
 
  Hashtable hm = new Hashtable();

  hm.put(100,"Dinesh");
  hm.put(102,"Sweety");
  hm.put(101,"Ankit");
  hm.put(103,"Nimmo");

  Set set = hm.entrySet();
  Iterator itr = set.iterator();

  while(itr.hasNext()){
   Map.Entry m=(Map.Entry)itr.next();
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit


<<Previous <<   || Index ||   >>Next >>


Difference between TreeMap vs HashMap

Both TreeMap & HashMap are two different implementation of the Map interface. Even though this post is titled “TreeMap vs HashMap” I would like to say how they are connected and how much similar they are.

Both TreeMap & HashMap are not synchronized. To make it synchronized we have to explicitly call Collections.synchronizedMap( mapName ) . Both supports “fail-fast” iterators. Both of them doesn’t support duplicate keys.

HashMap

1. HashMap allows null as both keys and values.
2. HashMap is useful when we need to access the map without considering how they are added to the map (means, unordered lookup of values using their keys).
3. HashMap is synchronized while it is being looked up. 
4. HashMap doesn’t allow duplicated entries.

The performance of HashMap is based on two optional parameter which we can specify during the creation of the HashMap. Initial capacity & load factor. Initial capacity is the bucket size assigned to a HashMap during it’s creation. Load factor decides when the HashMap needs to be expanded. If the load factor is 0.75, the size will be increased when the current size of the map crosses 75% of its capacity.

TreeMap

The basic difference between HashMap & TreeMap is that, 
1. in a TreeMap the elements are stored in a tree. 
2.TreeMap allows us to retrieve the elements in some sorted order defined by the user. So we can say that TreeMap is slower than HashMap. This is the only implementation based on SortedMap interface.

TreeMap allows us to specify an optional Comparator object during its creation. The keys should be compatible with the comparator specified. This comparator decides the order by which the keys need to be sorted.
public interface Comparator
{
    public int compare (Object object1, Object object2);
    public boolean equals (Object object);
}

If we are not specifying the comparator, TreeMap will try to sort the keys in the natural order. Means will consider them as instances of Comparable interface.
public interface Comparable
{
    public int compareTo (Object objectToCompare);
}
Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.
public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {
       this.value = value;
    }           
 
    public int compareTo (MyCustomKey key)
    {
       int comparison = 0;           
 
       // Note:
       // Return -1 if this.value < key.value
       // Return  0 if this.value = key.value
       // Return  1 if this.value > key.value           
 
       return (comparison);
    }
}

A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey(<value>)); may not give you what you were expecting. So it is always advices to override the hashCode() if objects of that class is being used as a key.
public class MyCustomKey implements Comparable
{
    private int value;
    public MyCustomKey(int value)
    {}
    public int compareTo (MyCustomKey key)
    {}        
 
    public int hashCode()
    {
        // Note:
        // If two objects are equal then their corresponding hashCode ()
        // should return the same value too.
        return (this.value * 199);
    }
}


<<Previous <<   || Index ||   >>Next >>

TreeMap class in collection framework


TreeMap class

  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.
TreeMap class in collection framework

You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.

The TreeMap class supports four constructors. The first form constructs an empty tree map that will be sorted by using the natural order of its keys:
TreeMap( )
The second form constructs an empty tree-based map that will be sorted by using the Comparator comp:
TreeMap(Comparator comp)
The third form initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys:
TreeMap(Map m)
The fourth form initializes a tree map with the entries from sm, which will be sorted in the same order as sm:
TreeMap(SortedMap sm)
Apart from the methods inherited from its parent classes, TreeMap defines following methods:
SNMethods with Description
1void clear()
Removes all mappings from this TreeMap.
2Object clone()
Returns a shallow copy of this TreeMap instance.
3Comparator comparator()
Returns the comparator used to order this map, or null if this map uses its keys' natural order.
4boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
5boolean containsValue(Object value) 
Returns true if this map maps one or more keys to the specified value.
6Set entrySet() 
Returns a set view of the mappings contained in this map.
7Object firstKey() 
Returns the first (lowest) key currently in this sorted map.
8Object get(Object key) 
Returns the value to which this map maps the specified key.
9SortedMap headMap(Object toKey) 
Returns a view of the portion of this map whose keys are strictly less than toKey.
10Set keySet()
Returns a Set view of the keys contained in this map.
11Object lastKey() 
Returns the last (highest) key currently in this sorted map.
12Object put(Object key, Object value) 
Associates the specified value with the specified key in this map.
13void putAll(Map map) 
Copies all of the mappings from the specified map to this map.
14Object remove(Object key) 
Removes the mapping for this key from this TreeMap if present.
15int size() 
Returns the number of key-value mappings in this map.
16SortedMap subMap(Object fromKey, Object toKey) 
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
17SortedMap tailMap(Object fromKey) 
Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
18Collection values() 
Returns a collection view of the values contained in this map.

Example:
import java.util.*;
class TreeMapDemo
{
 public static void main(String args[])
 {
  TreeMap< String,Integer> tm = new TreeMap< String,Integer>();
  tm.put("a",new Integer(100));
  tm.put("b",new Integer(200));
  tm.put("c",new Integer(300));
  tm.put("d",new Integer(400));

  Set< Map.Entry< String,Integer> > st = tm.entrySet();
  for(Map.Entry me:st)  
  {
   System.out.print(me.getKey()+":");
   System.out.println(me.getValue());
  }
 }
}

Output:
a 100
b 200
c 300
d 400


<<Previous <<   || Index ||   >>Next >>

LinkedHashMap class in collection framework

This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted.

This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.

You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.

The LinkedHashMap class supports five constructors. The first form constructs a default LinkedHashMap:
LinkedHashMap( )
The second form initializes the LinkedHashMap with the elements from m:
LinkedHashMap(Map m)
The third form initializes the capacity:
LinkedHashMap(int capacity)
The fourth form initializes both capacity and fill ratio. The meaning of capacity and fill ratio are the same as for HashMap:
LinkedHashMap(int capacity, float fillRatio)
The last form allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used.
LinkedHashMap(int capacity, float fillRatio, boolean Order)
  1. A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  2. It contains only unique elements.
  3. It may have one null key and multiple null values.
  4. It is same as HashMap instead maintains insertion order.
Hierarchy of LinkedHashMap class:
LinkedHashMap class in collection framework
Apart from the methods inherited from its parent classes, LinkedHashMap defines following methods:
SNMethods with Description
1void clear() 
Removes all mappings from this map.
2boolean containsKey(Object key) 
Returns true if this map maps one or more keys to the specified value.
3Object get(Object key) 
Returns the value to which this map maps the specified key.
4protected boolean removeEldestEntry(Map.Entry eldest) 
Returns true if this map should remove its eldest entry.

Example of LinkedHashMap class:

import java.util.*;
class Simple{
 public static void main(String args[]){
 
  LinkedHashMap hm=new LinkedHashMap();

  hm.put(100,"Dinesh");
  hm.put(101,"Sweety");
  hm.put(102,"Nimmo");

  Set set=hm.entrySet();
  Iterator itr=set.iterator();

  while(itr.hasNext()){
   Map.Entry m=(Map.Entry)itr.next();
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

Output:
100 Dinesh
101 Sweety
103 Nimmo



<<Previous <<   || Index ||   >>Next >>


How does java Hashmap work internally

What is Hashing?
Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.
HashMap is an array of Entry objects:
Consider HashMap as just an array of objects.

Have a look what this Object is:

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
... 
}

Each Entry object represents key-value pair. Field next refers to other Entry object if a bucket has more than 1 Entry.

Sometimes it might happen that hashCodes for 2 different objects are the same. In this case 2 objects will be saved in one bucket and will be presented as LinkedList. The entry point is more recently added object. This object refers to other object with next field and so one. Last entry refers to null.
When you create HashMap with default constructor
HashMap hashMap = new HashMap();
Array is gets created with size 16 and default 0.75 load balance.

How does java Hashmap work internally

Adding a new key-value pair
  1. Calculate hashcode for the key
  2. Calculate position hash % (arrayLength-1)) where element should be placed(bucket number)
  3. If you try to add a value with a key which has already been saved in HashMap, then value gets overwritten.
  4. Otherwise element is added to the bucket. If bucket has already at least one element - a new one is gets added and placed in the first position in the bucket. Its next field refers to the old element.
Deletion:
  1. Calculate hashcode for the given key
  2. Calculate bucket number (hash % (arrayLength-1))
  3. Get a reference to the first Entry object in the bucket and by means of equals method iterate over all entries in the given bucket. Eventually we will find correct Entry. If desired element is not found - return null
What put() method actually does:
Before going into put() method’s implementation, it is very important to learn that instances of Entry class are stored in an array. HashMap class defines this variable as:
/**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry[] table;
Now look at code implementation of put() method:
/**
  * Associates the specified value with the specified key in this map. If the
  * map previously contained a mapping for the key, the old value is
  * replaced.
  *
  * @param key
  *            key with which the specified value is to be associated
  * @param value
  *            value to be associated with the specified key
  * @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
  *         if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
  *         can also indicate that the map previously associated
  *         <tt>null</tt> with <tt>key</tt>.)
  */
 public V put(K key, V value) {
  if (key == null)
   return putForNullKey(value);
  int hash = hash(key.hashCode());
  int i = indexFor(hash, table.length);
  for (Entry<k , V> e = table[i]; e != null; e = e.next) {
   Object k;
   if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    V oldValue = e.value;
    e.value = value;
    e.recordAccess(this);
    return oldValue;
   }
  }

  modCount++;
  addEntry(hash, key, value, i);
  return null;
 }

Lets note down the steps one by one:

Step1- First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.

Step2- Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function, and passed the object’s hash code to this hash() function to bring hash value in range of array index size.

Step3- Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.

Step4- Here comes the main part. Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket].

Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.

So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.

If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.

What if we add the another value object with same key as entered before. Logically, it should replace the old value. How it is done? Well, after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.

In this way, HashMap ensure the uniqueness of keys.

How get() methods works internally
Now we have got the idea, how key-value pairs are stored in HashMap. Next big question is : what happens when an object is passed in get method of HashMap? How the value object is determined?

Answer we already should know that the way key uniqueness is determined in put() method , same logic is applied in get() method also. The moment HashMap identify exact match for the key object passed as argument, it simply returns the value object stored in current Entry object.

If no match is found, get() method returns null.

Let have a look at code:

/**
  * Returns the value to which the specified key is mapped, or {@code null}
  * if this map contains no mapping for the key.
  *
  * <p>
  * More formally, if this map contains a mapping from a key {@code k} to a
  * value {@code v} such that {@code (key==null ? k==null :
  * key.equals(k))}, then this method returns {@code v}; otherwise it returns
  * {@code null}. (There can be at most one such mapping.)
  *
  * </p><p>
  * A return value of {@code null} does not <i>necessarily</i> indicate that
  * the map contains no mapping for the key; it's also possible that the map
  * explicitly maps the key to {@code null}. The {@link #containsKey
  * containsKey} operation may be used to distinguish these two cases.
  *
  * @see #put(Object, Object)
  */
 public V get(Object key) {
  if (key == null)
   return getForNullKey();
  int hash = hash(key.hashCode());
  for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
   Object k;
   if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
    return e.value;
  }
  return null;
 }








<<Previous <<   || Index ||   >>Next >>



HashMap class in collection framework

  1. HashMap class extends AbstractMap and implements Map interface.
  2. It uses a hashtable to store the map. This allows the execution time of get() and put() to remain same.
  3. HashMap has four constructor.
  4. HashMap()
    HashMap(Map< ? extends k, ? extends V> m)
    HashMap(int capacity)
    HashMap(int capacity, float fillratio)
    
  5. HashMap does not maintain order of its element.
Hierarchy of HashMap class:
HashMap class in collection framework
SNMethods with Description
1void clear() 
Removes all mappings from this map.
2Object clone() 
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
3boolean containsKey(Object key) 
Returns true if this map contains a mapping for the specified key.
4boolean containsValue(Object value) 
Returns true if this map maps one or more keys to the specified value.
5Set entrySet() 
Returns a collection view of the mappings contained in this map.
6Object get(Object key) 
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key.
7boolean isEmpty()
Returns true if this map contains no key-value mappings.
8Set keySet() 
Returns a set view of the keys contained in this map.
9Object put(Object key, Object value)
Associates the specified value with the specified key in this map.
10putAll(Map m) 
Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
11Object remove(Object key) 
Removes the mapping for this key from this map if present.
12int size() 
Returns the number of key-value mappings in this map.
13Collection values() 
Returns a collection view of the values contained in this map.
Example of HashMap class:
import java.util.*;
class Simple{
 public static void main(String args[]){
 
  HashMap hm=new HashMap();

  hm.put(100,"Dinesh");
  hm.put(101,"Sweety");
  hm.put(102,"Nimmo");

  Set set=hm.entrySet();
  Iterator itr=set.iterator();

  while(itr.hasNext()){
   Map.Entry m=(Map.Entry)itr.next();
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}



Output:
102 Dinesh
100 Sweety
101 Nimmo




<<Previous <<   || Index ||   >>Next >>


Download excel file from JAX-RS

In this tutorial we will discuss about download ms excel files from JAX-RS, for user to download a file, annotate the method with @Produces("application/vnd.ms-excel") :
  1. Put @Produces("application/vnd.ms-excel") on service method, with a Response return type. It means the output is a ms excel file.
  2. Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.
1. Download Excel file in JAX-RS

Full example to download an ms excel file from JAX-RS.

package com.dineshonjava.ws.rest;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

/**
 * @author Dinesh Rajput
 *
 */
@Path("/excel")
public class ExcelFileService {
 private static final String EXCEL_PATH = "d:\\Contact.xls";
  
 @GET
 @Path("/get")
 @Produces("application/vnd.ms-excel")
 public Response getContactExcelFile() {
 
  File file = new File(EXCEL_PATH);
 
  ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition",
   "attachment; filename=\"contact_excel_file.xls\"");
  return response.build();
 
 }
}


2. Test

Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/excel/get".

Figure : MS-Excel file "d:\\Contact.xls" from server is prompt for user to download, with a new me excel file name "contact_excel_file.xls"

Download excel file from JAX-RS


Download SourceCode
Download excel file from JAX-RS.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>

Download pdf file from JAX-RS

In this tutorial we will discuss about download pdf files from JAX-RS, for user to download a file, annotate the method with @Produces("application/pdf") :
  1. Put @Produces("application/pdf") on service method, with a Response return type. It means the output is a pdf file.
  2. Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.

1. Download PDF file in JAX-RS

Full example to download an pdf file from JAX-RS.
package com.dineshonjava.ws.rest;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

/**
 * @author Dinesh Rajput
 *
 */
@Path("/pdf")
public class PdfFileService {
 private static final String PDF_PATH = "d:\\mongodb.pdf";
  
 @GET
 @Path("/get")
 @Produces("application/pdf")
 public Response getSalarySlipFile() {
 
  File file = new File(PDF_PATH);
 
  ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition",
   "attachment; filename=\"mongodb_pdf_file.pdf\"");
  return response.build();
 
 }
}

2. Test

Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/pdf/get".

Figure : PDF file "d:\\mongodb.pdf" from server is prompt for user to download, with a new pdf file name "mongodb_pdf_file.pdf"

Download pdf file from JAX-RS




Download SourceCode
Download pdf file from JAX-RS.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>

Download image file from JAX-RS

In this tutorial we will discuss about download image files from JAX-RS, for user to download a file, annotate the method with @Produces("image/image-type") :


  1. Put @Produces("image/png") on service method, with a Response return type. It means the output is a image file.
  2. Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.


1. Download Image in JAX-RS

Full example to download an image file from JAX-RS.
package com.dineshonjava.ws.rest;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

/**
 * @author Dinesh Rajput
 *
 */
@Path("/employeephoto")
public class EmployeeImageService {
 private static final String IMAGE_PATH = "d:\\employee_photo.png";
  
 @GET
 @Path("/get")
 @Produces("image/png")
 public Response getSalarySlipFile() {
 
  File file = new File(IMAGE_PATH);
 
  ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition",
   "attachment; filename=\"employee_image_photo.png\"");
  return response.build();
 
 }
}

2. Test

Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/employeephoto/get".

Figure : Image file "d:\\employee_photo.png" from server is prompt for user to download, with a new image  name "employee_image_photo.png"

Download image file from JAX-RS



Download SourceCode
Download image file from JAX-RS.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>


Download text file from JAX-RS

In this tutorial we will discuss about download text files from JAX-RS,  for user to download a file, annotate the method with @Produces("text/plain") :
  1. Put @Produces("text/plain") on service method, with a Response return type. It means the output is a text file.
  2. Set "Content-Disposition" in Response header to tell browser pop up a download box for user to download.

1. Download File in JAX-RS

See a full example to download a text file in JAX-RS.
package com.dineshonjava.ws.rest;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

/**
 * @author Dinesh Rajput
 *
 */
@Path("/salaryslipfile")
public class EmployeeSalarySlip {
 private static final String FILE_PATH = "d:\\salary.log";
  
 @GET
 @Path("/get")
 @Produces("text/plain")
 public Response getSalarySlipFile() {
 
  File file = new File(FILE_PATH);
 
  ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition",
   "attachment; filename=\"salary_slip_file.log\"");
  return response.build();
 
 }
 
}

2. Test

Deploy above JAX-RS service, access this URI pattern : "http://localhost:8181/sdnext/doj/salaryslipfile/get".

Figure : Text file "d:\\salary.log" from server is prompt for user to download, with a new file name "salary_slip_file.log"

Download text file from JAX-RS



Download SourceCode
Download text file from JAX-RS.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>


Get HTTP header in JAX-RS

In this tutorial, we will discuss about the two ways to get HTTP request header in JAX-RS :
  1. Inject directly with @HeaderParam
  2. Pragmatically via @Context
1. @HeaderParam Example

In this example, it gets the browser “user-agent” from request header.
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
 
@Path("/employee")
public class EmployeeController {
 
 @GET
 @Path("/get")
 public Response addEmployee(@HeaderParam("user-agent") String userAgent) {
 
  return Response.status(200)
    .entity("addEmployee is called, userAgent : " + userAgent)
    .build();
 
 }
 
}
Access via URI pattern "http://localhost:8181/sdnext/doj/employee/get", with Chrome, see following result :

addEmployee is called, userAgent : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36

2. @Context Example

Alternatively, you can use @Context to get "javax.ws.rs.core.HttpHeaders" directly, see equivalent version to get browser "user-agent".
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
 
@Path("/employee")
public class EmployeeController {
 
 @GET
 @Path("/get")
 public Response addEmployee(@Context HttpHeaders headers) {
 
  String userAgent = headers.getRequestHeader("user-agent").get(0);
 
  return Response.status(200)
   .entity("addEmployee is called, userAgent : " + userAgent)
   .build();
 
 }
 
}
Access via URI pattern "http://localhost:8181/sdnext/doj/employee/get", with Chrome, see following result :

addEmployee is called, userAgent : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36






References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>



JAX-RS @FormParam example

In this tutorial we will discuss about @FormParam, In JAX-RS, you can use @FormParam annotation to bind HTML form parameters value to a Java method. The following example show you how to do it :
1. HTML Form
See a simple HTML form with "post" method.
<html>
<body>
 <h1>JAX-RS @FormQuery Testing</h1>
 
 <form action="doj/employee/add" method="post">
  <p>
   Employee Name : <input type="text" name="empname" />
  </p>
  <p>
   Employee Age : <input type="text" name="empage" />
  </p>
  <input type="submit" value="Add Employee" />
 </form>
 
</body>
</html>
2. @FormParam Example

Example to use @FormParam to get above HTML form parameter values.
package com.dineshonjava.ws.rest;

import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

/**
 * @author Dinesh Rajput
 *
 */
@Path("/employee")
public class EmployeeController {
 
 
 @POST
  @Path("/add")
  public Response addEmployee(
    @FormParam("empname") String empname,
    @FormParam("empage") int empage) {
  
   return Response.status(200)
    .entity("addEmployee is called, employee name : " + empname + ", employee age : " + empage)
    .build();
  
  }
}


3. Now access the following urls.

http://localhost:8181/sdnext/userform.html

 JAX-RS @FormParam example

When "Add Employee" button is clicked, it will redirect to URL :
 http://localhost:8181/sdnext/doj/employee/add

 JAX-RS @FormParam example



Download SourceCode
JAX-RS @FormParam example.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>