WhoMakesTheJSessionId.java

/*
 * Copyright 2019 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.gringlobal.spring;

import java.util.Arrays;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import lombok.extern.slf4j.Slf4j;

/**
 * Enable this {@link WebListener} to figure out what initates the HTTP Session.
 *
 * <ul>
 * <li>init.jsp: session="false"</li>
 * <li>_csrf.getToken() then creates the session anyway in decorators -- this is
 * used for AJAX requests</li>
 * </ul>
 *
 * @author Matija Obreza
 */
@Slf4j
public class WhoMakesTheJSessionId implements HttpSessionListener {

	public WhoMakesTheJSessionId() {
		System.err.println("WhoMakesTheJSessionId listener instantiated.");
	}

	@Override
	public void sessionCreated(final HttpSessionEvent se) {
		log.debug("HTTP Session {} created", se.getSession().getId());
		se.getSession().setMaxInactiveInterval(60 * 30);
		if (log.isTraceEnabled()) {
			StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
			StringBuilder sb= new StringBuilder();
			Arrays.stream(stackTrace).forEach((st) -> {
				sb.append(Thread.currentThread().getName());
				sb.append("\t");
				sb.append(st.getClassName());
				sb.append(":");
				sb.append(st.getMethodName());
				sb.append("(");
				sb.append(st.getFileName());
				sb.append(":");
				sb.append(st.getLineNumber());
				sb.append(")\n");
			});
			log.trace("Session {} created in:\n{}", se.getSession().getId(), sb);
		}
	}

	@Override
	public void sessionDestroyed(final HttpSessionEvent se) {
		log.debug("Session {} destroyed", se.getSession().getId());
	}
}