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

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

Introduction

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

Prototype

public PutAttributesRequest() 

Source Link

Document

Default constructor for PutAttributesRequest object.

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 . j  a v a2s  . 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: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;//w ww  .  ja  v  a 2  s. c om
    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   w  w  w. ja  v  a2 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);
    }

}

From source file:com.duboisproject.rushhour.database.SdbInterface.java

License:Open Source License

/**
 * Add a play to the database.//from   www.j a v a 2 s .  c  o m
 */
public void putStats(Mathlete player, GameStatistics stats) throws RequestException {
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put(PLAYS_MATHLETE, player.id);
    attributes.put(PLAYS_LEVEL, Integer.toString(stats.levelId));
    attributes.put(PLAYS_TOTAL_MOVES, Integer.toString(stats.totalMoves));
    attributes.put(PLAYS_RESET_MOVES, Integer.toString(stats.resetMoves));
    attributes.put(PLAYS_START, stats.startTime.toString());
    attributes.put(PLAYS_TOTAL_TIME, stats.totalCompletionTime.toString());
    attributes.put(PLAYS_RESET_TIME, stats.resetCompletionTime.toString());

    PutAttributesRequest request = new PutAttributesRequest();
    request.setDomainName(PLAYS_DOMAIN);
    request.setItemName(UUID.randomUUID().toString());
    request.setAttributes(listify(attributes));

    try {
        client.putAttributes(request);
    } catch (AmazonClientException e) {
        throw new RequestException(REQUEST_FAILED_MESSAGE);
    }
}

From source file:com.zotoh.cloudapi.aws.SDB.java

License:Open Source License

private void modifyKVPairs(boolean replace, String domain, String item, KeyValuePair... vals)
        throws CloudException, InternalException {
    tstEStrArg("domain-name", domain);
    tstEStrArg("item-name", item);
    tstNEArray("keyvalue-pairs", vals);
    _svc.getCloud().getSDB().putAttributes(new PutAttributesRequest().withAttributes(toRAtts(replace, vals))
            .withItemName(item).withDomainName(domain));
}

From source file:org.apache.camel.component.aws.sdb.PutAttributesCommand.java

License:Apache License

public void execute() {
    PutAttributesRequest request = new PutAttributesRequest().withDomainName(determineDomainName())
            .withItemName(determineItemName()).withAttributes(determineReplaceableAttributes())
            .withExpected(determineUpdateCondition());
    log.trace("Sending request [{}] for exchange [{}]...", request, exchange);

    this.sdbClient.putAttributes(request);

    log.trace("Request sent");
}

From source file:thread.RollupThread.java

License:Apache License

private void putItem(String domain, String item, List<ReplaceableAttribute> list) {
    log.debug("Putting Amazon SimpleDB item: " + item);
    PutAttributesRequest request = new PutAttributesRequest().withDomainName(domain).withItemName(item);
    request.setAttributes(list);//from  w w  w .j  a  va2  s.com
    try {
        sdb.putAttributes(request);
    } catch (Exception e) {
        log.error("Unable to create item \"" + item + "\": " + e.getMessage());
        AdWhirlUtil.logException(e, log);
    }
}