RequestTrackingInterceptor.java

/**
 * Copyright 2014 Global Crop Diversity Trust
 *
 * 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 org.genesys.spring;

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

import org.apache.http.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//@Component
public class RequestTrackingInterceptor implements HandlerInterceptor {
	private static final Logger LOG = LoggerFactory.getLogger(RequestTrackingInterceptor.class);

	@Autowired
	private RequestTracker requestTracker;

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object x, Exception e) throws Exception {
		if (e == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Examining last request {} {} req={} respo={}", req.getMethod(), req.getServletPath(), req.getContentType(), res.getHeader(HttpHeaders.CONTENT_TYPE));
			}

			String ct = res.getHeader(HttpHeaders.CONTENT_TYPE);
			if ("GET".equals(req.getMethod()) && ct != null && ct.toLowerCase().startsWith("text/html")) {
				if (LOG.isInfoEnabled()) {
					LOG.info("Recording last GET request {}? {}", req.getServletPath(), req.getQueryString());
				}
				requestTracker.setLastGet(req.getServletPath() + (req.getQueryString() == null ? "" : "?" + req.getQueryString()));
			}
		}
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		return true;
	}

}