Example usage for com.amazonaws.services.simpledb.model UpdateCondition setExists

List of usage examples for com.amazonaws.services.simpledb.model UpdateCondition setExists

Introduction

In this page you can find the example usage for com.amazonaws.services.simpledb.model UpdateCondition setExists.

Prototype


public void setExists(Boolean exists) 

Source Link

Document

A value specifying whether or not the specified attribute must exist with the specified value in order for the update condition to be satisfied.

Usage

From source file:c3.ops.priam.aws.SDBInstanceData.java

License:Apache License

/**
 * Register a new instance. Registration will fail if a prior entry exists
 *
 * @param instance/*w ww.  java  2s. c  o m*/
 * @throws AmazonServiceException
 */
public void registerInstance(PriamInstance instance) throws AmazonServiceException {
    AmazonSimpleDBClient simpleDBClient = getSimpleDBClient();
    PutAttributesRequest putReq = new PutAttributesRequest(DOMAIN, getKey(instance),
            createAttributesToRegister(instance));
    UpdateCondition expected = new UpdateCondition();
    expected.setName(Attributes.INSTANCE_ID);
    expected.setExists(false);
    putReq.setExpected(expected);
    simpleDBClient.putAttributes(putReq);
}

From source file:com.aipo.aws.simpledb.SimpleDB.java

License:Open Source License

private static Integer counterJob(String domain) {
    AmazonSimpleDB client = getClient();
    GetAttributesRequest getAttributesRequest = new GetAttributesRequest();
    getAttributesRequest.setDomainName(DEFAULT_COUNTER_DOMAIN);
    getAttributesRequest.setItemName(domain);
    getAttributesRequest.setConsistentRead(true);
    Integer count = null;//  ww w .  j a va  2s. c o  m
    try {
        GetAttributesResult attributes = client.getAttributes(getAttributesRequest);
        List<Attribute> list = attributes.getAttributes();
        for (Attribute item : list) {
            if ("c".equals(item.getName())) {
                try {
                    count = Integer.valueOf(item.getValue());
                } catch (Throwable ignore) {

                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (count == null) {
        CreateDomainRequest createDomainRequest = new CreateDomainRequest(DEFAULT_COUNTER_DOMAIN);
        client.createDomain(createDomainRequest);
        count = 0;
    }

    int next = count + 1;
    PutAttributesRequest putAttributesRequest = new PutAttributesRequest();
    putAttributesRequest.setDomainName(DEFAULT_COUNTER_DOMAIN);
    putAttributesRequest.setItemName(domain);
    List<ReplaceableAttribute> attr = new ArrayList<ReplaceableAttribute>();
    attr.add(new ReplaceableAttribute("c", String.valueOf(next), true));
    putAttributesRequest.setAttributes(attr);
    UpdateCondition updateCondition = new UpdateCondition();
    if (next == 1) {
        updateCondition.setExists(false);
        updateCondition.setName("c");
    } else {
        updateCondition.setExists(true);
        updateCondition.setName("c");
        updateCondition.setValue(String.valueOf(count));
    }
    putAttributesRequest.setExpected(updateCondition);

    client.putAttributes(putAttributesRequest);

    return next;
}

From source file:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public int put(String itemName, Optional<Integer> version, ReplaceableAttribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }//from   www  .j  av a  2  s . co  m

    logger.log("About to add attrbutes to simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // Check the put will not take us over the maximum number of attributes:
    // N.B. if (replace == true) then this check could be over-eager, but not
    // worth refining it, since this effectively just alters the limit by one.
    ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

    if (versionedAttributes.left.isPresent()) {
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ")  have version number: " + versionedAttributes.left.get());
    } else {
        // There should be no attributes in this case.
        logger.log("Retrieved versioned attributes(Count: " + versionedAttributes.right.size()
                + ") have no version number");
    }

    Boolean tooManyAttributes = versionedAttributes.right.size() >= maxNumberOfAttributes;
    if (tooManyAttributes && !attribute.getValue().startsWith("Inactive")) {
        // We allow puts to inactivate attributes even when on the limit -
        // otherwise we could never delete when we're on the limit.
        logger.log("Cannot create attribute - the maximum number of attributes already exists ("
                + maxNumberOfAttributes
                + ") so throwing a 'Database put failed - too many attributes' exception");
        throw new Exception("Database put failed - too many attributes");
    }

    // Do a conditional put - so we don't overwrite someone else's attributes
    UpdateCondition updateCondition = new UpdateCondition();
    updateCondition.setName(versionAttributeName);
    ReplaceableAttribute versionAttribute = new ReplaceableAttribute();
    versionAttribute.setName(versionAttributeName);
    versionAttribute.setReplace(true);
    // Update will proceed unless the version number has changed
    if (version.isPresent()) {
        // A version number attribute exists - so it should be unchanged
        updateCondition.setValue(Integer.toString(version.get()));
        // Bump up our version number attribute
        versionAttribute.setValue(Integer.toString(version.get() + 1));
    } else {
        // A version number attribute did not exist - so it still should not
        updateCondition.setExists(false);
        // Set initial value for our version number attribute
        versionAttribute.setValue("0");
    }

    List<ReplaceableAttribute> replaceableAttributes = new ArrayList<>();
    replaceableAttributes.add(versionAttribute);

    // Add the new attribute
    replaceableAttributes.add(attribute);

    PutAttributesRequest simpleDBPutRequest = new PutAttributesRequest(simpleDbDomainName, itemName,
            replaceableAttributes, updateCondition);

    try {
        client.putAttributes(simpleDBPutRequest);
    } catch (AmazonServiceException ase) {
        if (ase.getErrorCode().contains("ConditionalCheckFailed")) {
            // Someone else has mutated an attribute since we read them. This is
            // likely to be rare, and a retry should almost always succeed. However,
            // we leave it to clients of this class to retry the call if they wish,
            // as the new mutation may mean they no longer want to do the put.
            logger.log("Caught AmazonServiceException for ConditionalCheckFailed whilst creating"
                    + " attribute(s) so throwing as 'Database put failed' instead");
            throw new Exception("Database put failed - conditional check failed");
        }
        throw ase;
    }

    logger.log("Created attribute(s) in simpledb");

    return Integer.parseInt(versionAttribute.getValue());
}

From source file:squash.booking.lambdas.core.OptimisticPersister.java

License:Apache License

@Override
public void delete(String itemName, Attribute attribute) throws Exception {

    if (!initialised) {
        throw new IllegalStateException("The optimistic persister has not been initialised");
    }/*from   w w w .j  av  a2  s  .  co  m*/

    logger.log("About to delete attribute from simpledb item: " + itemName);

    AmazonSimpleDB client = getSimpleDBClient();

    // We retry the delete if necessary if we get a
    // ConditionalCheckFailed exception, i.e. if someone else modifies the
    // database between us reading and writing it.
    RetryHelper.DoWithRetries(() -> {
        try {
            // Get existing attributes (and version number), via consistent
            // read:
            ImmutablePair<Optional<Integer>, Set<Attribute>> versionedAttributes = get(itemName);

            if (!versionedAttributes.left.isPresent()) {
                logger.log(
                        "A version number attribute did not exist - this means no attributes exist, so we have nothing to delete.");
                return null;
            }
            if (!versionedAttributes.right.contains(attribute)) {
                logger.log("The attribute did not exist - so we have nothing to delete.");
                return null;
            }

            // Since it seems impossible to update the version number while
            // deleting an attribute, we first mark the attribute as inactive,
            // and then delete it.
            ReplaceableAttribute inactiveAttribute = new ReplaceableAttribute();
            inactiveAttribute.setName(attribute.getName());
            inactiveAttribute.setValue("Inactive" + attribute.getValue());
            inactiveAttribute.setReplace(true);
            put(itemName, versionedAttributes.left, inactiveAttribute);

            // Now we can safely delete the attribute, as other readers will now
            // ignore it.
            UpdateCondition updateCondition = new UpdateCondition();
            updateCondition.setName(inactiveAttribute.getName());
            updateCondition.setValue(inactiveAttribute.getValue());
            // Update will proceed unless the attribute no longer exists
            updateCondition.setExists(true);

            Attribute attributeToDelete = new Attribute();
            attributeToDelete.setName(inactiveAttribute.getName());
            attributeToDelete.setValue(inactiveAttribute.getValue());
            List<Attribute> attributesToDelete = new ArrayList<>();
            attributesToDelete.add(attributeToDelete);
            DeleteAttributesRequest simpleDBDeleteRequest = new DeleteAttributesRequest(simpleDbDomainName,
                    itemName, attributesToDelete, updateCondition);
            client.deleteAttributes(simpleDBDeleteRequest);
            logger.log("Deleted attribute from simpledb");
            return null;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().contains("AttributeDoesNotExist")) {
                // Case of trying to delete an attribute that no longer exists -
                // that's ok - it probably just means more than one person was
                // trying to delete the attribute at once. So swallow this
                // exception
                logger.log(
                        "Caught AmazonServiceException for AttributeDoesNotExist whilst deleting attribute so"
                                + " swallowing and continuing");
                return null;
            } else {
                throw ase;
            }
        }
    }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger);
}

From source file:wwutil.jsoda.SimpleDBService.java

License:Mozilla Public License

private UpdateCondition buildExpectedValue(String modelName, String expectedField, Object expectedValue,
        boolean expectedExists) throws Exception {
    if (expectedValue == null)
        throw new IllegalArgumentException("ExpectedValue cannot be null.");

    String attrName = jsoda.getFieldAttrMap(modelName).get(expectedField);
    String fieldValue = DataUtil.encodeValueToAttrStr(expectedValue,
            jsoda.getField(modelName, expectedField).getType());
    UpdateCondition cond = new UpdateCondition();

    cond.setExists(expectedExists);
    cond.setName(attrName);/*from   w  w  w  . j  av  a2s  .  com*/
    if (expectedExists) {
        cond.setValue(fieldValue);
    }
    return cond;
}