com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient. 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: MoviesItemOps06.java    From aws-dynamodb-examples with 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 #2
Source File: StreamsAdapterDemoHelper.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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 File: ImageIngester.java    From aws-dynamodb-mars-json-demo with 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 #4
Source File: KinesisClientManager.java    From presto with 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 #5
Source File: DynamoDBBootstrapWorker.java    From dynamodb-import-export-tool with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: DynamoDBBootstrapWorker.java    From dynamodb-import-export-tool with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: KinesisClientManager.java    From presto-kinesis with 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 File: Utilities.java    From reinvent2013-mobile-photo-share with 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 #9
Source File: MCAWS.java    From aws-big-data-blog with Apache License 2.0 5 votes vote down vote up
public static void dynamoInsertHl7Json(String hl7Json, String mirthTable, String mirthId, String mirthDate) {
String firstName = "NONE";
       String lastName = "NONE";
       String dob = "NONE";
       String docType = "hl7";
String messageType = "NONE";

       AmazonDynamoDBClient client = new AmazonDynamoDBClient();
       client.withRegion(Regions.US_WEST_2);
       DynamoDB dynamoDB = new DynamoDB(client);
       Table table = dynamoDB.getTable(mirthTable);
       try {
       JSONObject obj = new JSONObject(hl7Json);

firstName = obj.getJSONObject("HL7Message").getJSONObject("PID").getJSONObject("PID.5").getString("PID.5.2");
lastName = obj.getJSONObject("HL7Message").getJSONObject("PID").getJSONObject("PID.5").getString("PID.5.1");
dob = obj.getJSONObject("HL7Message").getJSONObject("PID").getJSONObject("PID.7").getString("PID.7.1");
messageType = obj.getJSONObject("HL7Message").getJSONObject("MSH").getJSONObject("MSH.9").getString("MSH.9.1");
       } catch (org.json.JSONException e) { System.out.println("HL7 JSON ERROR"); }        

//replace empyty string with value representing blank
       hl7Json = hl7Json.replaceAll("\"\"","\"NONE\"");

       Item item =
           new Item()
               .withPrimaryKey("mirthid", mirthId)
               .withString("mirthdate", mirthDate)
               .withString("type", docType)
               .withString("FirstName", firstName)
               .withString("LastName", lastName)
               .withString("DOB", dob)
               .withString("HL7Type", messageType)
               .withString("Processed", "N")
               .withJSON("document", hl7Json);

       table.putItem(item);
   }
 
Example #10
Source File: DynamoDBBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 * @param accessKeyId
 * @param secretAccessKey
 * @param region
 */
public DynamoDBBackendImpl(String accessKeyId, String secretAccessKey, String region) {
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);
    AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentials);
    client.setRegion(Region.getRegion(Regions.fromName(region)));
    dynamoDB = new DynamoDB(client);
}
 
Example #11
Source File: AbstractDynamoDBProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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
Source File: DynamoDBAnnouncementWatcher.java    From hollow-reference-implementation with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: GenericDynamoDBTest.java    From strongbox with 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 #14
Source File: IAMPolicyManagerTest.java    From strongbox with 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 #15
Source File: DynamoDBHelper.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: DynamoDBService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
public DynamoDBService(Tenant tenant) {
    super(tenant);
    m_retry_wait_millis = getParamInt("retry_wait_millis", 5000);
    m_max_commit_attempts = getParamInt("max_commit_attempts", 10);
    m_max_read_attempts = getParamInt("max_read_attempts", 3);
    m_tenantPrefix = Utils.isEmpty(tenant.getNamespace()) ? "" : tenant.getNamespace() + "_"; 
    
    m_ddbClient = new AmazonDynamoDBClient(getCredentials());
    setRegionOrEndPoint();
    setDefaultCapacity();
    // TODO: Do something to test connection?
}
 
Example #17
Source File: DynamoDBUtils.java    From amazon-kinesis-connectors with 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 #18
Source File: TitanGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
private void open(boolean batchLoading)
{
    if(type == GraphDatabaseType.TITAN_DYNAMODB && config.getDynamodbPrecreateTables()) {
        List<CreateTableRequest> requests = new LinkedList<>();
        long wcu = config.getDynamodbTps();
        long rcu = Math.max(1, config.dynamodbConsistentRead() ? wcu : (wcu / 2));
        for(String store : Constants.REQUIRED_BACKEND_STORES) {
            final String tableName = config.getDynamodbTablePrefix() + "_" + store;
            if(BackendDataModel.MULTI == config.getDynamodbDataModel()) {
                requests.add(DynamoDBStore.createTableRequest(tableName,
                    rcu, wcu));
            } else if(BackendDataModel.SINGLE == config.getDynamodbDataModel()) {
                requests.add(DynamoDBSingleRowStore.createTableRequest(tableName, rcu, wcu));
            }
        }
        //TODO is this autocloseable?
        final AmazonDynamoDB client =
            new AmazonDynamoDBClient(Client.createAWSCredentialsProvider(config.getDynamodbCredentialsFqClassName(),
                config.getDynamodbCredentialsCtorArguments() == null ? null : config.getDynamodbCredentialsCtorArguments().split(",")));
        client.setEndpoint(config.getDynamodbEndpoint());
        for(CreateTableRequest request : requests) {
            try {
                client.createTable(request);
            } catch(ResourceInUseException ignore) {
                //already created, good
            }
        }
        client.shutdown();
    }
    titanGraph = buildTitanGraph(type, dbStorageDirectory, config, batchLoading);
}
 
Example #19
Source File: KinesisRecordSet.java    From presto-kinesis with Apache License 2.0 5 votes vote down vote up
public void checkpoint()
{
    if (checkpointEnabled) {
        if (kinesisShardCheckpointer == null) {
            AmazonDynamoDBClient dynamoDBClient = clientManager.getDynamoDBClient();
            long dynamoReadCapacity = kinesisConnectorConfig.getDynamoReadCapacity();
            long dynamoWriteCapacity = kinesisConnectorConfig.getDynamoWriteCapacity();
            long checkpointIntervalMs = kinesisConnectorConfig.getCheckpointIntervalMS().toMillis();
            String logicalProcessName = kinesisConnectorConfig.getLogicalProcessName();
            String dynamoDBTable = split.getStreamName();
            int curIterationNumber = kinesisConnectorConfig.getIterationNumber();

            String sessionIterationNo = SessionVariables.getSessionProperty(this.session, SessionVariables.ITERATION_NUMBER);
            String sessionLogicalName = SessionVariables.getSessionProperty(this.session, SessionVariables.CHECKPOINT_LOGICAL_NAME);

            if (sessionIterationNo != null) {
                curIterationNumber = Integer.parseInt(sessionIterationNo);
            }

            if (sessionLogicalName != null) {
                logicalProcessName = sessionLogicalName;
            }

            kinesisShardCheckpointer = new KinesisShardCheckpointer(dynamoDBClient,
                    dynamoDBTable,
                    split,
                    logicalProcessName,
                    curIterationNumber,
                    checkpointIntervalMs,
                    dynamoReadCapacity,
                    dynamoWriteCapacity);

            lastReadSeqNo = kinesisShardCheckpointer.getLastReadSeqNo();
        }
    }
}
 
Example #20
Source File: StreamsAdapterDemoHelper.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #21
Source File: MoviesItemOps04.java    From aws-dynamodb-examples with 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 #22
Source File: MoviesItemOps05.java    From aws-dynamodb-examples with 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 #23
Source File: GeoDynamoDBServlet.java    From dynamodb-geo with 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 #24
Source File: DeviceAuthentication.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #25
Source File: JCredStashWrapper.java    From herd with 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 #26
Source File: LambdaFormFunctionHandler.java    From aws-lambda-java-example with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #27
Source File: LambdaApprovalFunctionHandler.java    From aws-lambda-java-example with Apache License 2.0 5 votes vote down vote up
@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'}";
}
 
Example #28
Source File: StreamsAdapterDemoHelper.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
public static void deleteItem(AmazonDynamoDBClient client, String tableName, String id) {
    java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("Id", new AttributeValue().withN(id));

    DeleteItemRequest deleteItemRequest = new DeleteItemRequest()
        .withTableName(tableName)
        .withKey(key);
    client.deleteItem(deleteItemRequest);
}
 
Example #29
Source File: UserAuthentication.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up table name and creates one if it does not exist
 */
public UserAuthentication() {
    ddb = new AmazonDynamoDBClient(new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY));
    ddb.setEndpoint(Configuration.DYNAMODB_ENDPOINT);

    try {
        if (!doesTableExist(USER_TABLE)) {
            createIdentityTable();
        }
    } catch (DataAccessException e) {
        throw new RuntimeException("Failed to create device table.", e);
    }
}
 
Example #30
Source File: DynamoDBTableScanTest.java    From dynamodb-import-export-tool with Apache License 2.0 5 votes vote down vote up
/**
 * Test the parallel executor completion service with multiple segments and
 * make sure it creates the correct number of segments
 */
@Test
public void testGetParallelExecutorCompletionServiceWithVariousNumberOfSegments()
        throws Exception {
    int segments = 0;
    ExecutorService mockExec = createMock(ExecutorService.class);
    mockStatic(RateLimiter.class);
    AmazonDynamoDBClient mockClient = createMock(AmazonDynamoDBClient.class);
    RateLimiter mockRateLimiter = createMock(RateLimiter.class);
    expect(RateLimiter.create(rateLimit)).andReturn(mockRateLimiter);

    replay(RateLimiter.class);
    DynamoDBTableScan scanner = new DynamoDBTableScan(rateLimit, mockClient);
    ParallelScanExecutor mockScanExecutor = createMock(ParallelScanExecutor.class);
    ScanSegmentWorker mockSegmentWorker = createMock(ScanSegmentWorker.class);

    expectNew(ScanSegmentWorker.class, mockClient, mockRateLimiter, req)
            .andReturn(mockSegmentWorker);
    expectNew(ParallelScanExecutor.class, mockExec, 1).andReturn(
            mockScanExecutor);

    mockScanExecutor.addWorker(mockSegmentWorker, 0);

    int segments2 = 3;
    ScanRequest testReq = scanner.copyScanRequest(req).withTotalSegments(
            segments2);
    expectNew(ParallelScanExecutor.class, mockExec, segments2).andReturn(
            mockScanExecutor);
    for (int i = 0; i < segments2; i++) {
        expectNew(ScanSegmentWorker.class, mockClient, mockRateLimiter,
                scanner.copyScanRequest(testReq).withSegment(i)).andReturn(
                mockSegmentWorker);
        mockScanExecutor.addWorker(mockSegmentWorker, i);
    }

    replayAll();
    scanner.getParallelScanCompletionService(req, segments, mockExec, 0, 1);
    scanner.getParallelScanCompletionService(req, segments2, mockExec, 0, 1);
    verifyAll();
}