Search in sources :

Example 1 with DataTypeSerializer

use of org.lanternpowered.server.data.persistence.DataTypeSerializer in project LanternServer by LanternPowered.

the class MemoryDataView method setCollection.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCollection(String key, Collection<?> value) {
    final ImmutableList.Builder<Object> builder = ImmutableList.builder();
    final LanternDataManager manager = getDataManager();
    for (Object object : value) {
        if (object instanceof DataSerializable) {
            builder.add(((DataSerializable) object).toContainer());
        } else if (object instanceof DataView) {
            if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
                final MemoryDataView view = new MemoryDataContainer(this.safety);
                final DataView internalView = (DataView) object;
                for (Map.Entry<DataQuery, Object> entry : internalView.getValues(false).entrySet()) {
                    view.set(entry.getKey(), entry.getValue());
                }
                builder.add(view);
            } else {
                builder.add(object);
            }
        } else if (object instanceof CatalogType) {
            builder.add(((CatalogType) object).getId());
        } else if (object instanceof Map) {
            builder.add(ensureSerialization((Map) object));
        } else if (object instanceof Collection) {
            builder.add(ensureSerialization((Collection) object));
        } else {
            final TypeToken<?> typeToken = TypeToken.of(object.getClass());
            final DataTypeSerializer serializer = manager == null ? null : manager.getTypeSerializer(typeToken).orElse(null);
            if (serializer != null) {
                final Object result = serializer.serialize(typeToken, manager.getTypeSerializerContext(), object);
                checkArgument(!result.equals(this), "Cannot insert self-referencing Objects!");
                builder.add(result);
            } else {
                builder.add(object);
            }
        }
    }
    this.map.put(key, builder.build());
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) DataSerializable(org.spongepowered.api.data.DataSerializable) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) Collection(java.util.Collection) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 2 with DataTypeSerializer

use of org.lanternpowered.server.data.persistence.DataTypeSerializer in project LanternServer by LanternPowered.

the class MemoryDataView method set.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
    checkNotNull(path, "path");
    checkNotNull(value, "value");
    final LanternDataManager manager = getDataManager();
    final List<String> parts = path.getParts();
    final String key = parts.get(0);
    if (parts.size() > 1) {
        final DataQuery subQuery = of(key);
        final Optional<DataView> subViewOptional = getUnsafeView(subQuery);
        final DataView subView;
        if (!subViewOptional.isPresent()) {
            createView(subQuery);
            subView = (DataView) this.map.get(key);
        } else {
            subView = subViewOptional.get();
        }
        subView.set(path.popFirst(), value);
        return this;
    }
    Optional<DataTypeSerializer> optDataTypeSerializer;
    TypeToken typeToken;
    if (value instanceof DataView) {
        checkArgument(value != this, "Cannot set a DataView to itself.");
        // always have to copy a data view to avoid overwriting existing
        // views and to set the interior path correctly.
        copyDataView(path, (DataView) value);
    } else if (value instanceof DataSerializable) {
        final DataContainer valueContainer = ((DataSerializable) value).toContainer();
        checkArgument(!(valueContainer).equals(this), "Cannot insert self-referencing DataSerializable");
        // see above for why this is copied
        copyDataView(path, valueContainer);
    } else if (value instanceof CatalogType) {
        return set(path, ((CatalogType) value).getId());
    } else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Float || value instanceof Double || value instanceof Long || value instanceof String || value instanceof Character || value instanceof Boolean) {
        this.map.put(key, value);
        return this;
    } else if (manager != null && (optDataTypeSerializer = manager.getTypeSerializer(typeToken = TypeToken.of(value.getClass()))).isPresent()) {
        final DataTypeSerializer serializer = optDataTypeSerializer.get();
        final Object serialized = serializer.serialize(typeToken, manager.getTypeSerializerContext(), value);
        if (serialized instanceof DataContainer) {
            final DataContainer container = (DataContainer) serialized;
            checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
            // see above for why this is copied
            copyDataView(path, container);
        } else {
            this.map.put(key, serialized);
        }
    } else if (value instanceof Collection) {
        setCollection(key, (Collection) value);
    } else if (value instanceof Map) {
        setMap(key, (Map) value);
    } else if (value.getClass().isArray()) {
        if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
            if (value instanceof byte[]) {
                this.map.put(key, ArrayUtils.clone((byte[]) value));
            } else if (value instanceof short[]) {
                this.map.put(key, ArrayUtils.clone((short[]) value));
            } else if (value instanceof int[]) {
                this.map.put(key, ArrayUtils.clone((int[]) value));
            } else if (value instanceof long[]) {
                this.map.put(key, ArrayUtils.clone((long[]) value));
            } else if (value instanceof float[]) {
                this.map.put(key, ArrayUtils.clone((float[]) value));
            } else if (value instanceof double[]) {
                this.map.put(key, ArrayUtils.clone((double[]) value));
            } else if (value instanceof boolean[]) {
                this.map.put(key, ArrayUtils.clone((boolean[]) value));
            } else {
                this.map.put(key, ArrayUtils.clone((Object[]) value));
            }
        } else {
            this.map.put(key, value);
        }
    } else {
        this.map.put(key, value);
    }
    return this;
}
Also used : DataSerializable(org.spongepowered.api.data.DataSerializable) DataContainer(org.spongepowered.api.data.DataContainer) DataQuery(org.spongepowered.api.data.DataQuery) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) TypeToken(com.google.common.reflect.TypeToken) Collection(java.util.Collection) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 3 with DataTypeSerializer

use of org.lanternpowered.server.data.persistence.DataTypeSerializer in project LanternServer by LanternPowered.

the class CompositeValueContainerStore method deserialize.

@SuppressWarnings("unchecked")
@Override
public void deserialize(T object, DataView dataView) {
    if (object instanceof IValueContainer) {
        final IValueContainer<S> valueContainer = (IValueContainer<S>) object;
        final SimpleValueContainer simpleValueContainer = new SimpleValueContainer(new HashMap<>());
        deserializeValues(object, simpleValueContainer, dataView);
        final Optional<DataView> optDataView = dataView.getView(VALUES);
        if (optDataView.isPresent()) {
            final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
            final DataView valuesView = optDataView.get();
            for (Map.Entry<DataQuery, Object> entry : valuesView.getValues(false).entrySet()) {
                final Key key = KeyRegistryModule.get().getById(entry.getKey().toString()).orElse(null);
                if (key == null) {
                    Lantern.getLogger().warn("Unable to deserialize the data value with key: {} because it doesn't exist.", entry.getKey().toString());
                } else {
                    final TypeToken<?> typeToken = key.getElementToken();
                    final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
                    if (dataTypeSerializer == null) {
                        Lantern.getLogger().warn("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId());
                    } else {
                        if (simpleValueContainer.get(key).isPresent()) {
                            Lantern.getLogger().warn("Duplicate usage of the key: {}", key.getId());
                        } else {
                            simpleValueContainer.set(key, dataTypeSerializer.deserialize(typeToken, context, entry.getValue()));
                        }
                    }
                }
            }
        }
        for (Map.Entry<Key<?>, Object> entry : simpleValueContainer.getValues().entrySet()) {
            final Element element = (Element) valueContainer.getValueCollection().getElement((Key) entry.getKey()).orElse(null);
            if (element != null) {
                element.set(entry.getValue());
            } else {
                Lantern.getLogger().warn("Attempted to offer a unsupported value with key \"{}\" to the object {}", entry.getKey().toString(), object.toString());
            }
        }
        dataView.getView(DataQueries.SPONGE_DATA).ifPresent(view -> DataHelper.deserializeRawContainerData(dataView, valueContainer, DataQueries.CUSTOM_MANIPULATORS));
    } else {
    // Not sure what to do
    }
}
Also used : IValueContainer(org.lanternpowered.server.data.IValueContainer) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) SimpleValueContainer(org.lanternpowered.server.data.io.store.SimpleValueContainer) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) HashMap(java.util.HashMap) Map(java.util.Map) Key(org.spongepowered.api.data.key.Key)

Example 4 with DataTypeSerializer

use of org.lanternpowered.server.data.persistence.DataTypeSerializer in project LanternServer by LanternPowered.

the class CompositeValueContainerStore method serialize.

@SuppressWarnings("unchecked")
@Override
public void serialize(T object, DataView dataView) {
    if (object instanceof IValueContainer) {
        final IValueContainer<S> valueContainer = (IValueContainer<S>) object;
        final SimpleValueContainer simpleValueContainer = new SimpleValueContainer(new HashMap<>());
        for (KeyRegistration<?, ?> registration : valueContainer.getValueCollection().getAll()) {
            if (!(registration instanceof Element)) {
                continue;
            }
            final Key key = registration.getKey();
            final Object element = ((Element) registration).get();
            if (element != null) {
                simpleValueContainer.set(key, element);
            }
        }
        // Serialize the values, all written values will be removed from
        // the simple value container
        serializeValues(object, simpleValueContainer, dataView);
        // Write the rest to the Values tag
        final Map<Key<?>, Object> values = simpleValueContainer.getValues();
        if (!values.isEmpty()) {
            final DataView valuesView = dataView.createView(VALUES);
            final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
            for (Map.Entry<Key<?>, Object> entry : values.entrySet()) {
                final TypeToken<?> typeToken = entry.getKey().getElementToken();
                final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
                if (dataTypeSerializer == null) {
                    Lantern.getLogger().warn("Unable to serialize the data key value: " + entry.getKey());
                } else {
                    valuesView.set(DataQuery.of(entry.getKey().getId()), dataTypeSerializer.serialize(typeToken, context, entry.getValue()));
                }
            }
            if (valuesView.isEmpty()) {
                dataView.remove(VALUES);
            }
        }
        DataHelper.serializeRawContainerData(getOrCreateView(dataView, DataQueries.SPONGE_DATA), valueContainer, DataQueries.CUSTOM_MANIPULATORS);
    } else {
    // Not sure what to do
    }
}
Also used : IValueContainer(org.lanternpowered.server.data.IValueContainer) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) SimpleValueContainer(org.lanternpowered.server.data.io.store.SimpleValueContainer) DataView(org.spongepowered.api.data.DataView) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) HashMap(java.util.HashMap) Map(java.util.Map) Key(org.spongepowered.api.data.key.Key)

Example 5 with DataTypeSerializer

use of org.lanternpowered.server.data.persistence.DataTypeSerializer in project LanternServer by LanternPowered.

the class MemoryDataView method getObjectList.

@SuppressWarnings("unchecked")
@Override
public <T> Optional<List<T>> getObjectList(DataQuery path, Class<T> objectClass) {
    return getList(path).flatMap(list -> {
        final TypeToken<T> typeToken = TypeToken.of(objectClass);
        final LanternDataManager dataManager = Lantern.getGame().getDataManager();
        final DataTypeSerializer serializer = dataManager.getTypeSerializer(typeToken).orElse(null);
        if (serializer == null) {
            return Optional.empty();
        }
        return (Optional) Optional.of(list.stream().map(object -> serializer.deserialize(typeToken, dataManager.getTypeSerializerContext(), object)).collect(Collectors.toList()));
    });
}
Also used : Arrays(java.util.Arrays) ArrayUtils(org.apache.commons.lang3.ArrayUtils) TypeToken(com.google.common.reflect.TypeToken) DataQuery(org.spongepowered.api.data.DataQuery) Supplier(java.util.function.Supplier) Key(org.spongepowered.api.data.key.Key) ArrayList(java.util.ArrayList) DataSerializable(org.spongepowered.api.data.DataSerializable) LinkedHashMap(java.util.LinkedHashMap) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Lists(com.google.common.collect.Lists) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Objects(com.google.common.base.Objects) Nullable(javax.annotation.Nullable) ImmutableSet(com.google.common.collect.ImmutableSet) DataQuery.of(org.spongepowered.api.data.DataQuery.of) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) BaseValue(org.spongepowered.api.data.value.BaseValue) MoreObjects(com.google.common.base.MoreObjects) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Stream(java.util.stream.Stream) DataView(org.spongepowered.api.data.DataView) Lantern(org.lanternpowered.server.game.Lantern) Coerce(org.spongepowered.api.util.Coerce) Optional(java.util.Optional) Optional(java.util.Optional) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer)

Aggregations

DataTypeSerializer (org.lanternpowered.server.data.persistence.DataTypeSerializer)9 Map (java.util.Map)7 DataView (org.spongepowered.api.data.DataView)7 DataTypeSerializerContext (org.lanternpowered.server.data.persistence.DataTypeSerializerContext)6 DataQuery (org.spongepowered.api.data.DataQuery)6 Element (org.lanternpowered.server.data.element.Element)5 Key (org.spongepowered.api.data.key.Key)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Collection (java.util.Collection)3 LinkedHashMap (java.util.LinkedHashMap)3 CatalogType (org.spongepowered.api.CatalogType)3 DataContainer (org.spongepowered.api.data.DataContainer)3 ImmutableList (com.google.common.collect.ImmutableList)2 TypeToken (com.google.common.reflect.TypeToken)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 IValueContainer (org.lanternpowered.server.data.IValueContainer)2 SimpleValueContainer (org.lanternpowered.server.data.io.store.SimpleValueContainer)2 DataSerializable (org.spongepowered.api.data.DataSerializable)2 MoreObjects (com.google.common.base.MoreObjects)1