ETag Easy With RESTEasy

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on. In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

This article is a continuation of previous article

RESTEasy - A guide to implement CRUD Rest API

RESTEasy Advanced Guide - Filters and Interceptors

ETag:

ETag is an identifier passed in HTTP header for web cache validation and conditional requests for GET and PUT. There are two HTTP request header parameters like If-Match and If-None-Match to accomplish the functionalities of ETag. Read wiki for more info about ETag.

  • If-Match header ETag value matches in GET/PUT request it will produce/update the response otherwise preconditions failed message with status code 412
  • If-None-Match header ETag value doesn't match in GET/PUT request, it produces/update the response otherwise it returns the 304(Not modified)

Maven Dependency:

Start a maven web application project and add the following dependencies for rest easy framework:

<properties>
    <resteasy-version>3.7<resteasy-version>
</properties>

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>${resteasy-version}</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>${resteasy-version}</version>
</dependency>

To marshall and unmarshall Java entity, jettison provider need to be include in the dependency list.

<dependency>
   <groupId>org.jboss.resteasy</groupId>
   <artifactId>resteasy-jettison-provider</artifactId>
   <version>${resteasy-version}</version>
</dependency>

 

Create Service:

Let's create a employee model and rest service for create and update and see how it works.

  @XmlRootElement
  public class Employee {

      private int employeeId;
      private String employeeName;
      private long mobileNumber;
      private Date lastModifiedDate;

      public Employee() {
         this.lastModifiedDate = new Date();
      }

      public Employee(int employeeId, String employeeName, Long mobileNumber) {
         this.employeeId = employeeId;
         this.employeeName = employeeName;
         this.mobileNumber = mobileNumber;
         this.lastModifiedDate = new Date();
     }

      public int getEmployeeId() {
         return employeeId;
      }

      public void setEmployeeId(int employeeId) {
          this.employeeId = employeeId;
      }

      public String getEmployeeName() {
         return employeeName;
      }

      public void setEmployeeName(String employeeName) {
          this.employeeName = employeeName;
      }

      public long getMobileNumber() {
         return mobileNumber;
      }

      public void setMobileNumber(long mobileNumber) {
         this.mobileNumber = mobileNumber;
      }

      public Date getLastModifiedDate() {
         return this.lastModifiedDate;
      }

      public void updateDate() {
         this.lastModifiedDate = new Date();
      }
}

Employee rest service to get employee by id and patch request to update the mobile number for the employee. ETag has been generated using modified date field in employee model and evaluatePreconditions will do the magic of ETag validation. Add this EmployeeService class also singletons in ApplicationMain class.

 @Path("employees")
 public class EmployeeService {
 private static Map<Integer, Employee> employees = new HashMap<Integer, Employee>();
 static {
   employees.put(1, new Employee(1, "Nagappan", 9600030004));
 }

 @GET
 @Path("/{id}")
 @Produces({MediaType.APPLICATION_JSON})
 public Response getUserById(@PathParam("id") int id, @Context Request req) {
      CacheControl cc = new CacheControl();
      cc.setMaxAge(10);
      System.out.println(employees.get(id).getLastModifiedDate());

      EntityTag etag = new EntityTag(employees.get(id).getLastModifiedDate().hashCode()+"");
      Response.ResponseBuilder resp = req.evaluatePreconditions(etag);
      if (resp != null) {
           /* response code 412 for precondition failed.. */
           return resp.cacheControl(cc).tag(etag).build();
      } else {
         System.out.println("Pre-conditon matched");
      }

      System.out.println("generating response");
      return Response.status(200).entity(employees.get(id)).cacheControl(cc).tag(etag).build();
 }

 @PATCH
 @Path("/{id}/mobilenumber/{mobilenumber}")
 @Produces({MediaType.APPLICATION_JSON})
 public Response updateUserById(@PathParam("id") int id, @PathParam("mobilenumber") String mobilenumber, @Context Request req) {
       CacheControl cc = new CacheControl();
       cc.setMaxAge(1000);
       cc.setMustRevalidate(true);
       EntityTag etag = new EntityTag(employees.get(id).getLastModifiedDate().hashCode()+"");
       Response.ResponseBuilder resp = req.evaluatePreconditions(etag);
       if (resp!=null) {
           return resp.tag(etag).build();
       }
       employees.get(id).setMobileNumber(Long.parseLong(mobilenumber));
       employees.get(id).updateDate();
       return Response.status(200).entity("mobile number updated successfully").cacheControl(cc).build();
 }
}

Register service

Rest service registered to standalone Servlet container 3.0 ServletContainerInitializer by extending jax-rs Application class. ServletContainerInitializer is a programmatic way of registering servlets and services at the startup phase of webapplication

  @ApplicationPath("/rest")
  public class ApplicationMain extends Application {
  private Set<Object> singletons = new HashSet<>();

  public ApplicationMain() {
      singletons.add(new EmployeeService());
  }

  @Override
  public Set<Object> getSingletons() {
     return singletons;
   }
}

Now when we hit the employee get request, it responds with ETag value.

curl -i -X GET http://localhost:8080/resteasyexamples/rest/employees/1
HTTP/1.1 200
Cache-Control: no-transform, max-age=10
ETag: "-396822946"
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 24 May 2019 05:38:50 GMT

{"employee":{"employeeId":1,"employeeName":"Nagappan","mobileNumber":9600030004}}

 

Update the employee record only if it matches the ETag value

curl --header 'If-Match: -396822946' -i -X PATCH http://localhost:8080/resteasyexamples/rest/employees/1/mobilenumber/9000050002
HTTP/1.1 200
Content-Type: application/json
Content-Length: 34
Date: Fri, 24 May 2019 05:43:37 GMT

mobile number updated successfully

Then get the employee record to see the change has been affected. Here If-None-Match header has been used because previous update request would have changed the ETag so it should not be that value. Returned response has the change in Mobile number.

curl --header 'If-None-Match: -396822946' -i -X GET http://localhost:8080/resteasyexamples/rest/employees/1
HTTP/1.1 200
Cache-Control: no-transform, max-age=10
ETag: "-396510836"
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 24 May 2019 05:44:46 GMT

{"employee":{"employeeId":1,"employeeName":"Nagappan","mobileNumber":9000050002}}

If we give the above returned tag with header tag, if none match value, for get request we will get status code 304 resource not modified.

curl --header 'If-None-Match: -396510836' -i -X GET http://localhost:8080/resteasyexamples/rest/employees/1
HTTP/1.1 304
Cache-Control: no-transform, max-age=10
ETag: "-396510836"
Date: Fri, 24 May 2019 05:46:17 GMT

Likewise incorrect resource ETag given in if-match header, it will return precondition failed saying the resource with that ETag is not available.

curl --header 'If-Match: -396510835' -i -X GET http://localhost:8080/resteasyexamples/rest/employees/1
HTTP/1.1 412
Cache-Control: no-transform, max-age=10
ETag: "-396510836"
Content-Length: 0
Date: Fri, 24 May 2019 05:49:48 GMT

 

Reference:

RESTEasy Framework - https://resteasy.github.io/index.html

Code samples - https://github.com/nagappan080810/resteasy_workbook

 


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More



Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More


Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More


Laravel Paypal Integration - Smart button with server-side integration

  • laravel paypal smart-button

You would have seen a lot of blogs for paypal php integration with REST api which is driven completely in the backend. For checkout, paypal provides an easy way to checkout for client side ready-to-use smart button payment. This approach will work only from the frontend, which will not be safe and difficult to reconcile as the backend does not have any information about it. Server side integration with the paypal smart button will help us to reconcile or track the payments even after some issues in the users payment journey. In this blog, we have walkthrough the paypal smart button with server side php laravel integration.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


Angular Security - Authentication Service

  • angular security authentication jwt

Angular is a framework for creating single page web application. Angular facilitates the security feature and protection mechanism. It provides frameworks by verifying all the routing urls with security authguard interface to validate and verify the user and its permissions.

Read More


An introduction to web cache proxy server - nuster

  • web-cache proxy-server load-balancer

Nuster is a simple yet powerful web caching proxy server based on HAProxy. It is 100% compatible with HAProxy, and takes full advantage of the ACL functionality of HAProxy to provide fine-grained caching policy based on the content of request, response or server status. This article gives an overview of nuster - web cache proxy server, its installation and few examples of how to use it.

Read More


Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

Read More


Generate PDF from Javascript using jsPDF

  • pdf jspdf javascript

We show lot of data in our web applications, it will be awesome if we quickly download specific part of PDF rather than printing it. It will be easy to share for different stakeholders and also for focused meetings. In web application development, download to PDF means, we need to develop backend api specifically and then link it in frontend which takes longer development cylce. Instead it would be really great, if there is way to download what we see in the user interface quickly with few lines of Javascript, similar to export options in word processing application.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart php

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Solr vs Elastic Search

  • full-text-search search-engine lucene solr elastic-search

Solr and Elastic Search are built on top of Lucene. Both are open source and both have extra features which makes programmer life easy. This article explains the difference and the best situation to choose between them.

Read More


PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More


Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.