Why should you use Google Guava Libraries in your next project

January 27th, 2015 No comments

We have used google guava libraries heavily in our project and here are some core reasons why you should use guava libraries. Guava is open source library in java written by google. These are used by google so you can pretty much rely on them in your projects.

Why you should use Google Guava

An easy to use , out of the box libraries used by google engineers. Come with a lot of standard features which are missing in java. Since they have been used at google, you can be rest assured that they have thought about performance. I really like the useful functions they have build around collections like having mutable / immutable collections, supporting multikey map, static constructors.

Google calls the guava libraries as  productivity multiplier and I agree with that.

What we have used in Google Guava

Static Constructors

before JDK 7 , we would create a new constructor like

<br /><br />List cityList = new ArrayList();<br /><br />

After jdk7 , this has changed to

<br /><br />List cityList = new ArrayList&lt;&gt;();<br /><br />

Still I do not want to use new word. So in Guava, you can create using static constructor

List cityList = Lists.newArrayList();

Predicate

Determines a true or false value for a given input. More on predicate here Using predicates

Iterables

Look at this example on how you can iterate , and use predicate  to find out what

Set<>{

for (Target target : Iterables.filter(targets,
Predicates.not(new ConflictTargetPredicate()))) {
//do something
}

Multimap

Multimap in guava is similar to a Map, but you can associate multiple values with a single key. If you call put (K,V) twice, with the same key but different values, the multimap contains mappings from the key to both values.  So when you do a get(K),  A Collection<V) is returned.

Collections2

Renamed as Collections2  so that it does not conflict with java collections. Some of the major features in collections2 are

Immutable Collections

Immutable objects have many advantages, including:

  • Safe for use by untrusted libraries.
  • Thread-safe: can be used by many threads with no risk of race conditions.
  • Doesn’t need to support mutation, and can make time and space savings with that assumption. All immutable collection implementations are more memory-efficient than their mutable siblings (analysis)
  • Can be used as a constant, with the expectation that it will remain fixed

Making immutable copies of objects is a good defensive programming technique. Guava provides simple, easy-to-use immutable versions of each standard Collection type, including Guava’s own Collection variations.

JDK also provides collections to be immutable with Collections.unmodifiableXXX methods. Guava mentions that this is not good because

  • unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies
  • unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection
  • inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.

When you don’t expect to modify a collection, or expect a collection to remain constant, it’s a good practice to defensively copy it into an immutable collection.

Sets.newHashSet() : Creates a mutable empty hashSet instance

Lists.newArrayList() : Creates a mutable arraylist

Convert Set to a List

Handy to convert  set to list without declaring a new object.

</pre>
<code>Lists.newArrayList([yourSet])</code>

Functional style programming

</pre>
Collection<?> myNotNullsCollection = filter(myCollection, notNull());

This will remove elements which are null and return a new copy. Remember this will not modify the existing copy. A really handy feature.

Caches

A very useful feature to store data for short term. helps in improve performance at expense of some memory. A use case is let say you have to calculate interest rates for all days in a  year and you need to do that 200 times.

 

How to Use Predicate

November 15th, 2014 No comments

Predicate

Predicate is interface from google guava which determines a true or false value for a given input.

How do you use Predicate ? Below is an example on how you can use predicate to find element from collection based on Id . It is assumed that the object which is a subclass or of type IDObject.


import java.util.Collection;
import java.util.Set;
import com.google.common.base.Predicate;

public class FindByIdPredicate implements
		Predicate<IDObject> {

	private Long entityId;

	public FindByIdPredicate(final Long entityId) {
		this.entityId = entityId;

	}

	@Override
	public boolean apply(final IDObject input) {
		return input.getId().equals(this.entityId);
	}

	/**
	 * @param Collection
	 * @return IdObject if present or null
	 */
	public IDObject getEntity(final Collection<? extends IDObject> collection) {

		for (IDObject idObject : collection) {
			if (this.apply(idObject)) {
				return idObject;
			}
		}
		return null;

	}

	/**
	 * @param Set
	 * @return IdObject if present or null
	 */
	@SuppressWarnings("unchecked")
	public <T> T getEntity(final Set<? extends IDObject> set) {

		for (IDObject idObject : set) {
			if (this.apply(idObject)) {
				return (T) idObject;
			}
		}
		return null;

	}
}

As you can see , it makes is super easy and quick to find an object from collection using predicate which other wise you would have to iteration and check for each object

Installing linux on windows with VMPlayer from VMware

November 7th, 2014 No comments

If you are a programmer and have not yet utilized the power of VMWare, you have missed on something.

Below are step by step by step instructions to get linux (ubuntu flavour) up and running on your machine

1. Down load the VM Player for windows

http://www.vmware.com/download/player/download.html

2. Download the ubuntu image

ubuntu-12.10-desktop-i386.iso

Download ubuntu iso image

 

ubuntu on VMware

Once you upload the image, it will start configuring  your Virtual machine with Ubuntu

Short cuts : ctr + alt +D : minimize all windows

ctrl + T : open terminal window

http://www.howtogeek.com/howto/11287/how-to-run-ubuntu-in-windows-7-with-vmware-player/

Categories: Programming / tutorials Tags:

JVM Magic – What happens behind the scenes

November 7th, 2014 No comments

Found this excellent presentation on slide share. Thought would share with our readers

http://www.slideshare.net/jbaruch/jvm-magic

 

Categories: Programming / tutorials Tags:

Importing csv files with , in text field

June 20th, 2014 No comments

You would have faced this issue sometimes ot other if you are importing csv files and the text field has , in between.
Since it is CSV (comma separated value) while importing, it will break the text values and move to next column.
Definitely that is not what you want.!
What I do is I go and replace , with \,\

Now when you import, it should be all set

Categories: Technology Tags:

New to Git : Adding your code to Git for first time

June 10th, 2014 No comments

If you are new to Git and are looking for very basic stuff to check in yoru code, I found this answer at stackoverflow.com very helpful

http://stackoverflow.com/questions/2866872/how-can-i-upload-fresh-code-at-github

cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master

When I was not cloning , I faced some challenges

Categories: Programming / tutorials Tags:

Nosql with Mongo Db Tutorial

June 9th, 2014 No comments

In the last post we had given a short introduction to nosql

In this post , we will give a small working example with java with mongo db which is a type of nosql database.

Why Mongo DB

  • —It is type of Document database
  • —Written in C++
  • —Development started in 2007
  • —Commercial supported and developed by 10Gen
  • —Supports multiple types of indexing
  • —In built Sharding

What is Sharding ? Sharding is the process of storing data records across multiple machines

sharding

.

Sharding is MongoDB’s approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations.

Development Set Up Mongo

  1. Download and Install Mongo db. http://www.mongodb.org/downloads
  2. Install it on windows or linux.
  3. After installation create a path where you will store data. Don’t forget it is a database so it needs a location where the data can be stored. I created the path in C:\temp2\data\db
  4. Once you have installed go to bin directory and execute this command mongod –dbpath C:\temp2\data\db
  5. For linux users the account that is running mongodb should have write permissions to data/db directory. Run this command sudo chown `id -u` /data/db

Code Example


package demo;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

/**
 * 
 * 
 * @author Vinay
 *
 */
public class HelloMongoDB {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		HelloMongoDB helloMongo = new HelloMongoDB();
		helloMongo.insertData();
		helloMongo.findData();
		helloMongo.updateData();
	}

	/**
	 * An example of find data in mongo db
	 */
	private void findData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country");
		

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");
			DBCursor cursor = db.getCollection("hellomongo").
				find(basic).limit(5);

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

	}

	
	/**
	 * An example of update data in mongo db
	 */
	private void updateData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country")
		
		.append("count", 3)
		.append("states", 
					new BasicDBObject("1" , "MA 3")
						.append("2", "TX 3")
						.append("3", "CA 3"));

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");

			
			BasicDBObject newObject = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)
			.append("states", 
						new BasicDBObject("1" , "MA 1999")
							.append("2", "TX 1999")
							.append("3", "CA 1999"));
			
			db.getCollection("hellomongo").update(basic, newObject);
			

			BasicDBObject newObject2 = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)	;

			
			DBCursor cursor2 = db.getCollection("hellomongo").
					find(newObject2);
				
				while (cursor2.hasNext()) {
					
					System.out.println(cursor2.next());
					
					
				}
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * An example of inserting data in mongo db
	 */
	private void insertData(){
		
		try {
			
			//Connect to Mongo DB
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			
			// by default 3 databases are created local, admin, todo
			System.out.println(" Connected "+mongo.getDatabaseNames().toString());
			
			//Created a new database 
			DB db = mongo.getDB("hellomongo");
			
			Set<String> collections = db.getCollectionNames();
			for(String s : collections){
				System.out.println("Collection: " +s);
			}
			DBCollection items = db.getCollection("hellomongo");

			long timeInsertStart = System.currentTimeMillis();
			for(int i= 0; i<100 ; i++){
			
				items.insert(createObjectsToInsert(i));
			}
			long timeInsertEnd = System.currentTimeMillis();
			System.out.println(" Time to Insert --> "+(timeInsertEnd-timeInsertStart));
			
/*			DBObject myDoc = items.findOne();
			System.out.println(myDoc);
*/

			long timeFetchStart = System.currentTimeMillis();
			DBCursor cursor = items.find();
			long timeFetchEnd = System.currentTimeMillis();
			System.out.println(" Time to fetch --> "+(timeFetchEnd-timeFetchStart));
			while (cursor.hasNext()) {
				//System.out.println(cursor.next());
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
			
		}

	}
	
	private static BasicDBObject createObjectsToInsert(int count){
		
		BasicDBObject basic = new BasicDBObject("name" , "USA")
									.append("type", "country")
									.append("count", count)
									.append("states", 
												new BasicDBObject("1" , "MA "+count)
													.append("2", "TX "+count)
													.append("3", "CA "+count));
		
		return basic;
	}
	
}


pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>javaMongoDBExample</groupId>
  <artifactId>javaMongoDBExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>javaMongoDBExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Mongo Db driver -->
     <dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.12.0</version>
	</dependency>
  </dependencies>
</project>

Get the working project from github

Full Documentation

http://docs.mongodb.org/

Helpul Links

Introduction to NoSQL

June 9th, 2014 No comments

 

What is No SQL

No Sql are called as Next Generation database

Characteristics

  • —Non-relational
  • —Distributed
  • —Open-source
  • —Horizontally scalable
  • —No Predefined Schema

Horizontally scalable : Adding more machines to your resource. Vertical scaling is by adding more power.

NoSQL Database Types

There are 4 types of No Sql database

  • Document databases pair each key with a complex data structure known as a document. Documents can contain many different key-value pairs, or key-array pairs, or even nested documents. Couch DB, Mongo DB
  • Graph stores are used to store information about networks, such as social connections. Graph stores include Neo4J and HyperGraphDB.
  • Key-value stores are the simplest NoSQL databases. Every single item in the database is stored as an attribute name (or “key”), together with its value. Examples of key-value stores are Riak and Voldemort. Some key-value stores, such as Redis, allow each value to have a type, such as “integer”, which adds functionality.
  • Wide-column stores such as Cassandra and HBase are optimized for queries over large datasets, and store columns of data together, instead of rows. Hadoop/ Hbase, Cassnadra, Level DB (from Google), BigTable

Why No SQL ?

  1. Large columns of structured, semi structured data and unstructured data
  2. Efficient scale out architecture
  3. Helps in agile development

Example of data in mysql

{

“_id” : { “$oid” : “536ce8d1c25cf6e89fa7deeb”} ,

“name” : “USA” ,

“type” : “country” ,

“count” : “1” ,

“states” : { “1” : “MA” , “2” : “TX” , “3” : “CA”}

}

No SQL vs SQL

Some major differences between two

SQL Databases No SQL Database
Example Oracle , mysql Mondo DB, CouchDB, Neo4J
Storage Model Rows and tables Key-value. Data stored as single  document in JSON, XML
Schemas Static Dynamic
Scaling Vertical & Horizontal Horizontal
Transactions Yes Certain levels
Data Manipulation Select, Insert , Update Through Object Oriented API’s

Slide presentation at slideshare

Helpful Links

http://nosql-database.org/

http://www.mongodb.com/nosql-explained

http://couchdb.apache.org/

http://www.javacodegeeks.com/2013/03/a-3-step-guide-to-getting-started-with-nosql.html

Categories: Programming / tutorials Tags: