Map<String, ExpectedAttributeValue> expected = request.getExpected();
Map<String, AttributeValueUpdate> attributesToUpdate = request.getAttributeUpdates();
String returnValues = request.getReturnValues();
UpdateItemResult result = new UpdateItemResult();
result.setConsumedCapacityUnits(0.5);
// Check to make sure table exists
if (!this.tables.containsKey(tableName)) {
throw new ResourceNotFoundException("The table you're currently trying to access (" + tableName + ") doesn't exists.");
}
// Check to make sure Key is valid
String hashKeyValue = getKeyValue(key.getHashKeyElement());
String rangeKeyValue = getKeyValue(key.getRangeKeyElement());
Map<String, AttributeValue> item = this.tables.get(tableName).getItem(hashKeyValue, rangeKeyValue);
// Check conditional put
validateExpected(request.getExpected(), item);
if (item == null) {
item = new HashMap<String, AttributeValue>();
item.put(this.tables.get(tableName).getHashKeyName(), key.getHashKeyElement());
if (key.getRangeKeyElement() != null) {
item.put(this.tables.get(tableName).getRangeKeyName(), key.getRangeKeyElement());
}
for (String sKey : attributesToUpdate.keySet()) {
if (attributesToUpdate.get(sKey).getValue() != null) {
item.put(sKey, attributesToUpdate.get(sKey).getValue());
}
}
this.tables.get(tableName).putItem(item);
result.setAttributes(item);
} else {
Set<String> sKeyz = new HashSet<String>(item.keySet());
sKeyz.addAll(attributesToUpdate.keySet());
for (String sKey : sKeyz) {
if (attributesToUpdate.containsKey(sKey)) {
if (attributesToUpdate.get(sKey).getAction().equalsIgnoreCase(AttributeAction.PUT.name())) {
item.remove(sKey);
item.put(sKey, attributesToUpdate.get(sKey).getValue());
attributesToUpdate.remove(sKey);
} else if (attributesToUpdate.get(sKey).getAction().equalsIgnoreCase(AttributeAction.DELETE.name())) {
if (attributesToUpdate.get(sKey).getValue() != null) {
deleteAttributeValue(item, sKey, attributesToUpdate.get(sKey));
} else {
item.remove(sKey);
}
attributesToUpdate.remove(sKey);
} else if (attributesToUpdate.get(sKey).getAction().equalsIgnoreCase(AttributeAction.ADD.name())) {
if (attributesToUpdate.get(sKey).getValue() != null) {
addAttributeValue(item, sKey, attributesToUpdate.get(sKey));
} else {
throw new ResourceNotFoundException("the provided update item with attribute (" + sKey + ") doesn't have an AttributeValue to perform the ADD");
}
}
}
}
result.setAttributes(item);
}
return result;
}