QueryPreprocessor { public static String sanitize(String query) { String sanitizedQuery = ""; String sanitizedToken; ArrayList<String> tokens = tokenize(query); int i = 0; while (i < tokens.size()) { String token = tokens.get(i); if (isUnaryOperator(token)) { sanitizedToken = sanitizeUnaryOperator(token); } else if (isBinaryOperator(token)) { if ((i == 0) || isBinaryOperator(tokens.get(i - 1)) || (i >= tokens.size() - 1) || isBinaryOperator(tokens.get(i + 1))) { sanitizedToken = "" + BACKSLASH + token; } else { sanitizedToken = token; } } else { sanitizedToken = enablePartialMatches(token, 0); } if (i != 0) { sanitizedQuery += " "; } sanitizedQuery += sanitizedToken; i++; } logger.debug("Sanitized input '{}' to '{}'", query, sanitizedQuery); return sanitizedQuery; } private  QueryPreprocessor(); static String sanitize(String query);  }
@Test public void testBlankQueries() { assertEquals("", QueryPreprocessor.sanitize("")); assertEquals("", QueryPreprocessor.sanitize(" ")); }
@Test public void testDoubleQuotes() { assertEquals("\"Hello\"", QueryPreprocessor.sanitize("\"Hello\"")); assertEquals("*Hello* \"World\"", QueryPreprocessor.sanitize("Hello \"World\"")); assertEquals("*Hello* \"World\"", QueryPreprocessor.sanitize("Hello \"World")); assertEquals("*Hello* \"World Again\"", QueryPreprocessor.sanitize("Hello \"World Again")); assertEquals("*He\\\"llo* *Wor\\\"ld*", QueryPreprocessor.sanitize("He\"llo Wor\"ld")); }
@Test public void testWildcards() { assertEquals("*", QueryPreprocessor.sanitize("*")); assertEquals("*", QueryPreprocessor.sanitize(" * ")); assertEquals("*?*", QueryPreprocessor.sanitize("?")); assertEquals("*?*", QueryPreprocessor.sanitize(" ? ")); assertEquals("*H*llo* *Worl*d*", QueryPreprocessor.sanitize("H*llo Worl*d")); assertEquals("*H?llo* *Worl?d*", QueryPreprocessor.sanitize("H?llo Worl?d")); }
@Test public void testCharacterEscaping() { assertEquals("*\\(* *\\)* *\\[* *\\]* *\\{* *\\}* *\\~* *\\^* *\\:* *\\\\*", QueryPreprocessor.sanitize(" ( ) [ ] { } ~ ^ : \\")); assertEquals("\" ( ) [ ] { } ~ ^ : \\\"", QueryPreprocessor.sanitize("\" ( ) [ ] { } ~ ^ : \\\"")); assertEquals("\"|| && + - ! * ?\"", QueryPreprocessor.sanitize("\"|| && + - ! * ?\"")); }
@Test public void testPartialMatches() { assertEquals("*Hello*", QueryPreprocessor.sanitize("Hello")); assertEquals("*Hello*", QueryPreprocessor.sanitize("*Hello")); assertEquals("*Hello*", QueryPreprocessor.sanitize("Hello*")); assertEquals("*Hello*", QueryPreprocessor.sanitize("*Hello*")); assertEquals("*Hello* *World*", QueryPreprocessor.sanitize("Hello World")); assertEquals("*Hello* *World*", QueryPreprocessor.sanitize("Hello* World")); assertEquals("*Hello* *World*", QueryPreprocessor.sanitize("Hello *World")); assertEquals("*Hello* *World*", QueryPreprocessor.sanitize("*Hello* *World*")); }