Search in sources :

Example 1 with SerializationException

use of org.terasology.persistence.typeHandling.SerializationException in project Terasology by MovingBlocks.

the class EventSerializer method serialize.

/**
 * Serializes an event.
 *
 * @param event
 * @return The serialized event
 * @throws org.terasology.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 = typeSerializationLibrary.getSerializerFor(eventMetadata);
    ByteString.Output fieldIds = ByteString.newOutput();
    for (ReplicatedFieldMetadata field : eventMetadata.getFields()) {
        if (field.isReplicated()) {
            EntityData.Value serializedValue = ((ProtobufPersistedData) eventSerializer.serialize(field, event, serializationContext)).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.persistence.typeHandling.protobuf.ProtobufPersistedData) ByteString(com.google.protobuf.ByteString) EntityData(org.terasology.protobuf.EntityData) Event(org.terasology.entitySystem.event.Event) ReplicatedFieldMetadata(org.terasology.entitySystem.metadata.ReplicatedFieldMetadata) Serializer(org.terasology.persistence.typeHandling.Serializer)

Aggregations

ByteString (com.google.protobuf.ByteString)1 Event (org.terasology.entitySystem.event.Event)1 ReplicatedFieldMetadata (org.terasology.entitySystem.metadata.ReplicatedFieldMetadata)1 SerializationException (org.terasology.persistence.typeHandling.SerializationException)1 Serializer (org.terasology.persistence.typeHandling.Serializer)1 ProtobufPersistedData (org.terasology.persistence.typeHandling.protobuf.ProtobufPersistedData)1 EntityData (org.terasology.protobuf.EntityData)1