PROX-461: Add IpGenerator (#34)

This commit is contained in:
Baikov Dmitrii 2020-10-15 13:06:34 +03:00 committed by GitHub
parent 239f555fd1
commit 4ee25d5a2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 63 additions and 2 deletions

@ -1 +1 @@
Subproject commit 34f432a1e8e0adedbba23ecd29c1eb2412a8d416
Subproject commit f42e059d9ec93826ba4ad23232eed8ce67bd5486

View File

@ -13,7 +13,7 @@
</parent>
<artifactId>adapter-common-lib</artifactId>
<version>0.0.27</version>
<version>0.0.28</version>
<packaging>jar</packaging>
<name>adapter-common-lib</name>

View File

@ -0,0 +1,35 @@
package com.rbkmoney.adapter.common.utils.generator;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class IpGenerator {
public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
public static String checkAndGenerate(String ip) {
return checkAndGenerate(ip, DEFAULT_IP_ADDRESS);
}
public static String checkAndGenerate(String ip, String defaultIpAddress) {
try {
InetAddress address = InetAddress.getByName(ip);
if (StringUtils.isEmpty(ip) || address instanceof Inet6Address) {
return defaultIpAddress;
}
} catch (UnknownHostException e) {
log.error("Error when convert ipAddress: {}", ip, e);
return defaultIpAddress;
}
return ip;
}
}

View File

@ -0,0 +1,26 @@
package com.rbkmoney.adapter.common.utils.generator;
import org.junit.Assert;
import org.junit.Test;
public final class IpGeneratorTest {
public static final String IP_V4 = "123.0.0.2";
@Test
public void checkAndGenerate() {
String expectedIp = "127.0.0.1";
String resultIp = IpGenerator.checkAndGenerate("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
Assert.assertEquals(expectedIp, resultIp);
resultIp = IpGenerator.checkAndGenerate("");
Assert.assertEquals(expectedIp, resultIp);
resultIp = IpGenerator.checkAndGenerate(null);
Assert.assertEquals(expectedIp, resultIp);
resultIp = IpGenerator.checkAndGenerate(IP_V4);
Assert.assertEquals(IP_V4, resultIp);
}
}