1 package com.foxinmy.weixin4j.http;
2
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6
7
8
9
10
11
12
13
14
15 public class HttpVersion implements Comparable<HttpVersion> {
16
17 private static final Pattern VERSION_PATTERN = Pattern
18 .compile("(\\S+)/(\\d+)\\.(\\d+)");
19
20 public static final String HTTP_1_0_STRING = "HTTP/1.0";
21 public static final String HTTP_1_1_STRING = "HTTP/1.1";
22
23
24
25
26 public static final HttpVersion HTTP_1_0 = new HttpVersion("HTTP", 1, 0,
27 false);
28
29
30
31
32 public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP", 1, 1,
33 true);
34
35 private final String protocol;
36 private final int major;
37 private final int minor;
38 private final boolean keepAlive;
39 private final String text;
40
41 public HttpVersion(String text, boolean keepAlive) {
42 if (text == null) {
43 throw new NullPointerException("text");
44 }
45
46 text = text.trim().toUpperCase();
47 if (text.isEmpty()) {
48 throw new IllegalArgumentException("empty text");
49 }
50 Matcher m = VERSION_PATTERN.matcher(text);
51 if (!m.matches()) {
52 throw new IllegalArgumentException("invalid version format: "
53 + text);
54 }
55 this.protocol = m.group(1);
56 this.major = Integer.parseInt(m.group(2));
57 this.minor = Integer.parseInt(m.group(3));
58 this.keepAlive = keepAlive;
59 this.text = protocol + '/' + major + '.' + minor;
60 }
61
62 public HttpVersion(String protocol, int major, int minor, boolean keepAlive) {
63 this.protocol = protocol;
64 this.major = major;
65 this.minor = minor;
66 this.keepAlive = keepAlive;
67 this.text = protocol + '/' + major + '.' + minor;
68 }
69
70 public String getProtocol() {
71 return protocol;
72 }
73
74 public int getMajor() {
75 return major;
76 }
77
78 public int getMinor() {
79 return minor;
80 }
81
82 public boolean isKeepAlive() {
83 return keepAlive;
84 }
85
86 public String getText() {
87 return text;
88 }
89
90 @Override
91 public String toString() {
92 return getText();
93 }
94
95 @Override
96 public int hashCode() {
97 return (protocol.hashCode() * 31 + major) * 31 + minor;
98 }
99
100 @Override
101 public boolean equals(Object o) {
102 if (!(o instanceof HttpVersion)) {
103 return false;
104 }
105 HttpVersion that = (HttpVersion) o;
106 return minor == that.minor && major == that.major
107 && protocol.equals(that.protocol);
108 }
109
110 @Override
111 public int compareTo(HttpVersion o) {
112 int v = protocol.compareTo(o.protocol);
113 if (v != 0) {
114 return v;
115 }
116 v = major - o.major;
117 if (v != 0) {
118 return v;
119 }
120 return minor - o.minor;
121 }
122 }