Friday, April 19, 2013

JAVA_HOME annoyances on Linux (Ubuntu)

Just a quick writeup about an annoyance I come across every time I need to use Java on a Linux server. In my case I use the Ubuntu (12.04) server distro, so I'm unsure as to how this behaves on the other distro's. However, setting up the correct JAVA_HOME environment variable for a user never seems automatically done by the system or the package installers.

Tired of manually keeping track of the correct JAVA_HOME environment, I wrote this little script that is called in profile.d at logon time. It simply checks the /etc/alternatives/java symlink and resolves it. Then cuts of the /bin/java and optionally the /jre to construct the JAVA_HOME path. I know for sure that on some systems or in some situations this will not suffice, but on my system it does.

Put the following code in a file in /etc/profile.d (e.g. /etc/profile.d/java.sh):
JAVA_SEARCH="/etc/alternatives/java";

# Resolve link
INSTALLED_JAVA_ALTERNATIVES=`readlink -f ${JAVA_SEARCH}`

# Test if it is set
if [[ $INSTALLED_JAVA_ALTERNATIVES != $JAVA_SEARCH ]]; then
  # Test if the full path to java binary ends with /bin/java
  if [[ $INSTALLED_JAVA_ALTERNATIVES =~ .*/bin/java ]]; then
    JAVA_HOME_CANDIDATE=${INSTALLED_JAVA_ALTERNATIVES:0:-9}
    if [[ $JAVA_HOME_CANDIDATE =~ .*/jre ]]; then
      JAVA_HOME_CANDIDATE=${JAVA_HOME_CANDIDATE:0:-4}
    fi

    # Verify JVM
    if [[ -x ${JAVA_HOME_CANDIDATE}/bin/java ]]; then
      # Set the candidate as HOME
      export JAVA_HOME=${JAVA_HOME_CANDIDATE}
    fi
  fi
fi
When I happen to change the default Java JVM through the provided Ubuntu commands, this piece of scripting will make sure that the JAVA_HOME is correctly updated as well (after the next login). The script is very defensive, so if something isn't returned as expected then it will simply stop and not set a JAVA_HOME at all. Also, a user can still manually override the JAVA_HOME in his private profile.

As always, feel free to throw in a comment. The script is provided as-is and if your head explodes because of it, then don't blame me :)