Sunday, April 23, 2017

Java Program for JSON RESTful Web Service Example

In this post, I intend to provide the sample code to prepare a Java RESTful web service to GET and POST JSON message. Jersey has been used to create the service.

Here is the Dynamic Web Project structure:
(Ignore the errors. Update Maven and those will be gone. The below code works fine.)




  • 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>Restful Web Application</display-name>
  <servlet>
    <servlet-name>jersey-XMLExample-serlvet</servlet-name>
    <servlet-class>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com</param-value>
    </init-param>
    <init-param>
      <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>jersey-XMLExample-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>


  • pom.xml:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javacodegeeks.enterprise.rest.jersey</groupId>
<artifactId>JerseyJSONExample</artifactId>
<version>0.0.1-SNAPSHOT</version>

<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>

<dependencies>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.9</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.9</version>
</dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.9</version>
</dependency>



</dependencies>

</project>


  • Student.java:


package com.webService;


public class Student {

private int id;
private String firstName;
private String lastName;
private int age;

// Must have no-argument constructor
public Student() {

}

public Student(String fname, String lname, int age, int id) {
this.firstName = fname;
this.lastName = lname;
this.age = age;
this.id = id;
}

public void setFirstName(String fname) {
this.firstName = fname;
}

public String getFirstName() {
return this.firstName;
}


public void setLastName(String lname) {
this.lastName = lname;
}

public String getLastName() {
return this.lastName;
}


public void setAge(int age) {
this.age = age;
}

public int getAge() {
return this.age;
}


public void setId(int id) {
this.id = id;
}

public int getId() {
return this.id;
}

@Override
public String toString() {
return new StringBuffer(" First Name : ").append(this.firstName)
.append(" Last Name : ").append(this.lastName)
.append(" Age : ").append(this.age).append(" ID : ")
.append(this.id).toString();
}

}


  • JerseyRestService.java:


package com.webService;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/jsonServices")
public class JerseyRestService {


@GET
@Path("/show/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Student produceJSON( @PathParam("name") String name ) {

Student st = new Student(name,"Mathews",36,1);

return st;

}

@POST
@Path("/sendMessage")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON( Student student ) {

String output = student.toString();

return Response.status(200).entity(output).build();
}

}

  • JerseyClient.java:

package com.serviceClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.webService.Student;
// http://localhost:8080/JavaWebService/rest/jsonServices/show/Pradeep -- GET
// http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage -- POST
/*{
 "id": 1,
 "firstName": "MS",
 "lastName": "Dhoni",
 "age": 35
}*/
public class JerseyClient {

public static void main(String[] args) {
try {

Student st = new Student("Steve", "Smith", 28, 8);
ClientConfig clientConfig = new DefaultClientConfig();

clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

Client client = Client.create(clientConfig);

WebResource webResource = client
.resource("http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage");

ClientResponse response = webResource.accept("application/json")
.type("application/json").post(ClientResponse.class, st);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

String output = response.getEntity(String.class);

System.out.println("Server response! \n");
System.out.println(output);

} catch (Exception e) {

e.printStackTrace();

}

}

}


Run the Project on Server (e.g: Tomcat/Wildfly) and user the below URLs to see how it works:

  • GET:

http://localhost:8080/JavaWebService/rest/jsonServices/show/George


  • POST:

http://localhost:8080/JavaWebService/rest/jsonServices/sendMessage

Use the below JSON message to post from Postman or any other tool you prefer.

{
 "id": 1,
 "firstName": "MS",
 "lastName": "Dhoni",
 "age": 35
}

Thursday, April 30, 2015

Java Program to Implement Stack using Linked List

import java.util.*;
/*  Class Node  */
class Node
{
    protected int data;
    protected Node link;

    /*  Constructor  */
    public Node()
    {
        link = null;
        data = 0;
    }   
    /*  Constructor  */
    public Node(int d,Node n)
    {
        data = d;
        link = n;
    }   
    /*  Function to set link to next Node  */
    public void setLink(Node n)
    {
        link = n;
    }   
    /*  Function to set data to current Node  */
    public void setData(int d)
    {
        data = d;
    }   
    /*  Function to get link to next node  */
    public Node getLink()
    {
        return link;
    }   
    /*  Function to get data from current Node  */
    public int getData()
    {
        return data;
    }
}
/*  Class linkedStack  */
class linkedStack
{
    protected Node top ;
    protected int size ;

    /*  Constructor  */
    public linkedStack()
    {
        top = null;
        size = 0;
    }   
    /*  Function to check if stack is empty */
    public boolean isEmpty()
    {
        return top == null;
    }   
    /*  Function to get the size of the stack */
    public int getSize()
    {
        return size;
    }   
    /*  Function to push an element to the stack */
    public void push(int data)
    {
        Node nptr = new Node (data, null);
        if (top == null)
            top = nptr;
        else
        {
            nptr.setLink(top);
            top = nptr;
        }
        size++ ;
    }   
    /*  Function to pop an element from the stack */
    public int pop()
    {
        if (isEmpty() )
            throw new NoSuchElementException("Underflow Exception") ;
        Node ptr = top;
        top = ptr.getLink();
        size-- ;
        return ptr.getData();
    }   
    /*  Function to check the top element of the stack */
    public int peek()
    {
        if (isEmpty() )
            throw new NoSuchElementException("Underflow Exception") ;
        return top.getData();
    }   
    /*  Function to display the status of the stack */
    public void display()
    {
        System.out.print("\nStack = ");
        if (size == 0)
        {
            System.out.print("Empty\n");
            return ;
        }
        Node ptr = top;
        while (ptr != null)
        {
            System.out.print(ptr.getData()+" ");
            ptr = ptr.getLink();
        }
        System.out.println();       
    }
}

/* Class LinkedStackImplement */
public class LinkedStackImplement
{   
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);  
        /* Creating object of class linkedStack */  
        linkedStack ls = new linkedStack();         
        /* Perform Stack Operations */ 
        System.out.println("Linked Stack Test\n"); 
        char ch;    
        do
        {
            System.out.println("\nLinked Stack Operations");
            System.out.println("1. push");
            System.out.println("2. pop");
            System.out.println("3. peek");
            System.out.println("4. check empty");
            System.out.println("5. size");           
            int choice = scan.nextInt();
            switch (choice)
            {
            case 1 :
                System.out.println("Enter integer element to push");
                ls.push( scan.nextInt() );
                break;                        
            case 2 :
                try
                {
                    System.out.println("Popped Element = "+ ls.pop());
                }
                catch (Exception e)
                {
                    System.out.println("Error : " + e.getMessage());
                }   
                break;                        
            case 3 :
                try
                {
                    System.out.println("Peek Element = "+ ls.peek());
                }
                catch (Exception e)
                {
                    System.out.println("Error : " + e.getMessage());
                }
                break;                        
            case 4 :
                System.out.println("Empty status = "+ ls.isEmpty());
                break;               
            case 5 :
                System.out.println("Size = "+ ls.getSize());
                break;               
            case 6 :
                System.out.println("Stack = ");
                ls.display();
                break;                       
            default :
                System.out.println("Wrong Entry \n ");
                break;
            }          
            /* display stack */   
            ls.display();           
            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);      

        } while (ch == 'Y'|| ch == 'y');                
    }
}

Thursday, October 30, 2014

Java Program to demonstrate Exception Handling using try-catch block



public class MyExceptionHandle {
    public static void main(String a[]){
        try{
            for(int i=5;i>=0;i--){
                System.out.println(10/i);
            }
        } catch(Exception ex){
            System.out.println("Exception Message: "+ex.getMessage());
            ex.printStackTrace();
        }
        System.out.println("After for loop...");
    }
}


Output:

2
2
3
5
10
Exception Message: / by zero
java.lang.ArithmeticException: / by zero
        at com.myjava.exceptions.MyExceptionHandle.main(MyExceptionHandle.java:12)
After for loop...

Java Program to read integers from file with Scanner class


import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class ReadIntegers
{
    public static void main(String[] args)
    { try
{   Scanner s = new Scanner( new File("integers.dat") );
   while( s.hasNextInt() )
   { System.out.println( s.nextInt() );
   }
}
catch(IOException e)
{ System.out.println( e );
}
    }
}

Java Program to write 100 random integers to a file, 1 per line


import java.io.PrintStream;
import java.io.IOException;
import java.io.File;

import java.util.Random;

public class IntegersToFile
{ public static void main(String[] args)
{ try
{ PrintStream writer = new PrintStream( new File("randInts.txt"));
Random r = new Random();
final int LIMIT = 100;

for(int i = 0; i < LIMIT; i++)
{ writer.println( r.nextInt() );
}
writer.close();
}
catch(IOException e)
{ System.out.println("An error occured while trying to write to the file");
}
}
}

Java program to take input from Keyboard with Scanner class


import java.util.Scanner;

public class KeyboardInput
{

public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.print( "Enter your name: "  );
String name = s.nextLine();
System.out.println( "Hello " + name + "!" );
}
}

Sunday, October 26, 2014

Java Program to demonstrate Set


SetExample.java:

import java.util.*;

public class SetExample {

   public static void main(String args[]) {

       // We create a new, empty set
       Set mySet1 = new HashSet();
       // We add a few elements
       mySet1.add("A");
       mySet1.add("C");
       mySet1.add("A");
       mySet1.add("B");
       // Print the elements of the Set
       System.out.println("mySet1: " + mySet1);

       // Create a list and add some elements
       List list = new ArrayList();
       list.add("A");
       list.add("C");
       list.add("A");
       list.add("A");
       list.add("B");
       list.add("C");
       // Now create the set using the appropriate constructor
       Set mySet2 = new HashSet(list);
       // Print the elements of the list an the the set
       System.out.println("list: " + list);
       System.out.println("mySet2: " + mySet2);

       // Compare the two sets
       System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

       // Now we will remove one element from mySet2 and compare again
       mySet2.remove("A");
       System.out.println("mySet2: " + mySet2);
       System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

       // Lets check if our sets contain all the elements of the list
       System.out.println("MySet1 contains all the elements: " + mySet1.containsAll(list));
       System.out.println("MySet2 contains all the elements: " + mySet2.containsAll(list));

       // Use of Iterator in Set
       Iterator iterator = mySet1.iterator();
       while (iterator.hasNext()) {
           System.out.println("Iterator loop: " + iterator.next());
       }

       // Use of for-each in Set
       for (String str : mySet1) {
           System.out.println("for-each loop: " + str);
       }

       // Clearing all the elements
       mySet1.clear();
       System.out.println("mySet1 is Empty: " + mySet1.isEmpty());

       // Checking the number of elements
       System.out.println("mySet1 has: " + mySet1.size() + " Elements");
       System.out.println("mySet2 has: " + mySet2.size() + " Elements");

       // Creating an Array with the contents of the set
       String[] array = mySet2.toArray(new String[mySet2.size()]);
       System.out.println("The array:" + Arrays.toString(array));
   }
}
Output:
mySet1: [A, B, C]
list: [A, C, A, A, B, C]
mySet2: [A, B, C]
MySet1 matches mySet2: true
mySet2: [B, C]
MySet1 matches mySet2: false
MySet1 contains all the elements: true
MySet2 contains all the elements: false
Iterator loop: A
Iterator loop: B
Iterator loop: C
for-each loop: A
for-each loop: B
for-each loop: C
mySet1 is Empty: true
mySet1 has: 0 Elements
mySet2 has: 2 Elements
The array:[B, C]