com.amazonaws.services.dynamodbv2.model.PutItemRequest Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.model.PutItemRequest. 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: LowLevelItemBinaryExample.java    From aws-doc-sdk-examples with Apache License 2.0 7 votes vote down vote up
public static void createItem(String threadId, String replyDateTime) throws IOException {
    // Craft a long message
    String messageInput = "Long message to be compressed in a lengthy forum reply";

    // Compress the long message
    ByteBuffer compressedMessage = compressString(messageInput.toString());

    // Add a the reply
    Map<String, AttributeValue> replyInput = new HashMap<String, AttributeValue>();
    replyInput.put("Id", new AttributeValue().withS(threadId));
    replyInput.put("ReplyDateTime", new AttributeValue().withS(replyDateTime));
    replyInput.put("Message", new AttributeValue().withS("Long message follows"));
    replyInput.put("ExtendedMessage", new AttributeValue().withB(compressedMessage));
    replyInput.put("PostedBy", new AttributeValue().withS("User A"));

    PutItemRequest putReplyRequest = new PutItemRequest().withTableName(tableName).withItem(replyInput);

    client.putItem(putReplyRequest);
}
 
Example #2
Source File: DynamoDbDelegate.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 6 votes vote down vote up
public PutItemResult putItem(final PutItemRequest request) throws BackendException {
    setUserAgent(request);
    PutItemResult result;
    final int bytes = calculateItemSizeInBytes(request.getItem());
    getBytesHistogram(PUT_ITEM, request.getTableName()).update(bytes);
    final int wcu = computeWcu(bytes);
    timedWriteThrottle(PUT_ITEM, request.getTableName(), wcu);

    final Timer.Context apiTimerContext = getTimerContext(PUT_ITEM, request.getTableName());
    try {
        result = client.putItem(request);
    } catch (Exception e) {
        throw processDynamoDbApiException(e, PUT_ITEM, request.getTableName());
    } finally {
        apiTimerContext.stop();
    }
    meterConsumedCapacity(PUT_ITEM, result.getConsumedCapacity());

    return result;
}
 
Example #3
Source File: RequestTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTripPutAll() {
    PutItem r1 = new PutItem();
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(HASH_ATTR_NAME, new AttributeValue("a"));
    item.put("attr_ss", new AttributeValue().withSS("a", "b"));
    item.put("attr_n", new AttributeValue().withN("1"));
    item.put("attr_ns", new AttributeValue().withNS("1", "2"));
    item.put("attr_b", new AttributeValue().withB(ByteBuffer.wrap(new String("asdf").getBytes())));
    item.put("attr_bs", new AttributeValue().withBS(ByteBuffer.wrap(new String("asdf").getBytes()), ByteBuffer.wrap(new String("asdf").getBytes())));
    r1.setRequest(new PutItemRequest()
        .withTableName(TABLE_NAME)
        .withItem(item)
        .withReturnValues("ALL_OLD"));
    byte[] r1Bytes = Request.serialize("123", r1).array();
    Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
    assertEquals(r1.getRequest(), ((PutItem)r2).getRequest());
    byte[] r2Bytes = Request.serialize("123", r2).array();
    assertArrayEquals(r1Bytes, r2Bytes);
}
 
Example #4
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void commitCompletedTransaction() {
    Transaction t1 = manager.newTransaction();
    Transaction commitFailingTransaction = new Transaction(t1.getId(), manager, false) {
        @Override
        protected void doCommit() {
            throw new FailedYourRequestException();
        }
    };
    
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(key1));
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, key1, t1.getId(), true, true);
    
    t1.commit();
    commitFailingTransaction.commit();
}
 
Example #5
Source File: RequestTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTripPutAllJSON() {
    PutItem r1 = new PutItem();
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(HASH_ATTR_NAME, new AttributeValue("a"));
    item.put("json_attr", new AttributeValue().withM(JSON_M_ATTR_VAL));
    r1.setRequest(new PutItemRequest()
        .withTableName(TABLE_NAME)
        .withItem(item)
        .withReturnValues("ALL_OLD"));
    byte[] r1Bytes = Request.serialize("123", r1).array();
    Request r2 = Request.deserialize("123", ByteBuffer.wrap(r1Bytes));
    assertEquals(r1.getRequest(), ((PutItem)r2).getRequest());
    byte[] r2Bytes = Request.serialize("123", r2).array();
    assertArrayEquals(r1Bytes, r2Bytes);
}
 
Example #6
Source File: DeviceAuthentication.java    From reinvent2013-mobile-photo-share with Apache License 2.0 6 votes vote down vote up
/**
 * Store the UID, Key, username combination in the Identity table. The UID
 * will represent the item name and the item will contain attributes key and
 * username.
 * 
 * @param uid
 *            Unique device identifier
 * @param key
 *            encryption key associated with UID
 * @param username
 *            Unique user identifier
 */
protected void storeDevice(String uid, String key, String username) throws DataAccessException {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(ATTRIBUTE_UID, new AttributeValue().withS(uid));
    item.put(ATTRIBUTE_KEY, new AttributeValue().withS(key));
    item.put(ATTRIBUTE_USERNAME, new AttributeValue().withS(username));

    PutItemRequest putItemRequest = new PutItemRequest()
            .withTableName(DEVICE_TABLE)
            .withItem(item);
    try {
        ddb.putItem(putItemRequest);
    } catch (AmazonClientException e) {
        throw new DataAccessException(String.format("Failed to store device uid: %s; key: %s; username: %s", uid,
                key, username), e);
    }
}
 
Example #7
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getItemAfterPutItemInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> getResult1 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertNull(getResult1);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, t1.getId(), true, false);
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(putResult1);
    
    Map<String, AttributeValue> getResult2 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertEquals(getResult2, item1);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example #8
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getItemUncommittedInsert() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1));
    
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    Map<String, AttributeValue> item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1), IsolationLevel.UNCOMMITTED).getItem();
    assertNoSpecialAttributes(item);
    assertEquals(item1, item);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    t1.rollback();
}
 
Example #9
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getItemCommittedInsert() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1));
    
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    Map<String, AttributeValue> item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1), IsolationLevel.COMMITTED).getItem();
    assertNull(item);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    t1.rollback();
}
 
Example #10
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void containsBinaryAttributes() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(key);
    
    item.put("attr_b", new AttributeValue().withB(ByteBuffer.wrap("asdf\n\t\u0123".getBytes())));
    item.put("attr_bs", new AttributeValue().withBS(
        ByteBuffer.wrap("asdf\n\t\u0123".getBytes()),
        ByteBuffer.wrap("wef".getBytes())));
    
    t1.putItem(new PutItemRequest()
            .withTableName(INTEG_HASH_TABLE_NAME)
            .withItem(item));
    
    assertItemLocked(INTEG_HASH_TABLE_NAME, key, item, t1.getId(), true, true);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key, item, true);
}
 
Example #11
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void containsJSONAttributes() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(key);

    item.put("attr_json", new AttributeValue().withM(JSON_M_ATTR_VAL));

    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item));

    assertItemLocked(INTEG_HASH_TABLE_NAME, key, item, t1.getId(), true, true);

    t1.commit();

    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key, item, true);
}
 
Example #12
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void oneTransactionPerItem() {
    Transaction transaction = manager.newTransaction();
    Map<String, AttributeValue> key = newKey(INTEG_HASH_TABLE_NAME);
    
    transaction.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(key));
    try {
        transaction.putItem(new PutItemRequest()
            .withTableName(INTEG_HASH_TABLE_NAME)
            .withItem(key));
        fail();
    } catch(DuplicateRequestException e) {
        transaction.rollback();
    }
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key, false);
    transaction.delete(Long.MAX_VALUE);
}
 
Example #13
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void putItemAllOldInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(putResult1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example #14
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void putItemAllOldOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(putResult1, item0);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example #15
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void rollbackCompletedTransaction() {
    Transaction t1 = manager.newTransaction();
    Transaction rollbackFailingTransaction = new Transaction(t1.getId(), manager, false) {
        @Override
        protected void doRollback() {
            throw new FailedYourRequestException();
        }
    };
    
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(key1));
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, key1, t1.getId(), true, true);
    
    t1.rollback();
    rollbackFailingTransaction.rollback();
}
 
Example #16
Source File: DeviceAuthentication.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Store the UID, Key, username combination in the Identity table. The UID
 * will represent the item name and the item will contain attributes key and
 * username.
 * 
 * @param uid
 *            Unique device identifier
 * @param key
 *            encryption key associated with UID
 * @param username
 *            Unique user identifier
 */
protected void storeDevice(String uid, String key, String username) throws DataAccessException {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(ATTRIBUTE_UID, new AttributeValue().withS(uid));
    item.put(ATTRIBUTE_KEY, new AttributeValue().withS(key));
    item.put(ATTRIBUTE_USERNAME, new AttributeValue().withS(username));

    PutItemRequest putItemRequest = new PutItemRequest()
            .withTableName(DEVICE_TABLE)
            .withItem(item);
    try {
        ddb.putItem(putItemRequest);
    } catch (AmazonClientException e) {
        throw new DataAccessException(String.format("Failed to store device uid: %s; key: %s; username: %s", uid,
                key, username), e);
    }
}
 
Example #17
Source File: UserAuthentication.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Store the username, password combination in the Identity table. The
 * username will represent the item name and the item will contain a
 * attributes password and userid.
 * 
 * @param username
 *            Unique user identifier
 * @param password
 *            user password
 * @param uri
 *            endpoint URI
 */
protected void storeUser(String username, String password, String uri) throws DataAccessException {
    if (null == username || null == password) {
        return;
    }

    String hashedSaltedPassword = Utilities.getSaltedPassword(username, uri, password);

    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(ATTRIBUTE_USERNAME, new AttributeValue().withS(username));
    item.put(ATTRIBUTE_HASH_SALTED_PASSWORD, new AttributeValue().withS(hashedSaltedPassword));
    item.put(ATTRIBUTE_ENABLED, new AttributeValue().withS("true"));

    PutItemRequest putItemRequest = new PutItemRequest()
            .withTableName(USER_TABLE)
            .withItem(item);
    try {
        ddb.putItem(putItemRequest);
    } catch (AmazonClientException e) {
        throw new DataAccessException("Failed to store user: " + username, e);
    }
}
 
Example #18
Source File: DynamoDBReplicationEmitter.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a DynamoDB write request based on the DynamoDB Stream record.
 *
 * @param record
 *            The DynamoDB Stream record containing information about the update to a DynamoDB table
 * @return A DynamoDB request based on the DynamoDB Stream record
 */
private AmazonWebServiceRequest createRequest(final Record record) {
    final String eventName = record.getEventName();
    final AmazonWebServiceRequest request;
    if (eventName.equalsIgnoreCase(OperationType.INSERT.toString()) || eventName.equalsIgnoreCase(OperationType.MODIFY.toString())) {
        // For INSERT or MODIFY: Put the new image in the DynamoDB table
        PutItemRequest putItemRequest = new PutItemRequest();
        putItemRequest.setItem(record.getDynamodb().getNewImage());
        putItemRequest.setTableName(getTableName());
        request = putItemRequest;
    } else if (eventName.equalsIgnoreCase(OperationType.REMOVE.toString())) {
        // For REMOVE: Delete the item from the DynamoDB table
        DeleteItemRequest deleteItemRequest = new DeleteItemRequest();
        deleteItemRequest.setKey(record.getDynamodb().getKeys());
        deleteItemRequest.setTableName(getTableName());
        request = deleteItemRequest;
    } else {
        // This should only happen if DynamoDB Streams adds/changes its operation types
        log.warn("Unsupported operation type detected: " + eventName + ". Record: " + record);
        request = null;
    }
    if (null != request) {
        request.getRequestClientOptions().appendUserAgent(USER_AGENT);
    }
    return request;
}
 
Example #19
Source File: DynamoDBReplicationEmitterTestsBase.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void insertTest() throws Exception {
    // Set up the buffer and do sanity checks
    buffer.clear();
    buffer.consumeRecord(ITEM1_INSERT, ITEM1_INSERT.getDynamodb().getSizeBytes().intValue(), ITEM1_INSERT.getDynamodb().getSequenceNumber());
    assertEquals(ITEM1_INSERT.getDynamodb().getSequenceNumber(), buffer.getFirstSequenceNumber());
    assertEquals(ITEM1_INSERT.getDynamodb().getSequenceNumber(), buffer.getLastSequenceNumber());
    List<Record> buffered = buffer.getRecords();
    assertEquals(1, buffered.size());
    assertTrue(buffered.contains(ITEM1_INSERT));

    // Emit record
    resetAll(DYNAMODB);
    expectNew(AmazonDynamoDBAsyncClient.class, new Class<?>[] {AWSCredentialsProvider.class, ClientConfiguration.class, ExecutorService.class}, anyObject(AWSCredentialsProvider.class), anyObject(ClientConfiguration.class), anyObject(ExecutorService.class)).andReturn(DYNAMODB);
    DYNAMODB.putItemAsync(EasyMock.anyObject(PutItemRequest.class), anyObject(AsyncHandler.class));
    expectLastCall().andAnswer(SUCCESS_ANSWER);

    DYNAMODB.setEndpoint(EasyMock.anyString());
    EasyMock.expectLastCall().anyTimes();
    replayAll(DYNAMODB);
    IEmitter<Record> instance = createEmitterInstance();
    assertTrue(instance.emit(new UnmodifiableBuffer<Record>(buffer)).isEmpty());
    verifyAll();
}
 
Example #20
Source File: DynamoDBReplicationEmitterTestsBase.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void modifyTest() throws Exception {
    // Set up the buffer and do sanity checks
    buffer.clear();
    buffer.consumeRecord(ITEM1_MODIFY, ITEM1_MODIFY.getDynamodb().getSizeBytes().intValue(), ITEM1_MODIFY.getDynamodb().getSequenceNumber());
    assertEquals(ITEM1_MODIFY.getDynamodb().getSequenceNumber(), buffer.getFirstSequenceNumber());
    assertEquals(ITEM1_MODIFY.getDynamodb().getSequenceNumber(), buffer.getLastSequenceNumber());
    List<Record> buffered = buffer.getRecords();
    assertEquals(1, buffered.size());
    assertTrue(buffered.contains(ITEM1_MODIFY));

    // Emit record
    resetAll(DYNAMODB);
    DYNAMODB.putItemAsync(EasyMock.anyObject(PutItemRequest.class), anyObject(AsyncHandler.class));
    expectLastCall().andAnswer(SUCCESS_ANSWER);
    expectNew(AmazonDynamoDBAsyncClient.class, new Class<?>[] {AWSCredentialsProvider.class, ClientConfiguration.class, ExecutorService.class}, anyObject(AWSCredentialsProvider.class), anyObject(ClientConfiguration.class), anyObject(ExecutorService.class)).andReturn(DYNAMODB);
    DYNAMODB.setEndpoint(EasyMock.anyString());
    EasyMock.expectLastCall().anyTimes();
    replayAll(DYNAMODB);
    IEmitter<Record> instance = createEmitterInstance();
    assertTrue(instance.emit(new UnmodifiableBuffer<Record>(buffer)).isEmpty());
    verifyAll();
}
 
Example #21
Source File: DynamoDBReplicationEmitterTestsBase.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void multipleRecordsEmitsTest() throws Exception {
    // Set up the buffer and do sanity checks
    buffer.clear();
    buffer.consumeRecord(ITEM1_INSERT, ITEM1_INSERT.getDynamodb().getSizeBytes().intValue(), ITEM1_INSERT.getDynamodb().getSequenceNumber());
    buffer.consumeRecord(ITEM2_INSERT, ITEM2_INSERT.getDynamodb().getSizeBytes().intValue(), ITEM2_INSERT.getDynamodb().getSequenceNumber());
    assertEquals(ITEM1_INSERT.getDynamodb().getSequenceNumber(), buffer.getFirstSequenceNumber());
    assertEquals(ITEM2_INSERT.getDynamodb().getSequenceNumber(), buffer.getLastSequenceNumber());
    List<Record> buffered = buffer.getRecords();
    assertEquals(2, buffered.size());
    assertTrue(buffered.contains(ITEM1_INSERT));
    assertTrue(buffered.contains(ITEM2_INSERT));

    // Emit record
    resetAll(DYNAMODB);
    DYNAMODB.putItemAsync(EasyMock.anyObject(PutItemRequest.class), anyObject(AsyncHandler.class));
    expectLastCall().andAnswer(SUCCESS_ANSWER).times(2);
    expectNew(AmazonDynamoDBAsyncClient.class, new Class<?>[] {AWSCredentialsProvider.class, ClientConfiguration.class, ExecutorService.class}, anyObject(AWSCredentialsProvider.class), anyObject(ClientConfiguration.class), anyObject(ExecutorService.class)).andReturn(DYNAMODB);
    DYNAMODB.setEndpoint(EasyMock.anyString());
    EasyMock.expectLastCall().anyTimes();
    replayAll(DYNAMODB);
    IEmitter<Record> instance = createEmitterInstance();
    assertTrue(instance.emit(new UnmodifiableBuffer<Record>(buffer)).isEmpty());
    verifyAll();
}
 
Example #22
Source File: MapperTransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    Transaction t = manager.newTransaction();
    hashItem0 = new ExampleHashKeyItem();
    hashItem0.setId(UUID.randomUUID().toString());
    hashItem0.setSomething("val");
    hashItem0.setSomeSet(new HashSet<String>(Arrays.asList("one", "two")));
    t.save(hashItem0);
    key0 = newKey(INTEG_HASH_TABLE_NAME);
    item0 = new HashMap<String, AttributeValue>(key0);
    item0.put("s_someattr", new AttributeValue("val"));
    item0.put("ss_otherattr", new AttributeValue().withSS("one", "two"));
    Map<String, AttributeValue> putResult = t.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item0)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertNull(putResult);
    t.commit();
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0, true);
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, hashItem0.getKey(), hashItem0.getExpectedValues(), true);
}
 
Example #23
Source File: DynamoDBManager.java    From dynamodb-geo with Apache License 2.0 6 votes vote down vote up
public PutPointResult putPoint(PutPointRequest putPointRequest) {
	long geohash = S2Manager.generateGeohash(putPointRequest.getGeoPoint());
	long hashKey = S2Manager.generateHashKey(geohash, config.getHashKeyLength());
	String geoJson = GeoJsonMapper.stringFromGeoObject(putPointRequest.getGeoPoint());

	PutItemRequest putItemRequest = putPointRequest.getPutItemRequest();
	putItemRequest.setTableName(config.getTableName());

	AttributeValue hashKeyValue = new AttributeValue().withN(String.valueOf(hashKey));
	putItemRequest.getItem().put(config.getHashKeyAttributeName(), hashKeyValue);
	putItemRequest.getItem().put(config.getRangeKeyAttributeName(), putPointRequest.getRangeKeyValue());
	AttributeValue geohashValue = new AttributeValue().withN(Long.toString(geohash));
	putItemRequest.getItem().put(config.getGeohashAttributeName(), geohashValue);
	AttributeValue geoJsonValue = new AttributeValue().withS(geoJson);
	putItemRequest.getItem().put(config.getGeoJsonAttributeName(), geoJsonValue);

	PutItemResult putItemResult = config.getDynamoDBClient().putItem(putItemRequest);
	PutPointResult putPointResult = new PutPointResult(putItemResult);

	return putPointResult;
}
 
Example #24
Source File: LowLevelGlobalSecondaryIndexExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void putItem(
    String issueId, String title,
    String description, 
    String createDate, String lastUpdateDate,String dueDate, 
    Integer priority, String status) {

    HashMap<String, AttributeValue> item = new HashMap<String, AttributeValue>();

    item.put("IssueId", new AttributeValue().withS(issueId));
    item.put("Title", new AttributeValue().withS(title));
    item.put("Description", new AttributeValue().withS(description));
    item.put("CreateDate", new AttributeValue().withS(createDate));
    item.put("LastUpdateDate", new AttributeValue().withS(lastUpdateDate));
    item.put("DueDate", new AttributeValue().withS(dueDate));
    item.put("Priority", new AttributeValue().withN(priority.toString()));
    item.put("Status", new AttributeValue().withS(status));

    try {
        client.putItem(new PutItemRequest()
            .withTableName(tableName)
            .withItem(item));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: IndexRangeKeyAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    boolean recreateTable = false;
    setUpTableWithIndexRangeAttribute(recreateTable);
    DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider());
    EncryptionContext context = new EncryptionContext.Builder()
        .withHashKeyName(KEY_NAME)
        .withRangeKeyName(RANGE_KEY)
        .withTableName(TABLE_WITH_INDEX_RANGE_ATTRIBUTE)
        .build();
    // Insert the data
    for ( Map<String, AttributeValue> attr : attrs ) {
        attr = encryptor.encryptAllFieldsExcept(attr, context,
            KEY_NAME,
            RANGE_KEY, 
            INDEX_FOO_RANGE_KEY, 
            INDEX_BAR_RANGE_KEY,
            MULTIPLE_INDEX_RANGE_KEY, 
            VERSION_ATTRIBUTE);
        dynamo.putItem(new PutItemRequest(TABLE_WITH_INDEX_RANGE_ATTRIBUTE, attr));
    }
    mapper = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);
}
 
Example #26
Source File: TransactionItem.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new transaction item into the table.  Assumes txKey is already initialized.
 * @return the txItem
 * @throws TransactionException if the transaction already exists
 */
private Map<String, AttributeValue> insert() {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(AttributeName.STATE.toString(), new AttributeValue(STATE_PENDING));
    item.put(AttributeName.VERSION.toString(), new AttributeValue().withN(Integer.toString(1)));
    item.put(AttributeName.DATE.toString(), txManager.getCurrentTimeAttribute());
    item.putAll(txKey);
    
    Map<String, ExpectedAttributeValue> expectNotExists = new HashMap<String, ExpectedAttributeValue>(2);
    expectNotExists.put(AttributeName.TXID.toString(), new ExpectedAttributeValue(false));
    expectNotExists.put(AttributeName.STATE.toString(), new ExpectedAttributeValue(false));
    
    PutItemRequest request = new PutItemRequest()
        .withTableName(txManager.getTransactionTableName())
        .withItem(item)
        .withExpected(expectNotExists);
    
    try {
        txManager.getClient().putItem(request);
        return item;
    } catch (ConditionalCheckFailedException e) {
        throw new TransactionException("Failed to create new transaction with id " + txId, e);
    }
}
 
Example #27
Source File: StringSetAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    DynamoDBMapperCryptoIntegrationTestBase.setUp();
    DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider());
    EncryptionContext context = new EncryptionContext.Builder()
        .withHashKeyName(KEY_NAME)
        .withTableName(TABLE_NAME)
        .build();
    // Insert the data
    for ( Map<String, AttributeValue> attr : attrs ) {
        Map<String, Set<EncryptionFlags>> flags = encryptor.allEncryptionFlagsExcept(attr, KEY_NAME);
        flags.remove(EXTRA_ATTRIBUTE); // exclude "extra" entirely since
                                       // it's not defined in the
                                       // StringSetAttributeTestClass pojo
        attr = encryptor.encryptRecord(attr, flags, context);
        dynamo.putItem(new PutItemRequest(TABLE_NAME, attr));
    }
}
 
Example #28
Source File: RangeKeyAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    setUpTableWithRangeAttribute();
    DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(new TestEncryptionMaterialsProvider());
    EncryptionContext context = new EncryptionContext.Builder()
        .withHashKeyName(KEY_NAME)
        .withRangeKeyName(RANGE_KEY)
        .withTableName(TABLE_WITH_RANGE_ATTRIBUTE)
        .build();
    // Insert the data
    for ( Map<String, AttributeValue> attr : attrs ) {
        attr = encryptor.encryptAllFieldsExcept(attr, context, KEY_NAME,
                RANGE_KEY, VERSION_ATTRIBUTE, BIG_DECIMAL_ATTRIBUTE);
        dynamo.putItem(new PutItemRequest(TABLE_WITH_RANGE_ATTRIBUTE, attr));
    }
}
 
Example #29
Source File: LowLevelItemBinaryExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void createItem(String threadId, String replyDateTime) throws IOException {
    // Craft a long message
    String messageInput = "Long message to be compressed in a lengthy forum reply";
    
    // Compress the long message
    ByteBuffer compressedMessage = compressString(messageInput.toString());
    
    // Add a the reply
    Map<String, AttributeValue> replyInput = new HashMap<String, AttributeValue>();
    replyInput.put("Id", new AttributeValue().withS(threadId));
    replyInput.put("ReplyDateTime", new AttributeValue().withS(replyDateTime));
    replyInput.put("Message", new AttributeValue().withS("Long message follows"));
    replyInput.put("ExtendedMessage", new AttributeValue().withB(compressedMessage));
    replyInput.put("PostedBy", new AttributeValue().withS("User A"));
    
    PutItemRequest putReplyRequest = new PutItemRequest().withTableName(tableName).withItem(replyInput);
    
    client.putItem(putReplyRequest);
}
 
Example #30
Source File: LowLevelParallelScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void uploadProduct(String tableName, String productIndex) {
    try {
        // Add a book.
        Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
        item.put("Id", new AttributeValue().withN(productIndex));
        item.put("Title", new AttributeValue().withS("Book " + productIndex + " Title"));
        item.put("ISBN", new AttributeValue().withS("111-1111111111"));
        item.put("Authors", new AttributeValue().withSS(Arrays.asList("Author1")));
        item.put("Price", new AttributeValue().withN("2"));
        item.put("Dimensions", new AttributeValue().withS("8.5 x 11.0 x 0.5"));
        item.put("PageCount", new AttributeValue().withN("500"));
        item.put("InPublication", new AttributeValue().withBOOL(true));
        item.put("ProductCategory", new AttributeValue().withS("Book"));
        
        PutItemRequest itemRequest = new PutItemRequest().withTableName(tableName).withItem(item);
        client.putItem(itemRequest);
        item.clear();
        
    }   catch (AmazonServiceException ase) {
        System.err.println("Failed to create item " + productIndex + " in " + tableName);
    }
}