All Downloads are FREE. Search and download functionalities are using the official Maven repository.

clime.messadmin.utils.SessionUtils Maven / Gradle / Ivy

Go to download

Notification system and Session administration for J2EE Web Applications

There is a newer version: 4.1.1
Show newest version
package clime.messadmin.utils;

import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import clime.messadmin.model.ISessionInfo;
import clime.messadmin.model.Server;
import clime.messadmin.providers.ProviderUtils;
import clime.messadmin.providers.spi.LocaleProvider;
import clime.messadmin.providers.spi.UserNameProvider;

/**
 * Utility methods on HttpSessions...
 * @author Cédrik LIME
 */
public class SessionUtils {

	/**
	 * 
	 */
	private SessionUtils() {
		super();
	}

	/**
	 * Try to get user locale from the session, if possible.
	 * @param httpSession
	 * @return Locale
	 */
	public static Locale guessLocaleFromSession(final HttpSession httpSession) {
		if (null == httpSession) {
			return null;
		}
		try {
			Iterator ps = ProviderUtils.getProviders(LocaleProvider.class).iterator();
			while (ps.hasNext()) {
				LocaleProvider provider = (LocaleProvider) ps.next();
				Locale locale = provider.guessLocaleFromSession(httpSession);
				if (locale != null)
					return locale;
			}
			return null;
		} catch (IllegalStateException ise) {
			//ignore: invalidated session
			return null;
		}
	}

	/**
	 * Try to get user from the session, if possible.
	 * @param httpSession
	 * @return Object
	 */
	public static Object guessUserFromSession(final HttpSession httpSession) {
		if (null == httpSession) {
			return null;
		}
		try {
			Iterator ps = ProviderUtils.getProviders(UserNameProvider.class).iterator();
			while (ps.hasNext()) {
				UserNameProvider provider = (UserNameProvider) ps.next();
				Object user = provider.guessUserFromSession(httpSession);
				if (user != null)
					return user;
			}
			return null;
		} catch (IllegalStateException ise) {
			//ignore: invalidated session
			return null;
		}
	}


	public static int getUsedTimeForSession(HttpSession in_session) {
		try {
			ISessionInfo extraSessionInfo = Server.getInstance().getSession(in_session).getSessionInfo();
			if (null != extraSessionInfo) {
				return extraSessionInfo.getTotalUsedTime();
			} else {
				return -1;
			}
			//long diffMilliSeconds = in_session.getLastAccessedTime() - in_session.getCreationTime();
			//return diffMilliSeconds;
		} catch (IllegalStateException ise) {
			//ignore: invalidated session
			return -1;
		}
	}

	public static int getTTLForSession(HttpSession in_session) {
		try {
			long diffMilliSeconds = (1000*in_session.getMaxInactiveInterval()) - (System.currentTimeMillis() - in_session.getLastAccessedTime());
			return (int) diffMilliSeconds;
		} catch (IllegalStateException ise) {
			//ignore: invalidated session
			return -1;
		}
	}

	public static int getIdleTimeForSession(HttpSession in_session) {
		try {
			long diffMilliSeconds =  System.currentTimeMillis() - in_session.getLastAccessedTime();
			return (int) diffMilliSeconds;
		} catch (IllegalStateException ise) {
			//ignore: invalidated session
			return -1;
		}
	}

	//TODO: move this method in a utility package

	/**
	 * Returns the context path of the web application. The context path is
	 * the portion of the request URI that is used to select the context of
	 * the request. The context path always comes first in a request URI. The
	 * path starts with a "/" character but does not end with a "/" character.
	 * For servlets in the default (root) context, this method returns "".
	 * 
	 * It is possible that a servlet container may match a context by more than
	 * one context path. In such cases getContextPath() will return the actual
	 * context path used by the request and it may differ from the path returned
	 * by this method. The context path returned by this method should be considered
	 * as the prime or preferred context path of the application.
	 * 
	 * @return The context path of the web application.
	 */
	/**
	 * FIXME debug this method so that it really works! Should return the same as HttpServletRequest.getContextPath(). Now, where the hell is ServletContext.getContextPath()? :-( UPDATE: it's in 2.5 now!
	 * Returns the portion of the request URI that indicates the context
	 * of the request.  The context path always comes first in a request
	 * URI.  The path starts with a "/" character but does not end with a "/"
	 * character.  For servlets in the default (root) context, this method
	 * returns "". The container does not decode this string.
	 * 
	 * It is possible that a servlet container may match a context by more
	 * than one context path. In such cases this method will return the actual
	 * context path used by the request and it may differ from the path returned
	 * by the ServletContext.getContextPath() method. The context path returned
	 * by ServletContext.getContextPath() should be considered as the prime or
	 * preferred context path of the application.
	 * 
	 * @param session
	 * @return	a String specifying the portion of
	 *			the request URI that indicates the context of the request
	 */
	public static String getContext(HttpSession session) {
		return getContext(session.getServletContext());
	}
	public static String getContext(ServletContext context) {
		//FIXME try new 2.5 ServletContext.getContextPath() first; use new plugin architecture
		try {
			return context.getResource("/").getPath();
		} catch (MalformedURLException mue) {
			throw new RuntimeException(mue.getMessage());
		}
	}

	/**
	 * Reconstructs the URL the client used to make the request,
	 * using information in the HttpServletRequest object.
	 * The returned URL contains a protocol, server name, port
	 * number, and server path, and include query
	 * string parameters.
	 * 
	 * 

This method is useful for creating redirect messages * and for reporting errors. * * @param req a HttpServletRequest object * containing the client's request * * @return a String object containing * the reconstructed URL */ public static String getRequestURLWithMethodAndQueryString(HttpServletRequest req) { /* StringBuffer url = new StringBuffer(32); String scheme = req.getScheme(); int port = req.getServerPort(); if (port < 0) { port = 80; // Work around java.net.URL bug } //String servletPath = req.getServletPath(); //String pathInfo = req.getPathInfo(); String queryString = req.getQueryString(); url.append(scheme); // http, https url.append("://"); //$NON-NLS-1$ url.append(req.getServerName()); if ((scheme.equals ("http") && port != 80) //$NON-NLS-1$ || (scheme.equals ("https") && port != 443)) { //$NON-NLS-1$ url.append (':'); //$NON-NLS-1$ url.append (port); } //if (servletPath != null) // url.append (servletPath); //if (pathInfo != null) // url.append (pathInfo); url.append(req.getRequestURI()); if (queryString != null) { url.append('?').append(queryString); //$NON-NLS-1$ } return url.toString(); */ String method = req.getMethod(); StringBuffer requestURL = req.getRequestURL(); String queryString = req.getQueryString(); int totalLength = method.length() + 1 + requestURL.length() + (queryString==null?0:1+queryString.length()); StringBuffer buffer = new StringBuffer(totalLength); buffer.append(method).append(' ').append(requestURL); if (queryString != null && !"".equals(queryString)) { buffer.append('?').append(queryString); } return buffer.toString(); } /** * HttpServletRequest.getLocales() returns the server's default locale * if the request did not specify a preferred language. * We do not want this behavior, because it prevents us from using * the fallback locale. * We therefore need to return an empty Enumeration if no preferred * locale has been specified. This way, the logic for the fallback * locale will be able to kick in. */ public static Enumeration getRequestLocales(HttpServletRequest request) { Enumeration values = request.getHeaders("accept-language");//$NON-NLS-1$ if (values.hasMoreElements()) { // At least one "accept-language". Simply return // the enumeration returned by request.getLocales(). return request.getLocales(); } else { // No header for "accept-language". Simply return // the empty enumeration. return values; } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy