org.apache.commons.validator.routines.InetAddressValidator Java Examples

The following examples show how to use org.apache.commons.validator.routines.InetAddressValidator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IpPort.java    From quarantyne with Apache License 2.0 6 votes vote down vote up
static IpPort parse(String str) throws IllegalArgumentException {
  if (Strings.isNullOrEmpty(str)) {
    throw new IllegalArgumentException("ip:port null or empty");
  }

  String[] parts = str.split(":");

  if (parts.length == 2 && InetAddressValidator.getInstance().isValidInet4Address(parts[0])) {
    int port;
    try {
      port = Integer.parseInt(parts[1]);
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("Invalid ip:port {}" + str);
    }
    if (port > 0 && port < 65536){
      return new IpPort(parts[0], port);
    }
  }
  throw new IllegalArgumentException("Invalid ip:port {}" + str);
}
 
Example #2
Source File: HostnameUtils.java    From kafka-message-tool with MIT License 6 votes vote down vote up
private void assignLocalhostIpV4Addresses() {

        final InetAddressValidator validator = InetAddressValidator.getInstance();
        try {
            Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) enumeration.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();

                    final String hostAddress = i.getHostAddress();
                    if (!validator.isValidInet4Address(hostAddress)) {
                        continue;
                    }
                    localhostIpAddresses.add(hostAddress);
                }
            }
        } catch (SocketException exception) {
            Logger.error("Could not fetch localhost ip addresses", exception);
        }
    }
 
Example #3
Source File: HostnameUtils.java    From kafka-message-tool with MIT License 6 votes vote down vote up
private static Set<String> resolveIpsForHostname(String hostname) throws UnknownHostException {

        hostname = hostname.toLowerCase();
        Logger.trace(String.format("Resolving ip(s) for '%s'", hostname));
        if (InetAddressValidator.getInstance().isValidInet4Address(hostname)) {
            Logger.trace(String.format("Returning %s", hostname));
            return Collections.singleton(hostname);
        }
        if (hostname.equalsIgnoreCase("localhost")) {
            final Set<String> localhostIpAddresses = HostnameUtils.getInstance().getLocalhostIpAddresses();
            Logger.trace(String.format("Returning %s", localhostIpAddresses));
            return localhostIpAddresses;
        }
        final Set<String> hostIps = Collections.singleton(HostnameUtils.resolveHostName(hostname));
        Logger.trace(String.format("Returning '%s'", hostIps));
        return hostIps;
    }
 
Example #4
Source File: PackageData.java    From aliyun-log-producer-java with Apache License 2.0 5 votes vote down vote up
static String GetLocalMachineIp() {
    InetAddressValidator validator = new InetAddressValidator();
    String candidate = "";
    try {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface
                .getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
            NetworkInterface iface = ifaces.nextElement();

            if (iface.isUp()) {
                for (Enumeration<InetAddress> addresses = iface
                        .getInetAddresses(); addresses.hasMoreElements(); ) {

                    InetAddress address = addresses.nextElement();

                    if (!address.isLinkLocalAddress() && address.getHostAddress() != null) {
                        String ipAddress = address.getHostAddress();
                        if (ipAddress.equals(Consts.CONST_LOCAL_IP)) {
                            continue;
                        }
                        if (validator.isValidInet4Address(ipAddress)) {
                            return ipAddress;
                        }
                        if (validator.isValid(ipAddress)) {
                            candidate = ipAddress;
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        LOGGER.error("Failed to get local machine IP.", e);
    }
    return candidate;
}
 
Example #5
Source File: SecurityGroupAdmin.java    From Raigad with Apache License 2.0 5 votes vote down vote up
@DELETE
public Response removeACL(
        @QueryParam("ip") String ipAddress,
        @QueryParam("mask") Integer mask,
        @QueryParam("fromPort") int fromPort,
        @QueryParam("toPort") int toPort)
{
    if (!InetAddressValidator.getInstance().isValid(ipAddress)) {
        log.error("Invalid IP address", ipAddress);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    if (mask == null) {
        log.info("IP mask not provided, using /32");
        mask = DEFAULT_MASK;
    }

    try {
        membership.removeACL(Collections.singletonList(String.format("%s/%d", ipAddress, mask)), fromPort, toPort);
    }
    catch (Exception e) {
        log.error("Error removing ACL from a security group", e);
        return Response.serverError().build();
    }

    return Response.ok().build();
}
 
Example #6
Source File: SecurityGroupAdmin.java    From Raigad with Apache License 2.0 5 votes vote down vote up
@POST
public Response addACL(
        @QueryParam("ip") String ipAddress,
        @QueryParam("mask") Integer mask,
        @QueryParam("fromPort") int fromPort,
        @QueryParam("toPort") int toPort)
{
    if (!InetAddressValidator.getInstance().isValid(ipAddress)) {
        log.error("Invalid IP address", ipAddress);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    if (mask == null || mask < 8) {
        log.info("IP mask is too wide or not provided, using /32");
        mask = DEFAULT_MASK;
    }

    try {
        membership.addACL(Collections.singletonList(String.format("%s/%d", ipAddress, mask)), fromPort, toPort);
    }
    catch (Exception e) {
        log.error("Error adding ACL to a security group", e);
        return Response.serverError().build();
    }

    return Response.ok().build();
}
 
Example #7
Source File: NetUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static boolean isValidIp4(final String ip) {
    if (ip == null)
        return false;

    final InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValidInet4Address(ip);
}
 
Example #8
Source File: NetUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static boolean isValidIp6(final String ip) {
    if (ip == null)
        return  false;

    final InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValidInet6Address(ip);
}
 
Example #9
Source File: Validator.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Validates a field to be a valid IPv6 address
 *
 * @param name The field to check
 * @param message A custom error message instead of the default one
 */
public void expectIpv6(String name, String message) {
    String value = Optional.ofNullable(get(name)).orElse("");

    if (!InetAddressValidator.getInstance().isValidInet6Address(value)) {
        addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.IPV6_KEY.name(), name)));
    }
}
 
Example #10
Source File: Validator.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Validates a field to be a valid IPv4 address
 *
 * @param name The field to check
 * @param message A custom error message instead of the default one
 */
public void expectIpv4(String name, String message) {
    String value = Optional.ofNullable(get(name)).orElse("");

    if (!InetAddressValidator.getInstance().isValidInet4Address(value)) {
        addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.IPV4_KEY.name(), name)));
    }
}
 
Example #11
Source File: GridParameter.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckNewHubIp(@QueryParameter final String value) {
    if (value.length() == 0 || !InetAddressValidator.getInstance().isValid(value)) {
        return FormValidation.error("Please set a valid ip address");
    }

    return FormValidation.ok();
}
 
Example #12
Source File: GridParameter.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckRemoteWatcherIp(@QueryParameter final String value) {
    if (value.length() == 0 || !InetAddressValidator.getInstance().isValid(value)) {
        return FormValidation.error("Please set a valid ip address");
    }

    return FormValidation.ok();
}
 
Example #13
Source File: NodeConfiguration.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckNodeIp(@QueryParameter String value) throws IOException, ServletException {
    if (value.length() == 0 || !InetAddressValidator.getInstance().isValid(value)) {
        return FormValidation.error("Please set a valid ip address");
    }

    return FormValidation.ok();
}
 
Example #14
Source File: UtilAll.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
private static boolean ipV6Check(byte[] ip) {
    if (ip.length != 16) {
        throw new RuntimeException("illegal ipv6 bytes");
    }

    InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValidInet6Address(ipToIPv6Str(ip));
}
 
Example #15
Source File: RemoteAddressStrategyFactory.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public OneRemoteAddressStrategy(String netaddress) {
    this.netaddress = netaddress;
    InetAddressValidator validator = InetAddressValidator.getInstance();
    if (!(validator.isValidInet4Address(netaddress) || validator.isValidInet6Address(netaddress))) {
        throw new AclException(String.format("Netaddress examine Exception netaddress is %s", netaddress));
    }
}
 
Example #16
Source File: RemoteAddressStrategyFactory.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(PlainAccessResource plainAccessResource) {
    InetAddressValidator validator = InetAddressValidator.getInstance();
    String whiteRemoteAddress = plainAccessResource.getWhiteRemoteAddress();
    if (validator.isValidInet6Address(whiteRemoteAddress)) {
        whiteRemoteAddress = AclUtils.expandIP(whiteRemoteAddress, 8);
    }
    return multipleSet.contains(whiteRemoteAddress);
}
 
Example #17
Source File: RemoteAddressStrategyFactory.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public MultipleRemoteAddressStrategy(String[] strArray) {
    InetAddressValidator validator = InetAddressValidator.getInstance();
    for (String netaddress : strArray) {
        if (validator.isValidInet4Address(netaddress)) {
            multipleSet.add(netaddress);
        } else if (validator.isValidInet6Address(netaddress)) {
            multipleSet.add(AclUtils.expandIP(netaddress, 8));
        } else {
            throw new AclException(String.format("Netaddress examine Exception netaddress is %s", netaddress));
        }
    }
}
 
Example #18
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static boolean isValidIp6(final String ip) {
    if (ip == null) {
        return false;
    }

    final InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValidInet6Address(ip);
}
 
Example #19
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static boolean isValidIp4(final String ip) {
    if (ip == null) {
        return false;
    }

    final InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValidInet4Address(ip);
}
 
Example #20
Source File: EmailValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the domain component of an email address is valid.
 * @param domain being validated.
 * @return true if the email address's domain is valid.
 */
protected boolean isValidDomain(String domain) {
    boolean symbolic = false;

    // see if domain is an IP address in brackets
    Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain);

    if (ipDomainMatcher.matches()) {
        InetAddressValidator inetAddressValidator =
                InetAddressValidator.getInstance();
        if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) {
            return true;
        }
    } else {
        // Domain is symbolic name
        symbolic = DOMAIN_PATTERN.matcher(domain).matches();
    }

    if (symbolic) {
        if (!isValidSymbolicDomain(domain)) {
            return false;
        }
    } else {
        return false;
    }

    return true;
}
 
Example #21
Source File: SeleniumBuilder.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
public FormValidation doCheckHubIp(@QueryParameter String value) throws IOException, ServletException {
    if (value.length() == 0 || !InetAddressValidator.getInstance().isValid(value)) {
        return FormValidation.error("Please set a valid ip address");
    }

    return FormValidation.ok();
}
 
Example #22
Source File: OzoneSecurityUtil.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates through network interfaces and return all valid ip's not
 * listed in CertificateSignRequest#INVALID_IPS.
 *
 * @return List<InetAddress>
 * @throws IOException if no network interface are found or if an error
 * occurs.
 */
public static List<InetAddress> getValidInetsForCurrentHost()
    throws IOException {
  List<InetAddress> hostIps = new ArrayList<>();
  InetAddressValidator ipValidator = InetAddressValidator.getInstance();

  Enumeration<NetworkInterface> enumNI =
      NetworkInterface.getNetworkInterfaces();
  if (enumNI == null) {
    throw new IOException("Unable to get network interfaces.");
  }

  while (enumNI.hasMoreElements()) {
    NetworkInterface ifc = enumNI.nextElement();
    if (ifc.isUp()) {
      Enumeration<InetAddress> enumAdds = ifc.getInetAddresses();
      while (enumAdds.hasMoreElements()) {
        InetAddress addr = enumAdds.nextElement();

        String hostAddress = addr.getHostAddress();
        if (!INVALID_IPS.contains(hostAddress)
            && ipValidator.isValid(hostAddress)) {
          LOG.info("Adding ip:{},host:{}", hostAddress, addr.getHostName());
          hostIps.add(addr);
        } else {
          LOG.info("ip:{} not returned.", hostAddress);
        }
      }
    }
  }

  return hostIps;
}
 
Example #23
Source File: IPv6Validator.java    From java-bean-validation-extension with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    }
    return InetAddressValidator
            .getInstance()
            .isValidInet6Address(value);
}
 
Example #24
Source File: IPv4Validator.java    From java-bean-validation-extension with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    }
    return InetAddressValidator
            .getInstance()
            .isValidInet4Address(value);
}
 
Example #25
Source File: HIPAAMatcherAttributeValue.java    From arx with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(String value) {
    InetAddressValidator validator = InetAddressValidator.getInstance();
    return validator.isValid(value);
}
 
Example #26
Source File: DiscoverHardcodedIPAddressRuleProvider.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext)
{
    return ConfigurationBuilder
    .begin()
    .addRule()
    // for all files ending in java, properties, and xml,
    // query for the regular expression {ip}
    .when(FileContent.matches("{ip}").inFileNamed("{*}{type}"))
    .perform(new AbstractIterationOperation<FileLocationModel>()
    {
        // when a result is found, create an inline hint.
        // reference the inline hint with the hardcoded ip marker so that we can query for it
        // in the hardcoded ip report.
        public void perform(GraphRewrite event, EvaluationContext context, FileLocationModel payload)
        {
            // for all file location models that match the regular expression in the where clause, add
            // the IP Location Model to the graph
            if (InetAddressValidator.getInstance().isValid(payload.getSourceSnippit()))
            {
                // if the file is a property file, make sure the line isn't commented out.
                if (ignoreLine(event.getGraphContext(), payload))
                {
                    return;
                }

                if (payload.getFile() instanceof SourceFileModel)
                    ((SourceFileModel) payload.getFile()).setGenerateSourceReport(true);

                HardcodedIPLocationModel location = GraphService.addTypeToModel(event.getGraphContext(), payload,
                    HardcodedIPLocationModel.class);
                location.setRuleID(((Rule) context.get(Rule.class)).getId());
                location.setTitle("Hard-coded IP address");

                StringBuilder hintBody = new StringBuilder("**Hard-coded IP: ");
                hintBody.append(payload.getSourceSnippit());
                hintBody.append("**");

                hintBody.append(System.lineSeparator()+System.lineSeparator());
                hintBody.append("When migrating environments, hard-coded IP addresses may need to be modified or eliminated.");
                location.setHint(hintBody.toString());
                //location.setIssueCategory(IssueCategoryRegistry.loadFromGraph(event.getGraphContext(), IssueCategoryRegistry.MANDATORY));
                location.setIssueCategory(IssueCategoryRegistry.loadFromGraph(event.getGraphContext(), IssueCategoryRegistry.CLOUD_MANDATORY));
                location.setEffort(1);
            }
        }
    })
    .where("ip").matches(IP_PATTERN)
    .where("type").matches("\\.java|\\.properties|[^pom]\\.xml")
    .withId(getClass().getSimpleName());
}
 
Example #27
Source File: AppiumServiceBuilder.java    From java-client with Apache License 2.0 4 votes vote down vote up
@Override
protected ImmutableList<String> createArgs() {
    List<String> argList = new ArrayList<>();
    loadPathToMainScript();
    argList.add(appiumJS.getAbsolutePath());
    argList.add("--port");
    argList.add(String.valueOf(getPort()));

    if (StringUtils.isBlank(ipAddress)) {
        ipAddress = BROADCAST_IP_ADDRESS;
    } else {
        InetAddressValidator validator = InetAddressValidator.getInstance();
        if (!validator.isValid(ipAddress) && !validator.isValidInet4Address(ipAddress)
                && !validator.isValidInet6Address(ipAddress)) {
            throw new IllegalArgumentException(
                    "The invalid IP address " + ipAddress + " is defined");
        }
    }
    argList.add("--address");
    argList.add(ipAddress);

    File log = getLogFile();
    if (log != null) {
        argList.add("--log");
        argList.add(log.getAbsolutePath());
    }

    Set<Map.Entry<String, String>> entries = serverArguments.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        String argument = entry.getKey();
        String value = entry.getValue();
        if (StringUtils.isBlank(argument) || value == null) {
            continue;
        }

        argList.add(argument);
        if (!StringUtils.isBlank(value)) {
            argList.add(value);
        }
    }

    if (capabilities != null) {
        argList.add("--default-capabilities");
        argList.add(capabilitiesToCmdlineArg());
    }

    return new ImmutableList.Builder<String>().addAll(argList).build();
}
 
Example #28
Source File: InputsUtil.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private static boolean isValidIPv4Address(String input) {
    return new InetAddressValidator().isValidInet4Address(input) ? TRUE : FALSE;
}
 
Example #29
Source File: InputsUtil.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public static String getValidIPv4Address(String input) {
    if (isNotBlank(input) && !new InetAddressValidator().isValidInet4Address(input)) {
        throw new RuntimeException("The provided value for: " + input + " input must be a valid IPv4 address.");
    }
    return input;
}
 
Example #30
Source File: LinuxPingCommand.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
@Override
public String createCommand(LocalPingInputs localPingInputs) {
    StringBuilder command = new StringBuilder();
    final String targetHost = localPingInputs.getTargetHost();
    final String ipVersion = localPingInputs.getIpVersion();

    if (isEmpty(ipVersion)) {
        if (InetAddressValidator.getInstance().isValidInet6Address(targetHost)) {
            command.append("ping6 ");
        } else {
            command.append("ping ");
        }
    } else {
        if (ipVersion.equals(IP_VERSION_6)) {
            command.append("ping6 ");
        } else if (ipVersion.equals(IP_VERSION_4)) {
            command.append("ping ");
        } else {
            throw new IllegalArgumentException(format(INVALID_ARGUMENT_IP_VERSION, ipVersion));
        }
    }

    final String timeout = localPingInputs.getTimeout();
    if (isNotEmpty(timeout)) {
        if (!isValidLong(timeout)) {
            throw new RuntimeException(TIMEOUT_SHOULD_HAVE_A_NUMERIC_VALUE);
        }
        //transform timeout value from milliseconds to seconds
        Long timeoutValue = parseLong(timeout) / 1000;
        command.append(format("-w %s ", valueOf(timeoutValue)));
    }

    final String packetCount = localPingInputs.getPacketCount();
    if (isNotEmpty(packetCount)) {
        if (!isValidLong(packetCount)) {
            throw new RuntimeException(PACKET_COUNT_SHOULD_HAVE_A_NUMERIC_VALUE);
        }
        command.append(format("-c %s ", packetCount));
    } else {
        command.append(format("-c %s ", DEFAULT_PACKET_COUNT));
    }

    final String packetSize = localPingInputs.getPacketSize();
    if (isNotEmpty(packetSize)) {
        if (!isValidInt(packetSize)) {
            throw new RuntimeException(PACKET_SIZE_SHOULD_HAVE_A_NUMERIC_VALUE);
        }
        command.append(format("-s %s ", packetSize));
    }

    command.append(localPingInputs.getTargetHost());

    return command.toString();
}