com.dhenton9000.java.mongo.MongoTest.java Source code

Java tutorial

Introduction

Here is the source code for com.dhenton9000.java.mongo.MongoTest.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
    
 https://code.google.com/p/springmvc-sample/source/browse/trunk/spring/GoogleSpringMVCEclipse/test/com/dhenton9000/json/JacksonDemo.java
    
    
    
 */
package com.dhenton9000.java.mongo;

import com.dhenton9000.json.Restaurant;
import com.dhenton9000.json.Review;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import java.util.Set;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.bson.types.ObjectId;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

// or
/**
 *
 * @author dhenton
 */
public class MongoTest {

    public static final Logger LOG = LoggerFactory.getLogger(MongoTest.class);

    public static void main(String[] args) {
        MongoClient mongoClient = null;
        try {
            // mongoClient = new MongoClient("localhost", 27017);
            MongoClientURI mu = new MongoClientURI(
                    "mongodb://mongouser:mongo9000@ds029811.mongolab.com:29811/restaurant_collection");
            mongoClient = new MongoClient(mu);
        } catch (UnknownHostException ex) {
            LOG.error("unknown host error localhost");
            System.exit(25);

        }
        LOG.debug("start ");
        MongoTest mongoTest = new MongoTest();

        try {
            // mongoTest.collectionDemo(mongoClient);
            // mongoTest.writeDemo(mongoClient);
            mongoTest.loadData(mongoClient);
        } catch (Exception ex) {
            LOG.error("could not find file " + ex.getMessage());
            System.exit(34);

        }

        mongoClient.close();

        LOG.debug("end");

    }

    //TODO 
    // add a column in restaurants which is the count of the reviews
    // when you add a review, increment this number and assign it to the
    // review so the review can have a key, which is almost the review array 
    // index as reviews are deleted the next review gets the incremented
    // value stored with the restaurant so it always gets a unique review key
    // in theory would have to deal with contention for the key
    private void loadData(MongoClient mongoClient) throws Exception {
        File f = convertClassPathToFileRef("/restaurants.json");
        ObjectMapper mapper = new ObjectMapper();

        List<Restaurant> restaurants = mapper.readValue(f,
                TypeFactory.collectionType(List.class, Restaurant.class));

        DB db = mongoClient.getDB("restaurant_collection");
        for (Restaurant res : restaurants) {
            BasicDBObject doc = new BasicDBObject("name", res.getName()).append("city", trim(res.getCity()))
                    .append("state", trim(res.getState())).append("version", res.getVersion())
                    .append("zipCode", trim(res.getZipCode()));

            BasicDBList reviewList = new BasicDBList();
            ArrayList<BasicDBObject> reviews = new ArrayList<BasicDBObject>();
            for (Review rev : res.getReviews()) {
                BasicDBObject revObj = new BasicDBObject("starRating", rev.getStarRating());
                revObj.append("reviewListing", trim(rev.getReviewListing()));
                revObj.append("_id", new ObjectId());

                reviewList.add(revObj);
            }
            doc.append("reviews", reviewList);

            //.append("info", new BasicDBObject("x", 203).append("y", 102));
            DBCollection coll = db.getCollection("restaurants");
            coll.insert(doc);

        }

    }

    private String trim(String s) {
        if (s == null) {
            return null;
        }

        return s.trim();
    }

    private void collectionDemo(MongoClient mongoClient) {
        DB db = mongoClient.getDB("local");

        Set<String> collections = db.getCollectionNames();

        for (String t : collections) {
            LOG.debug("--> " + t);
        }
    }

    private void writeDemo(MongoClient mongoClient) {
        DB db = mongoClient.getDB("local");
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));
        DBCollection coll = db.getCollection("alpha");
        coll.insert(doc);
    }

    private File convertClassPathToFileRef(String path) throws FileNotFoundException {

        if (this.getClass().getResource(path) != null) {
            return new File(FileUtils.toFile(getClass().getResource(path)).getAbsolutePath());
        } else {
            String info = String.format("unable to find file at '%s'", path);
            throw new FileNotFoundException(info);
        }
    }
}