Skip to content

Instantly share code, notes, and snippets.

@martintreurnicht
Last active February 3, 2016 16:38
Show Gist options
  • Save martintreurnicht/ff92767e8c7d25c065b0 to your computer and use it in GitHub Desktop.
Save martintreurnicht/ff92767e8c7d25c065b0 to your computer and use it in GitHub Desktop.
Create Dynamo DB table when they don't exist
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.Projection;
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException;
import com.amazonaws.auth.AWSCredentials;
public class DynamoDbHelper {
private static DynamoDBMapper getDynamoDBMapper(final Configuration configuration, final Class<?> klass) {
val client = new AmazonDynamoDBClient();
client.setRegion(RegionUtils.getRegion(configuration.region));
val mapper = new DynamoDBMapper(client);
val request = mapper.generateCreateTableRequest(klass);
request.setProvisionedThroughput(
new ProvisionedThroughput(
configuration.read,
configuration.write
)
);
if (request.getGlobalSecondaryIndexes() != null) {
for (final GlobalSecondaryIndex index : request.getGlobalSecondaryIndexes()) {
index.setProvisionedThroughput(new ProvisionedThroughput(
configuration.read,
configuration.write
));
index.setProjection(new Projection().withProjectionType(ProjectionType.ALL));
}
}
final String tableName = request.getTableName();
try {
client.describeTable(tableName);
} catch (final ResourceNotFoundException e) {
log.info("Dynamo db table {} doesn't exist, attempting to create....", tableName);
client.createTable(request);
}
return mapper;
}
public static class Configuration implements AWSCredentials {
public String key;
public String secret;
public String region = "us-east-1";
public long read = 5L;
public long write = 5L;
@Override
public String getAWSAccessKeyId() {
return key;
}
@Override
public String getAWSSecretKey() {
return secret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment