Skip to content

Commit bbb70f3

Browse files
authored
feat: parse multiple types
Added `parse` method to parse string into collection of `MimeType`s ordering by `q` (qualifier) parameter. PR: #25 Close: #24
1 parent b41d291 commit bbb70f3

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/main/java/wtf/g4s8/mime/MimeType.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
*/
55
package wtf.g4s8.mime;
66

7+
import java.util.Arrays;
8+
import java.util.Collection;
79
import java.util.Optional;
810
import java.util.Set;
11+
import java.util.stream.Collectors;
912

1013
/**
1114
* Media type (or MIME type).
@@ -47,6 +50,29 @@ static MimeType of(final CharSequence src) {
4750
return new MimeTypeOfString(src);
4851
}
4952

53+
/**
54+
* Parse mime-type string containing multiple media types with qualifiers.
55+
* <p>
56+
* Multiple media types could be used in {@code Accept} headers.
57+
* Mime types are ordered first by qualifier param {@code q} value, then by order
58+
* of appearance in source string.
59+
* </p>
60+
* @param src Source string
61+
* @return Ordered collection of mime types
62+
* @since 2.1
63+
*/
64+
static Collection<MimeType> parse(final CharSequence src) {
65+
return Arrays.stream(src.toString().split(","))
66+
.map(String::trim)
67+
.map(MimeTypeOfString::new)
68+
.sorted(
69+
(left, right) -> Float.compare(
70+
right.param("q").map(Float::parseFloat).orElse(0F),
71+
left.param("q").map(Float::parseFloat).orElse(0F)
72+
)
73+
).collect(Collectors.toList());
74+
}
75+
5076
/**
5177
* Default decorator for mime type.
5278
* @since 2.0
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* The MIT License (MIT) Copyright (c) 2017-2021 Kirill Ch. <g4s8.public@gmail.com>
3+
* https://github.com/g4s8/mime/LICENSE.txt
4+
*/
5+
package wtf.g4s8.mime;
6+
// // text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
7+
8+
import org.hamcrest.MatcherAssert;
9+
import org.hamcrest.Matchers;
10+
import org.junit.jupiter.api.Test;
11+
12+
import wtf.g4s8.mime.test.HmMimeHasSubType;
13+
import wtf.g4s8.mime.test.HmMimeHasType;
14+
15+
/**
16+
* Test case for {@link MimeType}.
17+
*
18+
* @since 2.1
19+
*/
20+
final class MimeTypeTest {
21+
@Test
22+
void parseMultipleTypes() {
23+
MatcherAssert.assertThat(
24+
MimeType.parse("text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8"),
25+
Matchers.contains(
26+
Matchers.allOf(new HmMimeHasType("application"), new HmMimeHasSubType("xml")),
27+
Matchers.allOf(new HmMimeHasType("*"), new HmMimeHasSubType("*")),
28+
Matchers.allOf(new HmMimeHasType("text"), new HmMimeHasSubType("html")),
29+
Matchers.allOf(new HmMimeHasType("application"), new HmMimeHasSubType("xhtml+xml"))
30+
)
31+
);
32+
}
33+
}

0 commit comments

Comments
 (0)