21.4. Writing a Validation Class

In the event that a sensor's properties must have a certain value in order for the sensor to function properly, a validation class can be written to ensure that the value entered by the user is correct. Example 21.8, “The ValidateVimProperties class” is an example of a class extending PropertyValidation. The validation class must be placed into the same package as the extended SensorInstaller class.

Example 21.8. The ValidateVimProperties class

public class ValidateVimProperties extends PropertyValidation {

  /**
   * Adds key-value pairs to the methodNames HashMap. This must be done in order for
   * the method reflection to execute correctly when calling the validation methods in this class
   */
  public ValidateVimProperties() {
    this.methodNames.put("HACKYSTAT_VIM_SENSOR_DATA_FILE", "VimDataFilePath"); 1
  }

  /**
   * Validates the HACKYSTAT_VIM_SENSOR_DATA_FILE Property.
   * 
   * @param dataFile the datafile location.
   * @return true if the url is valid, false if not.
   */
  public boolean validateVimDataFilePath (String dataFile) { 2
    File file = new File(dataFile);
    if (new File(file.getAbsolutePath()).exists()) {
      return true;
    }
    else { // file path doesn't exist
      Control.getInstance()
          .notifyModelListeners(new PropertyEvent("Vim data filepath is invalid.", true));
      return false;
    }
  }
}

1

The map that is required by hackyInstaller to execute reflection on the validation class. The map has the key-value pair, Property Name -> Method Name. Each property that needs to be validated should have an entry into this map.

2

Each method that is specified in the methodName map should follow the naming convention, validate<MethodName>. Each property that is validated should have its own validate method. The validate method should return a boolean and accept a String, which is the value of the property entered by the user.