Java tutorial
/** * Copyright (C) 2012 Happy Coding <contact@happy-coding.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.happy_coding.viralo.mongodb; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MongoConnector. * <p/> * Indexes: * <p/> * db.friends.ensureIndex({authenticated_uid:1, uid: 1},{unique:true}); */ public final class MongoConnection { /** * Logger. */ private Logger logger; /** * Mongo handler. */ private Mongo mongo; /** * Mongo DB. */ private DB database; /** * the mongo connection instance for the singleton. */ private static MongoConnection instance; /** * The available collections. */ public enum CollectionName { FRIENDS, FOLLOWERS, TWEETS } /** * returns an instance to the MongoDB database. * * @return the mongo connection */ public static synchronized MongoConnection getInstance() { if (instance == null) { instance = new MongoConnection(); } return instance; } /** * the constructor. */ private MongoConnection() { logger = LoggerFactory.getLogger(getClass()); String mongoServer = System.getProperty("mongoserver"); String mongoPort = System.getProperty("mongoport"); String mongoDatabase = System.getProperty("mongodatabase"); try { /* * load addresses from properties file */ mongo = new Mongo(mongoServer, new Integer(mongoPort)); database = mongo.getDB(mongoDatabase); } catch (Exception e) { e.printStackTrace(); } } /** * return database. * * @return mongo db */ public DB getDatabase() { return database; } /** * Returns the collection with the given name. * * @param collectionName name of the collection. * @return the MongoDB collection. */ public DBCollection getCollection(CollectionName collectionName) { String name = collectionName.toString().toLowerCase(); return database.getCollection(name); } }