Just recently a user wanted to take some compiled MATLAB code and make it available online as a cgi script as part of their site. Very simple program that cleaves proteins, but this was the first I’ve ever encountered using compiled matlab code. Just like Java, matlab can compile mcode but required their runtime, MCR, to execute. Also like Java, loading up the whole runtime is rather intensive and when testing out the cgi script, it would run for a long time before printing a result. And I mean a long time in computer terms, almost 30 seconds, and for a cgi script that would just call the executable would do this for every request. Not good.
So I research and besides compiling into a standalone application, one can compile mcode into Java. Not only that but they provide examples of using this to host a matlab application using a Tomcat server. This solves the issue with loading the mcr, as the server handles that. Once I had it up and running, I was getting quick responses compared to the eternity it would take a cgi script. Only thing was, it took forever to figure out how to get the server to work correctly. Matlab’s documentation is great for their product, not much useful for anything beyond that.
First thing first in setting this up is installing the mcr on the server(or you could just install matlab itself, but I went with just the mcr). Matlab comes with the mcr installer, so its easy to just copy and run. Once installed, time to setup the environment. I could have put the LD_LIBRARY_PATH and XAPPLRESDIR variables directly into the tomcat settings config file, but I opted for placing it in /etc/profile.d. For example:
export LD_LIBRARY_PATH XAPPLRESDIR MCR_CACHE_ROOT
You’ll also notice MCR_CACHE_ROOT is set, that was the solution to the problem that I was having, but first one more step. The mcr also has a jar library, javabuilder.jar, that needs to be placed in /usr/share/tomcat/common/lib(ps if you are using Tomcat6 or higher, that would be tomcat/lib instead).
So now Tomcat is ready, but the mcr isn’t ready just yet. Turns out each compiled app uses its own cache folder and by default it tries to write to the home directory of the user that runs the application. Tomcat doesn’t really have a home directory and it was a source of much frustration trying to figure out the issue. Even the support tech wasn’t much help, I had to point it out to them when I had the epiphany. So I created a folder for it, set user tomcat as owner and set the environment variable and it worked.
I was able to then run the examples on tomcat and enjoy in the much faster response times.