|
| 1 | +package com.stripe.net; |
| 2 | + |
| 3 | +import com.google.gson.FieldNamingPolicy; |
| 4 | +import com.google.gson.Gson; |
| 5 | +import com.google.gson.GsonBuilder; |
| 6 | +import com.google.gson.JsonElement; |
| 7 | +import com.google.gson.JsonObject; |
| 8 | +import com.google.gson.TypeAdapter; |
| 9 | +import com.google.gson.TypeAdapterFactory; |
| 10 | +import com.google.gson.reflect.TypeToken; |
| 11 | +import com.google.gson.stream.JsonReader; |
| 12 | +import com.google.gson.stream.JsonWriter; |
| 13 | + |
| 14 | +import com.stripe.Stripe; |
| 15 | + |
| 16 | +import com.stripe.param.common.EmptyParam; |
| 17 | +import java.io.IOException; |
| 18 | +import java.util.Map; |
| 19 | + |
| 20 | +/** |
| 21 | + * Converter to map an api request object to an untyped map. |
| 22 | + * It is not called a *Serializer because the outcome is not a JSON data. |
| 23 | + * It is not called *UntypedMapDeserializer because it is not converting from JSON. |
| 24 | + */ |
| 25 | +class ApiRequestParamsConverter { |
| 26 | + /** |
| 27 | + * Strategy to flatten extra params in the API request parameters. |
| 28 | + */ |
| 29 | + private static class ExtraParamsFlatteningStrategy implements UntypedMapDeserializer.Strategy { |
| 30 | + @Override |
| 31 | + public void deserializeAndTransform(Map<String, Object> outerMap, |
| 32 | + Map.Entry<String, JsonElement> jsonEntry, |
| 33 | + UntypedMapDeserializer untypedMapDeserializer) { |
| 34 | + String key = jsonEntry.getKey(); |
| 35 | + JsonElement value = jsonEntry.getValue(); |
| 36 | + if (ApiRequestParams.EXTRA_PARAMS_KEY.equals(key)) { |
| 37 | + if (!value.isJsonObject()) { |
| 38 | + throw new IllegalStateException(String.format( |
| 39 | + "Unexpected schema for extra params. JSON object is expected at key `%s`, but found" |
| 40 | + + " `%s`. This is likely a problem with this current library version `%s`. " |
| 41 | + + "Please contact [email protected] for assistance.", |
| 42 | + ApiRequestParams.EXTRA_PARAMS_KEY, value, Stripe.VERSION)); |
| 43 | + } |
| 44 | + // JSON value now corresponds to the extra params map, and is also deserialized as a map. |
| 45 | + // Instead of putting this result map under the original key, flatten the map |
| 46 | + // by adding all its key/value pairs to the outer map instead. |
| 47 | + Map<String, Object> extraParamsMap = |
| 48 | + untypedMapDeserializer.deserialize(value.getAsJsonObject()); |
| 49 | + outerMap.putAll(extraParamsMap); |
| 50 | + } else { |
| 51 | + // Normal deserialization where output map has the same structure as the given JSON content. |
| 52 | + // The deserialized content is an untyped `Object` and added to the outer map at the |
| 53 | + // original key. |
| 54 | + outerMap.put(key, untypedMapDeserializer.deserializeJsonElement(value)); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Type adapter to convert an empty enum to null value to comply with the lower-lever encoding |
| 61 | + * logic for the API request parameters. |
| 62 | + */ |
| 63 | + private static class HasEmptyEnumTypeAdapterFactory implements TypeAdapterFactory { |
| 64 | + @SuppressWarnings("unchecked") |
| 65 | + @Override |
| 66 | + public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { |
| 67 | + if (!ApiRequestParams.EnumParam.class.isAssignableFrom(type.getRawType())) { |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + TypeAdapter<ApiRequestParams.EnumParam> paramEnum = |
| 72 | + new TypeAdapter<ApiRequestParams.EnumParam>() { |
| 73 | + @Override |
| 74 | + public void write(JsonWriter out, ApiRequestParams.EnumParam value) throws IOException { |
| 75 | + if (value.getValue().equals("")) { |
| 76 | + // need to restore serialize null setting |
| 77 | + // not to affect other fields |
| 78 | + boolean previousSetting = out.getSerializeNulls(); |
| 79 | + out.setSerializeNulls(true); |
| 80 | + out.nullValue(); |
| 81 | + out.setSerializeNulls(previousSetting); |
| 82 | + } else { |
| 83 | + out.value(value.getValue()); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + @Override |
| 88 | + public ApiRequestParams.EnumParam read(JsonReader in) { |
| 89 | + throw new UnsupportedOperationException( |
| 90 | + "No deserialization is expected from this private type adapter for enum param."); |
| 91 | + } |
| 92 | + }; |
| 93 | + return (TypeAdapter<T>) paramEnum.nullSafe(); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + private static final Gson GSON = new GsonBuilder() |
| 98 | + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) |
| 99 | + .registerTypeAdapterFactory(new ApiRequestParamsConverter.HasEmptyEnumTypeAdapterFactory()) |
| 100 | + .create(); |
| 101 | + |
| 102 | + private static final UntypedMapDeserializer FLATTENING_EXTRA_PARAMS_DESERIALIZER = |
| 103 | + new UntypedMapDeserializer(new ExtraParamsFlatteningStrategy()); |
| 104 | + |
| 105 | + /** |
| 106 | + * Convert the given request params into an untyped map. This map is |
| 107 | + * composed of {@code Map<String, Object>}, {@code List<Object>}, and basic Java data types. |
| 108 | + * This allows you to test building the request params and verify compatibility with your |
| 109 | + * prior integrations using the untyped params map |
| 110 | + * {@link ApiResource#request(ApiResource.RequestMethod, String, Map, Class, RequestOptions)}. |
| 111 | + * |
| 112 | + * <p>There are two peculiarities in this conversion: |
| 113 | + * |
| 114 | + * <p>1) {@link EmptyParam#EMPTY}, containing a raw empty string value, is converted to null. |
| 115 | + * This is because the form-encoding layer prohibits passing empty string as a param map value. |
| 116 | + * It, however, allows a null value in the map (present key but null value). |
| 117 | + * Because of the translation from `EMPTY` enum to null, deserializing this map back to a |
| 118 | + * request instance is lossy. The null value will not be converted back to the `EMPTY` enum. |
| 119 | + * |
| 120 | + * <p>2) Parameter with serialized name {@link ApiRequestParams#EXTRA_PARAMS_KEY} will be |
| 121 | + * flattened. This is to support passing new params that the current library has not |
| 122 | + * yet supported. |
| 123 | + */ |
| 124 | + Map<String, Object> convert(ApiRequestParams apiRequestParams) { |
| 125 | + JsonObject jsonParams = GSON.toJsonTree(apiRequestParams).getAsJsonObject(); |
| 126 | + return FLATTENING_EXTRA_PARAMS_DESERIALIZER.deserialize(jsonParams); |
| 127 | + } |
| 128 | +} |
0 commit comments