1 package net.matuschek.http.cookie; 2 3 6 7 import java.util.Vector ; 8 import java.net.URL ; 9 10 17 public class MemoryCookieManager implements CookieManager 18 { 19 20 23 class CleanupThread extends Thread { 24 MemoryCookieManager cm = null; 25 boolean finished = false; 26 27 public CleanupThread(MemoryCookieManager cm) { 28 this.cm = cm; 29 this.setDaemon(true); 30 } 31 32 33 public void finish() { 34 this.finished = true; 35 } 36 37 public void run() { 38 while (! finished) { 39 try { 41 sleep(60000); 42 } catch (InterruptedException e) { 43 this.finished=true; 44 } 45 cm.cleanUpExpired(); 46 } 47 } 48 } 49 50 51 52 private Vector <Cookie> cookies; 53 54 55 private CleanupThread ct = null; 56 57 58 59 65 public MemoryCookieManager() { 66 cookies = new Vector <Cookie>(); 67 68 75 } 76 77 78 83 public void add(Cookie cookie) { 84 if (ct == null) { 85 synchronized (this) { 86 if (ct == null) { 87 ct = new CleanupThread(this); 89 ct.start(); 90 } 91 } 92 } 93 for (int i=0; i<cookies.size(); i++) { 94 Cookie oldcookie = (Cookie)(cookies.elementAt(i)); 95 if (cookie.overwrites(oldcookie)) { 96 cookies.removeElementAt(i); 97 i--; 98 } 99 } 100 cookies.add(cookie); 101 } 102 103 104 108 public int countCookies() { 109 return this.cookies.size(); 110 } 111 112 113 120 public String cookiesForURL(URL u) { 121 final String SEP = "; "; 122 StringBuffer sb = new StringBuffer (); 123 124 for (int i=0; i<cookies.size(); i++) { 125 Cookie c = (Cookie)(cookies.elementAt(i)); 126 if (c.isValid(u)) { 127 sb.append(c.getNameValuePair()); 128 sb.append(SEP); 129 } 130 } 131 132 if (sb.length() > 0) { 133 return sb.substring(0,sb.length()-SEP.length()); 135 } else { 136 return null; 137 } 138 } 139 140 141 144 public void clear() { 145 this.cookies.clear(); 146 } 147 148 149 152 protected void cleanUpExpired() { 153 for (int i=0; i<cookies.size(); i++) { 154 Cookie c = (Cookie)(cookies.elementAt(i)); 155 156 if (! c.isValid()) { 158 cookies.removeElementAt(i); 159 i--; 160 } 161 } 162 } 163 164 168 public void finish() { 169 if (ct != null) { 170 ct.finished = true; 171 ct.interrupt(); 172 } 173 } 174 175 176 179 public String toString() { 180 StringBuffer sb = new StringBuffer (); 181 for (int i=0; i<cookies.size(); i++) { 182 sb.append(i+": "); 183 sb.append(cookies.elementAt(i).toString()); 184 sb.append("\n"); 185 } 186 return sb.toString(); 187 } 188 189 } 190 | Popular Tags |