2015-06-08 17:19:09 +02:00
|
|
|
package org.gcube.accounting.datamodel.validations.validators;
|
2015-05-29 17:39:24 +02:00
|
|
|
|
2015-06-05 11:06:17 +02:00
|
|
|
import java.io.Serializable;
|
2015-06-03 11:25:14 +02:00
|
|
|
import java.util.regex.Matcher;
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
|
2015-06-05 12:54:26 +02:00
|
|
|
import org.gcube.accounting.exception.InvalidValueException;
|
2015-06-03 11:25:14 +02:00
|
|
|
import org.slf4j.Logger;
|
|
|
|
import org.slf4j.LoggerFactory;
|
2015-05-29 17:39:24 +02:00
|
|
|
|
2015-06-05 18:50:07 +02:00
|
|
|
public class ValidIPValidator implements FieldValidator{
|
2015-06-03 11:25:14 +02:00
|
|
|
|
|
|
|
private static Logger logger = LoggerFactory.getLogger(ValidIPValidator.class);
|
|
|
|
|
2015-06-05 18:50:07 +02:00
|
|
|
private static final String ERROR = "Not valid IP Address";
|
|
|
|
|
2015-06-03 11:25:14 +02:00
|
|
|
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();
|
|
|
|
}
|
|
|
|
|
2015-06-05 18:50:07 +02:00
|
|
|
@Override
|
2015-06-05 12:54:26 +02:00
|
|
|
public Serializable validate(Serializable toValidate) throws InvalidValueException {
|
|
|
|
try {
|
|
|
|
if(isIpAddress((String) toValidate)){
|
|
|
|
return (String) toValidate;
|
|
|
|
}
|
|
|
|
}catch (Exception e) {
|
2015-06-05 18:50:07 +02:00
|
|
|
throw new InvalidValueException(ERROR, e.getCause());
|
2015-06-05 12:54:26 +02:00
|
|
|
}
|
2015-06-05 18:50:07 +02:00
|
|
|
throw new InvalidValueException(ERROR);
|
2015-05-29 17:39:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|