de.otto.mongodb.profiler.web.CacheInterceptor.java Source code

Java tutorial

Introduction

Here is the source code for de.otto.mongodb.profiler.web.CacheInterceptor.java

Source

/*
 *  Copyright 2013 Robert Gacki <robert.gacki@cgi.com>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.otto.mongodb.profiler.web;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Controls caching of handler method calls.
 */
public class CacheInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (noCache(handler)) {
            response.addHeader("Cache-Control", "no-cache");
            response.addHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "must-revalidate");
            response.addHeader("Cache-Control", "max-age=0");
            response.addHeader("Cache-Control", "max-stale=0");
            response.addHeader("Cache-Control", "post-check=0");
            response.addHeader("Cache-Control", "pre-check=0");
            response.addHeader("Pragma", "no-cache");
        }

        return true;
    }

    protected boolean noCache(Object handler) {

        if (handler instanceof HandlerMethod) {
            return noCache(((HandlerMethod) handler));
        }

        return false;
    }

    protected boolean noCache(HandlerMethod handler) {

        return handler.getMethodAnnotation(NoCache.class) != null
                || AnnotationUtils.findAnnotation(handler.getBeanType(), NoCache.class) != null;
    }

}