下面列出了java.time.zone.ZoneRulesException#software.amazon.awssdk.services.dynamodb.model.AttributeValue 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Key createKeyFromMap(Map<String, AttributeValue> itemMap,
TableSchema<?> tableSchema,
String indexName) {
String partitionKeyName = tableSchema.tableMetadata().indexPartitionKey(indexName);
Optional<String> sortKeyName = tableSchema.tableMetadata().indexSortKey(indexName);
AttributeValue partitionKeyValue = itemMap.get(partitionKeyName);
Optional<AttributeValue> sortKeyValue = sortKeyName.map(itemMap::get);
return sortKeyValue.map(
attributeValue -> Key.builder()
.partitionValue(partitionKeyValue)
.sortValue(attributeValue)
.build())
.orElseGet(
() -> Key.builder()
.partitionValue(partitionKeyValue).build());
}
@Test
public void mapperCanHandleIntDoubleMap() {
Map<Integer, Double> intDoubleMap = new ConcurrentHashMap<>();
intDoubleMap.put(1, 1.0);
intDoubleMap.put(2, 3.0);
Map<String, AttributeValue> attributeValueMap = new HashMap<>();
attributeValueMap.put("1", AttributeValue.builder().n("1.0").build());
attributeValueMap.put("2", AttributeValue.builder().n("3.0").build());
verifyNullableAttribute(EnhancedType.mapOf(Integer.class, Double.class),
a -> a.name("value")
.getter(FakeMappedItem::getAIntDoubleMap)
.setter(FakeMappedItem::setAIntDoubleMap),
FakeMappedItem.builder().aIntDoubleMap(intDoubleMap).build(),
AttributeValue.builder().m(attributeValueMap).build());
}
@Test
public void macListsUnsorted() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<>();
Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<>();
itemAttributes.put("Key1", AttributeValue.builder().ss("Value3", "Value1", "Value2").build());
attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", AttributeValue.builder().ns("100", "300", "200").build());
attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key3", AttributeValue.builder().bs(SdkBytes.fromByteArray(new byte[] { 3, 2, 1}),
SdkBytes.fromByteArray(new byte[] { 0, 1, 2, 3})).build());
attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], macKey);
Map<String, AttributeValue> scrambledAttributes = new HashMap<>();
scrambledAttributes.put("Key1", AttributeValue.builder().ss("Value1", "Value2", "Value3").build());
scrambledAttributes.put("Key2", AttributeValue.builder().ns("100", "200", "300").build());
scrambledAttributes.put("Key3", AttributeValue.builder().bs(SdkBytes.fromByteArray(new byte[] { 0, 1, 2, 3}),
SdkBytes.fromByteArray(new byte[] { 3, 2, 1})).build());
signerRsa.verifySignature(scrambledAttributes, attributeFlags, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@BeforeMethod
public void setUp() {
prov = new WrappedMaterialsProvider(encryptionKey, encryptionKey, macKey, Collections.emptyMap());
encryptor = new DynamoDbEncryptor(prov, "encryptor-");
attribs = new HashMap<>();
attribs.put("intValue", AttributeValue.builder().n("123").build());
attribs.put("stringValue", AttributeValue.builder().s("Hello world!").build());
attribs.put("byteArrayValue",
AttributeValue.builder().b(SdkBytes.fromByteArray(new byte[]{0, 1, 2, 3, 4, 5})).build());
attribs.put("stringSet",AttributeValue.builder().ss("Goodbye", "Cruel", "World", "?").build());
attribs.put("intSet", AttributeValue.builder().ns("1", "200", "10", "15", "0").build());
attribs.put("hashKey", AttributeValue.builder().n("5").build());
attribs.put("rangeKey", AttributeValue.builder().n("7").build());
attribs.put("version", AttributeValue.builder().n("0").build());
context = EncryptionContext.builder()
.tableName("TableName")
.hashKeyName("hashKey")
.rangeKeyName("rangeKey")
.build();
}
@Override
public Lease fromDynamoRecord(final Map<String, AttributeValue> dynamoRecord) {
Lease result = new Lease();
result.leaseKey(DynamoUtils.safeGetString(dynamoRecord, LEASE_KEY_KEY));
result.leaseOwner(DynamoUtils.safeGetString(dynamoRecord, LEASE_OWNER_KEY));
result.leaseCounter(DynamoUtils.safeGetLong(dynamoRecord, LEASE_COUNTER_KEY));
result.ownerSwitchesSinceCheckpoint(DynamoUtils.safeGetLong(dynamoRecord, OWNER_SWITCHES_KEY));
result.checkpoint(
new ExtendedSequenceNumber(
DynamoUtils.safeGetString(dynamoRecord, CHECKPOINT_SEQUENCE_NUMBER_KEY),
DynamoUtils.safeGetLong(dynamoRecord, CHECKPOINT_SUBSEQUENCE_NUMBER_KEY))
);
result.parentShardIds(DynamoUtils.safeGetSS(dynamoRecord, PARENT_SHARD_ID_KEY));
if (!Strings.isNullOrEmpty(DynamoUtils.safeGetString(dynamoRecord, PENDING_CHECKPOINT_SEQUENCE_KEY))) {
result.pendingCheckpoint(
new ExtendedSequenceNumber(
DynamoUtils.safeGetString(dynamoRecord, PENDING_CHECKPOINT_SEQUENCE_KEY),
DynamoUtils.safeGetLong(dynamoRecord, PENDING_CHECKPOINT_SUBSEQUENCE_KEY))
);
}
return result;
}
private DeleteItemRequest.Builder addExpressionsIfExist(DeleteItemRequest.Builder requestBuilder) {
if (this.request.conditionExpression() != null) {
requestBuilder = requestBuilder.conditionExpression(this.request.conditionExpression().expression());
Map<String, String> expressionNames = this.request.conditionExpression().expressionNames();
Map<String, AttributeValue> expressionValues = this.request.conditionExpression().expressionValues();
// Avoiding adding empty collections that the low level SDK will propagate to DynamoDb where it causes error.
if (expressionNames != null && !expressionNames.isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeNames(expressionNames);
}
if (expressionValues != null && !expressionValues.isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeValues(expressionValues);
}
}
return requestBuilder;
}
@Test
public void getEmptyBytes() {
Map<String, AttributeValue> itemMap = new HashMap<>();
itemMap.put("id", AttributeValue.builder().s("id123").build());
itemMap.put("b", EMPTY_BINARY);
GetItemResponse response = GetItemResponse.builder()
.item(itemMap)
.build();
when(mockDynamoDbClient.getItem(any(GetItemRequest.class))).thenReturn(response);
TestBean result = dynamoDbTable.getItem(r -> r.key(k -> k.partitionValue("id123")));
assertThat(result.getId()).isEqualTo("id123");
assertThat(result.getB()).isEqualTo(EMPTY_BYTES);
}
@Test
public void enumBean_listEnum() {
BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class);
EnumBean enumBean = new EnumBean();
enumBean.setId("id-value");
enumBean.setTestEnumList(Arrays.asList(EnumBean.TestEnum.ONE, EnumBean.TestEnum.TWO));
Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(enumBean, true);
AttributeValue expectedAttributeValue = AttributeValue.builder()
.l(stringValue("ONE"),
stringValue("TWO"))
.build();
assertThat(itemMap.size(), is(2));
assertThat(itemMap, hasEntry("id", stringValue("id-value")));
assertThat(itemMap, hasEntry("testEnumList", expectedAttributeValue));
EnumBean reverse = beanTableSchema.mapToItem(itemMap);
assertThat(reverse, is(equalTo(enumBean)));
}
@Test
public void usesCustomAttributeConverterProvider() {
String originalString = "test-string";
String expectedString = "test-string-custom";
when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1);
when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build());
StaticTableSchema<FakeMappedItem> tableSchema =
StaticTableSchema.builder(FakeMappedItem.class)
.newItemSupplier(FakeMappedItem::new)
.addAttribute(String.class, a -> a.name("aString")
.getter(FakeMappedItem::getAString)
.setter(FakeMappedItem::setAString))
.attributeConverterProviders(provider1)
.build();
Map<String, AttributeValue> resultMap =
tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false);
assertThat(resultMap.get("aString").s(), is(expectedString));
}
@Test(expectedExceptions = DynamoDbEncryptionException.class)
public void encryptionKeyIdMismatch() {
DirectKmsMaterialsProvider directProvider = new DirectKmsMaterialsProvider(kms, keyId);
String customKeyId = kms.createKey().keyMetadata().keyId();
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", AttributeValue.builder().n("10").build());
attrVals.put("rk", AttributeValue.builder().n("20").build());
attrVals.put("encryptionKeyId", AttributeValue.builder().s(customKeyId).build());
ctx = EncryptionContext.builder().hashKeyName("hk").rangeKeyName("rk")
.tableName("KmsTableName").attributeValues(attrVals).build();
EncryptionMaterials eMat = directProvider.getEncryptionMaterials(ctx);
EncryptionContext dCtx = ctx(eMat).toBuilder()
.hashKeyName("hk")
.rangeKeyName("rk")
.tableName("KmsTableName")
.attributeValues(attrVals)
.build();
ExtendedKmsMaterialProvider extendedProvider = new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId");
extendedProvider.getDecryptionMaterials(dCtx);
}
@Test
public void testComplexList() {
final List<AttributeValue> list1 = Arrays.asList(
AttributeValueBuilder.ofS("StringValue"),
AttributeValueBuilder.ofN("1000"),
AttributeValueBuilder.ofBool(Boolean.TRUE));
final List<AttributeValue> list22 = Arrays.asList(
AttributeValueBuilder.ofS("AWS"),
AttributeValueBuilder.ofN("-3700"),
AttributeValueBuilder.ofBool(Boolean.FALSE));
final List<AttributeValue> list2 = Arrays.asList(
AttributeValueBuilder.ofL(list22),
AttributeValueBuilder.ofNull());
AttributeValue av = AttributeValueBuilder.ofL(
AttributeValueBuilder.ofS("StringValue1"),
AttributeValueBuilder.ofL(list1),
AttributeValueBuilder.ofN("50"),
AttributeValueBuilder.ofL(list2));
assertAttributesAreEqual(av, unmarshall(marshall(av)));
}
@Test
public void signedOnly() {
Map<String, AttributeValue> encryptedAttributes =
EncryptionTestHelper.encryptAllFieldsExcept(encryptor, attribs, context, attribs.keySet());
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
EncryptionTestHelper.decryptAllFieldsExcept(encryptor, encryptedAttributes, context, attribs.keySet());
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test
public void testGetJob_Failure() throws Throwable {
String token = getToken(4);
JobTokenPayload tokenPayload = tokenManager.decodeToken(token);
Map<String, AttributeValue> primaryKey =
DynamoDBUtils.getPrimaryKeyFromToken(token, tokenPayload, maxShardId);
GetItemRequest getItemRequest =
GetItemRequest.builder()
.key(primaryKey)
.tableName(tableName)
.attributesToGet(Collections.singletonList(DynamoDBUtils.Attribute.JOB_SPEC.columnName))
.build();
CompletableFuture<GetItemResponse> ret = new CompletableFuture<>();
Exception exception = new Exception();
ret.completeExceptionally(exception);
when(ddbClient.getItem(getItemRequest)).thenReturn(ret);
CompletableFuture<Schedule> response = scheduleManager.getJob(token);
assertSame(getException(response), exception);
verify(ddbClient, times(1)).getItem(getItemRequest);
verifyNoMoreInteractions(ddbClient);
}
@Test
public void sigEcdsaWithIgnoredChange() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<>();
Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<>();
itemAttributes.put("Key1", AttributeValue.builder().s("Value1").build());
attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", AttributeValue.builder().n("100").build());
attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key3", AttributeValue.builder().b(SdkBytes.fromByteArray(new byte[] { 0, 1, 2, 3})).build());
attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key4", AttributeValue.builder().s("Ignored Value").build());
byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa);
itemAttributes.put("Key4", AttributeValue.builder().s("New Ignored Value").build());
signerEcdsa.verifySignature(itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
@Test
public void listBean_stringListList() {
BeanTableSchema<ListBean> beanTableSchema = BeanTableSchema.create(ListBean.class);
ListBean listBean = new ListBean();
listBean.setId("id-value");
listBean.setStringListList(Arrays.asList(Arrays.asList("one", "two"), Arrays.asList("three", "four")));
Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(listBean, true);
AttributeValue list1 = AttributeValue.builder().l(stringValue("one"), stringValue("two")).build();
AttributeValue list2 = AttributeValue.builder().l(stringValue("three"), stringValue("four")).build();
AttributeValue expectedAttributeValue = AttributeValue.builder()
.l(list1, list2)
.build();
assertThat(itemMap.size(), is(2));
assertThat(itemMap, hasEntry("id", stringValue("id-value")));
assertThat(itemMap, hasEntry("stringListList", expectedAttributeValue));
ListBean reverse = beanTableSchema.mapToItem(itemMap);
assertThat(reverse, is(equalTo(listBean)));
}
@Test
public void parameterizedDocumentBean_correctlyMapsAttributes() {
BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class);
ParameterizedAbstractBean<String> abstractBean = new ParameterizedAbstractBean<>();
abstractBean.setAttribute2("two");
ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean();
documentBean.setId("id-value");
documentBean.setAttribute1("one");
documentBean.setAbstractBean(abstractBean);
AttributeValue expectedDocument = AttributeValue.builder()
.m(singletonMap("attribute2", stringValue("two")))
.build();
Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true);
assertThat(itemMap.size(), is(3));
assertThat(itemMap, hasEntry("id", stringValue("id-value")));
assertThat(itemMap, hasEntry("attribute1", stringValue("one")));
assertThat(itemMap, hasEntry("abstractBean", expectedDocument));
}
@Test
public void transformResponse_correctlyTransformsIntoAnItem() {
FakeItem keyItem = createUniqueFakeItem();
DeleteItemOperation<FakeItem> deleteItemOperation =
DeleteItemOperation.create(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(keyItem.getId())).build());
Map<String, AttributeValue> responseMap = new HashMap<>();
responseMap.put("id", AttributeValue.builder().s(keyItem.getId()).build());
responseMap.put("subclass_attribute", AttributeValue.builder().s("test-value").build());
DeleteItemResponse response = DeleteItemResponse.builder()
.attributes(responseMap)
.build();
FakeItem result = deleteItemOperation.transformResponse(response,
FakeItem.getTableSchema(),
PRIMARY_CONTEXT,
null);
assertThat(result.getId(), is(keyItem.getId()));
assertThat(result.getSubclassAttribute(), is("test-value"));
}
@Test
public void documentBean_correctlyMapsAttributes() {
BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class);
AbstractBean abstractBean = new AbstractBean();
abstractBean.setAttribute2("two");
DocumentBean documentBean = new DocumentBean();
documentBean.setId("id-value");
documentBean.setAttribute1("one");
documentBean.setAbstractBean(abstractBean);
AttributeValue expectedDocument = AttributeValue.builder()
.m(singletonMap("attribute2", stringValue("two")))
.build();
Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true);
assertThat(itemMap.size(), is(3));
assertThat(itemMap, hasEntry("id", stringValue("id-value")));
assertThat(itemMap, hasEntry("attribute1", stringValue("one")));
assertThat(itemMap, hasEntry("abstractBean", expectedDocument));
}
@Test
public void fullEncryption() {
Map<String, AttributeValue> encryptedAttributes =
EncryptionTestHelper.encryptAllFieldsExcept(encryptor, Collections.unmodifiableMap(attribs), context, asList("hashKey", "rangeKey", "version"));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
EncryptionTestHelper.decryptAllFieldsExcept(encryptor, Collections.unmodifiableMap(encryptedAttributes), context, asList("hashKey", "rangeKey", "version"));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringValue"));
assertNull(encryptedAttributes.get("stringValue").s());
assertNotNull(encryptedAttributes.get("stringValue").b());
}
@Test
public void emptyConverterProviderList_correct_whenAttributeConvertersAreSupplied() {
BeanTableSchema<EmptyConverterProvidersValidBean> beanTableSchema =
BeanTableSchema.create(EmptyConverterProvidersValidBean.class);
EmptyConverterProvidersValidBean converterBean = new EmptyConverterProvidersValidBean();
converterBean.setId("id-value");
converterBean.setIntegerAttribute(123);
Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false);
assertThat(itemMap.size(), is(2));
assertThat(itemMap, hasEntry("id", stringValue("id-value-custom")));
assertThat(itemMap, hasEntry("integerAttribute", numberValue(133)));
EmptyConverterProvidersValidBean reverse = beanTableSchema.mapToItem(itemMap);
assertThat(reverse.getId(), is(equalTo("id-value-custom")));
assertThat(reverse.getIntegerAttribute(), is(equalTo(133)));
}
@BeforeMethod
public void setUp() {
prov = new SymmetricStaticProvider(encryptionKey, macKey,
Collections.emptyMap());
encryptor = new DynamoDbEncryptor(prov, "encryptor-");
attribs = new HashMap<>();
attribs.put("intValue", AttributeValue.builder().n("123").build());
attribs.put("stringValue", AttributeValue.builder().s("Hello world!").build());
attribs.put("byteArrayValue",
AttributeValue.builder().b(SdkBytes.fromByteArray(new byte[] {0, 1, 2, 3, 4, 5})).build());
attribs.put("stringSet", AttributeValue.builder().ss("Goodbye", "Cruel", "World", "?").build());
attribs.put("intSet", AttributeValue.builder().ns("1", "200", "10", "15", "0").build());
attribs.put("hashKey", AttributeValue.builder().n("5").build());
attribs.put("rangeKey", AttributeValue.builder().n("7").build());
attribs.put("version", AttributeValue.builder().n("0").build());
context = EncryptionContext.builder()
.tableName("TableName")
.hashKeyName("hashKey")
.rangeKeyName("rangeKey")
.build();
}
public static void scanItems( DynamoDbClient ddb,String tableName ) {
try {
ScanRequest scanRequest = ScanRequest.builder()
.tableName(tableName)
.build();
ScanResponse response = ddb.scan(scanRequest);
for (Map<String, AttributeValue> item : response.items()) {
Set<String> keys = item.keySet();
for (String key : keys) {
System.out.println ("The key name is "+key +"\n" );
System.out.println("The value is "+item.get(key).s());
}
}
} catch (DynamoDbException e) {
e.printStackTrace();
}
// snippet-end:[dynamodb.java2.dynamoDB_scan.main]
}
@Test
public void generateRequest_filterExpression_withValues() {
Map<String, AttributeValue> expressionValues = singletonMap(":test-key", stringValue("test-value"));
Expression filterExpression = Expression.builder()
.expression("test-expression")
.expressionValues(expressionValues)
.build();
QueryOperation<FakeItem> queryToTest =
QueryOperation.create(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId())))
.filterExpression(filterExpression)
.build());
QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(),
PRIMARY_CONTEXT,
null);
assertThat(queryRequest.filterExpression(), is("test-expression"));
assertThat(queryRequest.expressionAttributeValues(), hasEntry(":test-key", stringValue("test-value")));
}
public ApplicationsService(
final TokenSerializer<Map<String, AttributeValue>> paginationTokenSerializer,
final DynamoDbClient dynamodb, final ConfigProvider configProvider,
final Clock clock) {
this(paginationTokenSerializer, dynamodb, configureModelMapper(),
configProvider.getApplicationsTableName(), clock);
}
@Override
protected void assertUnlocked(String lockName) {
Map<String, AttributeValue> lockItem = getLockItem(lockName);
assertThat(fromIsoString(lockItem.get(LOCK_UNTIL).s())).isBeforeOrEqualTo(now());
assertThat(fromIsoString(lockItem.get(LOCKED_AT).s())).isBeforeOrEqualTo(now());
assertThat(lockItem.get(LOCKED_BY).s()).isNotEmpty();
}
@Test
public void mapperCanHandleByte() {
verifyNullableAttribute(EnhancedType.of(Byte.class),
a -> a.name("value")
.getter(FakeMappedItem::getAByte)
.setter(FakeMappedItem::setAByte),
FakeMappedItem.builder().aByte((byte)123).build(),
AttributeValue.builder().n("123").build());
}
@Test(expectedExceptions = DynamoDbEncryptionException.class)
public void RsaSignedOnlyBadSignature() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor = new DynamoDbEncryptor(
new SymmetricStaticProvider(encryptionKey, sigPair,
Collections.emptyMap()), "encryptor-");
Map<String, AttributeValue> encryptedAttributes = EncryptionTestHelper.encryptAllFieldsExcept(encryptor, attribs, context, attribs.keySet());
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> modifiedEncryptedAttributes = new HashMap<>(encryptedAttributes);
modifiedEncryptedAttributes.put("hashKey", AttributeValue.builder().n("666").build());
EncryptionTestHelper.decryptAllFieldsExcept(encryptor, modifiedEncryptedAttributes, context, attribs.keySet());
}
@Test
public void mapperCanHandlePrimitiveLong() {
verifyAttribute(EnhancedType.of(long.class),
a -> a.name("value")
.getter(FakeMappedItem::getAPrimitiveLong)
.setter(FakeMappedItem::setAPrimitiveLong),
FakeMappedItem.builder().aPrimitiveLong(123L).build(),
AttributeValue.builder().n("123").build());
}
@Test
public void mapperCanHandleFloat() {
verifyNullableAttribute(EnhancedType.of(Float.class),
a -> a.name("value")
.getter(FakeMappedItem::getAFloat)
.setter(FakeMappedItem::setAFloat),
FakeMappedItem.builder().aFloat(1.23f).build(),
AttributeValue.builder().n("1.23").build());
}
@Test
public void updateApplication_author() {
String userId = UUID.randomUUID().toString();
String applicationId = UUID.randomUUID().toString();
String author = UUID.randomUUID().toString();
Long version = 1L;
Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);
recordMap.put("version", AttributeValue.builder().n(version.toString()).build());
GetItemResponse response = GetItemResponse.builder()
.item(recordMap)
.build();
Map<String, AttributeValue> updateMap = new HashMap<>();
updateMap.put(":nv", AttributeValue.builder().n("2").build());
updateMap.put(":v", AttributeValue.builder().n("1").build());
updateMap.put(":a", AttributeValue.builder().s(author).build());
when(principal.getName()).thenReturn(userId);
when(dynamodb.getItem(any(GetItemRequest.class))).thenReturn(response);
UpdateApplicationInput input = new UpdateApplicationInput().author(author);
UpdateItemRequest expectedUpdateItemRequest = UpdateItemRequest.builder()
.tableName(TABLE_NAME)
.key(keyMap(userId, applicationId))
.updateExpression("SET author = :a,version = :nv")
.expressionAttributeValues(updateMap)
.conditionExpression("version = :v")
.build();
Application application = service.updateApplication(input, applicationId);
ArgumentCaptor<UpdateItemRequest> updateItemRequestArgumentCaptor = ArgumentCaptor.forClass(UpdateItemRequest.class);
verify(dynamodb).updateItem(updateItemRequestArgumentCaptor.capture());
UpdateItemRequest updateItemRequest = updateItemRequestArgumentCaptor.getValue();
assertThat(updateItemRequest).isEqualTo(expectedUpdateItemRequest);
assertThat(application.getApplicationId()).isEqualTo(applicationId);
assertThat(application.getAuthor()).isEqualTo(author);
}