Java Code Geeks

Monday, December 29, 2014

Why Scala is hard to grasp for Java developers

Scala is a multi-paradigm language. It has characteristics of object oriented programming, functional programming, meta programming (language oriented programming or DSL). So a java programmer might write scala code which looks completely different than a Clojure or Haskell programmer writing the same scala code. This is because java developer might use more of Java style (mutable variables, for loops) whereas the developers from functional programming style might use more of functional aspect of scala.
Here is a sample example, different ways to calculate sum  of a List of Double.

 class Test {  
  def sum(data : List[Double]) : Double = {  
   //uses a mutable variable to produce the sum, this is most of the java developer might use  
   //but it is not the best way to do so. Because most of the functional language does not like  
   //to have mutable variable  
   var sum : Double = 0  
   data.foreach( v => sum = sum+v)  
   //Fold and Reduce are two techniques calculate the value at one shot (without mutable variable)  
   val totalSum = data.foldLeft(0.0D){ (total,n) =>  
    total + n  
   }  
   val anotherSum = data.reduceLeft[Double]{(acc,n) =>  
    acc + n  
   }  
   //now short hand of fold and reduce. Underscore is positionally matched arg  
   val yetAnotherSum = data.foldLeft(0.0D)(_+_)  
   println("Sum = " + sum + " total sum = " + totalSum + " and another sum = " + anotherSum + " yet another sum = " + yetAnotherSum)  
   return sum  
  }  
 }  

As a result, a new developer gets confused which is the right way of doing thing. Think that you write a piece of code and gave it for review and even reviewers fight over the right way of doing it.

Overall as a rule of thumb, I think it is better if we consider Scala as a "functional language" and try to use the best practices from functional world. This is why I have started advising Java developers to learn one functional language like Haskell or Clojure before picking up the "Scala" book. This tunes java developers mind towards functional world and come out of habits of using mutable variables or explicit for loops.

This is however a delicate topic and would love to hear more from users who transformed from Java to scala developer.

Thursday, July 24, 2014

Spring Annotations vs xml configurations

I faced this question myself while working on projects. There are many school of thoughts on this topic, however after practicing both the styles, I have come to a point where I can compile a list of guidelines when to use one vs the other. Here is my guideline


  1. If you follow clean architecture principles, you must have heard uncle Bob repeatedly saying "A good architecture allows us to defer critical decisions like UI,framework,database etc". If you want to use spring as a framework to manage dependencies among your beans, do you want to minimize spring dependencies or want to move out of spring framework in the future? If yes, then go for XML which externalizes the configurations. But then in real world, I have not seen any big project that started as a spring project and then later got converted to a JEE project, so if you are spring shop, no problem to use annotations.
  2. Are you writing a library/API which will be used by many teams? In that case, it is easier for everyone to read and understand the XML config. All the bean dependencies are in one place so it is easier to understand rather than downloading the source code of your library from maven repo and go through the code/annotations.
  3. If you need to use spring transactions, I recommend to use annotation. It is hard for a developer to understand that your methods need transaction if that is externalized to a XML config, rather if it is annotated in your class/methods that is easier to follow and understand.
  4. If it is a considerable size of a project and you care for application startup time, then pay attention to context component scan. It may take long time for spring to scan your classpath, read annotations to load all the annotated beans and their autowired dependencies. 
Conclusion
So both the methods are useful and that is why both of them are supported. Choose one over other or choose both according to your need. You can of course mix both the approaches in one project.

Wednesday, July 23, 2014

Discussion around TDD

Recently there have been quite a few discussions on TDD, its usefulness and whether it helps in design or not. It first started from a blog post from David Heinemeier Hansson(creator of Ruby on Rails) - TDD is dead. Later it became more interesting when David, Martin Fowler and Kent Beck (writer of Junit) started a discussion on google plus. The videos for this series can be found here .
Whether you are practicing TDD or not, I think this is a very good discussion to listen to.  

Sunday, August 19, 2012

When to use java refection

Recently I faced with this question when to use java reflection? Many frameworks use it but we still keep saying do not use it in day to day work.  What's the real deal with it?
There are some real problems with using reflection,  java reflection is a hack from java compiler perspective. Reflection takes away all the compile time type checking of java and makes it more like a dynamic programming language. So compiler does not able to catch errors at the compile time but errors are thrown at the runtime. No IDE can refactor code written with reflection. If you refactor and change the signature of  the method, build will be fine but at runtime the code can fail because some code was using reflection to invoke the method with its old signature. These are some real reasons why we try to stay away from reflection. Above all of these there are performance issues also. Direct method call may be two to fifty times faster than the reflection counterpart, this is however very use case specific but in general, code with reflection runs slower on JVM.
But reflection is a powerful technique and it has a very clear use case. At the time of compilation if component A has no knowledge of component B but at the runtime, A wants to use classes of B, then A needs to use reflection. Example, Junit framework has no idea what test classes we are going to develop, so it needs to use reflection to understand the test class and methods. Hope this will clear the doubts in your mind as when to use reflection and not.

Tuesday, July 10, 2012

Client Side rendering - the new MVC

Client side rendering is getting popular now a days. Let me give a little bit of background and share my view that client side rendering is a good thing.
In pre historic days when MVC was not much popular, people used to write simple javascript to render a HTML page. However, managing this form of page is hard, because if you want to do a simple test like give 10%age of your users a new look and feel of the page to test whether people will like that new UI, will make all if - then - else statements inside of the javascript. As the requirements get complex, the UI get complex and javascript becomes unmanageable.
Then comes MVC world, where view layer is clearly a seperate layer managed in the server. Like some uses JSP as the view layer or template engines like Velocity as the view layer. For a velocity type of engine, UI developer writes the skeleton of the HTML page, server sends the model (data) and the template to the template engine and template engine renders the final HTML by merging the template with the data. Spring provides integrations with such template engines to resolve the views. This was a good strategy untill Ajax came into picture. In case of Ajax, the basic webpage loads fast and then lots of small fragmented request goes to the server and server sends back smaller data set back to the client. Now usually serer sends back small JSON objects and there needs to be some unit at the client side which will read this JSON and render the HTML. This pushed the concept of template engines to the client side.
Client side template engine like dust.js or mustach has similar concept like velocity template, they take the template and the data as the input and renders the HTML. Only difference is that it happens at the front end and not at the back end. One can push this concept little further and instead of the using Ajax, from the first request itself, they can use client side rendering. The flow goes something like this -

  1. User request the webpage on the browser
  2. webpage sends the request to the server
  3. server send back a basic html which has reference to the client side template js and the precompiled js files
  4. Server does not close the connection, but keep flushing JSON data as and when ready to the same client connection
  5. On the client side, template engines take the template name and the JSON data and renders them
Some useful things are happening here -
  1.  Load on the server reduces as the server is not merging the template with the data, its the client side browsers that are doing it. So this solution is scalable as the server load goes down
  2. Since javascripts can be cached by the browsers, so once the page is loaded, sub sequent operations on the page becomes faster as the template engine and the pre compiled javascript templates are already loaded in the browser memory.

Monday, July 9, 2012

Why business logic should not be in database stored procedures

Couple of years back I worked on a project which is database intensive. It was so much database intensive that most of the business logic were written in database stored procedures. Java code was a thin wrapper on this which used to call these procedures. There are lot of things that go wrong with this model of application development. While in all these years I had this in mind that it is bad to develop software whose all the knowledge is in the procedures but I could not itemize my thoughts exactly whats wrong with this approach. Fortunately Pramod Sadalage from ThoughtWorks have given it the details (http://www.sadalage.com/)- here are the below reasons why
  • Writing stored procedure code is fraught with danger as there are no modern IDE's that support refactoring, provide code smells like "variable not used", "variable out of scope".
  • Finding usages of a given stored procedure or function usually means doing a text search of the whole code base for the name of the function or stored procedure, so refactoring to change name is painful, which means names that do not make any sense are propagated, causing pain and loss of developer productivity
  • When coding of stored procedures is done, you need a database to compile the code, this usually means a large database install on your desktop or laptop the other option being to connect to the central database server, again this leads to developers having to carry a lot of dependent systems just to compile their code, this can to solved by database vendors providing a way to compile the code outside of the database.
  • Code complexity tools, PMD metrics, Checkstyle etc type of tools are very rare to find for stored procedures, thus making the visualization of metrics around the stored procedure code almost impossible or very hard
  • Unit testing stored procedures using *Unit testing frameworks out there like pl/sql unit, ounit, tsql unit is hard, since these frameworks need to be run inside the database and integrating them with Continuous Integration further exasperates the problems
  • Order or creation of stored procedures becomes important as you start creating lots of stored procedures and they become interdependent. While creating them in a brand new database, there are false notifications thrown around about missing stored procedures, usually to get around this problem, I have seen a master list of ordered stored procedures for creation maintained by the team or just recompile all stored procedures once they are created "ALTER RECOMPILE" was built for this. Both of these solutions have their own overhead.
  • While running CPU intensive stored procedures, the database engine is the only machine (like JVM) available for the code to run, so if you want to start more processes so that we can handle more requests, its not possible without a database engine. So the only solution left is to get a bigger box (Vertical Scaling)

Sunday, March 6, 2011

Spring Session Scoped Bean

Somehow my experience with spring was limited so far in my career. Its just that for last one year, I have been using Spring extensively. I recently used Spring's Session Scope beans. We most of the time use Singleton bean or the Prototype beans but session scoped beans are very useful in those use cases where you need to create an object per httpsession. For example, the shopping cart object which holds the list of shopping goods that a customer is buying. We can of course do this manually by creating a new Cart object per user session, however what if the lifecycle of such objects can be controlled by outside IOC containers like Spring? Yes, Spring Session and Request scoped beans are just for that, to create an object and bind that to each unique session/request.
Now the question really comes how to test such a bean in JUnit test cases? One way to test is - test just the functionality of the bean, but if I was more interested in to find out that Spring really does create object per sessions and can maintain the lifecycle of such beans. I created test cases to create a mock httpseesion and httprequest objects and fake one http user session.

Here are the steps to get session scoped beans in Junit test cases
1) Create one Session aware Application context which is XmlWebApplicationContext
2) Create mock session and mock httprequest
3) Write test cases to get the session scoped beans and write the necessary test cases
4) tear down the httpsession and request.




public class AbstractSessionTest extends TestCase {
protected XmlWebApplicationContext ctx;
protected MockHttpSession session;
protected MockHttpServletRequest request;

protected String[] getConfigLocations() {
return new String[] { "file:src/test/resources/test-context.xml" };
}

@BeforeTest
protected void setUp() throws Exception {
super.setUp();
ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(getConfigLocations());
ctx.setServletContext(new MockServletContext(""));
ctx.refresh();
createSession();
createRequest();
// set the session attributes that the bean might look for?
session.setAttribute("varname","value")
}
protected void createSession() {
session = new MockHttpSession(ctx.getServletContext());
}

protected void endSession() {
session.clearAttributes();
session = null;
}

protected void createRequest() {

request = new MockHttpServletRequest();
request.setSession(session);
request.setMethod("GET");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(
request));
}

protected void endRequest() {
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.requestCompleted();
RequestContextHolder.resetRequestAttributes();
request = null;

}

@AfterTest
public void tearDown() {
endRequest();
endSession();
}
}


One more useful tips here is - how to access the session variables from the Session Scoped beans? Well the friend here is RequestContextHolder. Using this - we can get hold of the httpsession inside of the bean and we can access any variables that was bound to this session in some http filter or any upper layer which might want to put session scoped variables to indicate one user specific data.


ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(false); // true == allow create
String value= (String)session.getAttribute("varname");

Saturday, September 4, 2010

My experience with some of the famous anti patterns in Software

There are two anti patterns that most of the software companies suffer from. These two anti patterns are so deep in the lifecycle of a software company that at times it becomes impossible to get rid of them.
If you ever work with a DBA who has more than 10 years of experience, you will notice one thing - they usually think anything and everything can be solved using Relational database system. I am not against relational database, it is the best thing that has ever happened to software. The concepts of relational database is solid and full proof, although this does not mean we should always think of database to solve any problems. If the data that is going to get stored in the database is not of relational in nature, why to force it to be stored in a relational database? This is what exactly google found out and came out of BigTable which is essentially a key/value pair (or hashtable). This anti pattern is known as "Golden Hammer" anti pattern. I can bet even many of us are suffering from this anti pattern. For example, in the next team meeting when someone tells you a problem, watch out what is your response? Are you offering the same solution to many different problems? Like one of my ex-colleague knew Hibernate very well, any problem you mention to him, there is a large chance he will apply hibernate to solve that problem !! Like one core Java developer will try to use Java to parse log files instead of 10 lines of Perl code ? Like one JEE developer uses EJB always whether it is required or not?One of my friend told me once that he is always using handful of "design patterns" though he knowns them all !!

One can be free from this anti pattern only if she knows many languages, many technologies and more importantly if she follows Richard Feynman's philosophy of leading life with an open palm. If we do not lock ourselves into favorites and make room for new ideas, then only we can be free from this anti pattern.

There is one more anti pattern which can be found at the team or organization level than that of at the individuals. It is called "vendor lock-in". Like one shop might be completely into Oracle database and using Oracle pl/sql procedure with business logics into it. Once I worked for a team where everyone from director to junior developer were comfortable writing business logics in the pl/sql code instead of at the application layer using Java or .Net. When I mentioned this to the director that it might become very costly if tomorrow your organization thinks they are not going to do any business with Oracle anymore, what will happen to all these code ? You might have to port them to Sybase or some other database vendor, instead, keep the logic at the application layer. He almost looked at me as if I am an alien and I do not know anything about how software works.

These are the reasons for which I like google. This is the only company that tries to keep an "open palm" strategy and comes up with their own systems - like Bigtable for their database.
To be a better software developer or architect, we should learn not to create favorites and keep an open mind so that we can welcome new ideas.

Sunday, July 25, 2010

Java Lazy initialization and Double Check Locking

According to the post at the javaworld, the double check locking is broken. I agree with the author, lets see what is double-check-locking idiom.
The below code snippet is usually used to initiate some private member variables lazily.



class SomeClass {
  private Resource resource = null;
   public Resource getResource() {
     if (resource == null)
     resource = new Resource();
     return resource;
   }
}

This is a very common use case, for example most of the time, your code might not need to use resource, so why to initiate this variable if it is too costly. Instead only initiate it when necessary.
This however will not work for multi-threaded applications, as there is a potential race condition. Two threads can see that resource is null and one thread override the resource variable initiated by another thread. Simple solution is to use Synchronized access, like

class SomeClass {
   private Resource resource = null;
   public Resource Synchronized getResource() {
     if (resource == null)
     resource = new Resource();
     return resource;
   }
}

But this is now slow because whether the resource is already being initiated or not, any calls to getReource will synchronized all the threads.
The smarter solution is to use Double Checking idiom something like this -



class SomeClass {
   private volatile Resource resource = null;
   public Resource getResource() {
     if (resource == null) {
     synchronized {
       if (resource == null)
       resource = new Resource();
     }
     }
     return resource;
   }
}

However, because of the Memory model of JAVA specification, the above mentioned code might work in one JVM but might fail at times. If you remove the volatile keyword, it is definitely broken, but even if you keep the volatile keyword, it is not certain that it will work.
So what is the solution ? The author at the javaworld mentions that we should avoid the lazy initialization and the following code -



class SomeClass {
   public static Resource resource = new Resource();
}


But the problem with this code is - whether you need or not, resource will be always initialized.

According to me, better way to use lazy initialization is to use "holder-class" idiom as explained in Effective Java by Joshua Bloch. It works like this -


class SomeClass {
   private static class FieldHolder {
     static final Resource field = new Resource();
   }
   public Resource getResource() {
     return FieldHolder.field;
   }
}


There is no synchronization, so no added cost. When the getResource method will be called for the very first time, it initiates the FieldHolder class for the very first time.

Monday, June 14, 2010

Cloud computing and the responsibility of a developer

Cloud computing is not anything new. But if we ask a developer what is that she is doing to make sure her application can take the advantages of cloud, we might not get a very definitive answer. I was also not sure of the definitive rules to be followed/adopted to develop better software to make use of cloud env.

Well, here is a very nice study guide for all of us - Building cloud-ready, multicore-friendly applications- The concepts are not new, but it is a very nice reading to understand how stateless, atomic, idempotent, parallel code can make use of cloud effectively. This is a two series paper which is a must read for developers.

Friday, June 4, 2010

Its all about the Neo - the singleton

Singleton is one of the most commonly used design pattern. However, a great deal of attention is required to make it right.
The invariant of singleton is to make sure - there is one instance of the object present always. This sounds simple and looks
like make the constructor private and have a private static final instance member variable is enough to create a singleton. But what if the object needs to be Serializable ? The moment someone makes the singleton object serializable, upon deserialization, you get another instance of it. So we need to provide readResolve() throws ObjectStreamException method to fix that.
The simple implementation of singleton is

public class SingleObject {

private static SingleObject INSTANCE = new SingleObject();
private SingleObject()
{
}
public static SingleObject getInstance() {
return INSTANCE;
}
}

This is proper but as the INSTANCE is a static field, so the instance of the Singleton object will be created always.
The other implementation is lazy initialization (anything that is lazy, pay special attention to the threading)

public class SingleObject {

private static SingleObject INSTANCE = null;
private SingleObject()
{
}
public static SingleObject getInstance() {
if (null == INSTANCE ) {
INSTANCE = new SingleObject();
}
return INSTANCE;
}
}

Looks to be okay but this one is broken in multi threaded system, if two threads calls the same getInstance method, the check-and-create pattern might produce two Instances.

One simple fix is -

public static synchronized SingleObject getInstance() {
if (null == INSTANCE ) {
INSTANCE = new SingleObject();
}
return INSTANCE;
}

but then, the penalty of getInstance calling is high now, whether the object is already created or not, always synchonization is required here and it will make the application slow. Ideally, only when object is not present, it needs to be created and hence synchronized. Instead in this case, the getInstance method is synchronized, so there is a performance penalty always
whether the object is already created or not.
The fix is little tricky and now the singleton coding becomes interesting -

public class SingleObject {

private volatile static SingleObject INSTANCE = null;
private SingleObject()
{
}
public static SingleObject getInstance() {
if (null == INSTANCE ) {
synchronized (SingleObject.class) {
if (null == INSTANCE) {
INSTANCE = new SingleObject();
}
}
}
return INSTANCE;
}
}


As we can see now, there are plenty of things to worry about, the volatile variable and the double check to ensure multiple threads work properly.

If we do not want to use synchronized at all and yet make it thread safe - use the "lazy initialization holder class" idiom as mentioned by Joshua Bloch.


public class SingleObject {

private SingleObject() {
System.out.println("It got created");
}
private static class ClassHolder {
static final SingleObject instance = new SingleObject();
}
public static SingleObject getInstance() {
return ClassHolder.instance;
}
public static void someOtherFunc() {
System.out.println("Some other func can also be static ?");
}
}

In this way, we can achieve thread safety, because for the first time, the getInstance method will be called, it will access
the class ClassHolder causing it to load and initiaze the instance variable.
This is a powerful method and can be very useful for any lazy property initialization of a class.

However, there is now an easy way to create singleton since JDK 1.5 and it is called Single value enum strategy. People who follows Joshua Block and Effective Java knows what I am talking about.


public enum SingleObjectEnum {

INSTANCE;
Public void othermethods…
}

Now, SingleObjectEnum.INSTANCE is definitely a singleton and multi-threading, serialization etc is not developers headache as it comes from JVM itself.

Thursday, May 13, 2010

Think of context before Design

Anyone related to software performs some design decision or other in their daily life. Sometimes we know that we are designing or sometime while coding we take those decisions naturally/unknowingly. Point is, any constructive work will have to choose among various choices to create/design something new, software is no exception.
I have realized over the years that the choices that we make can not be bound to very hard and fast rule cause they tend to change w.r.t context. And this is why it is so interesting.

For example, if we find some list of numbers to be sorted, we can say, we shall use QuickSort. Now think that these numbers are stored in a large file of 4 GB size, can we read all the numbers in memory and perform quick sort? We probably need to split the large file in several smaller files and perfom something like a mergesort. So the context really changed the decision.

I remember one time we wrote a perl function which will read all the lines in a file and perform some operations between lines. Lets say in one line, we have the cost of journey from A to B and in other line we have cost of journey from B to A. This program will combine the both way journey cost and produce one line (out of 2) after adding the costs in both ways. It was working everywhere, suddenly one day it stopped at some places. Problem is - if the file size grows large, out-of-memory error was coming.
How did the file size grow large? This program is supposed to run every after 15 min, but at some sites, customer did not run it for a week and when they re-enabled it again, it failed....
Again, context broke the design decision we took.

Around a year back I was reading some site and it was mentioned how one of the top most architect of microsoft takes interview. It was very interesting to see that he asks "design a house" type of question. The moment candidate draws some square box on the board and mentions the specifications as 16feet long, 13 feet wide, 12 feet high living room, he is almost out ...
Why ? –
Because the candidate did not ask the "context". That house was for a giraffe and not for the interviewer. So a 12 feet high becomes too less for the animal.
A good developer will always ask these questions before writing a single line of code. If he assumes something, he would also write down the assumptions.

Agile methodology tries to solve this problem. At first, it produces a basic (you can read it as crap) version of code with loads of assumptions. Show this to the user, and give them a shock, oh my god, these assumptions are not gonna work in my env! Now we are talking, we know, it is not going to work in your env, let’s note down those assumptions on which we shall work for next 6 months and give us more money :-)

Over the years I am trying to rectify myself on this -- design something and also think of breaking that design cause either today or tomorrow it will be broken by someone else in support/field/customer. Instead they find it, its better to find the problems by the creators themselves.

Wednesday, March 17, 2010

JSF and PopUP

By default JSF has no support for PopUps, unless you are using any custom JSF component library like Tomahawk (http://myfaces.apache.org/tomahawk/index.html), it is tough to achieve pop ups in JSF.
Lets say we want to create a web page which shows a link and on click of that link, one popup should appear with details of the element clicked. This is a very standard requirement like on click of "username" the pop up window should display the details of the user. In JSF it becomes tough because onclick event we can fire a javascript but that is not in sync with the backend action bean.
There is however an easy solution for this problem. The solution is to do the followings
1. Create one controller and bind it to the request scope
2. On click, form a URL which will look like this "newpage.jsp?param1=val"
3. The controller should read the params passed in the URL and process accordingly, for example in this case, the param would be the name of the user and the controller should contact LDAP or backend database server to fetch details data.
The controller can get the details of the parameters passed along with the URL by using FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap() - this will return the map whose key is the parameter name passed in the URL.

Friday, March 12, 2010

My Status update

wow just by looking at my blog, I am figuring out how much busy I was in last couple of months. Well, 2010 is here with lots of activity for myself. The first major change was breaking up with HP. It was a long relationship - around 7 years, found myself becoming very comfortable, so decided to leave and come to US as a consultant.
As a consultant, I am doing some pretty good work in last three month or so. I worked on JSF, worked on Webservices - Axis2 (and SwA).. its cool. I want to write about JSF 1.1 and PopUp, will post it as soon as I get some free time.

Monday, December 7, 2009

JAX-RPC and JAX-WS - how does the SOAP look?

Lets consider a method like the following –

public void purchaseOrder(String item, int quantity, String description)

When this method is serialized to SOAP packet using JAX-RPC engine, the packet looks like the below





This is called SOAP encoding. The method name is the root element under the Body tag of the soap packet. Each parameter is having type defined and the value. This type will be used by the SOAP brokers/engines to de-serialize to String or int values.

The same method needs to be written like “public void someMethod(PurchesOrder po)”
to be serialized to the similar SOAP packet using JAX-WS Document literal engine .
The same method can be left unchanged to be serialized to the similar SOAP packet using JAX-WS Document literal Wrapped (wrapped means, the parameters are wrapped inside the method name) engine .
The sample SOAP packet for JAX-WS is shown below-




In case of JAX-WS, the entire XML inside the Body is deserialized to an JavaBean following JAXB. The WSDL will contain the XSD for the PurchesOrder Bean.

Monday, August 24, 2009

Anti Patterns

Just finished reading this book on anti patterns. It is a very nice book which describes how we (the developer as well as the architects and managers) fail to deliver a software project properly even after all of our good intentions. Sometimes we follow wrong architecture, sometime the deadly sins of sloth, narrow-mindness, Apathy towards technology etc etc..
I quite like the anecdotal evidences that the authors have come up with for each of the well known anti patterns. While reading the book, sometimes I just jumped out from chair and shouted "oh god, I have experienced such problems before". I am sure, as a developer or lead or budding architect, I will be very careful now onwards to look for anti patterns while designing as well as while doing coding or reviews.

Sunday, May 31, 2009

Futuristic Build Process

Build – by definition is to compile all the source code of a project and create the deliverables. For example, build is to compile all Java code using ant or maven and then create the executable jar files or war files or ear files.

An effective build system goes long way to help the project. Nightly or at least weekly development build bits are essential to check the status of the project. Lets divide build systems in its effectiveness.

Step 0 – Build system checks the syntax errors. This is really basic and a must do for build systems. If there is a syntax error in any code , build should fails. It usually does as the compiler stops if there is a syntax error.

Step 1 – Build fails if the unit test fails on the code. This is where most of current projects are. Build fires the compilation, followed by creation of deployable jars/wars. As the last step, build fires the JUnit test cases. If the JUnit test case fails, build breaks. This makes sure the build output is sane and no unit test cases have failed on the build output.

Step 2 – Now lets consider of a build system which breaks if the code checkin has more complexity than the standard, or if the code coverage of the code checkin is less. There are several software metrics that are available now, like “Code Coverage”, “Cyclomatic complexity of code”, “CRAP Metric (Change Risk Analyzer and Predictor)”. [ there are already plugins available on the CRAP and Cyclomatic Metric, where can be found here]

If Build system is integrated with calculation of these metrics, that would guarentee a uniform code complexity and if anytime code complexity numbers come high from the code analysis tools, build should break. This is surely a cool thing to do considering the fact that now-a-days much of the code is getting auto generated. Example, you have a webservice which was using Framework version 1 {like axis1} and you were compiling WSDL file to generate the stub code. You move to Version 2 and build breaks because the auto generated code is more complex and hard to maintain.

It should be a collective decision of the project team whether to go for higher complexity of the code as a team.


This is where at Step2, I think the next generation build systems will go.

Saturday, March 21, 2009

How to connect to Tomcat to gather information from JMX MBeans?

Tomcat provides see of information through its JMX MBeans. It is also easy to connect to tomcat over JMX, just run tocat using the following options -



  1. -Dcom.sun.management.jmxremote.port=9999

  2. -Dcom.sun.management.jmxremote.ssl=false

  3. -Dcom.sun.management.jmxremote.authenticate=false



This will start the tomcat server on port 9999. Use these JVM options in the catalina.bat file - and keep them as JAVA_OPTS.

Once tomcat has opened this port, connect to tomcat using this sample code -



  1. JMXServiceURL jurl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");

  2. JMXConnector jmxc = JMXConnectorFactory.connect(jurl, null);

  3. MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();



This will connect to the tomcat server running on localhost with port 9999.

To fetch the value of an attribute - use the following code -



  1. mbsc.getAttribute(
    new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME, "VmVersion");



The above code will fetch the JVM version of the tomcat JVM using the standard runtime MBean of the JVM.

Sunday, January 25, 2009

Trie in Java

Trie is a good datastucture, details can be found here - http://en.wikipedia.org/wiki/Trie . I came across Trie while performing "Prefix" based searching. Have you ever Wondered what Data Structure is used behind the Mobile SMSes ? When we type SMS, it finishes the words or proposes what could be the end of the word. They are usually done by Trie or data structures like Trie.
Trie consumes less space so they are hot favourite data structures on PDAs or devices with less memory. Searching of a string in Trie takes around O(m) where m = length of the key. Compare it with Binary Tree which is O(logn) where n = number of elements in the tree. For a dictionary, this n could be real large.

Here is a simple implimentation of the Trie..
One class is called Node class which holds the Key and the value.



  1. public class Node {


  2. private char key;

  3. private String value;

  4. private List children;

  5. private boolean isTerminal;

  6. public boolean isTerminal() {

  7. return isTerminal;

  8. }

  9. public void setTerminal(boolean isTerminal) {

  10. this.isTerminal = isTerminal;

  11. }

  12. public Node(char key,String value)

  13. {

  14. this(key,value,new ArrayList());

  15. }

  16. public Node(char key, String value, List children) {

  17. super();

  18. this.key = key;

  19. this.value = value;

  20. this.children = children;

  21. }


  22. public char getKey() {

  23. return key;

  24. }

  25. public void setKey(char key) {

  26. this.key = key;

  27. }

  28. public String getValue() {

  29. return value;

  30. }

  31. public void setValue(String value) {

  32. this.value = value;

  33. }

  34. public List getChildren() {

  35. return children;

  36. }

  37. public void setChildren(List children) {

  38. this.children = children;

  39. }


  40. public void addChildren(Node child)

  41. {

  42. this.children.add(child);

  43. }






}

And the Main Trie class which builds the tree and finds any key...


package com.ds.trie;


  1. import java.io.BufferedReader;

  2. import java.io.File;

  3. import java.io.FileNotFoundException;

  4. import java.io.FileReader;

  5. import java.io.IOException;

  6. import java.util.ArrayList;

  7. import java.util.LinkedList;

  8. import java.util.List;

  9. import java.util.Queue;


  10. public class Trie {


  11. private Node root;

  12. private File fname;


  13. public Trie (String filename)

  14. {

  15. this.root = new Node('r',"root");

  16. this.fname = new File(filename);

  17. }


  18. public void buildTrie()

  19. {

  20. try {


  21. if (!fname.isFile())

  22. throw new FileNotFoundException("");

  23. BufferedReader f = new BufferedReader(new FileReader(fname));

  24. String key;

  25. try {

  26. while ((key = f.readLine()) != null)

  27. {

  28. // making value = full name only = key

  29. build(key,root,key);

  30. }

  31. } catch (IOException e) {

  32. // TODO Auto-generated catch block

  33. e.printStackTrace();

  34. }

  35. } catch (FileNotFoundException e) {

  36. // TODO Auto-generated catch block

  37. e.printStackTrace();

  38. }

  39. }


  40. // key = shamik

  41. private void build(String key,Node root,String value) {

  42. // TODO Auto-generated method stub

  43. char c = key.charAt(0); // c = s

  44. String tail = null;

  45. if (key.length() > 1)

  46. tail = key.substring(1); // hamik

  47. Node resultNode = findKeyinChildren(root,c); // find 's' in the children

  48. if (resultNode == null)

  49. {

  50. // this is a new key

  51. Node newNode = new Node(c,value);

  52. if (tail == null)

  53. newNode.setTerminal(true);

  54. else

  55. newNode.setTerminal(false);


  56. root.addChildren(newNode);

  57. if (tail == null)

  58. {

  59. return;

  60. }

  61. else

  62. build(tail,newNode,value);

  63. }

  64. else // got the key - s

  65. {

  66. if (tail == null)

  67. return;

  68. build (tail,resultNode,value);

  69. }

  70. }


  71. private Node findKeyinChildren(Node root, char c) {

  72. // TODO Auto-generated method stub

  73. List list = root.getChildren();

  74. if (list == null || list.size() == 0)

  75. return null;

  76. for (int i=0; i < list.size(); i++)

  77. {

  78. Node oneNode = list.get(i);

  79. if (oneNode.getKey() == c)

  80. return oneNode;

  81. }

  82. return null;

  83. }


  84. public List findKey(String key)

  85. {


  86. String value = null;

  87. List values = new ArrayList();


  88. Node resultNode = findinTrie(key,root);


  89. if (resultNode == null)

  90. {

  91. value = "Not found";

  92. values.add(value);


  93. }

  94. else

  95. {


  96. printTree(resultNode,values);


  97. }

  98. return values;


  99. }


  100. private void printTree(Node resultNode,List values) {

  101. // TODO Auto-generated method stub

  102. List list = resultNode.getChildren();


  103. if (resultNode.isTerminal())

  104. values.add(resultNode.getValue());


  105. if (list.size() == 0)

  106. {


  107. return;


  108. }

  109. else

  110. {

  111. for (int i=0; i<list.size();i++)

  112. {

  113. Node oneNode = list.get(i);

  114. printTree(oneNode,values);

  115. }

  116. }

  117. }


  118. private Node findinTrie(String key, Node root) {

  119. // TODO Auto-generated method stub

  120. // Implementing the Breath First Traversal

  121. char first = key.charAt(0);

  122. String tail = null;

  123. if (key.length() > 1)

  124. tail = key.substring(1);


  125. Node resultNode = this.findKeyinChildren(root, first);

  126. if (resultNode == null)

  127. {

  128. return null;

  129. }

  130. else

  131. {

  132. if (tail == null)

  133. return resultNode;

  134. else

  135. resultNode = findinTrie(tail,resultNode );

  136. }


  137. return resultNode;

  138. }


  139. public static void main(String[] args)

  140. {

  141. if (args.length <= 0)

  142. {

  143. System.out.println("Usage : Trie ");

  144. System.exit(1);

  145. }

  146. Trie trie = new Trie("C:\\test\\dictionary");

  147. trie.buildTrie();

  148. System.out.println("Going to look for " + args[0]);

  149. List vals = trie.findKey(args[0]);

  150. for (int i=0; i<vals.size(); i++)

  151. {

  152. System.out.println("possible value = " + vals.get(i));

  153. }


  154. }


  155. }



Thursday, January 15, 2009

Job Interview Question Part 2

For a tree, find out the largest possible value from the root to the leaf.

private int maxResult = 0;

public int findMaxRoot(Node root)
{
int result = root.getValue();

List nodes = root.getChilds();
if (nodes.size() == 0)
{

return result;
}
else
{

int maxChildTreeValue = 0;
for (int i=0; i {
//result = root.getValue();
Node oneNode = nodes.get(i);

result = findMaxRoot(oneNode);
if (result > maxChildTreeValue)
maxChildTreeValue = result;


}

result = maxChildTreeValue + root.getValue();

if (result > maxResult)
{
maxResult = result;

}
//maxResult = maxResult + root.getValue();


}
return maxResult;
}