Example usage for com.amazonaws.services.dynamodbv2.document.spec UpdateItemSpec UpdateItemSpec

List of usage examples for com.amazonaws.services.dynamodbv2.document.spec UpdateItemSpec UpdateItemSpec

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.document.spec UpdateItemSpec UpdateItemSpec.

Prototype

public UpdateItemSpec() 

Source Link

Usage

From source file:com.netflix.hollow.example.producer.infrastructure.DynamoDBAnnouncer.java

License:Apache License

@Override
public void announce(long stateVersion) {
    Table table = dynamoDB.getTable(tableName);

    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("namespace", blobNamespace)
            .withUpdateExpression("set #version = :ver").withNameMap(new NameMap().with("#version", "version"))
            .withValueMap(new ValueMap().withNumber(":ver", stateVersion));

    table.updateItem(updateItemSpec);/*w  w w. j  av  a2 s.c o  m*/
}

From source file:com.nodestone.ksum.RecordProcessor.java

License:Open Source License

/**
 * Update DynamoDB record:/*from   ww  w. j a v  a 2 s  . c o m*/
 *  - updating updates count
 *  - updating total sum
 */
private void updateRecord(RawData rawData) {
    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("CustomerId", rawData.custId)
            .withUpdateExpression("set TotalSum = TotalSum + :val, Updates = Updates + :inc")
            .withValueMap(
                    new ValueMap().withNumber(":val", Integer.parseInt(rawData.value)).withNumber(":inc", 1))
            .withReturnValues(ReturnValue.UPDATED_NEW);

    try {
        UpdateItemOutcome outcome = this.dbTable.updateItem(updateItemSpec);

        LOG.info("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());
    } catch (Exception e) {
        LOG.info("Update failed with exception:");
        LOG.info(e.getMessage());
    }
}

From source file:com.yahoo.athenz.zts.cert.impl.DynamoDBCertRecordStoreConnection.java

License:Apache License

@Override
public boolean updateX509CertRecord(X509CertRecord certRecord) {

    final String primaryKey = getPrimaryKey(certRecord.getProvider(), certRecord.getInstanceId(),
            certRecord.getService());//w w w.  j a  v a2  s .  com

    try {
        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(KEY_PRIMARY, primaryKey)
                .withAttributeUpdate(new AttributeUpdate(KEY_INSTANCE_ID).put(certRecord.getInstanceId()),
                        new AttributeUpdate(KEY_PROVIDER).put(certRecord.getProvider()),
                        new AttributeUpdate(KEY_SERVICE).put(certRecord.getService()),
                        new AttributeUpdate(KEY_CURRENT_SERIAL).put(certRecord.getCurrentSerial()),
                        new AttributeUpdate(KEY_CURRENT_IP).put(certRecord.getCurrentIP()),
                        new AttributeUpdate(KEY_CURRENT_TIME).put(certRecord.getCurrentTime().getTime()),
                        new AttributeUpdate(KEY_PREV_SERIAL).put(certRecord.getPrevSerial()),
                        new AttributeUpdate(KEY_PREV_IP).put(certRecord.getPrevIP()),
                        new AttributeUpdate(KEY_PREV_TIME).put(certRecord.getPrevTime().getTime()),
                        new AttributeUpdate(KEY_CLIENT_CERT).put(certRecord.getClientCert()),
                        new AttributeUpdate(KEY_TTL)
                                .put(certRecord.getCurrentTime().getTime() / 1000L + expiryTime));
        table.updateItem(updateItemSpec);
        return true;
    } catch (Exception ex) {
        LOGGER.error("DynamoDB Update Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
        return false;
    }
}

From source file:io.ignitr.dispatchr.manager.core.data.ClientRepository.java

License:Apache License

/**
 *
 * @param newClient/*from   w  ww.  j av a 2s.  co m*/
 * @return
 */
public Observable<Client> update(Client newClient) {
    return findOne(newClient.getClientId()).last().map(oldClient -> {
        Table clientTable = dynamoDB.getTable(CLIENT_TABLE_NAME);

        UpdateItemOutcome outcome = clientTable
                .updateItem(new UpdateItemSpec().withPrimaryKey("clientId", oldClient.getClientId())
                        .withAttributeUpdate(new AttributeUpdate("ownerName").put(newClient.getOwnerName()))
                        .withAttributeUpdate(new AttributeUpdate("ownerEmail").put(newClient.getOwnerEmail())));

        Item item = outcome.getItem();

        return convertFromItem(item);
    });
}

From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java

License:Open Source License

@Override
public E update(K key, JsonPatch patch, boolean increment, long version) {
    final PrimaryKey pk = createKeys(key);
    Preconditions.checkNotNull(patch, "patch must not be null");
    Preconditions.checkArgument(version >= -1);

    ExpressionSpecBuilder builder = patch.get();

    //add a condition on item existence
    builder.withCondition(ExpressionSpecBuilder.attribute_exists(hashKeyName));
    //add update expression for incrementing the version
    if (increment && versionProperty != null) {
        builder.addUpdate(ExpressionSpecBuilder.N(versionProperty)
                .set(ExpressionSpecBuilder.N(versionProperty).plus(1L)));
    }//from ww  w  . j a  va  2  s .  c o  m
    //add version condition
    if (version >= 0) {
        Preconditions.checkState(versionProperty != null);
        builder.withCondition(ExpressionSpecBuilder.N(versionProperty).eq(version));
    }

    UpdateItemExpressionSpec spec = builder.buildForUpdate();
    Preconditions.checkArgument(false == Strings.isNullOrEmpty(spec.getUpdateExpression()),
            "patch may not be empty"); // TODO add mechanism to JSON patch to allow iterating over list of ops
    try {
        UpdateItemOutcome updateItemOutcome = table.updateItem(new UpdateItemSpec().withExpressionSpec(spec)
                .withPrimaryKey(pk).withReturnValues(ReturnValue.ALL_NEW));
        return convertItemToDomain(updateItemOutcome.getItem());
    } catch (AmazonClientException e) {
        throw processUpdateItemException(key, e);
    }
}

From source file:org.chodavarapu.jgitaws.repositories.ConfigurationRepository.java

License:Eclipse Distribution License

public Observable<Void> updateConfiguration(String repositoryName, String text) {
    return configuration.getDynamoClient().updateItem(configuration.getConfigurationsTableName(),
            new UpdateItemSpec().withPrimaryKey(REPOSITORY_NAME_ATTRIBUTE, repositoryName)
                    .withAttributeUpdate(new AttributeUpdate(TEXT_ATTRIBUTE).put(text)),
            () -> new CreateTableRequest().withTableName(configuration.getConfigurationsTableName())
                    .withKeySchema(new KeySchemaElement().withAttributeName(REPOSITORY_NAME_ATTRIBUTE)
                            .withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(
                            new AttributeDefinition().withAttributeName(REPOSITORY_NAME_ATTRIBUTE)
                                    .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(new ProvisionedThroughput(
                            configuration.getInitialConfigurationsTableReadThroughput(),
                            configuration.getInitialConfigurationsTableWriteThroughput())));
}

From source file:org.chodavarapu.jgitaws.repositories.RefRepository.java

License:Eclipse Distribution License

public Observable<Boolean> compareAndPut(String repositoryName, Ref oldRef, Ref newRef) {
    boolean isSymbolic = newRef.isSymbolic();
    boolean isPeeled = newRef.isPeeled();
    String target = newRef.isSymbolic() ? newRef.getTarget().getName() : newRef.getObjectId().name();

    logger.debug("Saving ref {} -> {} in repository {}", newRef.getName(), target, repositoryName);

    UpdateItemSpec updateSpec = new UpdateItemSpec()
            .withPrimaryKey(new PrimaryKey(new KeyAttribute(REPOSITORY_NAME_ATTRIBUTE, repositoryName),
                    new KeyAttribute(NAME_ATTRIBUTE, newRef.getName())));

    StringBuilder updateExpression = new StringBuilder(COMPARE_AND_PUT_EXPRESSION);
    ValueMap valueMap = new ValueMap().withString(":target", target).withBoolean(":isSymbolic", isSymbolic)
            .withBoolean(":isPeeled", isPeeled);

    if (isPeeled && newRef.getPeeledObjectId() != null) {
        updateExpression.append(", ");
        updateExpression.append(PEELED_TARGET_ATTRIBUTE);
        updateExpression.append(" = :peeledTarget");
        valueMap = valueMap.withString(":peeledTarget", newRef.getPeeledObjectId().name());
    }/*from   ww  w  .  j a v  a2s. c o  m*/

    if (oldRef != null && oldRef.getStorage() != Ref.Storage.NEW) {
        String expected = oldRef.isSymbolic() ? oldRef.getTarget().getName() : oldRef.getObjectId().name();
        updateSpec = updateSpec.withConditionExpression("#target = :expected")
                .withNameMap(new NameMap().with("#target", TARGET_ATTRIBUTE));
        valueMap = valueMap.withString(":expected", expected);
    }

    updateSpec = updateSpec.withUpdateExpression(updateExpression.toString()).withValueMap(valueMap);

    return configuration.getDynamoClient()
            .updateItem(configuration.getRefsTableName(), updateSpec, tableCreator).map(v -> true)
            .doOnNext(v -> logger.debug("Saved ref {} in repository {}", newRef.getName(), repositoryName))
            .onErrorReturn(t -> false);
}

From source file:org.springframework.integration.aws.metadata.DynamoDbMetaDataStore.java

License:Apache License

@Override
public String putIfAbsent(String key, String value) {
    Assert.hasText(key, "'key' must not be empty.");
    Assert.hasText(value, "'value' must not be empty.");

    awaitForActive();//from  w ww  . j  ava 2s.  co m

    try {
        this.table.updateItem(new UpdateItemSpec().withPrimaryKey(KEY, key)
                .withAttributeUpdate(new AttributeUpdate(VALUE).put(value))
                .withExpected(new Expected(KEY).notExist()));

        return null;
    } catch (ConditionalCheckFailedException e) {
        return get(key);
    }
}

From source file:org.springframework.integration.aws.metadata.DynamoDbMetaDataStore.java

License:Apache License

@Override
public boolean replace(String key, String oldValue, String newValue) {
    Assert.hasText(key, "'key' must not be empty.");
    Assert.hasText(oldValue, "'value' must not be empty.");
    Assert.hasText(newValue, "'newValue' must not be empty.");

    awaitForActive();//from w w  w.  j a v  a 2 s.c o  m

    try {
        return this.table.updateItem(new UpdateItemSpec().withPrimaryKey(KEY, key)
                .withAttributeUpdate(new AttributeUpdate(VALUE).put(newValue))
                .withExpected(new Expected(VALUE).eq(oldValue)).withReturnValues(ReturnValue.UPDATED_NEW))
                .getItem() != null;
    } catch (ConditionalCheckFailedException e) {
        return false;
    }
}