Friday, August 5, 2016

Ubuntu Setup

I just moved to Ubuntu from Windows for numerous reasons and as I'm setting up my Ubuntu I have listed few points for future me. Here it goes..

Update Java

Ubuntu 14.04 comes default with Java 7, I need Java 8 for new projects and Java 6 for some legacy projects.

Clean existing JDK

sudo apt-get purge openjdk*
sudo apt-get purge icedtea-* openjdk-*
sudo dpkg --list | grep -i jdk
java -version
javac -version
which javaws


sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
java -version
sudo apt-get install oracle-java6-installer
java -version
sudo apt-get install oracle-java8-set-default
java -version

Update GIT

sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git
git --version

Eclipse - Install Neon

Brightness Issue


manual install - unzip tar.gz and set PATH


manual install and set PATH


Please make sure about version, keep consistent version as a suffix.

Update Kernel (for dual screen support)

minimize app (click same button to minimize)

Friday, February 19, 2016

Serlizing JSON polymorphically when type field is in parent JSON using Jackson

Today, I came across a json parsing situation where the sub-type field is outside the type json. Genrally we seen a situation like this

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
class Animal{}

class Dog extends Animal{}

class Cat extends Animal{}

and it de-serialize to json like this:

    "@class" : "x.y.z.Cat", ...

In my project I need to parse json like this
"status": "OK",
"messageName": "x.y.z.Success",
"messagePayload": {
"foo": "cd3a5697",
"bar": 224
"status": "ERROR",
"messageName": "x.y.z.Error",
"messagePayload": {
"errorInstanceId": "b292b864",
"errorDetailedMessage": "Invalid UUID string (Length mismatch)"

Now only thing that differs here is the messagePayload and the property that makes it different is either messageName or status. I googled this kind of json serializing problem but didn't get the expected results. All results gave example shown in above Animal class.

How I solved it - well its very simple trick that strike me next day. I was trying the make @JsonTypeInfo on messagePayload, which is not working as sub-type field is outside the payload json. When I used the @JsonTypeInfo on whole message it works:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.EXTERNAL_PROPERTY, property = "messageName")
    @JsonSubTypes.Type(value = Success.class, name = "x.y.z.Success"),
    @JsonSubTypes.Type(value = Error.class, name = "x.y.z.Error")})
public abstract class Response {
    private String status;
    public abstract Payload getMessagePayload();

public abstract class Payload {}

public class SuccessPayload extends Payload {
    private String foo;
    private Long bar;

public class ErrorPayload extends Payload {
    private String errorCode;
    private String errorInstanceId;
    private String errorDetailedMessage;

Now using this I get the correct serialized payload depending upon the message class am getting in json. hope this helps.

Sunday, February 7, 2016

My first C program: now and then

I was searching for some documents in gmail and found a mail that I sent to company X for their hiring process. It was a c program for searching word in file. I do not know how much time I have taken for it but it was basic search utility function.

The point of this blog is not discuss that program but to discuss how time makes you better programmer.

Here are the few things I would like to share myself -

  • It takes some learning to write clean code. 
  • Reed books like clean code.
  • You need mentor to learn from his experience.
  • Get a github account and see how experts are writing code.
This is not the complete list, there are many things you will acquire over a period of time which make you better programmer.

PS: If you are wondering how that program used to look like, then see this repo.

Saturday, February 22, 2014

Again writing fast & maintainable integration tests using in-memory db, liquibase, gradle and spring mvc test

This blog is improvisation to previously blogged testing effectively with database blog. In this blog we will remove the jetty setup and instead use Spring MVC Test framework which kind of simulate the request/response for your controllers via Spring Web Application context (no deployment, to http client tests) Here, we will write Spring MVC tests and -
  • Create the HSQLDB in-memory instance (instantiating datasource instance)
  • and run Liquibase scripts against them. (using Spring Lqiuibase bean)
1. Setup your web-service.

Write usual Controller->Service->Repository layer.

public class MapAnomalyReportEndpoint {

    private MapAnomalyReportService reportService;

    @RequestMapping(method = RequestMethod.GET)
    public Collection getReports() {
        return reportService.getReports();

2. Create Spring Java Config (No XML)

Configure the controllers.

@ComponentScan(basePackages = "com.rohankar.playground")
public class WebConfig {

    public InternalResourceViewResolver viewResolver() {
        final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;

Configure the data source. I'm taking JDBC parameters from context, you can very well read them from .properties or system prop.
public class JdbcConfig {

    private Environment env;

    @Bean(destroyMethod = "close")
    public DataSource getDataSource() throws NamingException {
        final Context ctx = new InitialContext();
        final BasicDataSource ds = new BasicDataSource();
        return ds;

    public JdbcTemplate getJdbcTemplate() throws NamingException {
        return new JdbcTemplate(getDataSource());

3. Create Spring Java Config for tests

This config is purely for running liquibase scripts on datasource.

public class TestConfig {

    private DataSource dataSource;

    public SpringLiquibase getLiquibase() {
        final SpringLiquibase liquibase = new SpringLiquibase();
        return liquibase;
4. Write integration test In setUp method, we're populating a context object with in-memory db parameters.
@ContextConfiguration(classes = {TestConfig.class})
public class MapAnomalyReportEndpointIntTest {

    private WebApplicationContext context;

    public static void setup() throws IllegalStateException, NamingException {
        final SimpleNamingContextBuilder context = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
        context.bind("java:comp/env/report/db/driverClass", "org.hsqldb.jdbc.JDBCDriver");
        context.bind("java:comp/env/report/db/url", "jdbc:hsqldb:mem:reportdb;shutdown=false");
        context.bind("java:comp/env/report/db/user", "sa");
        context.bind("java:comp/env/report/db/password", "");
        context.bind("java:comp/env/report/db/schema", "report");

    public void testGetReports() throws Exception {
        MockMvcBuilders.webAppContextSetup(context).build() //
            .perform(get("/reports")) //
            .andDo(print()) //
            .andExpect(status().isOk()) //
            .andExpect(content().contentType("application/json;charset=UTF-8")) //
            .andExpect(jsonPath("$[0].id").value(1)); // TODO assert other values
5. Run the tests, this wont require you to configure jetty, deploy the ws and run test against them!

You can clone the whole project from here.

PS: The given project is built using Gradle as I want to learn it.

Thursday, June 13, 2013

Writing fast & maintainable integration tests using test double, in-memory db, jetty, maven and spring

Writing an integration test which test end to end flow of your application can become cumbersome activity if you really hitting real db and services. The best way to mock, test double your external dependencies and thus speed up your test execution.

I created a dummy map-service project which demonstrate about writing maintainable and speedy integration tests using mocking, test double pattern, spring and automating them using maven and jetty. You can find the project at my github location:

Here are some code snippets explaining the important steps in configuring your project.

  1. POM - Configure jetty for deploying your app and running tests against it.
  2. .
  3. - In order to test double database and service calls
  4. public class MockBeanInjector implements BeanPostProcessor {
        private final static Logger LOG = LoggerFactory.getLogger(MockBeanInjector.class);
        public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
            return bean;
        public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
            if (bean instanceof DataSource) {
      "Mocking DataSource instance: " + bean);
                final EmbeddedDatabaseBuilder embeddedDatabaseBuilder = new EmbeddedDatabaseBuilder();
                final EmbeddedDatabase embeddedDatabase =
                return embeddedDatabase;
                // else
                // return new ClassPathXmlApplicationContext("applicationContext-test.xml").getBean("dataSource");
            if (bean instanceof AuthserverGateway) {
      "Mocking AuthserverGateway instance: " + bean);
                final AuthserverGateway mockAsGateway = mock(AuthserverGateway.class);
                final ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT);
                return mockAsGateway;
            } else {
                return bean;
  5. Finally tests
  6. public class PoiWsRestClientTest {
        public void should_create_poi() {
            // given
            final Poi poi = new Poi();
            poi.setName("Pizza Center");
            poi.setLatitude(new BigDecimal("23.23212"));
            poi.setLongitude(new BigDecimal("34.231312"));
            // when
            final URI location = new RestTemplate().postForLocation("http://localhost:8080/maps-service/pois", poi);
            // then
            assertThat(location.getPath(), endsWith("/pois/102"));
        public void should_read_poi() {
            // when
            final Poi poi = new RestTemplate().getForObject("http://localhost:8080/maps-service/pois/100", Poi.class);
            // then
            assertThat(poi.getId(), is("100"));
        public void should_delete_poi() {
            // given
            final HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "12345");
            final HttpEntity httpEntity = new HttpEntity(headers);
            // when
            final ResponseEntity response =
                new RestTemplate().exchange("http://localhost:8080/maps-service/pois/101", HttpMethod.DELETE, httpEntity,
            // then
            assertThat(response.getStatusCode(), is(HttpStatus.NO_CONTENT));

Wednesday, June 12, 2013

Code Kata - good way to learn new language

Recently, I started exploring and learning Scala and functional programming. So far, it is a good experience and as a programmer gives you new "functional" thought process about problem.

The best way to learn Scala or any language for that matter is to start writing Katas in that language. Coding Kata, if you're not familiar with it then must visit In short, coding kata is programming practice mostly done in TDD way, which makes you better programmer.

BTW, If you're wondering where are my katas in Scala, you can find them here:

Monday, April 8, 2013

A Day of Innovation: TomTom Pune DevDay 2013

Friday (6 April 2013) was a day of innovation and engineering, fun and quiz, it was a first TomTom Pune Engineering DevDay.

Key Highlights of the day:

  • Kick started with U2 public concert video, a good way to wakeup people.
  • Many speaker talked about how we can extend and experiment with our new generation map editing tool Cartopia
  • I talked about function programming and how we can achieve it using Scala.
  • There were coffee breaks with testers which showcase some really cool technologies like puppet, test automation using FlexPilot and risk based testing's.
  • Day end with exciting quiz, prize distribution and beer :)

If you want to be a part of next TomTom devday, join us