Skip to content

Commit

Permalink
Skip media type parsing for known string values (opensearch-project#1…
Browse files Browse the repository at this point in the history
…6358)

Signed-off-by: Andrew Ross <andrross@amazon.com>
  • Loading branch information
andrross authored and dk2k committed Oct 21, 2024
1 parent fbefe51 commit 48528af
Showing 1 changed file with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
public final class MediaTypeRegistry {
private static Map<String, MediaType> formatToMediaType = Map.of();
private static Map<String, MediaType> typeWithSubtypeToMediaType = Map.of();
private static Map<String, MediaType> knownStringsToMediaType = Map.of();

// Default mediaType singleton
private static MediaType DEFAULT_MEDIA_TYPE;
Expand Down Expand Up @@ -84,6 +85,8 @@ private static void register(MediaType[] acceptedMediaTypes, Map<String, MediaTy
// ensures the map is not overwritten:
Map<String, MediaType> typeMap = new HashMap<>(typeWithSubtypeToMediaType);
Map<String, MediaType> formatMap = new HashMap<>(formatToMediaType);
Map<String, MediaType> knownStringMap = new HashMap<>(knownStringsToMediaType);

for (MediaType mediaType : acceptedMediaTypes) {
if (formatMap.containsKey(mediaType.format())) {
throw new IllegalArgumentException("unable to register mediaType: [" + mediaType.format() + "]. Type already exists.");
Expand All @@ -107,13 +110,24 @@ private static void register(MediaType[] acceptedMediaTypes, Map<String, MediaTy
MediaType mediaType = entry.getValue();
typeMap.put(typeWithSubtype, mediaType);
formatMap.putIfAbsent(mediaType.format(), mediaType); // ignore if the additional type mapping already exists
knownStringMap.put(mediaType.mediaType(), mediaType);
knownStringMap.put(mediaType.mediaTypeWithoutParameters(), mediaType);
}

formatToMediaType = Map.copyOf(formatMap);
typeWithSubtypeToMediaType = Map.copyOf(typeMap);
knownStringsToMediaType = Map.copyOf(knownStringMap);
}

public static MediaType fromMediaType(String mediaType) {
if (mediaType == null) {
return null;
}
// Skip parsing if the string is an exact match for any known string value
final MediaType knownMediaType = knownStringsToMediaType.get(mediaType);
if (knownMediaType != null) {
return knownMediaType;
}
ParsedMediaType parsedMediaType = parseMediaType(mediaType);
return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
}
Expand Down

0 comments on commit 48528af

Please sign in to comment.