Monday, January 25, 2010

Command Scripts

Recently I had to create a test that simulated a catastrophic failure to ensure the integrity of an embedded database. Development time for the test was limited so I set out for the quickest approach and saved myself the hassle of mocking test cases for another day. The test would initialize the database and then insert a random number of rows. During the test the OS would kill the process while rows were being inserted and then restart the process to ensure the integrity of the database.

I ended up coming up with a command script in Windows XP that I felt was worth sharing due to its relative obscurity. I will save the majority of the details and only highlight the important points.

First, let's look at the script I made to launch the java process responsible for bootstrapping the database:

START java -cp . Sleeper
ping 1.0.0.0 -n 1 -w 5000 >NUL
FOR /F "tokens=1-2" in ('jps') DO (
IF "%%j" == "Sleeper" (
SET PID=%%i
)
)
TASKKILL /PID %PID%

For me, the coolest part of this script was using the jps command to get the PID for the process that I launched in the first step. My second favorite feature (*cough* hack *cough*) was the use of the ping command (not my idea see the link here). It's the only way I could get the script to wait for a few seconds before killing my process - allowing the test running a separate process to reach the portion of the test where the insertion was occurring. It's not the most reliable or sane approach but it worked perfectly for creating a quick simulation.

The second snippet isn't as exciting as the first but think it's a huge timesaver when trying to execute a Java program that has a very large number of dependencies all located in the same directory. This script scans the directory (e.g., the lib/ folder) and adds every filename ending with .jar to the classpath. Again, keep in mind that this isn't optimal - but it's something quick-and-dirty that you can use to get going:

::EnableDelayedExpansion must be turned on in order to
::programmatically append to the classpath
SETLOCAL EnableDelayedExpansion
SET CLASSPATH=.

FOR %%i IN (lib\*.jar) DO SET CLASSPATH=!CLASSPATH!;%%i

%JAVA_HOME%\bin\java -cp %CLASSPATH YourClassGoesHere

Be sure to include the SETLOCAL (http://ss64.com/nt/setlocal.html) directive and to use the ! operator instead of the % operator when doing the assignment.

No comments: