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

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient. 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: presto   Source File: KinesisClientManager.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public KinesisClientManager(KinesisConfig config)
{
    if (!isNullOrEmpty(config.getAccessKey()) && !isNullOrEmpty(config.getSecretKey())) {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(config.getAccessKey(), config.getSecretKey());
        this.client = new AmazonKinesisClient(awsCredentials);
        this.amazonS3Client = new AmazonS3Client(awsCredentials);
        this.dynamoDbClient = new AmazonDynamoDBClient(awsCredentials);
    }
    else {
        DefaultAWSCredentialsProviderChain defaultChain = new DefaultAWSCredentialsProviderChain();
        this.client = new AmazonKinesisClient(defaultChain);
        this.amazonS3Client = new AmazonS3Client(defaultChain);
        this.dynamoDbClient = new AmazonDynamoDBClient(defaultChain);
    }

    this.client.setEndpoint("kinesis." + config.getAwsRegion() + ".amazonaws.com");
    this.dynamoDbClient.setEndpoint("dynamodb." + config.getAwsRegion() + ".amazonaws.com");
}
 
Example 2
public static void updateItem(AmazonDynamoDBClient client, 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);
    client.updateItem(updateItemRequest);
}
 
Example 3
Source Project: aws-dynamodb-examples   Source File: MoviesItemOps06.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");
                
        // Conditional delete (will fail)
        
        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
            .withPrimaryKey(new PrimaryKey("year", 2015, "title", "The Big New Movie"))
            .withConditionExpression("info.rating <= :val")
            .withValueMap(new ValueMap()
                   .withNumber(":val", 5.0));
        
        System.out.println("Attempting a conditional delete...");
        try {
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DeleteItem failed");
        }

    }
 
Example 4
/**
 * Creates the DynamoDBBootstrapWorker, calculates the number of segments a
 * table should have, and creates a thread pool to prepare to scan.
 * 
 * @throws Exception
 */
public DynamoDBBootstrapWorker(AmazonDynamoDBClient client,
        double rateLimit, String tableName, ExecutorService exec,
        int section, int totalSections, int numSegments,
        boolean consistentScan) throws SectionOutOfRangeException {
    if (section > totalSections - 1 || section < 0) {
        throw new SectionOutOfRangeException(
                "Section of scan must be within [0...totalSections-1]");
    }

    this.client = client;
    this.rateLimit = rateLimit;
    this.tableName = tableName;

    this.numSegments = numSegments;
    this.section = section;
    this.totalSections = totalSections;
    this.consistentScan = consistentScan;

    super.threadPool = exec;
}
 
Example 5
/**
 * Creates the DynamoDBBootstrapWorker, calculates the number of segments a
 * table should have, and creates a thread pool to prepare to scan using an
 * eventually consistent scan.
 * 
 * @throws Exception
 */
public DynamoDBBootstrapWorker(AmazonDynamoDBClient client,
        double rateLimit, String tableName, int numThreads)
        throws NullReadCapacityException {
    this.client = client;
    this.rateLimit = rateLimit;
    this.tableName = tableName;
    TableDescription description = client.describeTable(tableName)
            .getTable();
    this.section = 0;
    this.totalSections = 1;
    this.consistentScan = false;

    this.numSegments = getNumberOfSegments(description);
    int numProcessors = Runtime.getRuntime().availableProcessors() * 4;
    if (numProcessors > numThreads) {
        numThreads = numProcessors;
    }
    super.threadPool = Executors.newFixedThreadPool(numThreads);
}
 
Example 6
Source Project: reinvent2013-mobile-photo-share   Source File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized GeoDataManager setupGeoDataManager() {
	if (geoDataManager == null) {
		String accessKey = getSystemProperty( "AWS_ACCESS_KEY_ID" ); 
		String secretKey = getSystemProperty( "AWS_SECRET_KEY" );
		String regionName = getSystemProperty( "PARAM2", "us-east-1" ); 
		String tableName = getSystemProperty( "PARAM3", "PhotoLocations" );

		AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
		AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(credentials);
		Region region = Region.getRegion(Regions.fromName(regionName));
		ddb.setRegion(region);

		GeoDataManagerConfiguration config = new GeoDataManagerConfiguration(ddb, tableName);
		geoDataManager = new GeoDataManager(config);
	}

	return geoDataManager;
}
 
Example 7
Source Project: presto-kinesis   Source File: KinesisClientManager.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
KinesisClientManager(KinesisConnectorConfig kinesisConnectorConfig)
{
    log.info("Creating new client for Consumer");
    if (nonEmpty(kinesisConnectorConfig.getAccessKey()) && nonEmpty(kinesisConnectorConfig.getSecretKey())) {
        this.kinesisAwsCredentials = new KinesisAwsCredentials(kinesisConnectorConfig.getAccessKey(), kinesisConnectorConfig.getSecretKey());
        this.client = new AmazonKinesisClient(this.kinesisAwsCredentials);
        this.amazonS3Client = new AmazonS3Client(this.kinesisAwsCredentials);
        this.dynamoDBClient = new AmazonDynamoDBClient(this.kinesisAwsCredentials);
    }
    else {
        this.kinesisAwsCredentials = null;
        DefaultAWSCredentialsProviderChain defaultChain = new DefaultAWSCredentialsProviderChain();
        this.client = new AmazonKinesisClient(defaultChain);
        this.amazonS3Client = new AmazonS3Client(defaultChain);
        this.dynamoDBClient = new AmazonDynamoDBClient(defaultChain);
    }

    this.client.setEndpoint("kinesis." + kinesisConnectorConfig.getAwsRegion() + ".amazonaws.com");
    this.dynamoDBClient.setEndpoint("dynamodb." + kinesisConnectorConfig.getAwsRegion() + ".amazonaws.com");
}
 
Example 8
Source Project: aws-dynamodb-mars-json-demo   Source File: ImageIngester.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a {@link ImageIngester} with the specified command line arguments and Amazon Web Services credentials
 * provider.
 *
 * @param args
 *            Command line arguments for retrieving the configuration
 * @param credentialsProvider
 *            Amazon Web Services credentials provider
 * @throws ExitException
 *             Error parsing configuration
 */
public ImageIngester(final String[] args, final AWSCredentialsProvider credentialsProvider) throws ExitException {
    // Parse command line arguments to locate configuration file
    final ImageIngesterCLI cli = new ImageIngesterCLI(args);
    config = cli.getConfig();
    // Validate the configuration file
    ConfigParser.validateConfig(config, REQUIRED_STRING_CONFIGURATIONS, REQUIRED_BOOLEAN_CONFIGURATIONS,
        REQUIRED_INTEGER_CONFIGURATIONS, REQUIRED_LONG_CONFIGURATIONS);
    // Parse configuration settings
    resourceTable = ConfigParser.parseString(config, CONFIG_RESOURCE_TABLE);
    imageTable = ConfigParser.parseString(config, CONFIG_IMAGE_TABLE);
    waitTime = ConfigParser.parseLong(config, CONFIG_WAIT_TIME, DEFAULT_WAIT_TIME);
    connectTimeout = ConfigParser.parseInteger(config, CONFIG_CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT);
    final String endpoint = ConfigParser.parseString(config, CONFIG_ENDPOINT);
    final int numManifestThreads = ConfigParser.parseInteger(config, CONFIG_NUM_MANIFEST_THREADS, DEFAULT_THREADS);
    // Setup state
    dynamoDB = new AmazonDynamoDBClient(credentialsProvider);
    dynamoDB.setEndpoint(endpoint);
    manifestPool = Executors.newFixedThreadPool(numManifestThreads);
}
 
Example 9
Source Project: wildfly-camel   Source File: DynamoDBUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static AmazonDynamoDBClient createDynamoDBClient() {
    BasicCredentialsProvider credentials = BasicCredentialsProvider.standard();
    AmazonDynamoDBClient client = !credentials.isValid() ? null : (AmazonDynamoDBClient)
            AmazonDynamoDBClientBuilder.standard()
            .withCredentials(credentials)
            .withRegion("eu-west-1")
            .build();
    return client;
}
 
Example 10
Source Project: amazon-kinesis-connectors   Source File: DynamoDBUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies if the table has the expected schema.
 * 
 * @param client
 *        The {@link AmazonDynamoDBClient} with Amazon DynamoDB read privileges
 * @param tableName
 *        The Amazon DynamoDB table to check
 * @param key
 *        The expected hashkey for the Amazon DynamoDB table
 * @return true if the Amazon DynamoDB table exists and the expected hashkey matches the table schema,
 *         otherwise return false
 */
private static boolean tableHasCorrectSchema(AmazonDynamoDBClient client, String tableName, String key) {
    DescribeTableRequest describeTableRequest = new DescribeTableRequest();
    describeTableRequest.setTableName(tableName);
    DescribeTableResult describeTableResult = client.describeTable(describeTableRequest);
    TableDescription tableDescription = describeTableResult.getTable();
    if (tableDescription.getAttributeDefinitions().size() != 1) {
        LOG.error("The number of attribute definitions does not match the existing table.");
        return false;
    }
    AttributeDefinition attributeDefinition = tableDescription.getAttributeDefinitions().get(0);
    if (!attributeDefinition.getAttributeName().equals(key)
            || !attributeDefinition.getAttributeType().equals(ScalarAttributeType.S.toString())) {
        LOG.error("Attribute name or type does not match existing table.");
        return false;
    }
    List<KeySchemaElement> KSEs = tableDescription.getKeySchema();
    if (KSEs.size() != 1) {
        LOG.error("The number of key schema elements does not match the existing table.");
        return false;
    }
    KeySchemaElement kse = KSEs.get(0);
    if (!kse.getAttributeName().equals(key) || !kse.getKeyType().equals(KeyType.HASH.toString())) {
        LOG.error("The hash key does not match the existing table.");
        return false;
    }
    return true;

}
 
Example 11
/**
 * Create client using credentials provider. This is the preferred way for creating clients
 */
@Override
protected AmazonDynamoDBClient createClient(final ProcessContext context, final AWSCredentialsProvider credentialsProvider, final ClientConfiguration config) {
    getLogger().debug("Creating client with credentials provider");

    final AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentialsProvider, config);

    return client;
}
 
Example 12
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AmazonDynamoDBClient createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().debug("Creating client with aws credentials");

    final AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, config);

    return client;
}
 
Example 13
Source Project: aws-dynamodb-examples   Source File: MoviesItemOps02.java    License: Apache License 2.0 5 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";

        final Map<String, Object> infoMap = new HashMap<String, Object>();
        infoMap.put("plot",  "Nothing happens at all.");
        infoMap.put("rating",  0.0);
        Item item = new Item()
            .withPrimaryKey(new PrimaryKey("year", year, "title", title))
            .withMap("info", infoMap);
        
        // Attempt a conditional write.  We expect this to fail.

        PutItemSpec putItemSpec = new PutItemSpec()
            .withItem(item)
            .withConditionExpression("attribute_not_exists(#yr) and attribute_not_exists(title)")
            .withNameMap(new NameMap()
                .with("#yr", "year"));
        
        System.out.println("Attempting a conditional write...");
        try {
            table.putItem(putItemSpec);
            System.out.println("PutItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (ConditionalCheckFailedException e) {
            e.printStackTrace(System.err);
            System.out.println("PutItem failed");
        }
    }
 
Example 14
Source Project: amazon-kinesis-connectors   Source File: DynamoDBEmitter.java    License: Apache License 2.0 5 votes vote down vote up
public DynamoDBEmitter(KinesisConnectorConfiguration configuration) {
    // Amazon DynamoDB Config
    this.dynamoDBEndpoint = configuration.DYNAMODB_ENDPOINT;
    this.dynamoDBTableName = configuration.DYNAMODB_DATA_TABLE_NAME;
    // Client
    this.dynamoDBClient = new AmazonDynamoDBClient(configuration.AWS_CREDENTIALS_PROVIDER);
    this.dynamoDBClient.setEndpoint(this.dynamoDBEndpoint);
}
 
Example 15
Source Project: wildfly-camel   Source File: DynamoDBUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void assertNoStaleTables(AmazonDynamoDBClient client, String when) {
    /* Get the list of tables without the ones in the deleting state */
    List<String> tables = client.listTables().getTableNames().stream()
            .filter(t -> System.currentTimeMillis() - AWSUtils.toEpochMillis(t) > AWSUtils.HOUR || !"DELETING".equals(client.describeTable(t).getTable().getTableStatus()))
            .collect(Collectors.toList());
    Assert.assertEquals(String.format("Found stale DynamoDB tables %s running the test: %s", when, tables), 0, tables.size());
}
 
Example 16
/**
 * Looks up table name and creates one if it does not exist
 */
public DeviceAuthentication() {
    ddb = new AmazonDynamoDBClient(new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY));
    ddb.setEndpoint(Configuration.DYNAMODB_ENDPOINT);

    try {
        if (!doesTableExist(DEVICE_TABLE)) {
            createDeviceTable();
        }
    } catch (DataAccessException e) {
        throw new RuntimeException("Failed to create device table.", e);
    }
}
 
Example 17
Source Project: dynamodb-geo   Source File: GeoDataManagerConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public GeoDataManagerConfiguration(AmazonDynamoDBClient dynamoDBClient, String tableName) {
	hashKeyAttributeName = DEFAULT_HASHKEY_ATTRIBUTE_NAME;
	rangeKeyAttributeName = DEFAULT_RANGEKEY_ATTRIBUTE_NAME;
	geohashAttributeName = DEFAULT_GEOHASH_ATTRIBUTE_NAME;
	geoJsonAttributeName = DEFAULT_GEOJSON_ATTRIBUTE_NAME;

	geohashIndexName = DEFAULT_GEOHASH_INDEX_ATTRIBUTE_NAME;

	hashKeyLength = DEFAULT_HASHKEY_LENGTH;

	this.dynamoDBClient = dynamoDBClient;
	this.tableName = tableName;
}
 
Example 18
public DynamoDBAnnouncementWatcher(AWSCredentials credentials, String tableName, String blobNamespace) {
    this.dynamoDB = new DynamoDB(new AmazonDynamoDBClient(credentials));
    this.tableName = tableName;
    this.blobNamespace = blobNamespace;
    this.subscribedConsumers = Collections.synchronizedList(new ArrayList<HollowConsumer>());
    
    this.latestVersion = readLatestVersion();
    
    setupPollingThread();
}
 
Example 19
Source Project: strongbox   Source File: GenericDynamoDBTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    this.mockDynamoDBClient = mock(AmazonDynamoDBClient.class);
    AWSCredentialsProvider mockCredentials = mock(AWSCredentialsProvider.class);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);
    this.dynamoDB = new DynamoDB(mockDynamoDBClient, mockCredentials, mockConfig, groupIdentifier, new ReentrantReadWriteLock());
}
 
Example 20
Source Project: strongbox   Source File: IAMPolicyManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() {
    mockCredentials = mock(AWSCredentialsProvider.class);
    mockClient = mock(AmazonIdentityManagementClient.class);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);
    IAMPolicyManager policyManager = new IAMPolicyManager(mockClient, mockCredentials, mockConfig);

    // The mockito spy acts like original object but mocks out the getAccount() method. As the getAccount() calls
    // directly rather than via a client that we can pass in we need to mock this out using a spy.
    partiallyMockedPolicyManager = spy(policyManager);
    doReturn(ACCOUNT).when(partiallyMockedPolicyManager).getAccount();

    // Set up KMSEncryptor for testing the policy creation methods. This gets a bit complicated but we need to
    // mock all the AWS dependencies from the KMSManager before using it to create the KMSEncryptor. The getAliasArn
    // needs to be mocked out with a spy to stop the call to getAccount.
    mockKMSClient = mock(AWSKMSClient.class);
    KMSManager kmsManager = new KMSManager(mockKMSClient, mockCredentials, mockConfig, group);
    KMSManager partiallyMockedKMSManager = spy(kmsManager);
    doReturn(KMS_ALIAS_ARN).when(partiallyMockedKMSManager).getAliasArn();
    kmsEncryptor = new KMSEncryptor(partiallyMockedKMSManager, mockCredentials, mockConfig, group, mock(AwsCrypto.class), EncryptionStrength.AES_256);

    // Set up store for testing the policy creation methods. Mock out the getArn method with a spy to stop the
    // call to getAccount().
    mockDynamoDBClient = mock(AmazonDynamoDBClient.class);
    DynamoDB store = new DynamoDB(mockDynamoDBClient, mockCredentials, mockConfig, group, new ReentrantReadWriteLock());
    partiallyMockedStore = spy(store);
    doReturn(DYNAMODB_ARN).when(partiallyMockedStore).getArn();
}
 
Example 21
public DynamoDBHelper(final Regions region, final AWSCredentialsProvider credentialsProvider) {
    final ClientConfiguration clientConfiguration = new ClientConfiguration()
            .withConnectionTimeout(ClientConfiguration.DEFAULT_CONNECTION_TIMEOUT)
            .withRetryPolicy(ClientConfiguration.DEFAULT_RETRY_POLICY)
            .withRequestTimeout(ClientConfiguration.DEFAULT_REQUEST_TIMEOUT)
            .withSocketTimeout(ClientConfiguration.DEFAULT_SOCKET_TIMEOUT);
    ddbClient = AmazonDynamoDBClient.builder()
            .withClientConfiguration(clientConfiguration)
            .withCredentials(credentialsProvider)
            .withRegion(region)
            .build();
}
 
Example 22
Source Project: amazon-kinesis-connectors   Source File: DynamoDBUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Amazon DynamoDB table if it does not already exist and have the correct schema. Then it
 * waits for the table to become active.
 * 
 * @param client
 *        The {@link AmazonDynamoDBClient} with Amazon DynamoDB read and write privileges
 * @param tableName
 *        The Amazon DynamoDB table to create
 * @param key
 *        The Amazon DynamoDB table hashkey
 * @param readCapacityUnits
 *        Number of read capacity units for the Amazon DynamoDB table
 * @param writeCapacityUnits
 *        Number of write capacity units for the Amazon DynamoDB table
 * @throws IllegalStateException
 *         Table already exists and schema does not match
 * @throws IllegalStateException
 *         Table is already getting created
 */
public static void createTable(AmazonDynamoDBClient client,
        String tableName,
        String key,
        long readCapacityUnits,
        long writeCapacityUnits) {
    if (tableExists(client, tableName)) {
        if (tableHasCorrectSchema(client, tableName, key)) {
            waitForActive(client, tableName);
            return;
        } else {
            throw new IllegalStateException("Table already exists and schema does not match");
        }

    }
    CreateTableRequest createTableRequest = new CreateTableRequest();
    createTableRequest.setTableName(tableName);
    createTableRequest.setKeySchema(Arrays.asList(new KeySchemaElement(key, KeyType.HASH)));
    createTableRequest.setProvisionedThroughput(new ProvisionedThroughput(readCapacityUnits, writeCapacityUnits));
    createTableRequest.setAttributeDefinitions(Arrays.asList(new AttributeDefinition(key, ScalarAttributeType.S)));
    try {
        client.createTable(createTableRequest);
    } catch (ResourceInUseException e) {
        throw new IllegalStateException("The table may already be getting created.", e);
    }
    LOG.info("Table " + tableName + " created");
    waitForActive(client, tableName);
}
 
Example 23
/**
 * @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();
    }
}
 
Example 24
Source Project: aws-dynamodb-examples   Source File: MoviesItemOps04.java    License: Apache License 2.0 5 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";
        
        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey("year", year, "title", title)
            .withUpdateExpression("set info.rating = info.rating + :val")
            .withValueMap(new ValueMap()
                .withNumber(":val", 1));

        System.out.println("Incrementing an atomic counter...");
        try {
            table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (Exception e) {
            System.out.println("UpdateItem failed");
            e.printStackTrace();
        }

    }
 
Example 25
Source Project: aws-dynamodb-examples   Source File: MoviesItemOps05.java    License: Apache License 2.0 5 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";

        // Conditional update (will fail)

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey(new PrimaryKey("year", 2015, "title",  "The Big New Movie"))
            .withUpdateExpression("remove info.actors[0]")
            .withConditionExpression("size(info.actors) > :num")
            .withValueMap(new ValueMap().withNumber(":num", 3));

        System.out.println("Attempting a conditional update...");
        try {
            table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (ConditionalCheckFailedException e) {
            e.printStackTrace();
            System.out.println("UpdateItem failed");
        }

    }
 
Example 26
Source Project: dynamodb-geo   Source File: GeoDynamoDBServlet.java    License: Apache License 2.0 5 votes vote down vote up
private void setupGeoDataManager() {
	String accessKey = System.getProperty("AWS_ACCESS_KEY_ID");
	String secretKey = System.getProperty("AWS_SECRET_KEY");
	String tableName = System.getProperty("PARAM1");
	String regionName = System.getProperty("PARAM2");

	AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
	AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(credentials);
	Region region = Region.getRegion(Regions.fromName(regionName));
	ddb.setRegion(region);

	config = new GeoDataManagerConfiguration(ddb, tableName);
	geoDataManager = new GeoDataManager(config);
}
 
Example 27
/**
 * Looks up table name and creates one if it does not exist
 */
public DeviceAuthentication() {
    ddb = new AmazonDynamoDBClient();
    ddb.setRegion(RegionUtils.getRegion(Configuration.REGION));
    
    try {
        if (!doesTableExist(DEVICE_TABLE)) {
            createDeviceTable();
        }
    } catch (DataAccessException e) {
        throw new RuntimeException("Failed to create device table.", e);
    }
}
 
Example 28
Source Project: herd   Source File: JCredStashWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for the JCredStashWrapper
 *
 * @param region the aws region location of the KMS Client
 * @param tableName name of the credentials table
 * @param clientConfiguration the AWS client configuration
 */
public JCredStashWrapper(String region, String tableName, ClientConfiguration clientConfiguration)
{
    AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(provider, clientConfiguration).withRegion(Regions.fromName(region));
    AWSKMSClient kms = new AWSKMSClient(provider, clientConfiguration).withRegion(Regions.fromName(region));
    credstash = new JCredStash(tableName, ddb, kms, new CredStashBouncyCastleCrypto());
}
 
Example 29
/**
 * Example object:
 * 
 * {"employee_id":"1", "employee_name":"John Doh", "expense_type":"travel",
 * "amount": "2565.75" }
 */
@Override
public Object handleRequest(Object input, Context context) {
	dynamoDB = new AmazonDynamoDBClient().withRegion(Region
			.getRegion(Regions.EU_WEST_1));
	// TODO
	// Parse the input object into a DynamoDB item, e.g., by using the newItem helper method
	// Create a PutItemRequest and send the request at the DynamoDB table with name 'lambda-reimbursment'

	return "{'status':'done'}";
}
 
Example 30
@Override
public Object handleRequest(Object input, Context context) {
	context.getLogger().log("input: " + input);
	if (input.toString().equals("{}") || input.toString().equals("")) {
		context.getLogger().log("input is empty: abort");
		return "{\"status\":\"error\",\"message\":\"input at lambda function is empty\"}";
	}

	dynamoDB = new AmazonDynamoDBClient().withRegion(Region
			.getRegion(Regions.EU_WEST_1));

	HashMap<String, String> mapInput = (HashMap<String, String>) input;
	Map<String, AttributeValue> employeeKey = new HashMap<String, AttributeValue>();
	String employeeId = mapInput.get("employee_id");
	context.getLogger().log("employee_id: " + employeeId);
	employeeKey.put("employee_id", new AttributeValue().withS(employeeId));
	Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>();
	attributeUpdates.put("approval", new AttributeValueUpdate()
			.withValue(new AttributeValue().withS("approved")));
	UpdateItemRequest updateItemRequest = new UpdateItemRequest()
			.withKey(employeeKey).withAttributeUpdates(attributeUpdates)
			.withTableName("lambda-reimbursment");
	UpdateItemResult updateItemResult = dynamoDB
			.updateItem(updateItemRequest);
	context.getLogger().log("Result: " + updateItemResult);

	return "{'status':'done'}";
}