Skip to content

Commit 32f7cba

Browse files
committed
#1140 RsHeaders
1 parent 5818aba commit 32f7cba

File tree

3 files changed

+319
-1
lines changed

3 files changed

+319
-1
lines changed

src/main/java/org/takes/rq/RqHeaders.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
import org.takes.misc.VerboseList;
4545

4646
/**
47-
* HTTP headers parsing
47+
* HTTP headers parsing.
4848
*
4949
* <p>All implementations of this interface must be immutable and
5050
* thread-safe.</p>
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
/*
2+
* The MIT License (MIT)
3+
*
4+
* Copyright (c) 2014-2022 Yegor Bugayenko
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included
14+
* in all copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
package org.takes.rs;
25+
26+
import java.io.IOException;
27+
import java.io.InputStream;
28+
import java.net.HttpURLConnection;
29+
import java.util.Collections;
30+
import java.util.HashMap;
31+
import java.util.Iterator;
32+
import java.util.LinkedList;
33+
import java.util.List;
34+
import java.util.Map;
35+
import java.util.Set;
36+
import lombok.EqualsAndHashCode;
37+
import org.cactoos.text.FormattedText;
38+
import org.cactoos.text.Lowered;
39+
import org.cactoos.text.TextOf;
40+
import org.cactoos.text.Trimmed;
41+
import org.cactoos.text.UncheckedText;
42+
import org.takes.HttpException;
43+
import org.takes.Response;
44+
import org.takes.misc.VerboseList;
45+
46+
/**
47+
* HTTP headers parsing.
48+
*
49+
* <p>All implementations of this interface must be immutable and
50+
* thread-safe.</p>
51+
*
52+
* @since 0.1
53+
*/
54+
@SuppressWarnings("PMD.TooManyMethods")
55+
public interface RsHeaders extends Response {
56+
57+
/**
58+
* Get single header.
59+
*
60+
* @param key Header name
61+
* @return List of values (can be empty)
62+
* @throws IOException If fails
63+
*/
64+
List<String> header(CharSequence key) throws IOException;
65+
66+
/**
67+
* Get all header names.
68+
*
69+
* @return All names
70+
* @throws IOException If fails
71+
*/
72+
Set<String> names() throws IOException;
73+
74+
/**
75+
* Request decorator, for HTTP headers parsing.
76+
*
77+
* <p>The class is immutable and thread-safe.
78+
*
79+
* @since 0.13.8
80+
*/
81+
@EqualsAndHashCode(callSuper = true)
82+
final class Base extends RsWrap implements RsHeaders {
83+
/**
84+
* Ctor.
85+
*
86+
* @param req Original request
87+
*/
88+
public Base(final Response req) {
89+
super(req);
90+
}
91+
92+
@Override
93+
public List<String> header(final CharSequence key)
94+
throws IOException {
95+
final List<String> values = this.map().getOrDefault(
96+
new UncheckedText(
97+
new Lowered(key.toString())
98+
).asString(),
99+
Collections.emptyList()
100+
);
101+
final List<String> list;
102+
if (values.isEmpty()) {
103+
list = new VerboseList<>(
104+
Collections.emptyList(),
105+
new FormattedText(
106+
"there are no headers by name \"%s\" among %d others: %s",
107+
key,
108+
this.map().size(),
109+
this.map().keySet()
110+
)
111+
);
112+
} else {
113+
list = new VerboseList<>(
114+
values,
115+
new FormattedText(
116+
"there are only %d headers by name \"%s\"",
117+
values.size(),
118+
key
119+
)
120+
);
121+
}
122+
return list;
123+
}
124+
125+
@Override
126+
public Set<String> names() throws IOException {
127+
return this.map().keySet();
128+
}
129+
130+
/**
131+
* Parse them all in a map.
132+
*
133+
* @return Map of them
134+
* @throws IOException If fails
135+
*/
136+
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
137+
private Map<String, List<String>> map() throws IOException {
138+
final Iterator<String> head = this.head().iterator();
139+
if (!head.hasNext()) {
140+
throw new HttpException(
141+
HttpURLConnection.HTTP_BAD_REQUEST,
142+
"a valid request must contain at least one line in the head"
143+
);
144+
}
145+
head.next();
146+
final Map<String, List<String>> map = new HashMap<>(0);
147+
while (head.hasNext()) {
148+
final String line = head.next();
149+
final String[] parts = line.split(":", 2);
150+
if (parts.length < 2) {
151+
throw new HttpException(
152+
HttpURLConnection.HTTP_BAD_REQUEST,
153+
String.format("invalid HTTP header: \"%s\"", line)
154+
);
155+
}
156+
final String key = new UncheckedText(
157+
new Lowered(new Trimmed(new TextOf(parts[0])))
158+
).asString();
159+
if (!map.containsKey(key)) {
160+
map.put(key, new LinkedList<>());
161+
}
162+
map.get(key).add(
163+
new UncheckedText(
164+
new Trimmed(new TextOf(parts[1]))
165+
).asString()
166+
);
167+
}
168+
return map;
169+
}
170+
}
171+
172+
/**
173+
* Smart decorator, with extra features.
174+
*
175+
* <p>The class is immutable and thread-safe.
176+
*
177+
* @since 0.16
178+
*/
179+
@EqualsAndHashCode
180+
final class Smart implements RsHeaders {
181+
/**
182+
* Original.
183+
*/
184+
private final RsHeaders origin;
185+
186+
/**
187+
* Ctor.
188+
* @param req Original request
189+
*/
190+
public Smart(final RsHeaders req) {
191+
this.origin = req;
192+
}
193+
194+
/**
195+
* Ctor.
196+
* @param req Original request
197+
*/
198+
public Smart(final Response req) {
199+
this(new RsHeaders.Base(req));
200+
}
201+
202+
@Override
203+
public List<String> header(final CharSequence name)
204+
throws IOException {
205+
return this.origin.header(name);
206+
}
207+
208+
@Override
209+
public Set<String> names() throws IOException {
210+
return this.origin.names();
211+
}
212+
213+
@Override
214+
public Iterable<String> head() throws IOException {
215+
return this.origin.head();
216+
}
217+
218+
@Override
219+
public InputStream body() throws IOException {
220+
return this.origin.body();
221+
}
222+
223+
/**
224+
* Get single header or throw HTTP exception.
225+
* @param name Name of header
226+
* @return Value of it
227+
* @throws IOException If fails
228+
*/
229+
public String single(final CharSequence name) throws IOException {
230+
final Iterator<String> params = this.header(name).iterator();
231+
if (!params.hasNext()) {
232+
throw new HttpException(
233+
HttpURLConnection.HTTP_BAD_REQUEST,
234+
String.format(
235+
"header \"%s\" is mandatory, not found among %s",
236+
name, this.names()
237+
)
238+
);
239+
}
240+
return params.next();
241+
}
242+
243+
/**
244+
* If header is present, returns the first header value.
245+
* If not, returns a default value.
246+
* @param name Name of header key
247+
* @param def Default value
248+
* @return Header Value or default value
249+
* @throws IOException If fails
250+
*/
251+
public String single(final CharSequence name, final CharSequence def)
252+
throws IOException {
253+
final String value;
254+
final Iterator<String> params = this.header(name).iterator();
255+
if (params.hasNext()) {
256+
value = params.next();
257+
} else {
258+
value = def.toString();
259+
}
260+
return value;
261+
}
262+
263+
}
264+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* The MIT License (MIT)
3+
*
4+
* Copyright (c) 2014-2022 Yegor Bugayenko
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included
14+
* in all copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
package org.takes.rs;
25+
26+
import java.io.IOException;
27+
import org.hamcrest.MatcherAssert;
28+
import org.hamcrest.Matchers;
29+
import org.junit.jupiter.api.Test;
30+
31+
/**
32+
* Test case for {@link RsHeaders}.
33+
* @since 0.1
34+
*/
35+
final class RsHeadersTest {
36+
37+
/**
38+
* RsHeaders can parse headers.
39+
* @throws IOException If some problem inside
40+
*/
41+
@Test
42+
void parsesHttpHeaders() throws IOException {
43+
MatcherAssert.assertThat(
44+
new RsHeaders.Base(
45+
new RsWithHeader(
46+
new RsEmpty(),
47+
"Content-type", "text/plain"
48+
)
49+
).header("content-type"),
50+
Matchers.hasItem("text/plain")
51+
);
52+
}
53+
54+
}

0 commit comments

Comments
 (0)