com.cybermkd.common.util.Cookier Maven / Gradle / Ivy
package com.cybermkd.common.util;
import com.cybermkd.common.http.HttpRequest;
import com.cybermkd.common.http.HttpResponse;
import com.cybermkd.common.util.json.Jsoner;
import com.alibaba.fastjson.TypeReference;
import java.util.HashMap;
import java.util.Map;
import static com.cybermkd.common.util.Checker.checkArgument;
/**
* @author Dreampie
* @date 2015-10-22
* @what
*/
public class Cookier {
private HttpRequest request;
private HttpResponse response;
private Map cookies;
public Cookier(HttpRequest request) {
this(request, null);
}
public Cookier(HttpResponse response) {
this(null, response);
}
public Cookier(HttpRequest request, HttpResponse response) {
checkArgument(request != null || response != null, "You must set request or response.");
this.request = request;
this.response = response;
this.cookies = new HashMap();
}
public String get(String name) {
return request.getCookiesMap().get(name);
}
public T get(String name, TypeReference type) {
Object result = null;
if (cookies.containsKey(name)) {
result = cookies.get(name);
} else {
Map cookieMap = request.getCookiesMap();
if (cookieMap.containsKey(name)) {
result = Jsoner.toObject(cookieMap.get(name), type);
cookies.put(name, result);
}
}
return (T) result;
}
public T get(String name, Class clazz) {
Object result = null;
if (cookies.containsKey(name)) {
result = cookies.get(name);
} else {
Map cookieMap = request.getCookiesMap();
if (cookieMap.containsKey(name)) {
result = Jsoner.toObject(cookieMap.get(name), clazz);
cookies.put(name, result);
}
}
return (T) result;
}
public void save(String name, Object value, int expiration) {
String v;
if (value instanceof String) {
v = (String) value;
} else {
v = Jsoner.toJSON(value);
}
response.addCookie(name, v, expiration);
}
}