Example usage for com.amazonaws.services.dynamodbv2.document.spec ScanSpec ScanSpec

List of usage examples for com.amazonaws.services.dynamodbv2.document.spec ScanSpec ScanSpec

Introduction

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

Prototype

public ScanSpec() 

Source Link

Usage

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

License:Apache License

private <T extends Item> ScanSpec generateScanSpec(final AttributeQuery query, final Class<T> tableItemType)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException, SecurityException {
    final Class<?> clazz = getScanSpecOperandType(query.getAttributeName(), tableItemType);

    ScanSpec scanSpec = new ScanSpec();

    final StringBuilder filterExpression = new StringBuilder();
    final ValueMap valueMap = new ValueMap();
    int valueMapCount = 0;

    if (query.getCondition().getComparisonOperator() == Operators.NULL) {
        filterExpression.append("attribute_not_exists(").append(query.getAttributeName()).append(")");
    } else if (query.getCondition().getComparisonOperator() == Operators.NOT_NULL) {
        filterExpression.append("attribute_exists(").append(query.getAttributeName()).append(")");
    } else {//ww w  . java 2 s .c o  m
        if (query.getCondition().getComparisonOperator() == Operators.EQUALS) {
            filterExpression.append(query.getAttributeName()).append(" IN (");

            final Iterator<String> valueIterator = query.getCondition().getValues().iterator();
            while (valueIterator.hasNext()) {
                filterExpression.append(":").append(valueMapCount);
                valueMap.with(":" + valueMapCount, valueIterator.next());
                valueMapCount++;
                if (valueIterator.hasNext()) {
                    filterExpression.append(",");
                }
            }
            filterExpression.append(")");
        } else if (query.getCondition().getComparisonOperator() == Operators.LESS_THAN_OR_EQUALS) {
            if (query.getCondition().getValues().size() == 1) {
                filterExpression.append(query.getAttributeName()).append(" <= ").append(":")
                        .append(valueMapCount);
                final Object valueInstance = clazz.getConstructor(String.class)
                        .newInstance(query.getCondition().getValues().iterator().next());
                valueMap.with(":" + valueMapCount, valueInstance);
                valueMapCount++;
            } else {
                // throw exeption??
            }
        } else if (query.getCondition().getComparisonOperator() == Operators.GREATER_THAN_OR_EQUALS) {
            if (query.getCondition().getValues().size() == 1) {
                filterExpression.append(query.getAttributeName()).append(" >= ").append(":")
                        .append(valueMapCount);
                final Object valueInstance = clazz.getConstructor(String.class)
                        .newInstance(query.getCondition().getValues().iterator().next());
                valueMap.with(":" + valueMapCount, valueInstance);
                valueMapCount++;
            } else {
                // throw exeption??
            }
        }
    }

    if (filterExpression.length() > 0) {
        scanSpec = scanSpec.withFilterExpression(filterExpression.toString());
    }
    if (valueMap.size() > 0) {
        scanSpec = scanSpec.withValueMap(valueMap);
    }
    return scanSpec;
}

From source file:io.ignitr.dispatchr.manager.core.data.ClientRepository.java

License:Apache License

/**
 * Finds all clients in DynamoDB./*w  ww . j a  va 2s  . co m*/
 *
 * @param offset number of records to offset when paginating
 * @param limit number of records to return when paginating
 * @param sortDir the direction to sort returned records when paginating
 * @param active a boolean flag indicating whether or not to return only "active" clients
 * @return an {@link Observable} that emits all clients
 */
public Observable<Client> findAll(long offset, long limit, String sortDir, boolean active) {
    return Observable.create(subscriber -> {
        Table clientTable = dynamoDB.getTable(CLIENT_TABLE_NAME);

        ItemCollection<ScanOutcome> results = clientTable.scan(new ScanSpec());

        results.forEach(item -> subscriber.onNext(convertFromItem(item)));

        subscriber.onCompleted();
    });
}

From source file:io.ignitr.dispatchr.manager.core.data.TopicRepository.java

License:Apache License

/**
 * Finds the metadata for all of the topics.
 *
 * @return an {@link Observable} of {@link Topic} containing the metadata about the topic
 *//*  w w w  .  j  a v a2s  .c om*/
public Observable<Topic> findAll() {
    return Observable.create(subscriber -> {
        Table table = dynamoDB.getTable(TOPIC_TABLE_NAME);

        ItemCollection<ScanOutcome> results = table.scan(new ScanSpec());

        results.forEach(item -> {
            Topic metadata = new Topic();
            metadata.setName(item.getString("name"));
            metadata.setArn(item.getString("arn"));
            metadata.setRegistered(true);

            subscriber.onNext(metadata);
        });

        subscriber.onCompleted();
    });
}

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

License:Open Source License

@Override
public Chunk<E> findAll(Chunkable chunkable) {
    Preconditions.checkNotNull(chunkable);
    Preconditions.checkArgument(Sort.Direction.DESC != chunkable.getDirection(),
            "DynamoDB only supports scanning forwards");
    ScanSpec spec = new ScanSpec();
    if (false == Strings.isNullOrEmpty(chunkable.getPaginationToken())) {
        spec.withExclusiveStartKey(new PrimaryKey(hashKeyName, chunkable.getPaginationToken()));
    }/*from  w  ww . jav  a 2 s .c  o m*/
    spec.withMaxPageSize(chunkable.getMaxPageSize()).withMaxResultSize(chunkable.getMaxPageSize());

    final ItemCollection<ScanOutcome> results = table.scan(spec);

    final List<Item> itemList;
    try {
        itemList = Lists.newArrayList(results.iterator());
    } catch (AmazonClientException e) {
        throw convertDynamoDBException(e, "scan", null /* conditionMessage */);
    }
    final List<E> entities = itemList.stream().map(this::convertItemToDomain) //O(n)
            .collect(Collectors.toList()); //O(n)
    final Map<String, AttributeValue> lastEvaluatedKey = results.getLastLowLevelResult() == null ? null
            : results.getLastLowLevelResult().getScanResult().getLastEvaluatedKey();
    final String paginationToken = lastEvaluatedKey == null ? null : lastEvaluatedKey.get(hashKeyName).getS();
    return new ChunkImpl<>(entities, paginationToken, chunkable);
}

From source file:vfma.LoadSensorData.java

License:Open Source License

public ArrayList<RawSensorData> getSensorData(String lastTimestamp) throws VFMException {

    ArrayList<RawSensorData> rsdlist = new ArrayList<RawSensorData>();

    try {//from   w  w w.ja  v  a2 s.  co m

        AmazonDynamoDBClient client = new AmazonDynamoDBClient()
                .withEndpoint("https://dynamodb.us-west-2.amazonaws.com");
        DynamoDB dynamoDB = new DynamoDB(client);
        Table table = dynamoDB.getTable("sensorData");
        ScanSpec scanSpec = new ScanSpec();

        System.out.println("Get sensors...");
        ItemCollection<ScanOutcome> items = table.scan(scanSpec);

        String lastTimeValue;

        Iterator<Item> iter = items.iterator();
        while (iter.hasNext()) {
            Item item = iter.next();

            RawSensorData rsd = new RawSensorData();

            rsd.setTimestamp(item.getJSON("pass").replace("\"", ""));
            final JSONObject rawData = new JSONObject(item.getJSON("payload"));
            rsd.setSensorId(rawData.getString("sensor_id_time"));
            rsd.setPassing(rawData.getString("passing"));

            System.out.println("Read " + rsd.getSensorId());

            if (rsd.getTimestamp().compareTo(lastTimestamp) > 0)
                rsdlist.add(rsd);

            lastTimeValue = rsd.getTimestamp();
        }

    } catch (Exception e) {
        System.err.println("Unable to scan the table:");
        System.err.println(e.getMessage());
    }

    return rsdlist;
}