com.atlassian.bamboo.specs.validators.common.InternetAddressValidator Maven / Gradle / Ivy
package com.atlassian.bamboo.specs.validators.common;
import com.atlassian.bamboo.specs.api.exceptions.PropertiesValidationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
public final class InternetAddressValidator {
private InternetAddressValidator() {
}
public static void checkComaSeparatedIpAddressesOrCidrs(final String ipAddressesOrCidrs) throws PropertiesValidationException {
for (final String ipAddressOrCidr : ipAddressesOrCidrs.split("\\s*,\\s*")) {
if (StringUtils.isNotEmpty(ipAddressOrCidr) && !isIpAddressOrCidrValid(ipAddressOrCidr)) {
throw new PropertiesValidationException(
String.format("Invalid coma separated IPs/CIDRs: %s, error when validating %s", ipAddressesOrCidrs, ipAddressOrCidr));
}
}
}
public static void checkIpAddressOrCidr(final String ipAddressOrCidr) throws PropertiesValidationException {
if (!isIpAddressOrCidrValid(ipAddressOrCidr)) {
throw new PropertiesValidationException(String.format("Invalid IP/CIDR: %s", ipAddressOrCidr));
}
}
private static boolean isIpAddressOrCidrValid(final String ipAddressOrCidr) {
final String ipAddress = StringUtils.substringBefore(ipAddressOrCidr, "/");
final String prefixLen = StringUtils.substringAfter(ipAddressOrCidr, "/");
if (!prefixLen.isEmpty() && !NumberUtils.isDigits(prefixLen)) {
return false;
}
return InetAddressValidator.getInstance().isValid(ipAddress);
}
}