Example usage for com.amazonaws.services.simpledb.model PutAttributesRequest setExpected

List of usage examples for com.amazonaws.services.simpledb.model PutAttributesRequest setExpected

Introduction

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

Prototype


public void setExpected(UpdateCondition expected) 

Source Link

Document

The update condition which, if specified, determines whether the specified attributes will be updated or not.

Usage

From source file:br.com.ingenieux.mojo.simpledb.cmd.PutAttributesCommand.java

License:Apache License

private void putAttribute(PutAttributesContext ctx, ObjectNode objectNode) {
    PutAttributesRequest request = new PutAttributesRequest();

    request.setDomainName(ctx.getDomain());

    Iterator<String> itFieldName = objectNode.fieldNames();

    while (itFieldName.hasNext()) {
        String key = itFieldName.next();

        if ("name".equals(key)) {
            String value = objectNode.get("name").textValue();

            request.setItemName(value);/*from  w  ww . ja v  a 2 s . c o  m*/
        } else if ("append".equals(key) || "replace".equals(key)) {
            boolean replaceP = "replace".equals(key);

            ArrayNode attributesNode = (ArrayNode) objectNode.get(key);

            Collection<ReplaceableAttribute> value = getAttributesFrom(attributesNode, replaceP);

            request.getAttributes().addAll(value);
        } else if ("expect".equals(key)) {
            ObjectNode expectNode = (ObjectNode) objectNode.get("expect");

            request.setExpected(getUpdateCondition(expectNode));
        }
    }

    service.putAttributes(request);
}

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/*from w ww .  ja va  2  s. 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;//from  w ww  . j a  v a2  s  .co 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:com.dateofrock.simpledbmapper.SimpleDBMapper.java

License:Apache License

/**
 * SimpleDB?????/*from   www  .jav a  2  s. c  o m*/
 * 
 * @param object
 *            {@link SimpleDBDomain}????POJO
 *            {@link SimpleDBVersionAttribute}
 *            ??????????????<a href=
 *            "http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/ConditionalPut.html"
 *            >Conditional Put</a>????
 */
public <T> void save(T object) {
    Class<?> clazz = object.getClass();
    String domainName = getDomainName(clazz);

    Field itemNameField = this.reflector.findItemNameField(clazz);
    if (itemNameField == null) {
        throw new SimpleDBMapperException(object + "@SimpleDBItemName????");
    }

    String itemName = null;
    itemName = this.reflector.encodeItemNameAsSimpleDBFormat(object, itemNameField);

    Set<Field> allFields = this.reflector.listAllFields(clazz);
    Map<String, Object> attributeMap = new HashMap<String, Object>();
    List<S3BlobReference> blobList = new ArrayList<S3BlobReference>();
    for (Field field : allFields) {
        try {
            String attributeName = this.reflector.getAttributeName(field);
            if (attributeName != null) {
                if (this.reflector.isAttributeField(field)) {
                    attributeMap.put(attributeName, field.get(object));
                } else if (this.reflector.isBlobField(field)) {
                    String s3BucketName = this.reflector.getS3BucketName(clazz);
                    String s3KeyPrefix = this.reflector.getS3KeyPrefix(clazz);
                    String s3ContentType = this.reflector.getS3ContentType(field);
                    // FIXME
                    S3BlobReference s3BlobRef = new S3BlobReference(attributeName, s3BucketName, s3KeyPrefix,
                            s3ContentType, field.get(object));
                    blobList.add(s3BlobRef);
                }
            }
        } catch (Exception e) {
            throw new SimpleDBMapperException(e);
        }
    }

    List<String> nullKeys = new ArrayList<String>();
    List<ReplaceableAttribute> replacableAttrs = new ArrayList<ReplaceableAttribute>();

    // SimpleDBAttribute
    for (Map.Entry<String, Object> entry : attributeMap.entrySet()) {
        String sdbAttributeName = entry.getKey();
        Object sdbValue = entry.getValue();
        if (sdbValue == null) {
            nullKeys.add(sdbAttributeName);// ?
        } else if (sdbValue instanceof Set) { // Set
            Set<?> c = (Set<?>) sdbValue;
            for (Object val : c) {
                replacableAttrs.add(new ReplaceableAttribute(sdbAttributeName,
                        this.reflector.encodeObjectAsSimpleDBFormat(val), true));
            }
        } else {
            replacableAttrs.add(new ReplaceableAttribute(sdbAttributeName,
                    this.reflector.encodeObjectAsSimpleDBFormat(sdbValue), true));
        }
    }

    // SimpleDBBlob
    // Upload?Blob?
    List<S3Task> uploadTasks = new ArrayList<S3Task>();
    for (S3BlobReference s3BlobRef : blobList) {
        String bucketName = s3BlobRef.getS3BucketName();
        if (bucketName == null) {
            throw new SimpleDBMapperException("Blob??s3BucketName????");
        }

        StringBuilder s3Key = new StringBuilder();
        String prefix = s3BlobRef.getPrefix();
        if (prefix == null) {
            throw new SimpleDBMapperException("Blob?prefix?null??????");
        }
        prefix = prefix.trim();
        s3Key.append(prefix);
        if (!prefix.isEmpty() && !prefix.endsWith("/")) {
            s3Key.append("/");
        }
        s3Key.append(itemName).append("/").append(s3BlobRef.getAttributeName());

        Object blobObject = s3BlobRef.getObject();
        if (blobObject == null) {
            nullKeys.add(s3BlobRef.getAttributeName());
            // ???Delete Object?
            // FIXME ????????SDB???DeleteAttribute?
            this.s3.deleteObject(bucketName, s3Key.toString());
        } else {
            // ?Blob????S3??????????????????????
            InputStream input = null;
            if (blobObject instanceof String) {
                // Blob?String
                // FIXME encoding???
                input = new ByteArrayInputStream(((String) blobObject).getBytes(Charset.forName("UTF-8")));
            } else if (blobObject.getClass().getSimpleName().equals("byte[]")) {
                // Blob?Byte?
                input = new ByteArrayInputStream((byte[]) blobObject);
            } else {
                throw new SimpleDBMapperException(
                        "Blob?????String????byte[]????");
            }
            S3Task uploadTask = new S3Task(this.s3, s3BlobRef.getAttributeName(), input, bucketName,
                    s3Key.toString(), s3BlobRef.getContentType());
            uploadTasks.add(uploadTask);
        }
    }

    // PutAttribute
    PutAttributesRequest req = new PutAttributesRequest();
    req.setDomainName(domainName);
    req.setItemName(itemName);

    // Version??object???Conditional PUT?
    Long nowVersion = System.currentTimeMillis();
    Field versionField = this.reflector.findVersionAttributeField(clazz);
    if (versionField != null) {
        try {
            Object versionObject = versionField.get(object);
            String versionAttributeName = versionField.getAnnotation(SimpleDBVersionAttribute.class)
                    .attributeName();
            if (versionObject != null) {
                if (versionObject instanceof Long) {
                    Long currentVersion = (Long) versionObject;
                    UpdateCondition expected = new UpdateCondition();
                    expected.setName(versionAttributeName);
                    expected.setValue(currentVersion.toString());
                    req.setExpected(expected);
                } else {
                    throw new SimpleDBMapperException(
                            "version?Long???????" + versionField);
                }
            }

            replacableAttrs.add(new ReplaceableAttribute(versionAttributeName, nowVersion.toString(), true));
        } catch (Exception e) {
            throw new SimpleDBMapperException("object?version??: " + object, e);
        }
    }

    // S3??
    List<S3TaskResult> taskFailures = new ArrayList<S3TaskResult>();
    ExecutorService executor = Executors.newFixedThreadPool(this.config.geS3AccessThreadPoolSize());
    try {
        List<Future<S3TaskResult>> futures = executor.invokeAll(uploadTasks);
        for (Future<S3TaskResult> future : futures) {
            S3TaskResult result = future.get();
            // SimpleDB?????
            replacableAttrs.add(new ReplaceableAttribute(result.getSimpleDBAttributeName(),
                    result.toSimpleDBAttributeValue(), true));
            if (!result.isSuccess()) {
                // Upload
                taskFailures.add(result);
            }
        }
    } catch (Exception e) {
        throw new SimpleDBMapperS3HandleException("S3??", e);
    }

    // UploadTask???
    if (!taskFailures.isEmpty()) {
        throw new SimpleDBMapperS3HandleException(taskFailures);
    }

    // SDB?PUT
    req.setAttributes(replacableAttrs);
    this.sdb.putAttributes(req);

    // version
    if (versionField != null) {
        try {
            versionField.set(object, nowVersion);
        } catch (Exception ignore) {
            throw new SimpleDBMapperException("version??", ignore);
        }
    }

    // DeleteAttribute
    if (!nullKeys.isEmpty()) {
        DeleteAttributesRequest delReq = new DeleteAttributesRequest();
        delReq.setDomainName(domainName);
        delReq.setItemName(itemName);
        Collection<Attribute> delAttrs = new ArrayList<Attribute>(nullKeys.size());
        for (String nullKey : nullKeys) {
            delAttrs.add(new Attribute(nullKey, null));
        }
        delReq.setAttributes(delAttrs);
        this.sdb.deleteAttributes(delReq);
    }

}