Checking Java versions from a batch script
Building software, and by building I mean the actual compilation aspect, is not that complicated. A couple commands and out pops a .class or .exe. When you want to automatically grab it out of version control, build, package, deploy and test it it can get a little hairy.
We’ve recently resurrected one of these systems which has ant at it’s core. It’s certainly not efficient with tonnes of environment assumptions and no safety nets to speak of.
Here is the first of those safety nets; a little batch script which wraps the ant task that launches the whole shebang and
- ensures that changes to the environment stay within the confines of the script
- checks that you have java in your path
- that the java version is the appropriate one
- that you have ANT_HOME set
- sets the classpath appropriately so the listener works
What it doesn’t do is always clean up after itself if something goes wrong, but I hope to catch and handle those inside the actual ant script.
Anyhow, after the cut is the actual script because it is rather large and going to bump things down artificially.
@ECHO OFF
setlocal
rem
rem check for correct java version
rem
:start_java_version
rem this is what is on slider now
set CORR_VERSION="1.4.2_04"
if "%JAVA_HOME%" == "" goto no_java_home
:have_java_home
"%JAVA_HOME%/bin/java" -version 2>ab_java_version.txt
goto check_java_version
:no_java_home
java -version 2>ab_java_version.txt
goto check_java_version
:check_java_version
for /f "tokens=3" %%g in (ab_java_version.txt) do (
if not %%g == %CORR_VERSION% goto wrong_java_version
goto end_java_version
)
:wrong_java_version
echo Expected JDK %CORR_VERSION%. Please set fix your JAVA_HOME or path and try again.
goto done
:end_java_version
rem
rem set ANT_HOME if it is not already set
rem
:start_ant_home
if "%ANT_HOME%" == "" goto no_ant_home
:have_ant_home
rem add it to the front of the path
set PATH="%ANT_HOME%\bin";%PATH%
goto end_ant_home
:no_ant_home
echo Set your ANT_HOME variable before running this script
goto done
:end_ant_home
rem CLS
set CLASSPATH=.;.\\\\log4j\\\\log4j-1.2.15.jar
if (%1) == () goto no_tag
rem specific tag desired
:tag
ant -f buildAndInstall.xml -listener org.apache.tools.ant.listener.Log4jListener -Dlog4j.configuration=log4j.properties -logger org.apache.tools.ant.listener.MailLogger -DMailLogger.properties.file=maillogger.properties -Dbuild.tag.name=%1 installNewBuild
goto done
:no_tag
ant -f buildAndInstall.xml -listener org.apache.tools.ant.listener.Log4jListener -Dlog4j.configuration=log4j.properties -logger org.apache.tools.ant.listener.MailLogger -DMailLogger.properties.file=maillogger.properties installNewBuild
goto done
:done
if exist ab_java_version.txt del ab_java_version.txt
endlocal