1 package org.oxerr.viagogo.model; 2 3 import java.io.UnsupportedEncodingException; 4 import java.net.URI; 5 import java.net.URLDecoder; 6 import java.nio.charset.StandardCharsets; 7 import java.time.Instant; 8 import java.time.LocalDateTime; 9 import java.util.Arrays; 10 import java.util.Collections; 11 import java.util.List; 12 import java.util.Map; 13 import java.util.Optional; 14 import java.util.regex.Pattern; 15 import java.util.stream.Collectors; 16 17 import io.openapitools.jackson.dataformat.hal.HALLink; 18 19 public final class Link { 20 21 private Map<String, List<String>> params; 22 23 public Link(String href) { 24 URI uri = URI.create(href); 25 this.params = Pattern.compile("&") 26 .splitAsStream(uri.getQuery()) 27 .map(s -> Arrays.copyOf(s.split("=", 2), 2)) 28 .collect(Collectors.groupingBy(s -> decode(s[0]), Collectors.mapping(s -> decode(s[1]), Collectors.toList()))); 29 } 30 public Link(HALLink halLink) { 31 this(halLink.getHref()); 32 } 33 34 public Optional<String> getFirst(String name) { 35 return Optional.ofNullable(params.get(name)) 36 .orElseGet(Collections::emptyList) 37 .stream() 38 .findFirst(); 39 } 40 41 public String getFirstAsString(String name) { 42 return getFirst(name).orElse(null); 43 } 44 45 public Long getFirstAsLong(String name) { 46 return getFirst(name).map(Long::parseLong).orElse(null); 47 } 48 49 public Integer getFirstAsInteger(String name) { 50 return getFirst(name).map(Integer::parseInt).orElse(null); 51 } 52 53 public Double getFirstAsDouble(String name) { 54 return getFirst(name).map(Double::parseDouble).orElse(null); 55 } 56 57 public Instant getFirstAsInstant(String name) { 58 return getFirst(name).map(Instant::parse).orElse(null); 59 } 60 61 public LocalDateTime getFirstAsLocalDateTime(String name) { 62 return getFirst(name).map(LocalDateTime::parse).orElse(null); 63 } 64 65 private static String decode(final String encoded) { 66 return Optional.ofNullable(encoded) 67 .map(e -> { 68 try { 69 return URLDecoder.decode(e, StandardCharsets.UTF_8.name()); 70 } catch (UnsupportedEncodingException ex) { 71 return e; 72 } 73 }) 74 .orElse(null); 75 } 76 77 }