Spring Data MongoDB Simple Find example

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for for new datastores while retaining store-specific features and capabilities. See more about SpringData

In this example we will see how to save and retrieve Customer bean using SpringData and Mongodb.

Prerequisites: Mongodb should be up and running

1. Create a Maven Project
Create a Maven project and add below dependencies

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.0.0.M2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>
 

2. Create Customer entity

package com.vinod.model;

public class Customer {
public String name;
public String address;

public Customer(String name, String address) {
super();
this.name = name;
this.address = address;
}
public Customer() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [name=" + name + ", address=" + address + "]";
}
}
 

3. Spring configuration xml

Place this file in to src/main/resources folder

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
<!-- Default bean name is 'mongo' -->
<mongo:mongo host="localhost" port="27017" />
<bean id="customermongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="customerdb" />
<constructor-arg name="defaultCollectionName" value="customerCollection" />
</bean>
<!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
<context:annotation-config />
</beans>

4. Create a Main class to save Customer details using spring data

package com.vinod.service;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;

import com.vinod.model.Customer;

public class SpringDataFindExample {
    public static void main(String args[]) {
        ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("customermongoTemplate");
        Customer customer = new Customer("Vinod", "Bangalore");
        mongoOperation.save("customerDetails", customer);

        // findone
        Customer savedCustomer = mongoOperation.findOne("customerDetails",
                new Query(Criteria.where("name").is("Vinod")), Customer.class);
        System.out.println("savedCustomer : " + savedCustomer);

        // findall

        List<Customer> savedCustomerList = mongoOperation.find("customerDetails",
                new Query(Criteria.where("name").is("Vinod")), Customer.class);
        System.out.println("savedCustomerlist : " + savedCustomerList);

    }
}
 

5. Output

savedCustomer : Customer [name=Vinod, address=Bangalore]

savedCustomerlist : [Customer [name=Vinod, address=Bangalore], Customer [name=Vinod, address=Bangalore], Customer [name=Vinod, address=Bangalore]]

6. Done!! Download example

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-spring-data

Spring Data MongoDB Simple Save Example

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for for new datastores while retaining store-specific features and capabilities. See more about SpringData

In this example we will see how to save and retrieve Customer bean using SpringData and Mongodb.

Prerequisites: Mongodb should be up and running

1. Create a Maven Project
Create a Maven project and add below dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
        <!-- mongodb java driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.0.0.M2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestone</id>
            <name>Spring Maven MILESTONE Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
 

2. Create Customer entity

package com.vinod.model;

public class Customer {
    public String name;
    public String address;

    public Customer(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
    public Customer() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }
}
 
 

3. Spring configuration xml

Place this file in to src/main/resources folder

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017" />
    <bean id="customermongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="customerdb" />
        <constructor-arg name="defaultCollectionName" value="customerCollection" />
    </bean>
    <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
    <context:annotation-config />
</beans>

4. Create a Main class to save Customer details using spring data

package com.vinod.service;

import java.util.Iterator;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;

import com.vinod.model.Customer;

public class SpringDataInsert {
    public static void main(String args[]) {
        ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("customermongoTemplate");
        Customer customer = new Customer("Vinod", "Bangalore");
        mongoOperation.save("customerDetails", customer);
        // List
        List<Customer> listCustomer = mongoOperation.getCollection("customerDetails", Customer.class);
        Iterator<Customer> iterator = listCustomer.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
 

5. Output

Customer [name=Vinod, address=Bangalore]

6. Done!! Download example

https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-spring-data

Java Database Connection Pooling example

Creating a connection to the database server is expensive. It is even more expensive if the server is located on another machine. Connection pool contains a number of open database connections which we can configure as minimum and maximum. There are lot of APIs available to create connection pooling also we can depend application server if it supports this feature, generally all the applications servers support connection pools. It creates the connection pool on behalf of you when it starts.

Here is one simple example which creates a connection pool maximum of size 5.

Prerequisites- mysql-connector-java-5.1.5-bin.jar should be there in the project class path.

Example (DatabaseConnectionPool.java)

package com.pretech;
 
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
 
public class DatabaseConnectionPool {
 
    private String driverName;
    private String password;
    private String url;
    private String user;
    private Driver driver;
    private Vector freeConnections;
    private int maxConn;
    private int count;
 
    /**
     * DatabaseConnectionPool constructor.
     *
     * @param drivername
     * @param conUrl
     * @param conuser
     * @param conpassword
     * @throws SQLException
     */

    public DatabaseConnectionPool(String drivername, String conUrl,
            String conuser, String conpassword) throws SQLException {
        freeConnections = new Vector();
        driverName = drivername;
        url = conUrl;
        user = conuser;
        password = conpassword;
        try {
            driver = (Driver) Class.forName(driverName).newInstance();
            DriverManager.registerDriver(driver);
        } catch (Exception _ex) {
            new SQLException();
        }
        count = 0;
        maxConn = 5;
    }
 
    /**
     * Method to destroy all connections.
     */

    public void destroy() {
        closeAll();
        try {
            DriverManager.deregisterDriver(driver);
            return;
        } catch (Exception e) {
            e.printStackTrace();
 
            return;
        }
    }
 
    /**
     * Method to add free connections in to pool.
     *
     * @param connection
     */

    public synchronized void freeConnection(Connection connection) {
        freeConnections.addElement(connection);
        count--;
        notifyAll();
    }
 
    /**
     * Method to get connections.
     *
     * @return Connection
     */

    public synchronized Connection getConnection() {
        Connection connection = null;
        if (freeConnections.size() > 0) {
            connection = (Connection) freeConnections.elementAt(0);
            freeConnections.removeElementAt(0);
            try {
                if (connection.isClosed()) {
                    connection = getConnection();
                }
            } catch (Exception e) {
                print(e.getMessage());
 
                connection = getConnection();
            }
            return connection;
        }
        if (count < maxConn) {
            connection = newConnection();
            print("NEW CONNECTION CREATED");
 
        }
        if (connection != null) {
            count++;
        }
        return connection;
    }
 
    /**
     * Method to close all resources
     */

    private synchronized void closeAll() {
        for (Enumeration enumeration = freeConnections.elements(); enumeration
                .hasMoreElements();) {
            Connection connection = (Connection) enumeration.nextElement();
            try {
                connection.close();
            } catch (Exception e) {
                print(e.getMessage());
            }
        }
        freeConnections.removeAllElements();
    }
 
    /**
     * Method to create new connection object.
     *
     * @return Connection.
     */

    private Connection newConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            print(e.getMessage());
            return null;
        }
        return connection;
    }
 
    private void print(String print) {
        System.out.println(print);
    }
}

Test Connection Pool(ConnectionPoolTest.java)

The above connection pool class we set the maximum number of connections as 5, in this test class we will create first 5 connections and release one connection and creates 6th connection ..see below example

package com.pretech;
 
import java.sql.Connection;
import java.sql.ResultSet;
 
public class ConnectionPoolTest {
    public static void main(String[] argv) {
        String dburl = "jdbc:mysql://localhost:3306/pretech";
        String driver = "com.mysql.jdbc.Driver";
        String sUser = "root";
        String sPwd = "root";
        java.sql.PreparedStatement pstmt;
        String select_sql = "select name,address from customer";
        ResultSet rs;
 
        DatabaseConnectionPool dbConnectionPool;
        // create database connection pool
        try {
            dbConnectionPool = new DatabaseConnectionPool(driver, dburl, sUser,
                    sPwd);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Connection c1, c2,c3,c4,c5,c6;
        c1 = dbConnectionPool.getConnection();
        c2 = dbConnectionPool.getConnection();
        c3 = dbConnectionPool.getConnection();
        c5 = dbConnectionPool.getConnection();
        c5 = dbConnectionPool.getConnection();
        dbConnectionPool.freeConnection(c5);
        c6 = dbConnectionPool.getConnection();
 
        try {
            pstmt = c6.prepareStatement(select_sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println("output value =>" + rs.getString(1) + ""
                        + rs.getString(2));
            }
            rs.close();
            pstmt.close();
            c1.setAutoCommit(true);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        // return first connection to the pool
        dbConnectionPool.freeConnection(c1);
        // release resources
        dbConnectionPool.destroy();
 
    }
 
}

Output

NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
NEW CONNECTION CREATED
output value =>Vinod  Bangalore
output value =>Santhosh  Kannur
output value =>Shiva  Mysore

 

How to configure SSL/HTTPS in Tomcat ?

Follow below simple two steps in enable SSL in your tomcat server. Generally to enable SSL we required certificate, in this example we are using our own key.  We can use Java keytool.exe  (Java\jdk1.7.0_06\bin\keytool.exe) to generate certificate.

Use below command to generate keys

keytool -genkey -alias pretech -keyalg RSA -keystore c:\vinod

Option details:

-genkey= Generate keys

-alias= Giving unique alias for keystore

-keyalg= To define algorithm (eg RSA_

-keystore=Location to store certificate

Step1 - Generate Key

image

Step 2- Configure Tomcat Server.xml

Replace connector details in your tomcat\conf\server.xml

	<Connector port="8080" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
         keystoreFile="c:\vinod"
         keystorePass="xxxxxx" />

Note: Replace kestorePass  xxxxxx with your password which is used during key generation.

Start tomcat


Start your tomcat server and check the admin console with https. We can see SSL is enabled.


image

How to get Java Thread State

Release 5.0 introduced the Thread.getState() method. When called on a thread, one of the following Thread.State values is returned:
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED

Example

package com.pretech;
public class ThreadState {
	public static void main(String[] args) {
		Threadone t1 = new Threadone();
		System.out.println(t1.getState());
		t1.start();
		System.out.println(t1.getState());
	}
}
class Threadone extends Thread {
	public void run() {
		System.out.println("HelloWorld");
	}
}

Output



NEW
RUNNABLE
HelloWorld
TERMINATED


Java OutOfMemoryError Common Examples

One common issue that many developers have to address is that of applications that terminate with java. lang. OutOfMemoryError. That error is thrown when there is insufficient space to allocate an object.

Java heap space

This indicates that an object could not be allocated in the heap. The issue may be just a configuration problem. You could get this error, for example, if the maximum heap size specified by the –Xmx command line option is insufficient for the application.

PermGen space

This indicates that the permanent generation is full. If an application loads a large number of classes, then the permanent generation may need to be increased. You can do so by specifying the command line option –XX:MaxPermSize=n, where n specifies the size.

Requested array size exceeds VM limit

This indicates that the application attempted to allocate an array that is larger than the heap size. For example, if an application tries to allocate an array of 512MB but the maximum heap size is 256MB, then this error will be thrown.

How to get System Environment details in java?

Example

package com.pretech;
import java.util.Map;
import java.util.Map.Entry;
public class SystemEnvExample {
	public static void main(String[] args) {
		Map<String, String> hMap = System.getenv();
        for (Entry<String, String> entry : hMap.entrySet()) {
            System.out.println(entry.getKey() + "  = "
                         + entry.getValue());
     }
	}
}

Output



USERPROFILE  = C:\Users\vinod
ProgramData  = C:\ProgramData
PATHEXT  = .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
JAVA_HOME  = C:\Program Files\Java\jdk1.7.0_06\
ProgramFiles(x86)  = C:\Program Files (x86)
TEMP  = C:\Users\vinod\AppData\Local\Temp
SystemDrive  = C:
MOZ_PLUGIN_PATH  = C:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\
ProgramFiles  = C:\Program Files
Path  = C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Broadcom\Broadcom 802.11\Driver;C:\Program Files\Java\jdk1.7.0_06\bin;D:\bOnPC_Development\apache-maven-3.0.1\bin;C:\Program Files\Internet Explorer;
HOMEDRIVE  = C:
PROCESSOR_REVISION  = 2505
USERDOMAIN  = vinod-PC
ALLUSERSPROFILE  = C:\ProgramData
ProgramW6432  = C:\Program Files
PROCESSOR_IDENTIFIER  = Intel64 Family 6 Model 37 Stepping 5, GenuineIntel
SESSIONNAME  = Console
TMP  = C:\Users\vinod\AppData\Local\Temp
CommonProgramFiles  = C:\Program Files\Common Files
=::  = ::\
LOGONSERVER  = \\VINOD-PC
PROCESSOR_ARCHITECTURE  = AMD64
FP_NO_HOST_CHECK  = NO
OS  = Windows_NT
HOMEPATH  = \Users\vinod
PROCESSOR_LEVEL  = 6
CommonProgramW6432  = C:\Program Files\Common Files
classpath  = C:\Program Files\Java\jdk1.7.0_06\lib;
LOCALAPPDATA  = C:\Users\vinod\AppData\Local
COMPUTERNAME  = VINOD-PC
windir  = C:\Windows
SystemRoot  = C:\Windows
NUMBER_OF_PROCESSORS  = 4
USERNAME  = vinod
PUBLIC  = C:\Users\Public
PSModulePath  = C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
CommonProgramFiles(x86)  = C:\Program Files (x86)\Common Files
ComSpec  = C:\Windows\system32\cmd.exe
APPDATA  = C:\Users\vinod\AppData\Roaming


Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts