Skip to content

Commit e360ceb

Browse files
authored
Skip media type parsing for known string values (#16358)
Signed-off-by: Andrew Ross <[email protected]>
1 parent dc8a435 commit e360ceb

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
public final class MediaTypeRegistry {
5858
private static Map<String, MediaType> formatToMediaType = Map.of();
5959
private static Map<String, MediaType> typeWithSubtypeToMediaType = Map.of();
60+
private static Map<String, MediaType> knownStringsToMediaType = Map.of();
6061

6162
// Default mediaType singleton
6263
private static MediaType DEFAULT_MEDIA_TYPE;
@@ -84,6 +85,8 @@ private static void register(MediaType[] acceptedMediaTypes, Map<String, MediaTy
8485
// ensures the map is not overwritten:
8586
Map<String, MediaType> typeMap = new HashMap<>(typeWithSubtypeToMediaType);
8687
Map<String, MediaType> formatMap = new HashMap<>(formatToMediaType);
88+
Map<String, MediaType> knownStringMap = new HashMap<>(knownStringsToMediaType);
89+
8790
for (MediaType mediaType : acceptedMediaTypes) {
8891
if (formatMap.containsKey(mediaType.format())) {
8992
throw new IllegalArgumentException("unable to register mediaType: [" + mediaType.format() + "]. Type already exists.");
@@ -107,13 +110,24 @@ private static void register(MediaType[] acceptedMediaTypes, Map<String, MediaTy
107110
MediaType mediaType = entry.getValue();
108111
typeMap.put(typeWithSubtype, mediaType);
109112
formatMap.putIfAbsent(mediaType.format(), mediaType); // ignore if the additional type mapping already exists
113+
knownStringMap.put(mediaType.mediaType(), mediaType);
114+
knownStringMap.put(mediaType.mediaTypeWithoutParameters(), mediaType);
110115
}
111116

112117
formatToMediaType = Map.copyOf(formatMap);
113118
typeWithSubtypeToMediaType = Map.copyOf(typeMap);
119+
knownStringsToMediaType = Map.copyOf(knownStringMap);
114120
}
115121

116122
public static MediaType fromMediaType(String mediaType) {
123+
if (mediaType == null) {
124+
return null;
125+
}
126+
// Skip parsing if the string is an exact match for any known string value
127+
final MediaType knownMediaType = knownStringsToMediaType.get(mediaType);
128+
if (knownMediaType != null) {
129+
return knownMediaType;
130+
}
117131
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
118132
return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
119133
}

0 commit comments

Comments
 (0)