Example usage for com.amazonaws.services.dynamodbv2.model Condition Condition

List of usage examples for com.amazonaws.services.dynamodbv2.model Condition Condition

Introduction

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

Prototype

Condition

Source Link

Usage

From source file:AmazonDynamoDBSample_PutThrottled.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//  w  ww  .  j av  a  2 s. c o m

    try {
        String tableName = "my-favorite-movies-table";

        // Create a table with a primary hash key named 'name', which holds
        // a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                        .withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

        // Create table if it does not exist yet
        TableUtils.createTableIfNotExists(dynamoDB, createTableRequest);
        // wait for the table to move into ACTIVE state
        TableUtils.waitUntilActive(dynamoDB, tableName);

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James",
                "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        Thread[] thrds = new Thread[16];
        for (int i = 0; i < thrds.length; i++) {
            thrds[i] = newItemCreationThread(tableName, i);
            thrds[i].start();
        }
        for (Thread thrd : thrds) {
            thrd.join();
        }

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:RandomQuery1OnDynamoDB.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from  w  w  w. j  a  v  a  2 s .co  m

    try {

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        System.out.println("Table count :" + tableDescription.getItemCount());

        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        // Scan items for movies with a year attribute greater than 1985
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        System.out.println("no of item " + lItem);
        for (int i = 0; i <= 49999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iNoOfItems));
            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withN(randomInt));
            scanFilter.put("id", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);
            System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1));

        }
        // calculate time difference for update file time
        long lEndTime = new Date().getTime();
        long difference = lEndTime - lStartTime;
        System.out.println("Elapsed milliseconds: " + difference);
        System.out.println("Elapsed seconds: " + difference * 0.001);
        System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:RandomQuery2OnDynamoDB.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();// w  ww. j  ava2 s  .c om

    try {

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);
        long lStartTime = new Date().getTime();
        System.out.println("start time: " + lStartTime);
        Random rn = new Random();
        Long lItem = tableDescription.getItemCount();
        int iNoOfItems = lItem.intValue();
        int iPointOnePercent = (int) ((int) iNoOfItems * 0.001);
        int iOnePercent = (int) ((int) iNoOfItems * 0.01);
        System.out.println("TotalItems:" + iNoOfItems + "::0.1% of data is :: " + iPointOnePercent
                + "::1% of data is :" + iOnePercent);

        // Generating 25000 random queries for 0.1 to 1 % of the data
        for (int i = 0; i <= 24999; i++) {
            String randomInt = Integer.toString(rn.nextInt(iOnePercent - iPointOnePercent) + iPointOnePercent);
            HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
            Condition condition = new Condition().withComparisonOperator(ComparisonOperator.EQ.toString())
                    .withAttributeValueList(new AttributeValue().withN(randomInt));
            scanFilter.put("id", condition);
            ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
            ScanResult scanResult = dynamoDB.scan(scanRequest);
            System.out.println("Random No :" + randomInt + ":: Query no: " + (i + 1));

        }
        // calculate time difference for update file time
        long lEndTime = new Date().getTime();
        long difference = lEndTime - lStartTime;
        System.out.println("Elapsed milliseconds: " + difference);
        System.out.println("Elapsed seconds: " + difference * 0.001);
        System.out.println("Elapsed Minutes: " + (int) ((difference / (1000 * 60)) % 60));

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:amazon.dynamodb.config.DynamoDBManager.java

License:Open Source License

/**
 * Query Amazon DynamoDB/*from   www.  java  2s .c  om*/
 *
 * @param hashKey Hash key for the query request.
 *
 * @param range The range of geohashs to query.
 *
 * @return The query result.
 */
public List<QueryResult> queryGeohash(QueryRequest queryRequest, long hashKey, GeoHashRango range) {
    List<QueryResult> queryResults = new ArrayList<QueryResult>();
    Map<String, AttributeValue> lastEvaluatedKey = null;

    do {
        Map<String, Condition> keyConditions = new HashMap<String, Condition>();

        Condition hashKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ)
                .withAttributeValueList(new AttributeValue().withN(String.valueOf(hashKey)));
        keyConditions.put(config.getHashKeyAttributeName(), hashKeyCondition);

        AttributeValue minRange = new AttributeValue().withN(Long.toString(range.getRangeMin()));
        AttributeValue maxRange = new AttributeValue().withN(Long.toString(range.getRangeMax()));

        Condition geohashCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN)
                .withAttributeValueList(minRange, maxRange);
        keyConditions.put(config.getGeohashAttributeName(), geohashCondition);

        queryRequest.withTableName(config.getTableName()).withKeyConditions(keyConditions)
                .withIndexName(config.getGeohashIndexName()).withConsistentRead(true)
                .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
                .withExclusiveStartKey(lastEvaluatedKey);

        QueryResult queryResult = config.getDynamoDBClient().query(queryRequest);
        queryResults.add(queryResult);

        lastEvaluatedKey = queryResult.getLastEvaluatedKey();

    } while (lastEvaluatedKey != null);

    return queryResults;
}

From source file:awslabs.lab22.SolutionCode.java

License:Open Source License

@Override
public QueryResult lookupByHashKey(AmazonDynamoDBClient ddbClient, String tableName, String company) {
    // Construct an AttributeValue object containing the provided company name.
    AttributeValue attributeValue = new AttributeValue().withS(company);
    // Construct a Condition object containing the desired comparison ("EQ") and the attribute value
    // containing the company name.
    Condition condition = new Condition().withComparisonOperator("EQ").withAttributeValueList(attributeValue);

    // Construct a QueryRequest object that performs a consistent read on the specified table for the
    // previously constructed condition.
    QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withConsistentRead(true);
    queryRequest.addKeyConditionsEntry("Company", condition);

    // Submit the query by calling the query method of the ddbClient object and return the result.
    return ddbClient.query(queryRequest);
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public List<Map<String, AttributeValue>> getImageItems(AmazonDynamoDBClient dynamoDbClient) {
    try {//from   w w w . ja  v a 2s.  co  m
        String tableName = System.getProperty("SESSIONTABLE");
        String keyPrefix = System.getProperty("PARAM3");

        ScanRequest scanRequest = new ScanRequest(tableName).withSelect("ALL_ATTRIBUTES");

        if (!keyPrefix.isEmpty()) {
            Map<String, Condition> scanFilter = new HashMap<String, Condition>();
            scanFilter.put("Key", new Condition().withAttributeValueList(new AttributeValue().withS(keyPrefix))
                    .withComparisonOperator("BEGINS_WITH"));
            scanRequest.withScanFilter(scanFilter);
        }

        return dynamoDbClient.scan(scanRequest).getItems();
    } catch (Exception ex) {
        labController.logMessageToPage("getImageItems Error: " + ex.getMessage() + ":" + ex.getStackTrace());
        return null;
    }
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public Boolean isImageInDynamo(AmazonDynamoDBClient dynamoDbClient, String tableName, String key) {
    QueryRequest queryRequest = new QueryRequest(tableName).withConsistentRead(true);
    queryRequest.addKeyConditionsEntry("Key",
            new Condition().withComparisonOperator("EQ").withAttributeValueList(new AttributeValue(key)));

    return (dynamoDbClient.query(queryRequest).getCount() > 0);
}

From source file:br.com.faccilitacorretor.middleware.dynamo.AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*  www  . ja va  2s  .c  o m*/

    try {
        String tableName = "my-favorite-movies-table";

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.awaitTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James",
                "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.alertlogic.aws.kinesis.test1.webserver.GetCountsServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    MultiMap<String> params = new MultiMap<>();
    UrlEncoded.decodeTo(req.getQueryString(), params, "UTF-8");

    // We need both parameters to properly query for counts
    if (!params.containsKey(PARAMETER_RESOURCE) || !params.containsKey(PARAMETER_RANGE_IN_SECONDS)) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//  www. ja v  a  2s.c o m
    }

    // Parse query string as a single integer - the number of seconds since "now" to query for new counts
    String resource = params.getString(PARAMETER_RESOURCE);
    int rangeInSeconds = Integer.parseInt(params.getString(PARAMETER_RANGE_IN_SECONDS));

    Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, -1 * rangeInSeconds);
    Date startTime = c.getTime();
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Querying for counts of resource %s since %s", resource,
                DATE_FORMATTER.get().format(startTime)));
    }

    DynamoDBQueryExpression<HttpReferrerPairsCount> query = new DynamoDBQueryExpression<>();
    HttpReferrerPairsCount hashKey = new HttpReferrerPairsCount();
    hashKey.setResource(resource);
    query.setHashKeyValues(hashKey);

    Condition recentUpdates = new Condition().withComparisonOperator(ComparisonOperator.GT)
            .withAttributeValueList(new AttributeValue().withS(DATE_FORMATTER.get().format(startTime)));
    query.setRangeKeyConditions(Collections.singletonMap("timestamp", recentUpdates));

    List<HttpReferrerPairsCount> counts = mapper.query(HttpReferrerPairsCount.class, query);

    // Return the counts as JSON
    resp.setContentType("application/json");
    resp.setStatus(HttpServletResponse.SC_OK);
    JSON.writeValue(resp.getWriter(), counts);
}

From source file:com.app.dynamoDb.DynamoFacebookUsers.java

License:Open Source License

public boolean isExist(String UserID) {
    ScanRequest scanRequest = new ScanRequest("FacebookUsers");

    Map<String, Condition> scanFilter = new HashMap<String, Condition>();
    scanFilter.put("UserID", new Condition().withAttributeValueList(new AttributeValue(UserID))
            .withComparisonOperator(ComparisonOperator.EQ));

    scanRequest.setScanFilter(scanFilter);
    ScanResult scanResult = dynamoDB.scan(scanRequest);

    for (Map<String, AttributeValue> item : scanResult.getItems()) {
        if (!(item.isEmpty()))
            return true;
    }//from   w  w  w.java 2s  . c om
    return false;
}