Custom JSON Deserialization with Jackson

We consume rest api as a json format and then unmarshal it to a POJO. Jackson’s “just works” out of the box and we really don’t do anything in most cases. But sometime we need custom dserializer to fulfill our custom needs and this tutorial will guide you through the process of creating your own custom dserializer.

Let’s say we have following entities.

public class User {
private Long id;
private String name;
private String email;

public Long getId() {
return id;

public User setId(Long id) { = id;
return this;

public String getName() {
return name;

public User setName(String name) { = name;
return this;

public String getEmail() {
return email;

public User setEmail(String email) { = email;
return this;

public String toString() {
final StringBuffer sb = new StringBuffer("User{");
sb.append(", name='").append(name).append('\'');
sb.append(", email='").append(email).append('\'');
return sb.toString();


public class Program {
private Long id;
private String name;
private User createdBy;
private String contents;

public Program(Long id, String name, String contents, User createdBy) { = id; = name;
this.contents = contents;
this.createdBy = createdBy;

public Program() {

public Long getId() {
return id;

public Program setId(Long id) { = id;
return this;

public String getName() {
return name;

public Program setName(String name) { = name;
return this;

public User getCreatedBy() {
return createdBy;

public Program setCreatedBy(User createdBy) {
this.createdBy = createdBy;
return this;

public String getContents() {
return contents;

public Program setContents(String contents) {
this.contents = contents;
return this;

public String toString() {
final StringBuffer sb = new StringBuffer("Program{");
sb.append(", name='").append(name).append('\'');
sb.append(", createdBy=").append(createdBy);
sb.append(", contents='").append(contents).append('\'');
return sb.toString();

Let’s serialize/marshal an object first.

User user = new User();
user.setName("Bazlur Rahman");

Program program = new Program();
program.setName("Program @# 1");
program.setContents("Some contents");

ObjectMapper objectMapper = new ObjectMapper();

final String json = objectMapper.writeValueAsString(program);

The above code will produce following josn-

"id": 1,
"name": "Program @# 1",
"createdBy": {
"id": 1,
"name": "Bazlur Rahman",
"email": ""
"contents": "Some contents"

Now can do the opposite very easily.  If we have this JSON, we can unmarshall to a program object using ObjectMapper as following  –

String jsonString = "{\"id\":1,\"name\":\"Program @# 1\",\"createdBy\":{\"id\":1,\"name\":\"Bazlur Rahman\",\"email\":\"\"},\"contents\":\"Some contents\"}";

final Program program1 = objectMapper.readValue(jsonString, Program.class);

Now let’s say, this is not the real case, we are going to have a different JSON from an api which doesn’t match with our Program class.

"id": 1,
"name": "Program @# 1",
"ownerId": 1
"contents": "Some contents"

Look at the json string, you can see, it has a different field that is owenerId.

Now if you want serialize this JSON as we did earlier, you will have exceptions.

There are two ways to avoid exceptions and have this seralized –


Ignore the unknown fields

Ignore the `onwerId`. Add following annotation in the Program class

@JsonIgnoreProperties(ignoreUnknown = true)
public class Program {}

Write custom deserializer

But there are cases when you actually need this `owerId` field. Lets say you want to relate it as as an id of the User class.

In such case, you need to write a custom deserializer-

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;


public class ProgramDeserializer extends JsonDeserializer<Program> {
public Program deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);

final Long id = node.get("id").asLong();
final String name = node.get("name").asText();
final String contents = node.get("contents").asText();
final long ownerId = node.get("ownerId").asLong();

User user = new User();

return new Program(id, name, contents, user);

As you can see, first you have to access the JsonNode from the JonsParser.  And then you can easily extract information from a JsonNode using get method. and you have to be make sure about the field name. It should be the exact name, spelling mistake will cause exceptions.

And finally you have to  register your ProgramDeserializer to the  `ObjectMapper`.

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Program.class, new ProgramDeserializer());


String newJsonString = "{\"id\":1,\"name\":\"Program @# 1\",\"ownerId\":1,\"contents\":\"Some contents\"}";
final Program program2 = mapper.readValue(newJsonString, Program.class);

Alternatively you can use annotation to register the deserializer directly –


@JsonDeserialize(using = ProgramDeserializer.<b>class</b>)
public class Program {

Full source code can be found in :

Why 1000 == 1000 returns false but 100 == 100 returns true in java?

This is probably one of the well discussed topic, but I found it interesting.

if you run the following code-

    Integer a = 1000, b = 1000;  
    System.out.println(a == b);//1
    Integer c = 100, d = 100;  
    System.out.println(c == d);//2

You will get –


Here is the basic:  we know that , if two references point to the same object, they are equal in terms of ==. If two references point to different objects, they are not equal in terms of == even though they have the same contents.

So, here last statement should be false as well.

This actually where it gets interesting, if you look into the class , you will find that there is a inner private class, that caches all Integer objects between -128 and 127.

So thing is, all small integers are cached internally and when we declare something like –

Integer c = 100;

What it does internally is:

Integer i = Integer.valueOf(100);

Now if we look into the valueOf() method , we will see-

    public static Integer valueOf(int i) {

      if (i >= IntegerCache.low && i
          return IntegerCache.cache[i + (-IntegerCache.low)];

      return new Integer(i);

If the value in the range -128 to 127, it returns the instance from the cache.


 Integer c = 100, d = 100;

basically point to the same object.

Thats why we do –

System.out.println(c == d);

We get true.

Now you might ask why does this caching require?

Well, the logical rationale is that “smaller” integers in this range are used much more often than larger ones, so using the same underlying objects is worth it to reduce the potential memory footprint.

However, you can abuse this thing using reflection API.

Run the following code, and enjoy the magic-

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

      Class cache = Integer.class.getDeclaredClasses()[0]; //1
      Field myCache = cache.getDeclaredField("cache"); //2

      Integer[] newCache = (Integer[]) myCache.get(cache); //4
      newCache[132] = newCache[133]; //5

      int a = 2;
      int b = a + a;
      System.out.printf("%d + %d = %d", a, a, b); //

New Integer/Long parse method in java 9

I have just got install the Java 9 early access release and started playing around. I know that, this not the major release and it is more  of a bug fix release with a few tiny features.

However, I found two additional pares method for long/Integer –

1. public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix)
                throws NumberFormatException {}
2. public static long parseUnsignedLong(CharSequence s, int beginIndex, int endIndex, int radix)
                throws NumberFormatException {}

both Integer and Long have these two methods.

So they basically parse a CharSequence argument as a signed int or long in the specified radix, beginning at the specified beginIndex and extending to endIndex – 1.

I found a question that a few people usually ask, is why we need a radix. Let me try to answer it shortly-

Radix is the base of a system of numeration. Actually there a whole lot of numeric system out there but only few of them are most popular which are – decimal (base 10) , binary (base 2), octal (base 8), hexadecimal ( base16) .

One numerical value can be converted to different bases. For example – the number 10 in binary be represents as 2 in decimal.

So when you have a character sequence and that as a base unlink decimal, you want to parse it , you have to provide the base.

Example –

Say you want to parse portion of a sequence of binary values into long

int result = Integer.parseInt("010010000100001001000100", 0, 7, 2);
System.out.println(result); //36

int result2 = Integer.parseInt("-6B4A", 0, 3, 16); 
System.out.println(result2); //-107

int result2 = Integer.parseUnsignedInt("6B4A", 0, 3, 16);
System.out.println(result2); //1716

How to find out the number of processor your system has ?


public class Main {

    public static void main(String[] args) {

        int availableProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println("Total number of system processors: " + availableProcessors);

        // Total number of system processors: 4

How to read name of the files in some directory and join them using commas ?


import java.util.StringJoiner;

public class Main {

    public static void main(String[] args) {
        File dir = new File("/home/rokonoid/Downloads");
        File[] files = dir.listFiles();

        String fileNames = Stream.of(files)
                .collect(Collectors.joining(", "));

Scala does optimize tail recursion at compile time

I just got wowed. Scala does optimize tail recursion at compile time, I didn’t know that.

Say I have the following countDown() method —

public static void main(String[] args) {

public static void countDown(int n) {
    if (n == 0) return;
    System.out.println(n + " ...");


    countDown(n - 1);

private static void waitASecond() {
    // do  some bla bla

Run it, you will immediately get java.lang.StackOverflowError. The equivalent Scala code, however, would run just fine.

def main(args: Array[String]): Unit = {

def waitASecond() = {}

def countDown(n: Int): Unit = {
  if (n == 0) return
  else {
    println(n + " ...")
    countDown(n - 1)

Java Stream API

I have been using Java Stream API massively these days. So I thought, why not write a short tutorial on it.

So what is steam anyway?

Don’t be confused with InputStream or OutputStream of Java IO. Stream are complete different thing in Java 8.

A stream basically represents a sequence of elements and provide a rich set of operations to compute those elements.

Its common to do bulk operation in our day to day business application. So normally we do use for loops and collections to do that, we iterate over the collection and then write if then else code and various variables come into play and we get a big chunk of ugly and sequential code.

We do the same thing using stream API but can abstract things in to a very high level using lambda and functional approach and write more elegant understandable and clean code. After having certain abstraction, we can do certain optimization, like we might want to go parallel, which was never easy before.

Well enough talk, lets do some code example –

1. First of all, lets remove regular for loop with IntStream. What I want to do is, print 1 to 10-

IntStream.range(0, 10)
          .forEach(value -> System.out.println(value));

Or just using method reference-


IntStream.range(0, 5)

2. I want to count number of elements in the list –

List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());;

3. I want to find average of all elements in the list –

Double avarage = -> item));

4. I want to get complete summery of the list

IntSummaryStatistics intSummaryStatistics = -> value));


//IntSummaryStatistics{count=99, sum=4950, min=1, average=50.000000, max=99}

5. Create a map out of the list

Map<Integer, Integer> map = -> p, q -> q * 3));


//{1=3, 2=6, 3=9, 4=12}

6. I want to get the maximum number of the list

        // first make a random integer list 
        List<Integer> randomInts = new Random().ints(-100, 100).limit(250).boxed().collect(Collectors.toList()); 
        Optional<Integer> max =; 
        max.ifPresent(value -> System.out.println(value)); 
        // or  
        max.ifPresent(System.out::println);// method reference 

7. Say I have a array of name and I want to count the name that starts wit ‘C’

String[] names = {"Fred Edwards", 
                "Anna Cox", 
                "Deborah Patterson", 
                "Ruth Torres", 
                "Shawn Powell", 
                "Rose Thompson", 
                "Rachel Barnes", 
                "Eugene Ramirez", 
                "Earl Flores", 
                "Janice Reed", 
                "Sarah Miller", 
                "Patricia Kelly", 
                "Carl Hall", 
                "Craig Wright", 
                "Martha Phillips", 
                "Thomas Howard", 
                "Steve Martinez", 
                "Diana Bailey", 
                "Kathleen Hughes", 
                "Russell Anderson", 
                "Theresa Perry"}; 
long c = Arrays.asList(names) 
                .filter(s -> s.startsWith("C")) 

8. Say I want to make all the name upper case and the sort and then print


An advance example

Say I have a class named Person ->

public class Person { 
    private String name; 
    private int age; 
    public String getName() { 
        return name; 
    public Person setName(String name) { = name; 
        return this; 
    public int getAge() { 
        return age; 
    public Person setAge(int age) { 
        this.age = age; 
        return this; 
    Person(String name, int age) { = name; 
        this.age = age; 
    public String toString() { 
        return name; 

9 . I want to get persons  group by age

        Map<Integer, List<Person>> collect = persons 

10  I want to get average age of all the persons

        Double collect1 = persons 

11. I want to print all the names that are eligible to vote in Bangladesh in a single string

        String sentence = 
                .filter(p -> p.getAge() >= 18) 
                .collect(Collectors.joining(" and ", " In Bangladesh ", " are of legal age for voting,")); 
        // In Bangladesh Rahim and Karim and Rehana and Rajib are of legal age for voting, 

To be continued …..

How to drop all tables in postgresql

Execute following commands:-

TO postgres;
TO public;
ON SCHEMA public IS 'standard public schema';

it works like a charm.

For details, please visit:

Gradle to maven conversion and vice versa

How to convert maven to gradle

The first thing is, you have to install gradle. Its easy. I know you can do it.  Go to the installing guide:

Now the second step is to run ‘gradle init‘ in the directory containing the POM file. This will  convert the maven build to a gradle build generating a setting.gradle file and one or  ore more build.gradle files.

Thats all.

How to convert gradle to maven

You just need to add  a maven plugin in your build.gradle.

Your build gradle should be like this-

apply plugin: 'java'
apply plugin: 'maven'

group = ''
// artifactId is taken by default, from folder name
version = '0.1-SNAPSHOT'

dependencies {
compile 'commons-lang:commons-lang:2.3'

Now run ‘gradle install‘ in the build.gradle folder.

Now you will find in the build/poms subfolder, a file called pom-default.xml which will contain the dependencies.

Now its all yours, copy it, customise it add up new stuff.

How to read call logs programmatically from android

It’s fairly easy. You need add following uses-permission in android manifest to get call history programmatically.

<uses-permission android:name="android.permission.READ_CONTACTS" />

That’s all here.

And then create an activity and layout. We need to query from ContentProvider. And for that I used CursorClassLoader.

Read about CursorLoader from here:


I want to load 4 properties and they are- phone Number, type of call eg. Outgoing or ingoing or missed call, Date and Time of the call and duration of the call.

So first use LoaderManager.LoaderCallbacks<Cursor> interface in your activity. It has three methods.

abstract Loader        onCreateLoader(int id, Bundle args)

//Instantiate and return a new Loader for the given ID.

abstract void      onLoadFinished(Loader loader, D data)

//Called when a previously created loader has finished its load.

abstract void      onLoaderReset(Loader loader)

//Called when a previously created loader is being reset, and thus making its data unavailable.

To initialize a query, we need to call LoaderManager.initLoader() at the very first place.

We are going to add a button and call this in that button events here and after this background framework will be initialized. As soon as the background framework is initialized, it calls your implementation of onCreateLoader(). To start the query, we have to return a CursorLoader from this method.


public Loader onCreateLoader(int loaderID, Bundle args) {
Log.d(TAG, "onCreateLoader() >> loaderID : " + loaderID);

switch (loaderID) {
// Returns a new CursorLoader
return new CursorLoader(
this,   // Parent activity context
CallLog.Calls.CONTENT_URI,        // Table to query
null,     // Projection to return
null,            // No selection clause
null,            // No selection arguments
null             // Default sort order
return null;


We are going access our expected data from a Cursor. And we will get this in the onLoadFinished() method.


    public void onLoadFinished(Loader loader, Cursor managedCursor) {
        Log.d(TAG, "onLoadFinished()");

        StringBuilder sb = new StringBuilder();

        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);

        sb.append("<h4>Call Log Details <h4>");


        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;

            int callTypeCode = Integer.parseInt(callType);
            switch (callTypeCode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "Outgoing";

                case CallLog.Calls.INCOMING_TYPE:
                    dir = "Incoming";

                case CallLog.Calls.MISSED_TYPE:
                    dir = "Missed";

                    .append("<td>Phone Number: </td>")
                    .append("<td>Call Type:</td>")
                    .append("<td>Date & Time:</td>")
                    .append("<td>Call Duration (Seconds):</td>")








Full Source code:



How the java code gets executed and performs better?

Please bear with my attempt to inform you a little regarding the execution of Java code.

Java’s code is compiled into byte code, which Java’s virtual machine executes.  This output is an intermediate language (IL) that is neither human readable nor machine-executable. Only the virtual machine understands it.  To execute this output, the virtual machine uses a Just in Time (JIT) compiler to interpret the byte code – so is Java an interpreted language as some people describe it, or is Java a compiled language?  The answer: Java is both.  Its source code is compiled with a static compiler into byte code – and then, the JIT interprets the compiler’s output.

From the previous description, one might be tempted to conclude that the JIT hurts performance, as it compiles during execution, a design that would seem to cause Java to run slowly. This conclusion, while intuitive, is incorrect.  The JIT actually performance quite well. At run time, it compiles byte code into machine code, which is later run by the JVM.   When Java executes, it executes machine code just as native code does – so it should run – discounting the JIT’s compilation costs – as fast as native code does.

However, C/C++ is generally regarding as providing better performance than Java does. The on-the-fly nature of Java’s execution lends credence to this thinking.  Compiling a piece of code into machine code takes a non-trivial amount of time.  If a language executes similar machine instructions but does not need compilation prior to the execution of them, then one can assume that the language in question runs faster than Java does – even when Java’s machine code output is maximally optimized.  However, Java isn’t maximally optimized, but C++ is not maximally optimized either.  No compiler can match the performance a top-notch assembly programmer who is an expert at manipulating the targeted hardware – so both Java and C++ can never be maximally optimized.  Making matters worse, both languages have inherent issues. Java must bear the reality that at least some of its code has to be compiled every time that it runs, and C++ is, when it must be generic, often not fully tailored to its hardware, as Java always is.  Even with the aforementioned handicap, one still expects Java’s compilation cost to give C++ in edge every scenario outside of very poorly coded or compiled C++.

However, appearances are deceiving; the JVM is a very intelligent environment and the JIT an intelligence compiler. For example, the JVM knows which methods are called frequently, as it maintains a count of each method’s calls.  When this count exceeds a certain threshold, the method’s machine code is kept, so that the JIT does not have to compile the method when it is called again – a decision that greatly reduces the cost of translating byte code into machine code.  Furthering this performance improvement, the JIT optimizes the most frequently used code. The JIT collects statistics to determine which parts of code fit this mold. Intelligent optimization of this ilk can, as Research indicates, yield big gains. Most research states that 80% of execution time is spent executing 20% of the code (“hot code”) – so optimizing these sections of code can yield sizeable performance benefits. The JIT optimizes “hot code.” It executes these sections in a highly optimized way directly on the operating system.  To achieve this goal, the JIT uses statistics to identify the “hot code.” In fact, Java performs even more optimization than efficiently executing “hot code.” It identifies the code that it executes the most and recompiles to run more efficiently than it previously did. These optimizations allow Java to achieve, in certain situations, better performance than C++ gives, without the need to resort to dangerous compiler settings or to dangerous optimization techniques.

Few resources to read:


I would like to thank my friend Collin Rusk for his help without which it would not be publish anyway.

Is it necessary to know everything about a programming language before starting to develop an application in it?

I want to build an application in Java that uses Swing, networking and databases (JDBC). However, the catch is that I donot know anything about these three fields. However, I do know some concepts of core java such as interfaces, inner classes, exceptions and debugging, collections, multithreading and I/O Streams.

I want to know if I “really” want to develop this application, should I wait and learn these concepts or should I jump right in? I am facing this as a severe mental handicap and would greatly appreciate some help here.

★ No

Answer by Bazlur Rahman Rokon:

So my suggestion would be, first learn a little stuff on swing, start developing the UI using swing, and then start learning few stuff on JDBC and then integrate your swing app with jdbc. And when you are little advance on these two, you may start networking stuff.
And doing all these, you will face problems, and thus you need to find more and learn more stuff to solve those problems.

Personally I loved this approach.

View Answer on Quora

Let’s play deep sleep

Do you ever take a train, bus, or cab? Do you ever fall asleep? Do you regularly miss your bus stop? Well, sleeping kit is here to help! Enter your destination into the application. When your transport is near your stop, sleeping kit will sound an alarm to alert you. If you’re asleep, the alarm will wake you up. If you’re forgetful, the alarm will remind you. Sleeping kit helps you travel more easily and effectively by removing part of the hassle.

Additionally you can share your location to anyone with sleeping kit easily.


You wanna give it try, right?

Get it on Google Play

Android Layout Property Initializer Plugin for IntelliJ IDEA

Well, the very first version of IntelliJ IDEA plugin that I wrote over the last two nights, is now available for public use. This is nothing big, just a little, doing for fun. Any feedback would be greatly appreciated.

General instruction

  1. First, download it from here.
  2. Just install it as you normally install plugin. Go to settings, then plugins and then click on the button named “Install from disk” and then locate it.
  3. Restart your IDE.

Now you can create an android project, create an activity and a layout. Design your layout.

Click on the image for further instruction.



or watch in

NB: I have tested with IntelliJ IDEA 13.


Update:  The plugin now available on Jet-brain plugin repository :

The 3rd party tools that I use in my every android application

Ormlite for Android

Well many of you love ORM (Object rational mapper). It’s just another cool orm tool simply works fine with android’s sqlite database.



Who didn’t hear of Dependency Injection these days?

RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. You must love it.



Simple Logging Wrapper Library for Android. Those who are used to with SLF4J, would love it.


Android Asynchronous Http Client

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. It’s really handy and easy to use. It covers almost everything regarding http request response stuff. Its only 25Kb for everything.


Sherlock ActionBar

After android 3.0 you have notice there is a nice stuff called Action bar and most of the android application use it.  It’s a nice extension of android support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API. You gotta love it.


A great place to learn and mingle

The Java User Group Bangladesh (JUGBD) is now formed and successfully finished its 2nd meetup in last week. We are doing great, it’s not an exaggeration.

For those who doesn’t know what is JUG, let me brief a little. Java User Groups (JUGs) are basically a group of enthusiastic people who loves java and develop product and service using Java related technology and love to share their knowledge to others. We get together in some place and then talk to each other, eat and have fun.

The primary vision of JUGBD is to continue meeting on very regular basis. As all the people are involved here are too much cool and enthusiastic, it always feels better to talk to each other and learning new things.

In August 2013, we had our first meetup. On this day, we formed the group with a few Java programmers of different software firms and with some students, both of whom were present at the event. Later we decide to have another meetup, which was held on 6th December, 2013. This time we received a huge response from the programmers here in Dhaka, a lot of them were physically present and most of them supported us. We had three speakers at this event. They gave talk on how Java technology influenced other technology, big data (Cassendra) and JVM diagnostic. All of talks were excellent.

A lot of software firm are stepping forward to help our events. Meetup 2.0 was sponsored by Therap Services, LLC. In addition, we got our sponsor for the next meetup already, which is really helpful to our community. We greatly appreciate this sort of help.

Right now, we are looking to contribute in some open source projects and thus we are looking for problems, ideas. Here is an open invitation to everybody: if you are a java programmer, enthusiastic about learning new stuff and love to talk about technologies, please join us. It’s a great opportunity for us to learn and mingle.

Android – Expandable TextView

There are so many thread in Stack overflow for expandable TextVeiw.

The idea is, initially the TextView will show a small portion of a long text and when it is clicked, it will show the rest of the text.

So here is the code that how I solved it.
Using following class:

package com.rokonoid.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
 * User: Bazlur Rahman Rokon
 * Date: 9/7/13 - 3:33 AM
public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 200;
    private static final String ELLIPSIS = ".....";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);

        setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                trim = !trim;

    private void setText() {
        super.setText(getDisplayableText(), bufferType);

    private CharSequence getDisplayableText() {
        return trim ? trimmedText : originalText;

    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        bufferType = type;

    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        } else {
            return originalText;

    public CharSequence getOriginalText() {
        return originalText;

    public void setTrimLength(int trimLength) {
        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);

    public int getTrimLength() {
        return trimLength;

And add following line in your attr.xml

<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="ExpandableTextView">
<attr name="trimLength" format="integer"/>

Put the following in your main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android=""

And test your activity

package com.rokonoid.widget;

import android.os.Bundle;

public class MyActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        String yourText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                "Ut volutpat interdum interdum. Nulla laoreet lacus diam, vitae " +
                "sodales sapien commodo faucibus. Vestibulum et feugiat enim. Donec " +
                "semper mi et euismod tempor. Sed sodales eleifend mi id varius. Nam " +
                "et ornare enim, sit amet gravida sapien. Quisque gravida et enim vel " +
                "volutpat. Vivamus egestas ut felis a blandit. Vivamus fringilla " +
                "dignissim mollis. Maecenas imperdiet interdum hendrerit. Aliquam" +
                " dictum hendrerit ultrices. Ut vitae vestibulum dolor. Donec auctor ante" +
                " eget libero molestie porta. Nam tempor fringilla ultricies. Nam sem " +
                "lectus, feugiat eget ullamcorper vitae, ornare et sem. Fusce dapibus ipsum" +
                " sed laoreet suscipit. ";

        ExpandableTextView expandableTextView = (ExpandableTextView) findViewById(;


Screenshot of textview with a small portion of long text.
Expandable TextView

Screenshot when you click on the text

Expandable TextView

How to Remove Duplicate Rows from a Table in SQL Server


It is obvious that if somehow duplicate rows get inserted into a table, it becomes a major issue to delete those duplicate rows. So this topic will help us to delete those duplicate rows from the specific table.


I used some basic T-SQL (Transact-SQL*) code to accomplish the problem. So you don’t need to worry understand the codes and even you can use just blindly.


I had a database table with duplicate rows and I wanted to get rid of it. So this is how I solved my issue.


First, say I have a table named Stores with following column.


So my first select query:


And Output:


Now look carefully in above figure, Stores table does contain duplicate records. Check first two columns marked with rad box. Every the columns are the same except Id.

Now let’s find out duplicate rows in a way so that we can easily understand. We are now going to add an extra column in a temporary table, let’s name it RowNumber. RowNumber will hold count of duplicate rows.

So let’s execute the following query:

,Longitude ORDER BY DmsCode) AS RowNumber, *
FROM Stores

You see, I haven’t include Id, since it’s not duplicate.


Now if you look above table RowNumber column, you will able to know which records contain duplicate values on rows with RowNumber greater than 1.

Now if we want to keep unique values in the table and delete others execute following query:

ORDER BY DmsCode) AS RowNumber, *
FROM nps_new.dbo.Stores
DELETE from Temp WHERE RowNumber >1

If the query executes, we will find only unique values in the table.


I did not explain the queries as I assumed that people who deals with such thing already know SQL.

Random Thoughts – Caffeine

I’m worried about my personal productivity these days. I am a person who used to spend (maybe waste) time doing random things, but still worried about personal productivity. There are people that the term personal productivity meant nothing to them at all. To be honest, I do not like them. I love those people who are always calculative, thoughtful and hardworking. I am kinda person, who at least pretend to be working all the time. By the way, I’m a programmer, I used to work in a close room sitting in a chair staring at a computer screen for hours upon hours. For the common people (who are not a programmer and have no idea what does a programmer actually)  may find it too wired and crazy things and I have some friends who cannot even imagine how a man can sit such long time without moving (my longest record is 18 hours in a day). Recently I did a little digging on YouTube and found that sitting for long without moving minimize productivity. Although I do not believe in their research. I believe only coffee or tea can improve the productivity and it is my secret. You have to know how to make great coffee or a tea. I believe that most people cannot make a good coffee or tea. I make my own coffee or tea. I believe I do make the best coffee / tea, though only a few of my friends agreed. And I don’t offer coffee/tea to everybody.

I have a random thought that programmer productivity is very dependent on caffeine.

My personal productivity is exhausted due to not having coffee too much these days. I feel sleepy during the day time and used to sleep all night. By the way, this is the Holy month of Ramadan and I do fast from dawn to dusk, and that is about 15 hours. And that’s why I cannot have a lot of coffee these days.

In my own definition productivity means, some actions that accomplish goal in a timely manner.

Programmers Freedom

There is no such thing as true freedom. This is probably a true realization. In my understanding, freedom means, minimizing the level of dependence. As a programmer, we used to think we have a true freedom in computer stuff, as it seems we can do whatever we want to do. It is true, in fact, at least in theory, but in practice we simply cannot do. We think about a problem and make a conceptual design in our head to solve that particular problem, and then select a programming language to implement. This is a typical scenario.

But the problem is to map our conceptual model into a programming language. This is not an easy task to do as we are heavily dependent on programming infrastructure. Sometimes we have to wait for the language designer to update certain things (we used to joke about Java updates), and if we require additional power from the IDE, we must wait for IDE vendor. Most importa­­ntly programming language has simple and few notations that can be expressed in comparison with our natural language. Most of the cases we the programmers spent our time to find ways to express our conceptual model in terms of programming level abstractions which is difficult and not creative and more or less waste of time.

So where’s our freedom? Are we not locked in some ways.

Java Installation in Ubuntu

Method 1

Step 1: download jdk from:


Step 2 : go to downloaded folder using command line terminal :

 cd ~/Download 

Step 3: install jdk

sudo tar -xzvf  jdk-7u21-linux-i586.tar.gz --directory=/usr/local/

sudo ln -s /usr/local/[jdk_folder_name]/ /usr/local/jdk

* change the folder name according to extracted jdk folder name,

Step 4: open .bashrc

sudo gedit .bashrc

Step 5: add following line end of the .bashrc file

export JAVA_HOME=/usr/local/jdk

Save and close .bashrc file.

Step 6: compile .bashrc file

source .bashrc


Step 7:  now test whether java is installed properly or not: goto terminal and time following line

java -version

if java is installed properly, java runtime information will be displayed.

if not… follow second method:
Method  2:

Step 1:  Preparing your system

First you need to remove openjdk for this run the following command from your terminal

 sudo apt-get purge openjdk*

Step 2:  If you installed java 7 from any other PPA and you are having problem with java then you have to do following steps before installing the PPA mentioned here

sudo rm /var/lib/dpkg/info/oracle-java7-installer*

sudo apt-get purge oracle-java7-installer*

sudo rm /etc/apt/sources.list.d/*java*

sudo apt-get update

Step 3:  Install oracle java 7 in ubuntu 13.04/12.10/12.04

Open the terminal and run the following commands

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

sudo apt-get install oracle-java7-installer

now give a smile :) :) :D

Executing Linux command from Java

You know Linux commands are always fun. We always play on terminals. How about executing from our favorite language java?

Then you need following class


public class CommandExecutor {
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[] { "/bin/sh", "-c", command };
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader input = new BufferedReader(new InputStreamReader(

BufferedReader stdError = new BufferedReader(new InputStreamReader(

String s = null;
while ((s = input.readLine()) != null) {

while ((s = stdError.readLine()) != null) {
} catch (IOException e) {
return sb.toString();

Now you can execute any command using this class.
For example-

public static void main(String[] args) {</pre>
String output = CommandExecutor.execute("ps aux | head -3");

And output will in your console like:

root         1  0.0  0.0  24600  2212 ?        Ss   Apr12   0:00 /sbin/init
root         2  0.0  0.0      0     0 ?        S    Apr12   0:00 [kthreadd]

Check out Birds Puzzle on Google Play

I have got an android app named Birds Puzzle in the android market. It is a kid friendly image slide puzzle game for Android displaying a set of bird picture slides that you move into the correct order.



in the very first window there is a menu, you have to press on new puzzle, and then a cover flow with different birds will appear, you have to select one. When you will select one, a new window will appear showing you the correct order of slides. And then you have to press play button in the top right corner of action bar, and puzzle will begin. You have to complete the puzzle with the time limit show in action bar. If you can solve the image within the limit, a dialog will appear showing the name of birds and a short description of birds with playing its voice.

Checkout : Birds Puzzle on Google Play

How to decompile android apk to java source code?

I wrote another post with the same title here and it got a lot of comments and people wanted to know more, and some point some visitors was confused. so here is the easiest copy-paste solution.

  1. Download dex2jar from
  2. Extract to a folder. for example /home/codexplo/( for linux), or  C:\ (for windows)

unzip -x -d /home/codexplo

  1. use dex2jar to generate .jar file. dex2jar will generate a file named someApk-dex2jar.jar in the working folder.
   linux sh /home/codexplo/dex2jar-version/ /home/codexplo/someApk.apk
   windows C:\dex2jar-version\d2j-dex2jar.bat someApk.apk
  1. use a decompiler to view the source.

that’s it

Reference :

How to enable usb debugging in ubuntu for nexus 7

get the terminal, type:

sudo vi /etc/udev/rules.d/70-android.rules


sudo gedit /etc/udev/rules.d/70-android.rules

and then add the following line:

SUBSYSTEM==”usb”, ATTR{idVendor}==”18d1″, ATTR{idProduct}==”4e42″, MODE=”0666″

DNS Explained

DNS মানে হলো Domain Name System.

এটি ইন্টারনেট এর সবচেয়ে গুরুত্বপূর্ণ জিনিস। এটি ছাড়া ইন্টারনেট যেকোন মুহূর্তে ধসে পরতে বাধ্য। ডিএনএস না থাকা মানে No Internet, No facebook, No Google. সুতরাং বুঝা যাচ্ছে ডিএনএস দি-ই-ই-ই-ই-ই-ই ইম্পট্যার্ন্ট!

তাহলে ডিএনএস কি?

আমরা সবাই জানি (যারা জানি না তারা নিজ দায়িত্ব জেনে নিন) প্রত্যেকটি কম্পিউটারের একটি আইপি এড্রেস থাকে। আইপি এড্রেস এর মাধ্যমে একটা কম্পিউটার আরেকটি কম্পিউটারকে চিনতে পারে। ধরা যাক ফেইসবুক, ফেইসবুক একটা এপ্লিক্যাশান, আলোচনার সুবিধার্থে ধরে নিলাম একটা মাত্র কম্পিউটারে ফেইসবুকটি চলে, আর কম্পিউটারের একটা আইপি এড্রেস আছে। সুতরাং আমাদের যে কম্পিউটারে ফেইসবুক চলে, সেই কম্পউটারের আইপি এড্রেসটি জানতে হবে যদি আমরা ফেইসবুক ব্যবহার করে চাই। আইপি এড্রেস হতে হয় ইউনিক। দুনিয়াতে যেহেতু কোটি কোটি কম্পিউটার, সুতরাং এই আইপি এড্রেস ইউনিক করতে গিয়ে এমন হয়েছে যে আমরা যারা সাধারণ মানুষ(যারা পাই-এর মান ২০০ ঘর পর্যন্ত মনে রাখতে পারে, তারা অসাধরণ) কোন ভাবেই মনে রাখতে পারি না। যেমন ফেইসবুকের আইপি এড্রেস হলো- গুগলের হলো সুতরাং হাজার হাজার ওয়েব সাইট যেগুলা আমরা প্রতিনিয়ত ব্রাউজ করি সেগুলার একটা নির্দিষ্ট আইপি এড্রেস থাকে। আমাদের কারো পক্ষেই এতো আইপি এড্রেস মনে রাখা সম্ভব না। আমরা যেহেতু বুদ্ধিমান, সুতরাং একটা উপায় বের করে ফেলেছি, আর সেটিই হলো ডোমেইন নেম সিস্টেম। আমরা প্রত্যকটি আইপি এড্রেস এর জন্যে একটি করে সুন্দর নাম দিয়ে রাখি, তাতে করে আমাদের মনে রাখতে সুবিধা হয়। ডোমেইন নেম সিস্টেম হলো একটা Distributed ডাটাবেইস এবং নেটওয়ার্ক সিস্টেম যেখানে আপইপি এড্রেসের সাথে একটা নাম লেখা থাকে এবং এতে করে আমাদের ফেইসবুকের আইপি এড্রেস মনে রাখতে হয় না, আমাদের মনে রাখলেই চলে।

এখন এটি তাহলে কিভাবে কাজ করে? আমারা যখন ব্রাউজারের এড্রেস বারে লিখি, তখন ব্রাউজার এবং অপারেটিং সিস্টেম চিন্তা করবে, এর আইপি এড্রেস আগে তারা থেকে জানে কিনা(will first determine if they know what the ip address is already)। এটি কম্পউটারে কনফিগার করা থাকতে পারে কিংবা মেমরীতে থাকতে পারে(it could be configured in computer or it could be in memory(cache)). এখন আসি, যদি ব্রাউজার এবং অপারেটিং সিস্টেম দুটির কেও-ই না জানে, তাহলে কি হবে?

What happens next?

ব্রাউজার অপারেটিং সিস্টেম এর কাছে ডোমেইন এর আইপি এড্রেস চেয়ে বসে থাকবে, আর অপারেটিং সিস্টেম এমনভাবে কনফিগার করা থাকে যে, সে একটি Resolving Name Server এর কাছে আস্ক করে পারে ডোমেইন নেইম এর জন্যে।

Resolving Name Server এর কাজ হলো ডিএনএস লুকআপ করা। এটি ওপারেটিং সিস্টেমের সাথে কনফিগার করা থাকে।

কিন্তু Resolving Name Server আইপি এড্রেস জানতেও পারে আবার নাও জানতে পারে। অপশন দুইটা। যদি মেমরিতে থাকে থাকে, তাহলে সাথে সাথে অপারেটিং সিস্টেমকে আইপি এড্রেসটি দিয়ে দেবে। না থাকলে সাথে সাথে রুট নেইম সার্ভারক কুয়েরি করবে। কিন্তু রুট নেম সার্ভার সাথে সাথে রিপ্লাই দিবে, I don’t know. But I do know where to find the com name severs. কম নেইম সার্ভার হচ্ছে টপ লেভেল ডুমেইন নেইম সার্ভার। রিসলভিং সার্ভার রুট সার্ভার এর কাছে সব ইনফরমেশন নিয়ে কেশ করে রাখে যাতে করে দ্বিতীয় বার রুট সার্ভারের কাছে যেতে না হয়। এরপর সে টপ লেভেল ডুমেইন সার্ভারের (TLD) কাছে কুয়েরি করে। এবং যথারীতি টপ লেভেল ডুমেইন সার্ভার রিপ্লায় দেয়… a a ah.. I don’t know, But I do know where to find the name server.

নেক্সট লেভেল নেইম সার্ভারের নাম হলো, Authoritative Name Server. সুতরাং আগের মতোই রিসলভিং সার্ভার TLD এর কাছ থেকে সব ইনফরমেশন নিয়ে Authoritative Name Server এর কাছে কুয়েরি করে, এবং সাথে সাথে Authoritative Name Server বলবে, Hey! I know where that is! Tell your browser to go to the IP address:

রিসলভিং নেইম সার্ভার ANS এর কাছে এই ইনফরমেন নিয়ে নিজের কাছে কেশ করে রাখে এবং অপারেটিং সিস্টেমকে বলে, অপারেটিং সিস্টেম তখন আইপি ব্রাওজারকে বলে, আর ব্রাওজার সাথে সাথে সেই আইপিতে হিট করে(কানেকশান ক্রিয়েট করে,Http protocol একটা বিশাল ফিরিস্তি, পরে কোন একসময় বলবো)।

Pretty Cool, huh!!

যদিও প্রসেসটা একটু জটিল, কিন্তু নেইম সার্ভার সিস্টেম কে এমন ভাবে বানানো হয়েছে, যাতে করে এটি চোখের পলকেই কাজ করে ফেলে।

সুতরাং চারটা জিনিস, Resolving Name Server, The ROOT server, The TLD server and Authoritative Name Server.

এর কোন একটি যদি কলাপস হয়, হে হে, সাথে সাথেই সব ইন্টারনেট নাই হয়ে যাবে।

Problems with unicode encoding in spring projects

I had a problem with the encoding of Unicode characters. I developed a simple web application with support for multiple languages​​, which is called internationalization or i18n. In this application, the data were saved in a database, and then re-shown. But I get exceptions on production and it was a unicode utf-8 character encoding problem.
By the way, my application was developed using spring and hibernate and jpa2. It was kind of a nightmare and I was getting the exceptions frequently and I was completely no where-zone. At least, after searching and using many sources, I found out the solutions.

So here is the solutions–

First you need add some extra parameter in your database url. For example–


Secondary you’ve to add a filter in your web.xml

















And finally you have to make sure you have added following line in your jsp pages

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

and finally follow the command in your terminal

You should now be logged into the MySQL prompt. Here type the following commands :

mysql> use user_db;

mysql> alter database user_db default character set utf8 collate utf8_unicode_ci;

Query OK, 1 row affected (0.00 sec)

This should have done it.

okay, that’s how I solved the issue.

A brief introduction of String in Java

What is string?

String is traditionally a sequence of characters. In Java string is an object and it is widely used in Java. String class is defined in java.lang package and implicitly available for all program.

String can be created in two ways.

  1. By string literal
  2. by new keyword

String literal

String literal is created by double quote, for example-

String aStrign = “A String is Created”:

each time you create an new string, the JVM first check the constant pool whether it is already in constant pool. If is already in available, JVM doesn’t create new string, instead, it just refer the old string as it is already available.

So, if we create strings like-

String a = “A”;

String b = “A”

here, first we created a string which referenced to the reference value a. now if we need another string and if we create like 2nd line of the example, JVM will first check whether there is already a string object in the constant pool which contained “A” available or not, if it is already there, no new string will be created, instead, our new string is referenced by the old one.

Now what is object pool?

Object pool is another kind of data structure managed by Java virtual machine. We all know about constant who ever writes codes in his life time. Constant pool are used for frequent access and less memory consumptions. If a constant is already available in Constant pool, JVM doesn’t need to create a new object.

By new Keyword

String can be create by new keyword as all the other objects are created. Example –

String aString = new String(“Rokon”);

Here is something we need to know.

String is immutable object. Immutable means if a object once created, it will never get changed.

So when we create a string object, it will just never get changed. So now if we assign a new value to an string, the scenario is like, for example –

aString = “A new value is assigned”;

here, a new string object will be created with the value “A new value is assigned” and the object will be referenced to aString and the previous String will be ready for garbage collector.

String concatenation : String concatenation is easy in Java, what you need to do, is adding a plus-

for example –

String firstName ="Bazlur";

String lastName = "Rahman";

int age = 45;

String textToPrint = "My Name is "+ firstName + " " + lastName + " and my age is "+ age;


Output: My Name is Bazlur Rahman and my age is 45

here every concatenation,a new object is created and old one gets ready for gc.

So if we need a thousand of concatenation, JVM will create thousands of new object which required huge memory. To avoid this issue, there is two Class available, they are, StringBuilder and StringBuffer.

Mutability and immutability : A long time ago, once I chatted with my friend. I think its something worthy about.

(08:08:44 PM) Bazlur Rahman: hey

(08:08:53 PM) crusk8: hey

(08:08:59 PM) Bazlur Rahman: how are u ?

(08:09:39 PM) Bazlur Rahman: do u know difference the between mutable and immutable object ?

(08:12:20 PM) crusk8: I was just looking at the idea on wikipedia. looks like the idea for immutable objects is to create an object, set to what you want, use it, and then let it alone

(08:13:16 PM) Bazlur Rahman: i have some basic idea though … but question is when to use them?

(08:14:16 PM) Bazlur Rahman: mutable object can be changed using mutator, and immutable object cant be changed… this is the main motivation ..right ..

(08:15:19 PM) crusk8: yeah. I guess you could use an immutable objects to modify other objects, but, for safety, that immutable object itself couldn’t be modified

(08:17:30 PM) Bazlur Rahman: yup.. don’t you think, immutable object is responsible for less performance.. every time, new object is created, old object is dropped, reference is changed, garbage collector is called…

(08:18:27 PM) crusk8: yeah. if you’re going to use an immutable object. you should use it cases where that object will almost never change

(08:20:10 PM) Bazlur Rahman: but is it good practice using immutable object always? because it is thread safe, I don’t need to do locking, it is protected,

(08:20:49 PM) Bazlur Rahman: and sometime it has good performance… like we dont need to make defensive copy ..

(08:21:39 PM) crusk8: you probably wouldn’t need to do locking on that object. for languages like c++ it would be const protected

(08:21:55 PM) crusk8: you only need to do locking when that object tries to modify other objects

(08:24:05 PM) Bazlur Rahman: so whats the point of using mutable or immutable object. should I always immutable object ?

(08:26:39 PM) crusk8: mutable objects are ones that need to be modified a lot. immutable ones are that rare if ever need to be modified. an immutable object could act like a controller for the mutable objects

(08:26:58 PM) crusk8: it can change them but the mutable objects can’t change it

(08:29:47 PM) Bazlur Rahman: I’m still confused, in which situation, I should use immutable object..? for security issues ?

(08:30:45 PM) crusk8: yeah. you’re the limiting the ways that an object can modified. only through reallocating the object

(08:31:03 PM) crusk8: not through mutators

(08:34:12 PM) Bazlur Rahman: hmm but it has some complexity while implementing immutable object I think ..

(08:35:23 PM) crusk8: I’m not sure if immutable means that object can’t modify its own internal variables. while processing something internal settings can;t be changed

(08:35:43 PM) crusk8: or just that the outside world can’t change things directly

(08:36:12 PM) crusk8: I suppose only data could be local to the function

By the way,

Here I’m going to tell you some advantage and disadvantage of immutable object.


Protection : you can send and immutable object to any class without worrying about it being altered by that class and you never have to make defensive copy.

Thread safe: Its fully thread safe, any number of threads can access them simultaneously, without any synchronization.

Disadvantage :

Constructor injection : it requires constructor injection while you are going implement inversion of control. In immutable object, there is no way to use mutator.

Implementation complexity : its very much boring to implement immutable object.

Some worthy reading list:

10 Things about Design

  1. “Simplicity is the ultimate sophistication.” – da Vinci
  2. The best deliverable are prototypes.
  3. Sketching is the most effective design method.
  4. Creativity comes from everywhere.
  5. Design is writing.
  6. Interruption is the enemy of productivity.
  7. Being healthy leads to better work.ay
  8. A great culture is the byproduct of great behavior.
  9. Design is at the heart of great companies.
  10. Design is never done.

Courtesy: Joshua Kaufman



A list of really good user interface design resources

Here is the list of links I found from a question in Quora