com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTripUpdateAllJSON() {
    UpdateItem r1 = new UpdateItem();
    Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put(HASH_ATTR_NAME, new AttributeValue("a"));

    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("attr_m", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withM(JSON_M_ATTR_VAL)));
    r1.setRequest(new UpdateItemRequest()
        .withTableName(TABLE_NAME)
        .withKey(key)
        .withAttributeUpdates(updates));
    byte[] r1Bytes = Request.serialize("123", r1).array();
    Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
    byte[] r2Bytes = Request.serialize("123", r2).array();
    assertArrayEquals(r1Bytes, r2Bytes);
}
 
Example #2
Source File: TransactionManagerDBFacadeIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    dynamodb.reset();
    uncommittedFacade = new TransactionManagerDynamoDBFacade(manager, Transaction.IsolationLevel.UNCOMMITTED);
    committedFacade = new TransactionManagerDynamoDBFacade(manager, Transaction.IsolationLevel.COMMITTED);
    key0 = newKey(INTEG_HASH_TABLE_NAME);
    item0 = new HashMap<String, AttributeValue>(key0);
    item0.put("s_someattr", new AttributeValue("val"));
    item0Filtered = new HashMap<String, AttributeValue>(item0);
    item0.put("attr_not_to_get", new AttributeValue("val_not_to_get"));
    attributesToGet = Arrays.asList(ID_ATTRIBUTE, "s_someattr"); // not including attr_not_to_get
    update = Collections.singletonMap(
            "s_someattr",
            new AttributeValueUpdate().withValue(new AttributeValue("val2")));
    item0Updated = new HashMap<String, AttributeValue>(item0);
    item0Updated.put("s_someattr", new AttributeValue("val2"));
}
 
Example #3
Source File: StreamsAdapterDemoHelper.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void updateItem(AmazonDynamoDBClient client, String tableName, String id, String val) {
    java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Id", new AttributeValue().withN(id));

    Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
    AttributeValueUpdate update = new AttributeValueUpdate()
        .withAction(AttributeAction.PUT)
        .withValue(new AttributeValue().withS(val));
    attributeUpdates.put("attribute-2", update);

    UpdateItemRequest updateItemRequest = new UpdateItemRequest()
        .withTableName(tableName)
        .withKey(key)
        .withAttributeUpdates(attributeUpdates);
    client.updateItem(updateItemRequest);
}
 
Example #4
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getThenUpdateNewItem() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("didn't exist"));
    
    Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
    updates1.put("asdf", new AttributeValueUpdate(new AttributeValue("didn't exist"), AttributeAction.PUT));
    
    Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, t1.getId(), true, false);
    assertNull(getResult);
    
    Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)
            .withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertEquals(item1, updateResult);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example #5
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getThenUpdateExistingItem() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> item0a = new HashMap<String, AttributeValue>(item0);
    item0a.put("wef", new AttributeValue("new attr"));
    
    Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
    updates1.put("wef", new AttributeValueUpdate(new AttributeValue("new attr"), AttributeAction.PUT));
    
    Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    assertEquals(item0, getResult);
    
    Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)
            .withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0a, t1.getId(), false, true);
    assertEquals(item0a, updateResult);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0a, true);
}
 
Example #6
Source File: AmazonDynamoDBStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 6 votes vote down vote up
@Test
public void test_updateItem_WithAllParameters() throws Exception {
  createTable();
  putItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);

  String UPDATE_ATTRIBUTE_VALUE = "UpdateAttributeValue1";

  Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
  key.put(TEST_ATTRIBUTE, new AttributeValue()
    .withS(TEST_ATTRIBUTE_VALUE));
  Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
  attributeUpdates.put(TEST_ATTRIBUTE, new AttributeValueUpdate()
    .withAction(AttributeAction.PUT)
    .withValue(new AttributeValue()
      .withS(UPDATE_ATTRIBUTE_VALUE)));
  String returnValues = "";

  UpdateItemResult result = dynamoDb.updateItem(TEST_TABLE_NAME, key, attributeUpdates, returnValues);
  Double units = result.getConsumedCapacity().getCapacityUnits();

  GetItemResult getItemResult = getItem(TEST_ATTRIBUTE, UPDATE_ATTRIBUTE_VALUE);
  String updatedValue = getItemResult.getItem().get(TEST_ATTRIBUTE).getS();

  assertThat(units.doubleValue(), equalTo(1.0));
  assertThat(updatedValue, equalTo(UPDATE_ATTRIBUTE_VALUE));
}
 
Example #7
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void updateItemAllOldInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(result1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example #8
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void updateItemAllOldOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(result1, item0);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example #9
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void updateItemAllNewInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertEquals(result1, item1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example #10
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void updateItemAllNewOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(result1, item1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example #11
Source File: GenericDynamoDB.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Override
public void create(Entry entry) {
    readWriteLock.writeLock().lock();

    try {
        Map<String, AttributeValue> keys = createKey(entry);
        Map<String, AttributeValueUpdate> attributes = createAttributes(entry);
        Map<String, ExpectedAttributeValue> expected = expectNotExists();

        try {
            executeUpdate(keys, attributes, expected);
        } catch (ConditionalCheckFailedException e) {
            throw new AlreadyExistsException("DynamoDB store entry already exists:" + keys.toString());
        }
    } finally {
        readWriteLock.writeLock().unlock();
    }
}
 
Example #12
Source File: GenericDynamoDB.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Override
public void update(Entry entry, Entry existingEntry) {
    readWriteLock.writeLock().lock();

    try {
        Map<String, AttributeValue> keys = createKey(entry);
        Map<String, AttributeValueUpdate> attributes = createAttributes(entry);
        Map<String, ExpectedAttributeValue> expected = expectExists(existingEntry);

        try {
            executeUpdate(keys, attributes, expected);
        } catch (ConditionalCheckFailedException e) {
            throw new DoesNotExistException("Precondition to update entry in DynamoDB failed:" + keys.toString());
        }
    } finally {
        readWriteLock.writeLock().unlock();
    }

}
 
Example #13
Source File: RequestTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTripUpdateAll() {
    UpdateItem r1 = new UpdateItem();
    Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put(HASH_ATTR_NAME, new AttributeValue("a"));

    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("attr_ss", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withSS("a", "b")));
    updates.put("attr_n", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withN("1")));
    updates.put("attr_ns", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withNS("1", "2")));
    updates.put("attr_b", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withB(ByteBuffer.wrap(new String("asdf").getBytes()))));
    updates.put("attr_bs", new AttributeValueUpdate().withAction("PUT").withValue(new AttributeValue().withBS(ByteBuffer.wrap(new String("asdf").getBytes()), ByteBuffer.wrap(new String("asdf").getBytes()))));
    r1.setRequest(new UpdateItemRequest()
        .withTableName(TABLE_NAME)
        .withKey(key)
        .withAttributeUpdates(updates));
    byte[] r1Bytes = Request.serialize("123", r1).array();
    Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
    byte[] r2Bytes = Request.serialize("123", r2).array();
    assertArrayEquals(r1Bytes, r2Bytes);
}
 
Example #14
Source File: GenericDynamoDB.java    From strongbox with Apache License 2.0 6 votes vote down vote up
private Map<String, AttributeValueUpdate> createAttributes(Entry entry) {
    Map<String, AttributeValueUpdate> attributes = new HashMap<>();
    attributes.put(SCHEMA_VERSION_FIELD_NAME, new AttributeValueUpdate()
            .withAction(AttributeAction.PUT)
            .withValue(new AttributeValue().withN(SCHEMA_VERSION)));

    attributes.put(OPTIMISTIC_LOCK_FIELD_NAME, new AttributeValueUpdate()
            .withAction(AttributeAction.PUT)
            .withValue(new AttributeValue().withS(sha(entry))));

    for (Map.Entry<Integer, String> e : attributeMappings.entrySet()) {

        Object value = getValue(entry, e.getValue());
        if (value != null) {
            attributes.put(e.getKey().toString(),
                    new AttributeValueUpdate()
                            .withAction(AttributeAction.PUT)
                            .withValue(getAttribute(value)));
        }
    }
    return attributes;
}
 
Example #15
Source File: TransactionDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public UpdateItemResult updateItem(String tableName,
        Map<String, AttributeValue> key,
        Map<String, AttributeValueUpdate> attributeUpdates,
        String returnValues) throws AmazonServiceException,
        AmazonClientException {
    return updateItem(new UpdateItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withAttributeUpdates(attributeUpdates)
            .withReturnValues(returnValues));
}
 
Example #16
Source File: GeoDynamoDBServlet.java    From dynamodb-geo with Apache License 2.0 5 votes vote down vote up
private void updatePoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
	GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
	AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(requestObject.getString("rangeKey"));

	String schoolName = requestObject.getString("schoolName");
	AttributeValueUpdate schoolNameValueUpdate = null;

	String memo = requestObject.getString("memo");
	AttributeValueUpdate memoValueUpdate = null;

	if (schoolName == null || schoolName.equalsIgnoreCase("")) {
		schoolNameValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.DELETE);
	} else {
		AttributeValue schoolNameAttributeValue = new AttributeValue().withS(schoolName);
		schoolNameValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(
				schoolNameAttributeValue);
	}

	if (memo == null || memo.equalsIgnoreCase("")) {
		memoValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.DELETE);
	} else {
		AttributeValue memoAttributeValue = new AttributeValue().withS(memo);
		memoValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(memoAttributeValue);
	}

	UpdatePointRequest updatePointRequest = new UpdatePointRequest(geoPoint, rangeKeyAttributeValue);
	updatePointRequest.getUpdateItemRequest().addAttributeUpdatesEntry("schoolName", schoolNameValueUpdate);
	updatePointRequest.getUpdateItemRequest().addAttributeUpdatesEntry("memo", memoValueUpdate);

	UpdatePointResult updatePointResult = geoDataManager.updatePoint(updatePointRequest);

	printUpdatePointResult(updatePointResult, out);
}
 
Example #17
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Test
public void getItemCommittedUpdated() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("asdf")));
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("asdf"));
    
    t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withAttributeUpdates(updates)
        .withKey(key0));
    
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    
    Map<String, AttributeValue> item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0), IsolationLevel.COMMITTED).getItem();
    assertNoSpecialAttributes(item);
    assertEquals(item0, item);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    
    t1.commit();
    
    item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0), IsolationLevel.COMMITTED).getItem();
    assertNoSpecialAttributes(item);
    assertEquals(item1, item);
}
 
Example #18
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Test
public void getItemCommittedUpdatedAndApplied() {
    Transaction t1 = new Transaction(UUID.randomUUID().toString(), manager, true) {
        @Override
        protected void doCommit() {
            //Skip cleaning up the transaction so we can validate reading.
        }
    };

    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("asdf")));
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("asdf"));

    t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withAttributeUpdates(updates)
        .withKey(key0));

    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);

    t1.commit();

    Map<String, AttributeValue> item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0), IsolationLevel.COMMITTED).getItem();
    assertNoSpecialAttributes(item);
    assertEquals(item1, item);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
}
 
Example #19
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Test
public void getItemCommittedMissingImage() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("asdf")));
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("asdf"));

    t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withAttributeUpdates(updates)
        .withKey(key0));

    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    
    dynamodb.getRequestsToTreatAsDeleted.add(new GetItemRequest()
        .withTableName(manager.getItemImageTableName())
        .addKeyEntry(AttributeName.IMAGE_ID.toString(), new AttributeValue(t1.getTxItem().txId + "#" + 1))
        .withConsistentRead(true));
    
    try {
        manager.getItem(new GetItemRequest()
            .withTableName(INTEG_HASH_TABLE_NAME)
            .withKey(key0), IsolationLevel.COMMITTED).getItem();
        fail("Should have thrown an exception.");
    } catch (TransactionException e) {
        assertEquals("null - Ran out of attempts to get a committed image of the item", e.getMessage());
    }
}
 
Example #20
Source File: TransactionManagerDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public UpdateItemResult updateItem(String tableName,
        Map<String, AttributeValue> key,
        Map<String, AttributeValueUpdate> attributeUpdates,
        String returnValues) throws AmazonServiceException,
        AmazonClientException {
    throw new UnsupportedOperationException("Use the underlying client instance instead");
}
 
Example #21
Source File: TransactionDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public UpdateItemResult updateItem(String tableName,
        Map<String, AttributeValue> key,
        Map<String, AttributeValueUpdate> attributeUpdates)
        throws AmazonServiceException, AmazonClientException {
    return updateItem(new UpdateItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withAttributeUpdates(attributeUpdates));
}
 
Example #22
Source File: TransactionItem.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
/**
 * Completes a transaction by marking its "Finalized" attribute.  This leaves the completed transaction item around
 * so that the party who created the transaction can see whether it was completed or rolled back.  They can then either 
 * delete the transaction record when they're done, or they can run a sweeper process to go and delete the completed transactions
 * later on. 
 * 
 * @param expectedCurrentState
 * @throws ConditionalCheckFailedException if the transaction is completed, doesn't exist anymore, or even if it isn't committed or rolled back  
 */
public void complete(final State expectedCurrentState) throws ConditionalCheckFailedException {
    Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(2);
    
    if(State.COMMITTED.equals(expectedCurrentState)) {
        expected.put(AttributeName.STATE.toString(), new ExpectedAttributeValue(new AttributeValue(STATE_COMMITTED)));
    } else if(State.ROLLED_BACK.equals(expectedCurrentState)) {
        expected.put(AttributeName.STATE.toString(), new ExpectedAttributeValue(new AttributeValue(STATE_ROLLED_BACK)));
    } else {
        throw new TransactionAssertionException(txId, "Illegal state in finish(): " + expectedCurrentState + " txItem " + txItem);
    }
    
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put(AttributeName.FINALIZED.toString(), new AttributeValueUpdate()
        .withAction(AttributeAction.PUT)
        .withValue(new AttributeValue(Transaction.BOOLEAN_TRUE_ATTR_VAL)));
    updates.put(AttributeName.DATE.toString(), new AttributeValueUpdate()
        .withAction(AttributeAction.PUT)
        .withValue(txManager.getCurrentTimeAttribute()));
    
    UpdateItemRequest completeRequest = new UpdateItemRequest()
        .withTableName(txManager.getTransactionTableName())
        .withKey(txKey)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)
        .withExpected(expected);
    
    txItem = txManager.getClient().updateItem(completeRequest).getAttributes();
}
 
Example #23
Source File: TransactionItem.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
/**
 * Marks the transaction item as either COMMITTED or ROLLED_BACK, but only if it was in the PENDING state.
 * It will also condition on the expected version. 
 * 
 * @param targetState
 * @param expectedVersion 
 * @throws ConditionalCheckFailedException if the transaction doesn't exist, isn't PENDING, is finalized, 
 *         or the expected version doesn't match (if specified)  
 */
public void finish(final State targetState, final int expectedVersion) throws ConditionalCheckFailedException {
    txAssert(State.COMMITTED.equals(targetState) || State.ROLLED_BACK.equals(targetState),"Illegal state in finish(): " + targetState, "txItem", txItem);
    Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>(2);
    expected.put(AttributeName.STATE.toString(), new ExpectedAttributeValue().withValue(new AttributeValue().withS(STATE_PENDING)));
    expected.put(AttributeName.FINALIZED.toString(), new ExpectedAttributeValue().withExists(false));
    expected.put(AttributeName.VERSION.toString(), new ExpectedAttributeValue().withValue(new AttributeValue().withN(Integer.toString(expectedVersion))));
    
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put(AttributeName.STATE.toString(), new AttributeValueUpdate()
        .withAction(AttributeAction.PUT)
        .withValue(new AttributeValue(stateToString(targetState))));
    updates.put(AttributeName.DATE.toString(), new AttributeValueUpdate()
        .withAction(AttributeAction.PUT)
        .withValue(txManager.getCurrentTimeAttribute()));
    
    UpdateItemRequest finishRequest = new UpdateItemRequest()
        .withTableName(txManager.getTransactionTableName())
        .withKey(txKey)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)
        .withExpected(expected);
    
    UpdateItemResult finishResult = txManager.getClient().updateItem(finishRequest);
    txItem = finishResult.getAttributes();
    if(txItem == null) {
        throw new TransactionAssertionException(txId, "Unexpected null tx item after committing " + targetState);
    }
}
 
Example #24
Source File: TransactionExamples.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
/**
 * This example shows that reads can be performed in a transaction, and read locks can be upgraded to write locks. 
 */
public void readThenWrite() {
    print("\n*** readThenWrite() ***\n");
    
    Transaction t1 = txManager.newTransaction();
    
    // Perform a GetItem request on the transaction
    print("Reading Item1");
    Map<String, AttributeValue> key1 = new HashMap<String, AttributeValue>();
    key1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1"));
    
    Map<String, AttributeValue> item1 = t1.getItem(new GetItemRequest()
        .withKey(key1)
        .withTableName(EXAMPLE_TABLE_NAME)).getItem();
    print("Item1: " + item1);
    
    // Now call UpdateItem to add a new attribute.
    // Notice that the library supports ReturnValues in writes
    print("Updating Item1");
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("Color", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("Green")));
    
    item1 = t1.updateItem(new UpdateItemRequest()
        .withKey(key1)
        .withTableName(EXAMPLE_TABLE_NAME)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    print("Item1 is now: " + item1);
    
    t1.commit();
    
    t1.delete();
}
 
Example #25
Source File: Transaction.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
/**
 * Releases the lock for the item.  If the item was inserted only to acquire the lock (if the item didn't exist before 
 * for a DeleteItem or LockItem), it will be deleted now.
 * 
 * Otherwise, all of the attributes uses for the transaction (tx id, transient flag, applied flag) will be removed.
 * 
 * Conditions on our transaction id owning the item
 * 
 * To be used once the transaction has committed only.
 * @param request
 */
protected void unlockItemAfterCommit(Request request) {
    try {
        Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>();
        expected.put(AttributeName.TXID.toString(), new ExpectedAttributeValue().withValue(new AttributeValue(txId)));
        
        if(request instanceof PutItem || request instanceof UpdateItem) {
            Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
            updates.put(AttributeName.TXID.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
            updates.put(AttributeName.TRANSIENT.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
            updates.put(AttributeName.APPLIED.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
            updates.put(AttributeName.DATE.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
            
            UpdateItemRequest update = new UpdateItemRequest()
                .withTableName(request.getTableName())
                .withKey(request.getKey(txManager))
                .withAttributeUpdates(updates)
                .withExpected(expected);
            txManager.getClient().updateItem(update);
        } else if(request instanceof DeleteItem) {
            DeleteItemRequest delete = new DeleteItemRequest()
                .withTableName(request.getTableName())
                .withKey(request.getKey(txManager))
                .withExpected(expected);
            txManager.getClient().deleteItem(delete);
        } else if(request instanceof GetItem) {
            releaseReadLock(request.getTableName(), request.getKey(txManager));
        } else {
            throw new TransactionAssertionException(txId, "Unknown request type: " + request.getClass());
        }
    } catch (ConditionalCheckFailedException e) {
        // ignore, unlock already happened
        // TODO if we really want to be paranoid we could condition on applied = 1, and then here
        //      we would have to read the item again and make sure that applied was 1 if we owned the lock (and assert otherwise) 
    }
}
 
Example #26
Source File: Transaction.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
protected static void releaseReadLock(String txId, TransactionManager txManager, String tableName, Map<String, AttributeValue> key) {
    Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>();
    expected.put(AttributeName.TXID.toString(), new ExpectedAttributeValue().withValue(new AttributeValue(txId)));
    expected.put(AttributeName.TRANSIENT.toString(), new ExpectedAttributeValue().withExists(false));
    expected.put(AttributeName.APPLIED.toString(), new ExpectedAttributeValue().withExists(false));
    
    try {
        Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(1);
        updates.put(AttributeName.TXID.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
        updates.put(AttributeName.DATE.toString(), new AttributeValueUpdate().withAction(AttributeAction.DELETE));
        
        UpdateItemRequest update = new UpdateItemRequest()
            .withTableName(tableName)
            .withAttributeUpdates(updates)
            .withKey(key)
            .withExpected(expected);
        txManager.getClient().updateItem(update);
    } catch (ConditionalCheckFailedException e) {
        try {
            expected.put(AttributeName.TRANSIENT.toString(), new ExpectedAttributeValue().withValue(new AttributeValue().withS(BOOLEAN_TRUE_ATTR_VAL)));
            
            DeleteItemRequest delete = new DeleteItemRequest()
                .withTableName(tableName)
                .withKey(key)
                .withExpected(expected);
            txManager.getClient().deleteItem(delete);    
        } catch (ConditionalCheckFailedException e1) {
            // Ignore, means it was definitely rolled back
            // Re-read to ensure that it wasn't applied
            Map<String, AttributeValue> item = getItem(txManager, tableName, key);
            txAssert(! (item != null && txId.equals(getOwner(item)) && item.containsKey(AttributeName.APPLIED.toString())), 
                "Item should not have been applied.  Unable to release lock", "item", item);
        }
    }
}
 
Example #27
Source File: TransactionManagerDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public UpdateItemResult updateItem(String tableName,
        Map<String, AttributeValue> key,
        Map<String, AttributeValueUpdate> attributeUpdates)
        throws AmazonServiceException, AmazonClientException {
    throw new UnsupportedOperationException("Use the underlying client instance instead");
}
 
Example #28
Source File: SingleUpdateBuilder.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 5 votes vote down vote up
public SingleUpdateBuilder put(final StaticBuffer column, final StaticBuffer value) {
    updates.put(encodeKeyBuffer(column),
            new AttributeValueUpdate()
                    .withAction(AttributeAction.PUT)
                    .withValue(encodeValue(value)));
    return this;
}
 
Example #29
Source File: DyNum.java    From jpeek with MIT License 5 votes vote down vote up
/**
 * Make an update.
 * @param action The action
 * @return The update
 */
public AttributeValueUpdate update(final AttributeAction action) {
    return new AttributeValueUpdate()
        .withAction(action)
        .withValue(
            new AttributeValue().withN(
                Long.toString(this.longValue())
            )
        );
}
 
Example #30
Source File: DynamoDBHelper.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
/**
 * Update item into FragmentCheckpoint table for the given input parameters
 *
 * @param streamName KVS Stream name
 * @param fragmentNumber Last processed fragment's fragment number
 * @param producerTime Last processed fragment's producer time
 * @param serverTime Last processed fragment's server time
 * @param updatedTime Time when the entry is going to be updated.
 */
public void updateItem(final String streamName, final String fragmentNumber,
                        final Long producerTime, final Long serverTime, final Long updatedTime) {
    try {
        final Map<String,AttributeValue> key = new HashMap<>();
        key.put(KVS_STREAM_NAME, new AttributeValue().withS(streamName));
        final Map<String,AttributeValueUpdate> updates = new HashMap<>();
        updates.put(FRAGMENT_NUMBER, new AttributeValueUpdate().withValue(
                new AttributeValue().withS(fragmentNumber)));
        updates.put(UPDATED_TIME, new AttributeValueUpdate().withValue(
                new AttributeValue().withN(updatedTime.toString())));
        updates.put(PRODUCER_TIME, new AttributeValueUpdate().withValue(
                new AttributeValue().withN(producerTime.toString())));
        updates.put(SERVER_TIME, new AttributeValueUpdate().withValue(
                new AttributeValue().withN(serverTime.toString())));
        final UpdateItemRequest updateItemRequest = new UpdateItemRequest()
        {{
            setTableName(TABLE_NAME);
            setKey(key);
            setAttributeUpdates(updates);
        }};

        final UpdateItemResult result = ddbClient.updateItem(updateItemRequest);
        log.info("Item updated : {}", result.getAttributes());
    } catch (final Exception e) {
        log.warn("Error while updating item in the table!", e);
    }
}