1 /* 2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"). 5 * You may not use this file except in compliance with the License. 6 * A copy of the License is located at 7 * 8 * http://aws.amazon.com/apache2.0 9 * 10 * or in the "license" file accompanying this file. This file is distributed 11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 * express or implied. See the License for the specific language governing 13 * permissions and limitations under the License. 14 */ 15 16 package software.amazon.awssdk.enhanced.dynamodb.internal.mapper; 17 18 import java.util.function.Consumer; 19 import software.amazon.awssdk.annotations.SdkInternalApi; 20 import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; 21 import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; 22 import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; 23 import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; 24 import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; 25 26 @SdkInternalApi 27 public class UpdateBehaviorTag implements StaticAttributeTag { 28 private static final String CUSTOM_METADATA_KEY_PREFIX = "UpdateBehavior:"; 29 private static final UpdateBehavior DEFAULT_UPDATE_BEHAVIOR = UpdateBehavior.WRITE_ALWAYS; 30 private static final UpdateBehaviorTag WRITE_ALWAYS_TAG = new UpdateBehaviorTag(UpdateBehavior.WRITE_ALWAYS); 31 private static final UpdateBehaviorTag WRITE_IF_NOT_EXISTS_TAG = 32 new UpdateBehaviorTag(UpdateBehavior.WRITE_IF_NOT_EXISTS); 33 34 private final UpdateBehavior updateBehavior; 35 UpdateBehaviorTag(UpdateBehavior updateBehavior)36 private UpdateBehaviorTag(UpdateBehavior updateBehavior) { 37 this.updateBehavior = updateBehavior; 38 } 39 fromUpdateBehavior(UpdateBehavior updateBehavior)40 public static UpdateBehaviorTag fromUpdateBehavior(UpdateBehavior updateBehavior) { 41 switch (updateBehavior) { 42 case WRITE_ALWAYS: 43 return WRITE_ALWAYS_TAG; 44 case WRITE_IF_NOT_EXISTS: 45 return WRITE_IF_NOT_EXISTS_TAG; 46 default: 47 throw new IllegalArgumentException("Update behavior '" + updateBehavior + "' not supported"); 48 } 49 } 50 resolveForAttribute(String attributeName, TableMetadata tableMetadata)51 public static UpdateBehavior resolveForAttribute(String attributeName, TableMetadata tableMetadata) { 52 String metadataKey = CUSTOM_METADATA_KEY_PREFIX + attributeName; 53 return tableMetadata.customMetadataObject(metadataKey, UpdateBehavior.class).orElse(DEFAULT_UPDATE_BEHAVIOR); 54 } 55 56 @Override modifyMetadata(String attributeName, AttributeValueType attributeValueType)57 public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, 58 AttributeValueType attributeValueType) { 59 return metadata -> 60 metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY_PREFIX + attributeName, this.updateBehavior); 61 } 62 } 63