package software.amazon.sns.subscription; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import software.amazon.cloudformation.exceptions.CfnInvalidRequestException; import java.util.Map; public final class SnsSubscriptionUtils { public static Map convertToJson(String jsonString) { final ObjectMapper objectMapper = new ObjectMapper(); Map attribute = null; if (jsonString != null) { try { attribute = objectMapper.readValue(jsonString, new TypeReference>() {}); } catch (Exception e) { throw new CfnInvalidRequestException(e); } } return attribute; } private static String convertJsonObjectToString(final Map objectMap) { final ObjectMapper objectMapper = new ObjectMapper(); String val = ""; if (objectMap != null) { try { val = objectMapper.writeValueAsString(objectMap); } catch(JsonProcessingException e) { throw new CfnInvalidRequestException(e); } } return val; } public static Map getAttributesForUpdate(final SubscriptionAttribute subscriptionAttribute, final Map previousPolicy, final Map desiredPolicy) { return getAttributesForUpdate(subscriptionAttribute, convertJsonObjectToString(previousPolicy), convertJsonObjectToString(desiredPolicy)); } public static Map getAttributesForUpdate(SubscriptionAttribute subscriptionAttribute, String previousValue, String desiredValue) { final Map attributeMap = Maps.newHashMap(); putIfChanged(attributeMap, subscriptionAttribute, previousValue , desiredValue); return attributeMap; } public static Map getAttributesForCreate(final ResourceModel currentmodel) { final Map attributeMap = Maps.newHashMap(); putIfNotEmpty(attributeMap, SubscriptionAttribute.DeliveryPolicy, convertJsonObjectToString(currentmodel.getDeliveryPolicy())); putIfNotEmpty(attributeMap, SubscriptionAttribute.FilterPolicy, convertJsonObjectToString(currentmodel.getFilterPolicy())); putIfNotEmpty(attributeMap, SubscriptionAttribute.RawMessageDelivery, currentmodel.getRawMessageDelivery() != null ? Boolean.toString(currentmodel.getRawMessageDelivery()) : ""); putIfNotEmpty(attributeMap, SubscriptionAttribute.RedrivePolicy, convertJsonObjectToString(currentmodel.getRedrivePolicy())); putIfNotEmpty(attributeMap, SubscriptionAttribute.SubscriptionRoleArn, currentmodel.getSubscriptionRoleArn()); return attributeMap; } private static void putIfNotEmpty(final Map attributeMap, final SubscriptionAttribute key, final String val) { if (!StringUtils.isEmpty(val)) { attributeMap.put(key.name(), val); } } private static void putIfChanged(final Map map, final SubscriptionAttribute key, final String previousValue, final String currentValue) { if (!StringUtils.equals(previousValue, currentValue)) { map.put(key.name(), currentValue); } } }