com.trk.aboutme.DynamoDB.DynamoDBManagerBooks.java Source code

Java tutorial

Introduction

Here is the source code for com.trk.aboutme.DynamoDB.DynamoDBManagerBooks.java

Source

/*
 * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 * 
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package com.trk.aboutme.DynamoDB;

import com.trk.aboutme.Shelf;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.util.Log;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBAutoGeneratedKey;
//import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapperConfig;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBQueryExpression;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBRangeKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBScanExpression;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBVersionAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.PaginatedScanList;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.DescribeTableResult;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.QueryResult;
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;

public class DynamoDBManagerBooks {

    private static final String TAG = "DynamoDBManager";

    /*
    * Creates a table with the following attributes:
    * 
    * Table name: testTableName Hash key: userNo type N Read Capacity Units: 10
    * Write Capacity Units: 5
    */
    public static void createTable() {

        Log.d(TAG, "Create Books table called");

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();

        KeySchemaElement kse = new KeySchemaElement().withAttributeName("pageID").withKeyType(KeyType.HASH);
        AttributeDefinition ad = new AttributeDefinition().withAttributeName("pageID")
                .withAttributeType(ScalarAttributeType.S);
        ProvisionedThroughput pt = new ProvisionedThroughput().withReadCapacityUnits(10l)
                .withWriteCapacityUnits(5l);

        CreateTableRequest request = new CreateTableRequest().withTableName(Constants.TABLE_NAME_PAGES)
                .withKeySchema(kse).withAttributeDefinitions(ad).withProvisionedThroughput(pt);

        try {
            Log.d(TAG, "Sending Create table request");
            ddb.createTable(request);
            Log.d(TAG, "Create request response successfully recieved");
        } catch (AmazonServiceException ex) {
            Log.e(TAG, "Error sending create table request", ex);
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }
    }

    /*
     * Retrieves the table description and returns the table status as a string.
     */
    public static String getTestTableStatus(String tablename) {

        try {
            AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();

            DescribeTableRequest request = new DescribeTableRequest().withTableName(tablename);
            DescribeTableResult result = ddb.describeTable(request);

            String status = result.getTable().getTableStatus();
            return status == null ? "" : status;

        } catch (ResourceNotFoundException e) {
        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }

        return "";
    }

    /*
     * Inserts ten users with userNo from 1 to 10 and random names.
     */
    public static <T> String insert(T input, String tablename) {
        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();
        DynamoDBMapper mapper = new DynamoDBMapper(ddb);
        String result = "false";
        try {
            //mapper.save(input);
            /*Map<String, AttributeValue> reply = new HashMap<String, AttributeValue>();
               reply.put("Id", new AttributeValue().withS("Amazon DynamoDB#DynamoDB Thread 1"));
               reply.put("ReplyDateTime", new AttributeValue().withS(dateFormatter.format(date3)));
               reply.put("Message", new AttributeValue().withS("DynamoDB Thread 1 Reply 1 text"));
               reply.put("PostedBy", new AttributeValue().withS("User A"));
                
               PutItemRequest replyRequest = new PutItemRequest().withTableName(tableName).withItem(reply);
               client.putItem(replyRequest);*/
            mapper.save(input, new DynamoDBMapperConfig(new DynamoDBMapperConfig.TableNameOverride(tablename)));
            return result;
        } catch (AmazonServiceException ex) {
            Log.e(TAG, "Error inserting users");
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
            return result;
        } finally {
            //TODO
        }
    }

    public static void ThreadPost(Pages pg, ResultListener<String> resultListener, Context context,
            boolean showProgressBar) {
        new DynoDBAsyncTask<Pages, Void, String>(new DynamoDBManagerBooks.PostPage(pg), resultListener, context,
                showProgressBar).execute();
    }

    private static class PostPage implements Command<String> {
        private Pages m_page;

        public PostPage(Pages p) {
            m_page = p;
        }

        @Override
        public String execute() throws IOException, IllegalStateException {
            return insert(m_page, Constants.TABLE_NAME_PAGES);
        }
    }

    public static ArrayList<Books> getBooksList(String tableName, String catagory) {

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();
        try {

            String bookId = catagory;
            long twoWeeksAgoMilli = (new Date()).getTime() - (5L * 24L * 60L * 60L * 1000L);
            Date twoWeeksAgo = new Date();
            twoWeeksAgo.setTime(twoWeeksAgoMilli);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            String twoWeeksAgoStr = df.format(twoWeeksAgo);
            ArrayList<Books> resultList = new ArrayList<Books>();

            Map<String, AttributeValue> lastEvaluatedKey = null;
            do {

                Condition hashKeyCondition = new Condition()
                        .withComparisonOperator(ComparisonOperator.EQ.toString())
                        .withAttributeValueList(new AttributeValue().withS(bookId));

                Condition rangeKeyCondition = new Condition()
                        .withComparisonOperator(ComparisonOperator.GT.toString())
                        .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));

                Map<String, Condition> keyConditions = new HashMap<String, Condition>();
                keyConditions.put("bookID", hashKeyCondition);
                keyConditions.put("posteddate", rangeKeyCondition);

                QueryRequest queryRequest = new QueryRequest().withTableName(tableName)
                        .withKeyConditions(keyConditions).withSelect("title, datecreated").withLimit(5)
                        .withExclusiveStartKey(lastEvaluatedKey);

                QueryResult result = ddb.query(queryRequest);
                for (Map<String, AttributeValue> item : result.getItems()) {
                    for (Map.Entry<String, AttributeValue> i : item.entrySet()) {

                        Books b = new Books();
                        AttributeValue value = i.getValue();
                        String vs = value.getS();

                        if (i.getKey().equals("title"))
                            b.setM_title(vs == null ? "" : vs);
                        if (i.getKey().equals("datecreated"))
                            b.setM_dateCreated(vs == null ? "" : vs);

                        resultList.add(b);
                    }
                }
                lastEvaluatedKey = result.getLastEvaluatedKey();
            } while (lastEvaluatedKey != null);

            return resultList;

        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }

        return null;
    }

    /*
     * Scans the table and returns the list of users.
     */
    public static ArrayList<Pages> getPageList(String tableName, String catagory, String book) {

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();
        try {

            String pageId = catagory + "#" + book;
            long twoWeeksAgoMilli = (new Date()).getTime() - (5L * 24L * 60L * 60L * 1000L);
            Date twoWeeksAgo = new Date();
            twoWeeksAgo.setTime(twoWeeksAgoMilli);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            String twoWeeksAgoStr = df.format(twoWeeksAgo);
            ArrayList<Pages> resultList = new ArrayList<Pages>();

            Map<String, AttributeValue> lastEvaluatedKey = null;
            do {

                Condition hashKeyCondition = new Condition()
                        .withComparisonOperator(ComparisonOperator.EQ.toString())
                        .withAttributeValueList(new AttributeValue().withS(pageId));

                Condition rangeKeyCondition = new Condition()
                        .withComparisonOperator(ComparisonOperator.GT.toString())
                        .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr));

                Map<String, Condition> keyConditions = new HashMap<String, Condition>();
                keyConditions.put("pageID", hashKeyCondition);
                keyConditions.put("datecreated", rangeKeyCondition);

                QueryRequest queryRequest = new QueryRequest().withTableName(tableName)
                        .withKeyConditions(keyConditions).withSelect("title, message, authorphoto, posteddate")
                        .withLimit(5).withExclusiveStartKey(lastEvaluatedKey);

                QueryResult result = ddb.query(queryRequest);
                for (Map<String, AttributeValue> item : result.getItems()) {
                    for (Map.Entry<String, AttributeValue> i : item.entrySet()) {
                        Pages p = new Pages();

                        AttributeValue value = i.getValue();
                        String vs = value.getS();
                        if (i.getKey().equals("title"))
                            p.setM_title(vs == null ? "" : vs);
                        if (i.getKey().equals("message"))
                            p.setM_message(vs == null ? "" : vs);
                        if (i.getKey().equals("authorphoto"))
                            p.setM_authorPhoto(vs == null ? "" : vs);
                        if (i.getKey().equals("posteddate"))
                            p.setM_postedDate(vs == null ? "" : vs);

                        resultList.add(p);
                    }
                }
                lastEvaluatedKey = result.getLastEvaluatedKey();
            } while (lastEvaluatedKey != null);

            return resultList;

        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }

        return null;
    }

    /*
     * Updates one attribute/value pair for the specified user.
     */
    public static <T> void update(T input) {

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();
        DynamoDBMapper mapper = new DynamoDBMapper(ddb);

        try {
            mapper.save(input);

        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }
    }

    /*
     * Deletes the specified user and all of its attribute/value pairs.
     */
    public static <T> void delete(T input) {

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();
        DynamoDBMapper mapper = new DynamoDBMapper(ddb);

        try {
            mapper.delete(input);

        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }
    }

    /*
     * Deletes the test table and all of its users and their attribute/value
     * pairs.
     */
    public static void cleanUp() {

        AmazonDynamoDBClient ddb = Shelf.clientManager.ddb();

        DeleteTableRequest request = new DeleteTableRequest().withTableName(Constants.TEST_TABLE_NAME);
        try {
            ddb.deleteTable(request);

        } catch (AmazonServiceException ex) {
            Shelf.clientManager.wipeCredentialsOnAuthError(ex);
        }
    }

    @DynamoDBTable(tableName = "Catagory") // Google News , Legacy topics
    public static class Catagory {
        @DynamoDBHashKey(attributeName = "bookID")
        @DynamoDBAutoGeneratedKey
        private String m_catogoryID;

        public String getM_catogoryID() {
            return m_catogoryID;
        }

        public void setM_catogoryID(String m_catogoryID) {
            this.m_catogoryID = m_catogoryID;
        }

        @DynamoDBAttribute(attributeName = "bookscount")
        private int m_noOfBooks;

        public int getM_noOfBooks() {
            return m_noOfBooks;
        }

        public void setM_noOfBooks(int m_noOfBooks) {
            this.m_noOfBooks = m_noOfBooks;
        }
    }

    @DynamoDBTable(tableName = "Book") // HeadLines , Personal topics 
    public static class Books {
        @DynamoDBHashKey(attributeName = "bookID")
        @DynamoDBAutoGeneratedKey
        private String mbookID; //catogory
        @DynamoDBAttribute(attributeName = "pagescount")
        private int m_noOfPages;
        @DynamoDBAttribute(attributeName = "title")
        private String m_title;
        @DynamoDBRangeKey(attributeName = "datecreated")
        private String m_dateCreated;
        @DynamoDBAttribute(attributeName = "catagory") // used when legacy topic search
        private String m_catagory;

        public String getMbookID() {
            return mbookID;
        }

        public void setMpageID(String mbookID) {
            this.mbookID = mbookID;
        }

        public int getM_noOfPages() {
            return m_noOfPages;
        }

        public void setM_noOfPages(int m_noOfPages) {
            this.m_noOfPages = m_noOfPages;
        }

        public String getM_title() {
            return m_title;
        }

        public void setM_title(String m_title) {
            this.m_title = m_title;
        }

        public String getM_dateCreated() {
            return m_dateCreated;
        }

        public void setM_dateCreated(String m_dateCreated) {
            this.m_dateCreated = m_dateCreated;
        }

        public String getM_catagory() {
            return m_catagory;
        }

        public void setM_catagory(String m_catagory) {
            this.m_catagory = m_catagory;
        }
    }

    @DynamoDBTable(tableName = "Pages") // App User's Views
    public static class Pages implements Serializable {
        @DynamoDBHashKey(attributeName = "pageID")
        private String m_pageID; // Catogory#Bookid
        @DynamoDBAttribute(attributeName = "title")
        private String m_title;
        @DynamoDBAttribute(attributeName = "message")
        private String m_message;
        @DynamoDBAttribute(attributeName = "authorphoto")
        private String m_authorPhoto;
        @DynamoDBAttribute(attributeName = "authorname")
        private String m_authorName;
        @DynamoDBRangeKey(attributeName = "posteddate")
        private String m_postedDate;

        public String getM_pageID() {
            return m_pageID;
        }

        public void setM_pageID(String m_pageID) {
            this.m_pageID = m_pageID;
        }

        public String getM_title() {
            return m_title;
        }

        public void setM_title(String m_title) {
            this.m_title = m_title;
        }

        public String getM_message() {
            return m_message;
        }

        public void setM_message(String m_message) {
            this.m_message = m_message;
        }

        public String getM_authorPhoto() {
            return m_authorPhoto;
        }

        public void setM_authorPhoto(String m_authorPhoto) {
            this.m_authorPhoto = m_authorPhoto;
        }

        public String getM_authorName() {
            return m_authorName;
        }

        public void setM_authorName(String m_authorName) {
            this.m_authorName = m_authorName;
        }

        public String getM_postedDate() {
            return m_postedDate;
        }

        public void setM_postedDate(String m_postedDate) {
            this.m_postedDate = m_postedDate;
        }
    }
}