|
42 | 42 | * @opensearch.internal |
43 | 43 | */ |
44 | 44 | public final class MediaTypeParserRegistry { |
45 | | - private static Map<String, MediaType> formatToMediaType; |
46 | | - private static Map<String, MediaType> typeWithSubtypeToMediaType; |
| 45 | + private static Map<String, MediaType> formatToMediaType = new HashMap<>(); |
| 46 | + private static Map<String, MediaType> typeWithSubtypeToMediaType = new HashMap<>(); |
47 | 47 |
|
48 | 48 | // Default mediaType singleton |
49 | 49 | private static MediaType DEFAULT_MEDIA_TYPE; |
50 | 50 |
|
51 | 51 | public static void register(MediaType[] acceptedMediaTypes, Map<String, MediaType> additionalMediaTypes) { |
52 | | - final int size = acceptedMediaTypes.length + additionalMediaTypes.size(); |
53 | | - Map<String, MediaType> typeMap = new HashMap<>(size); |
54 | | - Map<String, MediaType> formatMap = new HashMap<>(size); |
| 52 | + // ensures the map is not overwritten: |
| 53 | + Map<String, MediaType> typeMap = new HashMap<>(typeWithSubtypeToMediaType); |
| 54 | + Map<String, MediaType> formatMap = new HashMap<>(formatToMediaType); |
55 | 55 | for (MediaType mediaType : acceptedMediaTypes) { |
| 56 | + if (formatMap.containsKey(mediaType.format())) { |
| 57 | + throw new IllegalArgumentException("unable to register mediaType: [" + mediaType.format() + "]. Type already exists."); |
| 58 | + } |
56 | 59 | typeMap.put(mediaType.typeWithSubtype(), mediaType); |
57 | 60 | formatMap.put(mediaType.format(), mediaType); |
58 | 61 | } |
59 | 62 | for (Map.Entry<String, MediaType> entry : additionalMediaTypes.entrySet()) { |
60 | | - String typeWithSubtype = entry.getKey(); |
61 | | - MediaType mediaType = entry.getValue(); |
| 63 | + String typeWithSubtype = entry.getKey().toLowerCase(Locale.ROOT); |
| 64 | + if (typeMap.containsKey(typeWithSubtype)) { |
| 65 | + throw new IllegalArgumentException( |
| 66 | + "unable to register mediaType: [" |
| 67 | + + entry.getKey() |
| 68 | + + "]. " |
| 69 | + + "Type already exists and is mapped to: [." |
| 70 | + + entry.getValue().format() |
| 71 | + + "]" |
| 72 | + ); |
| 73 | + } |
62 | 74 |
|
63 | | - typeMap.put(typeWithSubtype.toLowerCase(Locale.ROOT), mediaType); |
64 | | - formatMap.put(mediaType.format(), mediaType); |
| 75 | + MediaType mediaType = entry.getValue(); |
| 76 | + typeMap.put(typeWithSubtype, mediaType); |
| 77 | + formatMap.putIfAbsent(mediaType.format(), mediaType); // ignore if the additional type mapping already exists |
65 | 78 | } |
66 | 79 |
|
67 | 80 | formatToMediaType = Map.copyOf(formatMap); |
|
0 commit comments