My name is Juri Strumpflohner and this is my technical blog. I'm a software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Dear reader of Juri's TechBlog,
I moved my blog to a new domain and a new hosting solution as well. I'm now blogging on juristr.com.

GWT Hyperlink Widget with Image

Standard GWT Hyperlink widgets don't seem to give the possibility to associate an image. This is quite awkward since you may want to provide nice icons along with your links. In my opinion, appropriate icons increase the user experience dramatically. But it is also not difficult to create image-enhanced hyperlink widgets.

public class HyperLink extends Hyperlink {

 public HyperLink(){
 }
 
 public void setResource(ImageResource imageResource){
  Image img = new Image(imageResource);
  img.setStyleName("navbarimg");
  DOM.insertBefore(getElement(), img.getElement(), DOM.getFirstChild(getElement()));
 }
}
Now you can use the widget like
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
 xmlns:g="urn:import:com.google.gwt.user.client.ui" 
 xmlns:v="urn:import:com.devbook.client.view" xmlns:d="urn:import:com.devbook.client.widget">
 <ui:style>
 </ui:style>
 <ui:with field="res" type="com.devbook.client.IDevbookImageBundle" />
 <g:DecoratorPanel ui:field="outerContainer">
  <g:HTMLPanel ui:field="mainContainer">
   <v:DecoratedPanel ui:field="titleContainer" text="Navigation"></v:DecoratedPanel>
   <g:VerticalPanel>
    <d:HyperLink resource="{res.add}" targetHistoryToken="addSourceItem">Add Item</d:HyperLink>
   </g:VerticalPanel>
  </g:HTMLPanel>
 </g:DecoratorPanel>
</ui:UiBinder> 
The above XML file makes use of the UiBinder which has been introduced with GWT 2.0. You have to take a look at the highlighted parts. First the HyperLink widget (shown at the beginning of this post) is being referenced. Then a reference to the ImageBundle you have defined for your GWT module is created. This bundle is needed to reference the image you'll show on the HyperLink widget. The resource="{res.add}" will be translated to a call of setResource(ImageResource). The passed ImageResource is the one defined in your ImageBundle.
public interface IDevbookImageBundle extends ClientBundle {
 ...
 @Source("com/devbook/images/add.png")
 ImageResource add();
 ...
}
The final result:

GWT, App Engine and App Engine Data Classes

I currently have some time before starting with my Master thesis project which will bring me back to Android programming. So to make use of that, I started to develop a project I already wanted to implement a couple of years ago, but due to my Master studies I didn't have the time to. I'll need some beta testers soon, so keep track of my blog here to catch the moment when everything goes online.
What I can reveal so far is that it will be a web application, using Google's GWT and it will be hosted on Google's cloud computing platform App Engine.

Today I was finishing the implementation of the basic CRUD operations, using JDO and App Engine's DataNucleus DataStore. Now the app possibly needs to store large strings surely more than 255 characters. You'd think that shouldn't be a problem, but App Engine's DataStore has some implications one should be aware of. Beside these, there are some well defined core value types, under which there is the restriction that you have to use the com.google.appengine.api.datastore.Text instead of the String datatype if you plan to store more than 255 character strings. Ok, that shouldn't be a problem for us, should it? Well...not exactly. If you plan to use App Engine together with plain old JSP or whatever view technology that it won't be a problem, but if you use GWT you have to keep in mind that you're implementing a client-server system. The difference: the GWT client lives within the browser. So the data has to be transferred between the two end-points and has to be serializable accordingly. com.google.appengine.api.datastore.Text isn't serializable though. This means you cannot share your POJOs between your GWT client app and server-side code. Now you have different possibilities. Some that come to my mind right now are..

  • using DTOs (Data Transfer Objects) which isn't that comfortable 'cause it causes a lot of boilerplate code
  • writing a serializable version of com.google.appengine.api.datastore.Text data class.
Fortunately a guy has already implemented such a serializable version of Text and provides it for free. I just tried it out and it works seamlessly, without writing a single additional line of code. Here some steps on how to use it (available descriptions on the web are really bad).
  1. Download the necessary jar files from http://www.resmarksystems.com/code/:
    appengine-utils-client-1.0.jar
    appengine-utils-server-1.0.jar

  2. Include the appengine-utils-client-1.0.jar in your build path. Copy the appengine-utils-server-1.0.jar to your WEB-INF/lib folder.

  3. On your GWT module file add the following:

    <inherits name="com.resmarksystems.AppEngineDataTypes"/>
    
    
  4. Restart your GWT app or compile it and everything should work as expected.
Resmarksystem's version doesn't just provide serializable versions of Text but also for Key, ShortBlob, Blob, Link, User.
If you get exceptions like
java.lang.ClassCastException: java.lang.String cannot be cast to com.google.appengine.api.datastore.Text
or
An IncompatibleRemoteServiceException was thrown while processing this call. 
then it's probably because you didn't correctly include the jar files as mentioned in step 2 above.

DockLayoutPanel doesn't work correctly??

Suppose you'd like to create a layout like the following using GWT:


With GWT 2.0 the documentation suggests to use the DockLayoutPanel.
<g:DockLayoutPanel unit='EM'>
  <g:north size='4'>
    <g:Label>Header</g:Label>
  </g:north>

  <g:west size='16'>
    <g:Label>Navigation</g:Label>
  </g:west>

  <g:center>
    <g:ScrollPanel>
      <g:Label>Content Area</g:Label>
    </g:ScrollPanel>
  </g:center>
</g:DockLayoutPanel>

However pay attention, this won't work if you use the standard mechanism like
public void onModuleLoad() {
 RootPanel.get("main").add(new MainUI());
}
where the new MainUI() contains the DockLayoutPanel as root element (I assume you're using GWT's new UiBinder mechanism), then the DockLayoutPanel won't work surprisingly.

Instead you have to use
public void onModuleLoad() {
   RootLayoutPanel panel = RootLayoutPanel.get();
   panel.add(new MainUI());
}

HowTo: Launch JavaScript after async postback of UpdatePanel

Assume the scenario where you want to launch a JavaScript function after your UpdatePanel finished to do its async postback. This turns out to actually be quite simple. What you do is to use the ScriptManager.RegisterStartupScript(...) method.

ScriptManager.RegisterStartupScript(btnSave, this.GetType(), "myScriptKey", "myFunction()", true);
The only thing I found that people misdo is to not specify the correct instance (1st parameter) that caused the asynchronous postback to fire and thus the UpdatePanel to do the postback. In such a case it will just fail silently.

GWT DecoratorPanel style problems

I just experienced a nice side effect that happens if you use a DecoratorPanel. In my example it contained a list of items and everything is fine.

Decorator panel with no width indication
So far, everything is shiny. Bad things start when you want your DecoratorPanel to expand on the whole width of your page. So you add a width="100%" and get this
Decorator panel borders totally not working

Of course this is a style problem. Some browsing on the web and by reading through bug reports I came out with the following piece of CSS you have to place in your main GWT application's CSS file:
.gwt-DecoratorPanel {
    table-layout: fixed;
}
.gwt-DecoratorPanel .topLeft,
.gwt-DecoratorPanel .topRight {
    width: 5px;
}
Refresh your browser and everything should work fine.

Reloaded: Clean up your folder. For OSX

When downloading files from the web I usually have a predefined folder where all the downloads from my different browsers are stored. It doesn't take long till that folder grows to quite a remarkable size. Sorting out the files which are still needed is then a cumbersome and time-consuming process. Therefore, years ago I created a Java console app which takes care of removing files of a certain age.

Since I own a Mac this has become even more easy. For instance, to delete all files from a folder which haven't been accessed for 90 days and more, all you have to do is to create an automator script that executes the following unix shell command:

find /Users/Juri/Downloads/* -type f -atime +90 -exec rm -f {} \;
Note the usage of the parameter -atime. According to the man page
-atime n
     File  was  last  accessed n*24 hours ago.  When find figures out
     how many 24-hour periods ago the file  was  last  accessed,  any
     fractional part is ignored, so to match -atime +1, a file has to
     have been accessed at least two days ago.
This parameter assures that files which you often touch (open/modify) will not be deleted from the folder. It would be somehow wrong to use -mtime.

In addition after the overall cleaning process of the files you should get rid of empty folders which is done by invoking
find /Users/Juri/Downloads/* -type d -depth -empty -exec rmdir {} \;

Now you can combine everything in an Automator script and launch it at login time and voilĂ . From now on you don't have to care any more about cleaning your downloads folder :)

(P.S.: For future reference you may also like to redirect log entries into a file in order to know which files have been deleted)

Are anonymous Lambda style event handlers a readability killer?

A standard event handling method in C# looks something like this

public void SomeOtherMethod()
{
   MyClass aObj = new MyClass();
   aObj.MyCustomEventName += new EventHandler(OnMyCustomEventName);
   ...
}

private void OnMyCustomEventName(object sender, EventArgs e)
{
    //do what you need to
}
Pretty straightforward. Now since C# 3.0 you have the possibility to declare anonymous methods of the type
public void SomeOtherMethod()
{
   MyClass aObj = new MyClass();
   aObj.MyCustomEventName += delegate(Object sender, EventArgs e)
   {
      //do what you need to
   };
}
This makes it more concise since you define the event handling code directly at the point where you register the event.
This is, by the way, also possible in Java by declaring anonymous types such as
public void someOtherMethod(){
   ...
   MyClass aObj = new MyClass();
   aObj.setOnMyCustomEventListener(new IMyCustomEventListener(){

      public void onMyCustomEvent(...){
         //do what you need to
      }

   });
}
Note:IMyCustomEventListener is an interface and nevertheless we use the new to "instantiate" it. How's that possible? Well, this is a language feature which behind instantiates an anonymous object implementing the according interface.

It is very similar to the C# declaration of the event by using anonymous methods. Now, Lambda expression allow you to write this even more concisely
public void SomeOtherMethod()
{
   MyClass aObj = new MyClass();
   aObj.MyCustomEventName += (s,e) =>
   {
      //do what you need to
   };
}
Nice, isn't it? In this way defining an event is really fast. The only doubt I have is in terms of readability. Now clearly the example above is perfectly readable, but it is just a dummy example. But consider a method where you have to define lots of event handlers for different components. Then declaring all the handlers in the way above may soon get very smelly.
Note, beside others, one reason for applying Extract Method is for readability purposes. When reading over a method, your eyes should grasp the essence and you should be immediately able to tell what the method is about, although you may not know in detail what - for instance - the internally called method RetrieveExpiredItems(aProductBag) will do, but according to its name it will retrieve the expired items from an object called aProductBag and that may be enough because actually you may be interested in something completely different. On the other side, if you code everything in one method you may have substantial difficulties in finding the interesting piece because you're flooded with all the details you won't even care about.

This same principle may also apply to the "inline" definition of such event handlers using Lambda expressions. As long as they're simple "one-liners" it may not pose any major problem, but as soon as the code within these handlers starts to grow it may become problematic.