Inserting javascript into GWT using JSNI

Posted in GWT, Java, Programming on January 27th, 2009 by Nick – 4 Comments

Sure the whole point of using GWT is so you don’t have to mess with that abortion known as javascript, but sometimes you may need (or actually want) to use javascript for something in your GWT application.  For this we use JavaScript Native Interface (JSNI).  JSNI uses the native keyword, so if you’ve used JNI (Java Native Interface) in the past you’ll have little to get used to.

I needed to use JSNI recently.  Since GWT doesn’t provide a way to bring the browser to the front or top like javascript does with it’s self.focus(); I was able to use JSNI to call that line of javascript.  Here’s a quick example:

public static native void bringToFront() /*-{
  self.focus();
}-*/;

Then all you need to do is call the bringToFront() method like you normally would.  Along with noticing in the native keyword, you’ll immediate see that the block looks commented out.  JSNI has two tokens to mark the beginning and end of your javascript the /*-{ marks the begin and }-*/ marks the end.  Everything in between those tokens are assumed to be javascript.

There are more examples on GWT JSNI site.

Simple Charts in GWT with gchart

Posted in GWT, Java, Programming on January 26th, 2009 by Nick – 9 Comments

I’ve been tasked with adding some simple charts to a GWT project and after looking at several APIs I’ve settled with trying out gchart.  A couple of reasons for this choice is:

  • gchart is 100% GWT (meaning it’s not a javascript wrapper)
  • It runs on the client-side. Some other charting APIs actually build the chart on the server-side as an image and return the link for the image.  This can be an advantage for some situations, so you may need to think about if you want a client-side or server-side render.
  • Open source under Apache License, Version 2.0
  • Very simple to use.

I put together a very simple example, and it shows how quickly you can build a chart.  The example is a compound interest financial calculator shown below (go ahead and try it out).  It has a few fields to enter your initial amount, annual contributions, interest rate, number of compounds per year and the number of years.  After clicking on the calculate button it will show your future amount and chart it.


In case the iframe doesn’t show up in your browser you can see and try the charting example here.

The simplicity of this charting API is the fact that the charts are GWT widgets.  Here’s the code for my compounding interest chart:

public class AmountChart extends GChart {
	public AmountChart() {
		setChartSize(240, 200);
		setPadding("4px");
		getXAxis().setAxisLabel("Years");
		getYAxis().setAxisLabel("$");
	}
 
	public void addPoint(double x, double y) {
		GWT.log("point added ("+x+", "+y+")", null );
		getCurve().addPoint(x, y);
	}
}

Then all I did was add it to the DecoratedTabPanel, put in the event listeners, the formula (which I got from wiki) and done.
You can download the full source here, and the entire application is client side.

Updated 2008-01-28: I updated the iframe that the form is in to be more friendly with IE. Also made a change recommended by John Gunther to remedy a problem with IE. Compiled using gchart 2.4 and I updated the downloadable source.

GWT Hosted Mode and Log4j

Posted in GWT, Java, Programming on January 19th, 2009 by Nick – 4 Comments

This is a short tutorial on getting log4j to run in the embedded Tomcat included with GWT.  Before I go on I need to say that log4j will only work on the server-side. GWT doesn’t support logging with log4j on the client side (yet…maybe). To log on the client side you’ll still have to use GWT.log()

There are four things we’ll need to accomplish:
1. Place the log4j.properties file
2. Write a servlet that will initialize the logger.
3. Modify the web.xml file.
4. Modify the GWT -shell and -compile scripts.

1. Place the log4j.properties file

Under <gwt-project>/tomcat/webapps/ROOT/WEB-INF/ create a “classes” dir.  The “classes” dir is where you put the log4j.properties file.  Here’s the log4j.properties file I’m using:
log4j.rootCategory=DEBUG, dest1, dest3

! Log to the console
log4j.appender.dest1=org.apache.log4j.ConsoleAppender
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%-5p %d{HH:mm:ss.SSS} [%-15.15t] [%-25.25c{1}] %m%n

! LOG TO A FILE
log4j.appender.dest3=org.apache.log4j.RollingFileAppender
log4j.appender.dest3.layout=org.apache.log4j.PatternLayout
log4j.appender.dest3.layout.ConversionPattern=%-5p %d{EEE MMM dd HH:mm:ss.SSS zzz yyyy} [%-15.15t] [%-25.25c{1}] %m%n

! Specify the file name
log4j.appender.dest3.File=./logs/hosted-log4j.log

! Control the maximum log file size
log4j.appender.dest3.MaxFileSize=3000KB
log4j.appender.dest3.MaxBackupIndex=3

2. Write a servlet that will initialize the logger.

Next you’ll want to have a servlet that will load the properties file and init the logger. This file (Log4JInitServlet.java) will go in the <gwt-project>/src/ dir.

package com.nick.example.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* Log4JInitServlet
*
* This class should get loaded first (based on the web.xml),
* so it can init the logger.
*
* @author Nick
*/
public class Log4JInitServlet extends HttpServlet {
  static final Logger logger = Logger.getLogger(Log4JInitServlet.class);
 
  public void init() throws ServletException {
    System.out.println("Log4JInitServlet init() starting.");
    String log4jfile = getInitParameter("log4j-properties");
    System.out.println("log4jfile: "+log4jfile);
    if (log4jfile != null) {
      String propertiesFilename = getServletContext().getRealPath(log4jfile);
      PropertyConfigurator.configure(propertiesFilename);
      logger.info("logger configured.");
    }else{
      System.out.println("Error setting up logger.");
    }
      System.out.println("Log4JInitServlet init() done.");
  }
}

This servlet should be loaded first, which can be accomplished by modifying the web.xml file.

3. Modify the web.xml file.

This file is located in <gwt-project>/tomcat/webapps/ROOT/WEB-INF/
My web.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>Log4JInitServlet</servlet-name>
    <servlet-class>com.nick.example.server.Log4JInitServlet</servlet-class>
    <init-param>
      <param-name>log4j-properties</param-name>
      <param-value>/WEB-INF/classes/log4j.properties</param-value>
     </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>shell</servlet-name>
    <servlet-class>com.google.gwt.dev.shell.GWTShellServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>shell</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Notice the line <load-on-startup>1</load-on-startup>, which tells tomcat to load the Log4JInitServlet first.

4. Modify the GWT -shell and -compile scripts.

Modify your gwt –shell and –compile files to add the log4j jar into the class path. Here’s my <project>-shell.cmd file. Take note of the log4j jar that I added.

[Windows]
@java -Xmx256M -cp “%~dp0\src;%~dp0\bin;C:/lib/gwt-windows-1.5.3/gwt-user.jar;C:/lib/gwt-windows-1.5.3/gwt-dev-windows.jar;C:/lib/gwt-windows-1.5.3/log4j-1.2.12.jar” com.google.gwt.dev.GWTShell -out “%~dp0\www” %* com.nick.example.HostedLog4j/HostedLog4j.html

[linux]
#!/bin/sh
APPDIR=`dirname $0`;
java -Xmx256M -cp “$APPDIR/src:$APPDIR/bin:$HOME/projects/gwt-linux-1.5.3/gwt-user.jar:$HOME/projects/gwt-linux-1.5.3/gwt-dev-linux.jar:$HOME/projects/lib/log4j-1.2.15.jar” com.google.gwt.dev.GWTShell -out “$APPDIR/www” “$@” com.nick.example.HostedLog4j/HostedLog4j.html;

Make sure to change the <project>-compile.cmd in the same way.
You can then run your <gwt-project>-shell.cmd and the logger should work. It will create a log directory in under <gwt-project> and place your log file inside there.

GWT-Ext to Ext-GWT

Posted in GWT, Java on January 13th, 2009 by Nick – 12 Comments

Trying both GWT-Ext and Ext-GWT

In trying to make a decision on whether to go GWT-Ext or Ext-GWT I’ve done some reading including the websites of those two technologies, forums, and various blogs like:

http://www.gwtsite.com/top-5-gwt-libraries/
http://roberthanson.blogspot.com/2008/04/gwt-ext-vs-ext-gwt.html
http://ajaxian.com/archives/to-gwt-ext-or-to-ext-gwt

The most talked about topic when discussing this comparison seems to be licensing, but I don’t want to spend much time on that.  Instead of comparing the two technologies line by line, I take a small existing vanilla GWT application and add new needed functionality such as drag and drop, resizable columns, sortable columns, and additional layouts.  This was done first using GWT-Ext and then again using Ext-GWT.  The opinions I gather are based on coding with both over a few days.

GWT-Ext Experience

This was actually my second choice, and became my first choice based on comparing the licenses of the two.  My first steps were changing out widgets used and hoping that the underlying code dealing with the model wouldn’t need to be modified (much).  Layouts are one thing I noticed that are considerably different.  Instead of using VerticalPanel or HorizontalPanel, you use a Panel and add a modifier to make it flow vertical or horizontal, much like Swing.  While this is good if you know Swing, and are starting the app from scratch, it can be a pain if converting like i am.

Another difference when dealing with going vanilla GWT to GWT-Ext was rewriting code that handles FlexTable or GridPanel updates or, in other words, the way you get data into the table.  In GWT land, you can treat the FlexTable as the data, much like a two-dim array, and set data to the cells.  GWT-Ext uses something called a Store, which is basically the data itself.  When you add to the Store, the GridPanel gets updated.  There are pros and cons to both methods I suppose, but that’s another discussion.  I will say the reason I stopped using GWT-Ext was because of problems rendering the grid to the screen when using the GridPanel with certain layouts.  I suspected this was due to it being a js wrapper.  It turned out there was a known bug which required a workaround just to get the grid to show.  After spending many hours dealing with this problem and a few others I decided I shouldn’t be wasting my time with something that has problems taking one panel and adding it to another like panel.add(grid).  In GUI building, an operation like that is simple and frequent.

On to Ext-GWT

Last thing I wanted to do was revert back and start again, but here it goes.

One big difference between the two Exts is that GWT-Ext is just javascript wrapper.  It’s visible while configuring because you’ll add scripts and javascript libraries to your public folder.  With Ext-GWT none of that needed to be done.  This is because Ext-GWT is a GWT library and doesn’t wrap javascript.  I like this.

So I start again changing out widgets, and notice that there’s almost no work to be done.  The new widgets use same function calls as old ones.  They did drop the ball on the Button class and it’s listener (actually, I don’t like the way events are coded).  Not sure why you would not stick with a ClickListener and onClick()….but whatever.   The layouts are similar, and they include VerticalPanel as well.  Changing the FlexTable out for the Grid took some work, but less than GWT-Ext.  It does use a StoreList (similar to GWT-Ext’s Store) but I felt it made a little more sense.  There was little time spent correcting column sizes and dealing with autofills, which makes me happy, and there were no issues getting the Grid to show up.

Final Decision

Well, everything was fine but another day has passed and I’m just not 100% happy with Ext-GWT.  Running the hosted browser and compiling has become slower than ever (still faster than GWT-Ext though).  I got to thinking and realized that the only enhanced component I really needed was the Grid over the FlexTable, and I did get the grid setup just like I wanted.  Since one of the things I really hated about Ext-GWT was the event handling code, I asked myself: Do I really need to have all of my buttons, checkboxes, panels, etc in Ext-GWT?  Can’t I just use the fancy Grid and then make everything else using vanilla GWT?  I decided to try this, and not only did it work perfectly, but there was noticably lower load times and increased speed.

My final take is, use vanilla GWT for events and where you can use it.  For GWT components that are missing features you need use Ext-GWT.

Java EchoServer Example

Posted in Java, Programming on January 11th, 2009 by Nick – Be the first to comment

I’m using this post to experiment with syntax highlighting in my blog.  Recently a friend needed a program to echo data on a socket while he was testing an internet appliance and some other network enabled hardware so I figured I’d just use that code as my example.

The EchoServer will open a listen socket on port 4444.  Compile it, run it and then to test it you can open a command prompt and type telnet localhost 4444

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * @author NickC
 */
public class EchoServer {
   private static final int BUFFER_SIZE = 256; 
   private static int listenPort = 4444;
 
   public static void main(String[] args) throws Exception{
      ServerSocket serverSock = new ServerSocket(listenPort);
      System.out.println("listening on port "+listenPort);
      Socket sock = serverSock.accept();
      System.out.println("new connection " + sock);
 
      InputStream sockIn = sock.getInputStream();
      OutputStream sockOut = sock.getOutputStream();
      byte[] buffer = new byte[BUFFER_SIZE];
      while(true) {
         Thread.sleep(50);
         int count = 0;
         if ((count = sockIn.available()) > 0) {
            if (count >= buffer.length) {
               count = buffer.length;
            }
            count =  sockIn.read(buffer, 0, count);
            System.out.println("echoing "+count+" bytes");
            sockOut.write(buffer, 0, count);
            sockOut.flush();
         }
      }
   }
}

Source in a file: EchoServer.java