JBoss application server tutorials

  • Full Screen
  • Wide Screen
  • Narrow Screen
  • Increase font size
  • Default font size
  • Decrease font size

RESTEasy Interceptors tutorial - RESTEasy interceptors

The Interceptors offered by RESTEasy 2.x

RESTEasy 2.3 offers 3 types of interceptors:

  • MessageBodyReader and MessageBodyWriter Interceptors: Invoked around the HTTP Request body marshalling/unmarshalling;
  • Method execution interceptors: Invoked before(PreProcessInterceptor) and after (PostProcessInterceptor) the JAX-RS method execution;
  • Client side interceptors: Invoked before and after the client performed the request(if you call the ClientExecutionContext proceed() method it will perform the request). For more information about RESTEasy Client API, please see this article.

By default these interceptor will be invoked to all requests that comes to your JAX-RS service, but you can implement the interface AcceptedByMethod and read the service information(HTTP Method, method to be invoked, etc) to chose if your interceptor should be executed, or not.
That’s enough, that’s what we need to know for going on this article. If you want to know more about this, please check the RESTEasy documentation..

Adding Logging

To gather information from the client and information of the method which will be executed, we created a simple Server Interceptor which implements PreProcessInterceptor interface. This means that it will be called before the JAX-RS method execution.

package org.mastertheboss.resteasy.resources.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.logging.Logger;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;

@Provider
@ServerInterceptor
public class LoggingInterceptor implements PreProcessInterceptor {
    Logger logger = Logger.getLogger(LoggingInterceptor.class);

    @Context
    HttpServletRequest servletRequest;

    public ServerResponse preProcess(HttpRequest request,
            ResourceMethod resourceMethod) throws Failure,
            WebApplicationException {

        String methodName = resourceMethod.getMethod().getName();
        logger.info("Receiving request from: " + servletRequest.getRemoteAddr());
        logger.info("Attempt to invoke method \"" + methodName + "\"");
        if (methodName.equals("calculateAllBasicTrigonometricFunctions")) {
            logger.info("\tCalculate will be performed with parameters:");
            logger.info("\tAdjacent: "
                    + request.getFormParameters().get("adjacent"));
            logger.info("\tOpposite: "
                    + request.getFormParameters().get("opposite"));
            logger.info("\tHypotenusa: "
                    + request.getFormParameters().get("hypotenusa"));
        }
        if (methodName.equals("history")) {
            logger.info("Retrieving history...");
        }
        if (methodName.equals("clearAll")) {
            logger.info("User " + servletRequest.getRemoteUser()
                    + " is trying to clear the history...");
        }
        return null;
    }
}


The implemented method receives parameters which contains information about the request done and Java information about the JAX-RS method. Our LoggingInterceptor simple catch request and method information and then log it. Notice we can also inject resources into this interceptor, in this case we are injecting the ServletRequest. In the method implementation,

Adding RESTEasy Validation

As the basic trigonometric functions need all the right triangle information (adjacent, opposite and hypotenusa), we will perform validation before the JAX-RS method execution.

package org.mastertheboss.resteasy.resources.interceptors;

import static java.lang.Double.parseDouble;
import static java.lang.Math.pow;

import java.lang.reflect.Method;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.Headers;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.AcceptedByMethod;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;

@Provider
@ServerInterceptor
public class ValidationInterceptor implements PreProcessInterceptor,
        AcceptedByMethod {

    private double adjacent;
    private double opposite;
    private double hypotenusa;

    @SuppressWarnings("rawtypes")
    public boolean accept(Class c, Method m) {
        return m.getName().equals("calculateAllBasicTrigonometricFunctions");
    }

    public ServerResponse preProcess(HttpRequest request,
            ResourceMethod resourceMethod) throws Failure,
            WebApplicationException {

        // start server response as null and perform the validations, if it gets
        // some value, it will be a valid response and the interceptor will stop
        // the request
        ServerResponse response = null;
        try {
            adjacent = parseDouble(request.getFormParameters()
                    .get("adjacent").get(0));
            opposite = Double.parseDouble(request.getFormParameters()
                    .get("opposite").get(0));
            hypotenusa = Double.parseDouble(request.getFormParameters()
                    .get("hypotenusa").get(0));

            // Pythagoras
            boolean isValid = pow(adjacent, 2) + pow(opposite, 2) == pow(
                    hypotenusa, 2);
            // If it is not valid we will create a response with an appropriated
            // HTTP Code
            if (!isValid) {
                response = new ServerResponse("Not a valid right triangle",
                        400, new Headers<Object>());
            }
        } catch (Exception e) {
            response = new ServerResponse(
                    "Please verify the sent parameters, can't convert for use",
                    400, new Headers<Object>());
        }
        return response;
    }
}

 

  Notice this interceptor is implementing an the interface AcceptedByMethod. We also have to implement the method accept, where we receive the target method information and we can decide whether  if this interceptor will be executed or not. Also  notice that according the data sent by the client we will create a response which can stop the execution. If we return null the execution will flow normally, if we return a Server Response, the execution will stop in this method and the request will not get into your JAX-RS method neither in order interceptors.

 




Top Programming Sites
You are here Projects RESTEasy RESTEasy Interceptors tutorial - RESTEasy interceptors