Tuesday, November 23, 2010

Java : Checking if environment variables are valid

Has a few problems with environment variables and I couldn't find a utility that would check them for me e.g. checking if all the entries in my PATH environment variable were valid.

So I rolled my own:


public class CheckEnv {

/**
* @param args the command line arguments
*/
static String envVar = "";
static String envValue = "";
static String envValueStrings[];
static String envValueString = "";
static boolean valid = false;

public static void main(String[] args) {
// TODO code application logic here

if (args.length < 1) {
System.out.println("\nUsage is 'java -jar CheckEnv.jar '");
System.out.println();
System.out.println(" e.g. 'java -jar CheckEnv.jar PATH'");
System.out.println(" 'java -jar CheckEnv.jar CLASSPATH'");
System.out.println(" 'java -jar CheckEnv.jar INCLUDE'");
System.out.println(" 'java -jar CheckEnv.jar LIB'");
System.exit(1);
}

envVar = args[0];

envValue = System.getenv(envVar);

System.out.println ("\nChecking for environment variable " + envVar + "\n");

if (envValue == null)
{
System.out.println ("Environment variable " + envVar + " doesn't exist");
System.exit(1);
}

envValueStrings = envValue.split(";");

for (int i = 0; i < envValueStrings.length; i++) {
envValueString = envValueStrings[i];

System.out.print("Checking " + envValueString + " ");

File file = new File(envValueString);
valid = file.exists();

if (valid) {
System.out.println("- variable exists");
} else {
System.out.println("- variable does not exist : WARNING");
}

}
}
}



Usage is 'java -jar CheckEnv.jar '

e.g. 'java -jar CheckEnv.jar PATH'
'java -jar CheckEnv.jar CLASSPATH'
'java -jar CheckEnv.jar INCLUDE'
'java -jar CheckEnv.jar LIB'


The output looks like e.g.


Checking C:\Program Files\Java\jdk1.6.0_22\jre\bin - variable exists
Checking C:\Program Files\Reflection - variable exists
Checking C:\Perl\bin\ - variable exists


Enjoy!

No comments: