1 package org.kuali.common.httplib.api.model; 2 3 import static com.google.common.base.Preconditions.checkArgument; 4 import static com.google.common.collect.Lists.transform; 5 import static com.google.common.net.UrlEscapers.urlFormParameterEscaper; 6 import static java.lang.String.format; 7 8 import java.util.List; 9 10 import com.google.common.base.Function; 11 import com.google.common.base.Joiner; 12 import com.google.common.escape.Escaper; 13 14 public final class QueryParams { 15 16 private QueryParams() {} 17 18 public static Function<QueryParam, String> parameterFunction() { 19 return QueryParamFunction.INSTANCE; 20 } 21 22 public static String asQueryString(List<QueryParam> params) { 23 checkArgument(!params.isEmpty(), "params must not be empty"); 24 return '?' + Joiner.on('&').join(transform(params, parameterFunction())); 25 } 26 27 private enum QueryParamFunction implements Function<QueryParam, String> { 28 INSTANCE; 29 30 private final Escaper escaper = urlFormParameterEscaper(); 31 32 @Override 33 public String apply(QueryParam input) { 34 if (input.getValue().isPresent()) { 35 return format("%s=%s", escaper.escape(input.getName()), escaper.escape(input.getValue().get())); 36 } else { 37 return format("%s", escaper.escape(input.getName())); 38 } 39 } 40 } 41 42 }