本文整理汇总了Java中com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException类的典型用法代码示例。如果您正苦于以下问题:Java ConditionalCheckFailedException类的具体用法?Java ConditionalCheckFailedException怎么用?Java ConditionalCheckFailedException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ConditionalCheckFailedException类属于com.amazonaws.services.dynamodbv2.model包,在下文中一共展示了ConditionalCheckFailedException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: create
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override public Void create(Group group) {
Item item = preparePutItem(group);
PutItemSpec putItemSpec = new PutItemSpec()
.withItem(item)
.withConditionExpression("attribute_not_exists(#ns_key)")
.withNameMap(new NameMap().with("#ns_key", HASH_KEY));
Table table = dynamoDB.getTable(groupTableName);
final Supplier<PutItemOutcome> putItemOutcomeSupplier = () -> {
try {
return table.putItem(putItemSpec);
} catch (ConditionalCheckFailedException e) {
throwConflictAlreadyExists(group);
return null;
}
};
return putItem(group, putItemOutcomeSupplier);
}
示例2: update
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override
public void update(Entry entry, Entry existingEntry) {
readWriteLock.writeLock().lock();
try {
Map<String, AttributeValue> keys = createKey(entry);
Map<String, AttributeValueUpdate> attributes = createAttributes(entry);
Map<String, ExpectedAttributeValue> expected = expectExists(existingEntry);
try {
executeUpdate(keys, attributes, expected);
} catch (ConditionalCheckFailedException e) {
throw new DoesNotExistException("Precondition to update entry in DynamoDB failed:" + keys.toString());
}
} finally {
readWriteLock.writeLock().unlock();
}
}
示例3: tryAddMissingPartition
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
private boolean tryAddMissingPartition(String dyanmoDBTaableName,DynamoDB dynamoDBClient, Partition partition){
Table ddbTable= dynamoDBClient.getTable(dyanmoDBTaableName);
Item item=new Item()
.withPrimaryKey("PartitionSpec",partition.spec())
.withString("PartitionPath",partition.path())
.withString("PartitionName", partition.name());
PutItemSpec itemSpec=new PutItemSpec()
.withItem(item)
.withConditionExpression("attribute_not_exists(#ps)")
.withNameMap(new NameMap()
.with("#ps","PartitionSpec"));
try{
ddbTable.putItem(itemSpec);
System.out.println("Item was added to the table.PartitionSpec="+partition.spec()+"; Path="+partition.path());
return true;
}
catch(ConditionalCheckFailedException e){
System.out.println(e.toString());
System.out.println("Item already exists. PartitionSpec="+partition.spec()+"; Path="+partition.path());
return false;
}
}
开发者ID:awslabs,项目名称:serverless-cf-analysis,代码行数:27,代码来源:CreateAthenaPartitionsBasedOnS3EventWithDDB.java
示例4: create
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override
public void create(Entry entry) {
readWriteLock.writeLock().lock();
try {
Map<String, AttributeValue> keys = createKey(entry);
Map<String, AttributeValueUpdate> attributes = createAttributes(entry);
Map<String, ExpectedAttributeValue> expected = expectNotExists();
try {
executeUpdate(keys, attributes, expected);
} catch (ConditionalCheckFailedException e) {
throw new AlreadyExistsException("DynamoDB store entry already exists:" + keys.toString());
}
} finally {
readWriteLock.writeLock().unlock();
}
}
示例5: testCreateEntryAlreadyExists
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Test
public void testCreateEntryAlreadyExists() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, false, Optional.empty());
// Already exists will cause a check failed exception.
when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow(
new ConditionalCheckFailedException(""));
boolean exceptionThrown = false;
try {
dynamoDB.create(rawSecretEntry);
} catch (AlreadyExistsException e) {
assertEquals(e.getMessage(), "DynamoDB store entry already exists:{1={S: secret1,}, 2={N: 1,}}");
exceptionThrown = true;
}
assertTrue(exceptionThrown);
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
示例6: testUpdateEntryDoesNotExist
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Test
public void testUpdateEntryDoesNotExist() throws Exception {
RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME);
RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME);
UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(alternativeRawSecretEntry));
when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow(
new ConditionalCheckFailedException(""));
boolean exceptionThrown = false;
try {
dynamoDB.update(rawSecretEntry, alternativeRawSecretEntry);
} catch (DoesNotExistException e) {
assertEquals(e.getMessage(), "Precondition to update entry in DynamoDB failed:{1={S: secret1,}, 2={N: 1,}}");
exceptionThrown = true;
}
assertTrue(exceptionThrown);
// Check all the expected calls to AWS were made.
verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest);
}
示例7: createItemIfNotExists
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
boolean createItemIfNotExists(String key, long currentTimeMillis, Context context) {
LambdaLogger logger = context.getLogger();
AmazonDynamoDB client = createDynamoDBClient(cc);
String functionName = context.getFunctionName();
try {
// Create a record if it does not exist
PutItemRequest req = new PutItemRequest().withTableName(TABLE_NAME)
.addItemEntry(COL_FUNCTION_NAME, new AttributeValue(functionName))
.addItemEntry(COL_KEY, new AttributeValue(key))
.addItemEntry(COL_CREATED_TIME, new AttributeValue().withN(Long.toString(currentTimeMillis)))
.addExpectedEntry(COL_FUNCTION_NAME, new ExpectedAttributeValue().withExists(false))
.addExpectedEntry(COL_KEY, new ExpectedAttributeValue().withExists(false));
client.putItem(req);
return true;
} catch (ConditionalCheckFailedException e) {
logger.log("Record exsited. functionName[" + functionName + "] key[" + key + "]");
return false;
} finally {
client.shutdown();
}
}
示例8: putItemOrThrow
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override
public void putItemOrThrow(T item) {
try {
Expected[] expected;
if ( null == _rkName ) {
expected = new Expected[]{
new Expected(_hkName).notExist()
};
} else {
expected = new Expected[]{
new Expected(_hkName).notExist(),
new Expected(_rkName).notExist()
};
}
maybeBackoff(false, () ->
_putItem.putItem(_encryption.encrypt(toItem(item)), expected));
} catch ( ConditionalCheckFailedException ex ) {
throw new EntityExistsException(ex);
}
}
示例9: transform
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override
public void transform(Item scoreItem, DynamoDB dynamodb) {
String playerName = scoreItem.getString(PLAYER_NAME);
int score = scoreItem.getInt(SCORE);
String date = scoreItem.getString(DATE);
Table table = dynamodb.getTable(HIGH_SCORES_BY_DATE_TABLE_NAME);
// Use conditional write to update max score
UpdateItemExpressionSpec updateMax = new ExpressionSpecBuilder()
.withCondition(N(MAX_SCORE).lt(score)
.or(attribute_not_exists(MAX_SCORE)))
.addUpdate(N(MAX_SCORE).set(score))
.buildForUpdate();
try {
table.updateItem(PLAYER_NAME, playerName, DATE, date, updateMax);
} catch (ConditionalCheckFailedException ccfe) {}
}
示例10: delete
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override
public <T extends Message> boolean delete(T item, Modifier... modifiers) throws DataStoreException {
DynamoClassMapping<T> tableInfo = getClassMapping(item);
log.debug("Delete {}", item);
for (Modifier modifier : modifiers) {
throw new UnsupportedOperationException();
}
DeleteItemRequest request = new DeleteItemRequest();
request.setTableName(tableInfo.getDynamoTableName());
request.setKey(tableInfo.buildCompleteKey(item));
request.setConditionExpression("attribute_exists(hash_key)");
try {
DeleteItemResult response = dynamoDB.deleteItem(request);
return true;
} catch (ConditionalCheckFailedException e) {
return false;
}
}
示例11: createFeature
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
@Override public Void createFeature(Feature feature) {
final String key = feature.getKey();
final String group = feature.getGroup();
final Item item = preparePutItem(feature);
final PutItemSpec putItemSpec = new PutItemSpec()
.withItem(item)
.withConditionExpression("attribute_not_exists(#featurekey)")
.withNameMap(new NameMap().with("#featurekey", RANGE_KEY));
final Supplier<PutItemOutcome> putItemOutcomeSupplier = () -> {
try {
return dynamoDB.getTable(featureTableName).putItem(putItemSpec);
} catch (ConditionalCheckFailedException e) {
logger.error("err=conflict_feature_already_exists feature_key={} {}", feature.getKey(),
e.getMessage());
throwConflictAlreadyExists(feature);
return null;
}
};
final DynamoDbCommand<PutItemOutcome> cmd = new DynamoDbCommand<>("createFeature",
putItemOutcomeSupplier,
() -> {
throw new RuntimeException("createFeature");
},
hystrixWriteConfiguration,
metrics);
final PutItemOutcome outcome = cmd.execute();
logger.info("{} /dynamodb_put_item_result=[{}]",
kvp("op", "createFeature", HASH_KEY, group, RANGE_KEY, key, "result", "ok"),
outcome.getPutItemResult().toString());
return null;
}
示例12: updateItem
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
boolean updateItem(String key, long currentTimeMillis, int expiredIntervalMillis, Context context) {
AmazonDynamoDB client = createDynamoDBClient(cc);
String functionName = context.getFunctionName();
try {
long sec = currentTimeMillis - expiredIntervalMillis;
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable(TABLE_NAME);
Map<String, String> expressionAttributeNames = new HashMap<>();
expressionAttributeNames.put("#created_time", COL_CREATED_TIME);
Map<String, Object> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":now", currentTimeMillis);
expressionAttributeValues.put(":expired", sec);
table.updateItem(new PrimaryKey(COL_FUNCTION_NAME, functionName, COL_KEY, key), "set #created_time = :now", // UpdateExpression
"#created_time < :expired", // ConditionExpression
expressionAttributeNames, expressionAttributeValues);
return true;
} catch (ConditionalCheckFailedException e) {
return false;
} finally {
client.shutdown();
}
}
示例13: insertFood
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
/**
* Inserting the food into the database, dislike and like are set to 0
* @param food
*/
public static void insertFood(FoodReceive food){
Log.d(LOG_TAG, "Inserting: " + food.getName());
final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
final FoodDO firstItem = new FoodDO();
firstItem.setFoodId(food.getFood_id());
firstItem.setRestaurantId(food.getLocation().getRestaurantId());
firstItem.setName(food.getName());
AmazonClientException lastException = null;
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
Map<String, ExpectedAttributeValue> expectedAttributes =
ImmutableMapParameter.<String, ExpectedAttributeValue>builder()
.put("foodId", new ExpectedAttributeValue(false)).build();
saveExpression.setExpected(expectedAttributes);
try {
// mapper.save(firstItem);
mapper.save(firstItem, saveExpression);
} catch (ConditionalCheckFailedException e){
Log.e(LOG_TAG,"The foodId exists: " + e.getMessage());
lastException = e;
} catch (final AmazonClientException ex) {
Log.e(LOG_TAG,"Failed saving item batch: " + ex.getMessage());
lastException = ex;
}
if (lastException != null) {
// Re-throw the last exception encountered to alert the user.
throw lastException;
}
Log.d(LOG_TAG, "Insert successful");
}
示例14: updateItem
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
private <V> V updateItem(UpdateItemSpec updateItemSpec, Class<V> type) {
try {
return maybeBackoff(false, () ->
fromItem(_encryption.decrypt(_updateItem.updateItem(updateItemSpec).getItem()), type));
} catch ( ConditionalCheckFailedException ex ) {
throw new RollbackException(ex);
}
}
示例15: tryLock
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; //导入依赖的package包/类
/**
* Acquires a distributed lock, returning true if it was acquired, false otherwise
*
* The lock, if acquired, has the passed expiry period in seconds. This means if another process attempts to
* aquire it, it will fail until now + expiryInSeconds, after which time it will succeed. This prevents the lock
* from being permanently locked, in case the acquiring process fails to release it for whatever reason.
*
* This is an atomic operation, only one process can acquire a lock at a time - if two processes contend
* for a lock, only one will ever get a return value of true from this method.
*/
@Override
public boolean tryLock(String lockKey, int expiryInSeconds) {
try {
lockKey = getEnvironmentSpecificLockKey(lockKey);
logger.info("Trying to acquire lock [{}]", lockKey);
Table table = dynamoDb.getTable(tableName);
Item lock = new Item()
.withPrimaryKey(TABLE_KEY, lockKey)
.withLong(LOCK, clock.millis() + (expiryInSeconds * 1000L))
.withString(TABLE_CREATED_AT, OffsetDateTime.now(clock).toString());
// create the lock if it doesn't exist, OR overwrite it if it's expired
table.putItem(
lock,
"attribute_not_exists(#id) OR #lockExpiry < :now",
ImmutableMap.of("#id", TABLE_KEY, "#lockExpiry", LOCK),
ImmutableMap.of(":now", clock.millis())
);
logger.info("Acquired lock [{}]", lockKey);
return true;
} catch (ConditionalCheckFailedException e) { // thrown if we tried to acquire a locked lock
logger.info("Could not acquire locked lock [{}]", lockKey);
} catch (Exception ex) { // thrown on any other, unexpected, error performing the request
logger.error("Error when trying to aquire lock [{}]: ", lockKey, ex);
}
return false;
}