Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<V> extends HashMap<String, V> {
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<? extends String, ? extends V> m) {
Objects.requireNonNull(m);
for (final Map.Entry<? extends String, ? extends V> 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<? super String, ? extends V> mappingFunction) {
final String normalized = normalizeKey(key);
return super.computeIfAbsent(normalized, mappingFunction);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import jakarta.annotation.Nonnull;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
Expand All @@ -23,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<String, ParseNodeFactory> contentTypeAssociatedFactories = new HashMap<>();
@Nonnull public final Map<String, ParseNodeFactory> contentTypeAssociatedFactories =
new CaseInsensitiveMap<>();

@Nonnull public String getValidContentType() {
throw new UnsupportedOperationException(
Expand All @@ -45,18 +46,21 @@ 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().toLowerCase(Locale.ROOT);
if (vendorSpecificContentType.isEmpty()) {
throw new ClientException(
"Content type " + contentType + " does not have a factory to be parsed");
}
ParseNodeFactory factory = contentTypeAssociatedFactories.get(vendorSpecificContentType);
if (factory != null) {
return factory.getParseNode(vendorSpecificContentType, rawResponse);
}
final String cleanedContentType =
contentTypeVendorCleanupPattern.matcher(vendorSpecificContentType).replaceAll("");
if (contentTypeAssociatedFactories.containsKey(cleanedContentType)) {
return contentTypeAssociatedFactories
.get(cleanedContentType)
.getParseNode(cleanedContentType, 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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import com.microsoft.kiota.store.BackingStoreSerializationWriterProxyFactory;

import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;

import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;

Expand All @@ -23,7 +23,7 @@ public SerializationWriterFactoryRegistry() {

/** List of factories that are registered by content type. */
@Nonnull public final HashMap<String, SerializationWriterFactory> contentTypeAssociatedFactories =
new HashMap<>();
new CaseInsensitiveMap<>();

@Nonnull public String getValidContentType() {
throw new UnsupportedOperationException(
Expand Down Expand Up @@ -52,53 +52,41 @@ public SerializationWriterFactoryRegistry() {
if (contentType.isEmpty()) {
throw new NullPointerException("contentType cannot be empty");
}
String cleanedContentType = getVendorSpecificContentType(contentType);
SerializationWriterFactory factory = getSerializationWriterFactory(cleanedContentType);
String cleanedContentType =
getVendorSpecificContentType(contentType).toLowerCase(Locale.ROOT);
if (cleanedContentType.isEmpty()) {
throw new ClientException(
"Content type " + contentType + " does not have a factory to be serialized");
}
SerializationWriterFactory factory = contentTypeAssociatedFactories.get(cleanedContentType);
String resolvedContentType = cleanedContentType;
if (factory == null) {
cleanedContentType = getCleanedVendorSpecificContentType(cleanedContentType);
factory =
getSerializationWriterFactory(
getCleanedVendorSpecificContentType(cleanedContentType));
factory = contentTypeAssociatedFactories.get(cleanedContentType);
if (factory == null) {
throw new ClientException(
"Content type "
+ contentType
+ " does not have a factory to be serialized");
}
resolvedContentType = cleanedContentType;
}
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
* @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
*/
@Nullable private SerializationWriterFactory getSerializationWriterFactory(
@Nonnull final String contentType) {
if (contentTypeAssociatedFactories.containsKey(contentType)) {
return contentTypeAssociatedFactories.get(contentType);
}
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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
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;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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;
Expand Down Expand Up @@ -77,4 +86,149 @@ 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));
}

@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));
}

@Test
void caseInsensitiveMapNormalizesKeysOnAddingAndLookup() {
var map = new CaseInsensitiveMap<String>();
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"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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);
Expand Down
Loading