001 package de.deepamehta.core.service; 002 003 import java.util.HashMap; 004 import java.util.Map; 005 006 007 008 /** 009 * Cookies sent by a client. 010 */ 011 public class ClientState { 012 013 // ---------------------------------------------------------------------------------------------- Instance Variables 014 015 private Map<String, String> values = new HashMap(); 016 017 // ---------------------------------------------------------------------------------------------------- Constructors 018 019 /** 020 * Converts a "Cookie" header value (String) to a map (key=String, value=String). 021 * E.g. "dm4_workspace_id=123; dm4_topicmap_id=234" => {"dm4_workspace_id"="123", "dm4_topicmap_id"="234"} 022 * <p> 023 * Called by JAX-RS container to create a ClientState from a "Cookie" @HeaderParam 024 */ 025 public ClientState(String cookie) { 026 if (cookie != null) { 027 for (String value : cookie.split("; ")) { 028 String[] val = value.split("=", 2); // Limit 2 ensures 2nd element in case of empty value 029 values.put(val[0], val[1]); 030 } 031 } 032 } 033 034 // -------------------------------------------------------------------------------------------------- Public Methods 035 036 /** 037 * Returns the value of the cookie for the given name, or throws an exception if no such cookie exists. 038 */ 039 public String get(String name) { 040 String value = values.get(name); 041 // 042 if (value == null) { 043 throw new RuntimeException("Missing \"" + name + "\" cookie (clientState=" + this + ")"); 044 } 045 // 046 return value; 047 } 048 049 /** 050 * Convenience method to access a long value of the cookie for the given name, or throws an exception 051 * if no such cookie exists. 052 */ 053 public long getLong(String name) { 054 try { 055 return Long.parseLong(get(name)); 056 } catch (Exception e) { 057 throw new RuntimeException("Getting a long value for the \"" + name + "\" cookie failed", e); 058 } 059 } 060 061 // --- 062 063 /** 064 * Checks if there is a cookie with the given name. 065 */ 066 public boolean has(String name) { 067 return values.get(name) != null; 068 } 069 070 // --- 071 072 @Override 073 public String toString() { 074 return values.toString(); 075 } 076 }