Java 类com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper 实例源码

项目:PlatePicks-Android    文件:TableRestaurant.java   
/**
 * Get the restaurant and return return Location object
 * @param restId
 * @return
 */
public static Location getRestaurantInfo (String restId){
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    RestaurantDO restaurantToGet;
    restaurantToGet = mapper.load(RestaurantDO.class, restId);

    //get information to construct Location object
    String city = restaurantToGet.getCity();
    String restaurantName = restaurantToGet.getRestaurantName();
    int postalCode = restaurantToGet.getPostalCode();
    String state = restaurantToGet.getState();
    List<String> address = restaurantToGet.getAddress();
    String restaurantId = restaurantToGet.getRestaurantId();
    double longitude = restaurantToGet.getLongitude();
    double latitude = restaurantToGet.getLatitude();
    List<String> category = restaurantToGet.getCategories();

    return new Location(city, restaurantName, postalCode, state, address, restaurantId, longitude,
            latitude, category);
}
项目:PlatePicks-Android    文件:TableFood.java   
public static FoodReceive getFood (String foodId){
        final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
        FoodDO foodToGet;
        foodToGet = mapper.load(FoodDO.class, foodId);
        String restId = foodToGet.getRestaurantId();
        String foodName = foodToGet.getName();
        //System.out.println("Got restaurant Id: " + foodToGet.getRestaurantId());
        Location loc = getRestaurantInfo(restId);
        URL myURL = null;

        try{
            String strURL = "http://s3-media3.fl.yelpcdn.com/bphoto/" + foodId + "/o.jpg";
            myURL = new URL(strURL);
        }catch (MalformedURLException e){
            System.out.println("Bad URL");
        }
//        return new FoodReceive("1", null , "3", myURL);
        return new FoodReceive(foodId, loc, foodName, myURL);
    }
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
/**
 * Saves the object given into DynamoDB, using the default configuration.
 * 
 * @param userId Cognito Identity Id
 * @param score game score
 * @param userName a name to display
 */
public static void saveRecord(String userId, int score, String userName) {
    Log.d(TAG, "Insert record called");
    checkDynamoDBClientAvailability();
    DynamoDBMapper mapper = new DynamoDBMapper(ddb);
    try {
        GameRecord r = new GameRecord();
        r.setUserId(userId);
        r.setScore(score);
        r.setUserName(userName);
        r.setGameId(Constants.GAME_ID);

        Log.d(TAG, "Inserting record");
        mapper.save(r);
        Log.d(TAG, "record inserted");
    } catch (AmazonServiceException ex) {
        throw new IllegalStateException("Error inserting record", ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
public static void insertUsers() {
    AmazonDynamoDBClient ddb = UserPreferenceDemoActivity.clientManager
            .ddb();
    DynamoDBMapper mapper = new DynamoDBMapper(ddb);

    try {
        for (int i = 1; i <= 10; i++) {
            UserPreference userPreference = new UserPreference();
            userPreference.setUserNo(i);
            userPreference.setFirstName(Constants.getRandomName());
            userPreference.setLastName(Constants.getRandomName());

            Log.d(TAG, "Inserting users");
            mapper.save(userPreference);
            Log.d(TAG, "Users inserted");
        }
    } catch (AmazonServiceException ex) {
        Log.e(TAG, "Error inserting users");
        UserPreferenceDemoActivity.clientManager
                .wipeCredentialsOnAuthError(ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
public static ArrayList<UserPreference> getUserList() {

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

        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
        try {
            PaginatedScanList<UserPreference> result = mapper.scan(
                    UserPreference.class, scanExpression);

            ArrayList<UserPreference> resultList = new ArrayList<UserPreference>();
            for (UserPreference up : result) {
                resultList.add(up);
            }
            return resultList;

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

        return null;
    }
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
public static UserPreference getUserPreference(int userNo) {

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

        try {
            UserPreference userPreference = mapper.load(UserPreference.class,
                    userNo);

            return userPreference;

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

        return null;
    }
项目:PlatePicks-Android    文件:NoSQLListResult.java   
@Override
public void updateItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    final double originalValue = result.getCreationDate();
    result.setCreationDate(SampleDataGenerator.getRandomSampleNumber());
    try {
        mapper.save(result);
    } catch (final AmazonClientException ex) {
        // Restore original data if save fails, and re-throw.
        result.setCreationDate(originalValue);
        throw ex;
    }
}
项目:PlatePicks-Android    文件:NoSQLCommentResult.java   
@Override
public void updateItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    final String originalValue = result.getContent();
    result.setContent(SampleDataGenerator.getRandomSampleString("content"));
    try {
        mapper.save(result);
    } catch (final AmazonClientException ex) {
        // Restore original data if save fails, and re-throw.
        result.setContent(originalValue);
        throw ex;
    }
}
项目:PlatePicks-Android    文件:NoSQLFoodResult.java   
@Override
public void updateItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    final double originalValue = result.getDislike();
    result.setDislike(SampleDataGenerator.getRandomSampleNumber());
    try {
        mapper.save(result);
    } catch (final AmazonClientException ex) {
        // Restore original data if save fails, and re-throw.
        result.setDislike(originalValue);
        throw ex;
    }
}
项目:PlatePicks-Android    文件:TableRestaurant.java   
public static void insertRestaurant (Location loc){
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();;

    RestaurantDO restaurantToBeInserted = new RestaurantDO();
    restaurantToBeInserted.setCity(loc.getCity());
    restaurantToBeInserted.setRestaurantName(loc.getRestaurantName());
    restaurantToBeInserted.setPostalCode(loc.getPostal_code());
    restaurantToBeInserted.setAddress(loc.getAddress());
    restaurantToBeInserted.setRestaurantId(loc.getRestaurantId());
    restaurantToBeInserted.setLongitude(loc.getLongitude());
    restaurantToBeInserted.setLatitude(loc.getLatitude());
    restaurantToBeInserted.setCategories(loc.getCategory());

    AmazonClientException lastException = null;

    try {
        mapper.save(restaurantToBeInserted);
    } catch (final AmazonClientException ex) {
        System.out.println("Failed saving item batch: " + ex.getMessage());
        lastException = ex;
    }

    if (lastException != null) {
        // Re-throw the last exception encountered to alert the user.
        throw lastException;
    }

    System.out.println("Insert successful");
}
项目:PlatePicks-Android    文件:TableFood.java   
/**
     * Inserting the food into the database, dislike and like are set to 0
     * @param food
     */
    public static void insertFood(FoodReceive food){
        Log.d(LOG_TAG, "Inserting: " + food.getName());
        final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
        final FoodDO firstItem = new FoodDO();

        firstItem.setFoodId(food.getFood_id());
        firstItem.setRestaurantId(food.getLocation().getRestaurantId());
        firstItem.setName(food.getName());

        AmazonClientException lastException = null;
        DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
        Map<String, ExpectedAttributeValue> expectedAttributes =
                ImmutableMapParameter.<String, ExpectedAttributeValue>builder()
                        .put("foodId", new ExpectedAttributeValue(false)).build();
        saveExpression.setExpected(expectedAttributes);

        try {
//            mapper.save(firstItem);
            mapper.save(firstItem, saveExpression);
        } catch (ConditionalCheckFailedException e){
            Log.e(LOG_TAG,"The foodId exists: " + e.getMessage());
            lastException = e;
        } catch (final AmazonClientException ex) {
            Log.e(LOG_TAG,"Failed saving item batch: " + ex.getMessage());
            lastException = ex;
        }

        if (lastException != null) {
            // Re-throw the last exception encountered to alert the user.
            throw lastException;
        }

        Log.d(LOG_TAG, "Insert successful");
    }
项目:PlatePicks-Android    文件:TableComment.java   
public static void insertComment(String userId, String foodId, String content) throws AmazonClientException {
        System.out.println("Inserting comment");

        long time = System.currentTimeMillis();
        String s = String.valueOf(time/1000);
//        System.out.println("time: " + time);

        final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
        final CommentDO firstItem = new CommentDO();

        firstItem.setUserId(userId);
        firstItem.setFoodId(foodId);
        firstItem.setContent(content);
        firstItem.setTime(time);
        AmazonClientException lastException = null;

        try {
            mapper.save(firstItem);
        } catch (final AmazonClientException ex) {
            System.out.println("Failed saving item batch: " + ex.getMessage());
            lastException = ex;
        }

        if (lastException != null) {
            // Re-throw the last exception encountered to alert the user.
            throw lastException;
        }

        System.out.println("Insert comment successful");
    }
项目:PlatePicks-Android    文件:TableComment.java   
public static List<CommentDO> getCommentsFromFoodID(String foodId) {
    Log.d(LOG_TAG, "Getting the comments from foodId");

    PaginatedScanList<CommentDO> results;
    Iterator<CommentDO> resultsIterator;

    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();

    // These hold attribute actual names
    final Map<String, String> filterExpressionAttributeNames = new HashMap<>();
    filterExpressionAttributeNames.put("#key", "foodId");

    // These hold attributes values
    final Map<String, AttributeValue> filterExpressionAttributeValues = new HashMap<>();
    filterExpressionAttributeValues.put(":value",
            new AttributeValue().withS(foodId));

    // Setup Scan
    final DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
            .withFilterExpression("#key = :value")
            .withExpressionAttributeNames(filterExpressionAttributeNames)
            .withExpressionAttributeValues(filterExpressionAttributeValues);

    // Execute Scan
    results = mapper.scan(CommentDO.class, scanExpression);

    return results;
}
项目:PlatePicks-Android    文件:TableComment.java   
public static List<CommentDO> getCommentsFromUserID(String userId) {
    Log.d(LOG_TAG, "Getting the comments from userId");

    PaginatedScanList<CommentDO> results;
    Iterator<CommentDO> resultsIterator;

    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();

    // These hold attribute actual names
    final Map<String, String> filterExpressionAttributeNames = new HashMap<>();
    filterExpressionAttributeNames.put("#key", "userId");

    // These hold attributes values
    final Map<String, AttributeValue> filterExpressionAttributeValues = new HashMap<>();
    filterExpressionAttributeValues.put(":value",
            new AttributeValue().withS(userId));

    // Setup Scan
    final DynamoDBScanExpression scanExpression = new DynamoDBScanExpression()
            .withFilterExpression("#key = :value")
            .withExpressionAttributeNames(filterExpressionAttributeNames)
            .withExpressionAttributeValues(filterExpressionAttributeValues);

    // Execute Scan
    results = mapper.scan(CommentDO.class, scanExpression);
    return results;
}
项目:PlatePicks-Android    文件:AWSMobileClient.java   
private AWSMobileClient(final Context context,
                        final String cognitoIdentityPoolID,
                        final Regions cognitoRegion,
                        final String mobileAnalyticsAppID,
                        final IdentityManager identityManager,
                        final ClientConfiguration clientConfiguration) {

    this.context = context;
    this.identityManager = identityManager;
    this.clientConfiguration = clientConfiguration;

    try {
        this.mobileAnalyticsManager =
            MobileAnalyticsManager.
                getOrCreateInstance(context,
                                    AWSConfiguration.AMAZON_MOBILE_ANALYTICS_APP_ID,
                                    AWSConfiguration.AMAZON_MOBILE_ANALYTICS_REGION,
                                    identityManager.getCredentialsProvider(),
                                    new AnalyticsConfig(clientConfiguration));
    }
    catch (final InitializationException ie) {
        Log.e(LOG_TAG, "Unable to initalize Amazon Mobile Analytics. " + ie.getMessage(), ie);
    }

    this.syncManager = new CognitoSyncManager(context, AWSConfiguration.AMAZON_COGNITO_REGION,
        identityManager.getCredentialsProvider(), clientConfiguration);
    this.dynamoDBClient = new AmazonDynamoDBClient(identityManager.getCredentialsProvider(), clientConfiguration);
    this.dynamoDBMapper = new DynamoDBMapper(dynamoDBClient);
}
项目:Bikeable    文件:MainActivity.java   
@Override
protected Void doInBackground(Void... params) {
    // init iria data
    IriaData.initIriaData();

    // Initialize the Amazon Cognito credentials provider
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            "eu-west-1:75f8b90a-9b52-485b-86c4-bc517b8ad22b", // Identity Pool ID
            Regions.EU_WEST_1 // Region
    );
    AmazonDynamoDBClient ddbClient = Region.getRegion(Regions.EU_WEST_1)
            .createClient(
                    AmazonDynamoDBClient.class,
                    credentialsProvider,
                    new ClientConfiguration()
            );
    mapper = new DynamoDBMapper(ddbClient);

    // get iria data
    try {
        ConstantsFromTable bikePathLayerUrl = mapper.load(ConstantsFromTable.class, "bikePathLayerUrl");
        ConstantsFromTable telOfanLayerUrl = mapper.load(ConstantsFromTable.class, "telOfanLayerUrl");
        ConstantsFromTable telOFunSiteURL = mapper.load(ConstantsFromTable.class, "telOFunStationsURL");
        IriaData.getIriaData(bikePathLayerUrl, telOfanLayerUrl, telOFunSiteURL);
        IriaData.isDataReceived = true;
    } catch (Exception e) { // There was a problem getting the data from the Municipality site
        Log.i("INFO:", "in main activity Data from iria is NOT OK");
        IriaData.isDataReceived = false;
        e.printStackTrace();
    }

    return null;
}
项目:Bikeable    文件:IriaData.java   
public static void updateTelOFunBikesAvailabilityWithDynamoDB(Marker marker, DynamoDBMapper mapper) throws IOException {

        SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
        outputFmt.setTimeZone(TimeZone.getTimeZone("utc"));
        String currUtcTimeStr = outputFmt.format(new Date());

        try {
            int stationId = Integer.parseInt(marker.getSnippet());
            StationFromTable selectedStation = mapper.load(StationFromTable.class, stationId);

            if (selectedStation != null) {
                String updateTimeStr =  selectedStation.getTimeStamp();
                Date updateTime = outputFmt.parse(updateTimeStr);
                Date currUtcTime = outputFmt.parse(currUtcTimeStr);
                long seconds = (updateTime.getTime()-currUtcTime.getTime())/1000;
                if (Math.abs(seconds) < 360 ) {
                    telOFunStationsDict.get(stationId).setNumOfStands(selectedStation.getStandsAvailable() +
                            selectedStation.getBikesAvailable());
                    telOFunStationsDict.get(stationId).setNumOfStandsAvailable(selectedStation.getStandsAvailable());
                    telOFunStationsDict.get(stationId).setNumOfBikesAvailable(selectedStation.getBikesAvailable());
                    telOFunStationsDict.get(stationId).setStationName(selectedStation.getName());
                    return;
                }
            }
        } catch (Exception e){
            updateTelOFunBikesAvailability(marker);
            return;
        }
        updateTelOFunBikesAvailability(marker);

    }
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
/**
 * Queries an Amazon DynamoDB table and returns the matching results, using
 * the default configuration.
 * 
 * @return a list of game records sorted by scores
 */
public static ArrayList<GameRecord> getGameRecords() {
    Log.d(TAG, "Get record rank called");
    checkDynamoDBClientAvailability();

    DynamoDBMapper mapper = new DynamoDBMapper(ddb);

    GameRecord r = new GameRecord();
    r.setGameId(Constants.GAME_ID);

    Condition rangeKeyCondition = new Condition();
    rangeKeyCondition.withComparisonOperator(ComparisonOperator.GT)
            .withAttributeValueList(new AttributeValue().withN("0"));

    DynamoDBQueryExpression<GameRecord> queryExpression = new DynamoDBQueryExpression<GameRecord>()
            .withHashKeyValues(r)
            .withRangeKeyCondition("score", rangeKeyCondition)
            .withConsistentRead(false).withScanIndexForward(false);

    try {
        Log.d(TAG, "Querying game records");
        PaginatedQueryList<GameRecord> result = mapper.query(
                GameRecord.class, queryExpression);
        Log.d(TAG, "Query result successfully received");
        ArrayList<GameRecord> resultList = new ArrayList<GameRecord>();
        if (result == null) {
            return resultList;
        }
        for (GameRecord up : result) {
            resultList.add(up);
        }
        return resultList;
    } catch (AmazonServiceException ex) {
        throw new IllegalStateException("Error querying", ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
/**
 * Gets a specific record according to the given userId.
 * 
 * @param userId Cognito Identity Id of the user
 * @return an instance of GameRecord
 */
public static GameRecord getRecord(int userId) {
    Log.d(TAG, "Get record called");
    checkDynamoDBClientAvailability();

    DynamoDBMapper mapper = new DynamoDBMapper(ddb);
    try {
        Log.d(TAG, "Loading game record");
        GameRecord n = mapper.load(GameRecord.class, userId);
        Log.d(TAG, "Loaded successfully");
        return n;
    } catch (AmazonServiceException ex) {
        throw new IllegalStateException("Error getting record", ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
/**
 * Updates one attribute/value pair for the specified record.
 * 
 * @param r a record to be updated
 */
public static void updateRecord(GameRecord r) {
    Log.d(TAG, "Update record called");
    checkDynamoDBClientAvailability();

    DynamoDBMapper mapper = new DynamoDBMapper(ddb);
    try {
        Log.d(TAG, "Updating record");
        mapper.save(r);
        Log.d(TAG, "Updated successfully");
    } catch (AmazonServiceException ex) {
        throw new IllegalStateException("Error updating record", ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
/**
 * Deletes the specified record and all of its attribute/value pairs.
 * 
 * @param r a record to be deleted
 */
public static void deleteRecord(GameRecord r) {
    Log.d(TAG, "Delete record called");
    checkDynamoDBClientAvailability();

    DynamoDBMapper mapper = new DynamoDBMapper(ddb);
    try {
        Log.d(TAG, "Deleting record");
        mapper.delete(r);
        Log.d(TAG, "Deleted successfully");
    } catch (AmazonServiceException ex) {
        throw new IllegalStateException("Error deleting record", ex);
    }
}
项目:aws-sdk-android-samples    文件:DynamoDBManager.java   
public static void deleteUser(UserPreference deleteUserPreference) {

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

        try {
            mapper.delete(deleteUserPreference);

        } catch (AmazonServiceException ex) {
            UserPreferenceDemoActivity.clientManager
                    .wipeCredentialsOnAuthError(ex);
        }
    }
项目:PlatePicks-Android    文件:NoSQLListResult.java   
@Override
public void deleteItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    mapper.delete(result);
}
项目:PlatePicks-Android    文件:NoSQLCommentResult.java   
@Override
public void deleteItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    mapper.delete(result);
}
项目:PlatePicks-Android    文件:NoSQLFoodResult.java   
@Override
public void deleteItem() {
    final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
    mapper.delete(result);
}
项目:PlatePicks-Android    文件:AWSMobileClient.java   
/**
 * Gets the Dynamo DB Object Mapper, which allows accessing DynamoDB tables using annotated
 * data object classes to represent your data using POJOs (Plain Old Java Objects).
 * @return the DynamoDB Object Mapper instance.
 */
public DynamoDBMapper getDynamoDBMapper() {
    return dynamoDBMapper;
}