1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.impl.cookie;
29
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Locale;
33
34 import org.apache.http.HeaderElement;
35 import org.apache.http.NameValuePair;
36 import org.apache.http.annotation.NotThreadSafe;
37 import org.apache.http.cookie.Cookie;
38 import org.apache.http.cookie.CookieAttributeHandler;
39 import org.apache.http.cookie.CookieOrigin;
40 import org.apache.http.cookie.MalformedCookieException;
41 import org.apache.http.util.Args;
42
43
44
45
46
47
48
49 @NotThreadSafe
50 public abstract class CookieSpecBase extends AbstractCookieSpec {
51
52 protected static String getDefaultPath(final CookieOrigin origin) {
53 String defaultPath = origin.getPath();
54 int lastSlashIndex = defaultPath.lastIndexOf('/');
55 if (lastSlashIndex >= 0) {
56 if (lastSlashIndex == 0) {
57
58 lastSlashIndex = 1;
59 }
60 defaultPath = defaultPath.substring(0, lastSlashIndex);
61 }
62 return defaultPath;
63 }
64
65 protected static String getDefaultDomain(final CookieOrigin origin) {
66 return origin.getHost();
67 }
68
69 protected List<Cookie> parse(final HeaderElement[] elems, final CookieOrigin origin)
70 throws MalformedCookieException {
71 final List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
72 for (final HeaderElement headerelement : elems) {
73 final String name = headerelement.getName();
74 final String value = headerelement.getValue();
75 if (name == null || name.length() == 0) {
76 throw new MalformedCookieException("Cookie name may not be empty");
77 }
78
79 final BasicClientCookie cookie = new BasicClientCookie(name, value);
80 cookie.setPath(getDefaultPath(origin));
81 cookie.setDomain(getDefaultDomain(origin));
82
83
84 final NameValuePair[] attribs = headerelement.getParameters();
85 for (int j = attribs.length - 1; j >= 0; j--) {
86 final NameValuePair attrib = attribs[j];
87 final String s = attrib.getName().toLowerCase(Locale.ENGLISH);
88
89 cookie.setAttribute(s, attrib.getValue());
90
91 final CookieAttributeHandler handler = findAttribHandler(s);
92 if (handler != null) {
93 handler.parse(cookie, attrib.getValue());
94 }
95 }
96 cookies.add(cookie);
97 }
98 return cookies;
99 }
100
101 public void validate(final Cookie cookie, final CookieOrigin origin)
102 throws MalformedCookieException {
103 Args.notNull(cookie, "Cookie");
104 Args.notNull(origin, "Cookie origin");
105 for (final CookieAttributeHandler handler: getAttribHandlers()) {
106 handler.validate(cookie, origin);
107 }
108 }
109
110 public boolean match(final Cookie cookie, final CookieOrigin origin) {
111 Args.notNull(cookie, "Cookie");
112 Args.notNull(origin, "Cookie origin");
113 for (final CookieAttributeHandler handler: getAttribHandlers()) {
114 if (!handler.match(cookie, origin)) {
115 return false;
116 }
117 }
118 return true;
119 }
120
121 }