com.amazonaws.services.dynamodbv2.AmazonDynamoDB Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDB. 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: DynamoDBRepositoryExtension.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
/**
 * 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 File: DynamoDBWorkerUtils.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: Application.java    From spring-data-dynamodb-examples with 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 #4
Source File: DynamoDBUtil.java    From serverless with 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 #5
Source File: DynaliteContainerTest.java    From testcontainers-java with 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
Source File: MostRecentEncryptedItem.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: MoviesDeleteTable.java    From aws-doc-sdk-examples with 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 #8
Source File: DynamoDBTableReplicator.java    From podyn with 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 #9
Source File: EncryptionContextOverridesWithDynamoDBMapper.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: KinesisShardCheckpointer.java    From presto-kinesis with 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 #11
Source File: DynamoDBEmbeddedTest.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: DynamoDBWorkerUtilsTest.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: KinesisShardCheckpointer.java    From presto with 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 #14
Source File: DynamoDBCertRecordStoreFactory.java    From athenz with 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 #15
Source File: CrossRegionReplicationIntegrationTests.java    From dynamodb-cross-region-library with Apache License 2.0 5 votes vote down vote up
private AmazonDynamoDB buildDynamoDbClient(Regions region) {
    return AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(
                    new AwsClientBuilder.EndpointConfiguration(DYNAMODB_LOCAL_ENDPOINT,
                            region.getName()))
            .build();
}
 
Example #16
Source File: AppConfiguration.java    From smartapp-sdk-java with 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 #17
Source File: DynamoDBIOTestHelper.java    From beam with 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 #18
Source File: Aws1ITest.java    From java-specialagent with 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 #19
Source File: DynamoDbTemplateTest.java    From Cheddar with 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 File: DynamoDbTemplateTest.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateItem_withStubItemAndCompoundPk() throws Exception {
    // Given
    final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName,
            new CompoundPrimaryKeyDefinition("id", "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);
    final StubItem stubItem = new StubItem();
    stubItem.setId(randomId());
    final String stringPropertyValue = randomString(10);
    stubItem.setStringProperty(stringPropertyValue);
    stubItem.setStringProperty2(randomString(10));
    final Long oldVersion = randomLong();
    stubItem.setVersion(oldVersion);

    // When
    dynamoDbTemplate.update(stubItem);

    // Then
    final ArgumentCaptor<UpdateItemRequest> updateItemRequestArgumentCaptor = ArgumentCaptor
            .forClass(UpdateItemRequest.class);
    verify(mockAmazonDynamoDbClient).updateItem(updateItemRequestArgumentCaptor.capture());
    final UpdateItemRequest updateItemRequest = updateItemRequestArgumentCaptor.getValue();
    assertEquals(schemaName + "." + tableName, updateItemRequest.getTableName());
    final Map<String, AttributeValue> key = new HashMap<>();
    key.put("id", new AttributeValue(stubItem.getId()));
    key.put("stringProperty", new AttributeValue(stubItem.getStringProperty()));
    assertEquals(key, updateItemRequest.getKey());
    assertEquals(updateItemRequest.getAttributeUpdates().size(), 4);
    assertEquals(
            new AttributeValueUpdate().withAction(AttributeAction.PUT)
                    .withValue(new AttributeValue(stubItem.getStringProperty2())),
            updateItemRequest.getAttributeUpdates().get("stringProperty2"));
    assertEquals(new ExpectedAttributeValue(new AttributeValue().withN(String.valueOf(oldVersion))),
            updateItemRequest.getExpected().get("version"));
}
 
Example #21
Source File: DynamoDBManager.java    From aws-dynamodb-mars-json-demo with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #22
Source File: DynamoDbTemplateTest.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGenerateKeys_withSequenceKeyGeneratorWithMultipleKeyCount() throws Exception {
    // Given
    final String sequenceName = randomString(10);
    final SequenceKeyGenerator sequenceKeyGenerator = new SequenceKeyGenerator(sequenceName, 5);
    final SequenceConfiguration sequenceConfiguration = new SequenceConfiguration(sequenceName);
    final Collection<SequenceConfiguration> sequenceConfigurations = new ArrayList<>();
    sequenceConfigurations.add(sequenceConfiguration);
    when(mockDatabaseSchemaHolder.sequenceConfigurations()).thenReturn(sequenceConfigurations);
    final AmazonDynamoDB mockAmazonDynamoDbClient = mock(AmazonDynamoDB.class);
    final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(mockDatabaseSchemaHolder);
    dynamoDbTemplate.initialize(mockAmazonDynamoDbClient);
    final UpdateItemResult mockUpdateItemResult = mock(UpdateItemResult.class);
    final Map<String, AttributeValue> mockUpdateItemResultAttributes = mock(Map.class);
    final AttributeValue mockCurrentValueAttributeValue = mock(AttributeValue.class);
    when(mockUpdateItemResultAttributes.get("currentValue")).thenReturn(mockCurrentValueAttributeValue);
    when(mockUpdateItemResult.getAttributes()).thenReturn(mockUpdateItemResultAttributes);
    when(mockAmazonDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(mockUpdateItemResult);
    when(mockCurrentValueAttributeValue.getN()).thenReturn("5");

    // When
    final GeneratedKeyHolder generatedKeyHolder = dynamoDbTemplate.generateKeys(sequenceKeyGenerator);

    // Then
    final ArgumentCaptor<UpdateItemRequest> updateItemRequestArgumentCaptor = ArgumentCaptor
            .forClass(UpdateItemRequest.class);
    verify(mockAmazonDynamoDbClient).updateItem(updateItemRequestArgumentCaptor.capture());
    assertEquals(schemaName + "-sequences", updateItemRequestArgumentCaptor.getValue().getTableName());
    assertThat(generatedKeyHolder.keys(), hasItems(1l, 2l, 3l, 4l, 5l));
    assertEquals(generatedKeyHolder.keys().size(), 5);
}
 
Example #23
Source File: DynamoDbTemplateTest.java    From Cheddar with 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 #24
Source File: StreamsAdapterDemoHelper.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: DynamoDBClientFetcherImplTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClientWithRegion() {
    System.setProperty(ZTS_PROP_DYNAMODB_REGION, "test.region");
    DynamoDBClientFetcher dynamoDBClientFetcher = DynamoDBClientFetcherFactory.getDynamoDBClientFetcher();
    PrivateKeyStore keyStore = Mockito.mock(PrivateKeyStore.class);
    ZTSClientNotificationSender ztsClientNotificationSender = Mockito.mock(ZTSClientNotificationSender.class);
    AmazonDynamoDB dynamoDBClient = dynamoDBClientFetcher.getDynamoDBClient(ztsClientNotificationSender, keyStore).getAmazonDynamoDB();
    assertNotNull(dynamoDBClient);
    System.clearProperty(ZTS_PROP_DYNAMODB_REGION);
}
 
Example #26
Source File: UpdateTable.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE = "\n" +
        "Usage:\n" +
        "    UpdateTable <table> <read> <write>\n\n" +
        "Where:\n" +
        "    table - the table to put the item in.\n" +
        "    read  - the new read capacity of the table.\n" +
        "    write - the new write capacity of the table.\n\n" +
        "Example:\n" +
        "    UpdateTable HelloTable 16 10\n";

    if (args.length < 3) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String table_name = args[0];
    Long read_capacity = Long.parseLong(args[1]);
    Long write_capacity = Long.parseLong(args[2]);

    System.out.format(
            "Updating %s with new provisioned throughput values\n",
            table_name);
    System.out.format("Read capacity : %d\n", read_capacity);
    System.out.format("Write capacity : %d\n", write_capacity);

    ProvisionedThroughput table_throughput = new ProvisionedThroughput(
          read_capacity, write_capacity);

    final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

    try {
        ddb.updateTable(table_name, table_throughput);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}
 
Example #27
Source File: DynamoDbTemplateTest.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreateItem_withStubItemWithExistingPrimaryKey() throws Exception {
    // Given
    final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName);
    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);
    final StubItem stubItem = new StubItem();
    stubItem.setId(randomId());
    final String stringPropertyValue = randomString(10);
    stubItem.setStringProperty(stringPropertyValue);
    when(mockAmazonDynamoDbClient.putItem(any(PutItemRequest.class)))
            .thenThrow(ConditionalCheckFailedException.class);

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

    // Then
    assertNotNull(actualException);
}
 
Example #28
Source File: DynamoDBCryptoIntegrationTestBase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #29
Source File: APIDemoHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    JSONObject responseJson = new JSONObject();

    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDB dynamoDb = new DynamoDB(client);

    try {
        JSONObject event = (JSONObject) parser.parse(reader);

        if (event.get("body") != null) {

            Person person = new Person((String) event.get("body"));

            dynamoDb.getTable(DYNAMODB_TABLE_NAME)
                .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId())
                    .withString("name", person.getName())));
        }

        JSONObject responseBody = new JSONObject();
        responseBody.put("message", "New item created");

        JSONObject headerJson = new JSONObject();
        headerJson.put("x-custom-header", "my custom header value");

        responseJson.put("statusCode", 200);
        responseJson.put("headers", headerJson);
        responseJson.put("body", responseBody.toString());

    } catch (ParseException pex) {
        responseJson.put("statusCode", 400);
        responseJson.put("exception", pex);
    }

    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseJson.toString());
    writer.close();
}
 
Example #30
Source File: DynamoDBSSHRecordStoreFactory.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public SSHRecordStore create(PrivateKeyStore keyStore) {

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

    ZTSClientNotificationSenderImpl ztsClientNotificationSender = new ZTSClientNotificationSenderImpl();
    AmazonDynamoDB client = getDynamoDBClient(ztsClientNotificationSender, keyStore);
    return new DynamoDBSSHRecordStore(client, tableName, ztsClientNotificationSender);
}