Sunday, November 27, 2016

Jersy 2.x Restful Service

package com.javatpoint.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
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.core.MediaType;
import javax.ws.rs.core.Response;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;


@Path("/ws")
public class ProductService {

 @GET
 @Path("/hellostring")
 @Produces(MediaType.TEXT_PLAIN)
 public String sayPlainTextHello() {
  return "Hello Jersey";
 }

 @GET
 @Path("/hellostring1")
 @Produces("text/plain")
 public String hello() {
  return "Hello World!!! dineshonjava";
 }


 @GET
 @Path("/hellohtml")
 @Produces(MediaType.TEXT_HTML)
 public String sayHtmlHello() {
  return "html " + "title" + "Hello Jersey" + "/title" + "bodyh1" + "Hello Jersey" + "/body/h1" + "/html ";
 }

 @GET
 @Path("/helloxml")
 @Produces(MediaType.TEXT_XML)
 public String sayXMLHello() {
  return "?xml version=\"1.0\"?" + "hello Hello Jersey" + "/hello";
 }


 @GET
 @Path("/test/{cusNo}")
 @Produces(MediaType.APPLICATION_JSON)
 public Customer produceCustomerDetailsinJSON(@PathParam("cusNo") int no) {
  Customer cust = new Customer();
  cust.setCustNo(no);
  cust.setCustName("Java4s");
  cust.setCustCountry("India");
  return cust;
 }

 @GET
 @Path("/employees")
 @Produces({
  MediaType.APPLICATION_XML,
  MediaType.APPLICATION_JSON
 })
 public List  Employee  listEmployees() {
//accept header value application/xml - return xml value
//accept header value application/json - return xml value
  return new ArrayList  Employee  (employees.values());
 }


 @GET
 @Path("/json/employees/")
 @Produces(MediaType.APPLICATION_JSON)
 public List  Employee  listEmployeesJSON() {
  return new ArrayList  Employee  (employees.values());
 }


 @Path("{word}")
 @GET
 @Produces("application/json")
 public Response reverser(@PathParam("word") String word) {
  StringBuilder sb = new StringBuilder();
  sb.append(word);
  ObjectMapper mapper = new ObjectMapper();
  ArrayNode arrayNode = mapper.createArrayNode();
  com.fasterxml.jackson.databind.node.ObjectNode node1 = mapper.createObjectNode();
  node1.put("original", sb.toString());
  node1.put("reversed", sb.reverse().toString());
  arrayNode.add(node1);
  return Response.status(200).entity(arrayNode.toString()).build();
 }

 @GET
 @Path("/hellojson")
 @Produces(MediaType.APPLICATION_JSON)
 public String sayJSONHello() {
  return "{\"Hello Jersey\":\"\"}";
 }

 @GET
 @Path("/get")
 @Produces(MediaType.APPLICATION_JSON)
 public Track getTrackInJSON() {
  Track track = new Track();
  track.setTitle("Enter Sandman");
  track.setSinger("Metallica");
  return track;
 }

 @GET
 @Path("/employee/{employeeid}")
 @Produces("application/xml")
 public Employee getEmployee(@PathParam("employeeid") String employeeId) {
  return employees.get(employeeId);
 }


 @GET
 @Path("/json/employee/{employeeid}")
 @Produces("application/json")
 public Employee getEmployeeJSON(@PathParam("employeeid") String employeeId) {
  return employees.get(employeeId);
 }

 @POST
 @Path("/post")
 @Consumes(MediaType.APPLICATION_JSON)// content-type must ne application/json
 public Response createTrackInJSON(Track track) {
  String result = "Track saved : " + track;
  System.out.println(result);
  return Response.status(201).entity(result).build();
 }

 @POST
 @Path("/add")
 public Response addUser(
  @FormParam("id") int id,
  @FormParam("name") String name,
  @FormParam("price") float price) {

  return Response.status(200)
   .entity(" Product added successfuly!br Id: " + id + "br Name: " + name + "br Price: " + price)
   .build();
 }


 private static Map  String, Employee  employees = new HashMap  String, Employee  ();

 static {

  Employee employee1 = new Employee();
  employee1.setEmployeeId("0");
  employee1.setEmployeeName("Dineh Rajput");
  employee1.setJobType("Sr.Software Engineer");
  employee1.setSalary(70000L);
  employee1.setAddress("Noida");
  employees.put(employee1.getEmployeeId(), employee1);

  Employee employee2 = new Employee();
  employee2.setEmployeeId("2");
  employee2.setEmployeeName("Abhishek");
  employee2.setJobType("Marketing");
  employee2.setSalary(50000L);
  employee2.setAddress("New Delhi");
  employees.put(employee2.getEmployeeId(), employee2);

 }


}


    $(document).ready(function(){
    // click on button submit
    $("#submit").on('click', function(){
    //var formData = JSON.stringify($("#myForm").serialize());
    var formData =JSON.stringify(QueryStringToJSON($("#myForm").serialize()));
    alert(formData);;
        // send ajax
    $.ajax({
     type: "POST",
     url: "http://localhost:8080/restfuljerseyformparam/rest/ws/post",
     data: formData,
     success: function(result){console.log(result);alert(result);},
     dataType: "json",
     contentType : "application/json"
    });
});
      });    
     
      function QueryStringToJSON(str) {          
       var pairs = str.split('&');
       var result = {};
       pairs.forEach(function(pair) {
           pair = pair.split('=');
           var name = pair[0]
           var value = pair[1]
           if( name.length )
               if (result[name] !== undefined) {
                   if (!result[name].push) {
                       result[name] = [result[name]];
                   }
               result[name].push(value || '');
               } else {
                   result[name] = value || '';
               }
       });
       return( result );
    }


    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.javatpoint.rest,com.fasterxml.jackson.jaxrs.json /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


No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...