QueryStringParser implements Parser<Map<String, String>> { @Override public Map<String, String> parse(final String queryString) throws MalformedInputException { Map<String, String> parameters = new HashMap<>(); String[] queryParametersArray = queryString.split(PAIR_SEPARATOR); for (int i = 0; i < queryParametersArray.length; i++) { if (queryParametersArray[i].length() == 0) { continue; } String[] parameterPair = queryParametersArray[i].split(VALUE_SEPARATOR, 2); if (parameterPair[0].length() == 0) { continue; } if (parameterPair.length > 1) { parameters.put(parameterPair[0], StringUtilities.urlDecode(parameterPair[1])); } } return parameters; }  @Override Map<String, String> parse(final String queryString);  }
@Test public void shouldParseFields() throws MalformedInputException { String data = "&param1=ABCD1" + "&param2=ABCD2" + "&param3=ABC=DEF" + "&param4=A%20B%20%3D%20%25%20*"; Parser<Map<String, String>> parser = new QueryStringParser(); Map<String, String> parameters = parser.parse(data); assertThat(parameters.size(), is(4)); assertThat(parameters.get("param1"), is("ABCD1")); assertThat(parameters.get("param2"), is("ABCD2")); assertThat(parameters.get("param3"), is("ABC=DEF")); assertThat(parameters.get("param4"), is("A B = % *")); }
@Test public void shouldParseEmptyFields() throws MalformedInputException { String data = ""; Parser<Map<String, String>> parser = new QueryStringParser(); Map<String, String> parameters = parser.parse(data); assertThat(parameters.size(), is(0)); }
@Test public void shouldParseNonValidString() throws MalformedInputException { String data = "/"; Parser<Map<String, String>> parser = new QueryStringParser(); Map<String, String> parameters = parser.parse(data); assertThat(parameters.size(), is(0)); }
@Test public void shouldParseIncompleteFields() throws MalformedInputException { String data = "=&param1=" + "&&" + "&param1=" + "&param2=ABCD2" + "&param3=ABC=DEF" + "&param4=A%20B%20%3D%20%25%20*"; Parser<Map<String, String>> parser = new QueryStringParser(); Map<String, String> parameters = parser.parse(data); assertThat(parameters.size(), is(4)); assertThat(parameters.get("param1"), is("")); assertThat(parameters.get("param2"), is("ABCD2")); assertThat(parameters.get("param3"), is("ABC=DEF")); assertThat(parameters.get("param4"), is("A B = % *")); }