Pages

Wednesday, December 5, 2012

SpacePong - version 2 - HTML5 Game with GWT

Hey,
This is just a small update of the game, to make it a bit more fun to play actually.
So now you can pick different levels to play and have something a bit more challenging.

The source code has changed of course, and you can find it like before on GitHub:
https://github.com/nirgit/GwtPong/tree/space_pong_ver_2_0_0


Enjoy!

Wednesday, November 28, 2012

GWT HTML5 Game Example - Pong

Hi everyone,

This post is intended to present a very simple example of a game, made with the HTML5 support of GWT.
The game uses only GWT, without any other 3rd party libraries such as PlayN which works with GWT and is rather famous and meant for creating games based on HTML5.
Take a look at PlayN's website: http://code.google.com/p/playn/

GWT provides an API to the underlying HTML5 Canvas, and lets you use it to create
custom graphics.

This example shows the game of Pong. Though the game might be a little buggy, it nevertheless makes use of the fundamental HTML5 Canvas features, such as drawing simple geometric shapes, such as rectangles, circles, gradients and with those elements creating a very simple and compact code for a game.

You can find all the code on GitHub for you to clone: https://github.com/nirgit/GwtPong

Click the screenshot to play:




Have fun playing!

Sunday, November 11, 2012

Gradle - Opinion, experience and examples

Opinion and Experience

I had quite a short experience with Gradle, but the impression it left is of an incredible tool.

I don't want to diss any other build tools out there like Ant or Maven, they're great,
and if you're a real savvy, you'll get the job done probably pretty fast.
I generally believe that one needs to use the right tool for the right task, but I'd dare say
that whatever you're doing with Maven or Ant you could probably do better with Gradle -
it is simpler, faster, shorter to write any build file, much more concise yet very powerful.

I have also my experience with Ant for years and with Maven, and I can tell you that I appreciate
Ant very much as a build tool. It does exactly what you expect it to do.
When you read a build.xml file, you'd hardly find something you don't understand.
It's just clear how things work, and what is expected at the end.
The problem is, you need to write so much "build code" in order to get your job done, especially
in a complex system, when you have includes of other extension.xml files you rely on and so on.
What about dependency resolution? - OK, so you could use Ivy, but that's just for dependency resolution.
It's not a "full" build tool in the sense of Maven that comes with creating your packages out of the box, deploying it to your tomcat and distributing it to your Repository.

Yes, Maven can be great but I must say that my 'like' metric towards it is not so stable.
It is too complicated to get simple stuff done... compiling GWT? - Get a plugin!
In Ant, it's really simple to compile a GWT project + you get the example from the GWT website.
In Gradle you can simply execute Ant Tasks, so no plugin extra work needed.
Want to include / exclude resources from your WAR file... why does it have to be complicated?
Dependency management and resolution is awesome, distributing your artifacts into a repository
is great, and fairly easy to do.

However, despite the good stuff of these build tools, I must say that from my personal experience  Gradle tops them.
Gradle like many other posts on the internet would say - brings all the good stuff from the worlds
of Ant and Maven while keeping the ugly stuff out.

What do I mean by that?

  1. It is the easiest build tool I've seen to get started with - simply download, extract and set the GRADLE_HOME environment variable on your path.
    Like Ant - no other configuration is needed! Sweet.
  2. Very well documented!
  3. You can execute any Ant task from the Gradle build files. Any.
  4. Dependency resolution - from Maven repositories, it leverages the existing repositories you may already have in your corporation without needing to change anything, while decreasing the verbosity of dependency declarations in the build file itself.
  5. Gradle is based on Groovy, so you can just program your build.
    And you can use all the libraries of Groovy. And it runs on the JVM, so you could theoretically use any Java library you like when running the build.
    Did I already say powerful?
  6. It is dynamic - You can tell Gradle in run-time for example, which sub-projects you'd like to include in your Project's build. I did that, using naming conventions for instance when I had a process that was auto-generating entire projects ready to be built in a pre-compilation phase. Incredible!
  7. No need to sit and rewrite ant targets to do jobs like clean, compile, jar, war etc... it is all there already!
  8. The integration with Eclipse is excellent. All you need is there.
  9. It just works!



Let me give you an example of how a simple Gradle build (build.gradle) file looks like:

apply plugin: 'java'
apply plugin: 'eclipse'
sourceCompatibility = 1.6
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'My project', 'Implementation-Version': version
    }
}
repositories {
    mavenCentral()
}
dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}



I think that what is so nice about this build file, is that you can understand it right away.
Lets go over the lines to try and understand this file:


  1. The first two lines declaring the "apply plugin...." means that you are telling Gradle to use plugins such as 'java' for example to it would know how to compile Java source to classes.
    Gradle is based on plugins, which facilitate all the needed 'know-how' and logic of performing
    various tasks. - You could write your own custom plugins as well.
  2. The 'eclipse' plugin for example generates the needed files for importing your Gradle project into Eclipse.
    You can read more on that on - The Eclipse Plugin.
  3. sourceCompatibility - tells Gradle what version of Java your source files are written in.
    You can also specify the 'targetCompatibility' attribute in order to compile your sources into a lower version of Java.
  4. version - Declares a variable called 'version' with the version number of your package
    (Be it a JAR or WAR file). The Jar files that are generated with the Gradle 'build' task, have a Maven convention. So the version number is appended to the name of the package at the end. (for example: "MyPackage-1.2.jar", in case version was given the value "1.2").
  5. jar { ... } - This is a Gradle Task is a "task" (can be thought of an Ant task) which is part of the 'java' plugin that assembles a Jar file from your compiled code.
    You can add to the manifest file your own attributes, such as a version number.
    Note that  'Implementation-Version': version is using the version number declared earlier in paragraph 3, but you could have used any other variable to place your value in there.
  6. repositories { mavenCentral() } - determines the repositories from which you want to perform dependency resolution.
    In this case - using the Maven Central repository.
  7. dependencies { ... } - determines the needed dependencies for your build.
    Like Maven's dependency scope, in Gradle there are also so called 'scopes' which you declare for your dependencies: compile, runtime, testCompile & testRuntime.In this case we declare for example the following:
    testCompile group: 'junit', name: 'junit', version: '4.+'Which makes sure to use the JUnit version 4 and above during compilation of test files.


That's it.
It's really short and simple!
Now you can just run from your command line : > gradle clean build
And you will get your project cleaned, compiled, packaged ("Jarred"), tested and with a JUnit test report, all under the 'build' directory of your project.
Of course, you can also distribute the artifacts (your Jars) to your repository, or just copy them
flat to an "Artifacts" directory of your project and so on.

But this was only to demonstrate how easy it is to create a build file, that does so much.

Examples

Running an Ant Task from Gradle build file:

You can run an Ant tasks from a Gradle build file simply by writing something like this:
ant.echo(message: "Building a project....")

This task in particular is not that useful... it's just a print, but it demonstrates how easy it is to execute Ant tasks!
Especially if you consider migrating from Ant, and you have custom Ant Tasks written
which you want to re-use - then you could easily do this.



Running an external Java program from an external Jar:

This could be handy if you want to run anything which is for example at a pre/post phase
of the build.
The snippet below shows how you would apply an XSLT on a XML file, using
the xalan library:
ant.java(jar: "lib/xalan.jar", fork: "true") {
arg(line: "-xml" + " abc.xml")
arg(line: "-xsl" + " myXslt.xsl")
}

(the "lib" directory is at the project's root directory as were the "abc.xml" and "myXslt.xsl" files).


Including Sub-Projects in your Project's build dynamically:

When your project is comprised from sub-projects, it is necessary to tell Gradle about
those sub-projects in a dedicated file called settings.gradle.
In that file, one needs to "include" the sub-projects that need to be built by Gradle.
So typically you could see something like this:
include 'server', 'client'
The great thing about Gradle is that in the settings file you can pretty much put just about anything
you put in a build file. The settings file is executed in the initialization phase of the build.
So if you want to dynamically include sub-projects into your build because you're generating them
from another process, or because you have many of them, or for any other reason, you can do
something like this:


new File(".").eachFile(groovy.io.FileType.DIRECTORIES) { f ->    if(f.name.startsWith("subProjectPrefix") {                
                            include f         
                 }
          }


This will just iterate over the root directory of your project, check if the current directory
it iterates on starts with the "subProjectPrefix" prefix, and includes it if it does.


This was really just the tip of what Gradle can offer you.
You can find many examples on the internet as well as on Gradle's installation directory.
(Look under %GRADLE_HOME%/samples - there are many build files examples).
So if you're using Ant, Ivy or Maven I recommend you to look into it, and give it a try,
I don't think you will regret it.


Gradle - http://www.gradle.org/

Friday, September 28, 2012

Merge on check-in, is there more to this?

In case you find yourself merging code very frequently when trying to commit/check in/push your changes to the version control system (VCS like GIT or SVN), you should start asking yourself - 
"Why am I merging so many times? What is the reason for this?".

If you are making lots of merges to your code - it could indicate a design problem in your project.
(I am trying to be very careful here, as each project is unique in its characteristics - the amount of code and modules, the amount of people working on it, and so on, so it does not necessarily point that out).

"How come?" you might ask...
Basically merging happens when more than one party checks out a piece of code makes changes to it and then checks it in. Only the first party that checks in is avoiding a merge, but all others that made changes (to a now stale version of a file) will have to merge their changes with the latest commits.

I heard many times the good argument that claims that to check-in small pieces of code at a time reduces the amount of merges and helps avoiding big sudden changes to the code which could render it buggy. 
While a "small" size of code is something subjective the idea is clear and makes sense.

It is easy to keep track of small changes. A single bug fix or small enhancement and so on.

Although this is a good practice and will help you reduce the amount of merges, there are sometimes still situations where merges happen more than they should.

There could be another reason why you're merging more than you should, and this reason could be - a design "problem" in your code.
Such "problem" could be for example :

1. Classes that represent two (or more) logical units or well defined purpose.

Then it's clear that if 2 people (or more) would need to make some changes regarding different functionalities of this class, because this is the way work was distributed in their team, those people are very likely to face merging issues when they will try to check-in their code.
While if the class would have been splitted into 2 (or more) distinguished classes with clear purpose, then the 2 parties wouldn't need to face a merging issue.
Unless... (here comes #2)

2. Dependencies - sure almost everyone has dependencies and that is how things work. 
But what happens if you are starting to have a lot of dependencies? Then you're also likely to face a merge. 
Only this time you'll have to change your dependants' code (code who uses your class/interface as API) in order not to break compilation, and in those dependants is exactly where the merge lies. 
(Someone who just worked on that class earlier using your now 'old' API... and now you have to adapt their new code! - I'm not talking about changing your interface or API as part of a general change in the infrastructure of the system, that is obvious, and intended to affect client code. I'm talking about the times where it was not meant to be or shouldn't be due to bad design, wrong API usage and so on.)
Although adapting client code might sound less problematic, reducing those incidents as much as possible by reducing the amount of your dependencies, will help you avoid more merges. (Changer point of view).
Also as a client, It would be less likely that someone would come and change your client code, and adapt it in a way that you did not mean.

So if you're having lots of merges, try to understand why you have them before trying to resolve them. Sometimes it is very tempting to go on with the merge, as today there are good automatic tools to perform a merge. But, maybe you'll find something interesting, or come up with a way to refactor code that was taken for granted as a "law of nature". 

You'll eventually earn less merges, a more modular well defined code, and become less error prone, 
After all, who hasn't made a mistake once of accidentally dropping some code on a merge?

So not every merge is a reason to start wondering why this is happening, but it should make you at least aware of the situation and think whether it could be different.
Hope  this post wasn't stating the obvious.


Sunday, August 26, 2012

GWT Chrome extension using version 2 manifest

Hi everyone,

A while ago I wrote a small post about how to create Chrome extension using GWT, claiming
you could use GWT to make powerful Chrome extension.
One of the comments was regarding the usage of the manifest version.
When you write a Chrome extension, you must provide with a file called manifest.json which
serves as some kind of descriptor file to your extension.
It contains all sorts of things, such as the name of the extension, description, icon, action,
javascript files involved, and so on...

One of the entries in that file is the version entry.
As for today Chrome supports the current version - 2, and also supports (for the moment)
version 1.
However, this is changing, and Google already announced that they will stop supporting version 1
in the future (see http://developer.chrome.com/extensions/manifest.html#manifest_version), due
to security reasons.

So I was asked whether it was possible or how is it possible to deploy the GWT extension with the
version 2 attribute in the manifest.json file.

Version 2, is stricter in terms of security than version 1. Especially when it comes to using external JavaScript files.
You can read about security concerns over here:
http://developer.chrome.com/extensions/content_scripts.html#security-considerations
http://developer.chrome.com/extensions/xhr.html

One of the problems I faced, was the inline scripting I had (JavaScript showing inside the HTML).
That problem came not only on my "Hosting" HTML file, but also on the compiled outputs of GWT,
where HTML file which was needed was created and contained JavaScript code.
When that happened, I couldn't execute the extension on Chrome using version 2 in the manifest.json file.

I wrote in response to a comment someone left regarding this problem, that in case Google would have a way to separate JavaScript files from HTML, then problems would be solved.
Back then, I didn't see such options for the GWT compiler.

However, after doing some more searching, I found out that it does exist (!).
And so by adding a simple line in the .gwt.xml file of the application, you can compile all
your GWT application output into a single JavaScript file. Meaning - no HTML files containing
inline JavaScripts.

The line one needs to add is:
...
<add-linker name="sso" />
...

I added it to my Quickpik.gwt.xml file, and so when you run the GWT compiler, you get at the end
one JavaScript file containing the entire code of your app. Awesome!

You can access the entire code on Github and download it from there:
https://github.com/nirgit/Quickpik

You can simply click on the "Downloads" on the right hand of the screen, in order to download
the repository as a ZIP file.

In case you're a GIT user, my suggestion is that you just clone the repository. It's really small.
Simply open your GIT shell and type:
git clone https://github.com/nirgit/Quickpik.git

The extension is already ready to be used in Chrome, and you can deploy it by opening Chrome's
Tools -> Extensions tab, and checking the "Developer mode" box.
Afterwards, you will be able to deploy the extension by selecting the "Load unpacked extension..."
option and selecting the war directory of Quickpik.

I am hoping this is somewhat useful.
I think GWT is an absolutely great tool, and one that can be a lot of fun writing Chrome Extensions.

Until next time!




Wednesday, July 11, 2012

Source on a Github repository

Hey everyone,

This is a really short note.
From now on, in case I will publish more code in the future I will try to make sure it is uploaded 
to Github, so anyone could profit from it.

The Github repository URL: https://github.com/nirgit

Enjoy.

Monday, July 9, 2012

Quickpik - GWT Chrome extension - Search photos



As a continuation to my previous post, this isn't about discussing anything.
It is about doing - giving an example of something quite simple & cool which you could do yourself using GWT, to build a chrome extension.

Being a bit of a GWT enthusiast, I built an extension for Google Chrome called QuickPik - which allows users to search for images from right from the toolbar.

Quickpik is using Google Images & Flickr (Yahoo) APIs.
You can run a simple search, and get some images as results. It's really simple.

You can just download the zip file from the link below, extract it and install the .crx file right into Google Chrome by dragging the file into it. If you're scared of some evil code running on your browser - just open the source code in the zip file, build the extension yourself, and then install it.

Keep in mind that the idea of this post is to show how easy it is to create a
cool extension for Chrome.
The code might not be extremely well documented, nor does it strictly follow Google's best practices like the MVP pattern or bundling CSS or Image resources and so on, but...

You can expect something compact and simple enough once you open it and take a look.
I don't think there should be a problem understanding much of the code.

Would love to get feedback if this helped anyone.

Both source code & Chrome extension below are available to download in one zip file.

Have fun !!!

The project on Github:  https://github.com/nirgit/Quickpik
A Zip file to download:   http://www18.zippyshare.com/v/16094412/file.html





Tuesday, June 5, 2012

Building Chrome extensions with GWT


Recently i took a look into Google Chrome Web Store. 
The web store as you can take a look for yourself, is loaded with apps, which many of them are given free.


I decided to understand what it takes from a simple developer like myself to build such an app which I can run on my browser & distribute on the Chrome Web Store.


Surprisingly, it does not take a lot of effort to write such an app/extension, especially if you're already familiar with a little bit of web development.
Google Chrome Extensions: http://code.google.com/chrome/extensions/overview.html


So what you really need is some knowledge of JavaScript, HTML & CSS to make a neat extension.


For me the real story began when I realized that for such requirements, one could actually use the (amazing) GWT framework to write such an extension. 
If you never looked into GWT, my personal recommendation is that you absolutely must in case you're into web-development. GWT is a truly incredible tool from my experience.


If you look at the file structure of such an extension, you can see from the "Google Chrome Extensions - Getting Started" tutorial (http://code.google.com/chrome/extensions/getstarted.html) that we're talking about 4 important files:

  1. manifest.json - This file if you like is some kind of a descriptor of your extension.
  2. An HTML file "hosting" your extension. 
  3. A JavaScript file containing all the cool interaction with your extension, and your script.
  4. A CSS file - for styling.

When you write your GWT application in Java and compile it afterwards, you get such files, except for the first one. That you will have to add yourself to the project.


So enough of "blabing" - Lets dive right into "How to do it" (if you're impatient, just scroll to the bottom of the page to download a zip file of the project):


1. Start a new web-application project in Eclipse, and let it create the default skeleton of the project.



2. After the project has been created, make some clean up in the project's structure by deleting the "server" and the "shared" packages.


3. Edit the .gwt.xml file and make sure the file's contents is something like:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='mychromeext'>

  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name='com.google.gwt.user.User'/>
  <!-- Inherit the default GWT style sheet.  You can change       -->
  <!-- the theme of your GWT application by uncommenting          -->
  <!-- any one of the following lines.                            -->
  <inherits name='com.google.gwt.user.theme.clean.Clean'/>
  <!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/>     -->
  <!-- Other module inherits                                      -->
  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.techdrum.chrome.ext.example.app.client.MyChromeExt'/>
  <!-- Specify the paths for translatable code                    -->
  <source path='client'/>

  <set-property name="user.agent" value="safari"/>
</module>
4. Delete the auto-generated Async file and it's matching service file.

5. Write some GWT code in the MyChromeExt.java file, something very simple like - 

package com.techdrum.chrome.ext.example.app.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class MyChromeExt implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
}
}
6. Almost done! Create a new file called "manifest.json" and place it under the "war" directory.
The file should contain the following:

{
  "name": "My GWT ext",
  "version": "1.0",
  "description": "Simple GWT Extension!",
  "browser_action": {
    "default_popup": "MyChromeExt.html"
  },
  "permissions": [
  ],
   "web_accessible_resources": [
    "mychromeext /E949D2D1E7CE643145D4D3D5FC28BB31.cache.html"
  ]
}
*Note the stressed file name!

7. Compile the project.

8. Match the file name with the .cache.html suffix under the directory mychromeext to the one mentioned in paragraph 6. 
So if you have something like BF13DA7B8EE69ECA8CAA8F35290E1E1E.cache.html
then your new manifest.json should look like:

{
  "name": "My GWT ext",
  "version": "1.0",
  "description": "Simple GWT Extension!",
  "browser_action": {
    "default_popup": "MyChromeExt.html"
  },
  "permissions": [
  ],
   "web_accessible_resources": [
    "mychromeext/BF13DA7B8EE69ECA8CAA8F35290E1E1E.cache.html"
  ]
}

9. That's it! Now you're ready to deploy your new extension on Google Chrome.
    To do that - open Chrome, and open the Extensions window:


10. Make sure to check the "Developer Mode" box, and then click on "Load unpacked extension..."
Select the war directory of the compiled project, and your new extension should appear on the Chrome toolbar next to the address bar.
When clicking on it, you'll see your app:


Congratulations!



Get the full code of the project here.

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.