Skip to content

Commit

Permalink
feat: Add Predicates to match header value and presence.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Sep 3, 2022
1 parent 4c64952 commit adaa821
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/main/java/io/github/nstdio/http/ext/Predicates.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Objects;
import java.util.function.Predicate;

Expand Down Expand Up @@ -45,4 +46,32 @@ public static Predicate<HttpRequest> uri(URI uri) {
Objects.requireNonNull(uri);
return r -> r.uri().equals(uri);
}

/**
* The {@code Predicate} that matches only {@code HttpResponse} with given header.
*
* @param name The header name.
* @param value The header value.
*
* @return The {@code Predicate} that matches {@code HttpResponse} with given header.
*/
public static <T> Predicate<HttpResponse<T>> hasHeader(String name, String value) {
Objects.requireNonNull(name);
Objects.requireNonNull(value);

return r -> r.headers().firstValue(name).filter(value::equals).isPresent();
}

/**
* The {@code Predicate} that matches only {@code HttpRequest} with given header.
*
* @param name The header name.
*
* @return The {@code Predicate} that matches {@code HttpRequest} with given header.
*/
public static <T> Predicate<HttpResponse<T>> hasHeader(String name) {
Objects.requireNonNull(name);

return r -> r.headers().firstValue(name).isPresent();
}
}
34 changes: 34 additions & 0 deletions src/test/kotlin/io/github/nstdio/http/ext/PredicatesTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,38 @@ class PredicatesTest {
.accepts(r1)
.rejects(r2)
}

@Test
fun `Should accept or reject with header name and value`() {
//given
val r = StaticHttpResponse.builder<Any>()
.statusCode(200)
.headers(HttpHeadersBuilder().add("Content-Type", "text/plain").build())
.build()

//when + then
assertThat(Predicates.hasHeader<Any>("Content-Type", "text/plain"))
.accepts(r)

assertThat(Predicates.hasHeader<Any>("Content-Type", "text/plain;charset=UTF-8"))
.rejects(r)
assertThat(Predicates.hasHeader<Any>("Content-Length", "12"))
.rejects(r)
}

@Test
fun `Should accept or reject with header name`() {
//given
val r = StaticHttpResponse.builder<Any>()
.statusCode(200)
.headers(HttpHeadersBuilder().add("Content-Type", "*/*").build())
.build()

//when + then
assertThat(Predicates.hasHeader<Any>("Content-Type"))
.accepts(r)

assertThat(Predicates.hasHeader<Any>("Content-Length"))
.rejects(r)
}
}

0 comments on commit adaa821

Please sign in to comment.