|
6 | 6 | import org.springframework.stereotype.Service;
|
7 | 7 |
|
8 | 8 | import java.io.IOException;
|
9 |
| -import java.util.concurrent.TimeUnit; |
10 |
| -import java.util.regex.Matcher; |
11 |
| -import java.util.regex.Pattern; |
| 9 | +import java.net.InetAddress; |
| 10 | +import java.net.UnknownHostException; |
12 | 11 |
|
13 | 12 | @Service
|
14 | 13 | public class DomainTestService {
|
15 | 14 |
|
16 | 15 | final static int timeoutMs = 10_000;
|
17 |
| - final static Pattern domainValidationRegex = Pattern.compile("^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\\.(xn--)?([a-z0-9\\-]{1,61}|[a-z0-9-]{1,30}\\.[a-z]{2,})", Pattern.CASE_INSENSITIVE); |
18 | 16 |
|
19 | 17 | public String testDomain(String domainName) throws DomainTestException {
|
20 |
| - if (!isValidDomainName(domainName)) { |
| 18 | + InetAddress address; |
| 19 | + try { |
| 20 | + address = InetAddress.getByName(domainName); |
| 21 | + } catch (UnknownHostException e) { |
21 | 22 | throw new InvalidDomainException("Invalid domain name: " + domainName + " - don't try to hack us!");
|
22 | 23 | }
|
23 | 24 |
|
24 | 25 | try {
|
25 |
| - //TODO use ProcessBuilder which looks cleaner |
26 |
| - Process process = Runtime.getRuntime().exec(new String[] {"sh", "-c", "ping -c 1 " + domainName}); |
27 |
| - if (!process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) { |
28 |
| - throw new UnableToTestDomainException("Timed out pinging domain"); |
29 |
| - } |
30 |
| - int exitCode = process.exitValue(); |
31 |
| - if (exitCode != 0) { |
32 |
| - String stderr = new String(process.getErrorStream().readAllBytes(), StandardCharsets.UTF_8); |
33 |
| - throw new UnableToTestDomainException("Ping returned exit status " + exitCode + ": " + stderr); |
| 26 | + boolean reachable = address.isReachable(timeoutMs); |
| 27 | + if (!reachable) { |
| 28 | + throw new UnableToTestDomainException("The domain " + domainName + "is not reachable!"); |
34 | 29 | }
|
35 |
| - return new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); |
| 30 | + return "The domain " + domainName + "is reachable!"; |
36 | 31 | } catch (IOException e) {
|
37 | 32 | throw new UnableToTestDomainException("Internal error while testing domain: " + e.getMessage());
|
38 |
| - } catch (InterruptedException e) { |
39 |
| - throw new UnableToTestDomainException("Timed out pinging domain"); |
40 | 33 | }
|
41 | 34 | }
|
42 |
| - |
43 |
| - static boolean isValidDomainName(String domainName) { |
44 |
| - Matcher matcher = domainValidationRegex.matcher(domainName); |
45 |
| - return matcher.find(); |
46 |
| - } |
47 | 35 | }
|
0 commit comments