ApiServlet extends HttpServlet { void utf8Fixup(final HttpServletRequest req, final Map<String, Object[]> params) { if (req.getQueryString() == null) { return; } final String[] paramsInQueryString = req.getQueryString().split("&"); if (paramsInQueryString != null) { for (final String param : paramsInQueryString) { final String[] paramTokens = param.split("=", 2); if (paramTokens.length == 2) { String name = decodeUtf8(paramTokens[0]); String value = decodeUtf8(paramTokens[1]); params.put(name, new String[] {value}); } else { s_logger.debug("Invalid parameter in URL found. param: " + param); } } } } ApiServlet(); @Override void init(final ServletConfig config); static final Logger s_logger; }
@Test public void utf8Fixup() { Mockito.when(request.getQueryString()).thenReturn( "foo=12345&bar=blah&baz=&param=param"); HashMap<String, Object[]> params = new HashMap<String, Object[]>(); servlet.utf8Fixup(request, params); Assert.assertEquals("12345", params.get("foo")[0]); Assert.assertEquals("blah", params.get("bar")[0]); }
@Test public void utf8FixupNull() { Mockito.when(request.getQueryString()).thenReturn("&&=a&=&&a&a=a=a=a"); servlet.utf8Fixup(request, new HashMap<String, Object[]>()); }
@Test public void utf8FixupStrangeInputs() { Mockito.when(request.getQueryString()).thenReturn("&&=a&=&&a&a=a=a=a"); HashMap<String, Object[]> params = new HashMap<String, Object[]>(); servlet.utf8Fixup(request, params); Assert.assertTrue(params.containsKey("")); }
@Test public void utf8FixupUtf() throws UnsupportedEncodingException { Mockito.when(request.getQueryString()).thenReturn( URLEncoder.encode("防水镜钻孔机", "UTF-8") + "=" + URLEncoder.encode("árvíztűrőtükörfúró", "UTF-8")); HashMap<String, Object[]> params = new HashMap<String, Object[]>(); servlet.utf8Fixup(request, params); Assert.assertEquals("árvíztűrőtükörfúró", params.get("防水镜钻孔机")[0]); }