Friday, November 21, 2014

How to implement an interface in a class but prohibit the class from implementing the interface methods in that class ?

Hi Friends,

Today I will present an interesting scenario in front of you . Normally we , most of the time will not come across such a scenario while coding . But there are exceptions and this happens to be ab exceptional exception that we should get to know.

Scenario :  Consider an interface K which has 2 methods in it : methA(), methB(). Now we need to have two classes A and B  in such a way that they will implement the interface K . But Class  A will only over ride methA() and Class B will implement methB() . How can we achieve that ?

Solution :

Normally when you implement an interface in a concrete class you will have to override the methods present in the interface otherwise the compiler will give an error . So  how we accomplish the  un accomplish-able like scenario stated above .

The answer is an Abstract Class . Yes , you heard it right : abstract class. An abstract class can implement an interface but it is not obliged to override any of the methods in the interface .

So for  our scenario , we can do it the following way :

public interface K {

public void methA();

public void methB();


Now we can  write our abstract class like this :

public abstract class A implements K{


You can check the above piece of code by running it in IDE of your choice (Eclipse, Netbeans etc). It will not throw any compiler error, because, an abstract class is not required  to override  any method in the interface , but it can if you want it to .

Hence, in this case, as we want to override methA() in class A, we can re organize Class A as :

public abstract class A implements K{

      public void methA(){




Now we can use the class B as a concrete class and have it extend B, like below :

public  class B extends A{


If you write just the above piece of code , the compiler will throw error and ask you to implement the un-implemented method methB(). That's because B is a concrete class and it implements K via A. Since, methA() is already overidden in class A , so the compiler asks the developer to override and implement methB() in class B.

In light of the above explanation we can organize the class B as :

public  class B extends A{

      public void methB(){




You can refer this stack overflow thread for more details :

That's it for today. Hopefully this will enlighten people who are not  aware of this concept .

Wednesday, November 19, 2014

Java 8 : Interfaces and Default Methods

Hi ,

Today I am going to post a bit about some of the exciting features of Java 8.

Pre-requisites  :

1> Install java 8 SDK
2> Install Eclipse Luna (Eclipse 4.4.1)

Without Eclipse Luna 4.4.1 , it will be very difficult to run programs in Java 8. So please download and install the Eclipse Luna Build .

So, let's get started with the good stuff .

Default Methods :

Now in java 8 , we can have methods with default signature in interface, which will have body logic or implementation logic . 

So, let's say I have an interface called Person below :

public interface Person {

default void sayHello() {
              System.out.println("Hello there in Person!");


As you can see if encapsulate a method name in the interface with default signature, you can add your logic in it.

Now what happens , when I have another interface with same method name but different implementation logic and I try to implement both of them in a single class ?

public interface Male {

default void sayHello() {
              System.out.println("Hi there in Male ");


My implementation class( is shown below :

As you can see, here the compile time error is thrown because the compiler is not understanding which "sayHello()" method it should implement.

So to resolve this ambiguity, we can override the sayHello() method in  the implementation class itself  like this :

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {



We can just call the appropriate / desired interface method directly inside .
To do this, we have to use the syntax : "Interface.super.methodname()"

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {



So a default method looks a lot like an abstract class implementation , does n't it ?
However, there is a subtle difference : An abstract class holds the state of its object as it can have constructors .But interfaces in java 8 with default methods cannot have constructors and as such cannot hold the state of an object. Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implement or classes.

That's all on interfaces from java 8 perspective .  I will come up with a new feature of Java 8 on my next post which will be related to Lambda Expressions .

Sunday, November 2, 2014

Different types of Locking in a threaded(multi or Uni) environment in Java

Hi friends,

I am back after a long hiatus. I became so wrapped up in several things that I forgot to share my experience here for a long time. Anyways, let's move forward with today's post.

Recently I delved into Java threading. In my experience , I did not come across a single web application that makes use of the java threading utilities(which is a shame really, since they are so versatile and useful; the other reason may be that they are bit tough to understand and implement). So , while going through different threading techniques, I stumbled upon a concept of threading called as locking. The more I read, the more confused I became. At last I was able to get myself out of such a tangled mess with some help. So here I will post about locking in a way that it's easy to understand .

What is Locking ?

Locking is a way in which a thread accesses a resource and tells other threads that they cannot access the same resource until he is done using it. So , that means when we use the synchronized keyword on a method or a code block , only one thread at a time can access it. Other threads will wait until the thread accessing it is finished with it's operation. That's called locking; means the resource is locked and no one else can access it unless it's unlocked for future use.

Types of Locking 

There are actually two types of locking:

1> Intrinsic Locking
2> Explicit Locking

Intrinsic locking are of different types like : Object level locking, class level locking and re entrant locking.

Object Level Locking :

Object level locking is using the synchronized key word on a non static method or a non static code block.So in such a type of locking, multiple threads will enter the class using different instances or objects of the class, but only one thread will have a lock on the method or the code block for a particular instance . This makes instance level data thread safe .

public class Death
    public synchronized void deathEaters(){} //non static method


public class Harbinger
    public void War(){
        synchronized (this) //non static code block

Class Level Locking :

Class level locking comes into play when synchronized key word is used on a static method or a static code block. That means at a given instance , if there are 100 threads, then only one thread can enter the method or code block. Other threads will be waiting . This comes into play because of  the nature of a static method. A static method is always available at class level and it is shared by all instances. Hence the need to have this type of locking here .

public class Death
    public synchronized static void deathEaters(){} // static method


public class Harbinger
    public static void War(){
        synchronized (Harbinger.class) //static code block

Re entrant locking :

This is an interesting concept. Synchronized methods are re entrant in nature .If a thread has lock on the monitor object using one synchronized method  and if another synchronized method requires to have the lock on the same monitor object then the thread can enter that method . That's why it is called re entrant ( the ability to re enter ) . Consider the following :

public class Famine{

public synchronized death(){

  public synchronized plague(){

If a thread enters death(), it has the lock on Famine object, so when it tries to execute plague() method, the thread is allowed to execute plague() method since it’s already holding the lock on the Famine object.

Explicit Locking :

Explicit locking is a way of introducing thread safety  without using synchronized keyword. Instead we can use the Lock API present in java.util.concurrent package to introduce locking.

public class Resource {
public void doResourcing(){
public void dologging(){

public class ExplicitLockingUsingSynchronized implements Runnable{
    private Resource resource;
public ExplicitLockingUsingSynchronized(Resource r){
        this.resource = r;
    public void run() {
        synchronized (resource) {

Now let's try this using the Lock API and we will remove the synchronized keyword.

public class ExplicitLockingImplementation implements Runnable{

    private Resource resource;
    private Lock lock;
    public ExplicitLockingImplementation(Resource r){
        this.resource = r;
        this.lock = new ReentrantLock();
    public void run() {
        try {
            if(lock.tryLock(10, TimeUnit.SECONDS)){
        } catch (InterruptedException e) {
            lock.unlock(); //release lock

Now do you see the difference : There a lot of  API related methods to help us with locking in the Lock API(for eg, usage of time out as I have shown here). It makes our job much, much easier . We can use a lot of conditions  and options using the lock API.

That's all on thread locking. I hope this will be very informative for people who are trying to understand the concept of locking in threads .

Tuesday, September 24, 2013

JAX WS SSL Configuration to solve wsdl certificate problems

Hi friends,

Back to you after a long time. This past 2 months , i had been crazy busy and hence, did  not  have enough time to discuss anything.

Today , i am going to discuss a very important topic. This is regarding the invocation of  a JAX-WS or JAX-RPC  service.

Some time back i was trying to invoke a JAX WS service from a stand alone java application (an application having a java class with the main method and having no application server at all). The problem was, every time i was trying to invoke any service operation, it was giving me a SSL CONFIGURATION EXCEPTION .

Now the reason behind it was that, every service call requires to validated . So how is that done ? It's done with the help of certificates. So what i  did was that, i got a hold of those certificates(the service i was using needed 2 of them) and integrated them with my java environment to make the WSDL hoster realize that it was a valid invocation.

My certificate names were cert1.cer and cert2.cer . And this how i integrated them in my  java  environment(In use RAD-Rational Application Developer) :

1. Place the below cry certificates in the path "C:\Program Files\IBM\SDP\jdk\jre\lib\security"

   cert1.cer, cert2.cer 

2. cacerts is the trusStore file. It's present in :
   C:/Program Files/IBM/SDP/jdk/jre/lib/security/cacerts

3. In command prompt perform the below execution :
C:\Program Files\IBM\SDP\jdk\jre\lib\security>"C:\Program Files\IBM\SDP\jdk\jre\bin\keytool" -import -alias cert1 -file cert1.cer -keystore cacerts

4. If it asks keystore password, mention changeit, which is the default keystore password

Enter keystore password: changeit

Trust this certificate? [no]:  yes
Certificate was added to keystore

5. Peform the steps 3 and 4 for the second certificate(cert2.cer).

And , i thought that was the end of it, but apparently it was not to be so. It seems , you have to configure the
""  in your program to make it work, and this is how you have got to do it :

System.setProperty("", "C:\\Program Files\\IBM\\SDP\\jdk\\jre\\lib\\security\\cacerts");
System.setProperty("", "changeit");

Now,the problem will be that the above piece of code will configure only the truststore, but that's not all; you have got to configure  the keystore as well. So for this , you have gotta add the following lines of code :

System.setProperty("", "C:\\Program Files\\IBM\\SDP\\jdk\\jre\\lib\\security\\cacerts");
System.setProperty("", "changeit");

And voila, everything will start working for you.
In case you are wondering how to add the certificates pro grammatically instead of adding them manually, then you can use this link :

THE UNIX WAY( no--check--certificates) :

Now if you are writing a shell script and you are invoking a particular operation of the web service , then you can actually tell the host not to validate the invocation for any certificates.
In my case, i normally use the CURL  command to do my bidding  , though other times it's the WGET command. So for example , my invocation of a service operation using a schell script will look something like this :

#! /bin/sh
if [ -n "${1}" ]; then

curl --silent \
     --data \
     @- \
     --header 'Content-Type: application/soap+xml; charset=utf-8' \
     --user-agent "" \
     ${ENDPOINT} <<EOF | xmllint --format -
<?xml version="1.0" encoding="utf-8"?>
    <CalcPrimeFactors xmlns="">

DON'T BE AFRAID  or alarmed , this is not a complicated code. Curl's just a command(you have to have it installed though in your linux distro), where you pass the end point and the request structure . Once that is done , this will give an out put , which for brevity , we can parse it using XMLLINT,  which is a command that parses the response in XML format. In case, you do not want to be validated for certificates, you just need to add the option no--check--certificates to the command invocation and you will get the response without   any  certificate hassles .

In my case, the output looks like this :

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="" xmlns:xsi="" xmlns:xsd="">
    <CalcPrimeFactorsResponse xmlns="">
      <CalcPrimeFactorsResult>2 3 3 5 3607 3803</CalcPrimeFactorsResult>

Hope this will be  fun to know for you all as it was for me.
Good bye.

Saturday, July 13, 2013

The magic of CSSPIE3 library

Hi friends,

Today i am gonna talk about an interesting tidbit that i came to know very recently.

The Problem :

I was working on installing a gradient for a page. For mozilla, the gradient was written as :

background: linear-gradient(to bottom, #ffffff 18%,#ecedeb 18%,#d1d5d0 100%);

And the pictorial view of that block of code comes up as something like this :

As you can see from above that the effect of the block of code is : the thick continuous red line that borders the element .

Now linear gradient cannot be used for the browser like IE8, as IE8 does not understand what it is. Hence we need to use filter here like :

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#d1d5d0',GradientType=0 );

The element gradientType = 0 signifies that we here are talking about a linear gradient. That's how IE understands a linear gradient. Now the problem with that is, once such a style is implemented, IE super  imposes that with it's own styles, thus marring the whole effect , like in here :

As you can see from the picture above we get discontinuous red lines even after applying the filter.
So for a long time i was languishing under the knowledge that IE 8 is not letting me bring up the gradient properly.

Reason :

The problem with using filters is that they are old pieces of code of a bygone era. They are not very reliable/good. No one really used them until recently when we got first class gradients/opacity etc. IE's old filter styles are well known for having major bugs and quirks. Hence  i was pondering on the possible solutions when i suddenly came across the CSSPIE3  library.

The way out :

CSS3Pie library is a little Javascript lib that tries to add a few standard CSS features to old IE versions, including CSS gradients. It works internally by using VML graphics, not filter styles, which means that you don't get the bugs thatfilter causes . Hence all i needed to do here was use the linear gradient and couple it to PIE.js. 

I downloaded the PIE.js from : .

Now to use it , first i described my style in jsp inside a class like :

<Style type="text/css">

     background: linear-gradient(to bottom, #ffffff 18%,#ecedeb 18%,#d1d5d0 100%);


In my jsp , i referred to it as :

<td class='ieMasterStyle'>Border</td>

Now calling this one is a bit tricky and it is a two step process :

STEP 1 :

Include the PIE.js script in your page, surrounded by a conditional comment to prevent it from being downloaded in other browsers:

<!--[if IE]>
<script type="text/javascript" src="path/to/PIE.js"></script>


or, in case, you don't want to download it , but just want to refer it from a CDN than do this :

<!--[if IE]>
<script type="text/javascript" src=""></script>

NOTE : Remeber to use PIE.js version 1.0 as it's the most stable version around.

STEP 2 :

Invoke the PIE.attach(el) function for each element that needs CSS3 styling. Make sure you do this after the page's DOM has been fully loaded. For example, using jQuery:

$(function() {
    if (window.PIE) {
        $('.ieMasterStyle').each(function() {

As you can see from above , i have fed the ieMasterStyle that i created directly o PIE.js, where in the PIE.js will do it's magic and apply the linear gradient for us . Hence the finished product in IE 8 looks like this :

And thus i achieved browser consitency and PIE.js saved my bacon.

That's it guys. Bye .

Thursday, July 4, 2013

Android : Layouts

Back to you guys after a long time. From today we will go inside in depth of android features and try to learn some new stuff along the way . The next few days, we will feverishly try to cover a lot of topics pertaining to android.  So let's get cracking .

What's an android layout ?

Well, a lay out is what it actually means. It's the main UI of your app and will contain several UI controls of your app. You can define your lay out height, width and orientation , add text views , buttons etc and when you run the app , all of them will come up in your app UI . Layouts are presented in XML. When you first create a layout, the main.xml  is created. In case you are wondering that's your lay out .

This is how a typical layout is created :

<LinearLayout  xmlns:android=""
    android:orientation="vertical" >
        android:text="@string/hello_world" />

        android:text="@string/hello_world" />

</LinearLayout >

I know, i know, you are very confused . Let's break it up then :

1> fill_parent --> means fill the parent window

2> vertical --> That's your typical orientation , you can specify 'horizontal' as well and no one will kill you.

3> wrap_content --> means wrap the content , kind of works like html wrap attribute, quite cool , huh !

Okay, kidding aside, these are very important attributes that define your layout, which means they tell your mobile / tablet that this is the way you want the app to be shown .

So let's run this one in eclipse, once we do that , this is what we will get in the emulator :

If  you look clearly up above , you will see the hello world string is coming twice and vertically one below the other. It's coming twice because we have two text views and vertically because the  orientation is vertical, duh......

So there you's been laid out for you. Till next time ....

Saturday, April 27, 2013

How to Set up an environment for Android Development

Hi friends,

Back to you after a long time. Today we are going to look into a very important technology  namely : Android. 

Now the android programming language is very useful for app development . A lot  of us want to be app developers but we are not sure about how to progress.  Well the upcoming few weeks , we will look deeply into this technology and try to learn a lot of things.

However, what good is this , if we don't have an application development environment to test what we have learnt ? So i am gonna tell you how how to set up a local work space for Android . Hang tight.

For the most part, you'll figure out pretty quickly through trial and error what you'll need. If you're using Eclipse, it will yell at you when you're missing things, and you simply find what you're missing in the SDK Manager and install it.
That said, here's what I needed to get up and running with a very basic setup (this assumes using Android 4.1, if you plan on building for an earlier version, then you'll need to download the corresponding libraries from that version):
  • SDK Platform
  • ARM EABI v7a System Image (optional, you can also grab the Intel x86 Atom and/or Mips System images if you plan on developing for one of those platforms; ARM is the default, from what I've seen)
  • Android SDK Platform-tools
You get these simply by going to the Android SDK Manager (your SDK folder/tools/android; or click the "SDK Manager" button in Eclipse), selecting what you need, and clicking "Install Packages". Once you do that, you can follow the rest of the guide that you linked for building your first app (I highly recommend it, it's extraordinarily beneficial), and your app should run with no problem.

Here's a snapshot to get you started :

Now all you gotta do , is install the packages that I have checked in and that creates your basic set up. The other stuff you can install later.

Hope that was useful. Very soon we will dive in to the world of Android.

Good Bye .

Sunday, April 7, 2013


Hi friends,

Today  we are gonna go in  a different direction . After some time , i thought of coming out with a series of tutorials on BASH scripting , which is a must if you wanna write complex scripts. My try outs here will
consist of commands written in UBUNTU 12.04 PP LTS as this is what i am using right now. So let us open up our terminal and begin our wonderful journey :

Finding out where the inbuilt commands lie :

Type :
bash$ : cd /bin
bash$/bin : ls

Creating my own directory and seeing the permissions it has :
mkdir kunal
ls -ld kunal → drwxrwxr-x 2 atri atri 4096 Apr 3 02:00 kunal

Consider these shell operations :

Consider the next set of shell commands :

How to make use of manual in Unix :
bash$ : man man
O/P :

What if we give :
bash$ : man cp

What is Shebang ? :

The shebang is the first line in a script because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file. If these are #! the rest of the line is interpreted as the executable to run and with the script file available to that program on stdin. Since the kernel will only look at the first two characters and has no notion of further lines, you must place the hash bang in line 1.
Let us consider the script below :

This script does a listing of files and in between the first and last listing , it tries to read a file. So if you try to execute the file without changing its permissions it won't run. Hence first you gotta do this :

bash $ : ls -lrt yourFile --> get the available permissions
bash $ : chmod a+x yourFile --> make the file executable.
Voila, now you are ready to run it. Just do :
bash $ :  ./yourFile


bash $: sh

That's  all for today. Next time we will delve deeper .

Good Bye .

Wednesday, March 13, 2013

Keeping a healthy Mind and Body

Hi Friends,

I am back again. These upcoming weeks we will look into various aspects of different technologies.
However, before doing that i thought i will publish this article.

The last few weeks had been the worst days of my life. Why ? Because  I had been ill. So here goes :

I know all of us are busy doing this and that. But if we do not keep a healthy body, none of this will matter. So listen to what i have got to say here as it is more important than all the articles that i have published during my life time.

As we get older the body’s tissues and organs start to work less efficiently. We have to work harder and harder to stay fit and active. But keeping well is also about anticipating what’s increasingly likely to go wrong, and taking steps to prevent harmful events from happening. This may mean not just eating the right foods and taking regular exercise, but also changing your living environment and watching out for possible dangers.
Preventative tactics are particularly important because our health doesn't just decline in a gradual way. Instead what’s often more important is a step-by-step decline on top of a slow deterioration in health. Every so often we have a major illness or event from which we never quite recover to previous levels of fitness. The most common causes include:
As we get older we have more and more of these acute episodes of illness and drop further and further back down the scale of general health. If we could dodge the acute illness we could stay well for longer even as ageing takes a general toll.

Listed below are ten essential elements of good health. If you take all of the actions listed below, you will be much healthier.

  • Eat a Healthy Breakfast
  • Drink at Least 8 Glasses of Water
  • Take a Good Quality Multiple Vitamin/Mineral
  • Connect with Other People
  • Express Your Emotions Appropriately
  • Eat Fruits and Vegetables
  • Spend at Least 30 Minutes Outdoors
  • Do Something Physically Active
  • Take Some Quiet Time for Yourself
  • Keep Regular Sleep Hours
  • Establish a Relationship with a Doctor You Can Trust

Lastly, this is helping me a lot : Meditate properly for at least half an hour.

Hence try to keep yourself healthy folks. This is the primary wealth for which you are fighting with the world. 

Sunday, February 17, 2013

Google glasses augmenting our reality

I have always wanted to write an article about the google glasses. Today I got a chance and hence here goes .

What is Augmented Reality :

Huh, i feel like i am in a new world, though everything around looks the same.

You may think you don’t know “augmented reality” but unconsciously dealing with it everyday. It is found in computer games. news cast, television shows, sports live telecast etc. Its a new way of presenting physical reality plus virtual reality.This is not a new technology. In fact, it was first introduced in 1990.

Augmented reality (AR) is a term for a live direct or an indirect view of a physical, real-world environment whose elements are augmented by computer-generated sensory input, such as sound or graphics.

Where is Augmented Reality Used :

1.  There are a lot of applications or uses of augmented reality today it helps ease our way of life. Lets start with American Football. When you watch a football game on tv, you may wonder a yellow line (super imposed first down line) which looks amazing because it adjusts by itself as the downs change.

2.  In February 2009, at the TED conference, Pattie Maes and Pranav Mistry presented their augmented-reality system, which they developed as part of MIT Media Lab’s Fluid Interfaces Group. They call it Sixth Sense, and it relies on some basic components that are found in many augmented reality systems:

Small projector

These components are strung together in a lanyard-like apparatus that the user wears around his neck. The user also wears four colored caps on the fingers, and these caps are used to manipulate the images that the projector emits.

The image above demonstrates augmented reality in action, dialing a phone pad projected to your hand and phone a friend. This is part of the Sixth sense augmented reality systems.

3.  A more advanced application of Augmented reality. This was viewed on a digital camera capable of AR. When you point out a building or certain location, it provides you information on restaurants, shops etc information available on that area. This is the same augmented reality being advertised by Samsung Galaxy Tab as its key features.

4.  Augmented reality is also used on medical operations where its difficult to identify organs on a difficult and bloody situations.

5. AR displays can be rendered on devices resembling eyeglasses. Versions include eye wear that employ cameras to intercept the real world view and re-display its augmented view through the eye pieces and devices in which the AR imagery is projected through or reflected off the surfaces of the eye wear lens pieces. This is where google glasses come handy .

Google Glasses :

It All started with Project Glass :

Project Glass is a research and development program by Google to develop an augmented reality head-mounted display (HMD). Project Glass products would display information in smartphone-like format hands-free and could interact with the Internet via natural language voice commands.The prototype's functionality and minimalist appearance (aluminium strip with 2 nose pads) has been compared to Steve Mann's Eye Tap. The operating system software used in the glasses will be Google's Android.

The New York Times originally reported that the glasses would be available to the public for "around the cost of current smartphones" by the end of 2012,but other reports have stated that the glasses are not expected to be available for purchase soon.The product (Google Glass Explorer Edition) will be available to United States Google I/O developers for $1,500, to be delivered in early 2013, while a consumer version is slated to be ready within a year of that.

So , in a very near future you are going to get your hands on google glasses and i am sure they are gonna change the way we view our world.