Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping dots in java. (StringEscapeUtil)

This is probably a super dumb question, but I can't work out why StringEscapeUtils is behaving in this manner.

It's the second assert that's failing, with the following error:

org.junit.ComparisonFailure: Did not escape correctly Expected :t\.ext Actual :t.ext

Tests

public class ServerDataTest {
    @Test
    public void escape() throws Exception {
        assertEquals("Did not escape correctly", "text", ServerData.escape("text"));
        assertEquals("Did not escape correctly", "t\\.ext", ServerData.escape("t.ext"));
        assertEquals("Did not escape correctly", "te\\\\xt", ServerData.escape("te\\xt"));
        assertEquals("Did not escape correctly", "te\\\\\\.xt", ServerData.escape("te\\.xt"));
    }
}

Escaper utility

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<>();{
        ESCAPE_MAP.put("\\", "\\\\");
        ESCAPE_MAP.put(".",  "\\.");
    }

    private static LookupTranslator ESCAPE = new LookupTranslator(ESCAPE_MAP);

    private final static Map<CharSequence, CharSequence> UNESCAPE_MAP = new HashMap<>();{
        UNESCAPE_MAP.put("\\\\", "\\");
        UNESCAPE_MAP.put("\\.", ".");
    }

    private static LookupTranslator UNESCAPE = new LookupTranslator(UNESCAPE_MAP);

    static String escape(String text){
        return StringEscapeUtils.builder(ESCAPE).escape(text).toString();
    }

    static String unescape(String text){
        return StringEscapeUtils.builder(UNESCAPE).escape(text).toString();
    }
like image 541
Ryan Leach Avatar asked Apr 08 '26 12:04

Ryan Leach


1 Answers

You never fill the static Maps ESCAPE_MAP and UNESCAPE_MAP, because you forget the keyword static.

Here's the correct code

private final static Map<CharSequence, CharSequence> ESCAPE_MAP = new HashMap<>();
static {
    ESCAPE_MAP.put("\\", "\\\\");
    ESCAPE_MAP.put(".",  "\\.");
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!