Thursday, May 26, 2011

Calling Java applet from Javascript

Hello.

Recently we were busy adding upload media to our webapp, it was required to upload large media files (more then 4G) from client browser to the main site while monitoring the progress. It was required that the user will be able to cancel downloads and have many possibly download running in parallel.

At first we tried to implement this using plupload which is flash client that use multi-part post, the sever side was implemented as Java servlet , this seems to works for small files but fail on large files, in addition memory was not free on some OS.

We next tried native html5 file upload that turn out to suffer with the same sickness, at the same time we noticed that jetty conent-length attibute is of type int and not long, that rules out both html5 upload and the multi part post approach.

Our last try was an FTP applet (based on our in house FTP client) that upload files to a Mina based FTP Server.
That turn out to be really successful, we let the applet handle the file choosing and the FTP to the server while keeping the UI in the Javascript side.
There were 2 things that gave us hard time while developing this applet.


  • The first is the security, it turns out that even while the applet is fully signed and allow all security, it can not do that from a thread that was called from Javascript -- Oracle doc has only one short sentence about this property and it took us a while finding it.What we did is use the command pattern, having one thread created from the applet constructor, this threads allow to do all since it does not a thread created for Javascript command execution. A request from Javascript create a command that returns a Future, those commands than inserted into a queue to be processed by the thread created at the applet constructor.This seems to work well. Pay attention that you should not use Java Executors to implement this queue since Java Executors are lazy in its thread creation.
  • The second issue related to the fact that embedding Java Applet in a page make the page load un responsive while the Java Plugin is loaded -- so we preferred to load the Applet dynamically the first time that the user try upload, this turn out to be tricky on Firefox on Mac and on IE you need to create a new IFrame for the applet, while in Firefox on Linux and Windows you can load the applet dynamically directly to your page.

The Applet Code code.