Skip to content

Commit

Permalink
Skip media type parsing for known string values (#16358)
Browse files Browse the repository at this point in the history
Signed-off-by: Andrew Ross <[email protected]>
(cherry picked from commit e360ceb)
Signed-off-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
github-actions[bot] committed Oct 17, 2024
1 parent 9c2d17f commit 0e495c5
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 0e495c5

Please sign in to comment.