-
Notifications
You must be signed in to change notification settings - Fork 10
/
CookieDecoder.java
97 lines (74 loc) · 2.46 KB
/
CookieDecoder.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.vtence.molecule.http;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CookieDecoder {
private static final Pattern NAME_VALUE_PAIR = Pattern.compile("(?:\\s|[;,])*+([^;=]++)(?:=([\"]((?:\\\\\"|[^\"])++)[\"]|[^;,]*+))?+");
private static final int NAME = 1;
private static final int VALUE = 2;
private static final String VERSION = "$Version";
private static final String PATH = "$Path";
private static final String DOMAIN = "$Domain";
public List<Cookie> decode(String header) {
List<Cookie> cookies = new ArrayList<>();
Matcher pair = NAME_VALUE_PAIR.matcher(header);
int pos = 0;
int version = 1;
if (pair.find()) {
if (name(pair).equals(VERSION)) {
pos = pair.end();
version = version(pair);
}
}
while (pair.find(pos)) {
pos = pair.end();
Cookie cookie = new Cookie(name(pair), value(pair));
cookie.version(version);
if (pair.find(pos)) {
if (name(pair).equals(PATH)) {
pos = pair.end();
cookie.path(value(pair));
}
}
if (pair.find(pos)) {
if (name(pair).equals(DOMAIN)) {
pos = pair.end();
cookie.domain(value(pair));
}
}
cookies.add(cookie);
}
return cookies;
}
private int version(Matcher pair) {
try {
return Integer.parseInt(value(pair));
} catch (Exception e) {
return 1;
}
}
private String name(Matcher pair) {
return pair.group(NAME);
}
private String value(Matcher pair) {
return unescape(unquote(pair.group(VALUE)));
}
private String unescape(String text) {
if (text == null) return null;
return text.replace("\\\"", "\"").replace("\\\\", "\\");
}
private String unquote(String text) {
if (text == null) return null;
if (text.length() > 2 && firstChar(text) == '"' && lastChar(text) == '"') {
return text.substring(1, text.length() - 1);
}
return text;
}
private char lastChar(String text) {
return text.charAt(text.length() - 1);
}
private char firstChar(String text) {
return text.charAt(0);
}
}