下面列出了怎么用com.amazonaws.services.dynamodbv2.model.CreateTableResult的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public DynamoDBResponse createTable(CreateTableRequest createTableRequest) throws IOException {
logger.info("creating JSON table");
String columnPairs = createTableRequest.getAttributeDefinitions().stream().map(this::attributeToPairs).collect(Collectors.joining(", "));
columnPairs += ",json_blob text";
String keyspace = keyspaceName;
String table = createTableRequest.getTableName();
String primaryKey = getPrimaryKey(createTableRequest.getKeySchema());
String statement = String.format("CREATE TABLE IF NOT EXISTS %s.\"%s\" ( %s, PRIMARY KEY %s);\n", keyspace, table, columnPairs, primaryKey);
ResultSet result = session().execute(statement);
if (result.wasApplied()) {
logger.info("created {} as {}", table, statement);
cassandraManager.refreshSchema();
TableDescription newTableDesc = this.getTableDescription(table, createTableRequest.getAttributeDefinitions(), createTableRequest.getKeySchema());
CreateTableResult createResult = (new CreateTableResult()).withTableDescription(newTableDesc);
return new DynamoDBResponse(createResult, 200);
}
return null;
}
@Test
public void testAsyncClient(final MockTracer tracer) throws Exception {
final AmazonDynamoDBAsync dbClient = buildAsyncClient();
final Future<CreateTableResult> createTableResultFuture = createTableAsync(dbClient, "asyncRequest");
try {
final CreateTableResult result = createTableResultFuture.get(10, TimeUnit.SECONDS);
// The following assertion is only relevant when a local instance of dynamodb is present.
// If a local instance of dynamodb is NOT present, an exception is thrown.
assertEquals("asyncRequest", result.getTableDescription().getTableName());
}
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());
}
private static Future<CreateTableResult> createTableAsync(final AmazonDynamoDBAsync dbClient, final String tableName) {
final String partitionKeyName = tableName + "Id";
final CreateTableRequest createTableRequest = new CreateTableRequest()
.withTableName(tableName).withKeySchema(new KeySchemaElement().withAttributeName(partitionKeyName).withKeyType(KeyType.HASH))
.withAttributeDefinitions(new AttributeDefinition().withAttributeName(partitionKeyName).withAttributeType("S"))
.withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L));
return dbClient.createTableAsync(createTableRequest, new AsyncHandler<CreateTableRequest,CreateTableResult>() {
@Override
public void onError(final Exception exception) {
}
@Override
public void onSuccess(final CreateTableRequest request, final CreateTableResult createTableResult) {
}
});
}
@Test
public void testCreateTableWithWait() throws Exception {
// Create fake responses from AWS. First response is still creating the table, second response the table
// has become active.
TableDescription creatingDescription = constructTableDescription(TableStatus.CREATING);
TableDescription createdDescription = constructTableDescription(TableStatus.ACTIVE);
CreateTableResult mockCreateResult = new CreateTableResult().withTableDescription(creatingDescription);
DescribeTableResult mockDescribeResultCreating = new DescribeTableResult().withTable(creatingDescription);
DescribeTableResult mockDescribeResultCreated = new DescribeTableResult().withTable(createdDescription);
// Create the table.
CreateTableRequest expectedRequest = dynamoDB.constructCreateTableRequest();
when(mockDynamoDBClient.createTable(expectedRequest)).thenReturn(mockCreateResult);
when(mockDynamoDBClient.describeTable(tableName)).thenReturn(mockDescribeResultCreating, mockDescribeResultCreated);
assertEquals(dynamoDB.create(), TEST_ARN);
verify(mockDynamoDBClient, times(1)).createTable(expectedRequest);
verify(mockDynamoDBClient, times(2)).describeTable(tableName);
}
private static void createTable() {
List<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition().withAttributeName("name").withAttributeType("S"));
List<KeySchemaElement> ks = new ArrayList<KeySchemaElement>();
ks.add(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)); // Partition
// key
ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(10L)
.withWriteCapacityUnits(10L);
CreateTableRequest request = new CreateTableRequest().withTableName(TABLENAME)
.withAttributeDefinitions(attributeDefinitions).withKeySchema(ks)
.withProvisionedThroughput(provisionedThroughput);
try {
CreateTableResult createdTableDescription = dynamoDBClient.createTable(request);
logger.info("Created Table: " + createdTableDescription);
// Wait for it to become active
waitForTableToBecomeAvailable(TABLENAME);
}
catch (ResourceInUseException e) {
logger.warn("Table already existed", e);
}
}
static void createTestTable(String tableName) {
CreateTableResult res = createDynamoTable(tableName);
TableDescription tableDesc = res.getTableDescription();
Assert.assertEquals(tableName, tableDesc.getTableName());
Assert.assertTrue(tableDesc.getKeySchema().toString().contains(ATTR_NAME_1));
Assert.assertTrue(tableDesc.getKeySchema().toString().contains(ATTR_NAME_2));
Assert.assertEquals(
tableDesc.getProvisionedThroughput().getReadCapacityUnits(), Long.valueOf(1000));
Assert.assertEquals(
tableDesc.getProvisionedThroughput().getWriteCapacityUnits(), Long.valueOf(1000));
Assert.assertEquals("ACTIVE", tableDesc.getTableStatus());
Assert.assertEquals(
"arn:aws:dynamodb:us-east-1:000000000000:table/" + tableName, tableDesc.getTableArn());
ListTablesResult tables = dynamoDBClient.listTables();
Assert.assertEquals(1, tables.getTableNames().size());
}
private static CreateTableResult createDynamoTable(String tableName) {
ImmutableList<AttributeDefinition> attributeDefinitions =
ImmutableList.of(
new AttributeDefinition(ATTR_NAME_1, ScalarAttributeType.S),
new AttributeDefinition(ATTR_NAME_2, ScalarAttributeType.N));
ImmutableList<KeySchemaElement> ks =
ImmutableList.of(
new KeySchemaElement(ATTR_NAME_1, KeyType.HASH),
new KeySchemaElement(ATTR_NAME_2, KeyType.RANGE));
ProvisionedThroughput provisionedthroughput = new ProvisionedThroughput(1000L, 1000L);
CreateTableRequest request =
new CreateTableRequest()
.withTableName(tableName)
.withAttributeDefinitions(attributeDefinitions)
.withKeySchema(ks)
.withProvisionedThroughput(provisionedthroughput);
return dynamoDBClient.createTable(request);
}
private CreateTableResult createTable() throws Exception {
List<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
AttributeDefinition attributeDefinition = new AttributeDefinition()
.withAttributeName(TEST_ATTRIBUTE)
.withAttributeType(ScalarAttributeType.S);
attributeDefinitions.add(attributeDefinition);
String tableName = TEST_TABLE_NAME;
List<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
KeySchemaElement keySchemaElement = new KeySchemaElement()
.withAttributeName(TEST_ATTRIBUTE)
.withKeyType(KeyType.HASH);
ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput()
.withReadCapacityUnits(UNITS)
.withWriteCapacityUnits(UNITS);
CreateTableResult result = dynamoDb.createTable(attributeDefinitions, tableName, keySchema, provisionedThroughput);
return result;
}
@Test
public void createTableTest() {
AmazonDynamoDB ddb = DynamoDBEmbedded.create().amazonDynamoDB();
try {
String tableName = "Movies";
String hashKeyName = "film_id";
CreateTableResult res = createTable(ddb, tableName, hashKeyName);
TableDescription tableDesc = res.getTableDescription();
assertEquals(tableName, tableDesc.getTableName());
assertEquals("[{AttributeName: " + hashKeyName + ",KeyType: HASH}]", tableDesc.getKeySchema().toString());
assertEquals("[{AttributeName: " + hashKeyName + ",AttributeType: S}]",
tableDesc.getAttributeDefinitions().toString());
assertEquals(Long.valueOf(1000L), tableDesc.getProvisionedThroughput().getReadCapacityUnits());
assertEquals(Long.valueOf(1000L), tableDesc.getProvisionedThroughput().getWriteCapacityUnits());
assertEquals("ACTIVE", tableDesc.getTableStatus());
assertEquals("arn:aws:dynamodb:ddblocal:000000000000:table/Movies", tableDesc.getTableArn());
ListTablesResult tables = ddb.listTables();
assertEquals(1, tables.getTableNames().size());
} finally {
ddb.shutdown();
}
}
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);
}
@Override
public String create() {
readWriteLock.writeLock().lock();
try {
CreateTableResult result = client.createTable(constructCreateTableRequest());
waitForTableToBecomeActive();
return result.getTableDescription().getTableArn();
} catch (ResourceInUseException e) {
throw new AlreadyExistsException(String.format("There is already a DynamoDB table called '%s'", tableName), e);
} finally {
readWriteLock.writeLock().unlock();
}
}
/**
* Creates the FragmentCheckpoint table if it doesn't exist already.
*/
public void createTableIfDoesntExist() {
// Check if table exists
if (!checkIfTableExists()) {
log.info("Creating table : {}", TABLE_NAME);
final CreateTableRequest request = new CreateTableRequest() {{
setAttributeDefinitions(
Collections.singletonList(
new AttributeDefinition(
KVS_STREAM_NAME,
ScalarAttributeType.S)));
setKeySchema(
Collections.singletonList(
new KeySchemaElement(
KVS_STREAM_NAME,
KeyType.HASH)));
setProvisionedThroughput(
new ProvisionedThroughput(1000L, 1000L));
setTableName(TABLE_NAME);
}};
try {
final CreateTableResult result = ddbClient.createTable(request);
log.info("Table created : {}", result.getTableDescription());
} catch (final AmazonDynamoDBException e) {
log.error("Error creating DDB table {}...", TABLE_NAME, e);
throw e;
}
}
}
/**
* @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();
}
}
private CreateTableResult createTable(final CreateTableRequest request) throws BackendException {
controlPlaneRateLimiter.acquire();
final Timer.Context apiTimerContext = getTimerContext(CREATE_TABLE, request.getTableName());
CreateTableResult result;
try {
result = client.createTable(request);
} catch (final Exception e) {
throw processDynamoDbApiException(e, CREATE_TABLE, request.getTableName());
} finally {
apiTimerContext.stop();
}
return result;
}
/**
* 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);
}
@Test
public void test_createTable_WithParameters() throws Exception {
CreateTableResult result = createTable();
TableDescription tableDescription = result.getTableDescription();
String createdTableName = tableDescription.getTableName();
assertThat(createdTableName, equalTo(TEST_TABLE_NAME));
}
@Test
public void testCreateTableTableDoesNotExist() {
final Collection<AttributeDefinition> ads = Arrays.asList(new AttributeDefinition("Hash", ScalarAttributeType.S));
final Collection<KeySchemaElement> kses = Arrays.asList(new KeySchemaElement("Hash", KeyType.HASH));
final TableDescription description = new TableDescription().withAttributeDefinitions(ads).withKeySchema(kses)
.withTableName(tableName);
final CreateTableResult cTR = new CreateTableResult().withTableDescription(description);
EasyMock.expect(dynamoDB.describeTable(tableName)).andThrow(new ResourceNotFoundException(null));
final CreateTableRequest request = new CreateTableRequest().withAttributeDefinitions(ads).withKeySchema(kses)
.withTableName(tableName);
EasyMock.expect(dynamoDB.createTable(request)).andReturn(cTR);
PowerMock.replayAll();
assertEquals(description, DynamoDBManager.createTable(dynamoDB, request));
PowerMock.verifyAll();
}
/**
* @return StreamArn
*/
public static String createTable(AmazonDynamoDBClient 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));
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();
}
}
private static void createTable()
{
List<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition().withAttributeName("name").withAttributeType("S"));
List<KeySchemaElement> ks = new ArrayList<KeySchemaElement>();
ks.add(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH));
ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(10L)
.withWriteCapacityUnits(10L);
CreateTableRequest request = new CreateTableRequest().withTableName(TABLENAME)
.withAttributeDefinitions(attributeDefinitions).withKeySchema(ks)
.withProvisionedThroughput(provisionedThroughput);
try
{
CreateTableResult createdTableDescription = dynamoDBClient.createTable(request);
logger.info("Created Table: " + createdTableDescription);
// Wait for it to become active
waitForTableToBecomeAvailable(TABLENAME);
}
catch (ResourceInUseException e)
{
logger.warn("Table already existed", e);
}
}
@Override
public CreateTableResult createTable(
List<AttributeDefinition> attributeDefinitions, String tableName,
List<KeySchemaElement> keySchema,
ProvisionedThroughput provisionedThroughput)
throws AmazonServiceException, AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}
@Override
public CreateTableResult createTable(
List<AttributeDefinition> attributeDefinitions, String tableName,
List<KeySchemaElement> keySchema,
ProvisionedThroughput provisionedThroughput) throws AmazonServiceException, AmazonClientException {
return getBackend().createTable(attributeDefinitions, tableName, keySchema, provisionedThroughput);
}
@Override
public CreateTableResult createTable(
List<AttributeDefinition> attributeDefinitions, String tableName,
List<KeySchemaElement> keySchema,
ProvisionedThroughput provisionedThroughput)
throws AmazonServiceException, AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}
@Override
public CreateTableResult createTable(CreateTableRequest createTableRequest) {
throw new UnsupportedOperationException();
}
@Override
public CreateTableResult createTable(List<AttributeDefinition> attributeDefinitions, String tableName,
List<KeySchemaElement> keySchema, ProvisionedThroughput provisionedThroughput) {
throw new UnsupportedOperationException();
}
public static void main(String[] args)
{
final String USAGE = "\n" +
"Usage:\n" +
" CreateTable <table>\n\n" +
"Where:\n" +
" table - the table to create.\n\n" +
"Example:\n" +
" CreateTable HelloTable\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
/* Read the name from command args */
String table_name = args[0];
System.out.format(
"Creating table \"%s\" with a simple primary key: \"Name\".\n",
table_name);
CreateTableRequest request = new CreateTableRequest()
.withAttributeDefinitions(new AttributeDefinition(
"Name", ScalarAttributeType.S))
.withKeySchema(new KeySchemaElement("Name", KeyType.HASH))
.withProvisionedThroughput(new ProvisionedThroughput(
new Long(10), new Long(10)))
.withTableName(table_name);
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();
try {
CreateTableResult result = ddb.createTable(request);
System.out.println(result.getTableDescription().getTableName());
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
}
System.out.println("Done!");
}
public static void main(String[] args)
{
final String USAGE = "\n" +
"Usage:\n" +
" CreateTable <table>\n\n" +
"Where:\n" +
" table - the table to create.\n\n" +
"Example:\n" +
" CreateTable GreetingsTable\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
/* Read the name from command args */
String table_name = args[0];
System.out.format("Creating table %s\n with a composite primary key:\n");
System.out.format("* Language - partition key\n");
System.out.format("* Greeting - sort key\n");
CreateTableRequest request = new CreateTableRequest()
.withAttributeDefinitions(
new AttributeDefinition("Language", ScalarAttributeType.S),
new AttributeDefinition("Greeting", ScalarAttributeType.S))
.withKeySchema(
new KeySchemaElement("Language", KeyType.HASH),
new KeySchemaElement("Greeting", KeyType.RANGE))
.withProvisionedThroughput(
new ProvisionedThroughput(new Long(10), new Long(10)))
.withTableName(table_name);
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();
try {
CreateTableResult result = ddb.createTable(request);
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
}
System.out.println("Done!");
}
@Override
public CreateTableResult createTable(CreateTableRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}
@Override
public CreateTableResult createTable(CreateTableRequest request) throws AmazonServiceException, AmazonClientException {
return getBackend().createTable(request);
}
@Override
public CreateTableResult createTable(CreateTableRequest arg0)
throws AmazonServiceException, AmazonClientException {
throw new UnsupportedOperationException("Use the underlying client instance instead");
}