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

com.github.gkutiel.flip.web.Web Maven / Gradle / Ivy

package com.github.gkutiel.flip.web;

import java.util.logging.Logger;

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

import com.github.gkutiel.flip.Fliplet;
import com.github.gkutiel.flip.RedirectException;

public class Web implements Req, Fliplet {

	private static final Logger LOGGER = Logger.getLogger(Web.class.getCanonicalName());

	protected HttpServletRequest req;
	protected HttpServletResponse res;

	@Override
	public  T get(final Key key) {
		final T t = HttpUtils.get(req.getCookies(), key);
		if (t == null) del(key.name());
		return t;
	}

	@Override
	public final void set(final HttpServletRequest req, final HttpServletResponse res) {
		this.req = req;
		this.res = res;
	}

	protected void del(final String key) {
		final Cookie c = new Cookie(key, "");
		c.setMaxAge(0);
		res.addCookie(c);
		LOGGER.info("DELETING COOKIE: " + key);
	}

	protected  T redirect(final String location) {
		throw new RedirectException(location);
	}

	protected  T redirectIfNull(final T value, final String location) {
		if (value != null) return value;
		return redirect(location);
	}

	protected String requestUrl() {
		final StringBuffer requestURL = req.getRequestURL();
		final String q = req.getQueryString();
		if (q != null) requestURL.append("?" + q);
		return requestURL.toString();
	}

	protected final  void set(final Key key, final T val) {
		this.set(key, val, Integer.MAX_VALUE);
	}

	protected 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