Saturday 23 August 2014

Conditional Get and Http Caching using Jersey

In this tutorial you will learn the conditional http feature using Jersey.The HTTP Protocol defines a caching mechanism, in which the proxy web-servers can cache pages, files, images etc. Since caching is in place, There is a method which the servers are asked to return the document, either the “cached” or “live” document.

This request of asking the server for a document considering a specific parameter is called a Conditional GET Request.

ETags or entity tags are useful HTTP headers which can help in building a super fast application by minimizing the server load on system. ETag is set to the response to the client so a client can use various control request headers such as If-Match and If-None-Match for conditional requests. javax.ws.rs.core.Response.ResponseBuilder#tag() and javax.ws.rs.core.EntityTag are useful classes to work on ETags.

On server side, a unchanged ETag (match done between ETag attached with HTTP request and ETag calculated for requested resource) simply means, resource is unchanged from last requested time, so simply sending a HTTP 304 header [Not Modified] will be enough so that client can use the local available copy of resource without worrying much.

To demonstrate the example, I have two REST APIs in Employee Service class.

a) GET http://localhost:8080/RestFileServer/service/employee-service/get-employee/1

This API will get the employee resource which will have a ETag attached to it. This ETag will be used by server to verify if employee details have been updated since last request or not.

b) PUT http://localhost:8080/RestFileServer/service/employee-service/update-employee/1

This API will update the employee resource and it  will force the server to return the new copy of resource again.

So Lets get started !

Employee.java

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "employee")
public class Employee implements Serializable {
@JsonProperty("id")
private int id;

@JsonProperty("firstName")
private String firstName;

@JsonProperty("lastName")
private String lastName;

@JsonProperty("last-modified")

private Date lastModified;

......//getter setters .........

Now we will create a dummy Employee database EmployeeData.

public class EmployeeData 
{
    public static HashMap<Integer, Employee> employees = new HashMap<Integer, Employee>();
    static
    {
        Employee emp = new Employee();
        emp.setId(1);
        emp.setFirstName("Kuntal");
        emp.setLastName("Ganguly");
        emp.setLastModified(new Date());
        employees.put(1, emp);
    }
     
    public static Employee getEmployeeById(Integer id)
    {
        return employees.get(id);
    }
     
    public static void updateEmployee(Integer id)
    {
        Employee emp = employees.get(id);
        emp.setLastName("Gangopadhay");
        emp.setLastModified(new Date());
    }
     
    public static Date getLastModifiedById(Integer id)
    {
        return employees.get(id).getLastModified();
    }

}

Finally the Employee Service.

@Path("/employee-service")
public class EmployeeService 
{
    @GET
    @Produces(MediaType.APPLICATION_JSON )
    @Path("/get-employee/{id}")
    public Response getEmployeeById(@PathParam("id") int id, @Context Request req) 
    {
        //Create cache control header
         CacheControl cc = new CacheControl();
         //Set max age to one day
         cc.setMaxAge(86400);
             
        Response.ResponseBuilder rb = null;
         
        //Calculate the ETag on last modified date of user resource  
        EntityTag etag = new EntityTag(EmployeeData.getLastModifiedById(id).hashCode()+"");
         
        //Verify if it matched with etag available in http request
        rb = req.evaluatePreconditions(etag);
         
        //If ETag matches the rb will be non-null; 
        //Use the rb to return the response without any further processing
        if (rb != null) 
        {
            return rb.cacheControl(cc).tag(etag).build();
        }
         
        //If rb is null then either it is first time request; or resource is modified
        //Get the updated representation and return with Etag attached to it
        rb = Response.ok(EmployeeData.getEmployeeById(id)).cacheControl(cc).tag(etag);
        return rb.build();
    }
     
    @PUT
    @Produces(MediaType.APPLICATION_JSON )
    @Path("/update-employee/{id}")
    public Response updateEmployeeById(@PathParam("id") int id) 
    {
        //Update the Employee resource
        EmployeeData.updateEmployee(id);
        return Response.status(200).build();
    }

}

After building and deploying this service in your server.You can navigate to the following and Validate:

1) First time request : GET http://localhost:8080/RestFileServer/service/employee-service/get-employee/1






2) Subsequent request(s) : GET http://localhost:8080/RestFileServer/service/employee-service/get-employee/1




3) Modify request : PUT http://localhost:8080/RestFileServer/service/employee-service/update-employee/1



4) Updated Resource : GET http://localhost:8080/RestFileServer/service/employee-service/get-employee/1




Hope you understand the http Caching and Conditional Get. :)
Download code

2 comments:



  1. مكافحة حشرات بالكويت
    كثير من الحشرات و الحيوانات الصغيرة موجودة في بيوتنا والتي نحن عادة لا أعرف. هذه الآفات تشغل مساحة المعيشة لدينا، و يقيم معظمهم في أماكن غير صحية أو التي هي غير نظيفة شركة مكافحة حشرات بالكويت . معظمهم من الآفات مثل الذباب والنمل و البق و غيرها من الحشرات تعيش في أو تتغذى على الغذاء وربما تحمل الأمراض والفيروسات المعدية التي يمكن أن تجعل لنا يصيبه على محمل الجد، إذا لم يتم السيطرة والقضاء عليها بشكل صحيح. شركة مكافحة حشرات يجب أن يمارس في المنازل وأماكن العمل أو أي مكان عام آخر من أجل توفير أكثر صحة وأمانا المحيطة بالنسبة لنا للعيش فيه.
    إذا كان منزلك وقد غزتها الآفات، تعرف أكثر على الأرجح مدى صعوبة أن تعالج المشكلة بنفسك. وهناك العديد من الآفات مما أسفر عن مصرع المواد للاستخدام المنزلي المتاحة في السوق، ولكن هذه قد لا تكون دائماً كفاءة. أنت بحاجة إلى الاستعانة بخدمات الآفات المهنية مراقبة فريق بويز للتخلص من جميع الآفات داخل منزلك، مكتب، أو أي منشأة أخرى. الآفات تمثل مصدر إزعاج كبير في أي منزل، وأنها يمكن أن تسبب أضرار رهيبة جداً. إذا قررت أن يكون هذه الآفات القضاء بطريقة مهنية، وعن طريق العلاج الصحيح والأكثر كفاءة يمكنك الاستمتاع مطهرة تماما والآفات مجاناً الصفحة الرئيسية.
    فى حال وجود حشرات بمنزلك اتصل بنا نحن شركة مكافحة حشرات
    من اهم واخطر الحشرات التي تنتشر في المملكه العربيه السعوديه هي “حشره النمل الابيض” وهي من اخطر ما يكن من الحشرات حيث انها تؤثر علي البنايات والقواعد الخرسانيه للبنايات مما يجعلها مهدده بالسقوط لو تمكن منها النمل الابيض (القرضه) وتعطى شركتنا على العمل ضمان يصل حتى عشرة سنوات ويتم القضاء على حشرة النمل الابيض نهائيا وفى حالة ظهور اى اصابة مره اخرى عند العميل يتم التعامل مع الاصابة فورا وبدون اى تكاليف على العميل ….
    نحن نقدم ايضا خدمة مكافحة قوارض

    ReplyDelete
  2. تركيب اثاث ايكيا بالرياض
    تركيب اثاث ايكيا بالرياض يعتبر من الأمور التي تحتاج إلى بعض المجهود والخبرة وذلك يتواجد لدينا، حيث تعمل على توفير كافة الادوات والآلات التي تساعد على تركيب جميع اثاث ايكيا بمختلف أنواعه سواء ثقيل أو خفيف و أيضاً غرف نوم وسفرة وغيرها من الأغراض الخشبية الاخرى، عن طريق فنيين متخصصين.

    ReplyDelete