Tuesday, December 18, 2012

Getting Started w/ Mongo DB in Linux using Java


The url below contains the information for installing mongo. The steps outline configuring apt to install the package. Following these steps will get mongo running and the ability to do CRUD via command line. You have to get a driver for the language of choice in order to do CRUD via code.


Installation Steps:

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/


Command Line Interface

Mongo’s commands and the like can be found here. The command line interface is pretty straight forward:
http://docs.mongodb.org/manual/crud/


Starting mongo:

sudo service mongodb start


Stopping mongo:

sudo service mongodb stop


Restarting mongo:

sudo service mongodb restart

Connecting to mongo:

mogo

Java Driver

You will need a driver to access MongoDB programmatically. Drivers exist for most languages. The tutorial on Mongo's website has some of this information. Note that the tutorial looks dated. It looks to be using objects that no longer exist in the current version of the driver. This adds confusion so best to avoid the tutorial to get started. I have included some brief code to setup a connection and do some simple CRUD in Mongo. Note that it is not production ready.

http://www.mongodb.org/display/DOCS/Java+Language+Center#JavaLanguageCenter-Basics


Adding the Java Driver with Maven

Just add the dependency below to your Maven file. Maven will take care of getting the jar in. This url will tell you the latest version Maven supports: http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver


<dependency>
     <groupId>org.mongodb</groupId>
     <artifactId>mongo-java-driver</artifactId>
     <version>2.9.1</version>
</dependency>


Code Example


import com.mongodb.*;  
 public class MongoUserDataAdapter {  
   private Mongo mongo = null;  
   private DB db = null;  
   private String serverAddress;  
   private int port;  
   private String databaseName;  
   private String collectionName;  
   /***  
   * this should be handled via config.  
   */  
   public MongoUserDataAdapter(){  
     this.serverAddress = "localhost";  
     this.port = 27017;  
     this.databaseName = "sebsTestDb";  
     this.collectionName = "users";  
   }  
   /***  
    * inserts the user into the collection in mongodb.  
    * @param user  
    * @return a user.  
    */  
   public User createUser(User user) {  
     User result = null;  
     try{  
       // mongo will create this if it doesn't exist.  
       DBCollection collection = db.getCollection(this.collectionName);  
       BasicDBObject document = this.createBasicUserDBObject(user);  
       WriteResult writeResult = collection.insert(WriteConcern.SAFE, document);  
       String error = writeResult.getError();  
       if(error.isEmpty()){  
         result = user;  
       }  
       // ToDo: have mongo set the Id.  
     }  
     catch (Exception ex){  
                //ToDo: log this  
     }  
     return result;  
   }  
   /***  
    * creates a DB document representation of user.  
    * @param user  
    * @return  
    */  
   private BasicDBObject createBasicUserDBObject(User user){  
     BasicDBObject document = new BasicDBObject();  
     document.put("id", user.getId());  
     document.put("email", user.getEmailAddress());  
     document.put("password", user.getPassword());  
     document.put("firstName", user.getFirstName());  
     document.put("lastName", user.getLastName());  
     return document;  
   }  
   public User getUser(String email) {  
     DBObject result = null;  
     DBCursor cursor = null;  
     try{  
       DBCollection collection = db.getCollection(this.collectionName);  
       BasicDBObject query = new BasicDBObject("email", email);  
       cursor = collection.find(query);  
       while(cursor.hasNext()){  
         result = cursor.next();  
       }  
     }  
     catch(Exception ex){  
          // todo: log this  
     }  
     finally{  
       cursor.close();  
     }  
     User user = null;  
     if(result != null){  
       Long id = (Long)result.get("id");  
       String address = (String)result.get("email");  
       String password = (String)result.get("password");  
       String firstName = (String)result.get("firstName");  
       String lastName = (String)result.get("lastName");  
       user = new User(id, address, password, firstName, lastName);  
     }  
     return user;  
   }  
   /***  
    * Connects to the monogdb  
    * @return false if some kind of exception.  
    */  
   public boolean connect(){  
     // this needs to be refactored out into properties where appropriate.  
     boolean success = true;  
     try{  
       // this opens the connection  
       this.mongo = new Mongo(this.serverAddress, this.port);  
       // mongo will create the database if it doesn't exist.  
       this.db = mongo.getDB(this.databaseName);  
     }  
     catch(Exception ex){  
       //ToDo: Log  
     }  
     return success;  
   }  
   public boolean close(){  
     boolean success = true;  
     try{  
       if(this.mongo != null){  
         this.mongo.close();  
       }  
     }  
     catch(Exception ex){  
       // ToDo: log  
       success = false;  
     }  
     return success;  
   }  
 }



References


http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/


http://www.mongodb.org/display/DOCS/Java+Language+Center#JavaLanguageCenter-Basics


http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver

http://docs.mongodb.org/manual/crud/

Sunday, October 28, 2012

Installing Maven 3 on Ubuntu 12.04

Prerequisites:
Must already have a jdk installed. In my case: java-7-oracle.

Open a terminal and execute the commands below.

  1. wget http://apache.petsads.us/maven/maven-3/3.0.4/binaries/apache-maven-3.0.4-bin.tar.gz
  2. tar -zxf apache-maven-3.0.4-bin.tar.gz  
  3. sudo cp -R apache-maven-3.0.4 /usr/local
  4. open the ~/.profile and add the following lines:
    1. M2_HOME="/usr/local/apache-maven-3.0.4"
    2. M2="$M2_HOME/bin"
    3. PATH="$M2:$PATH"
  5. Save the file and re-log to load the new environment variables.
  6. Make sure that java is in your path. This should have been done while setting up a jdk.
  7. mvn –version  to verify maven.

I've recently found that depending upon your ubuntu flavor, that the .profile file may not be used. Instead the .bashrc file may get loaded. I've seen this in Lubuntu (LXDE) and Bodhi (Enlightenment). The process is the same, just add the files to the ~/.bashrc instead.

Download Mirrors:
http://www.apache.org/dyn/closer.cgi/maven/maven-3/3.0.4/binaries/apache-maven-3.0.4-bin.tar.gz

Sources:
http://java.dzone.com/articles/installing-maven-304-ubuntu

https://help.ubuntu.com/community/EnvironmentVariables

http://maven.apache.org/download.htmlhttp://maven.apache.org/download.html

Sunday, October 14, 2012

Installing Netbeans on Ubuntu 12.04


The catch with doing anything in Java on Ubuntu is always the same - Ubuntu doesn't ship with Oracle’s Java installed. Instead, Ubuntu ships with Open JDK installed. Open JDK is an open source version of Java.

Some may argue that you can develop with and probably run Netbeans with Open JDK. That may be the case, for me I find the Oracle Java to be more trustworthy for production environment so will be using the Oracle bits. This is simply a matter of opinion.

Installing Netbeans on Ubuntu then requires two steps - installing the latest Oracle JDK and then installing Netbeans.

Installing Oracle JDK


Apt-get needs to be configured to point to a ppa that will take care of the heavy lifting. Note that I am running the 32 bit version. The 64 bit version is likely different. Open a terminal and execute the following:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer


Installing Netbeans


  1. Grab the version of Netbeans you are looking for here: http://netbeans.org/downloads/
  2. Use the File Manager to navigate to the Downloads folder and locate the *.sh file.
  3. Make the file executable (you can also do this with chmod +x):
    1. Right-click the file and open Properties.
    2. Click the Permissions tab and check “Allow executing file as program.”
    3. Apply
  4. Rename the file to something easier to manage (i.e. netbeans7.sh)
  5. Open a Terminal and cd to Downloads.
  6. run ./netbeans.sh
  7. Follow the on-screen prompts.
  8. Note that Netbeans will put a shortcut on the Desktop for you.




Sources:

http://www.ubuntugeek.com/how-to-install-oracle-java-7-in-ubuntu-12-04.html