Feb 10 09

In a recent stackoverflow.com question I asked for input on how to implemented animated GIFs in SWT table/tree viewer cells. Below is some code of the final solution.

Animation thread

The animation thread can be asked for the “current frame index” (CFI) by interested parties. The CFI thusly denotes the frame of an animated GIF which should be rendered. LabelProviders are the interested parties in this context because they actually render the images.

The thread increments the CFI in its run method. Also, Display#asyncExec is triggered in the run method. During the async execution the table/tree is ask to redraw and update – see lines 69ff.

/**
 * This animation thread doesn't actually animate anything itself. However, it acts as a pace maker
 * for other components that are able to render animated images. In a loop this thread marks
 * designated columns of a tree viewer (see constructor) for redrawing and calls
 * update() on the tree itself. Label providers on the other hand ask this thread for
 * the current frame index whenever they're triggered provide an image for the designated column.
 *
 * The viewer's content provider is ideally suited to control the life cycle of this thread. It can
 * create/destroy a thread instance whenever the viewer's content is updated.
 *
 */
public class BuildColorAnimationThread extends Thread {

  private final TreeViewer viewer;
  private final int animationColumnIndex;
  private final ImageLoader sampleImage;
  private int currentFrameIndex;
  private boolean cancel;
  private static BuildColorAnimationThread runningInstance;

  /**
   * C'tor which sets this instance to be the one running instance.
   *
   * @param viewer the viewer whose content should be animated
   * @param animationColumnIndex the index of the column to be animated
   * @param sampleImage a sample image which resembles the animation images in the viewer, the
   *        thread uses it to extract repeat-counts and frame delays
   * @see BuildColorAnimationThread#getRunningInstance()
   */
  public BuildColorAnimationThread(final TreeViewer viewer, final int animationColumnIndex,
      final ImageLoader sampleImage) {
    this.viewer = viewer;
    this.animationColumnIndex = animationColumnIndex;
    this.sampleImage = sampleImage;
    this.currentFrameIndex = 0;
    BuildColorAnimationThread.setRunningInstance(this);
  }

  /**
   * Returns the running instance of the animation thread or null if there's none.
   *
   * @return the running instance of the animation thread or null if there's none
   */
  public static BuildColorAnimationThread getRunningInstance() {
    return runningInstance;
  }

  private static void setRunningInstance(BuildColorAnimationThread runningInstance) {
    BuildColorAnimationThread.runningInstance = runningInstance;
  }

  @Override
  public void run() {
    int repeatCount = this.sampleImage.repeatCount;
    /*
     * The repeat count takes into consideration that an animated image might not be animated
     * infinitely but only for a given number of loops.
     */
    while (!this.cancel && !this.viewer.getTree().isDisposed()
        && (this.sampleImage.repeatCount == 0 || repeatCount > 0)) {
      this.viewer.getTree().getDisplay().asyncExec(new Runnable() {

        public void run() {
          final BuildColorAnimationThread thread = BuildColorAnimationThread.this;
          final Tree tree = thread.viewer.getTree();
          if (!tree.isDisposed()) {
            final Rectangle clientArea = tree.getClientArea();
            // Marks ONLY the animation column to be redrawn and not the entire table!
            tree.redraw(clientArea.x, clientArea.y, tree.getColumn(thread.animationColumnIndex)
                .getWidth(), clientArea.height, false);
            tree.update();
            // During the first loop currentFrameIndex=0...then currentFrameIndex=1,etc.
            thread.currentFrameIndex =
                (thread.currentFrameIndex + 1) % thread.sampleImage.data.length;
          }
        }
      });

      try {
        int ms = this.sampleImage.data[this.currentFrameIndex].delayTime * 10;
        if (ms < 20) {
          ms += 30;
        }
        if (ms < 30) {
          ms += 10;
        }
        Thread.sleep(ms);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
      /*
       * If the last frame was signaled as being the current frame, decrement the repeat count and
       * start again.
       */
      if (this.currentFrameIndex == this.sampleImage.data.length - 1) {
        repeatCount--;
      }
    }
  }

  /**
   * Returns the index of the current frame. Animation providers (i.e. renderers) call this method
   * in order to find out which frame of an animated image they should render at any given point in
   * time.
   *
   * @return frame index starting at 0
   */
  public int getCurrentFrameIndex() {
    return this.currentFrameIndex;
  }

  /**
   * Signals the thread to stop. It will finish the current execution in its run method and will
   * then stop.
   */
  public void cancel() {
    this.cancel = true;
  }
}

LabelProvider

I use my own implementation of an OwnerDrawLableProvider which paints a static image if the icon doesn’t have to be animated. If it needs to be animated (based on some attribute of the row’s input) it paints the frame of an animated GIF. The index of the frame to draw is determined by the animation thread shown above. Hint: the getImage() method is called by paint().

  /*
   * For each (animated) job color the provider keeps a map of frame_index-to-image entries. This
   * speeds up the process of delivering images for rendering because they don't have to be created
   * all the time from ImageData objects.
   */
  private final Map> imagesMap =
      new HashMap>();

  @Override
  protected Image getImage(Event event, Object element) {
    final IJob job = (IJob) element;
    Image image = BuildColorInfo.getIconImage(job.getColor());
    if (job.isRunning()) {
      final BuildColorAnimationThread animationThread =
          BuildColorAnimationThread.getRunningInstance();
      /*
       * Should no animation thread be running, the static image fetched a few lines above will be
       * returned.
       */
      if (animationThread != null) {
        final int currentFrameIndex = animationThread.getCurrentFrameIndex();
        Map images = this.imagesMap.get(job.getColor());
        if (images == null) {
          images = new HashMap();
          this.imagesMap.put(job.getColor(), images);
        }
        image = images.get(Integer.valueOf(currentFrameIndex));
        if (image == null) {
          image = createNewImage(event, job.getColor(), currentFrameIndex);
          images.put(Integer.valueOf(currentFrameIndex), image);
        }
      }
    }
    return image;
  }

  private Image createNewImage(Event event, JobColor color, int currentFrameIndex) {
    final ImageLoader imageLoader = BuildColorInfo.getImageLoader(color);
    return new Image(event.gc.getDevice(), imageLoader.data[currentFrameIndex]);
  }

“Controller”

The controller is responsible to start/stop the animation thread. Basically, whenever the viewer’s input changes the running animation thread must be canceled and a new thread must be started. The best hook for that is the viewer’s content provider – an implementation of I<Tree|Table>ContentProvider as it declares an inputChanged() method.

    @Override
    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      if (this.animationThread != null) {
        this.animationThread.cancel();
      }
      // Animates the first column.
      this.animationThread =
          new BuildColorAnimationThread((TreeViewer) viewer, 0, BuildColorInfo
              .getImageLoader(JobColor.BLUE_ANIME));
      this.animationThread.start();
    }

The code presented here was implemented for H2Eclipse, the Hudson plugin for Eclipse.

Feb 10 08

Use the JavaScript console in Firebug and run the following script snippet:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", "the_url",true); // Async HEAD request (relative path to avoid cross-domain restrictions)
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) { // make sure the request is complete
    alert(xmlhttp.getAllResponseHeaders()) // display the headers
  }
}
xmlhttp.send(null); // send request
Jan 10 28

cache-control, pragma, no-cache, expires header, and tons more. I learned a lot from the below referenced articles.

Caching tutorial for web authors: http://www.mnot.net/cache_docs/

jGuru forum question: http://www.jguru.com/faq/view.jsp?EID=377

Jan 10 18

This is a follow-up for the Beware of WebSphere admins post just below.

My first immediate conclusion after the described deployment problems was to ban the use of the jsession cookie  in future applications. If the application always includes the jsessionid parameter in URLs there’s nothing that can go wrong during deployment in terms of cookie paths.

Contemplating a second longer made it obvious that maybe this wouldn’t be such a wise decision after all. There are number of developers who try to enforce the exact opposite because the jsessionid URL parameter can be considered harmful. I highly recommend reading the following two blog posts that support this thesis:

http://randomcoder.com/articles/jsessionid-considered-harmful
http://boncey.org/2007_1_8_purging_jsessionid

Jan 10 18

A lot can go wrong when you deploy a simple Java EE application in IBM WebSphere – even if the application needs nothing but a Servlet container.

We recently shipped a JEE application to the customer. Although it was packaged in an EAR file, because the customer required it, it needs nothing but what the Servlet specification mandates. The application was tested both at other customer sites and on our internal infrastructure. Some customers use JBoss, others Oracle Weblogic and we use Tomcat internally. This new customer uses IBM WebSphere *sigh* – not our dearest friend, but so what. So we set up a WebSphere test server in-house and successfully deployed the application.

The customer asked us to fill in a several page form to specify all the necessary configuration parameters our application required. For almost all fields we settled for the provided default values because all we basically needed was a JNDI name pointing to a datasource.

Needless to say the application didn’t run out-of-the-box at the customer site.

Given the fact that the application runs fine on all but this customer’s infrastructure neither the customer nor I thought it necessary for us to provide on-site support. The log files we got for analysis indicated that somehow they seemed to have a multi-threading or multi-session problem. For two weeks the customer’s network and WebSphere specialists tried to figure our what was going on. When they were at their wits end, my repeated offer to send one of our engineers over was accepted. When he, too, was stuck a day later I asked him to share his screen remotely and show me request/response headers in HttpFox.

It became apparent immediately why our application constantly created new sessions. The cookie path for the jsessionid cookie was neither ‘/’ nor was it equal to the context root of our application. Hence, with every response our application returned a new jsession cookie, but when the browser sent a new request to the application it didn’t include the session id – because it didn’t find a cookie with a path that matched the application’s context root. Usually you’d notice this immediately because you’d have to authenticate yourself (i.e. log in) constantly with every request. Since the customer uses SSO this was done transparently in the background.

So, what’s this got to do with the WebSphere admin? Well, in the form mentioned above we were asked for the application cookie path. The default value was ‘/’ and therefore we hadn’t changed it. The admin, however, acted on his own authority and changed this to something else.

Dec 09 12

I just invested 30min to find tools/libraries which allow me to use PHP scripts instead of Java on the server when the front end is GWT. There are various potential channels through which GWT and PHP can talk to each other. GWT RPC, ideally native or over JSON/XML would certainly be the most obvious choice.

My Internet search didn’t turn up a whole lot of useful stuff…

http://code.google.com/p/gwtphp/

http://code.google.com/p/gwtamp/

http://code.google.com/p/lacertae/

http://download.boulder.ibm.com/ibmdl/pub/software/dw/xml/x-gwtphp/x-gwtphp-pdf.pdf

http://angel.hurtado.googlepages.com/tutorialgwt2

Sep 09 22

In most programming languages the regular expression pattern to find the digit ’1′ surrounded by ‘;’ and other digits would be something like

[;\d]*1[;\d]*

So, the pseudo character class “; or digit” is matched zero or more times, then the digit 1 is matched followed by zero or more “; or digit”s. A few examples:

<property id="foo" value=";1;;;"/>
yet another regexp test with 1;;;;3xxyyzz...
well I think you get the picture with this ;;;;1 shizzle even if it's ;1;2;3; or 123

With Oracle SQL, however, it’s a slightly different story. \d is not supported i.e. not properly recognized as being the character class for digits. However, the character class 0-9 which generally is the equivalent to \d seems to be supported. In Oracle you could therefore use

[;0-9]*1[;0-9]*

As far as I can tell this is an undocumented feature. The official Oracle regexp documentation only mentions that it supports the regular POSIX character class [:digit:]. Watch out, the equivalent to \d is the whole expression [:digit:] and not just :digit:. I was first fooled by the extra [] around the character class designator… So, according to the documentation you’d have to use

[;[:digit:]]*1[;[:digit:]]*
Sep 09 19

Finally, the first version of the iCalendar factory is here!

It generates iCalendar objects and streams them as .ics attachments to your browser. URL parameters define all the attributes of the iCalendar. This allows to generate calendar entries from virtually everywhere.

Sep 09 11

Yet another software configuration issue that I wasted a few hours at today.

Environment

Apache 2.2.13 connect to Tomcat 5.5 with mod_jk (ajp13). Apache requires basic-auth for “/” i.e. for all URLs it serves. Just to be 100% precise, Tomcat runs as a WTP server “inside” Eclipse. However, the fact that it’s not a standalone instance has no effect to either the problem or the solution.

Problem

I noticed that request.getUserPrincipal() returned null in my Servlet filter although basic-auth in Apache was successful. By raising the mod_jk log level to debug (JkLogLevel debug) and looking at the mod_jk.log I could confirm, however, that mod_jk at least passed the remote user along in the request.

Solution

Set tomcatAuthentication=”false” for the AJP/1.3 connector in server.xml. The parameter is explained in the Tomcat connector documentation: “If set to true, the authentication will be done in Tomcat. Otherwise, the authenticated principal will be propagated from the native webserver and used for authorization in Tomcat. The default value is true.”

A thread from the tomcat-users mailing list archive helped a lot: http://www.mail-archive.com/users@tomcat.apache.org/msg55080.html. I didn’t initially find that through a web search because I kept looking for something like “principal null Tomcat Apache mod_jk” instead of “REMOTE_USER null”.

Aug 09 16

On some of my Eclipse workspaces to Galileo update failed in the SVN department (Subversive). Activating anything remotely related to Team/SVN features triggered an error. The workspace log contained:

!MESSAGE An error occurred while automatically activating bundle org.eclipse.team.svn.core (512).
!STACK 0
org.osgi.framework.BundleException: Exception in org.eclipse.team.svn.core.SVNTeamPlugin.start() of bundle org.eclipse.team.svn.core.
 at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:805)
...
Caused by: java.io.StreamCorruptedException: invalid type code: 00
 at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1356)
 at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
 at org.eclipse.team.svn.core.svnstorage.AbstractSVNStorage.loadLocationsFromFile(AbstractSVNStorage.java:551)

I tried to start Eclipse with the -clean option – didn’t help. Then I updated the Subversive SVN plugin and all connectors – didn’t help.

What eventually did help was to remove all org.eclipse.team.* folders in the workspace’s .metadata\.plugins folder.