summaryrefslogtreecommitdiff
path: root/enigma-server/src/main/java/cuchaz/enigma/network/ServerAddress.java
blob: 09a13ccba5c9b2c2d40bcd59ca74bf37f2c4a31a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package cuchaz.enigma.network;

import java.util.Objects;

import org.jetbrains.annotations.Nullable;

public class ServerAddress {
	public final String address;
	public final int port;

	private ServerAddress(String address, int port) {
		this.address = address;
		this.port = port;
	}

	@Nullable
	public static ServerAddress of(String address, int port) {
		if (port < 0 || port > 65535) {
			return null;
		}

		if (address == null) {
			return null;
		}

		if (address.isEmpty()) {
			return null;
		}

		if (!address.matches("[a-zA-Z0-9.:-]+")) {
			return null;
		}

		if (address.startsWith("-") || address.endsWith("-")) {
			return null;
		}

		return new ServerAddress(address, port);
	}

	@Nullable
	public static ServerAddress from(String s, int defaultPort) {
		String address;
		int idx = s.indexOf(']');

		if (s.startsWith("[") && idx != -1) {
			address = s.substring(1, idx);
			s = s.substring(idx + 1);
		} else if (s.chars().filter(c -> c == ':').count() == 1) {
			idx = s.indexOf(':');
			address = s.substring(0, idx);
			s = s.substring(idx);
		} else {
			address = s;
			s = "";
		}

		int port;

		if (s.isEmpty()) {
			port = defaultPort;
		} else if (s.startsWith(":")) {
			s = s.substring(1);

			try {
				port = Integer.parseInt(s);
			} catch (NumberFormatException e) {
				return null;
			}
		} else {
			return null;
		}

		return ServerAddress.of(address, port);
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}

		if (o == null || getClass() != o.getClass()) {
			return false;
		}

		ServerAddress that = (ServerAddress) o;
		return port == that.port && Objects.equals(address, that.address);
	}

	@Override
	public int hashCode() {
		return Objects.hash(address, port);
	}

	@Override
	public String toString() {
		return String.format("ServerAddress { address: '%s', port: %d }", address, port);
	}
}