Example usage for com.amazonaws.services.dynamodbv2.document ItemCollection pages

List of usage examples for com.amazonaws.services.dynamodbv2.document ItemCollection pages

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.document ItemCollection pages.

Prototype

@Override
public PageIterable<Item, R> pages() 

Source Link

Document

Returns an Iterable> that iterates over pages of items from this collection.

Usage

From source file:com.exorath.service.party.service.DynamoDatabaseProvider.java

License:Apache License

/**
 * Get all parties where the key 'primKey' is 'uuid'
 * Some parties may be expired, service should check for those!
 *
 * @param uuid    The uuid to be looked for
 * @param primKey The index to search for the data
 * @return A list of all parties that matched the uuid to the primary key
 *///w  w  w .j a  v  a2s . c  o m
private List<Party> getParties(String uuid, String primKey) {
    QuerySpec query = getQuerySpec(primKey, uuid);
    ArrayList<Item> items = new ArrayList<>();

    ItemCollection<QueryOutcome> queryOutcome;
    if (primKey.equals(PARTY_UUID)) {
        queryOutcome = table.query(query);
    } else {
        Index index = table.getIndex(primKey);
        queryOutcome = index.query(query);
    }
    for (Page<Item, QueryOutcome> page : queryOutcome.pages()) {
        for (Item aPage : page) {
            items.add(aPage);
        }
    }

    if (items.size() > 0) { // Did the query return something?
        List<Party> parties = new ArrayList<>();
        for (Item item : items) {
            parties.add(getPartyFromItem(item));
        }
        return parties;
    }
    return null; // The party must not exist
}

From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java

License:Open Source License

private Chunk<Item> getItemListForGsi(String indexName, QuerySpec spec) {
    Preconditions.checkNotNull(spec, "spec must not be null");
    final ItemCollection<QueryOutcome> outcome = table.getIndex(indexName).query(spec);

    List<Item> results = new ArrayList<>();
    try {//from   w  w  w.j a v a2 s  .  c  o  m
        outcome.pages().forEach(p -> {
            p.iterator().forEachRemaining(o -> results.add(o));
        });
    } catch (AmazonServiceException e) {
        throw convertDynamoDBException(e, "getting by spec: " + spec.toString(),
                null /*no write condition exception*/);
    }
    Map<String, AttributeValue> lastEvaluatedKey = outcome.getLastLowLevelResult().getQueryResult()
            .getLastEvaluatedKey();
    String lastEvaluatedItemJson = lastEvaluatedKey == null ? null
            : Item.fromMap(InternalUtils.toSimpleMapValue(lastEvaluatedKey)).toJSON();

    return new ChunkImpl<>(results, lastEvaluatedItemJson, null /*chunkable*/);
}

From source file:ws.salient.aws.dynamodb.DynamoDBProfiles.java

License:Apache License

private Settings getSettings(String accountId) {
    return accounts.computeIfAbsent(accountId, (id) -> {
        Settings settings = new Settings();
        ItemCollection<QueryOutcome> items = dynamodb.getTable("SalientProfile")
                .query(new QuerySpec().withHashKey("accountId", id));
        items.pages().forEach((page) -> {
            page.iterator().forEachRemaining((item) -> {
                try {
                    Profile profile = new Profile();
                    if (item.hasAttribute("aliases")) {
                        profile.setAliases(json.readValue(item.getJSON("aliases"), Map.class));
                    }/*from w  w w.  j  ava 2s .  c o m*/
                    if (item.hasAttribute("properties")) {
                        if (item.get("properties") instanceof byte[]) {
                            log.info("Decrypt profile " + item.getString("profileName"));
                            DecryptResult decrypt = kms.decrypt(
                                    new DecryptRequest().addEncryptionContextEntry("accountId", accountId)
                                            .withCiphertextBlob(ByteBuffer.wrap(item.getBinary("properties"))));
                            profile.setProperties(
                                    json.readValue(decrypt.getPlaintext().array(), Properties.class));
                        } else {
                            Properties properties = new Properties();
                            properties.putAll(item.getMap("properties"));
                            profile.setProperties(properties);
                        }
                    }
                    if (item.hasAttribute("repositories")) {
                        profile.setRepositories(json.readValue(item.getJSON("repositories"),
                                json.getTypeFactory().constructCollectionType(Set.class, Repository.class)));
                    }
                    String name = item.getString("profileName");
                    Boolean active = item.getBoolean("active");
                    settings.withProfile(name, profile);
                    if (active) {
                        settings.withActiveProfile(name);
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
        });
        return settings;
    });
}

From source file:ws.salient.aws.dynamodb.DynamoDBStore.java

License:Apache License

public Session get(Command command, KnowledgeRepository repository, Properties properties,
        Injector parentInjector, Sessions sessions, QuerySpec sessionQuery) {
    String sessionId = command.getSessionId();
    String accountId = command.getAccountId();

    SecretKeySpec secretKey;//from  w  w w.ja va2  s .  c om
    ByteBuffer encryptedKey;
    Session session = new Session(sessionId);
    Page<Item, QueryOutcome> page = dynamodb.getTable("SalientSession").query(sessionQuery).firstPage();
    if (page != null && page.size() > 0) {

        try {
            Item result = page.iterator().next();

            encryptedKey = ByteBuffer.wrap((byte[]) result.getMap("secretKey").get("encrypted"));
            if (encryptedKey != null) {
                DecryptResult decrypt = kms.decrypt(new DecryptRequest()
                        .addEncryptionContextEntry("accountId", accountId)
                        .addEncryptionContextEntry("sessionId", sessionId).withCiphertextBlob(encryptedKey));
                byte[] key = decrypt.getPlaintext().array();
                secretKey = new SecretKeySpec(key, (String) result.getMap("secretKey").get("algorithm"));
            } else {
                secretKey = null;
            }

            result = decrypt(result, secretKey, "properties", "session");

            properties = json.readValue(result.getBinary("properties"), Properties.class);
            String knowledgeBaseId = result.getString("knowledgeBaseId");
            KnowledgeBase knowledgeBase = repository.getKnowledgeBase(knowledgeBaseId);
            String timestamp = result.getString("timestamp");

            session.init(knowledgeBase, properties, parentInjector, Instant.parse(timestamp),
                    result.getBinary("session"), sessions);

            int processCount = session.getProcessCount();

            List<Item> eventItems = new LinkedList();
            ItemCollection<QueryOutcome> query = dynamodb.getTable("SalientSessionEvent")
                    .query(new QuerySpec().withConsistentRead(true).withHashKey("sessionId", sessionId)
                            .withRangeKeyCondition(new RangeKeyCondition("timestamp").gt(timestamp)));
            query.pages().forEach((eventPage) -> {
                eventPage.forEach((eventItem) -> {
                    eventItems.add(eventItem);
                });
            });

            List<Command> commands = new LinkedList();

            eventItems.forEach((eventItem) -> {
                try {
                    eventItem = decrypt(eventItem, secretKey, "command");
                    byte[] value = eventItem.getBinary("command");
                    ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(value)) {
                        protected Class<?> resolveClass(ObjectStreamClass desc)
                                throws IOException, ClassNotFoundException {
                            return session.getKnowledgeBase().getContainer().getClassLoader()
                                    .loadClass(desc.getName());
                        }
                    };
                    Command event = (Command) objectIn.readObject();
                    if (event instanceof WorkItem) {
                        session.getWorkItemHandlers().forEach((handler) -> {
                            handler.getCompletedWorkItemIds().add(((WorkItem) event).getWorkItemId());
                        });
                    }
                    commands.add(event);
                } catch (ClassNotFoundException | IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
            commands.forEach((event) -> {
                session.accept(event);
            });
            session.getWorkItemHandlers().forEach((handler) -> {
                handler.getCompletedWorkItemIds().clear();
            });

        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    } else {
        GenerateDataKeyResult dataKey = generateEncryptionKey(accountId, sessionId);
        byte[] key = dataKey.getPlaintext().array();
        secretKey = new SecretKeySpec(key, "AES");
        encryptedKey = dataKey.getCiphertextBlob();
        KnowledgeBase knowledgeBase = repository.getKnowledgeBase(command.getKnowledgeBaseId());
        session.init(knowledgeBase, properties, parentInjector, command.getTimestamp(), sessions);
    }
    session.setEncryptedKey(encryptedKey);
    session.setSecretKey(secretKey);
    return session;
}