Skip to content

Commit

Permalink
fix: do not crash on unexpected map format in GenericMapTypeHandler (#…
Browse files Browse the repository at this point in the history
…5062)

Co-authored-by: Tobias Nett <skaldarnar@googlemail.com>
  • Loading branch information
jdrueckert and skaldarnar authored Aug 22, 2022
1 parent ceff6a9 commit f3f9d92
Show file tree
Hide file tree
Showing 2 changed files with 175 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

package org.terasology.persistence.typeHandling.coreTypes;

import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
Expand Down Expand Up @@ -61,28 +62,53 @@ private PersistedData serializeEntry(Map.Entry<K, V> entry, PersistedDataSeriali

@Override
public Optional<Map<K, V>> deserialize(PersistedData data) {
if (!data.isArray()) {
if (!data.isArray() || data.isValueMap()) {
logger.warn("Incorrect map format detected: object instead of array.\n" + getUsageInfo(data));
return Optional.empty();
}

Map<K, V> result = Maps.newLinkedHashMap();

for (PersistedData entry : data.getAsArray()) {
PersistedDataMap kvEntry = entry.getAsValueMap();
final Optional<K> key = keyHandler.deserialize(kvEntry.get(KEY));

if (key.isPresent()) {
final Optional<V> value = valueHandler.deserialize(kvEntry.get(VALUE));
if (value.isPresent()) {
result.put(key.get(), value.get());
} else {
logger.warn("Missing value for key '{}' with {} given entry '{}'", key.get(), valueHandler, kvEntry.get(VALUE));
}
} else {
logger.warn("Missing field '{}' for entry '{}'", KEY, kvEntry);
PersistedData rawKey = kvEntry.get(KEY);
PersistedData rawValue = kvEntry.get(VALUE);
if (rawKey == null || rawValue == null) {
logger.warn("Incorrect map format detected: missing map entry with \"key\" or \"value\" key.\n" + getUsageInfo(data));
return Optional.empty();
}

final Optional<K> key = keyHandler.deserialize(rawKey);
if (key.isEmpty()) {
logger.warn("Could not deserialize key '{}' as '{}'", rawKey, keyHandler.getClass().getSimpleName());
return Optional.empty();
}

final Optional<V> value = valueHandler.deserialize(kvEntry.get(VALUE));
if (value.isEmpty()) {
logger.warn("Could not deserialize value '{}' as '{}'", rawValue, valueHandler.getClass().getSimpleName());
return Optional.empty();
}

result.put(key.get(), value.get());
}

return Optional.of(result);
}

private String getUsageInfo(PersistedData data) {
return "Expected\n" +
" \"mapName\": [\n" +
" { \"key\": \"...\", \"value\": \"...\" }\n" +
" ]\n" +
"but found \n'{}'" + data + "'";
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("key", keyHandler)
.add("value", valueHandler)
.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

package org.terasology.persistence.typeHandling.coreTypes;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.terasology.persistence.typeHandling.PersistedData;
import org.terasology.persistence.typeHandling.PersistedDataSerializer;
Expand All @@ -12,7 +13,6 @@
import org.terasology.persistence.typeHandling.inMemory.PersistedString;
import org.terasology.persistence.typeHandling.inMemory.arrays.PersistedValueArray;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand All @@ -25,14 +25,102 @@ class GenericMapTypeHandlerTest {
private static final String TEST_KEY = "health:baseRegen";
private static final long TEST_VALUE = -1;

/**
* JSON equivalent:
* <pre><code>
* [
* {
* "key": "health:baseRegen",
* "value": -1
* }
* ]
* </code></pre>
*/
private final PersistedData testData = new PersistedValueArray(List.of(
new PersistedMap(Map.of(
GenericMapTypeHandler.KEY, new PersistedString(TEST_KEY),
GenericMapTypeHandler.VALUE, new PersistedLong(TEST_VALUE)
))
));

/**
* JSON equivalent:
* <pre><code>
* {
* "health:baseRegen": -1
* }
* </code></pre>
*/
private final PersistedData testDataMalformatted = new PersistedValueArray(List.of(
new PersistedMap(Map.of(
TEST_KEY, new PersistedLong(TEST_VALUE)
))
));

/**
* JSON equivalent:
* <pre><code>
* [
* {
* "not key": "health:baseRegen",
* "value": -1
* }
* ]
* </code></pre>
*/
private final PersistedData testDataMissingKeyEntry = new PersistedValueArray(List.of(
new PersistedMap(Map.of(
"not key", new PersistedString(TEST_KEY),
GenericMapTypeHandler.VALUE, new PersistedLong(TEST_VALUE)
))
));

/**
* JSON equivalent:
* <pre><code>
* [
* {
* "key": "health:baseRegen",
* "not value": -1
* }
* ]
* </code></pre>
*/
private final PersistedData testDataMissingValueEntry = new PersistedValueArray(List.of(
new PersistedMap(Map.of(
GenericMapTypeHandler.KEY, new PersistedString(TEST_KEY),
"not value", new PersistedLong(TEST_VALUE)
))
));

/**
* JSON equivalent:
* <pre><code>
* [
* {
* "key": "health:baseRegen",
* "value": -1
* },
* {
* "not key": "health:baseRegen",
* "not value": -1
* },
* ]
* </code></pre>
*/
private final PersistedData testDataValidAndInvalidMix = new PersistedValueArray(List.of(
new PersistedMap(Map.of(
GenericMapTypeHandler.KEY, new PersistedString(TEST_KEY),
GenericMapTypeHandler.VALUE, new PersistedLong(TEST_VALUE)
)),
new PersistedMap(Map.of(
"not key", new PersistedString(TEST_KEY),
"not value", new PersistedLong(TEST_VALUE)
))
));

@Test
@DisplayName("Data with valid formatting can be deserialized successfully.")
void testDeserialize() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
Expand All @@ -44,23 +132,69 @@ void testDeserialize() {
}

@Test
@DisplayName("Deserializing valid data with a mismatching value type handler fails deserialization (returns empty `Optional`)")
void testDeserializeWithMismatchedValueHandler() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
new UselessTypeHandler<>()
);

assertThat(th.deserialize(testData)).hasValue(Collections.emptyMap());
assertThat(th.deserialize(testData)).isEmpty();
}

@Test
@DisplayName("Deserializing valid data with a mismatching key type handler fails deserialization (returns empty `Optional`)")
void testDeserializeWithMismatchedKeyHandler() {
var th = new GenericMapTypeHandler<>(
new UselessTypeHandler<>(),
new LongTypeHandler()
);

assertThat(th.deserialize(testData)).hasValue(Collections.emptyMap());
assertThat(th.deserialize(testData)).isEmpty();
}

@Test
@DisplayName("Incorrectly formatted data (without an outer array) fails deserialization (returns empty `Optional`)")
void testDeserializeWithObjectInsteadOfArray() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
new LongTypeHandler()
);

assertThat(th.deserialize(testDataMalformatted)).isEmpty();
}

@Test
@DisplayName("Incorrectly formatted data (without a map entry with key \"key\") fails deserialization (returns empty `Optional`)")
void testDeserializeWithMissingKeyEntry() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
new LongTypeHandler()
);

assertThat(th.deserialize(testDataMissingKeyEntry)).isEmpty();
}

@Test
@DisplayName("Incorrectly formatted data (without a map entry with key \"value\") fails deserialization (returns empty `Optional`)")
void testDeserializeWithMissingValueEntry() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
new LongTypeHandler()
);

assertThat(th.deserialize(testDataMissingValueEntry)).isEmpty();
}

@Test
@DisplayName("A map containing both, correctly and incorrectly formatted data, fails deserialization (returns empty `Optional`)")
void testDeserializeWithValidAndInvalidEntries() {
var th = new GenericMapTypeHandler<>(
new StringTypeHandler(),
new LongTypeHandler()
);

assertThat(th.deserialize(testDataValidAndInvalidMix)).isEmpty();
}

/** Never returns a value. */
Expand Down

0 comments on commit f3f9d92

Please sign in to comment.