Monday, 26 September 2011

Google Collections

I'm surprised to see whether it's possible to do the following with Google Collections
The data structure Collection<Person> holds the list or persons and I wanted to find out person with name "X". This "X" can be passed to an API and that function should filter the collections based on that "X".

But I come to know if "X" is fixed, then we can filter the Collection<Person> like

com.google.common.base.Predicate<Person> predicate = new com.google.common.base.Predicate<Person>()
{
         public boolean apply(Person person)
         {
              if(person.getName().equals("Suresh")
                    return true;
             else
                    return false;
         }
}

public Collection<Person> filterPerson()
{
com.google.common.collect.Collections2.filter(personList, predicate);
//personList is Collection<Person>
}

It's very difficult to identify how to filter the persons collection by supplying name as an argument to filterPerson method like filterPerson(String name).

Can anyone know how to do this?

Sunday, 25 September 2011

Testing Java DB classes using In-Memory database.

I was searching in google to test Java classes which is simple JDBC connection to persist objects into MySQL DB tables. I don't want to create real DB to test the classes. I found out a way to test it using In-Memory database in MySQL with some Junit Stuff

For example, if you want to test the DB table "Students". You might have already written a DB Impl class to persist rows into "Students" table. Let's say, StudentsDBImpl.java is the class which needs to be tested. Write a Junit class StudentsDBImplTest.java and inside setup()
1. setup the JDBC connection as same as in old traditional way,
DriverManager.getConnection(URL, USERNAME, PASSWORD)
2. The only difference is the table creation which is shown below,
 create the "Students" table like
"CREATE TABLE Students(Id,Name,Description) Engine=Memory".

Note that the word "Memory" will create this table in memory allow any UPDATES to this table in cache even though the connection created in step 1 is the real one.

3. In teardown(), drop the table like "DROP TABLE Students" and close the connection, if needed.

Hope this is an easiest way to test the DB classes in Junit.