CookieBaker - Dead Simple Java Library to Manipulate Cookies as POJOs
Language: Java
package geeks.aretotally.in.cookiebaker;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
/**
* CookieBaker helps you save and read simple pojos as cookies
*
* <p><b>Read Cookie</b></p>
* <p>SamplePojo o = CookieBaker.getCookie(request, SamplePojo.class, name);</p>
* <p><b>Write Cookie</b></p>
* <p>CookieBaker.saveCookie(response, name, new SamplePojo(arg1, arg2));</p>
*
* @author Felipe Oliveira
* @version 0.1
*
*/
public abstract class CookieBaker {
/** Logger - Log is never enough!. */
protected static Logger logger = Logger.getLogger(CookieBaker.class.getCanonicalName());
/** The mapper. */
private static transient ObjectMapper mapper;
/**
* Gets the mapper.
*
* @return the mapper
*/
private static ObjectMapper getMapper() {
if (mapper == null) {
mapper = new ObjectMapper();
}
return mapper;
}
/**
* Gets the values.
*
* @param <T>
* the generic type
* @param request
* the request
* @param clazz
* the clazz
* @param name
* the name
* @return the values
*/
@SuppressWarnings("unchecked")
public static <T extends Serializable> T getCookie(HttpServletRequest request, Class<T> clazz,String name) {
try {
// Get Cookie
Cookie cookie = getCookieByName(request, name);
if (cookie == null || cookie.getValue() == null) {
return null;
}
// Get Value
String value = cookie.getValue();
// Get Token
String existingCryptToken = HmacKeyUtil.seperateTokenFromCookieString(value);
String generatedToken = HmacKeyUtil.getCryptographicToken(HmacKeyUtil.seperateCookieStringFromToken(value));
// Check Token
if ( existingCryptToken == null || generatedToken == null ) {
throw new RuntimeException("Invalid Null Token!");
}
if(!existingCryptToken.equals(generatedToken)) {
throw new RuntimeException("Invalid Token Match - Existing Token: " + existingCryptToken + ", Generated Token: " + generatedToken);
}
// Map Object
Object data = getMapper().readValue(cookie.getValue(), clazz);
return (T) data;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Save.
*
* @param <T>
* the generic type
* @param response
* the response
* @param name
* the name
* @param object
* the object
*/
public static <T extends Serializable> void saveCookie(HttpServletResponse response,
String name, T object) {
saveCookie(response, name, object, "/", -1, null);
}
/**
* Save.
*
* @param <T>
* the generic type
* @param response
* the response
* @param name
* the name
* @param object
* the object
* @param path
* the path
* @param maxAge
* the max age
* @param domain
* the domain
*/
public static <T extends Serializable> void saveCookie(HttpServletResponse response, String name, T object, String path, Integer maxAge, String domain) {
try {
String value = getMapper().writeValueAsString(object);
setCookie(response, name, value, path, maxAge, domain);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Sets the cookie.
*
* @param response
* the response
* @param name
* the name
* @param value
* the value
* @param path
* the path
* @param maxAge
* the max age
* @param domain
* the domain
*/
private static void setCookie(HttpServletResponse response, String name, String value, String path, Integer maxAge, String domain) {
if (response == null) {
return;
}
String token = HmacKeyUtil.getCryptographicToken(value);
value = value + token;
Cookie c = new Cookie(name, value);
c.setPath(path);
c.setMaxAge(maxAge);
if ( domain != null ) {
c.setDomain(domain);
}
response.addCookie(c);
}
/**
* Gets the cookie by name.
*
* @param request
* the request
* @param name
* the name
* @return the cookie by name
*/
private static Cookie getCookieByName(HttpServletRequest request, String name) {
if (request == null) {
return null;
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Cookie c;
for (int i = 0; i < cookies.length; i++) {
c = cookies[i];
if (c != null && c.getName().equals(name)) {
return c;
}
}
}
return null;
}
}
package geeks.aretotally.in.cookiebaker;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class ExceptionUtil {
/**
* Get Print Stack Trace.
* @param exception the exception
* @return a String representation of the stack trace
*/
public static String getStackTrace(Exception exception) {
return getStackTrace( (Throwable) exception );
}
/**
* Get Print Stack Trace.
* @param exception the exception
* @return a String representation of the stack trace
*/
public static String getStackTrace(Throwable exception) {
return getStackTrace( null, exception );
}
/**
* Get Print Stack Trace.
* @param exception the exception
* @param title the title
* @return a String representation of the stack trace
*/
public static String getStackTrace(String title, Exception exception) {
return getStackTrace( title, (Throwable) exception );
}
/**
* Get Print Stack Trace.
* @param exception the exception
* @param title the title
*/
public static String getStackTrace(String title, Throwable exception) {
StringBuffer sb = new StringBuffer();
sb.append( "\n" );
if ( title != null ) {
sb.append( title );
sb.append( "\n\n" );
}
if ( exception != null ) {
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
exception.printStackTrace( new PrintStream( ostr ) );
sb.append( ostr );
}
return sb.toString();
}
}
package geeks.aretotally.in.cookiebaker;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
// TODO: Auto-generated Javadoc
/**
* The Class SecretWritingPassPhrase.
*/
public abstract class HmacKeyUtil {
/** Logger - Log is never enough!. */
protected static Logger logger = Logger.getLogger(HmacKeyUtil.class
.getCanonicalName());
/** The Constant CODE_DIGITS. */
private static final int CODE_DIGITS = 5;
/** The Constant HMAC. */
private static final String HMAC = "HmacSHA1";
/** The Constant SECRET. */
private static final String SECRET = "WRHLCESS!DDE";
/**
* Hmac_sha1.
*
* @param keyBytes
* the key bytes
* @param text
* the text
* @return the byte[]
*/
private static byte[] hmac_sha1(byte[] keyBytes, byte[] text) {
try {
Mac hmacSha1;
try {
hmacSha1 = Mac.getInstance(HMAC);
} catch (NoSuchAlgorithmException nsae) {
return new byte[0];
}
SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
hmacSha1.init(macKey);
return hmacSha1.doFinal(text);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Gets the cryptographic token.
*
* @param text
* the text
* @return the cryptographic token
*/
public static String getCryptographicToken(String text) {
try {
byte[] secretKey = SECRET.getBytes();
byte[] hash = hmac_sha1(secretKey, text.getBytes());
// Mask the output and get the first codeDigit characters
// as the cryptographic token
int offset = hash[hash.length - 1] & 0xf;
int binary = ((hash[offset] & 0x7f) << 24)
| ((hash[offset + 1] & 0xff) << 16)
| ((hash[offset + 2] & 0xff) << 8)
| (hash[offset + 3] & 0xff);
double otp = binary % Math.pow(10, CODE_DIGITS);
String result = Integer.toString((int) otp);
while (result.length() < CODE_DIGITS) {
result = "0" + result;
}
return result;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* Seperate token from cookie string.
*
* @param cookieString
* the cookie string
* @return the string
*/
public static String seperateTokenFromCookieString(String cookieString) {
return cookieString.substring(cookieString.length() - CODE_DIGITS,
cookieString.length());
}
/**
* Seperate cookie string from token.
*
* @param cookieString
* the cookie string
* @return the string
*/
public static String seperateCookieStringFromToken(String cookieString) {
return cookieString.substring(0, cookieString.length() - CODE_DIGITS);
}
}
Reveal More

