Thursday 21 June 2012

Dependency Injection


I came across this problem when I was writing code for my product. We follow Test Driven Development as it suites our process. Well there are lots of benefits that you can get from Test Driven Development; I won’t dig deeper into that. But I faced lots of problems trying to adhere to this coding practice.

I had implemented this new interface and a private class that implements this interface. This new class was singleton.   Now the methods in this interface are used across many classes in many projects in the production code, all these classes are Unit tested. Since they unit tested, changing the code in these classes make things messier. But I had to take the pain of modifying the production code as well as the Unit test projects. But the tests still kept failing.

All I was trying to do is create a new interface pointer, and then use it across the class. I created this new interface pointer in the constructor of the classes that use this singleton class.

In the test class I was creating the interface pointer in the setup method of the class that use the singleton, but all the test cases were failing when I tried to call the interface’s methods in the test cases. The failed reason was null pointer. Now I couldn’t understand the reason for being null as the interface pointer is created in the setup method and setup method is definitely called every time.

One fine day I found out the actual root cause, the manner in which the interface pointer was getting created and passed was wrong. Since the new class was singleton, the object creation took place only when the production code was run, generally when you run the test cases the production code won’t get executed, hence the interface pointer was turning out to be null.

The solution for this is Dependency Injection. Since the test classes depended on the classes that used the new class and interface pointer was getting created in the constructor, I had to pass this pointer to the test cases. For the test cases to pass, I had to write a separate constructor with an extra parameter i.e. interface pointer. I am INJECTING the interface pointer so that the test cases ‘that DEPEND on it won’t fail.

So now in the test class, in the setup method, every time I created the production class’s object, I passed the interface’s pointer. After taking the pain of changing the code (again!), I finally managed to make the test cases pass.

Synchronization in Java

Synchronization refers to keeping multiple blocks in coherence with each other. The block that is surrounded by keyword synchronized can only be accessed by one entity at a time. When the entity requests access to the synchronized block and is granted access, a lock is set on the block. The lock gets released only when the entity that acquired the lock releases it. Synchronization is a must for mutual exclusion. In Java, implementing Synchronization is relatively simple compared to other programming languages. Synchronization in Java very important since Java supports multi-threading where multiple threads run in parallel to complete program execution. In a multi-threaded environment java object synchronization or class sync becomes very important

Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

Sample snippet for Synchronization in Java:

public class Count{
private static int count = 0;

public static synchronized int getCount(){
  return count;
}

public synchoronized setCount(int count){
   this.count = count;
}

}

Wednesday 20 June 2012

Asynchronous Pluggable Protocols


There are times in everyone’s life where you would have thought about customizing things that you are forced to use the pre-defined one. A custom made browser, an extension that you can call your own, your own IDE (Interface Development Environment) and so on.

If you have thought about creating your very own protocol on the line of http, https, etc. you have come to the right place.

You can create your own protocols and name it whatever you like, myprotocol, tiger, etc. and use the custom protocol in a similar way as http – tiger://google.com.

Microsoft provides an excellent way to help you create your own protocols. Enter Asynchronous Pluggable Protocols. Asynchronous Pluggable Protocols helps developers to create their own protocols; MIME filters that work with Microsoft’s Internet Explorer from version 4.0 and above.

You need to implement the IInterProtocolInfo interface for this purpose. Override the methods provided by this interface. One of the methods is ParseUrl; use this method to parse the URL, whether you are interested in processing it further. ParseUrl has the following form.

HRESULT ParseUrl(
    LPCWSTR pwzUrl,
    PARSEACTION ParseAction,
    DWORD dwParseFlags,
    LPWSTR pwzResult,
    DWORD cchResult,
    DWORD *pcchResult,
    DWORD dwReserved
);

The most important parameter is PARSEACTION, your methods needs to include switch case for each of the PARSEACTIONS.

The next important method is QueryInfo method. Use this method to decide which URL you wish to mark secured and others that you want to mark insecure so that the users of your application are notified about the same. QueryInfo has the following form

HRESULT QueryInfo(
    LPCWSTR pwzUrl,
    QUERYOPTION OueryOption,
    DWORD dwQueryFlags,
    LPVOID pBuffer,
    DWORD cbBuffer,
    DWORD *pcbBuf,
    DWORD dwReserved
);
 
Here the important parameter is QUERYOPTION. If you want your URL to pass through the IE security filter, then return TRUE for QUERY_CAN_NAVIGATE and QUERY_IS_SECURE.


Java Online Compiler


It's the On Demand day for us all today. So, we here at ThoughtMakers decided to come up with something that can benefit the Open Source community at the same time related to On Demand. So, here we are  with this cool Compile On Demand Java tool. We've hosted this on our ThoughtMakers website. So how does it work?

Well, the user just writes his code in the template we've provided and once done, clicks on "Compile". Our backend systems pulls the code and does what it has to do and streams the result over the browser and there you got the executed program.

So, how did we complete the jig-saw? Well, firstly, the HTML that posts contents to the backend server. The backend server reads the entire content which is the code and saves it locally making up a java file. The backend logic also knows to call system commands as batches and compiles the newly saved java file. Any error encountered is returned as stream and the same is given back to the user as html content. If all goes well and compilation is a success, the same is executed again by calling system commands as batches and the same is given back to the user as html.

Simple? Yes. Useful to the Community. Open Source it all.


Thank you folks.

Tuesday 19 June 2012

Fundas using Reflection

Reflection is one of the most powerful features in Java Programming language. You must be familiar with Object Oriented programming where you create blueprints called classes and make objects out of them, call instance methods using those objects or call static methods using the class.

Using Reflection, you can create objects from outside the class's namespace. In simple terms, you can create objects at runtime. Hypothetically, if at compile time there was a code to find out the number of objects for the class and if reflection's used, this code would fail. Reflection is so powerful that you would be able to hack into the class's methods and attributes. Below is a sample snippet which demonstrates Reflection

try
{
Class c = Class.forName("classname");     // Class handler
Field f = c.getField("fieldname");        // Get the field
Method m[] = c.getDeclaredMethods();    // Get all methods
}catch(Exception ex)
{
ex.printStackTrace();
}

The above was just a sample of Reflection's capabilities. For design a comprehensive Debugging tool, the best approach to go for is Reflection. This is because as an ideal case, a debugger must see the code from outside it's domain.

Reflection is also used to get all implemented Interfaces, finding out the superclass of a given class, getting information about constructors and much more.

Web Debugging using Fiddler.


Most of my day to day work involves working on Web Browsers (IE, Firefox, Chrome, etc). Many a times I am concerned over the data that is being transmitted from and to the Web browser. Sometime it becomes pain to figure the actual root cause of some issues related to Web browsers(Security issues, etc).

One of the tools that really help in indentifying the traffic from your web browser is Fiddler. Fiddler is web debugging tool that helps in identifying the information transmitted to and from the web browser. At runtime the traffic from WinINet’s HTTP(s) stack can be automatically directed through fiddler. All you have to do is start your fiddler, launch your web browser and then switch over to the fiddler to enjoy the transmission of the data over the net.

It can also be extended using .Net. So you can have your very own web debugger which you can play around with.

Enough said, try the fiddler here. Enjoy web debugging.

Monday 18 June 2012

Use Case for Hadoop

Well friends, Hadoop as we all know is a wonderful framework for handling bulk data. For those of you who haven't heard about Hadoop, here's a head's up about it:


Hadoop is a distributed system framework for handling huge amounts of data and is highly scalable. The scalability is the result of a Self-Healing High Bandwith Clustered Storage , known by the acronym of HDFS (Hadoop Distributed File System) and a specific fault-tolerant Distributed Processing, known as MapReduce.


Enough said, I had a use case to extract huge amounts of data in the form of IP Addresses. I had to crawl large number of sites and extract some data out of them. I thought why not use a distributed framework like that of Hadoop for accomplishing this task. Thank you Hadoop. You solved my problem quite easily without much of an effort. Friends, I tell you - Hadoop is a great way of leveraging the power of Distributed Systems.






PS: I love you HADOOP!



Do you like our Content?