com.amazonaws.services.dynamodbv2.document.Item Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.document.Item. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SampleDataTryQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String tableName, String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;
        long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        Table table = dynamoDB.getTable(tableName);

        QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("Id = :v1 and ReplyDateTime > :v2")
            .withValueMap(new ValueMap().withString(":v1", replyId).withString(":v2", twoWeeksAgoStr))
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        ItemCollection<QueryOutcome> items = table.query(querySpec);
        Iterator<Item> iterator = items.iterator();

        System.out.println("Query: printing results...");

        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }
    }
 
Example #2
Source File: DynamoDBInstallAppContextStoreTest.java    From smartapp-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getDoesNotRefreshNewToken() throws JsonProcessingException {
    token.accessTokenExpiration(now.plus(Duration.ofMinutes(61)));
    Item item = new Item()
        .withPrimaryKey("installedAppId", context.getInstalledAppId())
        .with("authToken", token.getAccessToken())
        .with("authTokenExpiration", token.getAccessTokenExpiration().toEpochMilli())
        .with("refreshToken", token.getRefreshToken())
        .with("refreshTokenExpiration", token.getRefreshTokenExpiration().toEpochMilli())
        .with("locationId", installedApp.getLocationId())
        .with("config", mapper.writeValueAsString(installedApp.getConfig()))
        .with("permissions", installedApp.getPermissions());

    when(table.getItem("installedAppId", (Object) "installed app id")).thenReturn(item);

    DefaultInstalledAppContext result = tester.get("installed app id");
    assertEquals(context, result);

    verify(tokenRefreshService, never()).refresh(any());
}
 
Example #3
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime <= :v_reply_dt_tm")
            .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_reply_dt_tm", twoWeeksAgoStr));

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesInLast15DaysWithConfig results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

    }
 
Example #4
Source File: MoviesItemOps01.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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();
        }       
    }
 
Example #5
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long startDateMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        long endDateMilli = (new Date()).getTime() - (5L * 24L * 60L * 60L * 1000L);
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime between :v_start_dt and :v_end_dt")
            .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_start_dt", startDate)
                .withString(":v_end_dt", endDate));

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }
    }
 
Example #6
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #7
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withKeyConditionExpression("Id = :v_id")
            .withValueMap(new ValueMap().withString(":v_id", replyId)).withMaxPageSize(1);

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesForAThreadSpecifyOptionalLimit results:");

        // Process each page of results
        int pageNum = 0;
        for (Page<Item, QueryOutcome> page : items.pages()) {

            System.out.println("\nPage: " + ++pageNum);

            // Process each item on the current page
            Iterator<Item> item = page.iterator();
            while (item.hasNext()) {
                System.out.println(item.next().toJSONPretty());
            }
        }
    }
 
Example #8
Source File: DynamoDBInstalledAppContextStore.java    From smartapp-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void add(DefaultInstalledAppContext context) {
    Table table = dynamoDB.getTable(tableName);
    InstalledApp installedApp = context.getInstalledApp();
    Token token = context.getToken();
    String configJson;
    try {
        configJson = mapper.writeValueAsString(installedApp.getConfig());
    } catch (JsonProcessingException e) {
        log.error("problem mapping config as JSON", e);
        configJson = null;
    }
    Item item = new Item().withPrimaryKey("installedAppId", context.getInstalledAppId())
            .with("authToken", token.getAccessToken()) // named to match NodeSDK version
            .with("authTokenExpiration", token.getAccessTokenExpiration().toEpochMilli())
            .with("refreshToken", token.getRefreshToken())
            .with("refreshTokenExpiration", token.getRefreshTokenExpiration().toEpochMilli())
            .with("locationId", installedApp.getLocationId()).with("config", configJson)
            .with("permissions", installedApp.getPermissions());
    PutItemOutcome outcome = table.putItem(item);
    if (log.isDebugEnabled()) {
        log.debug("put item outcome = " + outcome);
        log.debug("put item outcome.getItem() = " + outcome.getItem());
        log.debug("put item outcome.getPutItemResult() = " + outcome.getPutItemResult());
    }
}
 
Example #9
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void getSpace(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  try {
    logger.info(marker, "Getting space with ID: {}", spaceId);
    final Item item = spaces.getItem("id", spaceId);

    if (item == null) {
      logger.info(marker, "Getting space with ID: {} returned null", spaceId);
      handler.handle(Future.succeededFuture(null));
      return;
    }

    final Space space = Json.decodeValue(item.toJSON(), Space.class);
    if (space != null) {
      logger.info(marker, "Space ID: {} with title: \"{}\" has been decoded", spaceId, space.getTitle());
    } else {
      logger.info(marker, "Space ID: {} has been decoded to null", spaceId);
    }
    handler.handle(Future.succeededFuture(space));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure during getting a space from DynamoDB", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example #10
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Stores the relation between package name and spaces in Dynamo
 *
 * @param marker used in logs
 * @param space the space which is being stored
 */
private void storeSpaceIntoPackages(Marker marker, Space space) throws AmazonDynamoDBException {
  if (space == null) {
    return;
  }

  try {
    logger.info(marker, "Inserting packages {} into the packages table for space ID: {}", space.getPackages(), space.getId());
    if (space.getPackages() != null) {
      for (String packageName : space.getPackages()) {
        logger.info(marker, "Adding space ID: {} into package: {}", space.getId(), packageName);
        final Map<String, Object> packagesMap = new HashMap<>();
        packagesMap.put("packageName", packageName);
        packagesMap.put("spaceId", space.getId());

        packages.putItem(Item.fromMap(packagesMap));
      }
    }
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure storing space ID: {} into the packages table", space.getId(), e);
    throw e;
  }
}
 
Example #11
Source File: DynamoSpaceConfigClient.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
@Override
public void storeSpace(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  try {
    logger.info(marker, "Storing space with ID: {}", space.getId());

    final Map<String, Object> itemData = XyzSerializable.STATIC_MAPPER.get().convertValue(space, new TypeReference<Map<String, Object>>() {});
    itemData.put("shared", space.isShared() ? 1 : 0); // shared value must be a number because it's also used as index

    sanitize(itemData);
    spaces.putItem(Item.fromMap(itemData));

    deleteSpaceFromPackage(marker, space);
    storeSpaceIntoPackages(marker, space);

    logger.info(marker, "Space with ID: {} has been successfully stored", space.getId());
    handler.handle(Future.succeededFuture(space));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure storing a space into DynamoDB", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example #12
Source File: DynamoDBSSHRecordStoreConnection.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Override
public SSHCertRecord getSSHCertRecord(String instanceId, String service) {

    final String primaryKey = getPrimaryKey(instanceId, service);
    try {
        Item item = table.getItem(KEY_PRIMARY, primaryKey);
        if (item == null) {
            LOGGER.error("DynamoDB Get Error for {}: item not found", primaryKey);
            return null;
        }
        SSHCertRecord certRecord = new SSHCertRecord();
        certRecord.setInstanceId(instanceId);
        certRecord.setService(service);
        certRecord.setPrincipals(item.getString(KEY_PRINCIPALS));
        certRecord.setClientIP(item.getString(KEY_CLIENT_IP));
        certRecord.setPrivateIP(item.getString(KEY_PRIVATE_IP));
        return certRecord;
    } catch (Exception ex) {
        LOGGER.error("DynamoDB Get Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
        return null;
    }
}
 
Example #13
Source File: DocumentAPIScan.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findProductsForPriceLessThanOneHundred() {

        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());
        }
    }
 
Example #14
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void createItems() {

        Table table = dynamoDB.getTable(tableName);
        try {

            Item item = new Item().withPrimaryKey("Id", 120).withString("Title", "Book 120 Title")
                .withString("ISBN", "120-1111111111")
                .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author12", "Author22")))
                .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                .withBoolean("InPublication", false).withString("ProductCategory", "Book");
            table.putItem(item);

            item = new Item().withPrimaryKey("Id", 121).withString("Title", "Book 121 Title")
                .withString("ISBN", "121-1111111111")
                .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author21", "Author 22")))
                .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                .withBoolean("InPublication", true).withString("ProductCategory", "Book");
            table.putItem(item);

        }
        catch (Exception e) {
            System.err.println("Create items failed.");
            System.err.println(e.getMessage());

        }
    }
 
Example #15
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void retrieveItem() {
    Table table = dynamoDB.getTable(tableName);

    try {

        Item item = table.getItem("Id", 120, "Id, ISBN, Title, Authors", null);

        System.out.println("Printing item after retrieving it....");
        System.out.println(item.toJSONPretty());

    }
    catch (Exception e) {
        System.err.println("GetItem failed.");
        System.err.println(e.getMessage());
    }

}
 
Example #16
Source File: DynamoDBBackendImplTest.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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
}
 
Example #17
Source File: MoviesScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #18
Source File: DocumentAPIParallelScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #19
Source File: CreateTablesLoadData.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #20
Source File: DocumentAPIScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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());
    }    
}
 
Example #21
Source File: TryDaxTests.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
void scanTest(String tableName, DynamoDB client, int iterations) {
    long startTime, endTime;
    System.out.println("Scan test - all items in the table");
    Table table = client.getTable(tableName);

    for (int i = 0; i < iterations; i++) {
        startTime = System.nanoTime();
        ItemCollection<ScanOutcome> items = table.scan();
        try {

            Iterator<Item> iter = items.iterator();
            while (iter.hasNext()) {
                iter.next();
            }
        } catch (Exception e) {
            System.err.println("Unable to scan table:");
            e.printStackTrace();
        }
        endTime = System.nanoTime();
        printTime(startTime, endTime, iterations);
    }
}
 
Example #22
Source File: TryDaxHelper.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
void writeData(String tableName, DynamoDB client, int pkmax, int skmax) {
    Table table = client.getTable(tableName);
    System.out.println("Writing data to the table...");

    int stringSize = 1000;
    StringBuilder sb = new StringBuilder(stringSize);
    for (int i = 0; i < stringSize; i++) {
        sb.append('X');
    }
    String someData = sb.toString();

    try {
        for (Integer ipk = 1; ipk <= pkmax; ipk++) {
            System.out.println(("Writing " + skmax + " items for partition key: " + ipk));
            for (Integer isk = 1; isk <= skmax; isk++) {
                 table.putItem(new Item()
                         .withPrimaryKey("pk", ipk, "sk", isk)
                         .withString("someData", someData));
            }
        }
    } catch (Exception e) {
        System.err.println("Unable to write item:");
        e.printStackTrace();
    }
}
 
Example #23
Source File: DocumentAPIGlobalSecondaryIndexExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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);
    }
 
Example #24
Source File: DocumentAPIParallelScan.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #25
Source File: DynamoDBTableReplicator.java    From podyn with Apache License 2.0 6 votes vote down vote up
public TableRow rowWithJsonbFromDynamoRecord(Map<String,AttributeValue> dynamoItem) {
	TableRow row = tableSchema.createRow();
	Item item = new Item();

	for(Map.Entry<String, AttributeValue> entry : dynamoItem.entrySet()) {
		String keyName = entry.getKey();
		String columnName = dynamoKeyToColumnName(keyName);
		TableColumn column = tableSchema.getColumn(columnName);
		AttributeValue typedValue = entry.getValue();
		TableColumnValue columnValue = columnValueFromDynamoValue(typedValue);

		if (column != null) {
			row.setValue(columnName, columnValue);
		}

		item.with(keyName, columnValue.datum);
	}

	row.setValue("data", item.toJSON());

	return row;
}
 
Example #26
Source File: GettingStartedLoadData.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
 
Example #27
Source File: DynamoDBLockProviderIntegrationTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
protected void assertUnlocked(String lockName) {
    Item lockItem = getLockItem(lockName);
    assertThat(fromIsoString(lockItem.getString(LOCK_UNTIL))).isBeforeOrEqualTo(now());
    assertThat(fromIsoString(lockItem.getString(LOCKED_AT))).isBeforeOrEqualTo(now());
    assertThat(lockItem.getString(LOCKED_BY)).isNotEmpty();
}
 
Example #28
Source File: MCAWS.java    From aws-big-data-blog with Apache License 2.0 5 votes vote down vote up
public static void dynamoInsertJson(String ccdJson, String mirthTable, String mirthId, String mirthDate) {
       System.out.println( "Performing insert into DynamoDB" );
String firstName = "NONE";
String lastName = "NONE";
String dob = "NONE";
String docType = "ccda";

       AmazonDynamoDBClient client = new AmazonDynamoDBClient();
       client.withRegion(Regions.US_WEST_2);
       DynamoDB dynamoDB = new DynamoDB(client);
       Table table = dynamoDB.getTable(mirthTable);

//System.out.println(ccdJson);

       try {
       JSONObject obj = new JSONObject(ccdJson);

       firstName = obj.getJSONObject("data").getJSONObject("demographics").getJSONObject("name").getString("first");
       lastName = obj.getJSONObject("data").getJSONObject("demographics").getJSONObject("name").getString("last");
       dob = obj.getJSONObject("data").getJSONObject("demographics").getJSONObject("dob").getJSONObject("point").getString("date");

       //System.out.println(firstName);
       } catch (org.json.JSONException e) { System.out.println("JSON ERROR"); }

ccdJson = ccdJson.replaceAll("\"\"","\"NONE\"");

       Item item = 
           new Item()
               .withPrimaryKey("mirthid", mirthId)
               .withString("mirthdate", mirthDate)
	.withString("type", docType)
               .withString("FirstName", firstName)
               .withString("LastName", lastName)
               .withString("DOB", dob)
               .withString("Processed", "N")
               .withJSON("document", ccdJson);

       table.putItem(item);
   }
 
Example #29
Source File: MoviesItemOps01.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        final Map<String, Object> infoMap = new HashMap<String, Object>();
        infoMap.put("plot", "Nothing happens at all.");
        infoMap.put("rating", 0);

        try {
            System.out.println("Adding a new item...");
            PutItemOutcome outcome = table
                .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap));

            System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

        }
        catch (Exception e) {
            System.err.println("Unable to add item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }
 
Example #30
Source File: MoviesItemOps02.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        GetItemSpec spec = new GetItemSpec().withPrimaryKey("year", year, "title", title);

        try {
            System.out.println("Attempting to read the item...");
            Item outcome = table.getItem(spec);
            System.out.println("GetItem succeeded: " + outcome);

        }
        catch (Exception e) {
            System.err.println("Unable to read item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }