@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 Map<String, AttributeValue> getNodes(WebsiteModel websiteModel) { try { ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(websiteModel); Item item = new Item().withJSON(Utils.params.nodes, string); return InternalUtils.toAttributeValues(item); } catch (JsonProcessingException e) { LOG.error(e.getMessage()); } return new HashMap<>(); }
protected void readStateInternal(final Object state, final Class<?> stateClass, final Item item, final ObjectMapper mapper) { try { if (!state.getClass().equals(stateClass)) { throw new IllegalArgumentException(String.format("State class (%s) did not match expected class (%s), Storage Extension should override generatePutItem method", state.getClass().getName(), stateClass.getName())); } mapper.readerForUpdating(state).readValue(item.getJSON(DynamoDBUtils.FIELD_NAME_DATA)); } catch (IOException e) { throw new UncheckedException(e); } }
@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; }
@Override public int next() { Stopwatch watch = Stopwatch.createStarted(); topLevelState.reset(); int count = 0; Page<Item, ?> page; while (resultIter.hasNext()) { page = resultIter.next(); for (Item item : page) { int rowCount = count++; for (Map.Entry<String, Object> attribute : item.attributes()) { String name = attribute.getKey(); Object value = attribute.getValue(); SchemaPath column = getSchemaPath(name); topLevelState.setColumn(column); handleTopField(rowCount, name, value, topLevelState); } } } topLevelState.setRowCount(count); LOG.debug("Took {} ms to get {} records", watch.elapsed(TimeUnit.MILLISECONDS), count); return count; }
protected void verify(List<Map<String, Object>> rows, Item... items) { assertEquals("Wrong number of expected rows!" + "\nExpected: " + toString(items) + "\nGot rows: " + rows, items.length, rows.size()); for (int i = 0; i < items.length; i++) { Map<String, Object> row = rows.get(i); Item item = items[i]; assertEquals("Wrong number of fields in row! Got row: " + row + "\nExpected: " + item, row.size(), item.asMap().size()); for (Map.Entry<String, Object> field : row.entrySet()) { String name = field.getKey(); Object o = field.getValue(); if (o instanceof Text) { o = o.toString(); } if (item.get(name) instanceof Number) { equalsNumber(item, name, row); } else if (o instanceof byte[]) { assertArrayEquals("Array mismatch for: " + name, (byte[]) item.get(name), (byte[]) o); } else { assertEquals("Mismatch for: " + name, item.get(name), o); } } } }
@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); }
public Item decrypt(Item item) { if ( null == item ) return null; boolean hasKey = null != _keyProvider && _keyProvider.getKey(1) != null; Item result = new Item(); for ( Map.Entry<String, Object> entry : item.asMap().entrySet() ) { Object val = entry.getValue(); if ( hasKey && val instanceof byte[] ) { // ALWAYS *try* to decrypt byte[] (in case this field was previously encrypted): try { val = decrypt((byte[])val, Object.class); } catch ( Throwable ex ) { if ( requiresEncryption(entry.getKey()) ) { LOG.warn("Failed to decrypt '"+entry.getKey()+"'", ex); } } } result.with(entry.getKey(), val); } return result; }
/** * 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); } }
@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) {} }
@Override public Object handleRequest(DynamodbEvent input, Context context) { context.getLogger().log("Input: " + input); DynamoDB dynamodb = new DynamoDB(Regions.US_WEST_2); for (DynamodbStreamRecord record : input.getRecords()) { Map<String, AttributeValue> newData = record.getDynamodb().getNewImage(); if (newData == null) continue; // ignore deletes Item item = Item.fromMap(InternalCalls.toSimpleMapValue(newData)); DataTransformer.PLAYER_STATS_TRANSFORMER.transform(item, dynamodb); } return true; }
/** * Reads a page from a "shared" DynamoDB table. Shared tables are tables that have global secondary indexes * and can contain the objects of multiple apps. * @param <P> type of object * @param appid the app identifier (name) * @param pager a {@link Pager} * @return the id of the last object on the page, or null. */ public static <P extends ParaObject> List<P> readPageFromSharedTable(String appid, Pager pager) { LinkedList<P> results = new LinkedList<>(); if (StringUtils.isBlank(appid)) { return results; } Page<Item, QueryOutcome> items = queryGSI(appid, pager); if (items != null) { for (Item item : items) { P obj = ParaObjectUtils.setAnnotatedFields(item.asMap()); if (obj != null) { results.add(obj); } } } if (!results.isEmpty() && pager != null) { pager.setLastKey(results.peekLast().getId()); } return results; }
private static Page<Item, QueryOutcome> queryGSI(String appid, Pager p) { Pager pager = (p != null) ? p : new Pager(); Index index = getSharedIndex(); QuerySpec spec = new QuerySpec(). withMaxPageSize(pager.getLimit()). withMaxResultSize(pager.getLimit()). withKeyConditionExpression(Config._APPID + " = :aid"). withValueMap(new ValueMap().withString(":aid", appid)); if (!StringUtils.isBlank(pager.getLastKey())) { spec = spec.withExclusiveStartKey(new KeyAttribute(Config._APPID, appid), // HASH/PARTITION KEY new KeyAttribute(Config._ID, pager.getLastKey()), // RANGE/SORT KEY new KeyAttribute(Config._KEY, getKeyForAppid(pager.getLastKey(), appid))); // TABLE PRIMARY KEY } return index != null ? index.query(spec).firstPage() : null; }
/** * Test of createTable method, of class MySQLBackendImpl. */ @Test public void testPutItems() { System.out.println("Testing MySQLBackend.createTable (within first database"); try { backend.setDynamoDB(mockDynamoDB); backend.createTable(tableName, primaryKey); ArrayList<Item> aggregation = new ArrayList<Item>(); Item item = new Item().withString("field", "value"); aggregation.add(item); backend.putItems(tableName, aggregation); } catch (Exception e) { fail(e.getMessage()); } finally { assertTrue(backend.getDynamoDB().getTable(tableName) != null); } // try catch finally }
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"); 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 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()); } }
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 void saveTwitterStatus(String json) { // Workaround until https://github.com/aws/aws-sdk-java/issues/1189 is fixed json = json.replaceAll(":\"\"", ":null"); System.out.println("\n\njson: " + json); getTable().putItem(Item.fromJSON(json)); }
@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 Optional<Group> loadByKey(String key) { Table table = dynamoDB.getTable(this.groupTableName); QuerySpec querySpec = new QuerySpec() .withKeyConditionExpression(HASH_KEY + " = :k_app_key") .withValueMap(new ValueMap() .withString(":k_app_key", key) ) .withMaxResultSize(1) .withConsistentRead(true); DynamoDbCommand<ItemCollection<QueryOutcome>> cmd = new DynamoDbCommand<>("loadByKey", () -> queryTable(table, querySpec), () -> { throw new RuntimeException("loadByKey"); }, dynamodbNamespaceGraphQueryHystrix, metrics); final ItemCollection<QueryOutcome> items = cmd.execute(); final IteratorSupport<Item, QueryOutcome> iterator = items.iterator(); if (iterator.hasNext()) { return Optional.of(GroupSupport.toGroup(iterator.next().getString("json"))); } return Optional.empty(); }