
com.github.gkutiel.flip.web.Flipper Maven / Gradle / Ivy
package com.github.gkutiel.flip.web;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Flipper {
static class RedirectException extends RuntimeException {
public RedirectException(final String msg) {
super(msg);
}
}
private static final Logger LOGGER = Logger.getLogger(Flipper.class.getCanonicalName());
HttpServletRequest req;
HttpServletResponse res;
public void del(final String key) {
final Cookie c = new Cookie(key, "");
c.setMaxAge(0);
res.addCookie(c);
LOGGER.info("DELETING COOKIE: " + key);
}
public final T get(final Key key) {
final String val = HttpUtils.get(req.getCookies(), key.name());
if (val == null) return null;
final T t = HttpUtils.verify(val, key.valType());
if (t == null) del(key.name());
return t;
}
public T redirect(final Class> c, final String method) {
final StringBuilder url = new StringBuilder();
url.append("/");
url.append(c.getSimpleName());
if (method != null) {
url.append("/");
url.append(method);
}
return this.redirect(url.toString());
}
public T redirect(final String location) {
try {
res.sendRedirect(location);
throw new RedirectException(location);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
public T redirectIfNull(final T value, final String location) {
if (value != null) return value;
return redirect(location);
}
public final void set(final Key key, final T val) {
this.set(key, val, -1);
}
public final void set(final Key key, final T val, final int maxAge) {
if (val == null) throw new NullPointerException("val can't be null");
final Cookie c = HttpUtils.signedCookie(key.name(), val);
c.setPath("/");
c.setMaxAge(maxAge);
res.addCookie(c);
LOGGER.info("SETTING COOKIE: " + c.getName() + " : " + c.getValue());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy