Escape backslash in StringQuery.

Original Pull Request
Closes #2326

(cherry picked from commit 03ecc48b09e42a041c9f04bc47801b36adf91306)
This commit is contained in:
Peter-Josef Meisch 2022-10-11 22:36:43 +02:00
parent 02b6d54cc9
commit 2fa15f772a
No known key found for this signature in database
GPG Key ID: DE108246970C7708
2 changed files with 17 additions and 2 deletions

View File

@ -46,7 +46,11 @@ final public class StringQueryUtil {
String placeholder = Pattern.quote(matcher.group()) + "(?!\\d+)";
int index = NumberUtils.parseNumber(matcher.group(1), Integer.class);
result = result.replaceAll(placeholder, Matcher.quoteReplacement(getParameterWithIndex(accessor, index)));
String replacement = Matcher.quoteReplacement(getParameterWithIndex(accessor, index));
result = result.replaceAll(placeholder, replacement);
// need to escape backslashes that are not escapes for quotes so that they are sent as double-backslashes
// to Elasticsearch
result = result.replaceAll("\\\\([^\"'])", "\\\\\\\\$1");
}
return result;
}
@ -56,7 +60,6 @@ final public class StringQueryUtil {
Object parameter = accessor.getBindableValue(index);
String parameterValue = "null";
// noinspection ConstantConditions
if (parameter != null) {
parameterValue = convert(parameter);

View File

@ -129,6 +129,18 @@ public class ElasticsearchStringQueryUnitTests extends ElasticsearchStringQueryU
"{ 'bool' : { 'must' : { 'terms' : { 'name' : [\"hello \\\"Stranger\\\"\",\"Another string\"] } } } }");
}
@Test // #2326
@DisplayName("should escape backslashes in collection query parameters")
void shouldEscapeBackslashesInCollectionQueryParameters() throws NoSuchMethodException {
final List<String> parameters = Arrays.asList("param\\1", "param\\2");
List<String> params = new ArrayList<>(parameters);
org.springframework.data.elasticsearch.core.query.Query query = createQuery("findByNameIn", params);
assertThat(query).isInstanceOf(StringQuery.class);
assertThat(((StringQuery) query).getSource()).isEqualTo(
"{ 'bool' : { 'must' : { 'terms' : { 'name' : [\"param\\\\1\",\"param\\\\2\"] } } } }");
}
private org.springframework.data.elasticsearch.core.query.Query createQuery(String methodName, Object... args)
throws NoSuchMethodException {