Kotlin exercise 1: Connect to MongoDB -part 2-

beach-beautiful-beautiful-beach_1600x1200_93247

In the first part of this exercise we have seen how connect to a MongoDb with Java. Now that is clear how the connection can be performed, we can try to do the same with Kotlin.
Ok, no waste other time, start coding:


import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.MongoException
import java.net.UnknownHostException
import java.util.*

/**
 * Created by Claudio on 01/05/16.
 * This is a main to test mongoDB connection in kotlin
 */

fun main(args: Array<String>) {

    try
    {
        val mongo = MongoClient("localhost", 27017)

        val db = mongo.getDB("testDB")

        val table = db.getCollection("person")

        //Reflection example
        val person = Person("Jon","Doe",20);

        val data = person.javaClass;


        //Insert document
        val document = BasicDBObject()
        document.put("name", "mkyong")
        document.put("age", 30)
        document.put("createdDate", Date())
        table.insert(document)

        /**** Find and display ****/
        val searchQuery = BasicDBObject();
        searchQuery.put("name", "mkyong");

        val cursor = table.find(searchQuery);

        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }
    catch (e: UnknownHostException) {
        e.printStackTrace ( );
    } catch (e: MongoException) {
        e.printStackTrace();
}

}
  

Sorry but the kotlin code isn’t highlighted

How we see the code is similar with Java example and the output is equal:

Schermata 2016-05-04 alle 21.10.01

This code can be converted from Java code with the intellij IDE function called: “Convert java code to kotlin code”. This can be reached from the search tool or vith copy and paste of java code to kotlin file:

Cattura

For exercise the “Main.kt” code is was written from scratch.

In this little exercice I learned how connect to MongoDb and how code something more difficult to “hello world” in Kotlin.

A little step for mankind, a big step for a developer!

featured

Kotlin exercise 1: Connect to MongoDB -part 1-

3_maldive

After the firts posts on Kotlin, i want to creating something more difficult. And i chose to try a database connection in Kotlin.

In this exercise i chose to connect my little application to a Mongo database. This choice is driven by a book that i started to read in  these days: “MongoDb in action”, because i want to know more about this type of database. So i decided to try to use both new things: kotlin and MongoDB.

This exercise is organized in this way: first part is a java test connection and operations with MongoDB then the same operations are written in Kotlin.

Ok, let’s start with code:

Firt of all create the instance of mongodb client and create te DB:

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created by Claudio on 30/04/16.
 */
public class Main {

    public static void main(String[] args) {

        try {
            MongoClient mongo = new MongoClient( "localhost" , 27017 );

            DB db = mongo.getDB("testDB");

            DBCollection table;
            table = db.getCollection ("clienti");

            //Insert document
            BasicDBObject document = new BasicDBObject();
            document.put("name", "mkyong");
            document.put("age", 30);
            document.put ("createdDate", new Date ( ));
            table.insert(document);

            /**** Find and display ****/
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("name", "mkyong");

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }

        } catch (UnknownHostException e) {
            e.printStackTrace ( );
        } catch (MongoException e) {
            e.printStackTrace();
        }
    }

}

this is a little example to show how to:

  • connect to MongoDB (line 14)
  • create or get database (lines 16-19)
  • create a document (lines 22-26)
  • get insered data (lines 29-32)
  • show on standart output the datas (34-35)

The result of running this code is:

Schermata 2016-05-04 alle 21.09.20

The next part is focused on the Kotlin equivalent code.

 

Singleton pattern java example

I found singleton design pattern a useful pattern for my applications. But, what is this design pattern?

In this pattern a single class is responsible to create an object, and you are sure that only single object is created. In this manner, this class provides a way to access its only object which can be accessed directly. No instatiate is needed.

What are the features of this type of class:

  • private costructor
  • Static instance of itself
  • Static method to get own static instance

Now, create a Singleton Class:

SingleObject.java

public class Singleton {
    private static final Singleton instance = new Singleton();
    public static Singleton getInstance() { 
       return instance; 
    }
    public void showMessage(){
       System.out.println("Hello World!");
    }
}

Now use this class into a snippet:

SingletonPatternDemo.java

public class SingletonPatternDemo {
 public static void main(String[] args) {

   //illegal construct
   //Compile Time Error: The constructor SingleObject() is not visible
   //SingleObject object = new SingleObject();

   //Get the only object available
   Singleton object = Singleton.getInstance();

   //show the message
   object.showMessage();
 }

And now verify this code!