Example usage for com.amazonaws.services.dynamodbv2.model GetItemResult getItem

List of usage examples for com.amazonaws.services.dynamodbv2.model GetItemResult getItem

Introduction

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

Prototype


public java.util.Map<String, AttributeValue> getItem() 

Source Link

Document

A map of attribute names to AttributeValue objects, as specified by ProjectionExpression.

Usage

From source file:DynamoDB.java

License:Open Source License

public boolean getItem(Map<String, AttributeValue> item, String id, String message) {
    //GetItemResult result = dynamoDB.getItem(tableName, item);       
    GetItemRequest getItemRequest = new GetItemRequest().withTableName(tableName).withKey(item);
    GetItemResult result = dynamoDB.getItem(getItemRequest);
    if (result.getItem() != null) {
        //addItem(id,message);
        System.out.println("item present");
        return true;
    }/* w  w w. ja v a  2s  .co m*/
    //System.out.println(result.getItem());
    else {
        return false;
    }
}

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

License:Open Source License

private EntryList extractEntriesFromGetItemResult(final GetItemResult result, final StaticBuffer sliceStart,
        final StaticBuffer sliceEnd, final int limit) {
    final Map<String, AttributeValue> item = result.getItem();
    List<Entry> filteredEntries = Collections.emptyList();
    if (null != item) {
        item.remove(Constants.JANUSGRAPH_HASH_KEY);
        filteredEntries = new EntryBuilder(item).slice(sliceStart, sliceEnd).limit(limit).buildAll();
    }//from w w  w  .j a  va  2  s  .  c  o m
    return StaticArrayEntryList.of(filteredEntries);
}

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

License:Apache License

@Override
public User find(String email) throws DataSourceTableDoesNotExistException {
    try {/*from w  w  w  . j a va 2  s .c  o  m*/

        User user = null;

        // Create a request to find a User by email address
        GetItemRequest getItemRequest = new GetItemRequest()
                .withTableName(config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE))
                .addKeyEntry(HASH_KEY_NAME, new AttributeValue(email));

        // Issue the request to find the User in DynamoDB
        GetItemResult getItemResult = dynamoClient.getItem(getItemRequest);

        // If an item was found
        if (getItemResult.getItem() != null) {
            // Marshal the Map<String, AttributeValue> structure returned in
            // the
            // GetItemResult to a User object
            user = getUserFromMap(getItemResult.getItem());
        }

        return user;

    } catch (ResourceNotFoundException rnfe) {

        // The ResourceNotFoundException method is thrown by the getItem()
        // method
        // if the DynamoDB table doesn't exist. This exception is re-thrown
        // as a
        // custom, more specific DataSourceTableDoesNotExistException that
        // users
        // of this DAO understand.
        throw new DataSourceTableDoesNotExistException(
                config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE));
    }
}

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

License:Apache License

private Map<String, AttributeValue> readRaw(final ItemId itemId, final Class<? extends Item> itemClass,
        final Collection<String> attributes) {
    final ItemConfiguration itemConfiguration = getItemConfiguration(itemClass);
    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final GetItemRequest getItemRequest = new GetItemRequest(tableName, generateKey(itemId, itemConfiguration));
    if (attributes.size() > 0) {
        getItemRequest.withAttributesToGet(attributes);

    }//  w w  w. j  av  a2s  . c  om

    final GetItemResult getItemResult;
    try {
        getItemResult = amazonDynamoDbClient.getItem(getItemRequest);
    } catch (final AmazonServiceException e) {
        throw new PersistenceResourceFailureException("Failure while attempting to read from DynamoDB table",
                e);
    }

    if (getItemResult == null || getItemResult.getItem() == null) {
        throw new NonExistentItemException(String.format("The item of type [%s] with id [%s] does not exist",
                itemClass.getName(), itemId));
    } else {
        return getItemResult.getItem();
    }
}

From source file:com.erudika.para.persistence.AWSDynamoDAO.java

License:Apache License

private Map<String, AttributeValue> readRow(String key, String appid) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(appid)) {
        return null;
    }/*ww w  .j a v  a  2  s  .  c  o m*/
    Map<String, AttributeValue> row = null;
    try {
        GetItemRequest getItemRequest = new GetItemRequest(getTableNameForAppid(appid),
                Collections.singletonMap(Config._KEY, new AttributeValue(getKeyForAppid(key, appid))));
        GetItemResult res = client().getItem(getItemRequest);
        if (res != null && res.getItem() != null && !res.getItem().isEmpty()) {
            row = res.getItem();
        }
    } catch (Exception e) {
        logger.error("Could not read row from DB - appid={}, key={}", appid, key, e);
    }
    return (row == null || row.isEmpty()) ? null : row;
}

From source file:com.facebook.presto.dynamodb.DynamodbClient.java

License:Apache License

public Iterator<List<Map<String, AttributeValue>>> getTableData(String name,
        Optional<Entry<String, AttributeValue>> hashKeyCondition,
        Optional<Entry<String, Condition>> rangeKeyCondition) {
    AtomicReference<Map<String, AttributeValue>> lastKeyEvaluated = new AtomicReference<>();
    AtomicBoolean firstRun = new AtomicBoolean(true);

    return new Iterator<List<Map<String, AttributeValue>>>() {
        @Override/*w w  w  .j  av  a 2  s . c o  m*/
        public boolean hasNext() {
            return firstRun.get() && lastKeyEvaluated.get() != null;
        }

        @Override
        public List<Map<String, AttributeValue>> next() {
            firstRun.set(false);
            if (hashKeyCondition.isPresent()) {
                ImmutableMap.Builder<String, Condition> builder = ImmutableMap.builder();
                builder.put(hashKeyCondition.get().getKey(), new Condition()
                        .withAttributeValueList(hashKeyCondition.get().getValue()).withComparisonOperator(EQ));

                if (rangeKeyCondition.isPresent()) {
                    Entry<String, Condition> rangeEntry = rangeKeyCondition.get();
                    if (rangeEntry.getValue().getComparisonOperator() == EQ.name()
                            && rangeEntry.getValue().getAttributeValueList().size() == 1) {
                        GetItemResult item = dynamoDBClient.getItem(name,
                                ImmutableMap.of(hashKeyCondition.get().getKey(),
                                        hashKeyCondition.get().getValue(), rangeEntry.getKey(),
                                        rangeEntry.getValue().getAttributeValueList().get(0)));
                        return ImmutableList.of(item.getItem());
                    } else {
                        builder.put(rangeKeyCondition.get().getKey(), rangeKeyCondition.get().getValue());
                    }
                }

                QueryResult query = dynamoDBClient.query(
                        new QueryRequest().withTableName(name).withExclusiveStartKey(lastKeyEvaluated.get())
                                .withKeyConditions(builder.build()).withLimit(100000));

                lastKeyEvaluated.set(query.getLastEvaluatedKey());

                return query.getItems();
            } else {
                ScanResult scan = dynamoDBClient.scan(new ScanRequest()
                        .withExclusiveStartKey(lastKeyEvaluated.get()).withLimit(100000).withTableName(name));

                lastKeyEvaluated.set(scan.getLastEvaluatedKey());
                return scan.getItems();
            }
        }
    };
}

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

License:Open Source License

/**
 * Main2./* w  w w  .  j a v a2  s  . c  o m*/
 *
 * @param args the args
 */
public static void main2(String[] args) {
    init();

    Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("name", new AttributeValue().withS("Airplane"));

    GetItemRequest getItemRequest = new GetItemRequest().withTableName("my-favorite-movies-table").withKey(key)
            .withAttributesToGet(Arrays.asList("name", "fans", "rating", "year"));

    GetItemResult result = dynamoDB.getItem(getItemRequest);

    // Check the response.
    System.out.println("Printing item after retrieving it....");
    printItem(result.getItem());
}

From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java

License:Open Source License

/**
 * This example demonstrates two transactions attempting to write to the same item.  
 * Only one transaction will go through.
 *//*from  www .  j  a  va  2 s  .  co m*/
public void conflictingTransactions() {
    print("\n*** conflictingTransactions() ***\n");
    // Start transaction t1
    Transaction t1 = txManager.newTransaction();

    // Construct a primary key of an item that will overlap between two transactions.
    Map<String, AttributeValue> item1Key = new HashMap<String, AttributeValue>();
    item1Key.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item1"));
    item1Key = Collections.unmodifiableMap(item1Key);

    // Add a new PutItem request to the transaction object (instead of on the AmazonDynamoDB client)
    // This will eventually get rolled back when t2 tries to work on the same item
    Map<String, AttributeValue> item1T1 = new HashMap<String, AttributeValue>(item1Key);
    item1T1.put("WhichTransaction?", new AttributeValue("t1"));
    print("T1 - Put item: " + item1T1);
    t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1T1));
    print("T1 - At this point Item1 is in the table, but is not yet committed");

    Map<String, AttributeValue> item2T1 = new HashMap<String, AttributeValue>();
    item2T1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item2"));
    print("T1 - Put a second, non-overlapping item: " + item2T1);
    t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item2T1));
    print("T1 - At this point Item2 is also in the table, but is not yet committed");

    // Start a new transaction t2
    Transaction t2 = txManager.newTransaction();

    Map<String, AttributeValue> item1T2 = new HashMap<String, AttributeValue>(item1Key);
    item1T1.put("WhichTransaction?", new AttributeValue("t2 - I win!"));
    print("T2 - Put item: " + item1T2);
    t2.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1T2));
    print("T2 - At this point Item1 from t2 is in the table, but is not yet committed. t1 was rolled back.");

    // To prove that t1 will have been rolled back by this point, attempt to commit it.
    try {
        print("Attempting to commit t1 (this will fail)");
        t1.commit();
        throw new RuntimeException("T1 should have been rolled back. This is a bug.");
    } catch (TransactionRolledBackException e) {
        print("Transaction t1 was rolled back, as expected");
        t1.delete(); // Delete it, no longer needed
    }

    // Now put a second item as a part of t2
    Map<String, AttributeValue> item3T2 = new HashMap<String, AttributeValue>();
    item3T2.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item3"));
    print("T2 - Put item: " + item3T2);
    t2.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item3T2));
    print("T2 - At this point Item3 is in the table, but is not yet committed");

    print("Committing and deleting t2");
    t2.commit();

    t2.delete();

    // Now to verify, get the items Item1, Item2, and Item3.
    // More on read operations later. 
    GetItemResult result = txManager.getItem(
            new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item1Key),
            IsolationLevel.UNCOMMITTED);
    print("Notice that t2's write to Item1 won: " + result.getItem());

    result = txManager.getItem(new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item3T2),
            IsolationLevel.UNCOMMITTED);
    print("Notice that t2's write to Item3 also went through: " + result.getItem());

    result = txManager.getItem(new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item2T1),
            IsolationLevel.UNCOMMITTED);
    print("However, t1's write to Item2 did not go through (since Item2 is null): " + result.getItem());
}

From source file:com.makariev.dynamodb.preferences.UserPreferenceLowLevelAPIService.java

License:Open Source License

@Override
public UserPreference findByUserNo(int userNo) {
    Map<String, AttributeValue> primaryKey = new HashMap<>();
    AttributeValue avKey = new AttributeValue();
    avKey.withN(String.valueOf(userNo));
    primaryKey.put("userNo", avKey);
    //Key primaryKey = new Key().withHashKeyElement(userNoAttr);
    GetItemRequest request = new GetItemRequest().withTableName(UserPreference.TABLE_NAME).withKey(primaryKey);

    GetItemResult result = dynamoDb.getItem(request);

    Map userPreference = result.getItem();
    return toUserPreference(userPreference);
}

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

License:Open Source License

private EntryList extractEntriesFromGetItemResult(GetItemResult result, StaticBuffer sliceStart,
        StaticBuffer sliceEnd, int limit) {
    Map<String, AttributeValue> item = result.getItem();
    List<Entry> filteredEntries = Collections.emptyList();
    if (null != item) {
        item.remove(Constants.TITAN_HASH_KEY);
        filteredEntries = new EntryBuilder(item).slice(sliceStart, sliceEnd).limit(limit).buildAll();
    }//  w w w.  jav  a2s .com
    return StaticArrayEntryList.of(filteredEntries);
}