Search in sources :

Example 6 with PersistedDataSerializer

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)));
}
Also used : PersistedString(org.terasology.persistence.typeHandling.inMemory.PersistedString) PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) ArgumentMatcher(org.mockito.ArgumentMatcher) AbstractPersistedData(org.terasology.persistence.typeHandling.inMemory.AbstractPersistedData) PersistedData(org.terasology.persistence.typeHandling.PersistedData) PersistedString(org.terasology.persistence.typeHandling.inMemory.PersistedString) Test(org.junit.jupiter.api.Test)

Example 7 with PersistedDataSerializer

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);
}
Also used : PersistedDataMap(org.terasology.persistence.typeHandling.PersistedDataMap) Logger(org.slf4j.Logger) ReflectionUtil(org.terasology.reflection.ReflectionUtil) LoggerFactory(org.slf4j.LoggerFactory) TypeInfo(org.terasology.reflection.TypeInfo) Set(java.util.Set) PersistedData(org.terasology.persistence.typeHandling.PersistedData) Maps(com.google.common.collect.Maps) TypeHandler(org.terasology.persistence.typeHandling.TypeHandler) PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) TypeHandlerLibrary(org.terasology.persistence.typeHandling.TypeHandlerLibrary) Type(java.lang.reflect.Type) TypeHandlerContext(org.terasology.persistence.typeHandling.TypeHandlerContext) Map(java.util.Map) Optional(java.util.Optional) SerializationSandbox(org.terasology.persistence.typeHandling.reflection.SerializationSandbox) Type(java.lang.reflect.Type) PersistedData(org.terasology.persistence.typeHandling.PersistedData) TypeHandler(org.terasology.persistence.typeHandling.TypeHandler) PersistedDataMap(org.terasology.persistence.typeHandling.PersistedDataMap) Map(java.util.Map)

Example 8 with PersistedDataSerializer

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();
}
Also used : SerializationException(org.terasology.persistence.typeHandling.SerializationException) ProtobufPersistedData(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedData) ByteString(com.google.protobuf.ByteString) EntityData(org.terasology.protobuf.EntityData) Event(org.terasology.engine.entitySystem.event.Event) ReplicatedFieldMetadata(org.terasology.engine.entitySystem.metadata.ReplicatedFieldMetadata) Serializer(org.terasology.persistence.typeHandling.Serializer) PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) ProtobufPersistedDataSerializer(org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedDataSerializer)

Example 9 with PersistedDataSerializer

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();
        }
    }));
}
Also used : PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) ArgumentMatcher(org.mockito.ArgumentMatcher) PersistedData(org.terasology.persistence.typeHandling.PersistedData) Collection(java.util.Collection) Queue(java.util.Queue) Test(org.junit.jupiter.api.Test)

Example 10 with PersistedDataSerializer

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());
}
Also used : InMemoryPersistedDataSerializer(org.terasology.persistence.typeHandling.inMemory.InMemoryPersistedDataSerializer) PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) InMemoryPersistedDataSerializer(org.terasology.persistence.typeHandling.inMemory.InMemoryPersistedDataSerializer) PersistedData(org.terasology.persistence.typeHandling.PersistedData) Test(org.junit.jupiter.api.Test)

Aggregations

PersistedDataSerializer (org.terasology.persistence.typeHandling.PersistedDataSerializer)10 Test (org.junit.jupiter.api.Test)8 PersistedData (org.terasology.persistence.typeHandling.PersistedData)8 ArgumentMatcher (org.mockito.ArgumentMatcher)4 Collection (java.util.Collection)2 AbstractPersistedData (org.terasology.persistence.typeHandling.inMemory.AbstractPersistedData)2 PersistedString (org.terasology.persistence.typeHandling.inMemory.PersistedString)2 Maps (com.google.common.collect.Maps)1 ByteString (com.google.protobuf.ByteString)1 Type (java.lang.reflect.Type)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Queue (java.util.Queue)1 Set (java.util.Set)1 Logger (org.slf4j.Logger)1 LoggerFactory (org.slf4j.LoggerFactory)1 Event (org.terasology.engine.entitySystem.event.Event)1 ReplicatedFieldMetadata (org.terasology.engine.entitySystem.metadata.ReplicatedFieldMetadata)1 ProtobufPersistedData (org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedData)1 ProtobufPersistedDataSerializer (org.terasology.engine.persistence.typeHandling.protobuf.ProtobufPersistedDataSerializer)1