001package org.kohsuke.stapler.verb;
002
003import org.kohsuke.stapler.CancelRequestHandlingException;
004import org.kohsuke.stapler.StaplerRequest;
005import org.kohsuke.stapler.StaplerResponse;
006import org.kohsuke.stapler.interceptor.Interceptor;
007import org.kohsuke.stapler.interceptor.InterceptorAnnotation;
008
009import javax.servlet.ServletException;
010import java.lang.annotation.Annotation;
011import java.lang.reflect.InvocationTargetException;
012
013/**
014 * Restricts the routing to matching HTTP verbs.
015 *
016 * <h2>Usage</h2>
017 * <p>
018 * This package defines a number of HTTP verb (method) annotations that can be used to restrict
019 * routing. For example,
020 *
021 * <pre>
022 * &#64;WebMethod(name="") &#64;DELETE
023 * public void delete() {
024 *     // this method will be invoked only when the request is DELETE
025 *     ...
026 * }
027 *
028 * &#64;WebMethod(name="") &#64;POST
029 * public void create(&#64;JsonBody Order order) {
030 *     // this method will be invoked only when the request is POST
031 *     ...
032 * }
033 * </pre>
034 *
035 * <p>
036 * This class is the actual logic that implements this semantics on top of {@link Interceptor}.
037 *
038 * @author Kohsuke Kawaguchi
039 * @see GET
040 * @see POST
041 * @see PUT
042 * @see DELETE
043 */
044public class HttpVerbInterceptor extends Interceptor {
045    @Override
046    public Object invoke(StaplerRequest request, StaplerResponse response, Object instance, Object[] arguments) throws IllegalAccessException, InvocationTargetException, ServletException {
047        if (matches(request))
048            return target.invoke(request,response,instance,arguments);
049        else
050            throw new CancelRequestHandlingException();
051    }
052
053    private boolean matches(StaplerRequest request) {
054        String method = request.getMethod();
055
056        for (Annotation a : target.getAnnotations()) {
057            Class<? extends Annotation> t = a.annotationType();
058            InterceptorAnnotation ia = t.getAnnotation(InterceptorAnnotation.class);
059            if (ia != null && ia.value() == HttpVerbInterceptor.class) {
060                if (t.getSimpleName().equals(method)) {
061                    return true;
062                }
063            }
064        }
065        return false;
066    }
067}