Monday, June 20, 2016

RESTful Web Services(JAX-RS) in JavaEE with IntelliJ IDEA

What Are RESTful Web Services?

RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

Create a new JavaEE Web Module 

File - New Project - Select JavaEE Web Module 




In the IntelliJ IDEA, the RESTful Web Services development is based on the Java EE: RESTful Web Services (JAX-RS) plugin. Usually this plugin is bundled with IntelliJ IDEA and enabled by default.
To check whether plugin is enable or not go to Setting Dialog (Ctrl+Alt+S), from the left hand side select Plugins, After that type restful in the search box and check whether Java EE: RESTful Web Services (JAX-RS) is selected. if it's not make sure to enable that.

To add JAX-RS to the project right click on the project and click on Add Framework Support and put a tick to Restful Web Service element and make sure to select Download option to download the required libraries, and press OK



After that again right click on the project and click Open Module Settings - Go to libraries and click on the Change Version button and select jax-rs-jersey-1.12 and click OK. In the latest Jersey library HttpServerFactory class is not included but in this example we are using that class to create the server therefor we need to change the version in to jax-rs-jersey-1.12.



Now lets create the Restful Server

First Create a Class called CompanyDetails and modify it as below, This class we are using as a Data Model to return a details object.

/**
 * Created by easywayforcoadings on 6/20/16.
 */
public class CompanyDetails {

    private String welcomeMessage;
    private String companyName;
    private String companyAddress;
    private Integer companyPhone;

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getCompanyAddress() {
        return companyAddress;
    }

    public void setCompanyAddress(String companyAddress) {
        this.companyAddress = companyAddress;
    }

    public int getCompanyPhone() {
        return companyPhone;
    }

    public void setCompanyPhone(int companyPhone) {
        this.companyPhone = companyPhone;
    }
}


Create a new Class Called RestServer and change it as below Code Segment. This is the class we are going to use as the Server.

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import com.sun.net.httpserver.HttpServer;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/company_service/{username}")
public class RestServer {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public CompanyDetails getCompanyDetails(@PathParam("username") String userName) {

        CompanyDetails companyDetails = new CompanyDetails();
        companyDetails.setWelcomeMessage("Hello "+userName);
        companyDetails.setCompanyName("MY COMPANY PVT");
        companyDetails.setCompanyAddress("No. 111/1, MY ADDRESS");
        companyDetails.setCompanyPhone(123456789);
        return companyDetails;
    }

    public static void main(String[] args) throws IOException {

        HttpServer server = HttpServerFactory.create("http://localhost:9998/");
        server.start();

        System.out.println("Server running");
        System.out.println("Visit: http://localhost:9998/company_service/[userName]'");
        System.out.println("Hit return to stop...");
        System.in.read();
        System.out.println("Stopping server");
        server.stop(0);
        System.out.println("Server stopped");
    }
}

After that Save All, right click on the RestServer Class and click on Run 'RestServer.Main()' to start the server

Open the browser and check whether service is working or not via this address 

http://localhost:9998/company_service/easywayforcoadings123


Stop the server and lets create a Client to access our Restful Service

In the same project create a new Class called RestClient and change it as below 

/**
 * Created by easywayforcoadings on 6/20/16.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RestClient {

    public static void main(String[] argv) {

        try {

            URL url = new URL("http://localhost:9998/company_service/easywayforcoadings123");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

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

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Json Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }


    }
}

Save All and Right click on the RestServer to start the server first by clicking on Run 'RestServer.Main()' and finally right click on the RestClient and click on Run 'RestClient .Main()'


Output Result -:



Get more from  : http://techprogramme.com/