public MediaType withoutParameters() { if (params.isEmpty()) return this; return new MediaType(type, subType); }
public MediaType withParameters(Map<String, String> parameters) { return parameters.isEmpty() ? this : new MediaType(this.type, this.subType, parameters); }
public MediaType withParameter(String name, String value) { Map<String, String> newParams = new HashMap<>(params); newParams.put(name, value); return new MediaType(type, subType, newParams); }
public static MediaType parse(String str) { if (str == null || str.isEmpty()) throw log.missingMediaType(); int separatorIdx = str.indexOf(';'); boolean emptyParams = separatorIdx == -1; String types = emptyParams ? str : str.substring(0, separatorIdx); String params = emptyParams ? "" : str.substring(separatorIdx + 1); Map<String, String> paramMap = parseParams(params); // "*" is not a valid MediaType according to the https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, // but we'll ignore for now to play nice with java.net.HttpURLConnection. // More details on https://bugs.openjdk.java.net/browse/JDK-8163921 if (types.trim().equals("*")) { return emptyParams ? MediaType.MATCH_ALL : new MediaType("*", "*", paramMap); } if (types.indexOf('/') == -1) { throw log.invalidMediaTypeSubtype(); } String[] typeSubtype = types.split("/"); return new MediaType(typeSubtype[0].trim(), typeSubtype[1].trim(), paramMap); }
@Override @SuppressWarnings("unchecked") public MediaType readObject(ObjectInput input) throws IOException, ClassNotFoundException { boolean isInternal = input.readBoolean(); if (isInternal) { short id = input.readShort(); Map<String, String> params = (Map<String, String>) input.readObject(); return MediaTypeIds.getMediaType(id).withParameters(params); } else { String type = input.readUTF(); String subType = input.readUTF(); Map<String, String> params = (Map<String, String>) input.readObject(); return new MediaType(type, subType, params); } } }
@Test public void testToString() { assertEquals("application/xml", new MediaType("application", "xml", createMap(new MapEntry("q", "0.9"))).toString()); assertEquals("text/csv", new MediaType("text", "csv").toString()); assertEquals("foo/bar; a=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"))).toString()); assertEquals("foo/bar; a=2; b=1; c=2", new MediaType("foo", "bar", createMap(new MapEntry("a", "2"), new MapEntry("b", "1"), new MapEntry("c", "2"))).toString()); assertEquals("a/b; p=1", MediaType.fromString("a/b; p=1; q=2;").toStringExcludingParam("q")); }