package samples.webapps.simple.servlet;

/**
 * Encoder utility class
 * @author Tamil Vengan
 */

public final class Encoder {


    /**
     * Encode form input fields to avoid potential XSS attack
     *
     * @param input - The input string to be encoded
     */
    public static String encode(String input) {

        if (input == null)
            return null;

        StringBuffer inputsb = new StringBuffer(input);
        StringBuffer result = new StringBuffer(inputsb.length() + 200);

        for (int i = 0; i < inputsb.length(); i++) {
            switch (inputsb.charAt(i)) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            case '(':
                result.append("&#40;");
                break;
            case ')':
                result.append("&#41;");
                break;
            case '#':
                result.append("&#35;");
                break;
            default:
                result.append(inputsb.charAt(i));
            }
        }
        return (result.toString().trim());
    }
}