Monday, December 29, 2014

Joda-Time vs Date and Calendar Class in Java

This post is nothing special. I just thought to write it to highlight some benefits to using the Joda-Time library over the Date and Calendar class in Java.

I was working on a project that had to determine if a customer's invoice qualified for a marketing promotion.

The requirements are the following:
1. Check if number of days between retail date and current date is within the days to claim window.
2. Compare retail date if it falls between the marketing fund promotion's end date and start date.


Here's the code using the joda-time library:

 DateTime retailDate = new DateTime(remittanceItem.getRiData().getRetailDate());
 DateTime currentDate = new DateTime();
 for (BudgetDTO budgetDTO: budgetDTOList) {
  Integer daysToClaim = Integer.parseInt(budgetDTO.getRemitDays());
  DateTime startDate = new DateTime(budgetDTO.getStartDate());
  DateTime endDate = new DateTime(budgetDTO.getEndDate());
  //check first if currentDate -  retailDate is within the daysToClaim period
  if (Days.daysBetween(retailDate, currentDate).getDays() <= daysToClaim) {
   //check if retailDate is within the Budget startDate and endDate
   if (!retailDate.isBefore(startDate) && !retailDate.isAfter(endDate)) {
    mktgMapKey = budgetDTO.getProgramId() + "|" + budgetDTO.getIncentiveType();
    mktgMapValue = budgetDTO.getProgramDesc();
    mktgFundValueLabelMap.put(mktgMapKey, mktgMapValue);
    mktgFundProgramIdList.add(budgetDTO.getProgramId());  
   }
  }
 }


Here's the code using Date and Calendar class:

 //create the Date objects
 Date retailDate = remittanceItem.getRiData().getRetailDate();
 Date currentDate = new Date();
 SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss");
 for (BudgetDTO budgetDTO: budgetDTOList) {
  long daysToClaim = Long.valueOf(budgetDTO.getRemitDays()).longValue();
  
  //create the Calendar objects
  Calendar startDate = new GregorianCalendar();
  startDate.setTime(budgetDTO.getStartDate());

  Calendar endDate = new GregorianCalendar();
  endDate.setTime(budgetDTO.getEndDate());
  
  Calendar rtlDate = new GregorianCalendar();
  rtlDate.setTime(remittanceItem.getRiData().getRetailDate());
  
  //To compare RELIABLY using Calendar#before() and Calendar#after()
  //we need to clear the time section first for each Calendar object
  startDate.set(Calendar.HOUR, 0);
  startDate.set(Calendar.HOUR_OF_DAY, 0);
  startDate.set(Calendar.MINUTE, 0);
  startDate.set(Calendar.SECOND, 0);
  startDate.set(Calendar.MILLISECOND, 0);

  endDate.set(Calendar.HOUR, 11);
  endDate.set(Calendar.HOUR_OF_DAY, 23);
  endDate.set(Calendar.MINUTE, 59);
  endDate.set(Calendar.SECOND, 59);
  endDate.set(Calendar.MILLISECOND, 0);
  
  rtlDate.set(Calendar.HOUR, 0);
  rtlDate.set(Calendar.HOUR_OF_DAY, 0);
  rtlDate.set(Calendar.MINUTE, 0);
  rtlDate.set(Calendar.SECOND, 0);
  rtlDate.set(Calendar.MILLISECOND, 0);

  //calculate difference in number of days
  long diff = currentDate.getTime() - retailDate.getTime();
  long diffDays = diff / (24 * 60 * 60 * 1000);
  
  //check first if it is within the daysToClaim period
  if (diffDays <= daysToClaim) {
   //check if retailDate is within the Budget startDate and endDate
   if ((!rtlDate.before(startDate) && !rtlDate.after(endDate))){
    mktgMapKey = budgetDTO.getProgramId() + "|" + budgetDTO.getIncentiveType();
    mktgMapValue = budgetDTO.getProgramDesc();
    mktgFundValueLabelMap.put(mktgMapKey, mktgMapValue);
    mktgFundProgramIdList.add(budgetDTO.getProgramId());  
   }
  }
 }


So you see. Using the Joda-Time library is not complex but definitely cleaner and less verbose.


Resources:
Joda-Time API

Saturday, November 15, 2014

Sort a Map by value in Java

In Java, you simply use a TreeMap to have a map sorted by key.

But quite often, we need to sort a map by its value.

The method below will help you sort a map by its value. Simply use it in your code.

private static Map<String, String> sortMapByValue(Map<String, String> unsortMap) {
 // Convert Map to List
 List<Map.Entry<String, String>> list = 
  new LinkedList<Map.Entry<String, String>>(unsortMap.entrySet());

 // Sort list with comparator, to compare the Map values
 Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
  public int compare(Map.Entry<String, String> o1,
          Map.Entry<String, String> o2) {
   return (o1.getValue()).compareTo(o2.getValue());
  }
 });

 // Convert sorted map back to a Map
 Map<String, String> sortedMap = new LinkedHashMap<String, String>();
 for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) {
  Map.Entry<String, String> entry = it.next();
  sortedMap.put(entry.getKey(), entry.getValue());
 }
 return sortedMap;
}


Cheers!

Removing elements while iterating a Set in Java

Use an Iterator when removing an item from a Set Collection while iterating it so that it will not cause undefined behavior or the 'java.util.ConcurrentModificationException' exception.

To remove elements from a Set while iterating, you may use Iterator as shown below:

//set a reference to the set 
Set<Person> personSet = .....

//remove an element while iterating the set
Iterator<Person> iter = personSet.iterator();
while (iter.hasNext()) {
    Person person = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the set.
        iter.remove();
    }
}

You may also use a for-loop as shown below:

//set a reference to the set 
Set<Person> personSet = .....

//remove an element while iterating the set
for (Iterator<Person> iter = personSet.iterator(); iter.hasNext();) {
    Person person = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the set.
        iter.remove();
    }
}

Note that Iterator.remove is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Collection API
Set API

Removing elements while iterating a Map in Java

Use an Iterator when removing an item from a Map Collection while iterating it so that it will not cause undefined behavior or the 'java.util.ConcurrentModificationException' exception.

To remove elements from a Map while iterating, you should use Iterator as shown below:

//set a reference to the map
Map<String,Person> groupPersonMap = .....

Iterator<Map.Entry<String,Person>> iter = groupPersonMap.entrySet().iterator();
while (iter.hasNext()) {
   Map.Entry<String,PersonObj> entry = iter.next();
   String groupId = entry.getKey();
   Person person = entry.getValue();
   if ("name filter here".equals(person.getName())) {
      // Remove the current element from the iterator and the map.
      iter.remove();
   }
}

Note that Iterator.remove is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Collection API
Map API

Removing elements while iterating a List in Java

Use an Iterator when removing an item from a List Collection while iterating it so that it will not cause undefined behavior or the 'java.util.ConcurrentModificationException' exception.

To remove elements from a List while iterating, you should use Iterator as shown below:

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
Iterator<String> iter = nameList.iterator();
while (iter.hasNext()) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


You may also use a for-loop as shown below:

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
for (Iterator<String> iter = nameList.iterator(); iter.hasNext();) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


You may also use a ListIterator by using the List's listIterator() method.

//set a reference to the list 
List<String> nameList = .....

//remove an element while iterating the list
Iterator<String> iter = nameList.listIterator();
while (iter.hasNext()) {
    String name = iter.next();
    if (..condition here..) {
        // Remove the current element from the iterator and the list.
        iter.remove();
    }
}


Note that Iterator.remove()  and ListIterator.remove() is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Collection
Collection API
List API



Saturday, November 1, 2014

Check for duplicates in a List

A List typically allow duplicate elements. List is an ordered collection interface.

If you want to prevent duplicates, you would typically want to use a Set. If maintaining order is needed, use LinkedHashSet.

However, there are instances where you want to use a List and prevent duplicate elements when adding to the list.

You can check for duplicates in the List by using the HashSet(list) technique outlined below.


You should first override equals() and hashcode() methods in your class.

public class IncentiveVB implements Serializable  {

 private static final long serialVersionUID = 1L;
 

 private String incentiveId;
 
 private String incentiveName;
 
 private String incentiveCode;
 
 private String inputType; 
 
 /*
  * getters and setters here
  */
 
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((incentiveId == null) ? 0 : incentiveId.hashCode());
  result = prime * result
    + ((incentiveName == null) ? 0 : incentiveName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  IncentiveVB other = (IncentiveVB) obj;
  if (incentiveId == null) {
   if (other.incentiveId != null)
    return false;
  } else if (!incentiveId.equals(other.incentiveId))
   return false;
  if (incentiveName == null) {
   if (other.incentiveName != null)
    return false;
  } else if (!incentiveName.equals(other.incentiveName))
   return false;
  return true;
 } 
}


Here's a few ways you can override the equals() and hashCode() methods

Then, in your code check for duplicates in the list before actually adding an object into the list as shown below.

List<IncentiveVB> incentiveVBList = ....;
 
for (condition...) {

 /*
  * code to create 'incentiveVB' object here
  */

 //check for duplicates of this IncentiveVB in the list before adding to the list
 //by testing a copy of your List against a HashSet
 List<IncentiveVB> list = new ArrayList<IncentiveVB>(incentiveVBList);
 list.add(incentiveVB);
 Set<IncentiveVB> set = new HashSet<IncentiveVB>(list);
 if(set.size() < list.size()){
  //there are duplicates of this IncentiveVB in the list. don't add.
  continue;
 }
 incentiveVBList.add(incentiveVB);
}



Thursday, October 16, 2014

Iterate a Map in JSP using JSTL

Let's say we have a bean named 'CartViewBean'.

This bean has a map property named 'productMap'. This product map has the product code as the map's key and the product name as the map's value.

We will create a <select> element in our jsp and use the key-value pairs in the productMap to create the <option> tags for the <select> element.

The productMap's key will be the value and the productMap's value will be the text display of the <option> tag. So the productMap's value will be the one shown on the drop down display of the <select> statement.

You will need to create a reference to your Java bean in your JSP using the <bean:define> tag. In this example, we create a reference to the Java bean with the id 'cartVB'.

Then you will need to set a reference for the bean's map property 'cartVB.productMap' to a JSTL variable 'productMap'.

You can then iterate thru the map's elements using the  <c:forEach>  JSTL tag . You may also use the <c:remove> tag to clear and initialize the JSTL variable but it is optional.

<bean:define id="cartVB" name="cartViewBean" type="com.mycompany.view.CartViewBean"/>

<c:remove var="productMap"/>
<c:set var="productMap" value="${cartVB.productMap}" />
<select>
   <c:forEach var="product" items="${productMap}">
     <option value="<c:out value="${product.key}" />"> <c:out value="${product.value}" /> </option> 
   </c:forEach>
</select>

Monday, September 22, 2014

Inline Comparator Example

Here's an example of using an inline comparator in java.

To sort a list of Person objects according to its 'name' property, use the template below.

List personList = personListDTO.getPersons();
Collections.sort(personList ,new Comparator() {
   public int compare(Object o1, Object o2) {
    Person p1 = (Person)o1;
    Person p2 = (Person)o2;
    return p1.getName().compareTo(p2.getName());
   }
  });

You may also use the more compact form below.

List<Person> personList = personListDTO.getPersons(); 
Collections.sort(personList ,new Comparator<Person>() {
 public int compare(Person p1, Person p2) {
  return p1.getName().compareTo(p2.getName());
 }
}); 

This code will help you avoid getting a warning in eclipse of the generic type -

- Type safety: The expression of type new Comparator(){} needs unchecked conversion to conform to Comparator<? super Person>
- Type safety: Unchecked invocation sort(List<Person>, new Comparator(){}) of the generic method sort(List<T>, Comparator<? super T>) of type Collections
- Comparator is a raw type. References to generic type Comparator<T> should be parameterized 

Related Links:
More examples on using Comaparator in Java
How to sort a map in Java

Reference:
Collections class reference


Decode HTML Entities

This post is nothing special. Just a note to myself.

I needed a basic javascript function to decode HTML entities in a string. The string that is retrieved from the database was being encoded in the jsp with the HTML entity '&amp;' encoded in the string. 

So the string 'Tom & Harry' is being shown as "Tom &amp; Harry'.

I wrote a basic HTML decoder function in javascript since the strings are coming from a trusted source (my database).

Here is the HTML decoder function.

function decodeHTMLEntities(str) {
 var textArea = document.createElement("textarea");
 textArea.innerHTML = str; 
 return textArea.value;
}

If the source of the data is not trusted, you may use some of the other HTML decoder options discussed in the following links.

HTML decode options 1
HTML decode options 2

Please take note that the discussions from these links advise against using jQuery.html().text() to decode html entities as it's unsafe because user input should never have access to the DOM.

HTML Entity Reference
HTML Entitiy Reference

Tuesday, August 19, 2014

How to sort a Map in Java

Using a sorted map in java is fairly straight-forward. You simply use a TreeMap. A map that implements the SortedMap interface. A TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

All keys inserted into a sorted map must implement the Comparable interface, such as String and Date objects.

So if your map's key is a String then you are all set.

But if your map's key is a user-defined object, then what should you do?

It's simple. Use a Comparator class for your map's key.

Here's a usage example.

Let's create a Person class.

public class Person {

 private String name;
 private int age;
 
 public Person(String name, int age) {
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
}

 Create a Comparator for the Person class.

 public class PersonComparator implements Comparator<Person> {
     
     public PersonComparator() {}
        
     public int compare(Person person1, Person person2) {
         String name1 = person1.getName().toUpperCase();
         String name2 = person2.getName().toUpperCase();
         //ascending order        
         if ( (name1 == null || "".equals(name1.trim())) && (name2 == null || "".equals(name2.trim())) ) {
             //both names are empty 
             return 0;
         } else if ( (name1 == null || "".equals(name1.trim())) ) {
             // first bean has no name -- second should come before
             return 1;
         } else if ( (name2 == null || "".equals(name2.trim())) ) {
             // second bean has no name -- first should come before
             return -1;
         }
         if (name1 != null && !"".equals(name1.trim()) && name2 != null && !"".equals(name2.trim())) {
             return name1.compareToIgnoreCase(name2);
             //use below for descending order - also change conditions above
             //return name2.compareToIgnoreCase(name1);
         } 
         return 0;
     }
     
 }

Now, to have a sorted map with the Person class as the key, instantiate your map using the TreeMap constructor that accepts a Comparator argument - "TreeMap(Comparator<? super K> comparator)".

Here's the usage example.

public class TestSortedMap {
 
  public static void main(String[] args) {
 
  // instantiate a TreeMap 
  Map<Person, String> personCityMap = new TreeMap<Person, String>(new PersonComparator());
  map.put(new Person("Bianca", 18), "Torrance");
  map.put(new Person("Raymond", 10), "Los Angeles");
  map.put(new Person("Juancho", 14), "San Diego");

  // print the Person's name and age (properties of map's key) and the city (map's value) 
  for (Map.Entry<Person, String> entry : personCityMap.entrySet()) {
   System.out.println("Key : " + entry.getKey().getName() + " - " + entry.getKey().getAge() + " Value : "
    + entry.getValue());
  } 
  } 
}

The resulting map will be sorted by the Person.name property in ascending order.

Output.

Key: Bianca - 18  Value : Torrance
Key: Juancho - 14  Value : San Diego
Key: Raymond - 10  Value : Los Angeles

Resources:
Java TreeMap



Thursday, August 14, 2014

How to use Comparable and Comparator in Java

Comparable

A class that implements the Comparable interface can have its instances compared with each other. You use Comparable when you want to sort objects based on natural order. The class overrides the compareTo method and compares the this reference with another instance of the object.

Here is a usage example.

public class Person implements Comparable {

 private String name;
 private int age;
 
 public Person(String name, int age) {
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public int getAge() {
  return age;
 }
 
 public void setAge(int age) {
  this.age = age;
 }
 
 @Override
 public int compareTo(Person p) {
  if (this.getAge() > p.getAge()) 
   return 1;
  else if (this.getAge() < p.getAge())
   return -1;
  else 
   return 0;
 }
 
} 

Now, try this class using Arrays.sort as shown below.

public class SortPersonObjects {

 public static void main(String[] args) {
  
  Person p1 = new Person("Bianca", 18);
  Person p2 = new Person("Juancho", 14);
  Person p3 = new Person("Raymond", 10);
  
  Person[] persons = new Person[];
  
  persons[1] = p1;
  persons[2] = p2;
  persons[3] = p3;
  
  Arrays.sort(persons);
  
  for (Person person: persons) {
   System.out.println("Name: " + person.getName() + " " + person.getAge());
  }
 }
}

You will get the output below.

Name: Raymond 10
Name: Juancho 14
Name: Bianca 18


Comparator

A class that implements the Comparator interface will be a comparator for two objects provided to it. You use Comparator if you want to sort based on multiple properties of an object.

You use Comparator to sort objects by:

  • Passing the Comparator to a sort method such as Collections.sort() and Arrays.sort()
  • To allow precise control over the sort order
  • To control the order of some data structrures such as sorted sets and sorted maps

Here is a Comparator example for the Person class.

 public class PersonComparator implements Comparator<Person> {
     
     public PersonComparator() {}
        
     public int compare(Person person1, Person person2) {
         String name1 = person1.getName().toUpperCase();
         String name2 = person2.getName().toUpperCase();
         //ascending order        
         if ( (name1 == null || "".equals(name1.trim())) && (name2 == null || "".equals(name2.trim())) ) {
             //both names are empty 
             return 0;
         } else if ( (name1 == null || "".equals(name1.trim())) ) {
             // first bean has no name -- second should come before
             return 1;
         } else if ( (name2 == null || "".equals(name2.trim())) ) {
             // second bean has no name -- first should come before
             return -1;
         }
         if (name1 != null && !"".equals(name1.trim()) && name2 != null && !"".equals(name2.trim())) {
             return name1.compareToIgnoreCase(name2);
             //use below for descending order - also change conditions above
             //return name2.compareToIgnoreCase(name1);
         } 
         return 0;
     }
     
 }


Here is a usage example of the Comparator class.

public class SortPersonObjectsByComparator {

 public static void main(String[] args) {
  
  Person p1 = new Person("Bianca", 18);
  Person p2 = new Person("Juancho", 14);
  Person p3 = new Person("Raymond", 10);
  
  ArrayList<Person> persons = new ArrayList<Person>();
  
  persons.add(p1);
  persons.add(p2);
  persons.add(p3);
  
  Collections.sort(persons, new PersonComparator());
  
  for (Person person: persons) {
   System.out.println("Name: " + person.getName() + " " + person.getAge());
  }
 }
}

The new output you get is shown below.

Name: Bianca 18
Name: Juancho 14
Name: Raymond 10

Summary
By implementing Comparable, you're making sorting a fundamental part of the object (like integer and String objects). By implementing Comparator, you are creating a utility that sorts objects in a specific context (object properties used) to order them in a certain way.

Resources:
Comparable interface documentation
Comparator interface documentation

Examples:
Examples on java object sorting - embedded Comparator example
Comparator and Comparable examples
Comparator and Comparable examples

Saturday, August 2, 2014

CSS: How to make a DIV element float on a page

This post is nothing special. It's just basic CSS. Just a note for myself. If it helps you, then great!

You can make a block element like a DIV stay at a fixed position of the screen while the page scrolls making it look like the DIV is floating.

This is pretty simple. Just apply the following CSS properties below to the element.

position: fixed;
top: 100px;
right: 5px;


Thursday, July 10, 2014

CSS: How to center elements in a DIV or any container

Centering elements horizontally is pretty simple.

Just apply the following style rules to the element you want to center horizontally.


display: block;
margin: 0 auto;
 

I also came across this article on absolute centering. The technique very nicely align your element in the center of a container vertically and horizontally using these simple CSS style rules.

.Center-Container {
  position: relative;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
} 

More interesting techniques are shown on that article so be sure to check it out.


Monday, June 9, 2014

Setting Up Your Java Development Environment - Java JDK and Eclipse

This tutorial shows you how to set up the Java JDK and Eclipse IDE as your development environment.

Download the following:
1. Java JDK 1.7  download
2. Eclipse IDE for Java EE Developers 4.3.2  (Kepler)  download

You may get confused by the number of choices from the download pages. It may seem so logical but a lot of new developers get confused which one to download.

See screenshots below for reference:

 For the Java JDK, you would want the JDK download of course.



For Eclipse, you would want the the Eclipse IDE for Java EE Developers if you want to develop web applications. Choose the 32 bit or 64 bit download, whichever matches your operating system.




1. Install the Java JDK

 Click on the downloaded Java JDK file and follow the prompts to install.

It will most likely be installed at a location similar to this :

C:\Program Files\Java\jdk1.7.0_55


2. Set the JAVA_HOME system variable

Configure the Windows Environment Variables with the JAVA_HOME system variable.

Click on Windows 'Start' button  >  Right-click on 'Computer'  >  Properties  >  Advanced system setting  >  Environment Variables

You will get the popup page below:




Click the 'New' button then enter JAVA_HOME and the location of your installed JAVA JDK like on the image below:




Click the 'OK' button and you should now see the JAVA_HOME variable under the System variables like the image below:




3. Update the PATH system variable with the path to the JAVA JDK bin folder

While on the Environment Variables page, scroll to the Path system variable and select it Then click on the 'Edit' button.

 See image below.



You will get the System Variable page below.


Edit the Path system variable and add the entry " %JAVA_HOME%\bin " to point the Path variable to the JAVA JDK's bin folder.

Click the 'OK' button to apply the new settings.

This setting will allow you to run Java commands anywhere.


4. Verify your Java JDK installation is working

Open a new command prompt and type "java -version".



You should get a response similar to this to indicate a successful installation of  the Java JDK.


5. Install the Eclipse IDE

Click on the downloaded Eclipse installation file and follow the prompts to install.

When prompted for the location where to extract the file, I prefer installing it in the C drive in my designated Java folder:

C:\_java

After installation, you will find in your designated folder the Eclipse application.

See image below:



That's it. Your are done.


Thursday, May 1, 2014

Create a RESTful Web Service Client using Jersey and Eclipse - Tutorial

This tutorial shows how to create a RESTful web service client in Java using Eclipse and Jersey.

You may access the web service thru the browser but in this tutorial we will access the  RESTful web service thru a client application.

This new client application will test the web service created in this RESTful web service tutorial.

Development Environment
1. Eclipse IDE for Java EE Developers 4.3.2  (Kepler)  download
2. Jersey 2.7  download
3. JDK 1.7  download


1. Create a Java Project in Eclipse

Jersey provides a REST client library which we will use in this client application.

Create a new Java project.

File > New > Java Project




For project name enter:  RESTfulWSClient

Click Finish.

Create the package com.ericsoriano.restclient in your project's src folder.

Right-click on src folder > New > Package




For name enter:  com.ericsoriano.restclient

Click Finish.


2. Download Jersey and add Jersey Library to the project

If you don't have Jersey yet, download Jersey from here.

Unzip the downloaded Jersey zip file to your local directory.

Add all the jar files from Jersey's  api, ext and lib folders to your project and project build bath.

Right-click on project name > Build Path > Configure Build Path

You will get the Java Build Path page below.




Click 'Add Library' > Select 'User Library' > Next 

You will get the User Library page below.




Click on 'User Libraries'.

You will get the User Libraries page below.




Click 'New' > enter 'Jersey Library' > OK

Select 'Jersey Library' > Click 'Add External Jars' > add jars from Jersey's api folder

Select 'Jersey Library' > Click 'Add External Jars' > add jars from Jersey's ext folder

Select 'Jersey Library' > Click 'Add External Jars' > add jars from Jersey's lib folder

You will now have all the Jersey jars under your project's new Jersey Library.




Click OK.

You will then be back at the User Library page below.




Make sure the checkbox for 'Jersey Library' is checked.

Click Finish.

You should now be back on the Java Build Path page.




Make sure your newly created 'Jersey Library' is shown on the list.

Click OK.


3. Create your Java class

Create a new class "RESTClientDemo" under the package com.ericsoriano.restclient.

Copy the code below to your "RESTClientDemo" class.

package com.ericsoriano.restclient;


import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;


public class RESTClientDemo {
 
 public static void main(String[] args) { 
  // create a Client instance
  Client client = ClientBuilder.newClient();
  
  // point the root web target to the context root (base URI) of the RESTful web service - http://localhost:8080/RESTfulWSDemo/rest
  WebTarget rootWebTarget = client.target("http://localhost:8080/RESTfulWSDemo/rest");
  
  // target the resource exposed thru the URI - http://localhost:8080/RESTfulWSDemo/rest/demo
  WebTarget resourceWebTarget = rootWebTarget.path("demo");
  
  // prepare a HTTP request - representation media type requested is "text/plain"
  Invocation.Builder invocationBuilderText = resourceWebTarget.request(MediaType.TEXT_PLAIN_TYPE);
  //invocationBuilder.header("some-header", "true"); -- use this if you want to setup headers for the request
  
  // prepare a HTTP request - representation media type requested is "text/plain"
  Invocation.Builder invocationBuilderXML = resourceWebTarget.request(MediaType.TEXT_XML_TYPE);  
  
  // build the request and send to remote resource (RESTful web service)
  Response responseText = invocationBuilderText.get();
  Response responseXML = invocationBuilderXML.get();
  
  System.out.println("Response status = " + responseText.getStatus());
  System.out.println("Response as TEXT: " + responseText.readEntity(String.class));
  System.out.println("Response as XML: " + responseXML.readEntity(String.class));
  
  
  // test a PUT request --------------------------------------------------
  
  // target the resource annotated with @PUT exposed thru the URI - http://localhost:8080/RESTfulWSDemo/rest/demo/{employeeId}
  WebTarget employeeWebTarget = resourceWebTarget.path("10");  
  
  // prepare a HTTP request - representation media type requested is "text/plain"
  Invocation.Builder invocationBuilderEmployee = employeeWebTarget.request(MediaType.TEXT_PLAIN_TYPE);
  
  // build the request and send to remote resource (RESTful web service) - value of request parameter {employeeId} is sent thru the .path() method above 
  Response responseToPutRequest = invocationBuilderEmployee.put(Entity.entity("", MediaType.TEXT_PLAIN));
  System.out.println("");
  System.out.println("PUT request - Response as TEXT: " + responseToPutRequest.readEntity(String.class));
  
 }
}





4. Run the Java class

Create and run first the web service from this RESTful web service tutorial.

Run as  java application the RESTClientDemo class in eclipse.

You should get the following output:


Response status = 200
Response as TEXT: Jersey REST Web Service works!
Response as XML: <?xml version="1.0"?><message> Jersey REST Web Service works!</message>

PUT request - Response as TEXT: Employee 10 record is updated!


Tuesday, April 29, 2014

RESTful Web Services with Java JAX-RS using Jersey and Eclipse - Tutorial

This tutorial shows how to create RESTful web services in Java using Eclipse and Jersey.

REST (Representational State Transfer) is an architectural style based on the HTTP protocol where resources are identified by global IDs (typically using URIs). REST client applications use HTTP methods (GET/ POST/ PUT/ DELETE) to access the service's resources.

RESTful web services are based on HTTP methods and the concept of REST. A RESTful web service should define the base URI for the service, the supported MIME types for the response data (text, XML, JSON,..), and the supported set of operations (GET/ POST/ PUT/ DELETE) of the service.

The Java API for RESTful Web Services (JAX-RS) is an annotation-based API for implementing RESTful web services based on the  HTTP protocol. This is defined in the Java Specification Request (JSR) 311. Jersey is a JAX-RS reference implementation and provides it's own API with additional features and utilities.

JAX-RS also supports the creation of XML and JSON via the Java Architecture for XML Binding (JAXB).


JAX-RS annotations

@Path(/your_resource_path) - sets the path to the base URI + /your_resource_path. The base URI consists of your host, port, any context(project name), and the servlet's url-pattern(eg.; /rest) from the web.xml configuration file.

This tutorial's base URI, for example, is   http://localhost:8080/RESTfulWSDemo/rest
       
@GET - indicates that the annotated method will be invoked by a HTTP GET request   
@PUT - indicates that the annotated method will be invoked by a HTTP PUT request
@POST - indicates that the annotated method will be invoked by a HTTP POST request
@DELETE - indicates that the annotated method will be invoked by a HTTP DELETE request    
@Produces - defines the MIME media type a resource can produce and send back to the client
@Consumes - defines which MIME type is consumed by the method
@PathParam - is used in the method's arguments to set the value of the URI parameters into the methods arguments
@QueryParam - is used in the method's arguments to set the value of the query parameters into the methods arguments.

Query Parameters are the parameters in the http url in the format of a query string where all parameters appear in the end of the url after the '?' symbol and parameters are separated with the '&' symbol
e.g.  http://localhost:8080/RESTfulWS/rest/demo?employeeId1=10&employeeId2=20

Here are the Java JAX-RS and Jersey JAX-RS documentation for a complete listing and description of available annotations and applications.


Development Environment:
1. Eclipse IDE for Java EE Developers 4.3.2  (Kepler)  download
2. Jersey 2.7  download
3. JDK 1.7  download
4. Tomcat 7

This tutorial assumes that you have the Java JDK installed in your machine. You should also have Eclipse installed and configured with  a Tomcat 7 application server.


1. Create a Dynamic Web Project in Eclipse

Set your Eclipse view to Java EE perspective then click on:

File > New > Dynamic Web Project

You will get the shown page below.




For 'Project name':
Enter your project name such as "RESTfulWSDemo". This will be the context root of your application.

For 'Target runtime':
Select 'Apache Tomcat v7.0' or your desired server.

For 'Dynamic web module version':
Select the servlet version you will use. If you are using Java EE 6 or 7, select '3.0'.  If you are using Java EE 5, select '2.5' or lower.

You can see the Servlet mapping with JDK and Tomcat versions from the Tomcat-Servlet-JDK mapping page.

For 'Configuration':
Default Configuration is fine.


Click on 'Next' button

You will get the page shown below.



You don't need to do anything on this page.

Click on 'Next' button

You will get the page shown below.



Check the box for 'Generate web.xml deployment descriptor'.

Click on 'Finish' button.


2. Download Jersey and copy Jersey jars to project's lib folder

Unzip the downloaded Jersey zip file to your local directory.

Copy all the jar files from Jersey's  api, ext and lib folders to your projects  WebContent/WEB-INF/lib  folder.



3. Create your Java class

Right-click on Java Resources/src  folder.

Select New > Class

You will get the page shown below.



Enter your package name and the class name.

Click 'Finish".

Complete your new class with the following code:

package com.ericsoriano.restwebservice;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// @GET annotation registers the method to answer to a HTTP GET request
// @Produces annotation defines which MIME type is delivered by a method annotated with @GET
// @Produces can deliver text, XML, HTML

// The browser requests the HTML MIME type by default

// @Path annotation exposes resource (class and methods) to the client thru base URI + path

// URI = (context root)/(url-pattern in your web.xml's servlet mapping)/(path defined in your @Path annotation)  eg.;   RESTfulWSDemo/rest/demo

// URI parameter values are assigned to variables thru the methods's @Path annotation by enclosing the variables within curly braces "{}" eg.;   @Path("/add/{n1}/{n2}")

// @PathParam annotation is used in the method's signature to set the value of the parameter into the methods arguments
// eg.;  public String add(@PathParam("n1") int n1, @PathParam("n2") int n2)



// This class resource's URI effectively becomes "RESTfulWSDemo/rest/demo" thru the @Path annotation
@Path("/demo")
public class JerseyRESTWSDemo {

   // This method is called if client requests for HTML 
   @GET
   @Produces(MediaType.TEXT_HTML)
   public String serveHTML() {
    return "<html> " + "<title>" + "Jersey REST Demo" + "</title>"
         + "<body><h1>" + "Jersey REST Web Service works!" + "</body></h1>" + "</html> ";
   }

   // This method is called if client requests for TEXT_PLAIN 
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   public String serveText() {
    return "Jersey REST Web Service works!";
   }

   // This method is called if client requests for XML 
   @GET
   @Produces(MediaType.TEXT_XML)
   public String serveXML() {
    return "<?xml version=\"1.0\"?>" + "<message> Jersey REST Web Service works!" + "</message>";
   }
 
   @PUT
   @Path("/{employeeId}")
   @Produces(MediaType.TEXT_PLAIN)
   public String updateInfo(@PathParam("employeeId") String employeeId) {

    // CODE TO UPDATE EMPLOYEE RECORD GOES HERE
        
    return "Employee " + employeeId + " record is updated!";        
   
   }
   
   @GET
   @Path("/add/{n1}/{n2}")
   @Produces(MediaType.TEXT_HTML)
   public String add(@PathParam("n1") int n1, @PathParam("n2") int n2) {
    String output = "The sum of " + n1 + " and " + n2 + " is " + (n1 + n2);
    return "<html> " + "<title>" + "Jersey REST Demo" + "</title>"
         + "<body><h1>" + output + "</body></h1>" + "</html> ";
   }
}





4. Define the Jersey servlet dispatcher in your web.xml

You need to direct all the REST requests to the Jersey container by defining a servlet dispatcher in the application's web.xml file.

Modify the default web.xml created by Eclipse with the code below.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RESTfulWSDemo</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.ericsoriano.restwebservice</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>
 


NOTE: The values for the <servlet-class> and <param-name> are specifications for Jersey 2.0 and higher (Jersey 2.7 as of this writing).

The parameter <param-value>com.ericsoriano.restwebservice</param-value> defines the package Jersey will look at for the web service classes. This property must point to the package of your Java resource classes.

The <url-pattern>/rest/*</url-pattern> defines the base URL pattern to build the URL for your application's rest service classes.


5. Test the RESTful Web Service

Start your RESTful web service application by:

Right-click on project name > Run As > Run on Server

The URL consists of your host, port, context(project name), the servlet's url-pattern(eg.; /rest) from the web.xml configuration file, the /demo @Path annotation on your class file, and any @Path annotation on your methods (eg., /add/10/5)(see second test URL below).    


Test the REST service by typing the following URLs in the browser:

http://localhost:8080/RESTfulWSDemo/rest/demo

Returns this response on the browser:  Jersey REST Web Service works!

See browser screenshot below:





http://localhost:8080/RESTfulWSDemo/rest/demo/add/10/5

Returns this response on the browser:  The sum of 10 and 5 is 15

See browser screenshot below:




Saturday, April 26, 2014

How to Create a Web Application Project with Maven in Eclipse

In this tutorial, we will see how to create a web application in Eclipse using Maven's m2eclipse plugin. The m2eclipse plugin comes with the Eclipse IDE version 4.3.2.

Tools used:
1. Eclipse IDE for Java EE Developers 4.3.2   (Kepler)
2. Tomcat 7
3. JDK 1.7
4. Maven Eclipse Plugin - m2eclipse version 1.4


1. Create the Maven project in Eclipse

Click on File > New > Project > Maven > select Maven Project > click Next button





You will now get the screen below. Just check the box for 'Use default Workspace location' if it's not checked by default. Click the 'Next' button.





You will now get the screen below. You will need to select an archetype. An archetype is just ta template that Maven will use for your new web application project.

Enter 'webapp' into the filter textbox and select 'maven-archetype-webapp' from the list.

Click the 'Next' button.





You will now get the screen below. You need to enter your maven project's group Id, Artifact Id, Version and Package information. The 'Artifact Id' is your project's name.




Click the 'Finish' button. This will create your Maven project in eclipse.
You should now see the new project in the Package Explorer.



2.  Add the 'Server Runtime' library in the project's  'Java Build Path'  property.

Right-click on the project name > Properties > Java Build Path




Click on Add Library > select Server Runtime > select a servlet container (eg.; Apache Tomcat) > click on Finish.

You will be back on the screen above.

Click on Ok.

Eclipse should then automatically take the servlet container's libraries into the build path.

You should now see the servlet container library (eg.; Apache Tomcat library) in your projects directory.
You should also now see the following source folders created under your project's directory.

  • src/main/java
  • src/test/java

If it was not created, you may manually create it.



3.  Add or change (optional)  the 'JRE System Library' in the project's  'Java Build Path'  property.

Note that the list of libraries on the Java Build Path now shows Apache Tomcat (the Server Runtime library we added in the previous step).

You may now change the JRE System Library (optional - only if you want to) or add a JRE System Library if the  Java Build Path does not have one yet.

Right-click on the project name > Properties > Java Build Path 




Click on Add Library > select JRE System Library > click Next > choose your JRE (eg.; Workspace default JRE or Alternate JRE) > click on Finish.


Running this project in its bare form should give you the 'Hello World' webpage from index.jsp. Try it.

That's it. Your Maven web project in eclipse is now ready. You can now start adding dependencies and code to your project.