com.github.menglim.sutils.annotations.notempty.NotEmptyXSSValidator Maven / Gradle / Ivy
package com.github.menglim.sutils.annotations.notempty;
import com.github.menglim.sutils.SUtils;
import org.springframework.web.util.HtmlUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class NotEmptyXSSValidator implements ConstraintValidator {
private boolean stripHtml;
private boolean removeSpace;
private boolean allowedNull;
private int length;
@Override
public void initialize(NotEmptyXSS constraintAnnotation) {
stripHtml = constraintAnnotation.stripHtml();
removeSpace = constraintAnnotation.removeSpace();
allowedNull = constraintAnnotation.allowedNull();
length = constraintAnnotation.length();
}
@Override
public boolean isValid(Object object, ConstraintValidatorContext context) {
if (object instanceof String) {
String value = String.valueOf(object);
if (removeSpace) {
value = value.replaceAll("\\s+", "");
}
if (allowedNull) {
if (SUtils.getInstance().isNull(value)) {
return true;
}
}
if (length != -1) {
return value.length() == length;
}
// value = strip_html_tags(value);
if (SUtils.getInstance().isNull(value)) return false;
if (value.trim() == "") return false;
return !isHtml(value);
} else {
return SUtils.getInstance().nonNull(object);
}
}
public static boolean isHtml(String input) {
boolean isHtml = false;
if (input != null) {
String htmlEscapedHtml = HtmlUtils.htmlEscape(input);
if (!input.equals(htmlEscapedHtml)) {
isHtml = true;
}
}
return isHtml;
}
// public String strip_html_tags(String text) {
//
// text = text.replaceAll("@(.*?)@siu", " ");
// text = text.replaceAll("@(.*?)@siu", " ");
// text = text.replaceAll("@(.*?)@siu", " ");
// text = text.replaceAll("@(.*?)]*?.*?@siu", " ");
//
// if (text != null) {
// // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
// // avoid encoded attacks.
// // value = ESAPI.encoder().canonicalize(value);
//
// // Avoid null characters
// text = text.replaceAll("", "");
//
// // Avoid anything between script tags
// Pattern scriptPattern = Pattern.compile("", Pattern.CASE_INSENSITIVE);
// text = scriptPattern.matcher(text).replaceAll("");
//
// // Avoid anything in a src='...' type of expression
// scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
// text = scriptPattern.matcher(text).replaceAll("");
//
// scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
// text = scriptPattern.matcher(text).replaceAll("");
//
// // Remove any lonesome tag
// scriptPattern = Pattern.compile("", Pattern.CASE_INSENSITIVE);
// text = scriptPattern.matcher(text).replaceAll("");
//
// // Remove any lonesome