|
| 1 | +package jooby; |
| 2 | + |
| 3 | +import static com.google.common.base.Preconditions.checkState; |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Optional; |
| 9 | +import java.util.Set; |
| 10 | +import java.util.TreeMap; |
| 11 | + |
| 12 | +import javax.inject.Inject; |
| 13 | +import javax.inject.Singleton; |
| 14 | + |
| 15 | +import jooby.MediaType.Matcher; |
| 16 | +import jooby.internal.ForwardingMessageConverter; |
| 17 | + |
| 18 | +import com.google.common.base.Joiner; |
| 19 | + |
| 20 | +@Singleton |
| 21 | +public class BodyMapperSelector { |
| 22 | + |
| 23 | + private Set<BodyMapper> converters; |
| 24 | + |
| 25 | + private Map<MediaType, BodyMapper> converterMap = new HashMap<>(); |
| 26 | + |
| 27 | + @Inject |
| 28 | + public BodyMapperSelector(final Set<BodyMapper> converters) { |
| 29 | + checkState(converters != null && converters.size() > 0, "No message converters were found."); |
| 30 | + this.converters = converters; |
| 31 | + converters.forEach(c -> c.types().forEach(t -> converterMap.put(t, c))); |
| 32 | + } |
| 33 | + |
| 34 | + public Optional<BodyMapper> get(final Class<?> type, final List<MediaType> supported) { |
| 35 | + for (BodyMapper converter : converters) { |
| 36 | + for (MediaType it : supported) { |
| 37 | + if (converter.types().contains(it)) { |
| 38 | + return Optional.of(converter); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return Optional.empty(); |
| 43 | + } |
| 44 | + |
| 45 | + public BodyMapper getOrThrow(final Iterable<MediaType> candidates, final HttpStatus status) { |
| 46 | + return get(candidates) |
| 47 | + .orElseThrow( |
| 48 | + () -> new HttpException(status, Joiner.on(", ").join(candidates)) |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + public Optional<BodyMapper> get(final Iterable<MediaType> candidates) { |
| 53 | + for (MediaType mediaType : candidates) { |
| 54 | + BodyMapper converter = converterMap.get(mediaType); |
| 55 | + if (converter != null) { |
| 56 | + return Optional.of(converter); |
| 57 | + } |
| 58 | + } |
| 59 | + // degrade lookup |
| 60 | + Matcher matcher = MediaType.matcher(candidates); |
| 61 | + TreeMap<MediaType, BodyMapper> matches = new TreeMap<>(); |
| 62 | + for (BodyMapper converter : converters) { |
| 63 | + matcher.first(converter.types()).ifPresent((m) -> matches.putIfAbsent(m, converter)); |
| 64 | + } |
| 65 | + if (matches.isEmpty()) { |
| 66 | + return Optional.empty(); |
| 67 | + } |
| 68 | + Map.Entry<MediaType, BodyMapper> entry = matches.firstEntry(); |
| 69 | + return Optional.of(new ForwardingMessageConverter(entry.getValue(), entry.getKey())); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments