MediaTypeUtil { public static List<String> getSortedAcceptableMediaTypes(List<String> accept) { List<Item> result = new ArrayList<>(accept.size() + 1); for (String acceptItem : accept) { String[] subItems = acceptItem.split(","); for (String subItem : subItems) { String[] itemPlusParams = subItem.split(";"); String item = itemPlusParams[0].trim(); if (item.isEmpty()) continue; float weight = 1.0f; for (int i = 1; i < itemPlusParams.length; i++) { String[] param = itemPlusParams[i].split("=", 2); String paramName = param[0].trim(); if (param.length == 2 && paramName.equalsIgnoreCase("q")) { try { weight = Float.parseFloat(param[1].trim()); } catch (NumberFormatException e) { } break; } } result.add(new Item(item, weight)); } } return result.stream().sorted().map(i -> i.value).collect(Collectors.toList()); }  static List<String> getSortedAcceptableMediaTypes(List<String> accept);  }
@SuppressWarnings("unchecked") @Test public void canSplitupAcceptHeadersIntoPreferredMediaTypes() { List[] examples = new List[]{ emptyList(), emptyList(), singletonList(""), emptyList(), singletonList("**"), asList("xml", "json"), asList("xml", "json"), singletonList("json; q=0.4, xml"), asList("xml", "json"), singletonList("json; q=0.4, xml; q=0.5"), asList("xml", "json"), singletonList("json; q=0.8, xml; q=0.1"), asList("json", "xml"), singletonList("json; q=0.4;x=1, xml;a=20;q=0.5"), asList("xml", "json"), singletonList("json; q=0.8, xml; q=0.1"), asList("json", "xml"), asList("text/plain; q=0.5, text/html", "text/x-dvi; q=0.8, text/x-c"), asList("text/html", "text/x-c", "text/x-dvi", "text/plain"), }; for (int i = 0; i < examples.length; i += 2) { List<String> accept = examples[i]; List<String> expectedSortedAccepts = examples[i + 1]; List<String> result = MediaTypeUtil.getSortedAcceptableMediaTypes(accept); assertEquals("Example index: " + (i / 2), expectedSortedAccepts, result); } }