1

PROBLEM

I'm using Abatis as ORM. When I try to insert a json containing a specific string it crashes.

I have extracted the code from Abatis that generates the error:

CODE

            Map<String, Object> bindParams = new HashMap<String, Object>();

            bindParams.put("id", "194fa0f2-9706-493f-97ab-4eb300a8e4ed");
            bindParams.put("field", "{\"Messages\":\"ERRORE durante l'invocazione del servizio. 01 - Executor [java.util.concurrent.ThreadPoolExecutor@18a96588] did not accept task: org.springframework.aop.interceptor.AsyncExecutionInterceptor$1@14a7c67b\",\"Errors\":1}");

            String sql = "UPDATE <TABLE> SET NoteAgente = #field# WHERE Id = #id#";

            if (bindParams != null) {
                Iterator<String> mapIterator = bindParams.keySet().iterator();
                while (mapIterator.hasNext()) {
                    String key = mapIterator.next();
                    Object value = bindParams.get(key);

                    if(value instanceof String && value != null)
                        value = value.toString().replace("'", "''");

                    sql = sql.replaceAll("#" + key + "#", value == null ? "null"
                            : "'" + value.toString() + "'");
                }
            }

The problem is in the replaceAll method with the string $1@14a7c67b. You can also debug it writing

String s = "onetwothree";               
s = s.replaceAll("one", "$1@14a7c67b");

and it will also crashes.

Link 88
  • 553
  • 8
  • 27

1 Answers1

6

replaceAll takes a regular expression argument, and $1 is a special way of telling the java regex engine to use group-one as the replacement.

You need to use replace which matches/replaces the string literally:

String s = "onetwothree";
s = s.replace("one", "$1@14a7c67b");

You could also escape the $ character if you still need to use replaceAll:

s = s.replaceAll("one", "\\$1@14a7c67b");
epoch
  • 16,396
  • 4
  • 43
  • 71
  • 1
    Perfect answer! It works like a charm! Can't just mark this as answer, I will do it as soon as I can. – Link 88 May 12 '15 at 13:56
  • See also https://stackoverflow.com/a/50047372/245966 ; note also that unlike in JavaScript, in Java `replace` replaces all occurrences, not only the first one! – jakub.g Apr 26 '18 at 16:11