From a62274a8f64f6af8a31d8a7d722046e96f7a5461 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:05:53 +0530 Subject: [PATCH 1/9] fix(serialization): support content-type parameters and case-insensitivity in JsonParseNodeFactory Signed-off-by: Hardik Kaurani --- .../com/microsoft/kiota/serialization/JsonParseNodeFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonParseNodeFactory.java b/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonParseNodeFactory.java index 65a8d4876..02f34b9be 100644 --- a/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonParseNodeFactory.java +++ b/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonParseNodeFactory.java @@ -44,7 +44,7 @@ public JsonParseNodeFactory(@Nonnull Gson gson) { Objects.requireNonNull(rawResponse, "parameter rawResponse cannot be null"); if (contentType.isEmpty()) { throw new NullPointerException("contentType cannot be empty"); - } else if (!contentType.equals(validContentType)) { + } else if (!contentType.split(";", 2)[0].trim().equalsIgnoreCase(validContentType)) { throw new IllegalArgumentException("expected a " + validContentType + " content type"); } try (final InputStreamReader reader = From cab6b2de0bffaf214005bd28da5e1a844649e3f7 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:06:10 +0530 Subject: [PATCH 2/9] fix(serialization): support content-type parameters and case-insensitivity in JsonSerializationWriterFactory Signed-off-by: Hardik Kaurani --- .../kiota/serialization/JsonSerializationWriterFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactory.java b/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactory.java index f6420a1c0..626c15b99 100644 --- a/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactory.java +++ b/components/serialization/json/src/main/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactory.java @@ -20,7 +20,7 @@ public JsonSerializationWriterFactory() { * @param gson the {@link Gson} instance to use for writing value types. */ public JsonSerializationWriterFactory(@Nonnull Gson gson) { - Objects.requireNonNull(gson, "gson contentType cannot be null"); + Objects.requireNonNull(gson, "parameter gson cannot be null"); this.gson = gson; } @@ -37,7 +37,7 @@ public JsonSerializationWriterFactory(@Nonnull Gson gson) { Objects.requireNonNull(contentType, "parameter contentType cannot be null"); if (contentType.isEmpty()) { throw new NullPointerException("contentType cannot be empty"); - } else if (!contentType.equals(validContentType)) { + } else if (!contentType.split(";", 2)[0].trim().equalsIgnoreCase(validContentType)) { throw new IllegalArgumentException("expected a " + validContentType + " content type"); } return new JsonSerializationWriter(gson); From ca91ad0cb58998ac22ac347710989fdba72d44f4 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:06:32 +0530 Subject: [PATCH 3/9] fix(abstractions): normalize content-type casing, whitespace, and empty delimiters in ParseNodeFactoryRegistry Signed-off-by: Hardik Kaurani --- .../ParseNodeFactoryRegistry.java | 48 +++++++++++++++---- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java index 84f1b3d71..c34e17fba 100644 --- a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java +++ b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java @@ -3,9 +3,12 @@ import com.microsoft.kiota.ClientException; import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; import java.io.InputStream; +import java.util.AbstractMap; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; @@ -45,20 +48,47 @@ public ParseNodeFactoryRegistry() { if (contentType.isEmpty()) { throw new NullPointerException("contentType cannot be empty"); } - final String vendorSpecificContentType = contentType.split(";")[0]; - if (contentTypeAssociatedFactories.containsKey(vendorSpecificContentType)) { - return contentTypeAssociatedFactories - .get(vendorSpecificContentType) - .getParseNode(vendorSpecificContentType, rawResponse); + final String vendorSpecificContentType = contentType.split(";", 2)[0].trim(); + if (vendorSpecificContentType.isEmpty()) { + throw new ClientException( + "Content type " + contentType + " does not have a factory to be parsed"); + } + final Map.Entry vendorEntry = + getParseNodeFactoryEntry(vendorSpecificContentType); + if (vendorEntry != null) { + return vendorEntry.getValue().getParseNode(vendorEntry.getKey(), rawResponse); } final String cleanedContentType = contentTypeVendorCleanupPattern.matcher(vendorSpecificContentType).replaceAll(""); - if (contentTypeAssociatedFactories.containsKey(cleanedContentType)) { - return contentTypeAssociatedFactories - .get(cleanedContentType) - .getParseNode(cleanedContentType, rawResponse); + final Map.Entry cleanedEntry = + getParseNodeFactoryEntry(cleanedContentType); + if (cleanedEntry != null) { + return cleanedEntry.getValue().getParseNode(cleanedEntry.getKey(), rawResponse); } throw new ClientException( "Content type " + cleanedContentType + " does not have a factory to be parsed"); } + + @Nullable private Map.Entry getParseNodeFactoryEntry( + @Nonnull final String contentType) { + final ParseNodeFactory exactMatch = contentTypeAssociatedFactories.get(contentType); + if (exactMatch != null) { + return new AbstractMap.SimpleImmutableEntry<>(contentType, exactMatch); + } + final String lowerCaseContentType = contentType.toLowerCase(Locale.ROOT); + final ParseNodeFactory lowerMatch = + contentTypeAssociatedFactories.get(lowerCaseContentType); + if (lowerMatch != null) { + return new AbstractMap.SimpleImmutableEntry<>(lowerCaseContentType, lowerMatch); + } + for (final Map.Entry entry : + contentTypeAssociatedFactories.entrySet()) { + final String key = entry.getKey(); + final ParseNodeFactory factory = entry.getValue(); + if (key != null && factory != null && key.equalsIgnoreCase(contentType)) { + return entry; + } + } + return null; + } } From 858baccc2a7128305ddbe909898e814f61f00cec Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:06:58 +0530 Subject: [PATCH 4/9] fix(abstractions): normalize content-type casing, whitespace, and redundant cleanup in SerializationWriterFactoryRegistry Signed-off-by: Hardik Kaurani --- .../SerializationWriterFactoryRegistry.java | 58 +++++++++++++------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java index af7cb3a97..44059416f 100644 --- a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java +++ b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java @@ -6,7 +6,10 @@ import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import java.util.AbstractMap; import java.util.HashMap; +import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; @@ -53,52 +56,69 @@ public SerializationWriterFactoryRegistry() { throw new NullPointerException("contentType cannot be empty"); } String cleanedContentType = getVendorSpecificContentType(contentType); - SerializationWriterFactory factory = getSerializationWriterFactory(cleanedContentType); - if (factory == null) { + if (cleanedContentType.isEmpty()) { + throw new ClientException( + "Content type " + contentType + " does not have a factory to be serialized"); + } + Map.Entry entry = + getSerializationWriterFactoryEntry(cleanedContentType); + if (entry == null) { cleanedContentType = getCleanedVendorSpecificContentType(cleanedContentType); - factory = - getSerializationWriterFactory( - getCleanedVendorSpecificContentType(cleanedContentType)); - if (factory == null) { + entry = getSerializationWriterFactoryEntry(cleanedContentType); + if (entry == null) { throw new ClientException( "Content type " + contentType + " does not have a factory to be serialized"); } } + final String resolvedContentType = entry.getKey(); + final SerializationWriterFactory factory = entry.getValue(); if (!serializeOnlyChangedValues) { if (factory instanceof BackingStoreSerializationWriterProxyFactory) { return ((BackingStoreSerializationWriterProxyFactory) factory) - .getSerializationWriter(cleanedContentType, serializeOnlyChangedValues); + .getSerializationWriter(resolvedContentType, serializeOnlyChangedValues); } } - return factory.getSerializationWriter(cleanedContentType); + return factory.getSerializationWriter(resolvedContentType); } /** - * Gets a SerializationWriterFactory that is mapped to a cleaned content type string + * Gets a SerializationWriterFactory entry that is mapped to a cleaned content type string * @param contentType wrapper object carrying initial content type and result of parsing it - * @return the serialization writer factory or null if no mapped factory is found + * @return the serialization writer factory entry or null if no mapped factory is found */ - @Nullable private SerializationWriterFactory getSerializationWriterFactory( + @Nullable private Map.Entry getSerializationWriterFactoryEntry( @Nonnull final String contentType) { - if (contentTypeAssociatedFactories.containsKey(contentType)) { - return contentTypeAssociatedFactories.get(contentType); + final SerializationWriterFactory exactMatch = + contentTypeAssociatedFactories.get(contentType); + if (exactMatch != null) { + return new AbstractMap.SimpleImmutableEntry<>(contentType, exactMatch); + } + final String lowerCaseContentType = contentType.toLowerCase(Locale.ROOT); + final SerializationWriterFactory lowerMatch = + contentTypeAssociatedFactories.get(lowerCaseContentType); + if (lowerMatch != null) { + return new AbstractMap.SimpleImmutableEntry<>(lowerCaseContentType, lowerMatch); + } + for (final Map.Entry entry : + contentTypeAssociatedFactories.entrySet()) { + final String key = entry.getKey(); + final SerializationWriterFactory factory = entry.getValue(); + if (key != null && factory != null && key.equalsIgnoreCase(contentType)) { + return entry; + } } return null; } /** - * Splits content type by ; and returns first segment or original contentType + * Splits content type by ; and returns trimmed media type segment * @param contentType * @return vendor specific content type */ @Nonnull private String getVendorSpecificContentType(@Nonnull final String contentType) { - String[] split = contentType.split(";"); - if (split.length >= 1) { - return split[0]; - } - return contentType; + return contentType.split(";", 2)[0].trim(); } /** From fce1f453221a7cf2fddde569ec89ff5b48227a54 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:07:43 +0530 Subject: [PATCH 5/9] test(serialization): add content-type parameter and case-insensitivity tests for JsonParseNodeFactory Signed-off-by: Hardik Kaurani --- .../JsonParseNodeFactoryTests.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonParseNodeFactoryTests.java diff --git a/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonParseNodeFactoryTests.java b/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonParseNodeFactoryTests.java new file mode 100644 index 000000000..ccc1f5fe4 --- /dev/null +++ b/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonParseNodeFactoryTests.java @@ -0,0 +1,95 @@ +package com.microsoft.kiota.serialization; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; + +class JsonParseNodeFactoryTests { + private static final JsonParseNodeFactory _parseNodeFactory = new JsonParseNodeFactory(); + private static final String contentType = "application/json"; + + private static T nullValue() { + return Collections.emptyMap().get("missing"); + } + + @Test + void getsParseNodeForJsonContentType() { + final var rawResponse = + new ByteArrayInputStream("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8)); + final var parseNode = _parseNodeFactory.getParseNode(contentType, rawResponse); + assertNotNull(parseNode); + final var child = parseNode.getChildNode("key"); + assertNotNull(child); + assertEquals("value", child.getStringValue()); + } + + @Test + void throwsIllegalArgumentExceptionForInvalidContentType() { + final var rawResponse = + new ByteArrayInputStream("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8)); + assertThrows( + IllegalArgumentException.class, + () -> _parseNodeFactory.getParseNode("text/plain", rawResponse)); + } + + @Test + void throwsNullPointerExceptionForEmptyOrNullArguments() { + final var rawResponse = + new ByteArrayInputStream("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8)); + assertThrows( + NullPointerException.class, () -> _parseNodeFactory.getParseNode("", rawResponse)); + assertThrows( + NullPointerException.class, + () -> _parseNodeFactory.getParseNode(nullValue(), rawResponse)); + assertThrows( + NullPointerException.class, + () -> _parseNodeFactory.getParseNode(contentType, nullValue())); + assertThrows(NullPointerException.class, () -> new JsonParseNodeFactory(nullValue())); + } + + @ParameterizedTest + @ValueSource( + strings = { + "application/json; charset=utf-8", + "application/json; charset=UTF-8", + "application/json ; charset=utf-8", + "application/json; odata.metadata=minimal", + "APPLICATION/JSON", + "APPLICATION/JSON; CHARSET=UTF-8", + "Application/Json", + " application/json ; charset=utf-8", + }) + void getsParseNodeForContentTypeWithParametersOrCaseVariants(final String inputType) { + final var rawResponse = + new ByteArrayInputStream("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8)); + final var parseNode = _parseNodeFactory.getParseNode(inputType, rawResponse); + assertNotNull(parseNode); + final var child = parseNode.getChildNode("key"); + assertNotNull(child); + assertEquals("value", child.getStringValue()); + } + + @ParameterizedTest + @ValueSource( + strings = { + ";", + ";;", + "; charset=utf-8", + " ; charset=utf-8", + }) + void throwsIllegalArgumentExceptionForDelimiterOnlyOrMissingMediaType(final String inputType) { + final var rawResponse = + new ByteArrayInputStream("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8)); + assertThrows( + IllegalArgumentException.class, + () -> _parseNodeFactory.getParseNode(inputType, rawResponse)); + } +} From 0ce5588c218cce9a941e36f7f004ac730dc9520c Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:07:58 +0530 Subject: [PATCH 6/9] test(serialization): add content-type parameter and case-insensitivity tests for JsonSerializationWriterFactory Signed-off-by: Hardik Kaurani --- .../JsonSerializationWriterFactoryTests.java | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactoryTests.java diff --git a/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactoryTests.java b/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactoryTests.java new file mode 100644 index 000000000..7db3bbdd3 --- /dev/null +++ b/components/serialization/json/src/test/java/com/microsoft/kiota/serialization/JsonSerializationWriterFactoryTests.java @@ -0,0 +1,102 @@ +package com.microsoft.kiota.serialization; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.microsoft.kiota.Compatibility; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.charset.StandardCharsets; +import java.util.Collections; + +class JsonSerializationWriterFactoryTests { + private static final JsonSerializationWriterFactory _serializationWriterFactory = + new JsonSerializationWriterFactory(); + private static final String contentType = "application/json"; + + private static T nullValue() { + return Collections.emptyMap().get("missing"); + } + + @Test + void getsWriterForJsonContentType() throws Exception { + try (final var serializationWriter = + _serializationWriterFactory.getSerializationWriter(contentType)) { + assertNotNull(serializationWriter); + serializationWriter.writeStringValue(null, "ok"); + assertEquals( + "\"ok\"", + new String( + Compatibility.readAllBytes(serializationWriter.getSerializedContent()), + StandardCharsets.UTF_8)); + } + } + + @Test + void throwsIllegalArgumentExceptionForInvalidContentType() { + assertThrows( + IllegalArgumentException.class, + () -> _serializationWriterFactory.getSerializationWriter("text/plain")); + } + + @Test + void throwsNullPointerExceptionForEmptyOrNullArguments() { + assertThrows( + NullPointerException.class, + () -> _serializationWriterFactory.getSerializationWriter("")); + assertThrows( + NullPointerException.class, + () -> _serializationWriterFactory.getSerializationWriter(nullValue())); + final var gsonError = + assertThrows( + NullPointerException.class, + () -> new JsonSerializationWriterFactory(nullValue())); + assertTrue(gsonError.getMessage().contains("parameter gson cannot be null")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "application/json; charset=utf-8", + "application/json; charset=UTF-8", + "application/json ; charset=utf-8", + "application/json; odata.metadata=minimal", + "APPLICATION/JSON", + "APPLICATION/JSON; CHARSET=UTF-8", + "Application/Json", + " application/json ; charset=utf-8", + }) + void getsWriterForContentTypeWithParametersOrCaseVariants(final String inputType) + throws Exception { + try (final var serializationWriter = + _serializationWriterFactory.getSerializationWriter(inputType)) { + assertNotNull(serializationWriter); + assertEquals(contentType, _serializationWriterFactory.getValidContentType()); + serializationWriter.writeStringValue(null, "ok"); + assertEquals( + "\"ok\"", + new String( + Compatibility.readAllBytes(serializationWriter.getSerializedContent()), + StandardCharsets.UTF_8)); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + ";", + ";;", + "; charset=utf-8", + " ; charset=utf-8", + }) + void throwsIllegalArgumentExceptionForDelimiterOnlyOrMissingMediaType(final String inputType) { + assertThrows( + IllegalArgumentException.class, + () -> _serializationWriterFactory.getSerializationWriter(inputType)); + } +} From 6515158546d0c4c30b81e91d5a03849e4045bcc0 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:08:23 +0530 Subject: [PATCH 7/9] test(abstractions): add content-type normalization and delimiter edge-case tests for ParseNodeFactoryRegistry Signed-off-by: Hardik Kaurani --- .../FactoryRegistryExceptionTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java index bd00b5ec4..ceb571965 100644 --- a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java +++ b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java @@ -1,7 +1,13 @@ package com.microsoft.kiota.serialization; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.microsoft.kiota.ClientException; import com.microsoft.kiota.Compatibility; @@ -77,4 +83,52 @@ void registeredVendorContentTypesStillWork() throws Exception { StandardCharsets.UTF_8)); } } + + @ParameterizedTest + @ValueSource( + strings = { + "APPLICATION/JSON", + "Application/Json; charset=utf-8", + "application/json ; charset=utf-8", + " application/json ; charset=utf-8", + "Application/Vnd.Example+JSON ; charset=utf-8", + }) + void parseNodeRegistryResolvesCaseInsensitiveAndWhitespacePaddedContentTypes( + final String inputContentType) { + var parser = new ParseNodeFactoryRegistry(); + parser.contentTypeAssociatedFactories.put("application/json", new JsonParseNodeFactory()); + var response = new ByteArrayInputStream("42".getBytes(StandardCharsets.UTF_8)); + assertEquals(42, parser.getParseNode(inputContentType, response).getIntegerValue()); + } + + @Test + void parseNodeRegistryMatchesMixedCaseRegisteredFactoryKey() { + var parser = new ParseNodeFactoryRegistry(); + var customFactory = mock(ParseNodeFactory.class); + var mockNode = mock(ParseNode.class); + when(customFactory.getParseNode(eq("Application/Custom"), any())).thenReturn(mockNode); + parser.contentTypeAssociatedFactories.put("Application/Custom", customFactory); + + var response = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); + var result = parser.getParseNode("application/custom ; version=1", response); + assertNotNull(result); + verify(customFactory).getParseNode(eq("Application/Custom"), eq(response)); + } + + @ParameterizedTest + @ValueSource( + strings = { + ";", + ";;", + "; charset=utf-8", + " ", + " ; charset=utf-8", + }) + void parseNodeRegistryThrowsClientExceptionForDelimiterOnlyOrBlankContentTypes( + final String inputContentType) { + var parser = new ParseNodeFactoryRegistry(); + parser.contentTypeAssociatedFactories.put("application/json", new JsonParseNodeFactory()); + var response = new ByteArrayInputStream("42".getBytes(StandardCharsets.UTF_8)); + assertThrows(ClientException.class, () -> parser.getParseNode(inputContentType, response)); + } } From 5d75a3d2ebde613781e3cc7cf4bc3370d2147bb5 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Wed, 18 Nov 2026 17:08:41 +0530 Subject: [PATCH 8/9] test(abstractions): add content-type normalization and case-insensitivity tests for SerializationWriterFactoryRegistry Signed-off-by: Hardik Kaurani --- .../FactoryRegistryExceptionTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java index ceb571965..4fccc170a 100644 --- a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java +++ b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java @@ -11,6 +11,7 @@ import com.microsoft.kiota.ClientException; import com.microsoft.kiota.Compatibility; +import com.microsoft.kiota.store.BackingStoreSerializationWriterProxyFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -131,4 +132,75 @@ void parseNodeRegistryThrowsClientExceptionForDelimiterOnlyOrBlankContentTypes( var response = new ByteArrayInputStream("42".getBytes(StandardCharsets.UTF_8)); assertThrows(ClientException.class, () -> parser.getParseNode(inputContentType, response)); } + + @ParameterizedTest + @ValueSource( + strings = { + "APPLICATION/JSON", + "Application/Json; charset=utf-8", + "application/json ; charset=utf-8", + " application/json ; charset=utf-8", + "Application/Vnd.Example+JSON ; charset=utf-8", + }) + void serializationWriterRegistryResolvesCaseInsensitiveAndWhitespacePaddedContentTypes( + final String inputContentType) throws Exception { + var writers = new SerializationWriterFactoryRegistry(); + writers.contentTypeAssociatedFactories.put( + "application/json", new JsonSerializationWriterFactory()); + try (var writer = writers.getSerializationWriter(inputContentType)) { + writer.writeIntegerValue(null, 42); + assertEquals( + "42", + new String( + Compatibility.readAllBytes(writer.getSerializedContent()), + StandardCharsets.UTF_8)); + } + } + + @Test + void serializationWriterRegistryMatchesMixedCaseKeyAndBackingStoreBypass() throws Exception { + var writers = new SerializationWriterFactoryRegistry(); + var customFactory = mock(SerializationWriterFactory.class); + var mockWriter = mock(SerializationWriter.class); + when(customFactory.getSerializationWriter("Application/Custom")).thenReturn(mockWriter); + writers.contentTypeAssociatedFactories.put("Application/Custom", customFactory); + + var result = writers.getSerializationWriter("application/custom ; version=1"); + assertNotNull(result); + verify(customFactory).getSerializationWriter("Application/Custom"); + + var backingStoreRegistry = new SerializationWriterFactoryRegistry(); + backingStoreRegistry.contentTypeAssociatedFactories.put( + "application/json", + new BackingStoreSerializationWriterProxyFactory( + new JsonSerializationWriterFactory())); + try (var writer = + backingStoreRegistry.getSerializationWriter( + "APPLICATION/JSON ; charset=utf-8", false)) { + assertNotNull(writer); + writer.writeIntegerValue(null, 7); + assertEquals( + "7", + new String( + Compatibility.readAllBytes(writer.getSerializedContent()), + StandardCharsets.UTF_8)); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + ";", + ";;", + "; charset=utf-8", + " ", + " ; charset=utf-8", + }) + void serializationWriterRegistryThrowsClientExceptionForDelimiterOnlyOrBlankContentTypes( + final String inputContentType) { + var writers = new SerializationWriterFactoryRegistry(); + writers.contentTypeAssociatedFactories.put( + "application/json", new JsonSerializationWriterFactory()); + assertThrows(ClientException.class, () -> writers.getSerializationWriter(inputContentType)); + } } From 14966428cf694bce5517264212bebae1e52e7736 Mon Sep 17 00:00:00 2001 From: Hardik Kaurani Date: Fri, 20 Nov 2026 21:09:45 +0530 Subject: [PATCH 9/9] fix(abstractions): normalize registry content-type keys upon adding for O(1) lookups Signed-off-by: Hardik Kaurani --- .../serialization/CaseInsensitiveMap.java | 64 +++++++++++++++++++ .../ParseNodeFactoryRegistry.java | 46 +++---------- .../SerializationWriterFactoryRegistry.java | 50 +++------------ .../FactoryRegistryExceptionTest.java | 36 +++++++++-- 4 files changed, 115 insertions(+), 81 deletions(-) create mode 100644 components/abstractions/src/main/java/com/microsoft/kiota/serialization/CaseInsensitiveMap.java diff --git a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/CaseInsensitiveMap.java b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/CaseInsensitiveMap.java new file mode 100644 index 000000000..e34f4e28f --- /dev/null +++ b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/CaseInsensitiveMap.java @@ -0,0 +1,64 @@ +package com.microsoft.kiota.serialization; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +class CaseInsensitiveMap extends HashMap { + private static final long serialVersionUID = 1L; + + private static String normalizeKey(final String key) { + if (key == null) { + return null; + } + return key.split(";", 2)[0].trim().toLowerCase(Locale.ROOT); + } + + @Override + public V put(final String key, final V value) { + return super.put(normalizeKey(key), value); + } + + @Override + public void putAll(final Map m) { + Objects.requireNonNull(m); + for (final Map.Entry entry : m.entrySet()) { + put(entry.getKey(), entry.getValue()); + } + } + + @Override + public V get(final Object key) { + return super.get(key instanceof String ? normalizeKey((String) key) : key); + } + + @Override + public boolean containsKey(final Object key) { + return super.containsKey(key instanceof String ? normalizeKey((String) key) : key); + } + + @Override + public V remove(final Object key) { + return super.remove(key instanceof String ? normalizeKey((String) key) : key); + } + + @Override + public V getOrDefault(final Object key, final V defaultValue) { + return super.getOrDefault( + key instanceof String ? normalizeKey((String) key) : key, defaultValue); + } + + @Override + public V putIfAbsent(final String key, final V value) { + return super.putIfAbsent(normalizeKey(key), value); + } + + @Override + public V computeIfAbsent( + final String key, final Function mappingFunction) { + final String normalized = normalizeKey(key); + return super.computeIfAbsent(normalized, mappingFunction); + } +} diff --git a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java index c34e17fba..24243c713 100644 --- a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java +++ b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/ParseNodeFactoryRegistry.java @@ -3,11 +3,8 @@ import com.microsoft.kiota.ClientException; import jakarta.annotation.Nonnull; -import jakarta.annotation.Nullable; import java.io.InputStream; -import java.util.AbstractMap; -import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Objects; @@ -26,7 +23,8 @@ public ParseNodeFactoryRegistry() { public static final ParseNodeFactoryRegistry defaultInstance = new ParseNodeFactoryRegistry(); /** List of factories that are registered by content type. */ - @Nonnull public final Map contentTypeAssociatedFactories = new HashMap<>(); + @Nonnull public final Map contentTypeAssociatedFactories = + new CaseInsensitiveMap<>(); @Nonnull public String getValidContentType() { throw new UnsupportedOperationException( @@ -48,47 +46,23 @@ public ParseNodeFactoryRegistry() { if (contentType.isEmpty()) { throw new NullPointerException("contentType cannot be empty"); } - final String vendorSpecificContentType = contentType.split(";", 2)[0].trim(); + final String vendorSpecificContentType = + contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT); if (vendorSpecificContentType.isEmpty()) { throw new ClientException( "Content type " + contentType + " does not have a factory to be parsed"); } - final Map.Entry vendorEntry = - getParseNodeFactoryEntry(vendorSpecificContentType); - if (vendorEntry != null) { - return vendorEntry.getValue().getParseNode(vendorEntry.getKey(), rawResponse); + ParseNodeFactory factory = contentTypeAssociatedFactories.get(vendorSpecificContentType); + if (factory != null) { + return factory.getParseNode(vendorSpecificContentType, rawResponse); } final String cleanedContentType = contentTypeVendorCleanupPattern.matcher(vendorSpecificContentType).replaceAll(""); - final Map.Entry cleanedEntry = - getParseNodeFactoryEntry(cleanedContentType); - if (cleanedEntry != null) { - return cleanedEntry.getValue().getParseNode(cleanedEntry.getKey(), rawResponse); + factory = contentTypeAssociatedFactories.get(cleanedContentType); + if (factory != null) { + return factory.getParseNode(cleanedContentType, rawResponse); } throw new ClientException( "Content type " + cleanedContentType + " does not have a factory to be parsed"); } - - @Nullable private Map.Entry getParseNodeFactoryEntry( - @Nonnull final String contentType) { - final ParseNodeFactory exactMatch = contentTypeAssociatedFactories.get(contentType); - if (exactMatch != null) { - return new AbstractMap.SimpleImmutableEntry<>(contentType, exactMatch); - } - final String lowerCaseContentType = contentType.toLowerCase(Locale.ROOT); - final ParseNodeFactory lowerMatch = - contentTypeAssociatedFactories.get(lowerCaseContentType); - if (lowerMatch != null) { - return new AbstractMap.SimpleImmutableEntry<>(lowerCaseContentType, lowerMatch); - } - for (final Map.Entry entry : - contentTypeAssociatedFactories.entrySet()) { - final String key = entry.getKey(); - final ParseNodeFactory factory = entry.getValue(); - if (key != null && factory != null && key.equalsIgnoreCase(contentType)) { - return entry; - } - } - return null; - } } diff --git a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java index 44059416f..6e2ee334a 100644 --- a/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java +++ b/components/abstractions/src/main/java/com/microsoft/kiota/serialization/SerializationWriterFactoryRegistry.java @@ -4,12 +4,9 @@ import com.microsoft.kiota.store.BackingStoreSerializationWriterProxyFactory; import jakarta.annotation.Nonnull; -import jakarta.annotation.Nullable; -import java.util.AbstractMap; import java.util.HashMap; import java.util.Locale; -import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; @@ -26,7 +23,7 @@ public SerializationWriterFactoryRegistry() { /** List of factories that are registered by content type. */ @Nonnull public final HashMap contentTypeAssociatedFactories = - new HashMap<>(); + new CaseInsensitiveMap<>(); @Nonnull public String getValidContentType() { throw new UnsupportedOperationException( @@ -55,25 +52,25 @@ public SerializationWriterFactoryRegistry() { if (contentType.isEmpty()) { throw new NullPointerException("contentType cannot be empty"); } - String cleanedContentType = getVendorSpecificContentType(contentType); + String cleanedContentType = + getVendorSpecificContentType(contentType).toLowerCase(Locale.ROOT); if (cleanedContentType.isEmpty()) { throw new ClientException( "Content type " + contentType + " does not have a factory to be serialized"); } - Map.Entry entry = - getSerializationWriterFactoryEntry(cleanedContentType); - if (entry == null) { + SerializationWriterFactory factory = contentTypeAssociatedFactories.get(cleanedContentType); + String resolvedContentType = cleanedContentType; + if (factory == null) { cleanedContentType = getCleanedVendorSpecificContentType(cleanedContentType); - entry = getSerializationWriterFactoryEntry(cleanedContentType); - if (entry == null) { + factory = contentTypeAssociatedFactories.get(cleanedContentType); + if (factory == null) { throw new ClientException( "Content type " + contentType + " does not have a factory to be serialized"); } + resolvedContentType = cleanedContentType; } - final String resolvedContentType = entry.getKey(); - final SerializationWriterFactory factory = entry.getValue(); if (!serializeOnlyChangedValues) { if (factory instanceof BackingStoreSerializationWriterProxyFactory) { return ((BackingStoreSerializationWriterProxyFactory) factory) @@ -83,35 +80,6 @@ public SerializationWriterFactoryRegistry() { return factory.getSerializationWriter(resolvedContentType); } - /** - * Gets a SerializationWriterFactory entry that is mapped to a cleaned content type string - * @param contentType wrapper object carrying initial content type and result of parsing it - * @return the serialization writer factory entry or null if no mapped factory is found - */ - @Nullable private Map.Entry getSerializationWriterFactoryEntry( - @Nonnull final String contentType) { - final SerializationWriterFactory exactMatch = - contentTypeAssociatedFactories.get(contentType); - if (exactMatch != null) { - return new AbstractMap.SimpleImmutableEntry<>(contentType, exactMatch); - } - final String lowerCaseContentType = contentType.toLowerCase(Locale.ROOT); - final SerializationWriterFactory lowerMatch = - contentTypeAssociatedFactories.get(lowerCaseContentType); - if (lowerMatch != null) { - return new AbstractMap.SimpleImmutableEntry<>(lowerCaseContentType, lowerMatch); - } - for (final Map.Entry entry : - contentTypeAssociatedFactories.entrySet()) { - final String key = entry.getKey(); - final SerializationWriterFactory factory = entry.getValue(); - if (key != null && factory != null && key.equalsIgnoreCase(contentType)) { - return entry; - } - } - return null; - } - /** * Splits content type by ; and returns trimmed media type segment * @param contentType diff --git a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java index 4fccc170a..7429f38b9 100644 --- a/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java +++ b/components/abstractions/src/test/java/com/microsoft/kiota/serialization/FactoryRegistryExceptionTest.java @@ -1,8 +1,10 @@ package com.microsoft.kiota.serialization; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -107,13 +109,13 @@ void parseNodeRegistryMatchesMixedCaseRegisteredFactoryKey() { var parser = new ParseNodeFactoryRegistry(); var customFactory = mock(ParseNodeFactory.class); var mockNode = mock(ParseNode.class); - when(customFactory.getParseNode(eq("Application/Custom"), any())).thenReturn(mockNode); + when(customFactory.getParseNode(eq("application/custom"), any())).thenReturn(mockNode); parser.contentTypeAssociatedFactories.put("Application/Custom", customFactory); var response = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); var result = parser.getParseNode("application/custom ; version=1", response); assertNotNull(result); - verify(customFactory).getParseNode(eq("Application/Custom"), eq(response)); + verify(customFactory).getParseNode(eq("application/custom"), eq(response)); } @ParameterizedTest @@ -162,12 +164,12 @@ void serializationWriterRegistryMatchesMixedCaseKeyAndBackingStoreBypass() throw var writers = new SerializationWriterFactoryRegistry(); var customFactory = mock(SerializationWriterFactory.class); var mockWriter = mock(SerializationWriter.class); - when(customFactory.getSerializationWriter("Application/Custom")).thenReturn(mockWriter); + when(customFactory.getSerializationWriter("application/custom")).thenReturn(mockWriter); writers.contentTypeAssociatedFactories.put("Application/Custom", customFactory); var result = writers.getSerializationWriter("application/custom ; version=1"); assertNotNull(result); - verify(customFactory).getSerializationWriter("Application/Custom"); + verify(customFactory).getSerializationWriter("application/custom"); var backingStoreRegistry = new SerializationWriterFactoryRegistry(); backingStoreRegistry.contentTypeAssociatedFactories.put( @@ -203,4 +205,30 @@ void serializationWriterRegistryThrowsClientExceptionForDelimiterOnlyOrBlankCont "application/json", new JsonSerializationWriterFactory()); assertThrows(ClientException.class, () -> writers.getSerializationWriter(inputContentType)); } + + @Test + void caseInsensitiveMapNormalizesKeysOnAddingAndLookup() { + var map = new CaseInsensitiveMap(); + map.put("APPLICATION/JSON", "json"); + map.put("Text/Plain ; Charset=UTF-8", "text"); + + assertTrue(map.containsKey("application/json")); + assertTrue(map.containsKey("APPLICATION/JSON")); + assertEquals("json", map.get("application/json")); + assertEquals("json", map.get("Application/Json")); + assertEquals("json", map.get("APPLICATION/JSON ; charset=utf-8")); + + assertTrue(map.containsKey("text/plain")); + assertEquals("text", map.get("TEXT/PLAIN")); + + map.putAll(java.util.Collections.singletonMap("IMAGE/PNG", "png")); + assertTrue(map.containsKey("image/png")); + assertEquals("png", map.get("IMAGE/PNG")); + + assertEquals("default", map.getOrDefault("UNKNOWN/TYPE", "default")); + map.putIfAbsent("APPLICATION/XML", "xml"); + assertTrue(map.containsKey("application/xml")); + assertEquals("xml", map.remove("Application/XML")); + assertFalse(map.containsKey("application/xml")); + } }