source: josm/trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java@ 6568

Last change on this file since 6568 was 6568, checked in by simon04, 10 years ago

fix #9462 - fix preset values for opening_hour/… such that the OpeningHourTest does not yield warnings, add unit test that validates all preset values

File size: 9.5 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.data.validation.tests;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.InputStreamReader;
7import java.util.ArrayList;
8import java.util.Arrays;
9import java.util.Collections;
10import java.util.List;
11
12import javax.script.Invocable;
13import javax.script.ScriptEngine;
14import javax.script.ScriptEngineManager;
15import javax.script.ScriptException;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.command.ChangePropertyCommand;
19import org.openstreetmap.josm.data.osm.Node;
20import org.openstreetmap.josm.data.osm.OsmPrimitive;
21import org.openstreetmap.josm.data.osm.Relation;
22import org.openstreetmap.josm.data.osm.Way;
23import org.openstreetmap.josm.data.validation.FixableTestError;
24import org.openstreetmap.josm.data.validation.Severity;
25import org.openstreetmap.josm.data.validation.Test;
26import org.openstreetmap.josm.data.validation.TestError;
27import org.openstreetmap.josm.io.MirroredInputStream;
28import org.openstreetmap.josm.tools.Utils;
29
30/**
31 * Tests the correct usage of the opening hour syntax of the tags
32 * {@code opening_hours}, {@code collection_times}, {@code service_times} according to
33 * <a href="https://github.com/ypid/opening_hours.js">opening_hours.js</a>.
34 *
35 * @since 6370
36 */
37public class OpeningHourTest extends Test {
38
39 /**
40 * Javascript engine
41 */
42 public static final ScriptEngine ENGINE = new ScriptEngineManager().getEngineByName("JavaScript");
43
44 /**
45 * Constructs a new {@code OpeningHourTest}.
46 */
47 public OpeningHourTest() {
48 super(tr("Opening hours syntax"),
49 tr("This test checks the correct usage of the opening hours syntax."));
50 }
51
52 @Override
53 public void initialize() throws Exception {
54 super.initialize();
55 if (ENGINE != null) {
56 ENGINE.eval(new InputStreamReader(new MirroredInputStream("resource://data/validator/opening_hours.js"), Utils.UTF_8));
57 // fake country/state to not get errors on holidays
58 ENGINE.eval("var nominatimJSON = {address: {state: 'Bayern', country_code: 'de'}};");
59 ENGINE.eval("" +
60 "var oh = function (value, mode) {" +
61 " try {" +
62 " var r= new opening_hours(value, nominatimJSON, mode);" +
63 " r.getErrors = function() {return [];};" +
64 " return r;" +
65 " } catch(err) {" +
66 " return {" +
67 " getWarnings: function() {return [];}," +
68 " getErrors: function() {return [err.toString()]}" +
69 " };" +
70 " }" +
71 "};");
72 } else {
73 Main.warn("Unable to initialize OpeningHourTest because no JavaScript engine has been found");
74 }
75 }
76
77 static enum CheckMode {
78 TIME_RANGE(0), POINTS_IN_TIME(1), BOTH(2);
79 final int code;
80
81 CheckMode(int code) {
82 this.code = code;
83 }
84 }
85
86 protected Object parse(String value, CheckMode mode) throws ScriptException, NoSuchMethodException {
87 return ((Invocable) ENGINE).invokeFunction("oh", value, mode.code);
88 }
89
90 @SuppressWarnings("unchecked")
91 protected List<Object> getList(Object obj) throws ScriptException, NoSuchMethodException {
92 if (obj == null || "".equals(obj)) {
93 return Arrays.asList();
94 } else if (obj instanceof String) {
95 final Object[] strings = ((String) obj).split("\\\\n");
96 return Arrays.asList(strings);
97 } else if (obj instanceof List) {
98 return (List<Object>) obj;
99 } else {
100 // recursively call getList() with argument converted to newline-separated string
101 return getList(((Invocable) ENGINE).invokeMethod(obj, "join", "\\n"));
102 }
103 }
104
105 /**
106 * An error concerning invalid syntax for an "opening_hours"-like tag.
107 */
108 public class OpeningHoursTestError {
109 final Severity severity;
110 final String message, prettifiedValue;
111
112 /**
113 * Constructs a new {@code OpeningHoursTestError} with a known pretiffied value.
114 * @param message The error message
115 * @param severity The error severity
116 * @param prettifiedValue The prettified value
117 */
118 public OpeningHoursTestError(String message, Severity severity, String prettifiedValue) {
119 this.message = message;
120 this.severity = severity;
121 this.prettifiedValue = prettifiedValue;
122 }
123
124 /**
125 * Returns the real test error given to JOSM validator.
126 * @param p The incriminated OSM primitive.
127 * @param key The incriminated key, used for display.
128 * @return The real test error given to JOSM validator. Can be fixable or not if a prettified values has been determined.
129 */
130 public TestError getTestError(final OsmPrimitive p, final String key) {
131 if (prettifiedValue == null) {
132 return new TestError(OpeningHourTest.this, severity, message, 2901, p);
133 } else {
134 return new FixableTestError(OpeningHourTest.this, severity, message, 2901, p,
135 new ChangePropertyCommand(p, key, prettifiedValue));
136 }
137 }
138
139 /**
140 * Returns the error message.
141 * @return The error message.
142 */
143 public String getMessage() {
144 return message;
145 }
146
147 /**
148 * Returns the prettified value.
149 * @return The prettified value.
150 */
151 public String getPrettifiedValue() {
152 return prettifiedValue;
153 }
154
155 /**
156 * Returns the error severity.
157 * @return The error severity.
158 */
159 public Severity getSeverity() {
160 return severity;
161 }
162
163 @Override
164 public String toString() {
165 return getMessage() + " => " + getPrettifiedValue();
166 }
167 }
168
169 /**
170 * Checks for a correct usage of the opening hour syntax of the {@code value} given according to
171 * <a href="https://github.com/ypid/opening_hours.js">opening_hours.js</a> and returns a list containing
172 * validation errors or an empty list. Null values result in an empty list.
173 * @param key the OSM key (should be "opening_hours", "collection_times" or "service_times"). Used in error message
174 * @param value the opening hour value to be checked.
175 * @param mode whether to validate {@code value} as a time range, or points in time, or both.
176 * @return a list of {@link TestError} or an empty list
177 */
178 public List<OpeningHoursTestError> checkOpeningHourSyntax(final String key, final String value, CheckMode mode) {
179 if (ENGINE == null || value == null || value.trim().isEmpty()) {
180 return Collections.emptyList();
181 }
182 try {
183 final Object r = parse(value, mode);
184 final List<OpeningHoursTestError> errors = new ArrayList<OpeningHoursTestError>();
185 String prettifiedValue = null;
186 try {
187 prettifiedValue = (String) ((Invocable) ENGINE).invokeMethod(r, "prettifyValue");
188 } catch (Exception e) {
189 Main.debug(e.getMessage());
190 }
191 for (final Object i : getList(((Invocable) ENGINE).invokeMethod(r, "getErrors"))) {
192 errors.add(new OpeningHoursTestError(key + " - " + i.toString().trim(), Severity.ERROR, prettifiedValue));
193 }
194 for (final Object i : getList(((Invocable) ENGINE).invokeMethod(r, "getWarnings"))) {
195 errors.add(new OpeningHoursTestError(i.toString().trim(), Severity.WARNING, prettifiedValue));
196 }
197 if (errors.isEmpty() && prettifiedValue != null && !value.equals(prettifiedValue)) {
198 errors.add(new OpeningHoursTestError(tr("opening_hours value can be prettified"), Severity.OTHER, prettifiedValue));
199 }
200 return errors;
201 } catch (final Exception ex) {
202 throw new RuntimeException(ex);
203 }
204 }
205
206 /**
207 * Checks for a correct usage of the opening hour syntax of the {@code value} given, in time range mode, according to
208 * <a href="https://github.com/ypid/opening_hours.js">opening_hours.js</a> and returns a list containing
209 * validation errors or an empty list. Null values result in an empty list.
210 * @param key the OSM key (should be "opening_hours", "collection_times" or "service_times"). Used in error message
211 * @param value the opening hour value to be checked.
212 * @return a list of {@link TestError} or an empty list
213 */
214 public List<OpeningHoursTestError> checkOpeningHourSyntax(final String key, final String value) {
215 return checkOpeningHourSyntax(key, value, "opening_hours".equals(key) ? CheckMode.TIME_RANGE : CheckMode.BOTH);
216 }
217
218 protected void check(final OsmPrimitive p, final String key, CheckMode mode) {
219 for (OpeningHoursTestError e : checkOpeningHourSyntax(key, p.get(key), mode)) {
220 errors.add(e.getTestError(p, key));
221 }
222 }
223
224 protected void check(final OsmPrimitive p) {
225 check(p, "opening_hours", CheckMode.TIME_RANGE);
226 check(p, "collection_times", CheckMode.BOTH);
227 check(p, "service_times", CheckMode.BOTH);
228 }
229
230 @Override
231 public void visit(final Node n) {
232 check(n);
233 }
234
235 @Override
236 public void visit(final Relation r) {
237 check(r);
238 }
239
240 @Override
241 public void visit(final Way w) {
242 check(w);
243 }
244}
Note: See TracBrowser for help on using the repository browser.