Skip to content

Commit 86d4924

Browse files
committed
feat(demo-util): add some useful tool class
1 parent 4109f32 commit 86d4924

File tree

8 files changed

+503
-0
lines changed

8 files changed

+503
-0
lines changed

demo-util/pom.xml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,21 @@
1212

1313
<artifactId>demo-util</artifactId>
1414

15+
<dependencies>
16+
<dependency>
17+
<groupId>jakarta.servlet</groupId>
18+
<artifactId>jakarta.servlet-api</artifactId>
19+
</dependency>
20+
21+
<dependency>
22+
<groupId>com.fasterxml.jackson.core</groupId>
23+
<artifactId>jackson-databind</artifactId>
24+
</dependency>
25+
26+
<dependency>
27+
<groupId>org.slf4j</groupId>
28+
<artifactId>slf4j-api</artifactId>
29+
</dependency>
30+
</dependencies>
31+
1532
</project>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.helltractor.demo.util;
2+
3+
4+
import java.util.HexFormat;
5+
6+
public class ByteUtil {
7+
8+
/**
9+
* Convert bytes to hex string (all lower-case).
10+
*
11+
* @param b Input bytes.
12+
* @return Hex string.
13+
*/
14+
public static String toHexString(byte[] b) {
15+
return HexFormat.of().formatHex(b);
16+
}
17+
18+
/**
19+
* Convert byte to hex string (all lower-case).
20+
*
21+
* @param b Input bytes.
22+
* @return Hex string.
23+
*/
24+
public static String toHex(byte b) {
25+
return toHexString(new byte[]{b});
26+
}
27+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.helltractor.demo.util;
2+
3+
import javax.crypto.Mac;
4+
import javax.crypto.SecretKey;
5+
import javax.crypto.spec.SecretKeySpec;
6+
import java.nio.charset.StandardCharsets;
7+
import java.security.GeneralSecurityException;
8+
import java.security.MessageDigest;
9+
import java.security.NoSuchAlgorithmException;
10+
11+
/**
12+
* Utility class for hashing.
13+
*/
14+
public class HashUtil {
15+
16+
/**
17+
* Generate SHA-256 as hex string (all lower-case).
18+
*
19+
* @param input Input as String.
20+
* @return Hex string.
21+
*/
22+
public static String sha256(String input) {
23+
return sha256(input.getBytes(StandardCharsets.UTF_8));
24+
}
25+
26+
/**
27+
* Generate SHA-256 as hex string (all lower-case).
28+
*
29+
* @param input Input as bytes.
30+
* @return Hex string.
31+
*/
32+
public static String sha256(byte[] input) {
33+
MessageDigest md = null;
34+
try {
35+
md = MessageDigest.getInstance("SHA-256");
36+
} catch (NoSuchAlgorithmException e) {
37+
throw new RuntimeException(e);
38+
}
39+
md.update(input);
40+
byte[] digest = md.digest();
41+
return ByteUtil.toHexString(digest);
42+
}
43+
44+
/**
45+
* Do HMAC-SHA256.
46+
*
47+
* @return Hex string.
48+
*/
49+
public static byte[] hmacSha256AsBytes(byte[] data, byte[] key) {
50+
SecretKey skey = new SecretKeySpec(key, "HmacSHA256");
51+
Mac mac;
52+
try {
53+
mac = Mac.getInstance("HmacSHA256");
54+
mac.init(skey);
55+
} catch (GeneralSecurityException e) {
56+
throw new RuntimeException(e);
57+
}
58+
mac.update(data);
59+
return mac.doFinal();
60+
}
61+
62+
/**
63+
* Do HMAC-SHA256.
64+
*
65+
* @return Hex string.
66+
*/
67+
public static String hmacSha256(byte[] data, byte[] key) {
68+
return ByteUtil.toHexString(hmacSha256AsBytes(data, key));
69+
}
70+
71+
/**
72+
* Do HMAC-SHA256.
73+
*
74+
* @return byte[] as result.
75+
*/
76+
public static String hmacSha256(String data, String key) {
77+
return hmacSha256(data.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
78+
}
79+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.helltractor.demo.util;
2+
3+
import jakarta.servlet.http.HttpServletRequest;
4+
5+
public class HttpUtil {
6+
7+
public static boolean isSecure(HttpServletRequest request) {
8+
String forwarded = request.getHeader("x-forwarded-proto");
9+
if (forwarded != null) {
10+
return "https".equals(forwarded);
11+
}
12+
return "https".equals(request.getScheme());
13+
}
14+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.helltractor.demo.util;
2+
3+
import java.util.UUID;
4+
import java.util.regex.Matcher;
5+
import java.util.regex.Pattern;
6+
7+
public class IdUtil {
8+
9+
static Pattern STRING_ID_PATTERN = Pattern.compile("^[a-zA-Z0-9]{1,32}$");
10+
11+
public static String generateUniqueId() {
12+
return UUID.randomUUID().toString().replace("-", "");
13+
}
14+
15+
public static boolean isValidStringId(String id) {
16+
if (id == null || id.isEmpty()) {
17+
return false;
18+
}
19+
Matcher matcher = STRING_ID_PATTERN.matcher(id);
20+
return matcher.matches();
21+
}
22+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.helltractor.demo.util;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import java.net.Inet4Address;
7+
import java.net.InetAddress;
8+
import java.net.NetworkInterface;
9+
import java.util.ArrayList;
10+
import java.util.Enumeration;
11+
import java.util.List;
12+
13+
/**
14+
* IpUtil to get IP address.
15+
*/
16+
public class IpUtil {
17+
18+
static final Logger logger = LoggerFactory.getLogger(IpUtil.class);
19+
20+
static final String IP;
21+
22+
static final String HOST_ID;
23+
24+
static {
25+
IP = doGetIpAddress();
26+
HOST_ID = doGetHostId();
27+
logger.info("get ip address: {}, host id: {}", IP, HOST_ID);
28+
}
29+
30+
/**
31+
* Get localhost's IP address as string.
32+
*
33+
* @return IP address like "10.0.1.127"
34+
*/
35+
public static String getIpAddress() {
36+
return IP;
37+
}
38+
39+
public static String getHostId() {
40+
return HOST_ID;
41+
}
42+
43+
static String doGetHostId() {
44+
String id = getIpAddress();
45+
return id.replace(".", "_").replace("-", "_");
46+
}
47+
48+
static String doGetIpAddress() {
49+
List<InetAddress> ipList = new ArrayList<>();
50+
try {
51+
Enumeration<NetworkInterface> iterInterface = NetworkInterface.getNetworkInterfaces();
52+
while (iterInterface.hasMoreElements()) {
53+
NetworkInterface network = iterInterface.nextElement();
54+
if (network.isLoopback() || !network.isUp()) {
55+
continue;
56+
}
57+
Enumeration<InetAddress> itAddr = network.getInetAddresses();
58+
while (itAddr.hasMoreElements()) {
59+
InetAddress addr = itAddr.nextElement();
60+
if (!addr.isLoopbackAddress() && (addr instanceof Inet4Address)) {
61+
ipList.add(addr);
62+
}
63+
}
64+
}
65+
} catch (Exception e) {
66+
logger.warn("Get IP address by NetworkInterface.getNetworkInterfaces() failed: {}", e.getMessage());
67+
}
68+
ipList.forEach((ip) -> {
69+
logger.debug("Found ip address: {}", ip.getHostAddress());
70+
});
71+
if (ipList.isEmpty()) {
72+
return "127.0.0.1";
73+
}
74+
return ipList.get(0).getHostAddress();
75+
}
76+
}

0 commit comments

Comments
 (0)