类com.amazonaws.services.dynamodbv2.model.GetItemResult源码实例Demo

下面列出了怎么用com.amazonaws.services.dynamodbv2.model.GetItemResult的API类实例代码及写法,或者点击链接到github查看源代码。

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);
    }

}
 
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);
}
 
@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));
}
 
@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());
}
 
@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));
}
 
源代码6 项目: Cheddar   文件: DynamoDbTemplateIntegrationTest.java
@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());
}
 
源代码7 项目: Cheddar   文件: DynamoDbTemplateIntegrationTest.java
@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());
}
 
/**
 * 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;
}
 
@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();
}
 
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);
    }   

}
 
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);
}
 
源代码12 项目: dynamodb-geo   文件: DynamoDBManager.java
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;
}
 
@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);
}
 
@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);
}
 
源代码15 项目: pocket-etl   文件: DynamoDbFunctionalTest.java
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);
}
 
@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);
}
 
TestItem(TableSchema<?> schema,
                 GetItemResponse v2Response,

                 Object v1Key,
                 GetItemResult v1Response) {
    this.schema = schema;
    this.v2Response = v2Response;

    this.v1Key = v1Key;
    this.v1Response = v1Response;
}
 
@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);
            }
        }
    }
}
 
GetItemResult getItem(final GetItemRequest request) throws BackendException {
    setUserAgent(request);
    GetItemResult result;
    timedReadThrottle(GET_ITEM, request.getTableName(), estimateCapacityUnits(GET_ITEM, request.getTableName()));
    final Timer.Context apiTimerContext = getTimerContext(GET_ITEM, request.getTableName());
    try {
        result = client.getItem(request);
    } catch (Exception e) {
        throw processDynamoDbApiException(e, GET_ITEM, request.getTableName());
    } finally {
        apiTimerContext.stop();
    }
    meterConsumedCapacity(GET_ITEM, result.getConsumedCapacity());
    return result;
}
 
private EntryList extractEntriesFromGetItemResult(final GetItemResult result, final StaticBuffer sliceStart, final StaticBuffer sliceEnd, final int limit) {
    final Map<String, AttributeValue> item = result.getItem();
    List<Entry> filteredEntries = Collections.emptyList();
    if (null != item) {
        item.remove(Constants.JANUSGRAPH_HASH_KEY);
        filteredEntries = new EntryBuilder(item)
                .slice(sliceStart, sliceEnd)
                .limit(limit)
                .buildAll();
    }
    return StaticArrayEntryList.of(filteredEntries);
}
 
@Override
public EntryList getSlice(final KeySliceQuery query, final StoreTransaction txh) throws BackendException {
    log.debug("Entering getSliceKeySliceQuery table:{} query:{} txh:{}", getTableName(), encodeForLog(query), txh);
    final GetItemRequest request = super.createGetItemRequest().withKey(new ItemBuilder().hashKey(query.getKey()).build());
    final GetItemResult result = new ExponentialBackoff.GetItem(request, client.getDelegate()).runWithBackoff();

    final List<Entry> filteredEntries = extractEntriesFromGetItemResult(result, query.getSliceStart(), query.getSliceEnd(), query.getLimit());
    log.debug("Exiting getSliceKeySliceQuery table:{} query:{} txh:{} returning:{}", getTableName(), encodeForLog(query), txh,
              filteredEntries.size());
    return StaticArrayEntryList.of(filteredEntries);
}
 
@Test
public void test_getItem_WithAllParameters() throws Exception {
  createTable();
  putItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);

  GetItemResult result = getItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE);
  AttributeValue attributeValue = result.getItem().get(TEST_ATTRIBUTE);

  assertThat(attributeValue.getS(), equalTo(TEST_ATTRIBUTE_VALUE));
}
 
private GetItemResult getItem(String attributeName, String attributeValue) throws Exception {
  Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
  key.put(attributeName, new AttributeValue()
    .withS(attributeValue));
  Boolean consistentRead = new Boolean(true);

  GetItemResult result = dynamoDb.getItem(TEST_TABLE_NAME, key, consistentRead);

  return result;
}
 
@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();
}
 
@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);
            }
        }
    }
}
 
源代码26 项目: dynamodb-transactions   文件: IntegrationTest.java
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();
}
 
@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);
}
 
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());
}
 
源代码29 项目: dynamodb-transactions   文件: Transaction.java
/**
 * 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;
}
 
源代码30 项目: dynamodb-transactions   文件: Transaction.java
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();
}
 
 类方法
 同包方法