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

项目:java-translatebot    文件:CommandHandler.java   
private Collection<String> fetchChannelLanguages(final String channel) {

        final String id = "channel:" + channel + ":languages";
        final GetItemRequest getItemRequest = new GetItemRequest()
                .withAttributesToGet(Collections.singletonList("value"))
                .withKey(Collections.singletonMap("id", new AttributeValue(id)))
                .withTableName(TableName);
        final GetItemResult getItemResult = ddb.getItem(getItemRequest);
        final Optional<String> maybeValue = Optional.ofNullable(getItemResult.getItem())
                .map(i -> i.get("value"))
                .map(AttributeValue::getS);
        if (!maybeValue.isPresent())
            return Collections.emptyList();

        return Arrays.asList(maybeValue.get().trim().split(" +"));
    }
项目:java-translatebot    文件:DBValueRetriever.java   
private void fetchTheValue() {

        final GetItemRequest req = new GetItemRequest().withAttributesToGet("value")
                .withTableName(TableName)
                .withKey(Collections.singletonMap("id", new AttributeValue(this.id)));
        try {
            final GetItemResult result = ddb.getItem(req);
            synchronized (this.monitor) {
                if (result.getItem() == null) {
                    this.x = new RuntimeException("not found: id=" + this.id);
                } else {
                    this.v = result.getItem().get("value").getS();
                    if (this.v == null) {
                        this.x = new RuntimeException("found but no value for: id=" + this.id);
                    }
                }
            }
        } catch (final RuntimeException x) {
            synchronized (this.monitor) {
                this.x = x;
            }
        }

    }
项目:java-translatebot    文件:EventHandler.java   
private Collection<String> fetchChannelLanguages(final String channel) {

        final String id = "channel:" + channel + ":languages";
        final GetItemRequest getItemRequest = new GetItemRequest()
                .withAttributesToGet(Collections.singletonList("value"))
                .withKey(Collections.singletonMap("id", new AttributeValue(id)))
                .withTableName(TableName);
        final GetItemResult getItemResult = ddb.getItem(getItemRequest);
        final Optional<String> maybeValue = Optional.ofNullable(getItemResult.getItem())
                .map(i -> i.get("value"))
                .map(AttributeValue::getS);
        if (!maybeValue.isPresent())
            return Collections.emptyList();

        return Arrays.asList(maybeValue.get().trim().split(" +"));
    }
项目:snake-game-aws    文件:DDBGetTask.java   
protected DDBTaskResult doInBackground(Void... params) {

        Log.i("doInBackground", "Starting DDBGettask");

        DDBTaskResult result = new DDBTaskResult();

        try {
            // Need to specify the key of our item, which is a Map of our primary key attribute(s)
            Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
            key.put("userid", new AttributeValue().withS("user1234"));
            key.put("recordid", new AttributeValue().withS("highScore"));

            GetItemRequest getItemRequest = new GetItemRequest(AWSClientManager.DDB_TABLE_NAME,key);
            GetItemResult getItemResult = ddb.getItem(getItemRequest);

            result.setAttributeNumber(Integer.parseInt(getItemResult.getItem().get("data").getN()));

        } catch (AmazonServiceException ex) {
            ex.printStackTrace();
            Log.e("ddb-get-doInBackground", ex.getMessage());
        }

        return result;
    }
项目:aws-java-sdk-stubs    文件:AmazonDynamoDBStubTest.java   
@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());
}
项目:aws-java-sdk-stubs    文件:AmazonDynamoDBStubTest.java   
@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));
}
项目: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());
}
项目: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());
}
项目:ColumnStoreUnifier    文件:DynamoDbQueryHandler.java   
/**
 * Get item of table with provided key-value.
 * 
 * @param tableName
 * @param combinedKey
 * @return
 */
public static Row getRowByKey(String tableName, Key... combinedKey) {
    Map<String, AttributeValue> transformedKey = new HashMap<>();
    for (Key key : combinedKey) {
        transformedKey.put(key.getName(),
                new AttributeValue().withS(key.getValue()));
    }

    GetItemResult result = DynamoDbHandler.CLIENT
            .getItem(new GetItemRequest(tableName, transformedKey));

    List<Attribute> attributes = new ArrayList<>();
    for (String resultKey : result.getItem().keySet()) {
        attributes.add(new Attribute(resultKey, result.getItem()
                .get(resultKey).getS()));
    }

    return new Row(attributes);
}
项目:amazon-kinesis-aggregators    文件:InventoryModel.java   
/**
 * Method which returns the update information for an Aggregator process.
 * 
 * @param streamName The Stream name which is being aggregated.
 * @param applicationName The application which is hosting the aggregator.
 * @param workerId The worker ID which is running an aggregator instance.
 * @return Tuple of Last Write Time (String), Last Low Sequence, and Last
 *         High Sequence
 */
public InventoryStatus getLastUpdate(final String streamName, final String applicationName,
        final String namespace, final String shardId) {
    GetItemResult response = dynamoClient.getItem(InventoryModel.TABLE_NAME,
            getKey(streamName, applicationName, namespace, shardId));
    if (response.getItem() != null) {
        Map<String, AttributeValue> item = response.getItem();
        AttributeValue lastTime, lowSeq, highSeq = null;
        lastTime = item.get(InventoryModel.LAST_WRITE_TIME);
        lowSeq = item.get(InventoryModel.LAST_LOW_SEQ);
        highSeq = item.get(InventoryModel.LAST_HIGH_SEQ);

        return new InventoryStatus(lastTime == null ? null : lastTime.getS(),
                lowSeq == null ? null : lowSeq.getS(), highSeq == null ? null : highSeq.getS());
    } else {
        return null;
    }
}
项目:para    文件:AWSDynamoDAO.java   
private Map<String, AttributeValue> readRow(String key, String appid) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(appid)) {
        return null;
    }
    Map<String, AttributeValue> row = null;
    try {
        GetItemRequest getItemRequest = new GetItemRequest(getTableNameForAppid(appid),
                Collections.singletonMap(Config._KEY, new AttributeValue(getKeyForAppid(key, appid))));
        GetItemResult res = client().getItem(getItemRequest);
        if (res != null && res.getItem() != null && !res.getItem().isEmpty()) {
            row = res.getItem();
        }
    } catch (Exception e) {
        logger.error("Could not read row from DB - appid={}, key={}", appid, key, e);
    }
    return (row == null || row.isEmpty()) ? null : row;
}
项目:spring-security-oauth2-dynamodb    文件:DynamoDBClientDetailsService.java   
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    GetItemResult result = client.getItem(schema.getTableName(), Collections.singletonMap(schema.getColumnClientId(), new AttributeValue(clientId)));

    Map<String, AttributeValue> item = result.getItem();
    if (item == null) { 
        return null;
    }

    String resourceIds = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnResourceIds()));
    String scopes = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnScopes()));
    String grantTypes = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnAuthorizedGrantTypes()));
    String authorities = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnAuthorities()));
    String redirectUris = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnRegisteredRedirectUris()));

    String clientSecret = DynamoDBUtils.nullSafeGetS(item.get(schema.getColumnClientSecret()));

    ClientDetails clientDetails = createClientDetails(clientId, resourceIds, scopes, grantTypes, authorities, redirectUris, clientSecret, item);
    return clientDetails;
}
项目:spring-security-oauth2-dynamodb    文件:DynamoDBTemplate.java   
public <T> T get(String tableName, Map<String, AttributeValue> key, final ObjectExtractor<T> extractor, String... columnsToInclude) throws EmptyResultDataAccessException {
    Assert.notNull(tableName, "Table must not be null");
    Assert.notNull(extractor, "ObjectExtractor must not be null");
    if (logger.isDebugEnabled()) {
        logger.debug("Executing query on " + tableName + " for " + renderKey(key));
    }

    GetItemRequest request = new GetItemRequest(tableName, key, true);
    if (columnsToInclude != null && columnsToInclude.length > 0) {
        request.setAttributesToGet(Arrays.asList(columnsToInclude));
    }

    GetItemResult result = client.getItem(request);

    Map<String, AttributeValue> item = result.getItem();
    if (item == null) {
        throw new EmptyResultDataAccessException("No results found in " + tableName + "for " + renderKey(key));
    }

    return extractor.extract(item);
}
项目:aws-dynamodb-mars-json-demo    文件:DynamoDBWorkerUtils.java   
/**
 * 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;
}
项目:aws-dynamodb-mars-json-demo    文件:DynamoDBWorkerUtilsTest.java   
@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();
}
项目:aws-dynamodb-examples    文件:LowLevelItemCRUDExample.java   
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);
    }   

}
项目:aws-dynamodb-examples    文件:LowLevelItemBinaryExample.java   
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);
}
项目:metamodel    文件:DynamoDbDataContext.java   
@Override
protected Row executePrimaryKeyLookupQuery(Table table, List<SelectItem> selectItems, Column primaryKeyColumn,
        Object keyValue) {
    final List<String> attributeNames = new ArrayList<>();
    for (SelectItem selectItem : selectItems) {
        attributeNames.add(selectItem.getColumn().getName());
    }

    final GetItemRequest getItemRequest = new GetItemRequest(table.getName(), Collections.singletonMap(
            primaryKeyColumn.getName(), DynamoDbUtils.toAttributeValue(keyValue))).withAttributesToGet(
                    attributeNames);
    final GetItemResult item = _dynamoDb.getItem(getItemRequest);

    final Object[] values = new Object[selectItems.size()];
    for (int i = 0; i < values.length; i++) {
        final AttributeValue attributeValue = item.getItem().get(attributeNames.get(i));
        values[i] = DynamoDbUtils.toValue(attributeValue);
    }

    return new DefaultRow(new SimpleDataSetHeader(selectItems), values);
}
项目: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;
}
项目:webcrawler    文件:CrawlerService.java   
private Mono<GetItemResult> getItemResultMono(String url) {

        GetItemRequest getItemRequest = new GetItemRequest();
        getItemRequest.setTableName(Utils.table.websites);
        HashMap<String, AttributeValue> key = new HashMap<>();
        key.put(Utils.params.url, new AttributeValue(url));
        getItemRequest.setKey(key);

        return Mono.fromFuture(
                Utils.makeCompletableFuture(
                        dynamoDBAsync.getItemAsync(getItemRequest)))
                .doOnError((throwable -> LOG.error(Utils.error.failed_dynamo_get, url)));
    }
项目:java-translatebot    文件:EventHandler.java   
private Optional<String> googleToken(final String team) {
    final String id = "team:" + team + ":googletoken";
    final GetItemRequest getItemRequest = new GetItemRequest()
            .withAttributesToGet(Collections.singletonList("value"))
            .withKey(Collections.singletonMap("id", new AttributeValue(id)))
            .withTableName(TableName);
    final GetItemResult getItemResult = ddb.getItem(getItemRequest);
    return Optional.ofNullable(getItemResult.getItem()).map(i -> i.get("value")).map(AttributeValue::getS);
}
项目:Camel    文件:GetItemCommand.java   
@Override
public void execute() {
    GetItemResult result = ddbClient.getItem(new GetItemRequest()
            .withKey(determineKey())
            .withTableName(determineTableName())
            .withAttributesToGet(determineAttributeNames())
            .withConsistentRead(determineConsistentRead()));
    addAttributesToResult(result.getItem());
}
项目:dynamodb-janusgraph-storage-backend    文件:DynamoDbDelegate.java   
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;
}
项目:dynamodb-janusgraph-storage-backend    文件:DynamoDbSingleRowStore.java   
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);
}
项目:dynamodb-janusgraph-storage-backend    文件:DynamoDbSingleRowStore.java   
@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);
}
项目:dynamodb-online-index-violation-detector    文件:TableManager.java   
/**
 * 
 * Get the item from table by their hash key and range key
 * 
 */
public Map<String, AttributeValue> getItem(String tableName, String hashKeyName, AttributeValue hashkeyValue, String rangeKeyName,
        AttributeValue rangeKeyValue) {
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put(hashKeyName, hashkeyValue);
    if (rangeKeyValue != null)
        key.put(rangeKeyName, rangeKeyValue);

    GetItemRequest getItemRequest = new GetItemRequest().withTableName(tableName).withKey(key);

    GetItemResult result = client.getItem(getItemRequest);
    return result.getItem();
}
项目:aws-java-sdk-stubs    文件:AmazonDynamoDBStubTest.java   
@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));
}
项目:aws-java-sdk-stubs    文件:AmazonDynamoDBStubTest.java   
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;
}
项目:amediamanager    文件:DynamoDbUserDaoImpl.java   
@Override
public User find(String email) throws DataSourceTableDoesNotExistException {
    try {

        User user = null;

        // Create a request to find a User by email address
        GetItemRequest getItemRequest = new GetItemRequest()
                .withTableName(
                        config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE))
                .addKeyEntry(HASH_KEY_NAME, new AttributeValue(email));

        // Issue the request to find the User in DynamoDB
        GetItemResult getItemResult = dynamoClient.getItem(getItemRequest);

        // If an item was found
        if (getItemResult.getItem() != null) {
            // Marshal the Map<String, AttributeValue> structure returned in
            // the
            // GetItemResult to a User object
            user = getUserFromMap(getItemResult.getItem());
        }

        return user;

    } catch (ResourceNotFoundException rnfe) {

        // The ResourceNotFoundException method is thrown by the getItem()
        // method
        // if the DynamoDB table doesn't exist. This exception is re-thrown
        // as a
        // custom, more specific DataSourceTableDoesNotExistException that
        // users
        // of this DAO understand.
        throw new DataSourceTableDoesNotExistException(config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE));
    }
}
项目:milton-aws    文件:DynamoDBServiceImpl.java   
@Override
  public Map<String, AttributeValue> getItem(String tableName, HashMap<String, AttributeValue> primaryKey) {
      LOG.info("Retrieves a set of Attributes for an item that matches the primary key "
              + primaryKey + " from the table " + tableName);

    try {
        GetItemRequest getItemRequest = new GetItemRequest().withTableName(tableName)
                .withKey(primaryKey)
                .withConsistentRead(true);
          GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest);
          Map<String, AttributeValue> item = getItemResult.getItem();
          if (item == null || item.isEmpty()) {
        LOG.warn("Could not find any item for the given UUID: "
                + primaryKey + " from " + tableName);
            return Collections.emptyMap();
          }

    LOG.info("Listing collection from " + tableName + ": " + (item.size() / 8) + " items");
          return item;
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Requested resource " + tableName + " not found ", rnfe);
} catch (Exception ex) {
    LOG.error("Failed to get item into the " + tableName, ex);
}

      return Collections.emptyMap();
  }
项目:spring-security-oauth2-dynamodb    文件:DynamoDBUserDetailsManager.java   
protected UserDetails loadUserByUsername(String username, boolean consistentRead) throws UsernameNotFoundException {
    GetItemResult result = client.getItem(schema.getTableName(), Collections.singletonMap(schema.getColumnUsername(), new AttributeValue(username)), consistentRead);

    UserDetails user = buildUserFromItem(result.getItem());

    if (user == null) {
        throw new UsernameNotFoundException("No user found for " + username);
    }
    return user;
}
项目:spring-security-oauth2-dynamodb    文件:DynamoDBUserDetailsManager.java   
@Override
public boolean userExists(String username) {
    GetItemRequest request = new GetItemRequest(schema.getTableName(), Collections.singletonMap(schema.getColumnUsername(), new AttributeValue(username))) //
            .withAttributesToGet(schema.getColumnUsername());
    GetItemResult result = client.getItem(request);
    return result.getItem() != null;
}
项目:aws-dynamodb-mars-json-demo    文件:DynamoDBWorkerUtilsTest.java   
@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();
}
项目:aws-dynamodb-examples    文件:FaultInjectionRequestHandler.java   
@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);
            }
        }
    }
}
项目:jcabi-dynamo    文件:AwsItem.java   
@Override
public AttributeValue get(final String attr) throws IOException {
    final String attrib = String.format(Locale.ENGLISH, attr);
    AttributeValue value = this.attributes.get(attrib);
    if (value == null) {
        final AmazonDynamoDB aws = this.credentials.aws();
        try {
            final GetItemRequest request = this.makeItemRequestFor(attrib);
            final long start = System.currentTimeMillis();
            final GetItemResult result = aws.getItem(request);
            value = result.getItem().get(attrib);
            Logger.info(
                this,
                // @checkstyle LineLength (1 line)
                "#get('%s'): loaded '%[text]s' from DynamoDB, %s, in %[ms]s",
                attrib, value,
                new PrintableConsumedCapacity(
                    result.getConsumedCapacity()
                ).print(),
                System.currentTimeMillis() - start
            );
        } catch (final AmazonClientException ex) {
            throw new IOException(
                String.format(
                    "failed to get \"%s\" from \"%s\" by %s",
                    attr, this.name, this.keys
                ),
                ex
            );
        } finally {
            aws.shutdown();
        }
    }
    if (value == null) {
        throw new NoSuchElementException(
            String.format("attribute \"%s\" not found", attr)
        );
    }
    return value;
}
项目:cloudata    文件:DynamodbDataStore.java   
@Override
public <T extends Message> T findOne(T matcher, Modifier... modifiers) throws DataStoreException {
  DynamoClassMapping<T> tableInfo = getClassMapping(matcher);

  log.debug("findOne {} {}", matcher.getClass().getSimpleName(), matcher);

  Map<FieldDescriptor, Object> matcherFields = matcher.getAllFields();
  // TODO: Remove PK fields

  GetItemRequest request = new GetItemRequest();
  // TODO: Modifier for eventually consistent read?
  request.setConsistentRead(true);
  request.setTableName(tableInfo.getDynamoTableName());
  request.setKey(tableInfo.buildCompleteKey(matcher));

  for (Modifier modifier : modifiers) {
    throw new UnsupportedOperationException();
  }

  GetItemResult result = dynamoDB.getItem(request);
  Map<String, AttributeValue> itemData = result.getItem();
  if (itemData == null) {
    return null;
  }

  T item = tableInfo.mapFromDb(itemData);
  if (DataStore.matches(matcherFields, item)) {
    log.debug("found item: {}", item);
    return item;
  }

  return null;
}
项目:Camel    文件:AmazonDDBClientMock.java   
@Override
public GetItemResult getItem(GetItemRequest getItemRequest) {
    this.getItemRequest = getItemRequest;
    return new GetItemResult().withItem(getAttributes());
}
项目:dynamodb-janusgraph-storage-backend    文件:ExponentialBackoff.java   
@Override
protected GetItemResult call() throws BackendException {
    return delegate.getItem(request);
}
项目:dynamodb-janusgraph-storage-backend    文件:GetItemWorker.java   
@Override
public GetItemResultWrapper call() throws Exception {
    final GetItemResult result = new ExponentialBackoff.GetItem(request, dynamoDbDelegate).runWithBackoff();
    return new GetItemResultWrapper(hashKey, result);
}
项目:dynamodb-geo    文件:GetPointResult.java   
public GetPointResult(GetItemResult getItemResult) {
    this.getItemResult = getItemResult;
}