Skip to content

Instantly share code, notes, and snippets.

@20esaua
Created August 8, 2018 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 20esaua/08624df54039616fe00ab0defdfa2418 to your computer and use it in GitHub Desktop.
Save 20esaua/08624df54039616fe00ab0defdfa2418 to your computer and use it in GitHub Desktop.
For sanitizing user input
import java.net.URLEncoder;
import org.apache.commons.lang.StringEscapeUtils;
public class Sanitize {
/*
* @param input the String to be sanitized for use in HTML
* @return the sanitized String
*/
public static String html(Object input) {
// Note: HTML 4.0 does not have the single quote character.
return StringEscapeUtils.escapeHtml(stringValue(input)).replace("'", "'");
}
/*
* @param input the String to be sanitized for use in a JS String
* @return the sanitized String
*/
public static String js(Object input) {
return StringEscapeUtils.escapeJavaScript(stringValue(input));
}
/*
* @param input the URL parameter to be sanitized
* @return the URL encoded String
*/
public static String url(Object input) {
try {
// try for UTF-8
return URLEncoder.encode(stringValue(input), "UTF-8");
} catch (Exception e) {
// default to deprecated method
return URLEncoder.encode(stringValue(input));
}
}
/*
* @param input the String to have filtered for use in headers
* @return the sanitized String
*/
public static String header(Object input) {
return stringValue(input).replace("\n", "%0A").replace("\r", "%0D");
}
/*
* @param input the column name that must be sanitized
* @return the sanitized column name
*/
public static String column(Object input) {
return stringValue(input).replaceAll("[^A-Za-z0-9\\._]", "");
}
/*
* @param input the filename String to be sanitized
* @return the sanitized String
*/
public static String filename(Object input) {
return stringValue(input).replaceAll("[^a-zA-Z0-9\\._\\u0020]+", "_");
}
/*
* @param input the unsafe input
* @return a null-safe output
*/
public static String stringValue(Object input) {
return (input == null ? "null" : String.valueOf(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment