use of org.terasology.persistence.typeHandling.PersistedDataSerializer in project Terasology by MovingBlocks.
the class RuntimeDelegatingTypeHandlerTest method testSerializeSub.
@Test
void testSerializeSub() {
PersistedDataSerializer serializer = mock(PersistedDataSerializer.class);
when(serializer.serialize(any(String.class))).then(invocation -> new PersistedString((String) invocation.getArguments()[0]));
Base sub = new Sub();
runtimeDelegatingTypeHandler.serialize(sub, serializer);
verify(subTypeHandler).serialize(any(), any());
verify(serializer).serialize(argThat((ArgumentMatcher<Map<String, PersistedData>>) argument -> argument.get(RuntimeDelegatingTypeHandler.TYPE_FIELD).getAsString().equals(subType.getName()) && argument.containsKey(RuntimeDelegatingTypeHandler.VALUE_FIELD)));
}
use of org.terasology.persistence.typeHandling.PersistedDataSerializer in project Terasology by MovingBlocks.
the class RuntimeDelegatingTypeHandler method serializeNonNull.
@SuppressWarnings("unchecked")
@Override
public PersistedData serializeNonNull(T value, PersistedDataSerializer serializer) {
// If primitive, don't go looking for the runtime type, serialize as is
if (typeInfo.getRawType().isPrimitive() || Number.class.isAssignableFrom(typeInfo.getRawType())) {
if (delegateHandler != null) {
return delegateHandler.serialize(value, serializer);
}
LOGGER.error("Primitive '{}' does not have a TypeHandler", typeInfo);
return serializer.serializeNull();
}
TypeHandler<T> chosenHandler = delegateHandler;
Type runtimeType = getRuntimeTypeIfMoreSpecific(value);
if (!typeInfo.getType().equals(runtimeType)) {
Optional<TypeHandler<?>> runtimeTypeHandler = typeHandlerLibrary.getTypeHandler(runtimeType);
chosenHandler = (TypeHandler<T>) runtimeTypeHandler.map(typeHandler -> {
if (delegateHandler == null) {
return typeHandler;
}
if (!(typeHandler instanceof ObjectFieldMapTypeHandler) && typeHandler.getClass().equals(delegateHandler.getClass())) {
// use delegateHandler which might have more info
return delegateHandler;
}
if (!isDefaultTypeHandler(typeHandler)) {
// Custom handler for runtime type
return typeHandler;
}
if (!isDefaultTypeHandler(delegateHandler)) {
// Custom handler for specified type
return delegateHandler;
}
return typeHandler;
}).orElse(delegateHandler);
}
if (chosenHandler == null) {
LOGGER.warn("Could not find appropriate TypeHandler for runtime type '{}', " + "serializing as base type '{}'", runtimeType, typeInfo);
return serializeViaDelegate(value, serializer);
}
if (chosenHandler == delegateHandler) {
return serializeViaDelegate(value, serializer);
}
Map<String, PersistedData> typeValuePersistedDataMap = Maps.newLinkedHashMap();
Class<? extends T> subType = (Class<? extends T>) ReflectionUtil.getRawType(runtimeType);
String subTypeIdentifier = sandbox.getSubTypeIdentifier(subType, typeInfo.getRawType());
typeValuePersistedDataMap.put(TYPE_FIELD, serializer.serialize(subTypeIdentifier));
PersistedData serialized = chosenHandler.serialize(value, serializer);
// If the serialized representation is a Map, flatten it to include the class variable
if (serialized.isValueMap()) {
for (Map.Entry<String, PersistedData> entry : serialized.getAsValueMap().entrySet()) {
typeValuePersistedDataMap.put(entry.getKey(), entry.getValue());
}
} else {
typeValuePersistedDataMap.put(VALUE_FIELD, serialized);
}
return serializer.serialize(typeValuePersistedDataMap);
}
use of org.terasology.persistence.typeHandling.PersistedDataSerializer in project Terasology by MovingBlocks.
the class EventSerializer method serialize.
/**
* Serializes an event.
*
* @param event
* @return The serialized event
* @throws org.terasology.engine.persistence.typeHandling.SerializationException if an error occurs during serialization
*/
public EntityData.Event serialize(Event event) {
EventMetadata<?> eventMetadata = eventLibrary.getMetadata(event.getClass());
if (eventMetadata == null) {
throw new SerializationException("Unregistered event type: " + event.getClass());
} else if (!eventMetadata.isConstructable()) {
throw new SerializationException("Cannot serialize event '" + eventMetadata + "' - lacks default constructor so cannot be deserialized");
}
EntityData.Event.Builder eventData = EntityData.Event.newBuilder();
serializeEventType(event, eventData);
Serializer eventSerializer = typeHandlerLibrary.getSerializerFor(eventMetadata);
ByteString.Output fieldIds = ByteString.newOutput();
for (ReplicatedFieldMetadata field : eventMetadata.getFields()) {
if (field.isReplicated()) {
EntityData.Value serializedValue = ((ProtobufPersistedData) eventSerializer.serialize(field, event, persistedDataSerializer)).getValue();
if (serializedValue != null) {
eventData.addFieldValue(serializedValue);
fieldIds.write(field.getId());
}
}
}
eventData.setFieldIds(fieldIds.toByteString());
return eventData.build();
}
use of org.terasology.persistence.typeHandling.PersistedDataSerializer in project Terasology by MovingBlocks.
the class CollectionTypeHandlerTest method testSerialize.
@Test
void testSerialize() {
IntTypeHandler elementTypeHandler = mock(IntTypeHandler.class);
CollectionCopyConstructor<Queue<Integer>, Integer> constructor = Queues::newArrayDeque;
CollectionTypeHandler<Integer> typeHandler = new CollectionTypeHandler<>(elementTypeHandler, constructor);
Collection<Integer> collection = constructor.construct(Lists.newArrayList());
collection.addAll(Collections.nCopies(500, -1));
PersistedDataSerializer context = mock(PersistedDataSerializer.class);
typeHandler.serialize(collection, context);
verify(elementTypeHandler, times(collection.size())).serialize(any(), any());
verify(context).serialize(argThat(new ArgumentMatcher<Iterable<PersistedData>>() {
@Override
public boolean matches(Iterable<PersistedData> argument) {
return argument instanceof Collection && ((Collection) argument).size() == collection.size();
}
}));
}
use of org.terasology.persistence.typeHandling.PersistedDataSerializer in project Terasology by MovingBlocks.
the class CharacterTypeHandlerTest method testSerialize.
@Test
void testSerialize() {
PersistedDataSerializer serializer = new InMemoryPersistedDataSerializer();
char linefeedChar = '\n';
PersistedData data = typeHandler.serializeNonNull(linefeedChar, serializer);
Assertions.assertEquals("\n", data.getAsString());
}
Aggregations