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!



Browser Helper Objects: An introduction



Browser Helper Objects commonly called as BHO are, as name suggests, objects or components that helps you to utilize the browsers capabilities. It’s basically a dll (Dynamic Linked Library) that gets registered into your system, of course with your permission.

It’s basically a add-in to your browser. The most common browser helper object is the Google toolbar in Internet Explorer. You can search your queries directly from the toolbar. BHOs are used extensively by the marketing folks to pull in the advertisers. What they actually do is create BHOs that can track the traffic in one site. This piece of information is very useful for the advertisers looking for the users to a particular website.  They can track the information such as the kind of users, what they are interested in and so on.

There are lots of such BHOs today, collecting, tracking one information or the other.  Despite of being so helpful, a few can be malicious as well. Some BHOs gets installed in your system and then can take advantage of your browsing data. For example some BHOs are mainly interested in bank sites, where in the BHOs trap the user’s credentials and send it across to its owner/s.  I think you would know the rest of the story!

The BHO api (application programming interface) exposes loop holes and hooks that allows these malicious BHOs to access the page’s DOM (Document Object Model) which facilitates the BHO to control the page navigation
.
Microsoft provides apis for creating your own BHO.
In order to make sure your system does not fall prey to these malicious BHOs, you need to make sure you permit only trusted installations on your system.

Remember SECURITY is incomplete without “U”….

Sunday 17 June 2012

Power of Groovy and FreeMarker

Here I will tell you folks how Groovy and FreeMarker can be used to reduce the software turn around to a great extent. While working on enterprise applications, for coming up with your business logic you'd most probably work on technologies like Java, C++ or even Python. After building the logic, for the view part you would probably work on some GUI based languages for rendering the view. So, if you're responsible for developing both the Business layer and the View, you'd need to first build the business layer and then the view. It's not a parallel process. Yet another case would be you would only design the business layer and the UI programmers would design the view. In this case, the UI Programmers are still dependent on you. So, only after the Business layer development is complete will the UI programmers start building the view. Again, this is not a parallel development. 

Now pitches in Groovy and FreeMarker. Groovy is best suited for Java programmers as it drills down to a .class on compilation. It's got the power of both scripting and server side programming. FreeMarker is a template engine which renders wonderful view. So, here's the thing - The Server side programmers would develop their business logic at the same time while the UI Programmers develop their view. This enables parallel development. It reduces the total time for software produce to almost 50% less than what it used to be in earlier scenarios. 

Try out Groovy and FreeMarker and let me know if you like it and concur to the above.

Managed Debugging


Debugging is a process of analysing the dumps of the application. Dumps can be of different types-crash, hang, etc.  This debugging plays a major role in support of any product that any company ships. This also helps in determining the further improvements in the code base for future releases.

Debugging can be of two types-unmanaged and managed. Unmanaged is the one which involves the application written in unmanaged language for example C++ or VC++. Managed code on the hand involves the applications written in managed code-all supporting the .Net framework(C#, VB, etc.)

Unlike unmanaged debugging which involves analysing the dump files written in unmanaged code(C, C++), managed debugging is relatively easy. Most of the work will be done for you by the CLR (Common Language Runtime). Even the crashes, hangs are very limited in case of the managed application. Thanks to the CLR and the efficient Garbage collector provided by the .Net framework.

WinDbg is the tool that I generally use for debugging the crash, hang dumps. For managed debugging you will have to load the symbols first. You can do this using the following command.

.sympath SRV*D:\symbols*http://msdl.microsoft.com/download/symbols
This will load the Microsoft symbols.
Next process is to load the extension that provides the commands for managed debugging. This extension is called SOS. To load the extension use the following command
.loadby sos mscorwks
This will load the SOS extension. From now on you can use the command provided by the SOS for analysing the dump files.
You can find the commands here

Save your code from Java Decompilation

I took a break from the core, bottom-most almost hardware types kind of code - You know what I mean, to a little bit of securing my Java code. I used to work on a framework which was written in Java - A good one - robust, fast, highly scalable and even light. The problem with that framework was that it could easily be hacked - I mean decompiled. So, what I've seen many doing is, they rip code from such amazing frameworks and ship it as their own. I know it's not ethical but that's what happens many of times. So, how do you save yourself from such cheap yet occurring incidents of Java Code Decompilation? 


Of course from a bird's eye view, there needs to be some sort of locking implemented on your code or even encryption may be. To go about protecting your Java source code, we need obfuscators which helps us solve our problem. Obfuscators are good but really suck sometimes from the point of view of optimization. It's terrible that you write super optimized code and then pass it through some sorta machine and then it's all gone. It becomes junk again. So, while saving your code from decompilation, please do ensure that you're using the write obfuscator which still keeps your code optimized.


One another solution to protect your source code is to use Encrypted Jar Files. Well, I would not use this as a first option because of the process involved in encryption and decryption which is expensive. But well, this is a solution to save your code too!




Third option would be to compile your code directly to Platform specific Assembly. This destroys the entire motive of Java - Platform Independent. 


My Advice - Use a good obfuscator. Choose it wisely.




Here is Zelix Obfuscator which is good. Try it. Do some trials on various obfuscators and choose one which matches your code environment.



Saturday 2 June 2012

Improve Coding standards using Coding Kata


Improve Coding standards using Coding Kata

Kata means “form” in Japanese. Coding Kata is an approach where in you improve your coding standards, style, etc. by continuously working on a given problem. I know it is difficult to find time in your daily work routine, but trust me this will improve your coding to a great extent. (Try to find at least 1 hour per week for this, which would suffice).

Kata is generally used in Karate.  Karate has set of Kata. Kata are basically set of kicks and punches that you perform in a pattern. Idea behind this is to develop the pattern so thoroughly that, in emergencies you use technique to save yourself effectively. 

Similar to the karate, we use Kata in day to day programming. What you actually do is, follow certain standards, styles on a day to day basis so that you become thorough with this. Practice makes perfect. More you practice more thorough you become with this. When you face a real life problem, code automatically flows through you. And mind you, the code will be of good quality.

In order to learn or use TDD, we make use of Kata. The principle behind this is, you need to code the Test before coding the actual production code. Firstly, you will write failing test (what scenarios my code might fail) and then write the passing test (all success scenarios).

You start developing the test project. Gradually adding code to the production project that makes this test pass.  Eventually you will end up in the production code which is perfect (well almost!).  For example start with simple problems, for instance, Stack. Every week you try to improve the Stack. You should delete the previous week’s code and start afresh. 

Using TDD in your day to day work improves efficiency and makes the code more maintainable.

Data Structures with Java

Data Structures with Java

Today, I tried exploring the world of data structures using Java; it's time complexity, JVM's behavior when it comes to core dumps (as against c++). I found a very interesting part. I found that though there is no complexity of use of pointers in Java, it is very advantageous to use pointers while implementing non-linear data structures like Trees and Graphs. 

So, here's the question - How do I use simple, powerful language like Java but yet get the advantages of C++'s time optimization capabilities? One approach towards this is to use the Java's Native API. Though this still has overheads of two stack calls (One to load the library and the other to call the native function), I feel this approach is far better than actually implementing the data structure algorithm in Java.

Do you like our Content?