nbbrd.io.http.HttpHeadersBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-io-http Show documentation
Show all versions of java-io-http Show documentation
Common IO utilities - http
The newest version!
package nbbrd.io.http;
import lombok.NonNull;
import nbbrd.design.BuilderPattern;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@BuilderPattern(Map.class)
public final class HttpHeadersBuilder {
private final List> data = new ArrayList<>();
private BiPredicate filter = HttpHeadersBuilder::valueNotNullNorEmpty;
private static boolean valueNotNullNorEmpty(String k, String v) {
return v != null && !v.isEmpty();
}
public @NonNull HttpHeadersBuilder put(@NonNull Map> headers) {
keyValues(headers).forEach(data::add);
return this;
}
public @NonNull HttpHeadersBuilder put(@NonNull String key, @Nullable String value) {
data.add(headerOf(key, value));
return this;
}
public @NonNull HttpHeadersBuilder filter(@NonNull BiPredicate filter) {
this.filter = filter;
return this;
}
public @NonNull Map> build() {
return data.stream()
.filter(header -> filter.test(header.getKey(), header.getValue()))
.collect(COLLECTOR);
}
private static final Collector, ?, Map>> COLLECTOR =
Collectors.collectingAndThen(
Collectors.groupingBy(
Map.Entry::getKey,
() -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER),
toUnmodifiableList(Map.Entry::getValue)
),
Collections::unmodifiableMap
);
private static Collector> toUnmodifiableList(Function super T, ? extends U> mapper) {
return Collectors.mapping(mapper, toUnmodifiableList());
}
private static Collector> toUnmodifiableList() {
return Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList);
}
private static Map.@NonNull Entry headerOf(@NonNull String key, @Nullable String value) {
return new AbstractMap.SimpleImmutableEntry<>(key, value);
}
public static @NonNull Stream> keyValues(@NonNull Map> headers) {
return headers
.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream().map(value -> headerOf(entry.getKey(), value)));
}
}