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(" +")); }
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; } } }
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; }
@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)); }
@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()); }
@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()); }
/** * 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); }
/** * 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; } }
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; }
@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; }
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); }
/** * 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); }
@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); }
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; }
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))); }
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); }
@Override public void execute() { GetItemResult result = ddbClient.getItem(new GetItemRequest() .withKey(determineKey()) .withTableName(determineTableName()) .withAttributesToGet(determineAttributeNames()) .withConsistentRead(determineConsistentRead())); addAttributesToResult(result.getItem()); }
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); }
/** * * 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(); }
@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; }
@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)); } }
@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(); }
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; }
@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; }
@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); } } } }
@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; }
@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; }
@Override public GetItemResult getItem(GetItemRequest getItemRequest) { this.getItemRequest = getItemRequest; return new GetItemResult().withItem(getAttributes()); }
@Override protected GetItemResult call() throws BackendException { return delegate.getItem(request); }
@Override public GetItemResultWrapper call() throws Exception { final GetItemResult result = new ExponentialBackoff.GetItem(request, dynamoDbDelegate).runWithBackoff(); return new GetItemResultWrapper(hashKey, result); }
public GetPointResult(GetItemResult getItemResult) { this.getItemResult = getItemResult; }