Example usage for com.amazonaws.services.dynamodbv2.model AttributeValue getN

List of usage examples for com.amazonaws.services.dynamodbv2.model AttributeValue getN

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.model AttributeValue getN.

Prototype


public String getN() 

Source Link

Document

An attribute of type Number.

Usage

From source file:com.amazon.janusgraph.diskstorage.dynamodb.DynamoDbDelegate.java

License:Open Source License

/**
 * Helper method that can clone an Attribute Value
 *
 * @param val the AttributeValue to copy
 * @param sourceDestinationMap used to avoid loops by keeping track of references
 * @return a copy of val/*  www  .  j av  a  2  s .  co m*/
 */
public static AttributeValue clone(final AttributeValue val,
        final IdentityHashMap<AttributeValue, AttributeValue> sourceDestinationMap) {
    if (val == null) {
        return null;
    }

    if (sourceDestinationMap.containsKey(val)) {
        return sourceDestinationMap.get(val);
    }

    final AttributeValue clonedVal = new AttributeValue();
    sourceDestinationMap.put(val, clonedVal);
    if (val.getN() != null) {
        clonedVal.setN(val.getN());
    } else if (val.getS() != null) {
        clonedVal.setS(val.getS());
    } else if (val.getB() != null) {
        clonedVal.setB(val.getB());
    } else if (val.getNS() != null) {
        clonedVal.setNS(val.getNS());
    } else if (val.getSS() != null) {
        clonedVal.setSS(val.getSS());
    } else if (val.getBS() != null) {
        clonedVal.setBS(val.getBS());
    } else if (val.getBOOL() != null) {
        clonedVal.setBOOL(val.getBOOL());
    } else if (val.getNULL() != null) {
        clonedVal.setNULL(val.getNULL());
    } else if (val.getL() != null) {
        final List<AttributeValue> list = new ArrayList<>(val.getL().size());
        for (AttributeValue listItemValue : val.getL()) {
            if (!sourceDestinationMap.containsKey(listItemValue)) {
                sourceDestinationMap.put(listItemValue, clone(listItemValue, sourceDestinationMap));
            }
            list.add(sourceDestinationMap.get(listItemValue));
        }
        clonedVal.setL(list);
    } else if (val.getM() != null) {
        final Map<String, AttributeValue> map = new HashMap<>(val.getM().size());
        for (Entry<String, AttributeValue> pair : val.getM().entrySet()) {
            if (!sourceDestinationMap.containsKey(pair.getValue())) {
                sourceDestinationMap.put(pair.getValue(), clone(pair.getValue(), sourceDestinationMap));
            }
            map.put(pair.getKey(), sourceDestinationMap.get(pair.getValue()));
        }
        clonedVal.setM(map);
    }
    return clonedVal;
}

From source file:com.amazon.janusgraph.diskstorage.dynamodb.DynamoDbDelegate.java

License:Open Source License

/**Calculate attribute value size*/
private static int calculateAttributeSizeInBytes(final AttributeValue value) {
    int attrValSize = 0;
    if (value == null) {
        return attrValSize;
    }// ww w .  j  a v  a  2  s .c o m

    if (value.getB() != null) {
        final ByteBuffer b = value.getB();
        attrValSize += b.remaining();
    } else if (value.getS() != null) {
        final String s = value.getS();
        attrValSize += s.getBytes(UTF8).length;
    } else if (value.getN() != null) {
        attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER;
    } else if (value.getBS() != null) {
        final List<ByteBuffer> bs = value.getBS();
        for (ByteBuffer b : bs) {
            if (b != null) {
                attrValSize += b.remaining();
            }
        }
    } else if (value.getSS() != null) {
        final List<String> ss = value.getSS();
        for (String s : ss) {
            if (s != null) {
                attrValSize += s.getBytes(UTF8).length;
            }
        }
    } else if (value.getNS() != null) {
        final List<String> ns = value.getNS();
        for (String n : ns) {
            if (n != null) {
                attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER;
            }
        }
    } else if (value.getBOOL() != null) {
        attrValSize += 1;
    } else if (value.getNULL() != null) {
        attrValSize += 1;
    } else if (value.getM() != null) {
        for (Map.Entry<String, AttributeValue> entry : value.getM().entrySet()) {
            attrValSize += entry.getKey().getBytes(UTF8).length;
            attrValSize += calculateAttributeSizeInBytes(entry.getValue());
            attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES;
        }
        attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT;
    } else if (value.getL() != null) {
        final List<AttributeValue> list = value.getL();
        for (Integer i = 0; i < list.size(); i++) {
            attrValSize += calculateAttributeSizeInBytes(list.get(i));
            attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES;
        }
        attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT;
    }
    return attrValSize;
}

From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.AbstractDynamoDbTemplate.java

License:Apache License

@Override
public GeneratedKeyHolder generateKeys(final SequenceKeyGenerator sequenceKeyGenerator) {
    final String sequenceName = sequenceKeyGenerator.sequenceName();
    if (!sequenceConfigurations.contains(sequenceName)) {
        throw new IllegalStateException("Unsupported sequence: " + sequenceName);
    }/*from  w w  w.j  a v a 2 s  .  c  o m*/
    final Map<String, AttributeValue> key = new HashMap<>();
    key.put(SEQUENCE_NAME_ATTRIBUTE, new AttributeValue(sequenceName));
    final AttributeValueUpdate attributeValueUpdate = new AttributeValueUpdate().withAction("ADD")
            .withValue(new AttributeValue().withN(String.valueOf(sequenceKeyGenerator.keyCount())));
    final Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>();
    attributeUpdates.put(SEQUENCE_CURRENT_VALUE_ATTRIBUTE, attributeValueUpdate);
    final String tableName = databaseSchemaHolder.schemaName() + "-" + SEQUENCE_TABLE_NAME;
    final UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
            .withAttributeUpdates(attributeUpdates).withReturnValues("UPDATED_NEW");
    final UpdateItemResult updateItemResult;
    try {
        updateItemResult = amazonDynamoDbClient.updateItem(updateItemRequest);
    } catch (final AmazonServiceException e) {
        throw new PersistenceResourceFailureException(
                "Failure while attempting DynamoDb Update (generate keys)", e);
    }
    final Map<String, AttributeValue> attributes = updateItemResult.getAttributes();
    final AttributeValue currentAttributeValue = attributes.get(SEQUENCE_CURRENT_VALUE_ATTRIBUTE);
    final Long currentValue = Long.valueOf(currentAttributeValue.getN());
    final Collection<Long> keys = new ArrayList<>();
    for (long i = currentValue - sequenceKeyGenerator.keyCount(); i < currentValue; i++) {
        keys.add(i + 1);
    }
    return new GeneratedKeyHolder(keys);
}

From source file:com.github.sdmcraft.slingdynamo.demo.App.java

License:Open Source License

/**
 * Prints the item.//from w  w w. ja  v a  2 s.c o  m
 *
 * @param attributeList the attribute list
 */
private static void printItem(Map<String, AttributeValue> attributeList) {
    for (Map.Entry<String, AttributeValue> item : attributeList.entrySet()) {
        String attributeName = item.getKey();
        AttributeValue value = item.getValue();
        System.out.println(attributeName + " " + ((value.getS() == null) ? "" : ("S=[" + value.getS() + "]"))
                + ((value.getN() == null) ? "" : ("N=[" + value.getN() + "]"))
                + ((value.getB() == null) ? "" : ("B=[" + value.getB() + "]"))
                + ((value.getSS() == null) ? "" : ("SS=[" + value.getSS() + "]"))
                + ((value.getNS() == null) ? "" : ("NS=[" + value.getNS() + "]"))
                + ((value.getBS() == null) ? "" : ("BS=[" + value.getBS() + "] \n")));
    }
}

From source file:com.numenta.taurus.service.TaurusClient.java

License:Open Source License

/**
 * Get list of tweets for the given metric filtered by the given time range returning the
 * results as they become available asynchronously.
 *
 * @param metricName The metric name to retrieve the tweets from
 * @param from       The start time (aggregated) inclusive.
 * @param to         The end time (aggregated) inclusive.
 * @param callback   Callback for asynchronous call. It will be called on every {@link Tweet}
 *///from w  ww . j a  v a  2 s  .com
public void getTweets(String metricName, Date from, Date to, DataCallback<Tweet> callback)
        throws GrokException, IOException {
    if (metricName == null) {
        throw new ObjectNotFoundException("Cannot get tweets without metric name");
    }

    final TaurusDataFactory dataFactory = TaurusApplication.getInstance().getDataFactory();
    final SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
    timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    // Key conditions
    Map<String, Condition> keyConditions = new HashMap<>();

    // uid = modelId
    Condition modelIdCond = new Condition().withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue(metricName));
    keyConditions.put("metric_name", modelIdCond);

    Condition timestampCondition;
    if (from != null && to != null) {
        // timestamp >= from and timestamp <=to
        timestampCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN)
                .withAttributeValueList(new AttributeValue().withS(timestampFormat.format(from)),
                        new AttributeValue().withS(timestampFormat.format(to)));
        keyConditions.put("agg_ts", timestampCondition);
    } else if (from != null) {
        // timestamp >= from
        timestampCondition = new Condition().withComparisonOperator(ComparisonOperator.GT)
                .withAttributeValueList(new AttributeValue().withS(timestampFormat.format(from)));
        keyConditions.put("agg_ts", timestampCondition);
    } else if (to != null) {
        // timestamp <= to
        timestampCondition = new Condition().withComparisonOperator(ComparisonOperator.LT)
                .withAttributeValueList(new AttributeValue().withS(timestampFormat.format(to)));
        keyConditions.put("agg_ts", timestampCondition);
    }

    // Prepare query request
    QueryRequest query = new QueryRequest().withTableName(TWEETS_TABLE)
            .withAttributesToGet("tweet_uid", "userid", "text", "username", "agg_ts", "created_at",
                    "retweet_count")
            .withKeyConditions(keyConditions).withScanIndexForward(false)
            .withIndexName("taurus.metric_data-metric_name_index");

    QueryResult result;
    String tweetId;
    String userId;
    String userName;
    String text;
    Date created;
    Date aggregated;
    AttributeValue retweet;
    int retweetCount;
    Map<String, AttributeValue> lastKey;
    try {
        do {
            // Get results
            result = _awsClient.query(query);
            for (Map<String, AttributeValue> item : result.getItems()) {
                tweetId = item.get("tweet_uid").getS();
                userId = item.get("userid").getS();
                text = item.get("text").getS();
                userName = item.get("username").getS();
                aggregated = DataUtils.parseGrokDate(item.get("agg_ts").getS());
                created = DataUtils.parseGrokDate(item.get("created_at").getS());

                // "retweet_count" is optional
                retweet = item.get("retweet_count");
                if (retweet != null && retweet.getN() != null) {
                    retweetCount = Integer.parseInt(retweet.getN());
                } else {
                    retweetCount = 0;
                }
                if (!callback.onData(dataFactory.createTweet(tweetId, aggregated, created, userId, userName,
                        text, retweetCount))) {
                    // Canceled by the user
                    break;
                }
            }
            // Make sure to get all pages
            lastKey = result.getLastEvaluatedKey();
            query.setExclusiveStartKey(lastKey);
        } while (lastKey != null);
    } catch (AmazonClientException e) {
        // Wraps Amazon's unchecked exception as IOException
        throw new IOException(e);
    }
}

From source file:com.rapid7.diskstorage.dynamodb.DynamoDBDelegate.java

License:Open Source License

/**
 * Helper method that can clone an Attribute Value
 *
 * @param val the AttributeValue to copy
 * @param sourceDestinationMap used to avoid loops by keeping track of references
 * @return a copy of val/*from  w ww  . j  a va2s.c  o  m*/
 */
public static AttributeValue clone(AttributeValue val,
        IdentityHashMap<AttributeValue, AttributeValue> sourceDestinationMap) {
    if (val == null) {
        return null;
    }

    if (sourceDestinationMap.containsKey(val)) {
        return sourceDestinationMap.get(val);
    }

    AttributeValue clonedVal = new AttributeValue();
    sourceDestinationMap.put(val, clonedVal);
    if (val.getN() != null) {
        clonedVal.setN(val.getN());
    } else if (val.getS() != null) {
        clonedVal.setS(val.getS());
    } else if (val.getB() != null) {
        clonedVal.setB(val.getB());
    } else if (val.getNS() != null) {
        clonedVal.setNS(val.getNS());
    } else if (val.getSS() != null) {
        clonedVal.setSS(val.getSS());
    } else if (val.getBS() != null) {
        clonedVal.setBS(val.getBS());
    } else if (val.getBOOL() != null) {
        clonedVal.setBOOL(val.getBOOL());
    } else if (val.getNULL() != null) {
        clonedVal.setNULL(val.getNULL());
    } else if (val.getL() != null) {
        List<AttributeValue> list = new ArrayList<>(val.getL().size());
        for (AttributeValue listItemValue : val.getL()) {
            if (!sourceDestinationMap.containsKey(listItemValue)) {
                sourceDestinationMap.put(listItemValue, clone(listItemValue, sourceDestinationMap));
            }
            list.add(sourceDestinationMap.get(listItemValue));
        }
        clonedVal.setL(list);
    } else if (val.getM() != null) {
        Map<String, AttributeValue> map = new HashMap<>(val.getM().size());
        for (Entry<String, AttributeValue> pair : val.getM().entrySet()) {
            if (!sourceDestinationMap.containsKey(pair.getValue())) {
                sourceDestinationMap.put(pair.getValue(), clone(pair.getValue(), sourceDestinationMap));
            }
            map.put(pair.getKey(), sourceDestinationMap.get(pair.getValue()));
        }
        clonedVal.setM(map);
    }
    return clonedVal;
}

From source file:com.rapid7.diskstorage.dynamodb.DynamoDBDelegate.java

License:Open Source License

/**Calculate attribute value size*/
private static int calculateAttributeSizeInBytes(AttributeValue value) {
    int attrValSize = 0;
    if (value == null) {
        return attrValSize;
    }//from www.j av a2s.  c  o m

    if (value.getB() != null) {
        ByteBuffer b = value.getB();
        attrValSize += b.remaining();
    } else if (value.getS() != null) {
        String s = value.getS();
        attrValSize += s.getBytes(UTF8).length;
    } else if (value.getN() != null) {
        attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER;
    } else if (value.getBS() != null) {
        List<ByteBuffer> bs = value.getBS();
        for (ByteBuffer b : bs) {
            if (b != null) {
                attrValSize += b.remaining();
            }
        }
    } else if (value.getSS() != null) {
        List<String> ss = value.getSS();
        for (String s : ss) {
            if (s != null) {
                attrValSize += s.getBytes(UTF8).length;
            }
        }
    } else if (value.getNS() != null) {
        List<String> ns = value.getNS();
        for (String n : ns) {
            if (n != null) {
                attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER;
            }
        }
    } else if (value.getBOOL() != null) {
        attrValSize += 1;
    } else if (value.getNULL() != null) {
        attrValSize += 1;
    } else if (value.getM() != null) {
        for (Map.Entry<String, AttributeValue> entry : value.getM().entrySet()) {
            attrValSize += entry.getKey().getBytes(UTF8).length;
            attrValSize += calculateAttributeSizeInBytes(entry.getValue());
            attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES;
        }
        attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT;
    } else if (value.getL() != null) {
        List<AttributeValue> list = value.getL();
        for (Integer i = 0; i < list.size(); i++) {
            attrValSize += calculateAttributeSizeInBytes(list.get(i));
            attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES;
        }
        attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT;
    }
    return attrValSize;
}

From source file:com.tsatsatzu.subwar.game.logic.dynamo.DynamoUtils.java

License:Apache License

/**
 * Gets the int./*from   ww w  . j a v a 2s.c om*/
 *
 * @param data the data
 * @param name the name
 * @param def the def
 * @return the int
 */
public static int getInt(Map<String, AttributeValue> data, String name, int def) {
    AttributeValue val = data.get(name);
    if (val == null)
        return def;
    String snum = val.getN();
    if (snum == null)
        return def;
    try {
        int inum = Integer.parseInt(snum);
        return inum;
    } catch (NumberFormatException e) {
        return def;
    }
}

From source file:com.tsatsatzu.subwar.game.logic.dynamo.DynamoUtils.java

License:Apache License

/**
 * Gets the long.//from   ww  w.j a  v a2s  .  co m
 *
 * @param data the data
 * @param name the name
 * @param def the def
 * @return the long
 */
public static long getLong(Map<String, AttributeValue> data, String name, long def) {
    AttributeValue val = data.get(name);
    if (val == null)
        return def;
    String snum = val.getN();
    if (snum == null)
        return def;
    try {
        long inum = Long.parseLong(snum);
        return inum;
    } catch (NumberFormatException e) {
        return def;
    }
}

From source file:doug.iotdemo.server.web.WebServer.java

License:Open Source License

private void handleFetch(RoutingContext context) {
    ScanRequest scanRequest = new ScanRequest().withTableName(sensorTableName);
    db.scanAsync(scanRequest, new AsyncHandler<ScanRequest, ScanResult>() {
        @Override/*w w w .  j a  va  2 s.com*/
        public void onSuccess(ScanRequest request, ScanResult result) {
            JsonObject states = new JsonObject();
            for (Map<String, AttributeValue> item : result.getItems()) {
                AttributeValue stateValue = item.get("state");
                if (stateValue != null) {
                    JsonObject sensorObj = new JsonObject();
                    sensorObj.put("state", Integer.valueOf(stateValue.getN()));

                    if (item.get("time") != null) {
                        long time = Long.parseLong(item.get("time").getN());
                        long count = Long.parseLong(item.get("count").getN());
                        long thresh = time / count;
                        sensorObj.put("thresh", thresh);
                    }

                    states.put(item.get("sensor").getS(), sensorObj);
                }
            }
            context.response().end(states.encode());
        }

        @Override
        public void onError(Exception exception) {
            StringWriter msg = new StringWriter();
            exception.printStackTrace(new PrintWriter(msg));
            context.response().setStatusCode(500).end(msg.toString());
        }
    });
}