// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.*;

import javax.servlet.http.*;

public class SuperCookie {
   private String name;
   private Map store;
   public SuperCookie(String name) {
      this.name = name;
      store = new HashMap();
   }
   public SuperCookie(Cookie ck) {
      this.name = ck.getName();
      store = new HashMap();
      String value = ck.getValue();
      String[] pairs = value.split("&");
      for(int i = 0; i < pairs.length; i++) {
         String[] parts = pairs[i].split("=");
         store.put(parts[0], parts[1]);
      }
   }
   public void add(String key, String value) {
      store.put(key,value);
   }
   public String get(String key) {
      return (String)store.get(key);
   }
   public Cookie getCookie() {
      StringBuffer values = new StringBuffer("");
      Iterator it = store.keySet().iterator();
      while(it.hasNext()) {
         if(values.length() > 0) {
            values.append("&");
         }
         String key = (String)it.next();
         String value = (String)store.get(key);
         values.append(key + "=" + value);
      }
      return new Cookie(name, values.toString());
   }
    public static void main(String[] args) {
      SuperCookie sck = new SuperCookie("test");
      sck.add("k1", "v1");
      sck.add("k2", "v2");
      Cookie ck = sck.getCookie();
      System.out.println(ck.getValue());
      SuperCookie sck2 = new SuperCookie(ck);
      sck2.add("k3", "v3");
      Cookie ck2 = sck2.getCookie();
      System.out.println(ck2.getValue());
    }
}
