Friday, September 30, 2011

Determining Linux Distro/Version

# Determine the Linux distribution and version that is being run.
   #
   # Check for GNU/Linux distributions
   if [ -f /etc/SuSE-release ]; then
     DISTRIBUTION="suse"
   elif [ -f /etc/UnitedLinux-release ]; then
     DISTRIBUTION="united"
  elif [ -f /etc/debian_version ]; then
    DISTRIBUTION="debian"
  elif [ -f /etc/redhat-release ]; then
    a=`grep -i 'red.*hat.*enterprise.*linux' /etc/redhat-release`
    if test $? = 0; then
      DISTRIBUTION=rhel
    else
      a=`grep -i 'red.*hat.*linux' /etc/redhat-release`
      if test $? = 0; then
        DISTRIBUTION=rh
      else
        a=`grep -i 'cern.*e.*linux' /etc/redhat-release`
        if test $? = 0; then
          DISTRIBUTION=cel
        else
          a=`grep -i 'scientific linux cern' /etc/redhat-release`
          if test $? = 0; then
            DISTRIBUTION=slc
          else
            DISTRIBUTION="unknown"
          fi
        fi
      fi
    fi
  else
    DISTRIBUTION="unknown"
  fi

  ###    VERSION=`rpm -q redhat-release | sed -e 's#redhat[-]release[-]##'`

  case ${DISTRIBUTION} in
  rh|cel|rhel)
      VERSION=`cat /etc/redhat-release | sed -e 's#[^0-9]##g' -e 's#7[0-2]#73#'`
      ;;
  slc)
      VERSION=`cat /etc/redhat-release | sed -e 's#[^0-9]##g' | cut -c1`
      ;;
  debian)
      VERSION=`cat /etc/debian_version`
      if [ ${VERSION} = "testing/unstable" ]; then
          # The debian testing/unstable version must be translated into
          # a numeric version number, but no number makes sense so just
          # remove the version all together.
          VERSION=""
      fi
      ;;
  suse)
      VERSION=`cat /etc/SuSE-release | grep 'VERSION' | sed  -e 's#[^0-9]##g'`
      ;;
  united)
      VERSION=`cat /etc/UnitedLinux-release`
      ;;
  *)
      VERSION='00'
      ;;
  esac;

  echo ${DISTRIBUTION}${VERSION}

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... :)