Java Code Examples for com.amazonaws.services.dynamodbv2.AmazonDynamoDB

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDB. 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
/**
 * Creates a {@link Bean}.
 * 
 * @param <T>
 *            The type of the repository.
 * @param repositoryType
 *            The class representing the repository.
 * @param beanManager
 *            The BeanManager instance.
 * @return The bean.
 */
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {

	// Determine the amazondbclient bean which matches the qualifiers of the
	// repository.
	Bean<AmazonDynamoDB> amazonDynamoDBBean = amazonDynamoDBs.get(qualifiers);

	// Determine the dynamo db mapper configbean which matches the
	// qualifiers of the repository.
	Bean<DynamoDBMapperConfig> dynamoDBMapperConfigBean = dbMapperConfigs.get(qualifiers);
	
	if (amazonDynamoDBBean == null) {
		throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
				AmazonDynamoDBClient.class.getName(), qualifiers));
	}
	
	Bean<DynamoDBOperations> dynamoDBOperationsBean = dynamoDBOperationss.get(qualifiers);

	
	// Construct and return the repository bean.
	return new DynamoDBRepositoryBean<T>(beanManager, amazonDynamoDBBean, dynamoDBMapperConfigBean,dynamoDBOperationsBean,qualifiers,
			repositoryType);
}
 
Example 2
Source Project: presto   Source File: KinesisShardCheckpointer.java    License: Apache License 2.0 6 votes vote down vote up
public KinesisShardCheckpointer(
        AmazonDynamoDB dynamoDBClient,
        String dynamoDBTable,
        KinesisSplit kinesisSplit,
        String logicalProcessName,
        int currentIterationNumber,
        long checkpointIntervalMS,
        long dynamoReadCapacity,
        long dynamoWriteCapacity)
{
    this(new KinesisClientLeaseManager(dynamoDBTable, dynamoDBClient),
            kinesisSplit,
            logicalProcessName,
            currentIterationNumber,
            checkpointIntervalMS,
            dynamoReadCapacity,
            dynamoWriteCapacity);
}
 
Example 3
Source Project: presto-kinesis   Source File: KinesisShardCheckpointer.java    License: Apache License 2.0 6 votes vote down vote up
public KinesisShardCheckpointer(AmazonDynamoDB dynamoDBClient,
        String dynamoDBTable,
        KinesisSplit kinesisSplit,
        String logicalProcessName,
        int curIterationNumber,
        long checkpointIntervalMS,
        long dynamoReadCapacity,
        long dynamoWriteCapacity)
{
    this(new KinesisClientLeaseManager(dynamoDBTable, dynamoDBClient),
            kinesisSplit,
            logicalProcessName,
            curIterationNumber,
            checkpointIntervalMS,
            dynamoReadCapacity,
            dynamoWriteCapacity);
}
 
Example 4
public static void main(String[] args) throws GeneralSecurityException {
  final String mode = args[0];
  final String region = args[1];
  final String tableName = args[2];
  final String keyTableName = args[3];
  final String cmkArn = args[4];
  final String materialName = args[5];
  
  if (mode.equalsIgnoreCase("--setup")) {
    AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
    MetaStore.createTable(ddb, keyTableName, new ProvisionedThroughput(1L, 1L));
    return;
  }
  
  encryptRecord(tableName, keyTableName, region, cmkArn, materialName);
}
 
Example 5
Source Project: testcontainers-java   Source File: DynaliteContainerTest.java    License: MIT License 6 votes vote down vote up
private void runTest(AmazonDynamoDB client) {
    CreateTableRequest request = new CreateTableRequest()
            .withAttributeDefinitions(new AttributeDefinition(
                    "Name", ScalarAttributeType.S))
            .withKeySchema(new KeySchemaElement("Name", KeyType.HASH))
            .withProvisionedThroughput(new ProvisionedThroughput(
                10L, 10L))
            .withTableName("foo");


    client.createTable(request);

    final TableDescription tableDescription = client.describeTable("foo").getTable();

    assertNotNull("the description is not null", tableDescription);
    assertEquals("the table has the right name", "foo", tableDescription.getTableName());
    assertEquals("the name has the right primary key", "Name", tableDescription.getKeySchema().get(0).getAttributeName());
}
 
Example 6
public static void main(String[] args) throws GeneralSecurityException {
    final String cmkArn = args[0];
    final String region = args[1];
    final String encryptionContextTableName = args[2];

    AmazonDynamoDB ddb = null;
    AWSKMS kms = null;
    try {
        ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
        kms = AWSKMSClientBuilder.standard().withRegion(region).build();
        encryptRecord(cmkArn, encryptionContextTableName, ddb, kms);
    } finally {
        if (ddb != null) {
            ddb.shutdown();
        }
        if (kms != null) {
            kms.shutdown();
        }
    }
}
 
Example 7
Source Project: spring-data-dynamodb-examples   Source File: Application.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public CommandLineRunner multirepo(ConfigurableApplicationContext ctx, CustomerRepository jpaRepository,
		DeviceRepository dynamoDBRepository, AmazonDynamoDB amazonDynamoDB, DynamoDBMapper dynamoDBMapper,
		DynamoDBMapperConfig config) {
	return (args) -> {
		demoJPA(jpaRepository);

		CreateTableRequest ctr = dynamoDBMapper.generateCreateTableRequest(Device.class)
				.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
		TableUtils.createTableIfNotExists(amazonDynamoDB, ctr);
		TableUtils.waitUntilActive(amazonDynamoDB, ctr.getTableName());


		demoDynamoDB(dynamoDBRepository);

		ctx.close();
	};
}
 
Example 8
Source Project: serverless   Source File: DynamoDBUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static final AmazonDynamoDB getClient() {
    if (null != dynamodbClient) {
        return dynamodbClient;
    }

    String region = System.getenv("DYNAMODB_REGION");
    if (null == region) {
        System.err.println("Region is null, using default \"" + Regions.US_WEST_1 + "\"");
        region = Regions.US_WEST_1.name();
    }
    System.out.println("DynamoDB region: " + region);

    dynamodbClient = AmazonDynamoDBClientBuilder.standard()
            .withRegion(region)
            .build();
    
    System.out.println("Got DynamoDB client...");

    return dynamodbClient;
}
 
Example 9
Source Project: podyn   Source File: DynamoDBTableReplicator.java    License: Apache License 2.0 6 votes vote down vote up
public DynamoDBTableReplicator(
		AmazonDynamoDB dynamoDBClient,
		AmazonDynamoDBStreams streamsClient,
		AWSCredentialsProvider awsCredentialsProvider,
		ExecutorService executorService,
		TableEmitter emitter,
		String tableName) throws SQLException {
	this.dynamoDBClient = dynamoDBClient;
	this.streamsClient = streamsClient;
	this.awsCredentialsProvider = awsCredentialsProvider;
	this.executor = executorService;
	this.emitter = emitter;
	this.dynamoTableName = tableName;
	this.addColumnsEnabled = true;
	this.useCitus = false;
	this.useLowerCaseColumnNames = false;
	this.tableSchema = emitter.fetchSchema(this.dynamoTableName);
}
 
Example 10
private static CreateTableResult createTable(AmazonDynamoDB ddb, String tableName, String hashKeyName) {
    List<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
    attributeDefinitions.add(new AttributeDefinition(hashKeyName, ScalarAttributeType.S));

    List<KeySchemaElement> ks = new ArrayList<KeySchemaElement>();
    ks.add(new KeySchemaElement(hashKeyName, KeyType.HASH));

    ProvisionedThroughput provisionedthroughput = new ProvisionedThroughput(1000L, 1000L);

    CreateTableRequest request =
        new CreateTableRequest()
            .withTableName(tableName)
            .withAttributeDefinitions(attributeDefinitions)
            .withKeySchema(ks)
            .withProvisionedThroughput(provisionedthroughput);

    return ddb.createTable(request);
}
 
Example 11
@Test
public void testGetStoredETagExists() {
    AmazonDynamoDB dynamoDB = PowerMock.createMock(AmazonDynamoDB.class);
    Map<String, AttributeValue> resourceKey = new HashMap<String, AttributeValue>();
    resourceKey.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    // Get item
    dynamoDB.getItem(table, resourceKey);
    Map<String, AttributeValue> resourceResult = new HashMap<String, AttributeValue>();
    resourceResult.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    resourceResult.put(DynamoDBWorkerUtils.ETAG_KEY, new AttributeValue(eTag));
    GetItemResult result = new GetItemResult().withItem(resourceResult);
    PowerMock.expectLastCall().andReturn(result);
    PowerMock.replayAll();
    String resultETag = DynamoDBWorkerUtils.getStoredETag(dynamoDB, table, resource);
    assertEquals(eTag, resultETag);
    PowerMock.verifyAll();
}
 
Example 12
Source Project: athenz   Source File: DynamoDBCertRecordStoreFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CertRecordStore create(PrivateKeyStore keyStore) {

    final String tableName = System.getProperty(ZTSConsts.ZTS_PROP_CERT_DYNAMODB_TABLE_NAME);
    if (tableName == null || tableName.isEmpty()) {
        LOGGER.error("Cert Store DynamoDB table name not specified");
        throw new ResourceException(ResourceException.SERVICE_UNAVAILABLE, "DynamoDB table name not specified");
    }

    final String indexName = System.getProperty(ZTSConsts.ZTS_PROP_CERT_DYNAMODB_INDEX_CURRENT_TIME_NAME);
    if (indexName == null || indexName.isEmpty()) {
        LOGGER.error("Cert Store DynamoDB index current-time not specified");
        throw new ResourceException(ResourceException.SERVICE_UNAVAILABLE, "DynamoDB index current-time not specified");
    }

    ZTSClientNotificationSenderImpl ztsClientNotificationSender = new ZTSClientNotificationSenderImpl();
    AmazonDynamoDB client = getDynamoDBClient(ztsClientNotificationSender, keyStore);
    return new DynamoDBCertRecordStore(client, tableName, indexName, ztsClientNotificationSender);
}
 
Example 13
/**
 * Retrieves the stored ETag, if one exists, from DynamoDB.
 *
 * @param dynamoDB
 *            DynamoDB client configured with a region and credentials
 * @param table
 *            The resource table name
 * @param resource
 *            The URL String of the resource
 * @return The ETag String of the last copy processed or null if the resource has never been processed
 */
public static String getStoredETag(final AmazonDynamoDB dynamoDB, final String table, final String resource) {
    String oldETag;
    // Build key to retrieve item
    final Map<String, AttributeValue> resourceKey = new HashMap<String, AttributeValue>();
    resourceKey.put(MarsDynamoDBManager.RESOURCE_TABLE_HASH_KEY, new AttributeValue(resource));
    // Get item
    final GetItemResult result = dynamoDB.getItem(table, resourceKey);
    final Map<String, AttributeValue> item = result.getItem();
    if (item != null && item.containsKey(ETAG_KEY)) {
        // Item was found and contains ETag
        oldETag = item.get(ETAG_KEY).getS();
    } else {
        // Item was not found or did not contain ETag
        oldETag = null;
    }
    return oldETag;
}
 
Example 14
Source Project: aws-doc-sdk-examples   Source File: MoviesDeleteTable.java    License: Apache License 2.0 6 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");

        try {
            System.out.println("Attempting to delete table; please wait...");
            table.delete();
            table.waitForDelete();
            System.out.print("Success.");

        }
        catch (Exception e) {
            System.err.println("Unable to delete table: ");
            System.err.println(e.getMessage());
        }
    }
 
Example 15
/**
 * @return StreamArn
 */
public static String createTable(AmazonDynamoDB client, String tableName) {
    java.util.List<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
    attributeDefinitions.add(new AttributeDefinition().withAttributeName("Id").withAttributeType("N"));

    java.util.List<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
    keySchema.add(new KeySchemaElement().withAttributeName("Id").withKeyType(KeyType.HASH)); // Partition
                                                                                             // key

    ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(2L)
        .withWriteCapacityUnits(2L);

    StreamSpecification streamSpecification = new StreamSpecification();
    streamSpecification.setStreamEnabled(true);
    streamSpecification.setStreamViewType(StreamViewType.NEW_IMAGE);
    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
        .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema)
        .withProvisionedThroughput(provisionedThroughput).withStreamSpecification(streamSpecification);

    try {
        System.out.println("Creating table " + tableName);
        CreateTableResult result = client.createTable(createTableRequest);
        return result.getTableDescription().getLatestStreamArn();
    }
    catch (ResourceInUseException e) {
        System.out.println("Table already exists.");
        return describeTable(client, tableName).getTable().getLatestStreamArn();
    }
}
 
Example 16
Source Project: aws-dynamodb-encryption-java   Source File: MetaStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a DynamoDB Table with the correct properties to be used with a ProviderStore.
 *
 * @param ddb interface for accessing DynamoDB
 * @param tableName name of table that stores the meta data of the material.
 * @param provisionedThroughput required provisioned throughput of the this table.
 * @return result of create table request.
 */
public static CreateTableResult createTable(final AmazonDynamoDB ddb, final String tableName,
        final ProvisionedThroughput provisionedThroughput) {
    return ddb.createTable(Arrays.asList(new AttributeDefinition(DEFAULT_HASH_KEY,
            ScalarAttributeType.S), new AttributeDefinition(DEFAULT_RANGE_KEY,
                    ScalarAttributeType.N)), tableName, Arrays.asList(new KeySchemaElement(
                            DEFAULT_HASH_KEY, KeyType.HASH), new KeySchemaElement(DEFAULT_RANGE_KEY,
                                    KeyType.RANGE)), provisionedThroughput);

}
 
Example 17
Source Project: dynamodb-transactions   Source File: TransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the transaction table exists and has the correct schema.
 * 
 * @param client
 * @param transactionTableName
 * @param transactionImagesTableName
 * @throws ResourceInUseException if the table exists but has the wrong schema
 * @throws ResourceNotFoundException if the table does not exist
 */
public static void verifyTransactionTablesExist(AmazonDynamoDB client, String transactionTableName, String transactionImagesTableName) {
    String state = new TableHelper(client).verifyTableExists(transactionTableName, TRANSACTIONS_TABLE_ATTRIBUTES, TRANSACTIONS_TABLE_KEY_SCHEMA, null/*localIndexes*/);
    if(! "ACTIVE".equals(state)) {
        throw new ResourceInUseException("Table " + transactionTableName + " is not ACTIVE");
    }
    
    state = new TableHelper(client).verifyTableExists(transactionImagesTableName, TRANSACTION_IMAGES_TABLE_ATTRIBUTES, TRANSACTION_IMAGES_TABLE_KEY_SCHEMA, null/*localIndexes*/);
    if(! "ACTIVE".equals(state)) {
        throw new ResourceInUseException("Table " + transactionImagesTableName + " is not ACTIVE");
    }
}
 
Example 18
Source Project: beam   Source File: DynamoDBIOTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
static AmazonDynamoDB getDynamoDBClient() {
  // Note: each test case got to have their own dynamo client obj, can't be shared
  // Otherwise will run into connection pool issue
  return AmazonDynamoDBClientBuilder.standard()
      .withEndpointConfiguration(
          localStackContainer.getEndpointConfiguration(LocalStackContainer.Service.DYNAMODB))
      .withCredentials(localStackContainer.getDefaultCredentialsProvider())
      .build();
}
 
Example 19
Source Project: Cheddar   Source File: DynamoDbTemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreateItem_withUniqueConstraintAndDuplicateWithDifferentCase() throws Exception {
    // Given
    final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
    final UniqueConstraint uniqueConstraint = new UniqueConstraint("stringProperty");
    itemConfiguration.registerUniqueConstraints(Arrays.asList(uniqueConstraint));
    final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
    when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(mockDatabaseSchemaHolder);
    final AmazonDynamoDB mockAmazonDynamoDbClient = mock(AmazonDynamoDB.class);
    dynamoDbTemplate.initialize(mockAmazonDynamoDbClient);
    when(mockAmazonDynamoDbClient.putItem(any(PutItemRequest.class)))
            .thenThrow(ConditionalCheckFailedException.class);
    final StubItem stubItem = new StubItem();
    stubItem.setId(randomId());
    final String stringPropertyValue = randomString(10);
    stubItem.setStringProperty(stringPropertyValue.toLowerCase());

    // When
    ItemConstraintViolationException actualException = null;
    try {
        dynamoDbTemplate.create(stubItem);
    } catch (final ItemConstraintViolationException e) {
        actualException = e;
    }

    // Then
    final ArgumentCaptor<PutItemRequest> putItemRequestArgumentCaptor = ArgumentCaptor
            .forClass(PutItemRequest.class);
    verify(mockAmazonDynamoDbClient, times(1)).putItem(putItemRequestArgumentCaptor.capture());
    final PutItemRequest putItemRequest1 = putItemRequestArgumentCaptor.getValue();
    assertEquals(schemaName + "-indexes." + tableName, putItemRequest1.getTableName());
    assertEquals(2, putItemRequest1.getItem().size());
    assertEquals(new AttributeValue("stringProperty"), putItemRequest1.getItem().get("property"));
    assertEquals(new AttributeValue(stringPropertyValue.toUpperCase()), putItemRequest1.getItem().get("value"));
    assertEquals(new ExpectedAttributeValue(false), putItemRequest1.getExpected().get("value"));
    assertNotNull(actualException);
    verify(mockAmazonDynamoDbClient, never()).deleteItem(any(DeleteItemRequest.class));
}
 
Example 20
Source Project: smartapp-sdk-java   Source File: AppConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public DefaultInstalledAppContextStore installedAppContextStore(
        TokenRefreshService tokenRefreshService) {
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDB dynamoDB = new DynamoDB(client);
    return new DynamoDBInstalledAppContextStore(dynamoDB, tokenRefreshService);
}
 
Example 21
private AmazonDynamoDB buildDynamoDbClient(Regions region) {
    return AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(
                    new AwsClientBuilder.EndpointConfiguration(DYNAMODB_LOCAL_ENDPOINT,
                            region.getName()))
            .build();
}
 
Example 22
@Override
public AmazonDynamoDB amazonDynamoDB() {
    return decorateWithConfigsAndBuild(
        AmazonDynamoDBClientBuilder.standard(),
        LocalstackDocker::getEndpointDynamoDB
    );
}
 
Example 23
Source Project: java-specialagent   Source File: AwsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncClient(final MockTracer tracer) {
  final AmazonDynamoDB dbClient = buildClient();
  try {
    createTable(dbClient, "table-1");
  }
  catch (final Exception e) {
    logger.log(Level.WARNING, e.getMessage());
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals("CreateTableRequest", spans.get(0).operationName());
}
 
Example 24
Source Project: java-specialagent   Source File: AwsTest.java    License: Apache License 2.0 5 votes vote down vote up
private static AmazonDynamoDB buildClient() {
  final EndpointConfiguration endpointConfiguration = new EndpointConfiguration("http://localhost:8000", "us-west-2");
  final BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
  return AmazonDynamoDBClientBuilder
    .standard()
    .withEndpointConfiguration(endpointConfiguration)
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withClientConfiguration(new ClientConfiguration().withConnectionTimeout(1))
    .build();
}
 
Example 25
Source Project: beam   Source File: BasicDynamoDBProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AmazonDynamoDB createDynamoDB() {
  return AmazonDynamoDBClientBuilder.standard()
      .withCredentials(getCredentialsProvider())
      .withRegion(region)
      .build();
}
 
Example 26
Source Project: java-specialagent   Source File: Aws1ITest.java    License: Apache License 2.0 5 votes vote down vote up
private static AmazonDynamoDB buildClient() {
  final AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2");
  final BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
  final AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder
    .standard()
    .withEndpointConfiguration(endpointConfiguration)
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withClientConfiguration(new ClientConfiguration().withConnectionTimeout(1));
  return builder.build();
}
 
Example 27
/**
 * Creates DynamoDB table. If the table already exists, it validates the key schema. If the key schemas match, a
 * warning is logged, otherwise an exception is raised.
 *
 * @param dynamoDB
 *            {@link AmazonDynamoDB} used to create the table specified in the request.
 * @param request
 *            Request for creating a table.
 * @return TableDescription of the existing table or newly created table
 */
public static TableDescription createTable(final AmazonDynamoDB dynamoDB, final CreateTableRequest request) {
    try {
        final DescribeTableResult result = dynamoDB.describeTable(request.getTableName());
        if (!request.getKeySchema().equals(result.getTable().getKeySchema())) {
            throw new IllegalStateException("Table " + request.getTableName()
                + " already exists and has an invalid schema");
        }
        LOGGER.warning("Table " + request.getTableName() + " already exists");
        return result.getTable();
    } catch (final ResourceNotFoundException e) {
        return dynamoDB.createTable(request).getTableDescription();
    }
}
 
Example 28
Source Project: Cheddar   Source File: DynamoDbTemplateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeleteItem_withStubItemWithUniqueConstraint() throws Exception {
    // Given
    final StubItem stubItem = new StubItem();
    stubItem.setId(randomId());
    stubItem.setStringProperty(randomString(10));
    stubItem.setVersion(randomLong());
    final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
    itemConfiguration.registerUniqueConstraints(Arrays.asList(new UniqueConstraint("stringProperty")));
    final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration);
    when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations);
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(mockDatabaseSchemaHolder);
    final AmazonDynamoDB mockAmazonDynamoDbClient = mock(AmazonDynamoDB.class);
    dynamoDbTemplate.initialize(mockAmazonDynamoDbClient);

    // When
    dynamoDbTemplate.delete(stubItem);

    // Then
    final ArgumentCaptor<DeleteItemRequest> deleteItemRequestArgumentCaptor = ArgumentCaptor
            .forClass(DeleteItemRequest.class);
    verify(mockAmazonDynamoDbClient, times(2)).deleteItem(deleteItemRequestArgumentCaptor.capture());
    final List<DeleteItemRequest> deleteItemRequests = deleteItemRequestArgumentCaptor.getAllValues();
    final Iterator<DeleteItemRequest> iterator = deleteItemRequests.iterator();

    final DeleteItemRequest deleteItemRequest1 = iterator.next();
    assertEquals(schemaName + "." + tableName, deleteItemRequest1.getTableName());
    assertEquals(1, deleteItemRequest1.getKey().size());
    assertEquals(new AttributeValue(stubItem.getId()), deleteItemRequest1.getKey().get("id"));
    assertEquals(new ExpectedAttributeValue(new AttributeValue().withN(String.valueOf(stubItem.getVersion()))),
            deleteItemRequest1.getExpected().get("version"));

    final DeleteItemRequest deleteItemRequest2 = iterator.next();
    assertEquals(schemaName + "-indexes." + tableName, deleteItemRequest2.getTableName());
    assertEquals(2, deleteItemRequest2.getKey().size());
    assertEquals(new AttributeValue("stringProperty"), deleteItemRequest2.getKey().get("property"));
    assertEquals(new AttributeValue(stubItem.getStringProperty().toUpperCase()),
            deleteItemRequest2.getKey().get("value"));
}
 
Example 29
public static void updateItem(AmazonDynamoDB dynamoDBClient, String tableName, String id, String val) {
    java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Id", new AttributeValue().withN(id));

    Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
    AttributeValueUpdate update = new AttributeValueUpdate().withAction(AttributeAction.PUT)
        .withValue(new AttributeValue().withS(val));
    attributeUpdates.put("attribute-2", update);

    UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
        .withAttributeUpdates(attributeUpdates);
    dynamoDBClient.updateItem(updateItemRequest);
}
 
Example 30
public static void waitForTableToBecomeDeleted(AmazonDynamoDB dynamo, String tableName) {
    log.info(() -> "Waiting for " + tableName + " to become Deleted...");
    long startTime = System.currentTimeMillis();
    long endTime = startTime + (60_000);
    while (System.currentTimeMillis() < endTime) {
        try {
            Thread.sleep(5_000);
        } catch (Exception e) {
            // Ignored or expected.
        }
        try {
            DescribeTableRequest request = new DescribeTableRequest(tableName);
            TableDescription table = dynamo.describeTable(request).getTable();

            log.info(() -> "  - current state: " + table.getTableStatus());
            if (table.getTableStatus() == "DELETING") {
                continue;
            }
        } catch (AmazonDynamoDBException exception) {
            if (exception.getErrorCode().equalsIgnoreCase("ResourceNotFoundException")) {
                log.info(() -> "successfully deleted");
                return;
            }
        }
    }

    throw new RuntimeException("Table " + tableName + " never went deleted");
}