1 package org.djutils.cli;
2
3 import static org.junit.Assert.assertEquals;
4
5 import org.djutils.exceptions.Throw;
6 import org.junit.Test;
7
8 import picocli.CommandLine;
9 import picocli.CommandLine.Command;
10 import picocli.CommandLine.ITypeConverter;
11 import picocli.CommandLine.Option;
12
13
14
15
16
17
18
19
20
21 public class TestCLIRegisterConverter
22 {
23
24 public static class LatLon
25 {
26
27 private final double lat;
28
29
30 private final double lon;
31
32
33
34
35
36 public LatLon(final double lat, final double lon)
37 {
38 this.lat = lat;
39 this.lon = lon;
40 }
41
42
43
44
45 public double getLat()
46 {
47 return this.lat;
48 }
49
50
51
52
53 public double getLon()
54 {
55 return this.lon;
56 }
57
58
59
60
61
62
63
64 public static LatLon of(final String latlon) throws RuntimeException
65 {
66 String ll = latlon;
67 Throw.when(!ll.startsWith("("), RuntimeException.class, "string does not contain '('");
68 Throw.when(!ll.endsWith(")"), RuntimeException.class, "string does not contain ')'");
69 ll = ll.replaceAll("\\(", "").replaceAll("\\)", "");
70 String[] llArr = ll.split("\\,");
71 Throw.when(llArr.length != 2, RuntimeException.class, "string does not contain one ','");
72 double lat = Double.parseDouble(llArr[0].trim());
73 double lon = Double.parseDouble(llArr[1].trim());
74 return new LatLon(lat, lon);
75 }
76 }
77
78
79 @Command(description = "Test program for CLI", name = "Program", mixinStandardHelpOptions = true, version = "1.0")
80 public static class Options
81 {
82
83 @Option(names = {"-l", "--latlon"}, description = "Latitude and longitude of the form '(lat, lon)'")
84 private LatLon latLon;
85
86
87 public LatLon getLatLon()
88 {
89 return this.latLon;
90 }
91 }
92
93
94
95
96 public static class LatLonConverter implements ITypeConverter<LatLon>
97 {
98
99 @Override
100 public LatLon convert(final String value) throws Exception
101 {
102 return LatLon.of(value);
103 }
104 }
105
106
107
108
109
110
111
112
113 @Test
114 public void testCliRegisterConverters()
115 throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, CliException
116 {
117
118 String[] args = new String[] {"-l", "(50.2,71.3)"};
119 Options options = new Options();
120 CommandLine cmd = new CommandLine(options);
121 cmd.registerConverter(LatLon.class, new LatLonConverter());
122 CliUtil.execute(cmd, args);
123 assertEquals(50.2, options.getLatLon().getLat(), 0.001);
124 assertEquals(71.3, options.getLatLon().getLon(), 0.001);
125 }
126 }