57 lines
1.5 KiB
Java
57 lines
1.5 KiB
Java
package org.gcube.accounting.datamodel.validators;
|
|
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
import org.gcube.common.validator.annotations.FieldValidator;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
public class ValidIPValidator implements FieldValidator<ValidLong>{
|
|
|
|
private static Logger logger = LoggerFactory.getLogger(ValidIPValidator.class);
|
|
|
|
public Class<ValidLong> annotation() {
|
|
return ValidLong.class;
|
|
}
|
|
|
|
private static Pattern IPV4_PATTERN = null;
|
|
private static Pattern IPV6_PATTERN = null;
|
|
|
|
private static final String ipv4Regex = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
|
|
private static final String ipv6Regex = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
|
|
|
|
static {
|
|
try {
|
|
IPV4_PATTERN = Pattern.compile(ipv4Regex,
|
|
Pattern.CASE_INSENSITIVE);
|
|
IPV6_PATTERN = Pattern.compile(ipv6Regex,
|
|
Pattern.CASE_INSENSITIVE);
|
|
} catch(Exception e) {
|
|
logger.error("Unable to compile pattern", e.getCause());
|
|
}
|
|
}
|
|
|
|
protected static boolean isIpAddress(String ipAddress) {
|
|
Matcher ipV4Matcher = IPV4_PATTERN.matcher(ipAddress);
|
|
if (ipV4Matcher.matches()) {
|
|
return true;
|
|
}
|
|
|
|
Matcher ipV6Matcher = IPV6_PATTERN.matcher(ipAddress);
|
|
return ipV6Matcher.matches();
|
|
}
|
|
|
|
public boolean isValid(Object toValidate) {
|
|
if(toValidate instanceof String){
|
|
return isIpAddress((String) toValidate);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public String getErrorSuffix() {
|
|
return "not valid IP Address";
|
|
}
|
|
|
|
}
|