// 2012-11-29 johnpfeiffer
// TODO better handling/validation of arguments
package net.kittyandbear;
import java.io.IOException;
import java.io.PrintStream;
public class PropertiesWriterCLI {
protected static final int MINIMUMPARAMETERS = 1;
protected static final int MAXIMUMPARAMETERS = 3;
public static final String CORRECTUSAGE = "Read the file, use a key to get a value, or use a key to replace a value... usage: "
+ "\nVIEW VALUES SORTED: java -jar PropertiesWriterGetValueCLI-" + PropertiesWriter.CLASSVERSION
+ " pathAndFilename.properties [KEY] [NEWVALUE]";
static public void main( String args[] ) {
if (argsAreInvalid( args )) {
System.out.println( "ERROR: " + args.length + " Incorrect number of parameters, " + CORRECTUSAGE );
System.exit( 1 );
}
if (args.length == 1) {
displayKeyValueMapping( args[0], System.out );
}
else if (args.length == 2) {
displayKeyValue( args[0], args[1] , System.out );
}
else if (args.length == 3) {
replaceKeyValue( args[0], args[1], args[2] );
}
else {
System.out.println( "ERROR: Incorrect number of parameters, " + CORRECTUSAGE );
System.exit( 1 );
}
}
private static boolean argsAreInvalid( String args[] ) {
boolean areInvalid = true;
if (args != null && args.length >= MINIMUMPARAMETERS & args.length <= MAXIMUMPARAMETERS) {
areInvalid = false;
}
return ( areInvalid );
}
private static void displayKeyValueMapping( String pathAndFilename, PrintStream out ) {
try {
PropertiesReader properties = new PropertiesReader( pathAndFilename );
out.println( properties.getKeysAndValuesSortedByKeysString() );
}
catch( IOException e ) {
out.println( "ERROR: IOException " + e.getMessage() );
}
}
private static void displayKeyValue( String pathAndFilename, String key, PrintStream out ) {
try {
PropertiesReader properties = new PropertiesReader( pathAndFilename );
String value = properties.getPropertyValue( key );
if (value == null) {
out.println( "ERROR: key " + key + " not found in " + pathAndFilename );
}
else {
out.println( properties.getPropertyValue( key ) );
}
}
catch( IllegalArgumentException e ) {
System.out.println( "ERROR: IllegalArgumentException " + e.getMessage() );
}
catch( IOException e ) {
System.out.println( "ERROR: IOException " + e.getMessage() );
}
}
private static void replaceKeyValue( String pathAndFilename, String key, String newValue ) {
try {
PropertiesReader read = new PropertiesReader( pathAndFilename );
String value = read.getPropertyValue( key );
if( value != null )
{
System.out.println( "DEBUG: for entry: " + key + " , " + value + " with " + newValue );
}
PropertiesWriter properties = new PropertiesWriter( pathAndFilename );
properties.setPropertyValue( key, newValue );
properties.writeSorted( pathAndFilename );
}
catch( IllegalArgumentException e ) {
System.out.println( "ERROR: IllegalArgumentException " + e.getMessage() );
}
catch( IOException e ) {
System.out.println( "ERROR: IOException " + e.getMessage() );
}
}
} // end class