package de.juplo.yourshouter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.CookieGenerator;
import org.thymeleaf.util.StringUtils;
/**
* Utility class for managing the cookie that remembers the user.
*
* @author Kai Moritz
*/
final class UserCookieGenerator
{
private final static Logger LOG =
LoggerFactory.getLogger(UserCookieGenerator.class);
public final static UserCookieGenerator INSTANCE = new UserCookieGenerator();
private final CookieGenerator generator = new CookieGenerator();
/**
* Constructs an instance of this class, using user
as the
* cookie-name.
*/
private UserCookieGenerator()
{
generator.setCookieName("user");
}
/**
* Creates a cookie with the name user
, that stores the ID of
* the user for subsequent calls.
*
* @param user
* The ID of the current user
* @param response
* The {@link HttpServletResponse} to store the cookie in.
*/
public void addCookie(String user, HttpServletResponse response)
{
LOG.debug("adding cookie {}={}", generator.getCookieName(), user);
generator.addCookie(response, user);
}
/**
* Removes the cookie with the name user
by storing an empty
* string as its value.
*
* @param response
* The {@link HttpServletResponse} to remove the cookie from.
*/
public void removeCookie(HttpServletResponse response)
{
LOG.debug("removing cookie {}", generator.getCookieName());
generator.addCookie(response, "");
}
/**
* Reads the current value of the cookie with the name user
.
*
* @param request
* The {@link HttpServletRequest} to read the cookie-value from.
* @return
* The value of the cookie with the name user
, or
* null
, if no cookie by that name can be found or the value
* of the cookie is an empty string.
*/
public String readCookieValue(HttpServletRequest request)
{
String name = generator.getCookieName();
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (Cookie cookie : cookies)
{
if (cookie.getName().equals(name))
{
String value = cookie.getValue();
if (!StringUtils.isEmptyOrWhitespace(value))
{
LOG.debug("found cookie {}={}", name, value);
return value;
}
}
}
}
LOG.debug("cookie \"{}\" not found!", name);
return null;
}
}