github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/feign/EncodingUtils.mustache (about) 1 package {{invokerPackage}}; 2 3 import java.io.UnsupportedEncodingException; 4 import java.net.URLEncoder; 5 import java.util.ArrayList; 6 import java.util.Collection; 7 import java.util.List; 8 9 /** 10 * Utilities to support Swagger encoding formats in Feign. 11 */ 12 public final class EncodingUtils { 13 14 /** 15 * Private constructor. Do not construct this class. 16 */ 17 private EncodingUtils() {} 18 19 /** 20 * <p>Encodes a collection of query parameters according to the Swagger 21 * collection format.</p> 22 * 23 * <p>Of the various collection formats defined by Swagger ("csv", "tsv", 24 * etc), Feign only natively supports "multi". This utility generates the 25 * other format types so it will be properly processed by Feign.</p> 26 * 27 * <p>Note, as part of reformatting, it URL encodes the parameters as 28 * well.</p> 29 * @param parameters The collection object to be formatted. This object will 30 * not be changed. 31 * @param collectionFormat The Swagger collection format (eg, "csv", "tsv", 32 * "pipes"). See the 33 * <a href="http://swagger.io/specification/#parameter-object-44"> 34 * OpenAPI Spec</a> for more details. 35 * @return An object that will be correctly formatted by Feign. 36 */ 37 public static Object encodeCollection(Collection<?> parameters, 38 String collectionFormat) { 39 if (parameters == null) { 40 return parameters; 41 } 42 List<String> stringValues = new ArrayList<>(parameters.size()); 43 for (Object parameter : parameters) { 44 // ignore null values (same behavior as Feign) 45 if (parameter != null) { 46 stringValues.add(encode(parameter)); 47 } 48 } 49 // Feign natively handles single-element lists and the "multi" format. 50 if (stringValues.size() < 2 || "multi".equals(collectionFormat)) { 51 return stringValues; 52 } 53 // Otherwise return a formatted String 54 String[] stringArray = stringValues.toArray(new String[0]); 55 switch (collectionFormat) { 56 case "csv": 57 default: 58 return StringUtil.join(stringArray, ","); 59 case "ssv": 60 return StringUtil.join(stringArray, " "); 61 case "tsv": 62 return StringUtil.join(stringArray, "\t"); 63 case "pipes": 64 return StringUtil.join(stringArray, "|"); 65 } 66 } 67 68 /** 69 * URL encode a single query parameter. 70 * @param parameter The query parameter to encode. This object will not be 71 * changed. 72 * @return The URL encoded string representation of the parameter. If the 73 * parameter is null, returns null. 74 */ 75 public static String encode(Object parameter) { 76 if (parameter == null) { 77 return null; 78 } 79 try { 80 return URLEncoder.encode(parameter.toString(), "UTF-8").replaceAll("\\+", "%20"); 81 } catch (UnsupportedEncodingException e) { 82 // Should never happen, UTF-8 is always supported 83 throw new RuntimeException(e); 84 } 85 } 86 }