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

The following examples show how to use com.amazonaws.services.dynamodbv2.document.Item. These examples are extracted from open source projects. 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 Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: 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 2
Source Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: 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 3
Source Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: 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 4
@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 5
Source Project: aws-dynamodb-examples   Source File: MoviesItemOps01.java    License: 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 6
@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 7
Source Project: podyn   Source File: DynamoDBTableReplicator.java    License: 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 8
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 9
Source Project: aws-doc-sdk-examples   Source File: TryDaxHelper.java    License: 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 10
Source Project: aws-doc-sdk-examples   Source File: TryDaxTests.java    License: 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 11
Source Project: aws-dynamodb-examples   Source File: DocumentAPIScan.java    License: 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 12
Source Project: aws-doc-sdk-examples   Source File: SampleDataTryQuery.java    License: 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 13
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 14
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 15
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 16
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 17
Source Project: aws-doc-sdk-examples   Source File: DocumentAPIScan.java    License: 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 18
Source Project: aws-doc-sdk-examples   Source File: DocumentAPIQuery.java    License: 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 19
Source Project: aws-doc-sdk-examples   Source File: DocumentAPIQuery.java    License: 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 20
Source Project: aws-doc-sdk-examples   Source File: DocumentAPIQuery.java    License: 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 21
Source Project: aws-doc-sdk-examples   Source File: DocumentAPIQuery.java    License: 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 22
Source Project: athenz   Source File: DynamoDBSSHRecordStoreConnection.java    License: 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 23
/**
 * 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 24
Source Project: aws-dynamodb-examples   Source File: MoviesScan.java    License: 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 25
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 26
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 Project: xyz-hub   Source File: DynamoSpaceConfigClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the relationship between a space and their packages
 *
 * @param marker used in logs
 * @param space the spaceId which is being deleted
 */
private void deleteSpaceFromPackage(Marker marker, Space space) throws AmazonDynamoDBException {
  if (space == null) {
    return;
  }

  try {
    logger.info(marker, "Removing packages from space ID: {}", space.getId());
    final List<String> packagesList = new ArrayList<>();

    if (space.getPackages() != null) {
      packagesList.addAll(space.getPackages());
    } else {
      final GetItemSpec spec = new GetItemSpec().withPrimaryKey("id", space.getId()).withProjectionExpression("packages");
      final Item item = spaces.getItem(spec);
      if (item != null && item.isPresent("packages")) {
        packagesList.addAll(item.getList("packages"));
      }
    }

    logger.info(marker, "Packages {} to be removed from space ID: {}", packagesList, space.getId());
    for (String packageName : packagesList) {
      packages.deleteItem("packageName", packageName, "spaceId", space.getId());
    }
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure deleting space ID: {} from the packages table", space.getId(), e);
    throw e;
  }
}
 
Example 28
@Override
public void run() {
    System.out.println("Scanning " + tableName + " segment " + segment + " out of " + totalSegments + " segments " + itemLimit + " items at a time...");
    int totalScannedItemCount = 0;

    Table table = dynamoDB.getTable(tableName);
    
    try {
        ScanSpec spec = new ScanSpec()
            .withMaxResultSize(itemLimit)
            .withTotalSegments(totalSegments)
            .withSegment(segment);
        
        ItemCollection<ScanOutcome> items = table.scan(spec);
        Iterator<Item> iterator = items.iterator();
          
        Item currentItem = null;
        while (iterator.hasNext()) {
            totalScannedItemCount++;
            currentItem = iterator.next();
            System.out.println(currentItem.toString());
        }    
            
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } finally {
        System.out.println("Scanned " + totalScannedItemCount 
            + " items from segment " + segment + " out of " 
            + totalSegments + " of " + tableName);
    }
}
 
Example 29
private DefaultInstalledAppContext contextFromItem(Item item) {
    Permissions permissions = new Permissions();
    List<?> permissionsList = item.getList("permissions");
    if (permissionsList != null) {
        for (Object permission : permissionsList) {
            permissions.add((String) permission);
        }
    }

    ConfigMap config;
    try {
        config = mapper.readValue(item.getString("config"), ConfigMap.class);
    } catch (IOException e) {
        log.error("problem converting stored config JSON ("
            + item.getString("config") + ") back to config", e);
        config = new ConfigMap();
    }
    InstalledApp installedApp = new InstalledApp()
        .installedAppId(item.getString("installedAppId"))
        .locationId(item.getString("locationId"))
        .config(config)
        .permissions(permissions);
    Token token = new Token()
        .accessToken(item.getString("authToken")) // named to match NodeSDK version
        .accessTokenExpiration(Instant.ofEpochMilli(item.getLong("authTokenExpiration")))
        .refreshToken(item.getString("refreshToken"))
        .refreshTokenExpiration(Instant.ofEpochMilli(item.getLong("refreshTokenExpiration")));

    return new DefaultInstalledAppContext()
        .installedApp(installedApp)
        .token(token);
}
 
Example 30
@Override
public Stream<DefaultInstalledAppContext> get() {
    Table table = dynamoDB.getTable(tableName);
    ItemCollection<ScanOutcome> scanItems = table.scan();
    Iterator<Item> iter = scanItems.iterator();
    Iterable<Item> iterable = () -> iter;
    return StreamSupport.stream(iterable.spliterator(), false)
        .map(item -> refreshed(contextFromItem(item)));
}