Things to consider before diving into Java Programming Language

I would like to point out a few things first –
  1. Java has the largest ecosystem among all the languages. So it may take you some time to get used to it. Give it 2 years, and it will be worth the effort. ( Though this should be true for every programming language)
  2. If you want to get quick output, I’m afraid, java is probably not the right tool for the job.
  3. Java is essentially a lower level language than other languages like Python or Ruby. You sacrifice some productivity, but gain a lot of finer control and substantial performance. But if you’re building smaller apps like blogs and such with limited performance requirements, Java may not be the best too.
  4. There is no black magic in Java ecosystem. If you want to do certain things using java, you really have to know in detail and it requires a good amount of time and continuous effort.
  5. Android is not Java. Android uses a small part of Java, but it’s far from true Java.
That being said, let me tell you some good things about Java.
  1. It has been 21 years since the first release. Almost all known problems in software development have been solved using Java. You will find anything and everything that can be solved using Java. This is a huge leverage. If you can’t figure out something, you really do not have to sweat, you will definitely find something on google .
  2. It’s open source, so you can read every bit of its source code.
  3. Some people always keep saying that Java is dead and all kinds of things, do not believe them. Honestly, they have no idea. All the large organizations are using Java and they will continue to do so. Most of the sophisticated enterprise software e.g. ( IBM, Google, Oracle, Facebook, Netflix, Amazon, eBay, Linkedin, Alibaba’s softwares), financial services, health and medical services, big data technologies, high-frequency trading software, scientific programs are written in Java. Do you think they will go disappear overnight? The answer is a big Noooo.
  4. Pay matters. Recent reports confirm Java programmers are among the highest paid programmers in the software industry. (true, google it) : http://www.indeed.com/salary/Java-Developer.html
  5. If you just know Java well enough, most other languages-technologies will be very easy for you, and some of them will take only a week to peek even. The reason is, most of the other technologies simply copied things from Java ecosystem. You will find a lot of similarities there.
  6. Java is the most popular language on Earth, you do not really have to worry about a job. Checkout: (Http://www.tiobe.com/tiobe_index?page=index)
  7. There are number of Java shops in Dhaka : https://www.facebook.com/notes/java-user-group-bangladesh-jugbd/list-of-company-at-dhaka-using-java/906671442712875
  8. A few more reasons to learn java: https://blogs.oracle.com/oracleuniversity/entry/10_reasons_why_you_should
Are you still here?

The magic word in Java : CAFEBABE

Java compiler compiles a Java Source code into bytecode and stores it in a .class file which is then get executed by JMV.

Well, we all know this, but do you know that all Java classes start with a magic word called – CAFE BABE ?

In case you’re curious and interested to know why, bear with my attempt to inform you something interesting.

Go to the vim(whatever editor you like to) and with the simple following java code.


public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello, world!");
    }
}

cafebabe1

Now compile it and open the HelloWorld.class in a hex editor –

$ javac HelloWorld.java

$ xxd HelloWorld.class

cafebabe2

Did you notice the CAFE BABE part ? If you open any java .class file with hex editor, you will find this magic word at the beginning.
Well its just a hexadecimal number which is 3405691582 in decimal.

(CAFEBABE)16 = (3405691582)10

But why it is so magical that it has to add in each class file is probably the most important question to be asked.

Well, James Gosling explained why: –

We used to go to lunch at a place called St Michael’s Alley.  According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big.  It was a pretty funky place that was definitely a Grateful Dead Kinda Place.  When Jerry died, they even put up a little Buddhist-esque shrine.  When we used to go there, we referred to the place as Cafe Dead.  Somewhere along the line it was noticed that this was a HEX number.  I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes.  I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after “CAFE” (it seemed to be a good theme) I hit on BABE and decided to use it.  At that time, it didn’t seem terribly important or destined to go anywhere but the trash-can of history.  So CAFEBABE  became the class file format, and CAFEDEAD was the persistent object format.  But the persistent object facility went away, and along with it went the use of CAFEDEAD – it was eventually replaced by RMI.

 

Reference :  http://radio-weblogs.com/0100490/2003/01/28.html

How to change the brightness of LCD display from command line in Ubuntu

Open your terminal and type this –

 $ xrandr -q | grep "connected" 

If you have multiple monitors, you will have output as –

VGA1 connected primary 1280x1024+1920+0 (normal left inverted right x axis y axis) 338mm x 270mm

HDMI1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 477mm x 268mm

here, VGA1 and HDMI1 are your display.

If you want to change the brightness of ‘VGA1’ type following

 $ xrandr --output LVDS1 --brightness 0.9

The brightness ranges from 0.0 to 1.0 and 1.0 means full black.

long/double are not atomic in Java

So I have been reading a lot of texts lately. Java Concurrency in Practice was probably one of the best book written for concurrent programming in Java. Though this book is written prior to Java 7, but it is still valid and did an excellent job explaining all the fundamentals.

While reading, I came across a paragraph entitled “Nonatomic 64-bit operations“. I actually never knew that in java 64-bit long and double values to be treated as two 32-bit values.  That means, a 64 bit write operation is basically performed as two separate 32-bit operations. This behavior can result in indeterminate values being read in code and that lacks atomicity.

According to the Java Language Specification (JSL-17.7)

For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.

Writes and reads of volatile long and double values are always atomic.
Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.
Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32-bit values. For efficiency’s sake, this behavior is implementation-specific; an implementation of the Java Virtual Machine is free to perform writes to long and double values atomically or in two parts.
Implementations of the Java Virtual Machine are encouraged to avoid splitting 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid possible complications.

So point is, in java, long and double aren’t’ thread safe. When multiple threads are going to access a long or a double value without synchronization, it can cause problems. To ensure atomic/thread safety, it is essential to use volatile to ensure changes made by one thread are visible to other threads. And that’s how we can ensure the read/write is atomic and thread safe.

However, If all reads and writes of 64-bit long and double values occur within a synchronized block, the atomicity of the read/write is guaranteed.

TL,DR

  • double and long in java aren’t’ thread safe.
  • Add volatile keyword before them to make sure atomic read/write, thread safety.

example –


private volatile long i = 0;

Custom JSON Deserialization with Jackson

We consume rest api as a json format and then unmarshal it to a POJO. Jackson’s org.codehaus.jackson.map.ObjectMapper “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) {
this.id = id;
return this;
}

public String getName() {
return name;
}

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

public String getEmail() {
return email;
}

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

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

And

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) {
this.id = id;
this.name = name;
this.contents = contents;
this.createdBy = createdBy;
}

public Program() {
}

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

public Program setName(String name) {
this.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;
}

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

Let’s serialize/marshal an object first.

User user = new User();
user.setId(1L);
user.setEmail("example@example.com");
user.setName("Bazlur Rahman");

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

ObjectMapper objectMapper = new ObjectMapper();

final String json = objectMapper.writeValueAsString(program);
System.out.println(json);

The above code will produce following josn-


{
"id": 1,
"name": "Program @# 1",
"createdBy": {
"id": 1,
"name": "Bazlur Rahman",
"email": "example@example.com"
},
"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\":\"example@example.com\"},\"contents\":\"Some contents\"}";

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

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;

import java.io.IOException;

public class ProgramDeserializer extends JsonDeserializer<Program> {
@Override
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();
user.setId(ownerId);

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());

mapper.registerModule(module);

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 : https://github.com/rokon12/json-deserializer

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 –

false
true

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 Integer.java class , you will find that there is a inner private class, IntegerCache.java 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.

So

 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
      myCache.setAccessible(true);//3

      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 ?

package com.bazlur.tips;

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 ?

package com.bazlur.tips;

import java.io.File;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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)
                .map(File::getName)
                .collect(Collectors.joining(", "));
        System.out.println(fileNames);
    }
}

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) {
    countDown(1_000_000_000);
}


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

    waitASecond();

    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 = {
  countDown(1000000000)
}

def waitASecond() = {}

def countDown(n: Int): Unit = {
  if (n == 0) return
  else {
    println(n + " ...")
    waitASecond()
    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)
         .forEach(System.out::println);

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


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

list.stream().count();

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


Double avarage = list.stream().collect(Collectors.averagingInt(item -> item));

4. I want to get complete summery of the list


IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(value -> value));

System.out.println(intSummaryStatistics);

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

5. Create a map out of the list


Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(p -> p, q -> q * 3));

System.out.println(map);

//{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 = randomInts.stream().reduce(Math::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) 
                .stream() 
                .filter(s -> s.startsWith("C")) 
                .count();


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

 Arrays.asList(names) 
                .stream() 
                .map(String::toUpperCase) 
                .sorted() 
                .forEach(System.out::println);

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) { 
        this.name = name; 
        return this; 
    } 
 
    public int getAge() { 
        return age; 
    } 
 
    public Person setAge(int age) { 
        this.age = age; 
        return this; 
    } 
 
    Person(String name, int age) { 
        this.name = name; 
        this.age = age; 
    } 
 
    @Override 
    public String toString() { 
        return name; 
    } 
} 

9 . I want to get persons  group by age

 
        Map<Integer, List<Person>> collect = persons 
                .stream() 
                .collect(Collectors.groupingBy(Person::getAge)); 

10  I want to get average age of all the persons

 
        Double collect1 = persons 
                .stream() 
                .collect(Collectors.averagingInt(Person::getAge)); 

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

 
        String sentence = persons.stream() 
                .filter(p -> p.getAge() >= 18) 
                .map(Person::getName) 
                .collect(Collectors.joining(" and ", " In Bangladesh ", " are of legal age for voting,")); 
 
        System.out.println(sentence); 
        // 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:-

DROP SCHEMA public
CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public
TO postgres;
GRANT ALL ON SCHEMA public
TO public;
COMMENT
ON SCHEMA public IS 'standard public schema';

it works like a charm.

For details, please visit: http://stackoverflow.com/a/21247009/893197

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: http://www.gradle.org/docs/current/userguide/installation.html

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 = 'com.bazlur.app'
// 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:  http://developer.android.com/training/load-data-background/setup-loader.html

 

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.

 


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

switch (loaderID) {
case URL_LOADER:
// 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
);
default:
return null;
}
}

 

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

 


@Override
    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>");
        sb.append("\n");
        sb.append("\n");

        sb.append("<table>");

        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";
                    break;

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

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

            sb.append("<tr>")
                    .append("<td>Phone Number: </td>")
                    .append("<td><strong>")
                    .append(phNumber)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Call Type:</td>")
                    .append("<td><strong>")
                    .append(dir)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Date & Time:</td>")
                    .append("<td><strong>")
                    .append(callDayTime)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<tr>")
                    .append("<td>Call Duration (Seconds):</td>")
                    .append("<td><strong>")
                    .append(callDuration)
                    .append("</strong></td>");
            sb.append("</tr>");
            sb.append("<br/>");
            sb.append("<br/>");
        }
        sb.append("</table>");

        managedCursor.close();

        callLogsTextView.setText(Html.fromHtml(sb.toString()));
    }

 

Output:

 

device-2014-04-17-013232

 

Full Source code:  https://github.com/rokon12/call-log

 

Reference: http://android2011dev.blogspot.com/2011/08/get-android-phone-call-historylog.html

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:

  1. http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/underst_jit.html
  2. http://pic.dhe.ibm.com/infocenter/java7sdk/v7r0/index.jsp?topic=%2Fcom.ibm.java.win.70.doc%2Fdiag%2Funderstanding%2Fjit_overview.html
  3. http://artiomg.blogspot.com/2011/10/just-in-time-compiler-jit-in-hotspot.html
  4. http://www.javaworld.com/article/2078635/enterprise-middleware/jvm-performance-optimization–part-2–compilers.html

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.

Screenshot_2014-02-24-23-18-07_framed

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.

output_llOElX

 

or watch in

NB: I have tested with IntelliJ IDEA 13.

Cheers!!

Update:  The plugin now available on Jet-brain plugin repository : http://plugins.jetbrains.com/plugin/7377?pr=idea

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.

Link: http://ormlite.com/sqlite_java_android_orm.shtml

RoboGuice

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.

Link: https://github.com/roboguice/roboguice/wiki

Log4Android

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

Link: https://github.com/oronno/log4android

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.

Link: http://loopj.com/android-async-http/

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.

Link: http://actionbarsherlock.com/

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);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }

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

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

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

    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);
        setText();
    }

    public int getTrimLength() {
        return trimLength;
    }
}

And add following line in your attr.xml

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

Put the following in your main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
 <com.rokonoid.widget.ExpandableTextView
 android:id="@+id/lorem_ipsum"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
 </LinearLayout>

And test your activity

package com.rokonoid.widget;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        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(R.id.lorem_ipsum);
        expandableTextView.setText(yourText);

    }
}

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

Introduction

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.

Background

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.

Problem

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

Solution

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

Table_Stores

So my first select query:

SELECT * FROM Stores

And Output:

SelectQuery

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:

WITH Temp AS
(
SELECT row_number() OVER (PARTITION BY
Slno
,Region
,Territory
,Town
,ShopName
,ShopAddress
,ShopType
,Slab
,Phone
,DmsCode
,Latitude
,Longitude ORDER BY DmsCode) AS RowNumber, *
FROM Stores
)SELECT * FROM Temp

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

SelectQuery

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:

WITH Temp AS
(
SELECT row_number() OVER (PARTITION BY
Slno
,Region
,Territory
,Town
,ShopName
,ShopAddress
,ShopType
,Slab
,Phone
,DmsCode
,Latitude
,Longitude
ORDER BY DmsCode) AS RowNumber, *
FROM nps_new.dbo.Stores
)
DELETE from Temp WHERE RowNumber >1
SELECT * FROM Stores ORDER BY DmsCode

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

Disclaimer:

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: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

 

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🙂🙂😀

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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(
proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));

String s = null;
while ((s = input.readLine()) != null) {
sb.append(s);
sb.append("\n");
}

while ((s = stdError.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
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");
 System.out.println(output);
 }

And output will in your console like:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
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.

 ic_luncher

Instruction:

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 http://code.google.com/p/dex2jar/downloads/list
  2. Extract dex2jar-version.zip to a folder. for example /home/codexplo/( for linux), or  C:\ (for windows)

unzip -x dex2jar-version.zip -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/d2j-dex2jar.sh /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 : http://code.google.com/p/dex2jar/wiki/UserGuide

How to enable usb debugging in ubuntu for nexus 7

get the terminal, type:

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

or

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. সুতরাং বুঝা যাচ্ছে ডিএনএস দি-ই-ই-ই-ই-ই-ই ইম্পট্যার্ন্ট!

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

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

এখন এটি তাহলে কিভাবে কাজ করে? আমারা যখন ব্রাউজারের এড্রেস বারে http://www.facebook.com লিখি, তখন ব্রাউজার এবং অপারেটিং সিস্টেম চিন্তা করবে, এর আইপি এড্রেস আগে তারা থেকে জানে কিনা(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 facebook.com 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: 173.252.110.27.

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

Pretty Cool, huh!!

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

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

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