Search in sources :

Example 1 with DynamoDBQueryExpression

use of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression in project openhab1-addons by openhab.

the class DynamoDBPersistenceService method createQueryExpression.

/**
     * Construct dynamodb query from filter
     *
     * @param filter
     * @return DynamoDBQueryExpression corresponding to the given FilterCriteria
     */
private DynamoDBQueryExpression<DynamoDBItem<?>> createQueryExpression(Class<? extends DynamoDBItem<?>> dtoClass, FilterCriteria filter) {
    DynamoDBItem<?> item = getDynamoDBHashKey(dtoClass, filter.getItemName());
    final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression = new DynamoDBQueryExpression<DynamoDBItem<?>>().withHashKeyValues(item).withScanIndexForward(filter.getOrdering() == Ordering.ASCENDING).withLimit(filter.getPageSize());
    Condition timeFilter = maybeAddTimeFilter(queryExpression, filter);
    maybeAddStateFilter(filter, queryExpression);
    logger.debug("Querying: {} with {}", filter.getItemName(), timeFilter);
    return queryExpression;
}
Also used : Condition(com.amazonaws.services.dynamodbv2.model.Condition)

Example 2 with DynamoDBQueryExpression

use of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression in project aws-doc-sdk-examples by awsdocs.

the class DynamoDBMapperQueryScanExample method FindRepliesPostedWithinTimePeriod.

private static void FindRepliesPostedWithinTimePeriod(DynamoDBMapper mapper, String forumName, String threadSubject) throws Exception {
    String partitionKey = forumName + "#" + threadSubject;
    System.out.println("FindRepliesPostedWithinTimePeriod: Find replies for thread Message = 'DynamoDB Thread 2' posted within a period.");
    // Two
    long startDateMilli = (new Date()).getTime() - (14L * 24L * 60L * 60L * 1000L);
    // weeks
    // ago.
    // One
    long endDateMilli = (new Date()).getTime() - (7L * 24L * 60L * 60L * 1000L);
    // week
    // ago.
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    String startDate = dateFormatter.format(startDateMilli);
    String endDate = dateFormatter.format(endDateMilli);
    Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
    eav.put(":val1", new AttributeValue().withS(partitionKey));
    eav.put(":val2", new AttributeValue().withS(startDate));
    eav.put(":val3", new AttributeValue().withS(endDate));
    DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>().withKeyConditionExpression("Id = :val1 and ReplyDateTime between :val2 and :val3").withExpressionAttributeValues(eav);
    List<Reply> betweenReplies = mapper.query(Reply.class, queryExpression);
    for (Reply reply : betweenReplies) {
        System.out.format("Id=%s, Message=%s, PostedBy=%s %n, PostedDateTime=%s %n", reply.getId(), reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime());
    }
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) HashMap(java.util.HashMap) DynamoDBQueryExpression(com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 3 with DynamoDBQueryExpression

use of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression in project openhab1-addons by openhab.

the class DynamoDBPersistenceService method maybeAddStateFilter.

private void maybeAddStateFilter(FilterCriteria filter, final DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression) {
    if (filter.getOperator() != null && filter.getState() != null) {
        // Convert filter's state to DynamoDBItem in order get suitable string representation for the state
        final DynamoDBItem<?> filterState = AbstractDynamoDBItem.fromState(filter.getItemName(), filter.getState(), new Date());
        queryExpression.setFilterExpression(String.format("%s %s :opstate", DynamoDBItem.ATTRIBUTE_NAME_ITEMSTATE, operatorAsString(filter.getOperator())));
        filterState.accept(new DynamoDBItemVisitor() {

            @Override
            public void visit(DynamoDBStringItem dynamoStringItem) {
                queryExpression.setExpressionAttributeValues(ImmutableMap.of(":opstate", new AttributeValue().withS(dynamoStringItem.getState())));
            }

            @Override
            public void visit(DynamoDBBigDecimalItem dynamoBigDecimalItem) {
                queryExpression.setExpressionAttributeValues(ImmutableMap.of(":opstate", new AttributeValue().withN(dynamoBigDecimalItem.getState().toPlainString())));
            }
        });
    }
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) Date(java.util.Date)

Example 4 with DynamoDBQueryExpression

use of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression in project openhab1-addons by openhab.

the class DynamoDBPersistenceService method query.

/**
     * {@inheritDoc}
     */
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    logger.debug("got a query");
    if (!isProperlyConfigured) {
        logger.warn("Configuration for dynamodb not yet loaded or broken. Not storing item.");
        return Collections.emptyList();
    }
    if (!maybeConnectAndCheckConnection()) {
        logger.warn("DynamoDB not connected. Not storing item.");
        return Collections.emptyList();
    }
    String itemName = filter.getItemName();
    Item item = getItemFromRegistry(itemName);
    if (item == null) {
        logger.warn("Could not get item {} from registry!", itemName);
        return Collections.emptyList();
    }
    Class<DynamoDBItem<?>> dtoClass = AbstractDynamoDBItem.getDynamoItemClass(item.getClass());
    String tableName = tableNameResolver.fromClass(dtoClass);
    DynamoDBMapper mapper = getDBMapper(tableName);
    logger.debug("item {} (class {}) will be tried to query using dto class {} from table {}", itemName, item.getClass(), dtoClass, tableName);
    List<HistoricItem> historicItems = new ArrayList<HistoricItem>();
    DynamoDBQueryExpression<DynamoDBItem<?>> queryExpression = createQueryExpression(dtoClass, filter);
    @SuppressWarnings("rawtypes") final PaginatedQueryList<? extends DynamoDBItem> paginatedList;
    try {
        paginatedList = mapper.query(dtoClass, queryExpression);
    } catch (AmazonServiceException e) {
        logger.error("DynamoDB query raised unexpected exception: {}. Returning empty collection. " + "Status code 400 (resource not found) might occur if table was just created.", e.getMessage());
        return Collections.emptyList();
    }
    for (int itemIndexOnPage = 0; itemIndexOnPage < filter.getPageSize(); itemIndexOnPage++) {
        int itemIndex = filter.getPageNumber() * filter.getPageSize() + itemIndexOnPage;
        DynamoDBItem<?> dynamoItem;
        try {
            dynamoItem = paginatedList.get(itemIndex);
        } catch (IndexOutOfBoundsException e) {
            logger.debug("Index {} is out-of-bounds", itemIndex);
            break;
        }
        if (dynamoItem != null) {
            HistoricItem historicItem = dynamoItem.asHistoricItem(item);
            logger.trace("Dynamo item {} converted to historic item: {}", item, historicItem);
            historicItems.add(historicItem);
        }
    }
    return historicItems;
}
Also used : DynamoDBMapper(com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper) ArrayList(java.util.ArrayList) HistoricItem(org.openhab.core.persistence.HistoricItem) Item(org.openhab.core.items.Item) AmazonServiceException(com.amazonaws.AmazonServiceException) HistoricItem(org.openhab.core.persistence.HistoricItem)

Example 5 with DynamoDBQueryExpression

use of com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression in project aws-doc-sdk-examples by awsdocs.

the class DynamoDBMapperQueryScanExample method FindRepliesInLast15Days.

private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumName, String threadSubject) throws Exception {
    System.out.println("FindRepliesInLast15Days: Replies within last 15 days.");
    String partitionKey = forumName + "#" + threadSubject;
    long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
    Date twoWeeksAgo = new Date();
    twoWeeksAgo.setTime(twoWeeksAgoMilli);
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    String twoWeeksAgoStr = dateFormatter.format(twoWeeksAgo);
    Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
    eav.put(":val1", new AttributeValue().withS(partitionKey));
    eav.put(":val2", new AttributeValue().withS(twoWeeksAgoStr.toString()));
    DynamoDBQueryExpression<Reply> queryExpression = new DynamoDBQueryExpression<Reply>().withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2").withExpressionAttributeValues(eav);
    List<Reply> latestReplies = mapper.query(Reply.class, queryExpression);
    for (Reply reply : latestReplies) {
        System.out.format("Id=%s, Message=%s, PostedBy=%s %n, ReplyDateTime=%s %n", reply.getId(), reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime());
    }
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) HashMap(java.util.HashMap) DynamoDBQueryExpression(com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Aggregations

AttributeValue (com.amazonaws.services.dynamodbv2.model.AttributeValue)3 Date (java.util.Date)3 DynamoDBQueryExpression (com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression)2 SimpleDateFormat (java.text.SimpleDateFormat)2 HashMap (java.util.HashMap)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 DynamoDBMapper (com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper)1 Condition (com.amazonaws.services.dynamodbv2.model.Condition)1 ArrayList (java.util.ArrayList)1 Item (org.openhab.core.items.Item)1 HistoricItem (org.openhab.core.persistence.HistoricItem)1