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

The following examples show how to use com.amazonaws.services.dynamodbv2.model.GetItemResult. 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: DynamoDBWorkerUtilsTest.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStoredETagExists() {
    AmazonDynamoDB dynamoDB = PowerMock.createMock(AmazonDynamoDB.class);
    Map<String, AttributeValue> resourceKey = new HashMap<String, AttributeValue>();
    resourceKey.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    // Get item
    dynamoDB.getItem(table, resourceKey);
    Map<String, AttributeValue> resourceResult = new HashMap<String, AttributeValue>();
    resourceResult.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    resourceResult.put(DynamoDBWorkerUtils.ETAG_KEY, new AttributeValue(eTag));
    GetItemResult result = new GetItemResult().withItem(resourceResult);
    PowerMock.expectLastCall().andReturn(result);
    PowerMock.replayAll();
    String resultETag = DynamoDBWorkerUtils.getStoredETag(dynamoDB, table, resource);
    assertEquals(eTag, resultETag);
    PowerMock.verifyAll();
}
 
Example #2
Source File: ReadCommittedIsolationHandlerImplUnitTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void handleItemRetriesWhenUnknownCompletedTransaction() {
    doReturn(mockTx).when(isolationHandler).loadTransaction(TX_ID);
    doThrow(UnknownCompletedTransactionException.class).when(isolationHandler).getOldCommittedItem(mockTx, TABLE_NAME, KEY);
    when(mockTxManager.createKeyMap(TABLE_NAME, NON_TRANSIENT_APPLIED_ITEM)).thenReturn(KEY);
    when(mockClient.getItem(GET_ITEM_REQUEST)).thenReturn(new GetItemResult().withItem(NON_TRANSIENT_APPLIED_ITEM));
    boolean caughtException = false;
    try {
        isolationHandler.handleItem(NON_TRANSIENT_APPLIED_ITEM, TABLE_NAME, 1);
    } catch (TransactionException e) {
        caughtException = true;
    }
    assertTrue(caughtException);
    verify(isolationHandler, times(2)).loadTransaction(TX_ID);
    verify(isolationHandler).createGetItemRequest(TABLE_NAME, NON_TRANSIENT_APPLIED_ITEM);
    verify(mockClient).getItem(GET_ITEM_REQUEST);
}
 
Example #3
Source File: ReadCommittedIsolationHandlerImplUnitTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void handleItemRetriesWhenTransactionNotFound() {
    doThrow(TransactionNotFoundException.class).when(isolationHandler).loadTransaction(TX_ID);
    when(mockTxManager.createKeyMap(TABLE_NAME, NON_TRANSIENT_APPLIED_ITEM)).thenReturn(KEY);
    when(mockClient.getItem(GET_ITEM_REQUEST)).thenReturn(new GetItemResult().withItem(NON_TRANSIENT_APPLIED_ITEM));
    boolean caughtException = false;
    try {
        isolationHandler.handleItem(NON_TRANSIENT_APPLIED_ITEM, TABLE_NAME, 1);
    } catch (TransactionException e) {
        caughtException = true;
    }
    assertTrue(caughtException);
    verify(isolationHandler, times(2)).loadTransaction(TX_ID);
    verify(isolationHandler).createGetItemRequest(TABLE_NAME, NON_TRANSIENT_APPLIED_ITEM);
    verify(mockClient).getItem(GET_ITEM_REQUEST);
}
 
Example #4
Source File: DynamoDBManager.java    From dynamodb-geo with Apache License 2.0 6 votes vote down vote up
public GetPointResult getPoint(GetPointRequest getPointRequest) {
	long geohash = S2Manager.generateGeohash(getPointRequest.getGeoPoint());
	long hashKey = S2Manager.generateHashKey(geohash, config.getHashKeyLength());

	GetItemRequest getItemRequest = getPointRequest.getGetItemRequest();
	getItemRequest.setTableName(config.getTableName());

	AttributeValue hashKeyValue = new AttributeValue().withN(String.valueOf(hashKey));
	getItemRequest.getKey().put(config.getHashKeyAttributeName(), hashKeyValue);
	getItemRequest.getKey().put(config.getRangeKeyAttributeName(), getPointRequest.getRangeKeyValue());

	GetItemResult getItemResult = config.getDynamoDBClient().getItem(getItemRequest);
	GetPointResult getPointResult = new GetPointResult(getItemResult);

	return getPointResult;
}
 
Example #5
Source File: LowLevelItemBinaryExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void retrieveItem(String threadId, String replyDateTime) throws IOException {
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Id", new AttributeValue().withS(threadId));
    key.put("ReplyDateTime", new AttributeValue().withS(replyDateTime));
    
    GetItemRequest getReplyRequest = new GetItemRequest()
        .withTableName(tableName)
        .withKey(key)
        .withConsistentRead(true);
    
    GetItemResult getReplyResult = client.getItem(getReplyRequest);
    
    // Decompress the reply message and print
    Map<String, AttributeValue> reply = getReplyResult.getItem();
    String message = decompressString(reply.get("ExtendedMessage").getB());
    System.out.println("Reply message:\n"
        + " Id: " + reply.get("Id").getS() + "\n" 
        + " ReplyDateTime: " + reply.get("ReplyDateTime").getS() + "\n" 
        + " PostedBy: " + reply.get("PostedBy").getS() + "\n"
        + " Message: " + reply.get("Message").getS() + "\n"
        + " ExtendedMessage (decompressed): " + message);
}
 
Example #6
Source File: LowLevelItemCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void retrieveItem() {
    try {
        
        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("120"));
        GetItemRequest getItemRequest = new GetItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withProjectionExpression("Id, ISBN, Title, Authors");
        
        GetItemResult result = client.getItem(getItemRequest);

        // Check the response.
        System.out.println("Printing item after retrieving it....");
        printItem(result.getItem());            
                    
    }  catch (AmazonServiceException ase) {
                System.err.println("Failed to retrieve item in " + tableName);
    }   

}
 
Example #7
Source File: DynamoDBWorkerUtils.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the stored ETag, if one exists, from DynamoDB.
 *
 * @param dynamoDB
 *            DynamoDB client configured with a region and credentials
 * @param table
 *            The resource table name
 * @param resource
 *            The URL String of the resource
 * @return The ETag String of the last copy processed or null if the resource has never been processed
 */
public static String getStoredETag(final AmazonDynamoDB dynamoDB, final String table, final String resource) {
    String oldETag;
    // Build key to retrieve item
    final Map<String, AttributeValue> resourceKey = new HashMap<String, AttributeValue>();
    resourceKey.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    // Get item
    final GetItemResult result = dynamoDB.getItem(table, resourceKey);
    final Map<String, AttributeValue> item = result.getItem();
    if (item != null && item.containsKey(ETAG_KEY)) {
        // Item was found and contains ETag
        oldETag = item.get(ETAG_KEY).getS();
    } else {
        // Item was not found or did not contain ETag
        oldETag = null;
    }
    return oldETag;
}
 
Example #8
Source File: DynamoDbTemplateIntegrationTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteItem_withItemWithCompoundPk() throws Exception {
    // Given
    final StubWithRangeItem createdItem = dataGenerator.createStubWithRangeItem();
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder);
    dynamoDbTemplate.initialize(amazonDynamoDbClient);

    // When
    dynamoDbTemplate.delete(createdItem);

    // Then
    final Map<String, AttributeValue> key = new HashMap<>();
    key.put("id", new AttributeValue(createdItem.getId()));
    key.put("supportingId", new AttributeValue(createdItem.getSupportingId()));
    final GetItemResult result = amazonDynamoDbClient.getItem(
            dataGenerator.getUnitTestSchemaName() + "." + dataGenerator.getStubItemWithRangeTableName(), key);
    assertNull(result.getItem());
}
 
Example #9
Source File: DynamoDbTemplateIntegrationTest.java    From Cheddar with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteItem_withItem() throws Exception {
    // Given
    final StubItem createdItem = dataGenerator.createStubItem();
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder);
    dynamoDbTemplate.initialize(amazonDynamoDbClient);

    // When
    dynamoDbTemplate.delete(createdItem);

    // Then
    final Map<String, AttributeValue> key = new HashMap<>();
    key.put("id", new AttributeValue(createdItem.getId()));
    final GetItemResult result = amazonDynamoDbClient
            .getItem(dataGenerator.getUnitTestSchemaName() + "." + dataGenerator.getStubItemTableName(), key);
    assertNull(result.getItem());
}
 
Example #10
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 #11
Source File: AmazonDynamoDBStubTest.java    From aws-java-sdk-stubs with Apache License 2.0 6 votes vote down vote up
@Test
public void test_deleteItem_WithAllParameters() throws Exception {
  createTable();
  putItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);

  Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
  key.put(TEST_ATTRIBUTE, new AttributeValue()
    .withS(TEST_ATTRIBUTE_VALUE));
  String returnValues = "";

  DeleteItemResult deleteResult = dynamoDb.deleteItem(TEST_TABLE_NAME, key, returnValues);
  AttributeValue attributeValue = deleteResult.getAttributes().get(TEST_ATTRIBUTE);

  GetItemResult getResult = getItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);

  assertThat(attributeValue.getS(), equalTo(TEST_ATTRIBUTE_VALUE));
  assertThat(getResult, nullValue());
}
 
Example #12
Source File: SimpleNumericAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void performanceTest() throws Exception {
    NumberAttributeTestClass obj = getUniqueObject();
    DynamoDBMapper mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
    mapper.save(obj);
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put(KEY_NAME, new AttributeValue().withS(obj.getKey()));
    GetItemResult item = dynamo.getItem(new GetItemRequest()
            .withTableName("aws-java-sdk-util-crypto").withKey(key));
    
    long start = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        mapper.marshallIntoObject(NumberAttributeTestClass.class, item.getItem());
    }        
    
    long end = System.currentTimeMillis();
    
    System.err.println("time: " + (end - start));
}
 
Example #13
Source File: LowLevelItemBinaryExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void retrieveItem(String threadId, String replyDateTime) throws IOException {
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Id", new AttributeValue().withS(threadId));
    key.put("ReplyDateTime", new AttributeValue().withS(replyDateTime));

    GetItemRequest getReplyRequest = new GetItemRequest().withTableName(tableName).withKey(key)
        .withConsistentRead(true);

    GetItemResult getReplyResult = client.getItem(getReplyRequest);

    // Decompress the reply message and print
    Map<String, AttributeValue> reply = getReplyResult.getItem();
    String message = decompressString(reply.get("ExtendedMessage").getB());
    System.out.println("Reply message:\n" + " Id: " + reply.get("Id").getS() + "\n" + " ReplyDateTime: "
        + reply.get("ReplyDateTime").getS() + "\n" + " PostedBy: " + reply.get("PostedBy").getS() + "\n"
        + " Message: " + reply.get("Message").getS() + "\n" + " ExtendedMessage (decompressed): " + message);
}
 
Example #14
Source File: LowLevelItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void retrieveItem() {
    try {

        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("120"));
        GetItemRequest getItemRequest = new GetItemRequest().withTableName(tableName).withKey(key)
            .withProjectionExpression("Id, ISBN, Title, Authors");

        GetItemResult result = client.getItem(getItemRequest);

        // Check the response.
        System.out.println("Printing item after retrieving it....");
        printItem(result.getItem());

    }
    catch (AmazonServiceException ase) {
        System.err.println("Failed to retrieve item in " + tableName);
    }

}
 
Example #15
Source File: DynamoDbFunctionalTest.java    From pocket-etl with Apache License 2.0 5 votes vote down vote up
private GetItemResult getThingFromDdb(String key) {
    final HashMap<String, AttributeValue> requestItems = new HashMap<>();
    requestItems.put("pk", new AttributeValue(key));
    final GetItemRequest getItemRequest = new GetItemRequest();
    getItemRequest.withTableName(tableName).withKey(requestItems);
    return ddb.getItem(getItemRequest);
}
 
Example #16
Source File: DynamoDBServiceImpl2.java    From Serverless-Programming-Cookbook with MIT License 5 votes vote down vote up
@Override
public final Response getItem(final Request request) {

    final HashMap<String, AttributeValue> primaryKey = new HashMap<>();
    primaryKey.put(request.getPartitionKey(), new AttributeValue(request.getPartitionKeyValue()));
    primaryKey.put(request.getSortKey(), new AttributeValue().withN(request.getSortKeyValue()));

    final GetItemResult getItemResult = dynamoDBClient.getItem(new GetItemRequest()
            .withTableName(request.getTableName())
            .withKey(primaryKey));

    return new Response("PK of Item read using get-item (V2): "
            + prepareKeyStr(getItemResult.getItem(), request), null);
}
 
Example #17
Source File: TransactionDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public GetItemResult getItem(String tableName,
        Map<String, AttributeValue> key, Boolean consistentRead)
        throws AmazonServiceException, AmazonClientException {
    return getItem(new GetItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withConsistentRead(consistentRead));
}
 
Example #18
Source File: TransactionDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public GetItemResult getItem(String tableName,
        Map<String, AttributeValue> key) throws AmazonServiceException,
        AmazonClientException {
    return getItem(new GetItemRequest()
            .withTableName(tableName)
            .withKey(key));
}
 
Example #19
Source File: TransactionDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
private void checkExpectedValues(String tableName,
        Map<String, AttributeValue> itemKey,
        Map<String, ExpectedAttributeValue> expectedValues) {
    if (expectedValues != null && !expectedValues.isEmpty()) {
        for (Map.Entry<String, ExpectedAttributeValue> entry : expectedValues.entrySet()) {
            if ((entry.getValue().isExists() == null || entry.getValue().isExists() == true)
                    && entry.getValue().getValue() == null) {
                throw new IllegalArgumentException("An explicit value is required when Exists is null or true, "
                        + "but none was found in expected values for item with key " + itemKey +
                        ": " + expectedValues);
            }
        }

        // simulate by loading the item and checking the values;
        // this also has the effect of locking the item, which gives the
        // same behavior
        GetItemResult result = getItem(new GetItemRequest()
                .withAttributesToGet(expectedValues.keySet())
                .withKey(itemKey)
                .withTableName(tableName));
        Map<String, AttributeValue> item = result.getItem();
        try {
            checkExpectedValues(expectedValues, item);
        } catch (ConditionalCheckFailedException e) {
            throw new ConditionalCheckFailedException("Item " + itemKey + " had unexpected attributes: " + e.getMessage());
        }
    }
}
 
Example #20
Source File: TransactionManager.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
public GetItemResult getItem(GetItemRequest request, IsolationLevel isolationLevel) {
    if (request.getAttributesToGet() != null) {
        Set<String> attributesToGet = new HashSet<String>(request.getAttributesToGet());
        attributesToGet.addAll(Transaction.SPECIAL_ATTR_NAMES);
        request.setAttributesToGet(attributesToGet);
    }
    GetItemResult result = getClient().getItem(request);
    Map<String, AttributeValue> item = getReadIsolationHandler(isolationLevel).handleItem(result.getItem(), request.getAttributesToGet(), request.getTableName());
    Transaction.stripSpecialAttributes(item);
    result.setItem(item);
    return result;
}
 
Example #21
Source File: FaultInjectionRequestHandler.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void afterResponse(Request<?> request, Response<?> response) {
    /*
     * The following is a hit and miss for multi-threaded clients as the
     * cache size is only 50 entries
     */
    String awsRequestId = dynamoDBClient.getCachedResponseMetadata(request.getOriginalRequest()).getRequestId();
    logger.info("AWS RequestID: " + awsRequestId);

    /*
     * Here you could inspect and alter the response object to see how your
     * application behaves for specific data
     */
    if (request.getOriginalRequest() instanceof GetItemRequest) {
        GetItemResult result = (GetItemResult) response.getAwsResponse();

        Map<String, AttributeValue> item = result.getItem();

        if (item.get("name").getS().equals("Airplane")) {

            // Alter the item
            item.put("name", new AttributeValue("newAirplane"));
            item.put("new attr", new AttributeValue("new attr"));

            // Add some delay
            try {
                Thread.sleep(500);
            }
            catch (InterruptedException ie) {
                logger.info(ie);
                throw new RuntimeException(ie);
            }
        }
    }
}
 
Example #22
Source File: TransactionManagerDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public GetItemResult getItem(String tableName,
        Map<String, AttributeValue> key, Boolean consistentRead)
        throws AmazonServiceException, AmazonClientException {
    return getItem(new GetItemRequest()
            .withTableName(tableName)
            .withKey(key)
            .withConsistentRead(consistentRead));
}
 
Example #23
Source File: TransactionManagerDynamoDBFacade.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public GetItemResult getItem(
        String tableName,
        Map<String, AttributeValue> key) throws AmazonServiceException, AmazonClientException {
    return getItem(new GetItemRequest()
            .withTableName(tableName)
            .withKey(key));
}
 
Example #24
Source File: Transaction.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
protected static Map<String, AttributeValue> getItem(TransactionManager txManager, String tableName, Map<String, AttributeValue> key) {
    GetItemRequest getRequest = new GetItemRequest()
        .withTableName(tableName)
        .withConsistentRead(true)
        .withKey(key);
    GetItemResult getResult = txManager.getClient().getItem(getRequest);
    return getResult.getItem();
}
 
Example #25
Source File: Transaction.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
/**
 * Locks an item for the duration of the transaction, unless it is already locked. Useful for isolated reads.  
 * Returns the copy of the item as it exists so far in the transaction (if reading after a write in the same transaction)
 * 
 * @param request
 * @throws DuplicateRequestException if the item in the request is already involved in this transaction
 * @throws ItemNotLockedException when another transaction is confirmed to have the lock on the item in the request
 * @throws TransactionCompletedException when the transaction has already completed
 * @throws TransactionNotFoundException if the transaction does not exist
 * @throws TransactionException on unexpected errors or unresolvable OCC contention
 */
public GetItemResult getItem(GetItemRequest request)
    throws DuplicateRequestException, ItemNotLockedException, 
        TransactionCompletedException, TransactionNotFoundException, TransactionException {
    
    GetItem wrappedRequest = new GetItem();
    wrappedRequest.setRequest(request);
    Map<String, AttributeValue> item = driveRequest(wrappedRequest);
    stripSpecialAttributes(item);
    GetItemResult result = new GetItemResult().withItem(item);
    return result;
}
 
Example #26
Source File: TransactionManagerDBFacadeIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
private void testGetItemContainsItem(
        final TransactionManagerDynamoDBFacade facade,
        final Map<String, AttributeValue> item,
        final boolean filterAttributes) {
    GetItemRequest request = new GetItemRequest()
            .withTableName(INTEG_HASH_TABLE_NAME)
            .withKey(key0);
    if (filterAttributes) {
        request.setAttributesToGet(attributesToGet);
    }
    GetItemResult result = facade.getItem(request);
    assertContainsNoTransactionAttributes(result.getItem());
    assertEquals(item, result.getItem());
}
 
Example #27
Source File: FailingAmazonDynamoDBClient.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Override
public GetItemResult getItem(GetItemRequest getItemRequest) throws AmazonServiceException, AmazonClientException {
    if(requestsToFail.contains(getItemRequest)) {
        throw new FailedYourRequestException();
    }
    if (getRequestsToTreatAsDeleted.contains(getItemRequest)) {
        return new GetItemResult();
    }
    Queue<GetItemResult> stubbedResults = getRequestsToStub.get(getItemRequest);
    if (stubbedResults != null && !stubbedResults.isEmpty()) {
        return stubbedResults.remove();
    }
    return super.getItem(getItemRequest);
}
 
Example #28
Source File: IntegrationTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
protected Map<String, AttributeValue> getItem(String tableName, Map<String, AttributeValue> key) {
    GetItemResult result = dynamodb.getItem(new GetItemRequest()
        .withTableName(tableName)
        .withKey(key)
        .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
        .withConsistentRead(true));
    return result.getItem();
}
 
Example #29
Source File: FaultInjectionRequestHandler.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void afterResponse(Request<?> request, Response<?> response)
{
    /*
     * The following is a hit and miss for multi-threaded clients as the
     * cache size is only 50 entries
     */
    String awsRequestId = dynamoDBClient.getCachedResponseMetadata(request.getOriginalRequest()).getRequestId();
    logger.info("AWS RequestID: " + awsRequestId);

    /*
     * Here you could inspect and alter the response object to see how your
     * application behaves for specific data
     */
    if (request.getOriginalRequest() instanceof GetItemRequest)
    {
        GetItemResult result = (GetItemResult) response.getAwsResponse();

        Map<String, AttributeValue> item = result.getItem();

        if (item.get("name").getS().equals("Airplane"))
        {

            // Alter the item
            item.put("name", new AttributeValue("newAirplane"));
            item.put("new attr", new AttributeValue("new attr"));

            // Add some delay
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException ie)
            {
                logger.info(ie);
                throw new RuntimeException(ie);
            }
        }
    }
}
 
Example #30
Source File: DynamoDBWorkerUtilsTest.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetStoredETagDoesNotExist() {
    AmazonDynamoDB dynamoDB = PowerMock.createMock(AmazonDynamoDB.class);
    Map<String, AttributeValue> resourceKey = new HashMap<String, AttributeValue>();
    resourceKey.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    // Get item
    dynamoDB.getItem(table, resourceKey);
    GetItemResult result = new GetItemResult();
    PowerMock.expectLastCall().andReturn(result);
    PowerMock.replayAll();
    String resultETag = DynamoDBWorkerUtils.getStoredETag(dynamoDB, table, resource);
    assertEquals(null, resultETag);
    PowerMock.verifyAll();
}