@Override public Void create(Group group) { Item item = preparePutItem(group); PutItemSpec putItemSpec = new PutItemSpec() .withItem(item) .withConditionExpression("attribute_not_exists(#ns_key)") .withNameMap(new NameMap().with("#ns_key", HASH_KEY)); Table table = dynamoDB.getTable(groupTableName); final Supplier<PutItemOutcome> putItemOutcomeSupplier = () -> { try { return table.putItem(putItemSpec); } catch (ConditionalCheckFailedException e) { throwConflictAlreadyExists(group); return null; } }; return putItem(group, putItemOutcomeSupplier); }
@Override public Optional<Feature> loadFeatureByKey(String group, String key) { logger.info("{}", kvp("op", "loadFeatureByKey", HASH_KEY, group, RANGE_KEY, key)); Table table = dynamoDB.getTable(featureTableName); DynamoDbCommand<Item> cmd = new DynamoDbCommand<>("loadFeatureByKey", () -> getItem(group, key, table), () -> { throw new RuntimeException("loadFeatureById"); }, hystrixReadConfiguration, metrics); Item item = cmd.execute(); if (item == null) { return Optional.empty(); } return Optional.of(FeatureSupport.toFeature(item.getString("json"))); }
private boolean tryAddMissingPartition(String dyanmoDBTaableName,DynamoDB dynamoDBClient, Partition partition){ Table ddbTable= dynamoDBClient.getTable(dyanmoDBTaableName); Item item=new Item() .withPrimaryKey("PartitionSpec",partition.spec()) .withString("PartitionPath",partition.path()) .withString("PartitionName", partition.name()); PutItemSpec itemSpec=new PutItemSpec() .withItem(item) .withConditionExpression("attribute_not_exists(#ps)") .withNameMap(new NameMap() .with("#ps","PartitionSpec")); try{ ddbTable.putItem(itemSpec); System.out.println("Item was added to the table.PartitionSpec="+partition.spec()+"; Path="+partition.path()); return true; } catch(ConditionalCheckFailedException e){ System.out.println(e.toString()); System.out.println("Item already exists. PartitionSpec="+partition.spec()+"; Path="+partition.path()); return false; } }
@Override public StorageTestState readState(final String identity) { final Table table = dynamoDBConnection.getDynamoDB().getTable(getTableName()); final Item item = table.getItem("_id", generateItemId(identity)); if (item != null) { try { final StorageTestState testState = new HelloState(); dynamoDBConnection.getMapper().readerForUpdating(testState).readValue(item.getJSON("_state")); return testState; } catch (Exception e) { throw new UncheckedException(e); } } return null; }
protected Table createHashAndSortTable(String pk, String sort) throws InterruptedException { ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(); ScalarAttributeType type = ScalarAttributeType.S; attributeDefinitions.add(new AttributeDefinition() .withAttributeName(pk).withAttributeType(type)); attributeDefinitions .add(new AttributeDefinition().withAttributeName(sort).withAttributeType(type)); ArrayList<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName(pk).withKeyType(KeyType.HASH)); keySchema.add(new KeySchemaElement().withAttributeName(sort).withKeyType(KeyType.RANGE)); CreateTableRequest request = new CreateTableRequest() .withKeySchema(keySchema) .withAttributeDefinitions(attributeDefinitions); return createTable(request); }
protected Table createTable(CreateTableRequest request) throws InterruptedException { DynamoDB dynamoDB = new DynamoDB(tables.getAsyncClient()); request.withProvisionedThroughput(new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(6L)); if (request.getTableName() == null) { String tableName = tables.getTestTableName(); tableName = tableName.replace('-', '_'); request.setTableName(tableName); } Table table = dynamoDB.createTable(request); table.waitForActive(); return table; }
@Test public void testPrimaryAndSortKeySpecification() throws Exception { String pk = "pk", sort = "sort"; Table table = createHashAndSortTable(pk, sort); Item item = new Item(); item.with(pk, "p1"); item.with(sort, "s1"); item.with(COL1, "1"); table.putItem(item); Item item2 = new Item(); item2.with(pk, "p1"); item2.with(sort, "s0"); item2.with(COL1, "2"); table.putItem(item2); // should create a get String query = selectStarWithPK("p1", "t", table) + " AND sort = 's1'"; verify(runAndReadResults(query), item); validatePlanWithGets(query, pkEquals("p1").and(create("equal", "sort", "s1"))); // should create a query query = selectStarWithPK("p1", "t", table) + " AND sort >= 's1'"; verify(runAndReadResults(query), item); validatePlanWithQueries(query, of(pkEquals("p1").and( DynamoPlanValidationUtils.gte("sort", "s1")), null)); }
@Test public void testWhereColumnEqualsNull() throws Exception { Item item = item(); item.with(COL1, null); Table table = createTableWithItems(item); String query = selectStarWithPK("pk", "t", table) + " AND t." + COL1 + " = cast(null as varchar)"; verify(runAndReadResults(query), item); ImmutablePair<DynamoFilterSpec, DynamoFilterSpec> spec = of(pkEquals("pk"), DynamoPlanValidationUtils .equals(COL1, null)); validatePlanWithQueries(query, spec); // we return nulls are varchar b/c we can cast anything from varchar. Make sure that a // boolean null cast also works query = selectStarWithPK("pk", "t", table) + " AND t." + COL1 + " = cast(null as boolean)"; verify(runAndReadResults(query), item); validatePlanWithQueries(query, spec); }
/** * Similar to above, but we check for the non-existance of a column */ @Test public void testWhereNoColumnValueIsNull() throws Exception { Item item = item(); Table table = createTableWithItems(item); String query = selectStarWithPK("pk", "t", table) + " AND t." + COL1 + " = cast(null as varchar)"; assertEquals("Should not have found a row when checking for = null and column not set!", 0, runAndReadResults(query).size()); ImmutablePair<DynamoFilterSpec, DynamoFilterSpec> spec = of(pkEquals("pk"), DynamoPlanValidationUtils .equals(COL1, null)); validatePlanWithQueries(query, spec); // see above for why trying a different type query = selectStarWithPK("pk", "t", table) + " AND t." + COL1 + " = cast(null as BOOLEAN)"; assertEquals("Should not have found a row when checking for = null and column not set!", 0, runAndReadResults(query).size()); validatePlanWithQueries(query, spec); query = selectStarWithPK("pk", "t", table) + " AND t." + COL1 + " IS NULL"; verify(runAndReadResults(query), item); validatePlanWithQueries(query, of(spec.getLeft(), create("isNull", COL1))); }
@Test public void testSimpleScan() throws Exception { Item item = item(); item.with(COL1, 1); Table table = createTableWithItems(item); String select = "SELECT *" + from(table) + "t WHERE t." + COL1 + " = 1"; verify(runAndReadResults(select), item); DynamoFilterSpec spec = DynamoPlanValidationUtils.equals(COL1, 1); validatePlanWithScan(select, spec); Item item2 = new Item(); item2.with(PK, "pk2"); item2.with(COL1, 2); table.putItem(item2); verify(runAndReadResults(select), item); // plan doesn't change as the table gets larger validatePlanWithScan(select, spec); }
@Test public void testGetAndQuery() throws Exception { Item item = item(); item.with(COL1, "1"); Item i2 = new Item(); i2.with(PK, "pk2"); i2.with(COL1, 2); Table table = createTableWithItems(item, i2); String query = "SELECT *" + from(table) + "t WHERE " + "t." + PK + " = 'pk' OR " + "t." + PK + " = 'pk2' AND t." + COL1 + " >= 2" + "ORDER BY t." + PK + " ASC"; verify(runAndReadResults(query), item, i2); validatePlan(query, null, null, newArrayList(new DynamoQueryFilterSpec(pkEquals("pk2"), DynamoPlanValidationUtils .gte(COL1, 2)), new DynamoGetFilterSpec(pkEquals("pk")))); }
@Test public void testQueryOrQuery() throws Exception { Item item = item(); item.with(COL1, 1); Item i2 = new Item(); i2.with(PK, "pk2"); i2.with(COL1, 2); Table table = createTableWithItems(item, i2); String query = "SELECT *" + from(table) + "t WHERE " + "t." + PK + " = 'pk' AND t." + COL1 + " = 1" + " OR " + "t." + PK + " = 'pk2' AND t." + COL1 + " >= 2" + "ORDER BY t." + PK + " ASC"; verify(runAndReadResults(query), item, i2); validatePlanWithQueries(query, of(pkEquals("pk2"), DynamoPlanValidationUtils.gte(COL1, 2)), of(pkEquals("pk"), DynamoPlanValidationUtils.equals(COL1, 1))); }
@Test public void testQueryAndQueryForcesScan() throws Exception { Item item = item(); item.with(COL1, 1); Item i2 = new Item(); i2.with(PK, "pk2"); i2.with(COL1, 2); Table table = createTableWithItems(item, i2); String query = "SELECT *" + from(table) + "t WHERE " + "t." + PK + " = 'pk' AND t." + COL1 + " = 1" + " AND " + "t." + PK + " = 'pk2' AND t." + COL1 + " >= 2" + "ORDER BY t." + PK + " ASC"; verify(runAndReadResults(query)); validatePlanWithScan(query, pkEquals("pk").and(DynamoPlanValidationUtils.equals(COL1, 1)).and( pkEquals("pk2")).and(DynamoPlanValidationUtils.gte(COL1, 2))); }
@Test public void testQueryOrAttributeForcesScan() throws Exception { Item item = item(); item.with(COL1, 1); Item i2 = new Item(); i2.with(PK, "pk2"); i2.with(COL1, 2); Table table = createTableWithItems(item, i2); String query = "SELECT *" + from(table) + "t WHERE " + "(t." + PK + " = 'pk' AND t." + COL1 + " = 1)" + " OR " + "t." + COL1 + " >= 2" + "ORDER BY t." + PK + " ASC"; verify(runAndReadResults(query), item, i2); validatePlanWithScan(query, pkEquals("pk").and(DynamoPlanValidationUtils.equals(COL1, 1)).or( DynamoPlanValidationUtils.gte(COL1, 2))); }
@Test public void testMultiRangeQuery() throws Exception { Table table = createHashAndSortTable(PK, COL1); Item item = item(); item.with(COL1, "1"); table.putItem(item); Item i2 = item(); i2.with(COL1, "2"); table.putItem(i2); String query = "SELECT *" + from(table) + "t WHERE " + "t." + PK + " = 'pk'" + " AND (" + "t." + COL1 + " = '1'" + " AND " + "t." + COL1 + " >= '2')"; verify(runAndReadResults(query)); validatePlanWithQueries(query, of( pkEquals("pk").and(DynamoPlanValidationUtils.equals(COL1, "1")), null), of(pkEquals("pk").and(DynamoPlanValidationUtils.gte(COL1, "2")), null)); // verify(runAndReadResults("SELECT *" + from(table) + "t WHERE " + // "t." + PK + " = 'pk'" + " AND (" + // "t." + COL1 + " = '1'" + // " OR " + // "t." + COL1 + " >= '2')"), item, i2); }
@Test public void testHashKeyMapping() throws Exception { Item item = new Item(); item.with(PK, "ab"); Table table = createTableWithItems(item); updatePlugin(plugin -> { Map<String, Object> args = new HashMap<>(); args.put("@class", LengthBasedTwoPartHashKeyMapper.class.getName()); args.put("length", 1); DynamoKeyMapperSpec spec = new DynamoKeyMapperSpec(of("h1", "h2"), of("S", "S"), args); plugin.setDynamoKeyMapperForTesting(table.getTableName(), spec); }); Item expected = new Item(); expected.with("h1", "a"); expected.with("h2", "b"); expected.with(PK, "ab"); selectStar(table, true, expected); }
/** * Release a distributed lock, by setting its expiry to 0 * * This always succeeds. There should be no legitimate contention between processes for lock release, as long as * this is only called when you're *certain* that the process already holds the lock. */ @Override public void unlock(String lockKey) { lockKey = getEnvironmentSpecificLockKey(lockKey); logger.info("Releasing lock [{}]", lockKey); Table table = dynamoDb.getTable(tableName); try { Item item = new Item() .withPrimaryKey(TABLE_KEY, lockKey) .withLong(LOCK, 0) // setting an expiry of 0 means the lock is always expired, therefore released .withString(TABLE_CREATED_AT, OffsetDateTime.now(clock).toString()); table.putItem(item); logger.info("Released lock [{}]", lockKey); } catch (Exception ex) { logger.error("Failed to release lock [{}]", lockKey); } }
private String scaleTable(String tableName, Long readCapacity, Long writeCapacity) { Table table = dynamoDB.getTable(tableName); ProvisionedThroughput tp = new ProvisionedThroughput(); tp.setReadCapacityUnits(readCapacity); tp.setWriteCapacityUnits(writeCapacity); TableDescription d = table.describe(); if (!Objects.equals(d.getProvisionedThroughput().getReadCapacityUnits(), readCapacity) || !Objects.equals(d.getProvisionedThroughput().getWriteCapacityUnits(), writeCapacity)) { d = table.updateTable(tp); return tableName + "\nRequested read/write : " + readCapacity + "/" + writeCapacity + "\nCurrent read/write :" + d.getProvisionedThroughput().getReadCapacityUnits() + "/" + d.getProvisionedThroughput().getWriteCapacityUnits() + "\nStatus : " + d.getTableStatus() + "\n"; } else { return tableName + "\n Requested throughput equals current throughput\n"; } }
private void createTable(Class tableClass) { CreateTableRequest createTableRequest = mapper.generateCreateTableRequest(tableClass); createTableRequest.setProvisionedThroughput(new ProvisionedThroughput(dbReadCapacity, dbWriteCapacity)); if (tableExists(createTableRequest.getTableName())) { LOG.info("Table {} already exists", createTableRequest.getTableName()); return; } try { DynamoDB dynamoDB = new DynamoDB(amazonDynamoDB); Table table = dynamoDB.createTable(createTableRequest); LOG.info("Creating table {} ... ", createTableRequest.getTableName()); table.waitForActive(); LOG.info("Table {} was created successfully.", createTableRequest.getTableName()); } catch (Exception e) { LOG.error("Failed to create table {}. ", createTableRequest.getTableName()); LOG.error(e); throw new ConfigurationException("Failed to create table" + createTableRequest.getTableName(), e); } }
@Override public void transform(Item scoreItem, DynamoDB dynamodb) { String playerName = scoreItem.getString(PLAYER_NAME); int score = scoreItem.getInt(SCORE); int gameLength = scoreItem.getInt(GAME_LENGTH); /* * The XSpec API allows you to use DynamoDB's expression language * to execute expressions on the service-side. * * https://java.awsblog.com/post/TxBG87QOQZRZJF/-DynamoDB-XSpec-API */ Table viewTable = dynamodb.getTable(PLAYER_STATS_TABLE_NAME); UpdateItemExpressionSpec incrementTotalOrder = new ExpressionSpecBuilder() .addUpdate(N(TOTAL_SCORE).add(score)) .addUpdate(N(TOTAL_GAMEPLAY).add(gameLength)) .addUpdate(N(TOTAL_GAMES).add(1)) .buildForUpdate(); viewTable.updateItem(PLAYER_NAME, playerName, incrementTotalOrder); }
@Override public void transform(Item scoreItem, DynamoDB dynamodb) { String playerName = scoreItem.getString(PLAYER_NAME); int score = scoreItem.getInt(SCORE); String date = scoreItem.getString(DATE); Table table = dynamodb.getTable(HIGH_SCORES_BY_DATE_TABLE_NAME); // Use conditional write to update max score UpdateItemExpressionSpec updateMax = new ExpressionSpecBuilder() .withCondition(N(MAX_SCORE).lt(score) .or(attribute_not_exists(MAX_SCORE))) .addUpdate(N(MAX_SCORE).set(score)) .buildForUpdate(); try { table.updateItem(PLAYER_NAME, playerName, DATE, date, updateMax); } catch (ConditionalCheckFailedException ccfe) {} }
private static void loadSampleForums(String tableName) { Table table = dynamoDB.getTable(tableName); try { System.out.println("Adding data to " + tableName); Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB") .withString("Category", "Amazon Web Services") .withNumber("Threads", 2).withNumber("Messages", 4) .withNumber("Views", 1000); table.putItem(item); item = new Item().withPrimaryKey("Name", "Amazon S3") .withString("Category", "Amazon Web Services") .withNumber("Threads", 0); table.putItem(item); } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); } }
private static void loadSampleForums(String tableName) { Table table = dynamoDB.getTable(tableName); try { System.out.println("Adding data to " + tableName); Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB") .withString("Category", "Amazon Web Services") .withNumber("Threads", 2) .withNumber("Messages", 4) .withNumber("Views", 1000); table.putItem(item); item = new Item().withPrimaryKey("Name", "Amazon S3") .withString("Category", "Amazon Web Services") .withNumber("Threads", 0); table.putItem(item); } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); } }
public static void main(String[] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.setEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Movies"); // Conditional delete (will fail) DeleteItemSpec deleteItemSpec = new DeleteItemSpec() .withPrimaryKey(new PrimaryKey("year", 2015, "title", "The Big New Movie")) .withConditionExpression("info.rating <= :val") .withValueMap(new ValueMap() .withNumber(":val", 5.0)); System.out.println("Attempting a conditional delete..."); try { table.deleteItem(deleteItemSpec); System.out.println("DeleteItem succeeded"); } catch (Exception e) { e.printStackTrace(); System.out.println("DeleteItem failed"); } }
public static void main(String[] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.setEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Movies"); ScanSpec scanSpec = new ScanSpec() .withProjectionExpression("#yr, title, info.rating") .withFilterExpression("#yr between :start_yr and :end_yr") .withNameMap(new NameMap().with("#yr", "year")) .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959)); ItemCollection<ScanOutcome> items = table.scan(scanSpec); Iterator<Item> iter = items.iterator(); while (iter.hasNext()) { Item item = iter.next(); System.out.println(item.toString()); } }
public static void main(String[] args) { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.setEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Movies"); int year = 2015; String title = "The Big New Movie"; try { table.putItem(new Item() .withPrimaryKey("year", year, "title", title) .withJSON("info", "{\"plot\" : \"Something happens.\"}")); System.out.println("PutItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty()); } catch (Exception e) { System.out.println("PutItem failed"); e.printStackTrace(); } }
public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient(); client.setEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); String tableName = "Movies"; Table table = dynamoDB.createTable(tableName, Arrays.asList( new KeySchemaElement("year", KeyType.HASH), new KeySchemaElement("title", KeyType.RANGE)), Arrays.asList( new AttributeDefinition("year", ScalarAttributeType.N), new AttributeDefinition("title", ScalarAttributeType.S)), new ProvisionedThroughput(10L, 10L)); try { TableUtils.waitUntilActive(client, tableName); System.out.println("Table status: " + table.getDescription().getTableStatus()); } catch (AmazonClientException e) { e.printStackTrace(); System.exit(1); } }
public static void createItem(String threadId, String replyDateTime) throws IOException { Table table = dynamoDB.getTable(tableName); // Craft a long message String messageInput = "Long message to be compressed in a lengthy forum reply"; // Compress the long message ByteBuffer compressedMessage = compressString(messageInput.toString()); table.putItem(new Item() .withPrimaryKey("Id", threadId) .withString("ReplyDateTime", replyDateTime) .withString("Message", "Long message follows") .withBinary("ExtendedMessage", compressedMessage) .withString("PostedBy", "User A")); }
public static void retrieveItem(String threadId, String replyDateTime) throws IOException { Table table = dynamoDB.getTable(tableName); GetItemSpec spec = new GetItemSpec() .withPrimaryKey("Id", threadId, "ReplyDateTime", replyDateTime) .withConsistentRead(true); Item item = table.getItem(spec); // Uncompress the reply message and print String uncompressed = uncompressString(ByteBuffer.wrap(item.getBinary("ExtendedMessage"))); System.out.println("Reply message:\n" + " Id: " + item.getString("Id") + "\n" + " ReplyDateTime: " + item.getString("ReplyDateTime") + "\n" + " PostedBy: " + item.getString("PostedBy") + "\n" + " Message: " + item.getString("Message") + "\n" + " ExtendedMessage (uncompressed): " + uncompressed + "\n"); }
private static void uploadProduct(String tableName, int productIndex) { Table table = dynamoDB.getTable(tableName); try { System.out.println("Processing record #" + productIndex); Item item = new Item() .withPrimaryKey("Id", productIndex) .withString("Title", "Book " + productIndex + " Title") .withString("ISBN", "111-1111111111") .withStringSet( "Authors", new HashSet<String>(Arrays.asList("Author1"))) .withNumber("Price", 2) .withString("Dimensions", "8.5 x 11.0 x 0.5") .withNumber("PageCount", 500) .withBoolean("InPublication", true) .withString("ProductCategory", "Book"); table.putItem(item); } catch (Exception e) { System.err.println("Failed to create item " + productIndex + " in " + tableName); System.err.println(e.getMessage()); } }
static void deleteExampleTable() { Table table = dynamoDB.getTable(tableName); try { System.out.println("Issuing DeleteTable request for " + tableName); table.delete(); System.out.println("Waiting for " + tableName + " to be deleted...this may take a while..."); table.waitForDelete(); } catch (Exception e) { System.err.println("DeleteTable request failed for " + tableName); System.err.println(e.getMessage()); } }
private static void deleteItem() { Table table = dynamoDB.getTable(tableName); try { DeleteItemSpec deleteItemSpec = new DeleteItemSpec() .withPrimaryKey("Id", 120) .withConditionExpression("#ip = :val") .withNameMap(new NameMap() .with("#ip", "InPublication")) .withValueMap(new ValueMap() .withBoolean(":val", false)) .withReturnValues(ReturnValue.ALL_OLD); DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec); // Check the response. System.out.println("Printing item that was deleted..."); System.out.println(outcome.getItem().toJSONPretty()); } catch (Exception e) { System.err.println("Error deleting item in " + tableName); System.err.println(e.getMessage()); } }
private static void findProductsForPriceLessThanZero() { Table table = dynamoDB.getTable(tableName); Map<String, Object> expressionAttributeValues = new HashMap<String, Object>(); expressionAttributeValues.put(":pr", 100); ItemCollection<ScanOutcome> items = table.scan( "Price < :pr", //FilterExpression "Id, Title, ProductCategory, Price", //ProjectionExpression null, //ExpressionAttributeNames - not used in this example expressionAttributeValues); System.out.println("Scan of " + tableName + " for items with a price less than 100."); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); } }
private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) { Table table = dynamoDB.getTable(tableName); String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec() .withProjectionExpression("Message, ReplyDateTime, PostedBy") .withKeyConditionExpression("Id = :v_id") .withFilterExpression("PostedBy = :v_postedby") .withValueMap(new ValueMap() .withString(":v_id", replyId) .withString(":v_postedby", "User B")); ItemCollection<QueryOutcome> items = table.query(spec); System.out.println("\nfindRepliesUsingAFilterExpression results:"); Iterator<Item> iterator = items.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().toJSONPretty()); } }
public static void putItem( String issueId, String title, String description, String createDate, String lastUpdateDate, String dueDate, Integer priority, String status) { Table table = dynamoDB.getTable(tableName); Item item = new Item() .withPrimaryKey("IssueId", issueId) .withString("Title", title) .withString("Description", description) .withString("CreateDate", createDate) .withString("LastUpdateDate", lastUpdateDate) .withString("DueDate", dueDate) .withNumber("Priority", priority) .withString("Status", status); table.putItem(item); }
@Override public void writePacket(String deviceId, Date time, MAVLinkPacket packet) throws IOException { if (deviceId == null || deviceId.isEmpty() || time == null || packet == null) { return; } Table table = dynamoDB.getTable(tableName); table.putItem(new Item().withPrimaryKey(ATTR_DEVICE_ID, deviceId, ATTR_TIME, time.getTime()) .withNumber(ATTR_MSG_ID, packet.msgid) .withJSON(ATTR_MESSAGE, toJSON(packet))); }
public static final Table getTable() { if (null != table) { return table; } table = new DynamoDB(getClient()).getTable(getTableName()); System.out.println("Got DynamoDB table..."); return table; }
@Override public Void saveRelation(Group group, String relationHashKey, String relationRangeKey) { Item item = new Item() .withString(GroupStorage.SUBJECT_KEY, relationHashKey) .withString(GroupStorage.OBJECT_RELATION_KEY, relationRangeKey); Table table = dynamoDB.getTable(groupGraphTableName); DynamoDbCommand<PutItemOutcome> cmd = new DynamoDbCommand<>("saveRelation", () -> table.putItem(item), () -> { throw new RuntimeException("saveRelation"); }, dynamodbGraphWriteHystrix, metrics); PutItemOutcome outcome = cmd.execute(); logger.info("{} /dynamodb_put_item_result=[{}]", kvp("op", "saveRelation", "appkey", group.getKey(), "hash_key", relationHashKey, "range_key", relationRangeKey, "result", "ok"), outcome.getPutItemResult().toString()); return null; }
@Override public Void removeRelation(Group group, String relationHashKey, String relationRangeKey) { Table table = dynamoDB.getTable(groupGraphTableName); final PrimaryKey key = new PrimaryKey( GroupStorage.SUBJECT_KEY, relationHashKey, GroupStorage.OBJECT_RELATION_KEY, relationRangeKey ); DynamoDbCommand<DeleteItemOutcome> cmd = new DynamoDbCommand<>("removeRelation", () -> table.deleteItem(key), () -> { throw new RuntimeException("removeRelation"); }, dynamodbGraphWriteHystrix, metrics); final DeleteItemOutcome deleteItemOutcome = cmd.execute(); logger.info("{} /dynamodb_remove_item_result=[{}]", kvp("op", "removeRelation", "appkey", group.getKey(), "hash_key", relationHashKey, "range_key", relationRangeKey, "result", "ok"), deleteItemOutcome.getDeleteItemResult().toString()); return null; }
@Override public boolean queryRelationExists(String relationHashKey, String relationRangeKey) { Table table = dynamoDB.getTable(this.groupGraphTableName); QuerySpec querySpec = new QuerySpec() .withKeyConditionExpression("subject = :k_subject and object_relation = :k_object_relation") .withValueMap(new ValueMap() .withString(":k_subject", relationHashKey) .withString(":k_object_relation", relationRangeKey) ) .withMaxResultSize(1) .withConsistentRead(true); DynamoDbCommand<ItemCollection<QueryOutcome>> cmd = new DynamoDbCommand<>("queryRelation", () -> queryTable(table, querySpec), () -> { throw new RuntimeException("queryRelation"); }, dynamodbNamespaceGraphQueryHystrix, metrics); // can't use getLastLowLevelResult directly; it's false unless the outcome is iterated first :| return cmd.execute().iterator().hasNext(); }