Guava equivalent for Apache commons.lang3 StringEscapeUtils.escapeJava ()

I am currently using StringEscapeUtils.escapeJava()from Apache Commons, but this is marked as deprecated since 3.6, and the suggestion is to move on to the package commons-text. Since I am not currently dependent on this and do not feel the need to add another dependency only for this package, I studied the shielding functionality that one of my other included libraries (Guava) provides.

However, I could not find the equivalent of the method escapeJava(). Since Guava seems to work a little differently, I was wondering if anyone could indicate how I could achieve the same result using Guava? (or using deprecated classes from commons-lang3)

+4
source share
2 answers

Since I could not find suitable alternatives in guava, I gave it another option using the StringUtilsfrom class lang3. I made a little utility function that escapes newlines and tabs. Suggestions are welcome, but for now it will be done.

public static String escapeForLogs(String input) {
  return org.apache.commons.lang3.StringUtils.replaceEach(
    input,
    new String[] { "\r\n", "\r", "\n", "\t" },
    new String[] { "\\\\n", "\\\\n", "\\\\n", "\\\\t" }
  );
}

I run the following tests:

@Test
public void testEscapeForLogs() {
  assertEquals("without linebreaks/tabs stays the same", "lala", e scapeForLogs("lala"));
  assertEquals("empty string is fine", "", escapeForLogs(""));
  assertEquals("newline gets escaped", "\\\\n", escapeForLogs("\n"));
  assertEquals("two newlines", "\\\\n\\\\n", escapeForLogs("\n\n"));
  assertEquals("tab", "\\\\t", escapeForLogs("\t"));
  assertEquals("return carridge gets escaped", "\\\\n", escapeForLogs("\r"));
  assertEquals("return carridge+newline gets converted", "\\\\n", escapeForLogs("\r\n"));
  assertEquals("newline before cr+nl", "\\\\n\\\\n", escapeForLogs("\n\r\n"));
  assertEquals("2 cr+nl", "\\\\n\\\\n", escapeForLogs("\r\n\r\n"));
  assertEquals("some combination", "lala\\\\nlalala\\\\n\\\\nla\\\\tla", escapeForLogs("lala\nlalala\n\nla\tla"));
}
0
source

I do not see anything comparable. It really seems like the best option is to just add a dependency on commons-text.

However, if you are really against it, you can use Guava Escapersand try to rebuild the Java rules found in StringEscapeUtils#ESCAPE_JAVA. However, this seems like the worst approach.

+2
source

Source: https://habr.com/ru/post/1693665/


All Articles