com.university.mongodb.courses.m101j.blogapplication.BlogPostDAO.java Source code

Java tutorial

Introduction

Here is the source code for com.university.mongodb.courses.m101j.blogapplication.BlogPostDAO.java

Source

/*
 * Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.university.mongodb.courses.m101j.blogapplication;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class BlogPostDAO {
    DBCollection postsCollection;

    private static final String POST_TITLE = "title";
    private static final String POST_AUTHOR = "author";
    private static final String POST_BODY = "body";
    private static final String POST_PERMALINK = "permalink";
    private static final String POST_COMMENTS = "comments";
    private static final String POST_TAGS = "tags";
    private static final String POST_DATE = "date";

    private static final String COMMENT_AUTHOR = "author";
    private static final String COMMENT_BODY = "body";
    private static final String COMMENT_EMAIL = "email";

    public BlogPostDAO(final DB blogDatabase) {
        postsCollection = blogDatabase.getCollection("posts");
    }

    // Return a single post corresponding to a permalink
    public DBObject findByPermalink(String permalink) {

        DBObject post = null;
        // XXX HW 3.2, Work Here
        post = postsCollection.findOne(new BasicDBObject(POST_PERMALINK, permalink));

        // fix up if a post has no likes
        if (post != null) {
            List<DBObject> comments = (List<DBObject>) post.get(POST_COMMENTS);
            for (DBObject comment : comments) {
                if (!comment.containsField("num_likes")) {
                    comment.put("num_likes", 0);
                }
            }
        }

        return post;
    }

    // Return a list of posts in descending order. Limit determines
    // how many posts are returned.
    public List<DBObject> findByDateDescending(int limit) {

        List<DBObject> posts = null;
        // XXX HW 3.2, Work Here
        // Return a list of DBObjects, each one a post from the posts collection
        DBCursor cursor = postsCollection.find(new BasicDBObject()).limit(limit)
                .sort(new BasicDBObject(POST_DATE, -1));
        posts = new ArrayList<>(cursor.count());

        try {
            posts = cursor.toArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }

        return posts;
    }

    public List<DBObject> findByTagDateDescending(final String tag) {
        List<DBObject> posts;
        BasicDBObject query = new BasicDBObject("tags", tag);
        System.out.println("/tag query: " + query.toString());
        DBCursor cursor = postsCollection.find(query).sort(new BasicDBObject().append("date", -1)).limit(10);
        try {
            posts = cursor.toArray();
        } finally {
            cursor.close();
        }
        return posts;
    }

    public String addPost(String title, String body, List<String> tags, String username) {

        System.out.println("inserting blog entry " + title + " " + body);

        String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _
        permalink = permalink.replaceAll("\\W", ""); // get rid of non
        // alphanumeric
        permalink = permalink.toLowerCase();

        BasicDBObject post = new BasicDBObject();
        // XXX HW 3.2, Work Here
        // Remember that a valid post has the following keys:
        // author, body, permalink, tags, comments, date
        //
        // A few hints:
        // - Don't forget to create an empty list of comments
        // - for the value of the date key, today's datetime is fine.
        // - tags are already in list form that implements suitable interface.
        // - we created the permalink for you above.

        // Build the post object and insert it
        post.append(POST_TITLE, title).append(POST_AUTHOR, username).append(POST_BODY, body)
                .append(POST_PERMALINK, permalink).append(POST_TAGS, tags)
                .append(POST_COMMENTS, Collections.EMPTY_LIST).append(POST_DATE, new Date());

        try {
            postsCollection.insert(post);
        } catch (Exception e) {
            System.err.println("Unable to insert post... " + e);
        }
        return permalink;
    }

    // White space to protect the innocent

    // Append a comment to a blog post
    public void addPostComment(final String name, final String email, final String body, final String permalink) {

        // XXX HW 3.3, Work Here
        // Hints:
        // - email is optional and may come in NULL. Check for that.
        // - best solution uses an update command to the database and a suitable
        // operator to append the comment on to any existing list of comments
        DBObject post = findByPermalink(permalink);

        BasicDBObject comment = new BasicDBObject();
        if (email != null && !email.equals("")) {
            comment.append(COMMENT_EMAIL, email);
        }
        comment.append(COMMENT_AUTHOR, name).append(COMMENT_BODY, body);

        // add comment
        BasicDBObject update = new BasicDBObject().append("$push", new BasicDBObject(POST_COMMENTS, comment));
        try {
            postsCollection.update(post, update);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void likePost(final String permalink, final int ordinal) {
        // XXX Final Exam, Please work here
        // Add code to increment the num_likes for the 'ordinal' comment
        // that was clicked on.
        // provided you use num_likes as your key name, no other changes should
        // be required
        // alternatively, you can use whatever you like but will need to make a
        // couple of other
        // changes to templates and post retrieval code.

        postsCollection.update(new BasicDBObject(POST_PERMALINK, permalink),
                new BasicDBObject("$inc", new BasicDBObject(POST_COMMENTS + "." + ordinal + ".num_likes", 1)));

    }

}