-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
DynamoDBMapper.java
1804 lines (1588 loc) · 76.2 KB
/
DynamoDBMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2011-2013 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.datamodeling;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.http.AmazonHttpClient;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.ConsistentReads;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate;
import com.amazonaws.services.dynamodbv2.model.BatchGetItemRequest;
import com.amazonaws.services.dynamodbv2.model.BatchGetItemResult;
import com.amazonaws.services.dynamodbv2.model.BatchWriteItemRequest;
import com.amazonaws.services.dynamodbv2.model.BatchWriteItemResult;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest;
import com.amazonaws.services.dynamodbv2.model.DeleteRequest;
import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.GetItemResult;
import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutRequest;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.services.dynamodbv2.model.Select;
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
import com.amazonaws.services.dynamodbv2.model.WriteRequest;
import com.amazonaws.util.VersionInfoUtils;
/**
* Object mapper for domain-object interaction with DynamoDB.
* <p>
* To use, annotate domain classes with the annotations found in the
* com.amazonaws.services.dynamodbv2.datamodeling package. A minimal example:
*
* <pre>
* @DynamoDBTable(tableName = "TestTable")
* public class TestClass {
*
* private Long key;
* private double rangeKey;
* private Long version;
*
* private Set<Integer> integerSetAttribute;
*
* @DynamoDBHashKey
* public Long getKey() {
* return key;
* }
*
* public void setKey(Long key) {
* this.key = key;
* }
*
* @DynamoDBRangeKey
* public double getRangeKey() {
* return rangeKey;
* }
*
* public void setRangeKey(double rangeKey) {
* this.rangeKey = rangeKey;
* }
*
* @DynamoDBAttribute(attributeName = "integerSetAttribute")
* public Set<Integer> getIntegerAttribute() {
* return integerSetAttribute;
* }
*
* public void setIntegerAttribute(Set<Integer> integerAttribute) {
* this.integerSetAttribute = integerAttribute;
* }
*
* @DynamoDBVersionAttribute
* public Long getVersion() {
* return version;
* }
*
* public void setVersion(Long version) {
* this.version = version;
* }
* }
* </pre>
* <p>
* Save instances of annotated classes to DynamoDB, retrieve them, and delete
* them using the {@link DynamoDBMapper} class, as in the following example.
*
* <pre>
* DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
* Long hashKey = 105L;
* double rangeKey = 1.0d;
* TestClass obj = mapper.load(TestClass.class, hashKey, rangeKey);
* obj.getIntegerAttribute().add(42);
* mapper.save(obj);
* mapper.delete(obj);
* </pre>
* <p>
* When using the save, load, and delete methods, {@link DynamoDBMapper} will
* throw {@link DynamoDBMappingException}s to indicate that domain classes are
* incorrectly annotated or otherwise incompatible with this class. Service
* exceptions will always be propagated as {@link AmazonClientException}, and
* DynamoDB-specific subclasses such as {@link ConditionalCheckFailedException}
* will be used when possible.
* <p>
* This class is thread-safe and can be shared between threads. It's also very
* lightweight, so it doesn't need to be.
*
* @see DynamoDBTable
* @see DynamoDBHashKey
* @see DynamoDBRangeKey
* @see DynamoDBAutoGeneratedKey
* @see DynamoDBAttribute
* @see DynamoDBVersionAttribute
* @see DynamoDBIgnore
* @see DynamoDBMarshalling
* @see DynamoDBMapperConfig
*/
public class DynamoDBMapper {
private final AmazonDynamoDB db;
private final DynamoDBMapperConfig config;
private static final DynamoDBReflector reflector = new DynamoDBReflector();
/** The max back off time for batch write */
private static final long MAX_BACKOFF_IN_MILLISECONDS = 1000 * 3;
/**
* User agent for requests made using the {@link DynamoDBMapper}.
*/
private static final String USER_AGENT = DynamoDBMapper.class.getName() + "/" + VersionInfoUtils.getVersion();
/**
* Constructs a new mapper with the service object given, using the default
* configuration.
*
* @param dynamoDB
* The service object to use for all service calls.
* @see DynamoDBMapperConfig#DEFAULT
*/
public DynamoDBMapper(AmazonDynamoDB dynamoDB) {
this(dynamoDB, DynamoDBMapperConfig.DEFAULT);
}
/**
* Constructs a new mapper with the service object and configuration given.
*
* @param dynamoDB
* The service object to use for all service calls.
* @param config
* The default configuration to use for all service calls. It can
* be overridden on a per-operation basis.
*/
public DynamoDBMapper(AmazonDynamoDB dynamoDB, DynamoDBMapperConfig config) {
this.db = dynamoDB;
this.config = config;
}
/**
* Loads an object with the hash key given and a configuration override.
* This configuration overrides the default provided at object construction.
*
* @see DynamoDBMapper#load(Class, Object, Object, DynamoDBMapperConfig)
*/
public <T extends Object> T load(Class<T> clazz, Object hashKey, DynamoDBMapperConfig config) {
return load(clazz, hashKey, null, config);
}
/**
* Loads an object with the hash key given, using the default configuration.
*
* @see DynamoDBMapper#load(Class, Object, Object, DynamoDBMapperConfig)
*/
public <T extends Object> T load(Class<T> clazz, Object hashKey) {
return load(clazz, hashKey, null, config);
}
/**
* Loads an object with a hash and range key, using the default
* configuration.
*
* @see DynamoDBMapper#load(Class, Object, Object, DynamoDBMapperConfig)
*/
public <T extends Object> T load(Class<T> clazz, Object hashKey, Object rangeKey) {
return load(clazz, hashKey, rangeKey, config);
}
/**
* Returns an object whose keys match those of the prototype key object given,
* or null if no such item exists.
*
* @param keyObject
* An object of the class to load with the keys values to match.
*
* @see DynamoDBMapper#load(Object, DynamoDBMapperConfig)
*/
public <T extends Object> T load(T keyObject) {
return load(keyObject, this.config);
}
/**
* Returns an object whose keys match those of the prototype key object given,
* or null if no such item exists.
*
* @param keyObject
* An object of the class to load with the keys values to match.
* @param config
* Configuration for the service call to retrieve the object from
* DynamoDB. This configuration overrides the default given at
* construction.
*/
public <T extends Object> T load(T keyObject, DynamoDBMapperConfig config) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) keyObject.getClass();
config = mergeConfig(config);
String tableName = getTableName(clazz, config);
GetItemRequest rq = new GetItemRequest();
Map<String, AttributeValue> key = getKey(keyObject, clazz);
rq.setKey(key);
rq.setTableName(tableName);
rq.setConsistentRead(config.getConsistentReads() == ConsistentReads.CONSISTENT);
GetItemResult item = db.getItem(applyUserAgent(rq));
Map<String, AttributeValue> itemAttributes = item.getItem();
if ( itemAttributes == null ) {
return null;
}
return marshallIntoObject(clazz, itemAttributes);
}
/**
* Returns a key map for the key object given.
*
* @param keyObject
* The key object, corresponding to an item in a dynamo table.
*/
@SuppressWarnings("unchecked")
private <T> Map<String, AttributeValue> getKey(T keyObject) {
return getKey(keyObject, (Class<T>)keyObject.getClass());
}
private <T> Map<String, AttributeValue> getKey(T keyObject, Class<T> clazz) {
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
for (Method keyGetter : reflector.getKeyGetters(clazz)) {
Object getterResult = safeInvoke(keyGetter, keyObject);
AttributeValue keyAttributeValue = getSimpleAttributeValue(keyGetter, getterResult);
if (keyAttributeValue == null) {
throw new DynamoDBMappingException("Null key found for " + keyGetter);
}
key.put(reflector.getAttributeName(keyGetter), keyAttributeValue);
}
if ( key.isEmpty() ) {
throw new DynamoDBMappingException("Class must be annotated with " + DynamoDBHashKey.class + " and "
+ DynamoDBRangeKey.class);
}
return key;
}
/**
* Returns an object with the given hash key, or null if no such object
* exists.
*
* @param clazz
* The class to load, corresponding to a DynamoDB table.
* @param hashKey
* The key of the object.
* @param rangeKey
* The range key of the object, or null for tables without a
* range key.
* @param config
* Configuration for the service call to retrieve the object from
* DynamoDB. This configuration overrides the default given at
* construction.
*/
public <T extends Object> T load(Class<T> clazz, Object hashKey, Object rangeKey, DynamoDBMapperConfig config) {
config = mergeConfig(config);
T keyObject = createKeyObject(clazz, hashKey, rangeKey);
return load(keyObject, config);
}
/**
* Creates a key prototype object for the class given with the single hash and range key given.
*/
private <T> T createKeyObject(Class<T> clazz, Object hashKey, Object rangeKey) {
T keyObject = null;
try {
keyObject = clazz.newInstance();
} catch ( Exception e ) {
throw new DynamoDBMappingException("Failed to instantiate class", e);
}
boolean seenHashKey = false;
boolean seenRangeKey = false;
for ( Method getter : reflector.getKeyGetters(clazz) ) {
if ( getter.isAnnotationPresent(DynamoDBHashKey.class) ) {
if ( seenHashKey ) {
throw new DynamoDBMappingException("Found more than one method annotated with "
+ DynamoDBHashKey.class + " for class " + clazz
+ ". Use load(Object) for tables with more than a single hash and range key.");
}
seenHashKey = true;
safeInvoke(reflector.getSetter(getter), keyObject, hashKey);
} else if ( getter.isAnnotationPresent(DynamoDBRangeKey.class) ) {
if ( seenRangeKey ) {
throw new DynamoDBMappingException("Found more than one method annotated with "
+ DynamoDBRangeKey.class + " for class " + clazz
+ ". Use load(Object) for tables with more than a single hash and range key.");
}
seenRangeKey = true;
safeInvoke(reflector.getSetter(getter), keyObject, rangeKey);
}
}
if ( !seenHashKey ) {
throw new DynamoDBMappingException("No method annotated with " + DynamoDBHashKey.class + " for class "
+ clazz + ".");
} else if ( rangeKey != null && !seenRangeKey ) {
throw new DynamoDBMappingException("No method annotated with " + DynamoDBRangeKey.class + " for class "
+ clazz + ".");
}
return keyObject;
}
/**
* Returns a map of attribute name to EQ condition for the key prototype
* object given.
*/
private Map<String, Condition> getHashKeyEqualsConditions(Object obj) {
Map<String, Condition> conditions = new HashMap<String, Condition>();
for ( Method getter : reflector.getKeyGetters(obj.getClass()) ) {
if ( getter.isAnnotationPresent(DynamoDBHashKey.class) ) {
conditions.put(
reflector.getAttributeName(getter),
new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(
getSimpleAttributeValue(getter, safeInvoke(getter, obj, (Object[])null))));
}
}
return conditions;
}
/**
* Returns the table name for the class given.
*/
private <T> String getTableName(Class<T> clazz, DynamoDBMapperConfig config) {
DynamoDBTable table = reflector.getTable(clazz);
String tableName = table.tableName();
if ( config.getTableNameOverride() != null ) {
if ( config.getTableNameOverride().getTableName() != null ) {
tableName = config.getTableNameOverride().getTableName();
} else {
tableName = config.getTableNameOverride().getTableNamePrefix() + tableName;
}
}
return tableName;
}
/**
* Creates and fills in the attributes on an instance of the class given
* with the attributes given.
* <p>
* This is accomplished by looking for getter methods annotated with an
* appropriate annotation, then looking for matching attribute names in the
* item attribute map.
*
* @param clazz
* The class to instantiate and hydrate
* @param itemAttributes
* The set of item attributes, keyed by attribute name.
*/
public <T> T marshallIntoObject(Class<T> clazz, Map<String, AttributeValue> itemAttributes) {
T toReturn = null;
try {
toReturn = clazz.newInstance();
} catch ( InstantiationException e ) {
throw new DynamoDBMappingException("Failed to instantiate new instance of class", e);
} catch ( IllegalAccessException e ) {
throw new DynamoDBMappingException("Failed to instantiate new instance of class", e);
}
if ( itemAttributes == null || itemAttributes.isEmpty() )
return toReturn;
itemAttributes = untransformAttributes(clazz, itemAttributes);
for ( Method m : reflector.getRelevantGetters(clazz) ) {
String attributeName = reflector.getAttributeName(m);
if ( itemAttributes.containsKey(attributeName) ) {
setValue(toReturn, m, itemAttributes.get(attributeName));
}
}
return toReturn;
}
/**
* Marshalls the list of item attributes into objects of type clazz
*
* @see DynamoDBMapper#marshallIntoObject(Class, Map)
*/
public <T> List<T> marshallIntoObjects(Class<T> clazz, List<Map<String, AttributeValue>> itemAttributes) {
List<T> result = new ArrayList<T>();
for (Map<String, AttributeValue> item : itemAttributes) {
result.add(marshallIntoObject(clazz, item));
}
return result;
}
/**
* Sets the value in the return object corresponding to the service result.
*/
private <T> void setValue(final T toReturn, final Method getter, AttributeValue value) {
Method setter = reflector.getSetter(getter);
ArgumentUnmarshaller unmarhsaller = reflector.getArgumentUnmarshaller(toReturn, getter, setter);
unmarhsaller.typeCheck(value, setter);
Object argument;
try {
argument = unmarhsaller.unmarshall(value);
} catch ( IllegalArgumentException e ) {
throw new DynamoDBMappingException("Couldn't unmarshall value " + value + " for " + setter, e);
} catch ( ParseException e ) {
throw new DynamoDBMappingException("Error attempting to parse date string " + value + " for "+ setter, e);
}
safeInvoke(setter, toReturn, argument);
}
/**
* Returns an {@link AttributeValue} corresponding to the getter and return
* result given, treating it as a non-versioned attribute.
*/
private AttributeValue getSimpleAttributeValue(final Method getter, final Object getterReturnResult) {
if ( getterReturnResult == null )
return null;
ArgumentMarshaller marshaller = reflector.getArgumentMarshaller(getter);
return marshaller.marshall(getterReturnResult);
}
/**
* Saves the object given into DynamoDB, using the default configuration.
*
* @see DynamoDBMapper#save(Object, DynamoDBMapperConfig)
*/
public <T extends Object> void save(T object) {
save(object, config);
}
/**
* Saves an item in DynamoDB. The service method used is determined by the
* {@link DynamoDBMapperConfig#getSaveBehavior()} value, to use either
* {@link AWSDynamoDB#putItem(PutItemRequest)} or
* {@link AWSDynamoDB#updateItem(UpdateItemRequest)}. For updates, a null
* value for an object property will remove it from that item in DynamoDB.
* For puts, a null value will not be passed to the service. The effect is
* therefore the same, except when the item in DynamoDB contains attributes
* that aren't modeled by the domain object given.
*
* @param object
* The object to save into DynamoDB
* @param config
* The configuration to use, which overrides the default provided
* at object construction.
*/
public <T extends Object> void save(T object, DynamoDBMapperConfig config) {
config = mergeConfig(config);
@SuppressWarnings("unchecked")
Class<? extends T> clazz = (Class<? extends T>) object.getClass();
String tableName = getTableName(clazz, config);
Map<String, AttributeValueUpdate> updateValues = new HashMap<String, AttributeValueUpdate>();
Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>();
boolean forcePut = config.getSaveBehavior() == SaveBehavior.CLOBBER;
List<ValueUpdate> inMemoryUpdates = new LinkedList<ValueUpdate>();
Collection<Method> keyGetters = reflector.getKeyGetters(clazz);
/*
* Determine if there are any auto-assigned keys to assign. If so, force
* a put and assign the keys.
*/
boolean hashKeyGetterFound = false;
for ( Method method : keyGetters ) {
Object getterResult = safeInvoke(method, object);
if ( getterResult == null && reflector.isAssignableKey(method) ) {
forcePut = true;
}
if ( method.isAnnotationPresent(DynamoDBHashKey.class) ) {
hashKeyGetterFound = true;
}
}
if ( !hashKeyGetterFound ) {
throw new DynamoDBMappingException("No " + DynamoDBHashKey.class + " annotation found in class " + clazz);
}
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
/*
* First handle keys
*/
for ( Method method : keyGetters ) {
Object getterResult = safeInvoke(method, object);
String attributeName = reflector.getAttributeName(method);
if ( getterResult == null && reflector.isAssignableKey(method) ) {
AttributeValue newVersionValue = getAutoGeneratedKeyAttributeValue(method, getterResult);
key.put(attributeName, newVersionValue);
if ( forcePut ) {
updateValues.put(attributeName,
new AttributeValueUpdate().withAction("PUT").withValue(newVersionValue));
inMemoryUpdates.add(new ValueUpdate(method, newVersionValue, object));
if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) {
// Add an expect clause to make sure that the item
// doesn't already exist, since it's supposed to be new
ExpectedAttributeValue expected = new ExpectedAttributeValue();
expected.setExists(false);
expectedValues.put(attributeName, expected);
}
}
} else {
AttributeValue currentValue = getSimpleAttributeValue(method, getterResult);
if ( currentValue == null ) {
throw new DynamoDBMappingException("Null or empty value for key: " + method);
}
key.put(attributeName, currentValue);
if ( forcePut ) {
updateValues.put(attributeName, new AttributeValueUpdate().withValue(currentValue)
.withAction("PUT"));
}
}
}
/*
* Next construct an update for every non-key property
*/
for ( Method method : reflector.getRelevantGetters(clazz) ) {
// Skip any key methods, since they are handled separately
if ( keyGetters.contains(method) )
continue;
Object getterResult = safeInvoke(method, object);
String attributeName = reflector.getAttributeName(method);
/*
* If this is a versioned field, update it
*/
if ( reflector.isVersionAttributeGetter(method) ) {
if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) {
// First establish the expected (current) value for the
// update call
ExpectedAttributeValue expected = new ExpectedAttributeValue();
// For new objects, insist that the value doesn't exist.
// For existing ones, insist it has the old value.
AttributeValue currentValue = getSimpleAttributeValue(method, getterResult);
expected.setExists(currentValue != null);
if ( currentValue != null ) {
expected.setValue(currentValue);
}
expectedValues.put(attributeName, expected);
}
AttributeValue newVersionValue = getVersionAttributeValue(method, getterResult);
updateValues
.put(attributeName, new AttributeValueUpdate().withAction("PUT").withValue(newVersionValue));
inMemoryUpdates.add(new ValueUpdate(method, newVersionValue, object));
}
/*
* Otherwise apply the update value for this attribute.
*/
else {
AttributeValue currentValue = getSimpleAttributeValue(method, getterResult);
if ( currentValue != null ) {
updateValues.put(attributeName, new AttributeValueUpdate().withValue(currentValue)
.withAction("PUT"));
} else if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) {
updateValues.put(attributeName, new AttributeValueUpdate().withAction("DELETE"));
}
}
}
/*
* Do a put or an update, according to the configuration. For a put (not
* the default), we need to munge the data type.
*/
if ( config.getSaveBehavior() == SaveBehavior.CLOBBER || forcePut ) {
db.putItem(applyUserAgent(new PutItemRequest().withTableName(tableName)
.withItem(transformAttributes(clazz, convertToItem(updateValues)))
.withExpected(expectedValues)));
} else {
db.updateItem(applyUserAgent(new UpdateItemRequest().withTableName(tableName).withKey(key)
.withAttributeUpdates(transformAttributeUpdates(clazz, key, updateValues)).withExpected(expectedValues)));
}
/*
* Finally, after the service call has succeeded, update the in-memory
* object with new field values as appropriate.
*/
for ( ValueUpdate update : inMemoryUpdates ) {
update.apply();
}
}
/**
* Deletes the given object from its DynamoDB table.
*/
public void delete(Object object) {
delete(object, this.config);
}
/**
* Deletes the given object from its DynamoDB table.
*
* @param config
* Config override object. If {@link SaveBehavior#CLOBBER} is
* supplied, version fields will not be considered when deleting
* the object.
*/
public <T> void delete(T object, DynamoDBMapperConfig config) {
config = mergeConfig(config);
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) object.getClass();
String tableName = getTableName(clazz, config);
Map<String, AttributeValue> key = getKey(object, clazz);
/*
* If there is a version field, make sure we assert its value. If the
* version field is null (only should happen in unusual circumstances),
* pretend it doesn't have a version field after all.
*/
Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>();
if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) {
for ( Method method : reflector.getRelevantGetters(clazz) ) {
if ( reflector.isVersionAttributeGetter(method) ) {
Object getterResult = safeInvoke(method, object);
String attributeName = reflector.getAttributeName(method);
ExpectedAttributeValue expected = new ExpectedAttributeValue();
AttributeValue currentValue = getSimpleAttributeValue(method, getterResult);
expected.setExists(currentValue != null);
if ( currentValue != null )
expected.setValue(currentValue);
expectedValues.put(attributeName, expected);
break;
}
}
}
db.deleteItem(applyUserAgent(new DeleteItemRequest().withKey(key).withTableName(tableName).withExpected(expectedValues)));
}
/**
* Deletes the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @see DynamoDBMapper#batchWrite(List, List, DynamoDBMapperConfig)
*/
public List<FailedBatch> batchDelete(List<? extends Object> objectsToDelete) {
return batchWrite(Collections.emptyList(), objectsToDelete, this.config);
}
/**
* Deletes the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @see DynamoDBMapper#batchWrite(List, List, DynamoDBMapperConfig)
*/
public List<FailedBatch> batchDelete(Object... objectsToDelete) {
return batchWrite(Collections.emptyList(), Arrays.asList(objectsToDelete), this.config);
}
/**
* Saves the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @see DynamoDBMapper#batchWrite(List, List, DynamoDBMapperConfig)
*/
public List<FailedBatch> batchSave(List<? extends Object> objectsToSave) {
return batchWrite(objectsToSave, Collections.emptyList(), this.config);
}
/**
* Saves the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @see DynamoDBMapper#batchWrite(List, List, DynamoDBMapperConfig)
*/
public List<FailedBatch> batchSave(Object... objectsToSave) {
return batchWrite(Arrays.asList(objectsToSave), Collections.emptyList(), this.config);
}
/**
* Saves and deletes the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @see DynamoDBMapper#batchWrite(List, List, DynamoDBMapperConfig)
*/
public List<FailedBatch> batchWrite(List<? extends Object> objectsToWrite, List<? extends Object> objectsToDelete) {
return batchWrite(objectsToWrite, objectsToDelete, this.config);
}
/**
* Saves and deletes the objects given using one or more calls to the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)} API.
*
* @param objectsToWrite
* A list of objects to save to DynamoDB. No version checks are
* performed, as required by the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)}
* API.
* @param objectsToDelete
* A list of objects to delete from DynamoDB. No version checks
* are performed, as required by the
* {@link AmazonDynamoDB#batchWriteItem(BatchWriteItemRequest)}
* API.
* @param config
* Only {@link DynamoDBMapperConfig#getTableNameOverride()} is
* considered; if specified, all objects in the two parameter
* lists will be considered to belong to the given table
* override.
* @return A list of failed batches which includes the unprocessed items and
* the exceptions causing the failure.
*/
public List<FailedBatch> batchWrite(List<? extends Object> objectsToWrite, List<? extends Object> objectsToDelete, DynamoDBMapperConfig config) {
config = mergeConfig(config);
List<FailedBatch> totalFailedBatches = new LinkedList<FailedBatch>();
HashMap<String, List<WriteRequest>> requestItems = new HashMap<String, List<WriteRequest>>();
List<ValueUpdate> inMemoryUpdates = new LinkedList<ValueUpdate>();
for ( Object toWrite : objectsToWrite ) {
Class<?> clazz = toWrite.getClass();
String tableName = getTableName(clazz, config);
Map<String, AttributeValue> attributeValues = new HashMap<String, AttributeValue>();
// Look at every getter and construct a value object for it
for ( Method method : reflector.getRelevantGetters(clazz) ) {
Object getterResult = safeInvoke(method, toWrite);
String attributeName = reflector.getAttributeName(method);
AttributeValue currentValue = null;
if ( getterResult == null && reflector.isAssignableKey(method) ) {
currentValue = getAutoGeneratedKeyAttributeValue(method, getterResult);
inMemoryUpdates.add(new ValueUpdate(method, currentValue, toWrite));
} else {
currentValue = getSimpleAttributeValue(method, getterResult);
}
if ( currentValue != null ) {
attributeValues.put(attributeName, currentValue);
}
}
if ( !requestItems.containsKey(tableName) ) {
requestItems.put(tableName, new LinkedList<WriteRequest>());
}
requestItems.get(tableName).add(
new WriteRequest().withPutRequest(new PutRequest().withItem(transformAttributes(clazz, attributeValues))));
}
for ( Object toDelete : objectsToDelete ) {
Class<?> clazz = toDelete.getClass();
String tableName = getTableName(clazz, config);
Map<String, AttributeValue> key = getKey(toDelete);
if ( !requestItems.containsKey(tableName) ) {
requestItems.put(tableName, new LinkedList<WriteRequest>());
}
requestItems.get(tableName).add(
new WriteRequest().withDeleteRequest(new DeleteRequest().withKey(key)));
}
// Break into chunks of 25 items and make service requests to DynamoDB
while ( !requestItems.isEmpty() ) {
HashMap<String, List<WriteRequest>> batch = new HashMap<String, List<WriteRequest>>();
int i = 0;
Iterator<Entry<String, List<WriteRequest>>> tableIter = requestItems.entrySet().iterator();
while ( tableIter.hasNext() && i < 25 ) {
Entry<String, List<WriteRequest>> tableRequest = tableIter.next();
batch.put(tableRequest.getKey(), new LinkedList<WriteRequest>());
Iterator<WriteRequest> writeRequestIter = tableRequest.getValue().iterator();
while ( writeRequestIter.hasNext() && i++ < 25 ) {
WriteRequest writeRequest = writeRequestIter.next();
batch.get(tableRequest.getKey()).add(writeRequest);
writeRequestIter.remove();
}
// If we've processed all the write requests for this table,
// remove it from the parent iterator.
if ( !writeRequestIter.hasNext() ) {
tableIter.remove();
}
}
List<FailedBatch> failedBatches = writeOneBatch(batch);
if (failedBatches != null) {
totalFailedBatches.addAll(failedBatches);
// If contains throttling exception, we do a backoff
if (containsThrottlingException(failedBatches)) {
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AmazonClientException(e.getMessage(), e);
}
}
}
}
// Once the entire batch is processed, update assigned keys in memory
for ( ValueUpdate update : inMemoryUpdates ) {
update.apply();
}
return totalFailedBatches;
}
/**
* Process one batch of requests(max 25). It will divide the batch if
* receives request too large exception(the total size of the request is beyond 1M).
*/
private List<FailedBatch> writeOneBatch(Map<String, List<WriteRequest>> batch) {
List<FailedBatch> failedBatches = new LinkedList<FailedBatch>();
Map<String, List<WriteRequest>> firstHalfBatch = new HashMap<String, List<WriteRequest>>();
Map<String, List<WriteRequest>> secondHalfBatch = new HashMap<String, List<WriteRequest>>();
FailedBatch failedBatch = callUntilCompletion(batch);
if (failedBatch != null) {
// If the exception is request entity too large, we divide the batch
// into smaller parts.
if (failedBatch.getException() instanceof AmazonServiceException
&& AmazonHttpClient.isRequestEntityTooLargeException((AmazonServiceException) failedBatch.getException())) {
// If only one item left, the item size must beyond 64k, which
// exceedes the limit.
if (computeFailedBatchSize(failedBatch) == 1) {
failedBatches.add(failedBatch);
} else {
divideBatch(batch, firstHalfBatch, secondHalfBatch);
failedBatches.addAll(writeOneBatch(firstHalfBatch));
failedBatches.addAll(writeOneBatch(secondHalfBatch));
}
} else {
failedBatches.add(failedBatch);
}
}
return failedBatches;
}
/**
* Check whether there are throttling exception in the failed batches.
*/
private boolean containsThrottlingException (List<FailedBatch> failedBatches) {
for (FailedBatch failedBatch : failedBatches) {
Exception e = failedBatch.getException();
if (e instanceof AmazonServiceException
&& AmazonHttpClient.isThrottlingException((AmazonServiceException) e)) {
return true;
}
}
return false;
}
/**
* Divide the batch of objects to save into two smaller batches. Each contains half of the elements.
*/
private void divideBatch(Map<String, List<WriteRequest>> batch, Map<String, List<WriteRequest>> firstHalfBatch, Map<String, List<WriteRequest>> secondHalfBatch) {
for (String key : batch.keySet()) {
List<WriteRequest> requests = batch.get(key);
List<WriteRequest> firstHalfRequests = requests.subList(0, requests.size() / 2);
List<WriteRequest> secondHalfRequests = requests.subList(requests.size() / 2, requests.size());
firstHalfBatch.put(key, firstHalfRequests);
secondHalfBatch.put(key, secondHalfRequests);
}
}
/**
* Count the total number of unprocessed items in the failed batch.
*/
private int computeFailedBatchSize(FailedBatch failedBatch) {
int count = 0;
for (String tableName : failedBatch.getUnprocessedItems().keySet()) {
count += failedBatch.getUnprocessedItems().get(tableName).size();
}
return count;
}
/**
* Continue trying to process the batch until it finishes or an exception
* occurs.
*/
private FailedBatch callUntilCompletion(Map<String, List<WriteRequest>> batch) {
BatchWriteItemResult result = null;
int retries = 0;
FailedBatch failedBatch = null;
while (true) {
try {
result = db.batchWriteItem(new BatchWriteItemRequest().withRequestItems(batch));
} catch (Exception e) {
failedBatch = new FailedBatch();
failedBatch.setUnprocessedItems(batch);
failedBatch.setException(e);
return failedBatch;
}
retries++;
batch = result.getUnprocessedItems();
if (batch.size() > 0) {
pauseExponentially(retries);
} else {
break;
}
}
return failedBatch;
}
/**
* Retrieves multiple items from multiple tables using their primary keys.
*
* @see DynamoDBMapper#batchLoad(List, DynamoDBMapperConfig)
*/
public Map<String, List<Object>> batchLoad(List<Object> itemsToGet) {