package properties;

import java.util.*;
import java.io.*;

/**
 * This PropertiesHelper class is a useful class that reads out properties files.
 * Each application should have a class that de-abstracts this one, so that the
 * application-specific property-files can be stored with it in the same directory.
 */
public abstract class PropertiesHelper {

  /**
   * This method reads the propertiesfile specified by <code>localFileName</code>
   * and returns the properties wrapped in a Properties object.
   * When the system property <code>environment</code> is specified, the value
   * will be prepended to the filename. E.g. localFileName = 'appProps', when
   * <code>environment</code> is set to 'tst', the file containing the properties
   * should be called 'tst.appProps.properties'.
   *
   * @exception RuntimeException when the file specified can not be found/read.
   */
	public final Properties getProperties(String localFileName) {
    // get the prefix for the environment we are running in
    String env = System.getProperty("environment");
    String prefix = "";
    if (env != null) {
      prefix = env + ".";
    }
    String lfn = prefix + localFileName + ".properties";
		// get the properties file as an input stream
    Class theClass = this.getClass();
		InputStream instr = theClass.getResourceAsStream(lfn);
		if(instr == null) {
			throw new RuntimeException("Couldn't locate the "+lfn+" file");
		}

		// create empty properties object
		Properties props = new Properties();

		// N.B. this throws an IOException if it fails
    try {
      props.load(instr);
      instr.close();
		} catch (IOException e) {
			throw new RuntimeException("Error loading properties for "+lfn);
    }
		return props;
	}
}
