001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import java.util.ArrayList; 005import java.util.Collections; 006import java.util.EnumSet; 007import java.util.List; 008import java.util.Locale; 009import java.util.Optional; 010import java.util.Set; 011import java.util.regex.Matcher; 012import java.util.regex.Pattern; 013import java.util.stream.Collectors; 014import java.util.stream.Stream; 015 016import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 017import org.openstreetmap.josm.data.osm.search.SearchCompiler; 018import org.openstreetmap.josm.data.osm.search.SearchCompiler.Match; 019import org.openstreetmap.josm.data.osm.search.SearchParseError; 020 021/** 022 * Builds an Overpass QL from a {@link org.openstreetmap.josm.actions.search.SearchAction} query. 023 * 024 * @since 8744 (using tyrasd/overpass-wizard), 16262 (standalone) 025 */ 026public final class SearchCompilerQueryWizard { 027 028 private SearchCompilerQueryWizard() { 029 // private constructor for utility class 030 } 031 032 /** 033 * Builds an Overpass QL from a {@link org.openstreetmap.josm.actions.search.SearchAction} like query. 034 * @param search the {@link org.openstreetmap.josm.actions.search.SearchAction} like query 035 * @return an Overpass QL query 036 * @throws UncheckedParseException when the parsing fails 037 */ 038 public static String constructQuery(final String search) { 039 try { 040 Matcher matcher = Pattern.compile("\\s+GLOBAL\\s*$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS) 041 .matcher(search); 042 if (matcher.find()) { 043 final Match match = SearchCompiler.compile(matcher.replaceFirst("")); 044 return constructQuery(match, ";", ""); 045 } 046 047 matcher = Pattern.compile("\\s+IN BBOX\\s*$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS) 048 .matcher(search); 049 if (matcher.find()) { 050 final Match match = SearchCompiler.compile(matcher.replaceFirst("")); 051 return constructQuery(match, "[bbox:{{bbox}}];", ""); 052 } 053 054 matcher = Pattern.compile("\\s+(?<mode>IN|AROUND)\\s+(?<area>[^\" ]+|\"[^\"]+\")\\s*$", 055 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS).matcher(search); 056 if (matcher.find()) { 057 final Match match = SearchCompiler.compile(matcher.replaceFirst("")); 058 final String mode = matcher.group("mode").toUpperCase(Locale.ENGLISH); 059 final String area = Utils.strip(matcher.group("area"), "\""); 060 if ("IN".equals(mode)) { 061 return constructQuery(match, ";\n{{geocodeArea:" + area + "}}->.searchArea;", "(area.searchArea)"); 062 } else if ("AROUND".equals(mode)) { 063 return constructQuery(match, ";\n{{radius=1000}}", "(around:{{radius}},{{geocodeCoords:" + area + "}})"); 064 } else { 065 throw new IllegalStateException(mode); 066 } 067 } 068 069 final Match match = SearchCompiler.compile(search); 070 return constructQuery(match, "[bbox:{{bbox}}];", ""); 071 } catch (SearchParseError | UnsupportedOperationException e) { 072 throw new UncheckedParseException(e); 073 } 074 } 075 076 private static String constructQuery(final Match match, final String bounds, final String queryLineSuffix) { 077 final List<Match> normalized = normalizeToDNF(match); 078 final List<String> queryLines = new ArrayList<>(); 079 queryLines.add("[out:xml][timeout:90]" + bounds); 080 queryLines.add("("); 081 for (Match conjunction : normalized) { 082 final EnumSet<OsmPrimitiveType> types = EnumSet.noneOf(OsmPrimitiveType.class); 083 final String query = constructQuery(conjunction, types); 084 queryLines.addAll((types.isEmpty() || types.size() == 3 085 ? Stream.of("nwr") 086 : types.stream().map(OsmPrimitiveType::getAPIName)) 087 .map(type -> " " + type + query + queryLineSuffix + ";") 088 .collect(Collectors.toList())); 089 } 090 queryLines.add(");"); 091 queryLines.add("(._;>;);"); 092 queryLines.add("out meta;"); 093 return String.join("\n", queryLines); 094 } 095 096 private static String constructQuery(Match match, final Set<OsmPrimitiveType> types) { 097 final boolean negated; 098 if (match instanceof SearchCompiler.Not) { 099 negated = true; 100 match = ((SearchCompiler.Not) match).getMatch(); 101 } else { 102 negated = false; 103 } 104 if (match instanceof SearchCompiler.And) { 105 return ((SearchCompiler.And) match).map(m -> constructQuery(m, types), (s1, s2) -> s1 + s2); 106 } else if (match instanceof SearchCompiler.KeyValue) { 107 final String key = ((SearchCompiler.KeyValue) match).getKey(); 108 final String value = ((SearchCompiler.KeyValue) match).getValue(); 109 if ("newer".equals(key)) { 110 return "(newer:" + quote("{{date:" + value + "}}") + ")"; 111 } 112 return "[~" + quote(key) + "~" + quote(value) + "]"; 113 } else if (match instanceof SearchCompiler.ExactKeyValue) { 114 // https://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide 115 // ["key"] -- filter objects tagged with this key and any value 116 // [!"key"] -- filter objects not tagged with this key and any value 117 // ["key"="value"] -- filter objects tagged with this key and this value 118 // ["key"!="value"] -- filter objects tagged with this key but not this value, or not tagged with this key 119 // ["key"~"value"] -- filter objects tagged with this key and a value matching a regular expression 120 // ["key"!~"value"] -- filter objects tagged with this key but a value not matching a regular expression 121 // [~"key"~"value"] -- filter objects tagged with a key and a value matching regular expressions 122 // [~"key"~"value", i] -- filter objects tagged with a key and a case-insensitive value matching regular expressions 123 final String key = ((SearchCompiler.ExactKeyValue) match).getKey(); 124 final String value = ((SearchCompiler.ExactKeyValue) match).getValue(); 125 final SearchCompiler.ExactKeyValue.Mode mode = ((SearchCompiler.ExactKeyValue) match).getMode(); 126 switch (mode) { 127 case ANY_VALUE: 128 return "[" + (negated ? "!" : "") + quote(key) + "]"; 129 case EXACT: 130 return "[" + quote(key) + (negated ? "!=" : "=") + quote(value) + "]"; 131 case ANY_KEY: // *=value 132 // fall through 133 case EXACT_REGEXP: 134 final Matcher matcher = Pattern.compile("/(?<regex>.*)/(?<flags>i)?").matcher(value); 135 final String valueQuery = matcher.matches() 136 ? quote(matcher.group("regex")) + Optional.ofNullable(matcher.group("flags")).map(f -> "," + f).orElse("") 137 : quote(value); 138 if (mode == SearchCompiler.ExactKeyValue.Mode.ANY_KEY) 139 return "[~\"^.*$\"" + (negated ? "!~" : "~") + valueQuery + "]"; 140 return "[" + quote(key) + (negated ? "!~" : "~") + valueQuery + "]"; 141 case MISSING_KEY: 142 // special case for empty values, see https://github.com/drolbr/Overpass-API/issues/53 143 return "[" + quote(key) + (negated ? "!~" : "~") + quote("^$") + "]"; 144 default: 145 return ""; 146 } 147 } else if (match instanceof SearchCompiler.BooleanMatch) { 148 final String key = ((SearchCompiler.BooleanMatch) match).getKey(); 149 return negated 150 ? "[" + quote(key) + "~\"false|no|0|off\"]" 151 : "[" + quote(key) + "~\"true|yes|1|on\"]"; 152 } else if (match instanceof SearchCompiler.UserMatch) { 153 final String user = ((SearchCompiler.UserMatch) match).getUser(); 154 return user.matches("\\d+") 155 ? "(uid:" + user + ")" 156 : "(user:" + quote(user) + ")"; 157 } else if (match instanceof SearchCompiler.ExactType) { 158 types.add(((SearchCompiler.ExactType) match).getType()); 159 return ""; 160 } 161 Logging.warn("Unsupported match type {0}: {1}", match.getClass(), match); 162 return "/*" + match + "*/"; 163 } 164 165 /** 166 * Quotes the given string for its use in Overpass QL 167 * @param s the string to quote 168 * @return the quoted string 169 */ 170 private static String quote(final String s) { 171 return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; 172 } 173 174 /** 175 * Normalizes the match to disjunctive normal form: A∧(B∨C) ⇔ (A∧B)∨(A∧C) 176 * @param match the match to normalize 177 * @return the match in disjunctive normal form 178 */ 179 private static List<Match> normalizeToDNF(final Match match) { 180 if (match instanceof SearchCompiler.And) { 181 return ((SearchCompiler.And) match).map(SearchCompilerQueryWizard::normalizeToDNF, (lhs, rhs) -> lhs.stream() 182 .flatMap(l -> rhs.stream().map(r -> new SearchCompiler.And(l, r))) 183 .collect(Collectors.toList())); 184 } else if (match instanceof SearchCompiler.Or) { 185 return ((SearchCompiler.Or) match).map(SearchCompilerQueryWizard::normalizeToDNF, CompositeList::new); 186 } else if (match instanceof SearchCompiler.Xor) { 187 throw new UnsupportedOperationException(match.toString()); 188 } else if (match instanceof SearchCompiler.Not) { 189 // only support negated KeyValue or ExactKeyValue matches 190 final Match innerMatch = ((SearchCompiler.Not) match).getMatch(); 191 if (innerMatch instanceof SearchCompiler.BooleanMatch 192 || innerMatch instanceof SearchCompiler.KeyValue 193 || innerMatch instanceof SearchCompiler.ExactKeyValue) { 194 return Collections.singletonList(match); 195 } 196 throw new UnsupportedOperationException(match.toString()); 197 } else { 198 return Collections.singletonList(match); 199 } 200 } 201 202}