1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.chabala.brick.controllab;
20
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 import java.lang.invoke.MethodHandles;
25 import java.util.List;
26
27 import static org.hamcrest.Matchers.*;
28 import static org.junit.Assume.assumeThat;
29
30
31
32
33
34
35 @SuppressWarnings("WeakerAccess")
36 public final class PortChooser {
37 private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
38 private static final String TOO_FEW_PORTS_MESSAGE = "as many serial ports as requested should be available";
39
40
41 public static final String OVERRIDE_TEST_PORT_PROPERTY = "brick-control-lab.overrideTestPort";
42
43
44
45
46
47
48 public static String choosePort(ControlLab controlLab) {
49 return choosePort(controlLab, 1);
50 }
51
52
53
54
55
56
57
58 public static String choosePort(ControlLab controlLab, int position) {
59 String overrideTestPort = System.getProperty(OVERRIDE_TEST_PORT_PROPERTY, "");
60 int zeroBasedPosition = position - 1;
61
62 if (overrideTestPort.isEmpty()) {
63 List<String> availablePorts = controlLab.getAvailablePorts();
64 assumeThat("a serial port should be available", availablePorts, is(not(empty())));
65 log.debug("Available ports: {}", String.join(", ", availablePorts));
66 assumeThat(TOO_FEW_PORTS_MESSAGE, availablePorts, hasSize(greaterThanOrEqualTo(position)));
67 return availablePorts.get(zeroBasedPosition);
68 } else {
69 log.debug("{} property is defined: {}", OVERRIDE_TEST_PORT_PROPERTY, overrideTestPort);
70 String[] overrideTestPorts = overrideTestPort.split(",");
71 assumeThat(TOO_FEW_PORTS_MESSAGE, overrideTestPorts, arrayWithSize(greaterThanOrEqualTo(position)));
72 return overrideTestPorts[zeroBasedPosition];
73 }
74 }
75
76 private PortChooser() {
77 throw new UnsupportedOperationException();
78 }
79 }