1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.jclouds.http;
20
21 import static com.google.common.base.Preconditions.checkNotNull;
22
23 import java.util.Collection;
24
25 import org.jclouds.javax.annotation.Nullable;
26
27 import org.jclouds.http.internal.PayloadEnclosingImpl;
28 import org.jclouds.io.Payload;
29
30 import com.google.common.collect.ImmutableMultimap;
31 import com.google.common.collect.Multimap;
32
33
34
35
36
37
38 public class HttpMessage extends PayloadEnclosingImpl {
39 public static Builder<? extends HttpMessage> builder() {
40 return new Builder<HttpMessage>();
41 }
42
43 public static class Builder<T extends HttpMessage> {
44 protected Payload payload;
45 protected Multimap<String, String> headers = ImmutableMultimap.of();
46
47 public Builder<T> payload(Payload payload) {
48 this.payload = payload;
49 return this;
50 }
51
52 public Builder<T> headers(Multimap<String, String> headers) {
53 this.headers = ImmutableMultimap.copyOf(checkNotNull(headers, "headers"));
54 return this;
55 }
56
57 @SuppressWarnings("unchecked")
58 public T build() {
59 return (T) new HttpMessage(payload, headers);
60 }
61
62 public static <X extends HttpMessage> Builder<X> from(X input) {
63 return new Builder<X>().payload(input.getPayload()).headers(input.getHeaders());
64 }
65 }
66
67 protected final Multimap<String, String> headers;
68
69 public HttpMessage(@Nullable Payload payload, Multimap<String, String> headers) {
70 super(payload);
71 this.headers = ImmutableMultimap.copyOf(checkNotNull(headers, "headers"));
72 }
73
74 public Multimap<String, String> getHeaders() {
75 return headers;
76 }
77
78
79
80
81 public String getFirstHeaderOrNull(String string) {
82 Collection<String> values = headers.get(string);
83 if (values.size() == 0)
84 values = headers.get(string.toLowerCase());
85 return (values.size() >= 1) ? values.iterator().next() : null;
86 }
87
88 public Builder<? extends HttpMessage> toBuilder() {
89 return Builder.from(this);
90 }
91
92 @Override
93 public int hashCode() {
94 final int prime = 31;
95 int result = super.hashCode();
96 result = prime * result + ((headers == null) ? 0 : headers.hashCode());
97 return result;
98 }
99
100 @Override
101 public boolean equals(Object obj) {
102 if (this == obj)
103 return true;
104 if (!super.equals(obj))
105 return false;
106 if (getClass() != obj.getClass())
107 return false;
108 HttpMessage other = (HttpMessage) obj;
109 if (headers == null) {
110 if (other.headers != null)
111 return false;
112 } else if (!headers.equals(other.headers))
113 return false;
114 return true;
115 }
116
117 @Override
118 public String toString() {
119 return "[headers=" + headers + ", payload=" + payload + "]";
120 }
121
122 }