Wednesday, September 28, 2011

Fork off a process and specify a timeout value for it to complete in Java

I have a personal preference to code in C/C++ or Java. However, I'll swap between any other programming language I know if I think it will solve my problem. For what it's worth, people often get frustrated when they ask me what language is the best (or worse, or most important, etc..) because I'll often ask them what they know best, and state that as my answer.

Anyhow, I've had this need to interact with a couple of programs that have no API whatsoever. My solution has been to run the suckers and grab their output. For that reason, I got to learn a bit about how to execute a command in a separate process in Java. Through a class called ProcessBuilder (java.lang package), it allows one to get the input or output stream of the subprocess, as well as the exit status (among other available information).

Quick example:

import java.io.*;
import java.util.*;
public class MyExample {
  public static void main(String args[]) throws IOException {
    if (args.length <= 0) {
      System.err.println("What should I run?");
      System.exit(-1);
    }
    Process process = new ProcessBuilder(args).start();
    InputStream is = process.getInputStream();
    InputStreamReader reader = new InputStreamReader(is);
    BufferedReader buffer = new BufferedReader(
reader);
    String line;
    System.out.printf("Output of running %s is:", Arrays.toString(args));
    while ((line = 
buffer.readLine()) != null) {
      System.out.println(line);
    }
  }
} 


And while I won't go into details of how to customize your ProcessBuilder inputs, you can try this out with > java MyExample ls.

My problem is that the software I'm executing in the subprocess, forks other threads and processes. Which screws up the process' signaling in Java. So I actually do the process forking in another C-based software I coded, and use Java to call that one. (Complicated tongue-twister, right?) But, this requires that the Java process waits until my C code finishes, which has to wait until the other programs finishes. For that reason, I had to include a  process.waitFor(); right after the start command.

This leads to the title of this post: How to specify a time out value to the waitFor()? Apparently waitFor() has no timeout. Which means that I need to create yet another Thread just to wait for it, and join both of the after the timeout expires.


  1. Thread thread = new Thread(new Runnable()  
  2. {  
  3.     public void run()  
  4.     {  
  5.         try  
  6.         {  
  7.             process.waitFor();  
  8.         }  
  9.         catch (Exception e) { e.printStackTrace(); }  
  10.     }  
  11. });  
  12. thread.start();  
  13. thread.join(15000); // 15 seconds  


It's one of those things that I'm not necessarily bragging about, but not ashamed either. And most importantly, I don't want to forget. :)

Monday, September 26, 2011

Overlay plots in R (or "Is there a command equivalent to 'hold on' of MATLAB in R?")

So used to the simple method of plotting graphs in MATLAB, I've run into a couple of quirky situations while using R. As the tile of this post describes it, the latest problem I've had was when I was trying to overlay different plots on the same graph.

In MATLAB, this is easy: we just plot, then issue a 'hold on', then plot again. Done!

In R, I've finally found a solution: between two calls to plot, I set a 'par(new=T)'. Additionally one should specify the xlim as well as the ylim=c(y1,y2) in each call to plot() to get proper matching of the overlaid plots.

Quick example (YMMV):


f1.range = range(f1.results)
f2.range = range(f2.results)
plot(f1, broken = TRUE, bcontrol = list(style = "gap"), ylim = range(f1.range, f2.range))
par(new=T)
plot(f2, ylim = range(f1.range, f2.range), pch=24)

Monday, September 5, 2011

Get HTTP session variables in Spring MVC controller

Normally I don't care to have Request or Session data "leaking" around my code, and limit it's awareness to the controller. But for this small project I'm porting from a desktop version of the software to a web-enabled one (Spring MVC), I didn't want too many layers of abstractions. In case I ever need to do this again:


ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
User loggedInUser = (User)attr.getAttribute("loggedInUser", RequestAttributes.SCOPE_SESSION);

Killing tomcat when it runs out of memory...

I've been pushing the limits on a large file parsing lately and, more often than not, have had to resort to manually killing the tomcat process. Normally, I'd just do a 'ps aux | grep tomcat' and then kill the process. However, I've grown tired of this and thought it would be more interesting to have a one-liner do it for me.


ps aux | grep tomcat | awk '{print $2}' | xargs kill -9

Yes, there are ways to reduce the amount of data from the original 'ps' command.. but 'ps aux' is aliased on my machine, and I'm don't really care about the extra processing this will incur at this moment... :)

Thursday, July 14, 2011

How to rebuild the LaunchServices database

I discovered I had 6 versions of GIMP on my computer (although only one was active). If your "Open With" menu shows applications that are no longer installed, or shows some of them as duplicates, you can use the following Terminal command to rebuild your LaunchServices database:

/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user -f

Wednesday, July 13, 2011

How to modify the FIGURE prefix in LATEX

How to change the prefix of all figure captions LaTeX? For example, IEEEtran defaults to "Fig.", and I wanted "Figure."?
\renewcommand{\figurename}{Figure}

Monday, July 11, 2011

How to synchronize files through a SSH shell to a unix server

I have my own server, but until today I'd just manually update the files I changed. Never once thought of writing a script to do it for me... Until today. Solution? RSYNC!


rsync -e ssh -avz ./FOLDER ssh.server.address:NEW_FOLDER_LOCATION/

rsync's speciality lies in its ability to analyse files and only copy the changes made to files rather than all files. This can lead to enormous improvements when copying a directory tree a second time.

-a Archive mode, most likely you should always keep this on. Preserves file permissions and does not follow symlinks.
-v Verbose, lists files being copied
-z Enable compression, this will compress each file as it gets sent over the pipe. 
-e ssh Uses ssh as the transport, this should always be specified.


Make sure that rsync is installed on both client and server machines. I've heard that rsync has problems with trailing spaces and characters, so notice that there is NONE on the folder, but there is one on the new folder location.