From 056701ae6d49eede96b44d3cebb027303d4f18c6 Mon Sep 17 00:00:00 2001 From: "Ray J. Greenwell" Date: Thu, 8 May 2014 15:02:45 -0700 Subject: [PATCH] Added a static method to turn a Map straight into a query string. Sometimes we have a Map already built via other methods, and there's really no reason to copy each key/value into a Multimap prior to encoding them. Accept a Map and just take the small extra step of toStringing every key and value, otherwise we'd have to transform the map values and that's a bunch of extra wrapping. --- .../threerings/servlet/util/QueryBuilder.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/threerings/servlet/util/QueryBuilder.java b/src/main/java/com/threerings/servlet/util/QueryBuilder.java index 51f0105..22d4724 100644 --- a/src/main/java/com/threerings/servlet/util/QueryBuilder.java +++ b/src/main/java/com/threerings/servlet/util/QueryBuilder.java @@ -10,8 +10,10 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; +import com.google.common.base.Functions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.samskivert.util.StringUtil; @@ -19,6 +21,14 @@ import com.samskivert.util.Tuple; public class QueryBuilder { + /** + * Build a query directly from the specified map. + */ + public static String build (Map values) + { + return encode(new StringBuilder(), values.entrySet()); + } + /** * Retrieve the only value for the given key, or null if it's not defined. If the key has more * than one value defined, an IllegalArgumentException will be thrown. @@ -110,13 +120,13 @@ public class QueryBuilder return encode(new StringBuilder(), _params.entries()); } - protected static String encode (StringBuilder out, Iterable> entries) + protected static String encode (StringBuilder out, Iterable> entries) { boolean appended = false; - for (Map.Entry entry : entries) { - out.append(StringUtil.encode(entry.getKey())). + for (Map.Entry entry : entries) { + out.append(StringUtil.encode(String.valueOf(entry.getKey()))). append('='). - append(StringUtil.encode(entry.getValue())). + append(StringUtil.encode(String.valueOf(entry.getValue()))). append('&'); appended = true; }