3

Let's pretend I have a JCR 2 query string that is made like this:

String sql2Query = "SELECT * FROM [cq:PageContent] " +
                   "WHERE [aProperty] <> \" + aValue + "\"";

Are there helper methods using which I can escape aValue?

By the way, I already know that in SQL2 we can use placeholders for queries and let the framework take care of escaping of values for us, but if I were to create this query dynamically, how can I escape aValue to prevent SQL injection as well as construction of broken queries?

Behrang
  • 46,888
  • 25
  • 118
  • 160

2 Answers2

8

Yes, you can use placeholders. Even dynamically created queries can use placeholders.

As for SQL-2, you need to use single quotes, not double quotes. Example:

SELECT * FROM [cq:PageContent]
WHERE [aProperty] <> 'Joe''s Taxi'

You only need to escape single quotes, using a single quote escape character:

String aValue = "Joe's Taxi";
String sql2Query = "SELECT * FROM [cq:PageContent] " +
    "WHERE [aProperty] <> '" + aValue.replaceAll("'", "''") + "'";

If you want to use XPath, you can use single quotes or double quotes, but usually single quotes are used as well (the same as in SQL-2). XPath queries don't support placeholders currently.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
  • Thanks. I was mainly looking for an API helper class/method to escape the text for me. Something similar to `QueryEscapeUtils.escapeStringVariable(String s)`. – Behrang Dec 02 '14 at 13:29
  • 3
    The same solution provides with org.apache.jackrabbit.oak.query.SQL2Parser.escapeStringLiteral("String for escape") (Can be added with groupId: org.apache.jackrabbit, and artifactId:oak-core) – Evgeniy Fitsner Oct 21 '16 at 19:25
1

Apparently org.apache.jackrabbit.util.Text has escapeIllegalJcrChars. Would this help?

More information: https://jackrabbit.apache.org/api/1.4/org/apache/jackrabbit/util/Text.html

bashaus
  • 1,614
  • 1
  • 17
  • 33