Created
August 8, 2018 19:01
-
-
Save 20esaua/08624df54039616fe00ab0defdfa2418 to your computer and use it in GitHub Desktop.
For sanitizing user input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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