Pages

Monday, May 7, 2012

GWT - FlowPanel + CSS vs HorizontalPanel and VerticalPanel

I've been working with GWT for the past half year, and am extremely excited about this awesome web-framework !
I recommend anyone who is doing web-development to look into it. As a person that came from the world of Java Swing, the transition was very smooth, and most importantly - fun !

Anyhow, this is not the focus of this particular post. I'm not here to say how great GWT is or
persuade you to use it (although you really should if you want to create amazing rich web apps!!!).

This is about GWT's particular widget - FlowPanel and its advantages over using HorizontalPanel & VerticalPanel.

The "problem" is as follows:
Using HorizontalPanel or VerticalPanel to layout your widgets can be very intuitive and comfortable, especially if you come from the world of Java Swing, where Layout Manager extending components help you to lay out your widgets, without forcing you to think too much how they do it.
GWT widgets are a little different.
GWT is a compiler in it's core, that takes Java code, and compiles it into JavaScript that eventually runs on your browser. Different widgets compile into different HTML elements that are attached into the DOM and need to be rendered, so it is very important to keep your DOM as compact and simple as possible so the browser has to deal with less elements thus rendering your page faster, and is also helpful when you need to look yourself at the DOM to find a specific element or understand the hierarchy.

Using the HorizontalPanel or VerticalPanel, can create some serious performance overhead, and especially when you have lots of those in your application.
The reason is because GWT compiles HorizontalPanel & VerticalPanel into HTML Tables.
When you have a lot of those tables, and with many widgets inside you will end up having
lots of those "<td></td>" , "<tr></tr>" tags which resemble the lines and cells of the tables,
and of course the encapsulating tags of the "<table></table>" & "<tbody></tbody>".

FlowPanel on the other hand is compiled into a "<div></div>" - plain and short.

So as you can see, the problem is that when you have lots of those Vertical/HorizontalPanel - you end up generating a lot more elements in the DOM.

This in turn reflects on the performance of your application. Each time you'd want to manipulate those tables - add a cell, remove one, change content, the look-up into the DOM is longer, and the operations consume more processing.
After the change you will end up making to the DOM, the browser will have to re-render those changes in order to reflect them to the user - the more complicated hierarchy you will have the slower the rendering will be performed.

Ok, now I feel I repeated myself enough, so the point should be clear.

So, after understanding why it's better to use (in many cases, although not necessarily all), here's what needs to be done in order to make the change:


  1. Replace your VerticalPanel (or HorizontalPanel) widget with FlowPanel widget.
  2. In case you're using HorizontalPanel and wish to place widgets next to each other, don't forget to use CSS float attribute.

Example:

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;


public class MessagePanel extends Composite {


// Using FlowPanel instead of HorizontalPanel
private final FlowPanel contentPanel;


// Widgets of the message panel.
private Label messageCaption ;
private TextBox messageContent ;
private Button send ;

/**
* C'tor
*/
public MessagePanel() {
this.contentPanel = new FlowPanel();
initWidget(this.contentPanel) ;
// Lets add contents to the panel.
addContents();
// add styles !
addStyles() ;
}


private void addContents() {
// add a name caption
messageCaption = new Label("Message:");
contentPanel.add(messageCaption);
// add an input text field
messageContent = new TextBox();
contentPanel.add(messageContent);
// add a "send" button...
send = new Button("Send message!");
contentPanel.add(send);
}

private void addStyles() {
messageCaption.getElement().getStyle().setProperty("float", "left") ;
messageContent.getElement().getStyle().setProperty("float", "left") ;
send.getElement().getStyle().setProperty("float", "left") ;
}
}


Of course, the code above is only to demonstrate what you can achieve, but not necessarily
how you should really implement it. CSS styles should be put in a CSS file and you should follow GWT's best practices. 

In any case, the outcome of instantiating this widget and adding it results the following:



And results in the following hierarchy in the DOM (from Chrome) :

<div>
<div class="gwt-Label" style="float: left; ">Message:</div>
<input type="text" class="gwt-TextBox" style="float: left; " id="acpro_inp0">
<button type="button" class="gwt-Button" style="float: left; ">Send message!</button>
</div>

So, as you can see this part of the DOM is very concise and straightforward.

Change to FlowPanel to boost your application's performance & to generate simpler DOM.

Happy tuning !

Sunday, April 29, 2012

Spring ROO 1.2 review

This post as the title mentions, is about my personal impressions and thoughts about the 
'Spring ROO' framework, version 1.2.1.

What is ROO?
ROO is a tool, which helps automating the development process of web-applications written in Java.
It supports different kinds of technology stack, such as GWT & Spring MVC in the front end, JPA & Hibernate, EclipseLink in the back-end and such.
The framework is entirely based on the Spring framework, in order to accomplish the goal of creating a full-blown, end-to-end web-application.
The idea is to be able to rapidly create and maintain a web-application with a few 'shell' commands, and then let the users (the developers) fill in the gaps and customize business logic, application state and so on.

ROO monitors the changes the developer makes while writing code, and adapts the application's infrastructure to match and support the developer's actions.

I recommend you visit the ROO website in any case to get the best understanding of the tool.

Before I start telling you what I did and experienced I have to say that I enjoyed working with ROO.
The installation was fast & easy, the ROO shell was easy to use and the documentation was satisfying.

So! after some short-long intro, let me tell you -

What did I do?
1. Created a simple web-application based on a multi-module project - Server & Client modules.
2. Used GWT as the front-end, JPA over Hibernate with a DB in the back-end.
3. Wrote custom code and integrated it in the auto generated files of ROO.
4. Tried to change/add/remove a service (BL) & repository (DAO).
5. Inspected generated code.
6. Tried to remove project's dependency from ROO.

What I experienced
 1. The amount of code generated for the client module (GWT) was quite overwhelming. So many files were created to show/edit/create/delete a single entity named Product in the DB. While some of the generated code is absolutely necessary, a lot of code was created to support every possible option on the front-end.

Unfortunately, this is not configurable, and I could not find a way to tell ROO exactly what I wish to generate ('scaffold'), like - "only desktop support", "only mobile support", "only view/read" capabilities, etc... You can only pick which Entities on your model to scaffold (support on the front-end and back-end). All this leads to a very big codebase, which won't necessarily be used.
This leads to verbosity and a lot of redundancy, which makes your codebase larger and
more complex for no reason.

2. Front end's design - Is following Google's best practices which is really great. You can learn
quite a bit of Google's understanding the design of a web-application on the front end.

3. Generated code looks fairly neat, however all generated code managed by ROO is "hidden" in AspectJ files. - Some people don't like this.

4. No easy removal* of ROO from the project in my opinion... - You could just stop ROO from monitoring your application and continue developing your project. But, all the generated AspectJ files remain. This could be a problem for the future, in case you want to change your classes' implementation. (* - Please see comments at the bottom).

5. Writing tests & integrating them with Services layer was easy.

6. Great end-to-end integration tests, that run on the Browser using Selenium (some kind of a web-driver script player).
It feels to me that even though ROO's GWT add-on tried very hard to give a real added value to developers, it added more complexity than simplicity, and that is in my opinion due to the fact that 
a lot of code is being generated. And that makes it hard in the beginning to dive into the code.

Not to mention how much tweaking needs to be done to disable features for instance.
And in case you're letting ROO manage your project further, you will have to keep track of that
stuff all the time. So if you 'messed' up by scaffolding some entity which you didn't want, you'll spend
your time removing the unwanted code. where is the Undo feature of the shell?
ROO just doesn't feel as fine grained as I would expect it to be.

Conclusion
I think that ROO is walking in the right direction, empowering developers to deal only with the logic of their web applications and not trouble themselves with infrastructure and design problems of standard web-applications.
I am not sure I would use it (especially not the front-end) in production, yet.
Despite all that, it still benefits as a really nice tool for prototyping (or quickly setting up a back-end & DB configuration), and for learning how to implement a web app with best practices.

What can you profit from it:
1. It is an amazing tool to create a web-app POC very fast!
2. It is an awesome tool to learn new technologies and see how they work with each other.
3. Spring ROO applies best practices.
Explanation: ROO has a 'plug-ins' platform, which lets anyone to generate code following a simple command in the shell. 
Google for instance wrote such a plug-in for ROO to integrate with GWT. As a result you get the BEST, latest results for architectural/design/technology/practices on your web-app.
4. It's a great tool to get your backend Spring based infrastructure ready with a DB, in a few minutes, or see how it should be done properly.
5. Runtime performance - Best runtime performance you could have achieved yourself probably.
All generated code/configuration is processed in compile time as regular Java files only!
Following best practices of Spring & other vendors like Google, you can rest assure that there should be no performance issues caused by this tool. (or with very little chance for it to happen - even the best software giants have bugs sometimes).
6. Did I mention the great integration tests running automatically on the browser?
I personally loved this feature!

I think it would be wise to keep an eye on ROO for the future, as it has already been out there for some time, and keeps on improving.

Visit 'Spring ROO': http://www.springsource.org/spring-roo



Tuesday, March 20, 2012

DI with Guice for Java Swing

If you're familiar with Dependency Injection (DI) concepts and frameworks such as Spring,
you know the great benefits it introduces when developing an application.
Spring which I daily use (and praise), is a framework (or an application platform if to be more accurate) that one of its core features and philosophy is DI.

Some of the benefits of DI are well known:

  1. Simplified code.
  2. Reduced dependencies.
  3. Helps 'modularity' and creation of reusable components.
  4. Helps you test your application better.
  5. Lazy loading.


Surely there are other benefits you could think of which were not mentioned above.
So, why not bring all that good stuff to your Rich Client ?

The connection of DI to the title of this post is how to integrate DI in your front-end in case you are building a Rich client application, using Java Swing or GWT for example.

You could follow the MVC pattern (which is well known, and can be great) to build your rich client, and integrate it with a DI framework. However I strongly recommend you consider the MVP pattern for an even better design of your front-end. Which I find it to be much 'cleaner'.
(In MVC some of the business-logic code is scattered between the controller and the View. It's harder
to re-use your View objects/Widgets, especially in case you want to give it to someone else to use, or integrate them in another product).

Smarter people than me talk about it, and you can find great talks on YouTube regarding this subject.

You can later also check Google I/O's excellent talk for "Best Practices for Architecting GWT App"  http://www.youtube.com/watch?v=PDuhR18-EdM

So, if we follow the MVP design pattern and Google's best practices (even if we don't use GWT),
we end up with few key components in our app, i'll try to give some description what they do:

  1. "The" Event Bus - The component where presenters 'listen' to, and can fire events to.
  2. The Presenters - The components which encapsulate the logic of your application.
  3. The Views / Displays - Simply a view - can be a panel with widgets in it. No logic in here!
  4. A Model - Where you keep important data that can be accessed by one or more presenters.


"Show me the code!"

Lets assume you're writing your rich client in Java Swing.
We will use the lightweight DI framework "Guice" by Google:
http://code.google.com/p/google-guice/ to help us achieve our goal.

Lets go over some steps to realize what needs to be done in order to get this to work - don't forget to download Guice and put it's Jars in the classpath.
(Or, scroll all the way down to download the zip file containing the source code).


1) Define a simple View as a dumb object, not knowing anything about logic:
public class ContentPaneDisplay extends JPanel { .... }

2) Define a high level IPresenter interface and the IContentPanePresenter interface:

public interface IPresenter {
/**
* A method of all implementing presenters for presenting themselves on a given container.
* @param c
*/
void go(Container c) ;
}

public interface IContentPanePresenter extends IPresenter {}


3) Define a Presenter that will use view object above as its display:

public class ContentPanePresenter implements IContentPanePresenter {
public static interface IDisplay {
JComponent getAsComponent() ;
}
private final IDisplay display ;
....
}

4) Make ContentPaneDisplay implement the ContentPanePresenter.IDisplay interface.

5) Configure the Display class and the Presenter class to be used by Guice:

public class ApplicationDIModule extends AbstractModule {
@Override
protected void configure() {
// Lets configure some stuff !
bind(IContentPanePresenter.class).to(ContentPanePresenter.class).in(Singleton.class) ;
bind(ContentPanePresenter.IDisplay.class).to(ContentPaneDisplay.class).in(Singleton.class) ;
}
}

6) Add the @Inject annotation to the ContentPanePresenter to be injected the display:

/**
* C'tor
* This is where DI takes place!!!
* Guice will instantiate and provide this presenter with a matching display!
* @param display
*/
@Inject
public ContentPanePresenter(IDisplay display) {
this.display = display ;
...
}


7) Now all that's left is to call the Guice injector to get the ContentPanePresenter:
private static void go(Container container) {
// Guice.createInjector() takes your Modules, and returns a new Injector instance.
   Injector injector = Guice.createInjector(new ApplicationDIModule());
// lets get the 'Main' content pane Presenter !!
   IContentPanePresenter contentPanePresenter =
                                                            injector.getInstance(IContentPanePresenter.class) ;
contentPanePresenter.go(container) ;
}



Sunday, January 22, 2012

More (software) performance, less carbon dioxide

This post is a little different than the older ones.
This time, it's about how "Making a performant software, helps reducing carbon dioxide emissions".

So, what's the connection you ask, and why is it even important?
I'm not writing this post to convince you that global warming is not a theory. It sure isn't.
The vast majority of researches on this topic amongst the scientific community, indicate we are facing a new reality where nature starts kicking back, corresponding our irresponsible actions as humans.

You're encouraged to read and explore this must topic (IMHO) yourself to realize how it effects your life directly, and how it effects our planet.
A great book, which I very much enjoyed reading and also inspired me to make this post is:

"Hot, Flat, and Crowded" by Thomas L. Friedman. (There's also a 2nd edition of the book).
(His website: http://www.thomaslfriedman.com/)

However, I think there are many other ways you can choose to enrich and extend your knowledge about this concerning subject, from books and magazines to getting involved in your own community and raise awareness.

So, assuming we understand the importance of a change we should make, not only because of
energy problems in the world, not only because of extreme climate changes and amounts of Greenhouse gas particles in the air, although extremely important, this is also a lot about how to make your software more competitive than others in the IT market.

You create an added value in terms of "green" to your customers, bringing them more benefit in
energy consumption, which translates to reduced electricity bills, and helps tagging their company
as "greener".

So this is about how you as a software engineer can help make this change.

The idea is very simple(yet, a little harder to implement and keep in mind):
The more computations your software makes, the more CPU is needed for computation, and
more energy is needed to cool it down.
Since a CPU is an electronic device like anything else pretty much on your computer, and consumes
energy (Watts). The more you use it, the more energy you consume. Rather logical!

If we can reduce the amounts of computations on our CPU, than less energy will be needed.
If our software won't perform any computations, then the CPU usage will be at minimum.


What can you do!?

  1. Improve your computations in the code.
  2. Replace for a faster algorithm than the one you're using
  3. Make stress tests - measure CPU performance with profilers.
  4. Add "Green" Unit tests to your software to make sure CPU utilization doesn't exceed a certain limit you or your company set to itself.
  5. Perform long and "heavy" processing during night time or when electricity is cheaper.
  6. Create an acceptance test for your software, making sure in all cases computations don't exceed a certain bar, or make sure average computation per day stays low.

So, as you can see the theory is extremely simple to understand.
The question is, how much can we 'save' or what do we save ?

Lets make a simple example.
This is totally not based on any scientific research, and is using only given inputs from official manufacturers and website i found on the web and using some common sense.

Suppose your computer has a CPU from a known brand like Intel or AMD.
Such CPU can consume up to 130W (Watts) for TDP - which is the maximum amount of power needed to cool down that CPU so it can work properly.

If you are running on a high loaded server which is operating 24h / 7d than you get
24 x 365 (hours) = 8760 hours of using this CPU.

Lets assume that the average CPU utilization stands on 80%, because of your software computations.
This translates to an average of 104W in order to keep that CPU working.

The price for a Kilo-Watt is something your local electricity company charges for, and it changes depending on many factors.
However, I found some numbers on the web, and as I see it may vary, but since this should be
a constant in the "cost calculation formula" as the electricity price is (usually fixed, or has a fixed average), we'll just use some number, say 15 cents for a Kilowatt (kw).

So now we can calculate how much we would need to pay just for this CPU to work:

(104W) * (24 * 365h) * (15cents)
-----------------------------------------------           =     13,665  cents.
                    1000

So that's 136$ dollars for the entire year. Doesn't look so much ?

If hypothetically you will be able to reduce the average CPU consumption to 25%, you will get:

(32.5W) * (24 * 365h) * (15cents)
-----------------------------------------------           =     4,270  cents.
                    1000

and that is 42.70$ dollars a year. That's about 68% less to pay. And if you or your client have dozens of servers or more, say 100, then you could save (approx.):   (136 - 42.70) * 100 = 9,330$.
And that's already some money, especially as it accumulates over years and years.

Not to mention all the carbon dioxide emissions you reduce by making your software more efficient!
A coal based power plant can emit up to 1 Kilogram of Carbon Dioxide per 1 Kilowatt!
(Again I must stress that different numbers could be found on the web, but the idea is very clear).
Which means that by utilizing 25% of your CPU instead of 80% you reduce carbon dioxide emissions
dramatically! And in numbers you emit 284.7 Kg, instead of 911.04 Kg !
And that is only for one CPU!
I'm sorry, I just can't shout it loud enough.

Just imagine having this amount of garbage bags pile around your own house !!!
I'd rather live without any garbage bags around my house at all I can tell you that ! But I would definitely be happy to reduce the amount as much as I can.

Remember, just because it goes into the air, doesn't mean it is not there ! - it even rhymes !

Change starts today.

Tuesday, December 13, 2011

Password encryption in Java

This time, it's about security.
And specifically about how as a developer, you should protect the passwords of your users.

I think there can't be enough emphasis of how important it is to keep the password of your users safe.
So, instead of 'lecturing' about why you should do it, lets dive in right away into how you do it.

So, given the fact you have different users on your system, and each of them has a password,
we would like to keep their passwords safe.

This translates to storing their passwords somewhere (a DB for example), encrypted.

So before we really give code example how it's done, a small note on encryption:
When you pick an encryption algorithm to apply on your passwords, try to think if you ever
plan on decrypting them. In most cases the answer is 'NO'.
(Picking a symmetrical algorithm also means that in case an attacker finds out the key,
they can use it to decrypt the passwords).

Thus, we'll drop all symmetrical algorithms such as AES(Rijndael), RSA based, etc.. and pick
an asymmetrical encrypting algorithm such as hashing.

Hashing algorithms such as SHA are asymmetrical-key algorithms, meaning that for an attacker
that put their hands on the encrypted password it is impossible to recover the original password.
Different inputs for SHA can yield the same output, but with a very low probability.

Now that we understand why we should use a Hashing algorithm, we can explain the steps for
encrypting and give an example code how it's done in Java.

Encryption recipe:

1. Take password and salt* as an input.
2. Apply some hashing algorithm on the input. (We will choose SHA-256)
3. Repeat step 2 a large amount of times where the input to the algorithm is the last output of the encryption.

*salt - Is an additional fixed input for adding complexity for the encrypted password.

Lets write this in Java:




package nm.example;


import org.apache.commons.codec.binary.Base64;
import java.security.MessageDigest;


public class PasswordEncrypter {


    private final static int NUMBER_OF_HASHING = 10000 ;
    private final static String CHARSET = "UTF-8" ;
    private final static String ENCRYPTING_ALGORITHM = "SHA-256";


    /**
     * Encrypts a given password.
     */
    public static String encryptPassword(String salt, String password) throws Exception {
        // Transform the given password & salt to Base64 in order
        // to work on a closed set of 64 characters instead of Unicode.
        Base64 base64EncoderDecoder = new Base64();
        String b64password = base64EncoderDecoder.encodeAsString(password.getBytes(CHARSET)) ;
        // Create the salt & transform it to Base64.
        String b64Salt = base64EncoderDecoder.encodeAsString(salt.getBytes(CHARSET));
        // The encryption!
        byte[] proposedDigest = getHash(b64password, b64Salt);
        return base64EncoderDecoder.encodeAsString(proposedDigest) ;
    }


    /**
     * From a password, a number of iterations and a salt,
     * returns the corresponding digest
     */
    private static byte[] getHash(String password, String salt) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(ENCRYPTING_ALGORITHM);
        digest.reset();
        digest.update(salt.getBytes(CHARSET));
        byte[] passwordBytes = password.getBytes(CHARSET);
        byte[] input = digest.digest(passwordBytes);
        for (int i = 0; i < NUMBER_OF_HASHING; i++) {
            digest.reset();
            input = digest.digest(input);
        }
        return input;
    }
}

So the output for:  
PasswordEncrypter.encryptPassword("secret-salt", "my-password")
is "NiNP/e/NOzmoCQGaShXENFzpYXv7+EclH9st+dnfBWE="

As you can see I'm using the Apache Commons Codec library for Base64 encoding,
which is available at: http://commons.apache.org/codec/download_codec.cgi


Happy encrypting.