Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
public class ValidateOutput {
  // allows only alphanumeric characters and spaces
  private Pattern pattern = Pattern.compile("^[a-zA-Z0-9\\s]{0,20}$");

  // validates and encodes the input field based on a whitelist
  private String validate(String name, String input) throws ValidationException {
    String canonical = normalize(input);

    if(!pattern.matcher(canonical).matches()) {
      throw new ValidationException( "Improper format in " + name + " field");
    }
    
    // performs output encoding for non valid characters 
    canonical = HTMLEntityEncode(canonical);
    return canonical;
  }

  // normalizes to known instances 	
  private String normalize(String input) {
    String canonical = java.text.Normalizer.normalize(input, Normalizer.Form.NFKC);
    return canonical;
  }

  // Encodes non valid data
  public static String HTMLEntityEncode(String input) {
    StringBuffer sb = new StringBuffer();

    for (int i = 0;i < input.length();++i) {
      char ch = input.charAt( i );
        if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' ||
            ch >= '0' && ch <= '9'(Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
          sb.append(ch);
        } else {
          sb.append("&#" + (int)ch + ";");
        }
    }
    return sb.toString();
  }

  public static void display() throws ValidationException {
    // description and input are String variables containing values obtained from a database
    // description = "description" and input = "2 items available"
    ValidateOutput vo = new ValidateOutput();
    vo.validate(description, input);
    // pass to another system or display to the user
  }
}

...