Search in sources :

Example 6 with DataTypeSerializer

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

the class DataHelper method serializeRawRegisteredKeyData.

public static void serializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer, Set<Key> ignoredKeys) {
    DataView view = null;
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || ignoredKeys.contains(key) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Element element = (Element) registration;
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        final Object object = element.get();
        if (object == null) {
            continue;
        }
        final Object value = typeSerializer.serialize(typeToken, context, object);
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        view.set(key.getQuery(), value);
    }
    Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
    if (holder != null) {
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        for (Map.Entry<DataQuery, Object> entry : holder.get().getValues(false).entrySet()) {
            if (!view.contains(entry.getKey())) {
                view.set(entry.getKey(), entry.getValue());
            }
        }
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Map(java.util.Map)

Example 7 with DataTypeSerializer

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

the class DataHelper method deserializeRawRegisteredKeyData.

public static void deserializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer) throws InvalidDataException {
    dataView = dataView.getView(DataQueries.DATA_VALUES).orElse(null);
    if (dataView == null) {
        return;
    }
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Optional<Object> data = dataView.get(key.getQuery());
        if (!data.isPresent()) {
            continue;
        }
        dataView.remove(key.getQuery());
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        ((Element) registration).set(typeSerializer.deserialize(typeToken, context, data.get()));
    }
    if (valueContainer instanceof CompositeValueStore) {
        final CompositeValueStore store = (CompositeValueStore) valueContainer;
        for (Map.Entry<DataQuery, Object> entry : dataView.getValues(false).entrySet()) {
            final Key<?> key = KeyRegistryModule.get().getByQuery(entry.getKey()).orElse(null);
            if (key == null) {
                continue;
            }
            final TypeToken<?> typeToken = key.getElementToken();
            final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
            store.offer(key, typeSerializer.deserialize(typeToken, context, entry.getValue()));
            dataView.remove(entry.getKey());
        }
    }
    if (!dataView.isEmpty()) {
        // Should be safe to cast, at least if nobody touches this key
        Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
        if (holder == null) {
            holder = valueCollection.register(LanternKeys.FAILED_DATA_VALUES, null);
        }
        holder.set(dataView);
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) CompositeValueStore(org.spongepowered.api.data.value.mutable.CompositeValueStore) Map(java.util.Map)

Example 8 with DataTypeSerializer

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

the class DataHelper method toContainer.

public static DataContainer toContainer(IValueContainer valueContainer) {
    final DataContainer dataContainer = DataContainer.createNew();
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        if (!(registration instanceof Element)) {
            continue;
        }
        final Key<?> key = registration.getKey();
        final DataQuery dataQuery = key.getQuery();
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
        // The value's shouldn't be null inside a data manipulator,
        // since it doesn't support removal of values
        dataContainer.set(dataQuery, typeSerializer.serialize(typeToken, context, checkNotNull(((Element) registration).get(), "element")));
    }
    return dataContainer;
}
Also used : DataContainer(org.spongepowered.api.data.DataContainer) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer)

Example 9 with DataTypeSerializer

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

the class CommandSetData method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final ThreadLocal<Key<?>> currentKey = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player")), new PatternMatchingCommandElement(Text.of("key")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(Key.class).stream().map(Key::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<Key> ret = Sponge.getGame().getRegistry().getType(Key.class, choice);
            if (!ret.isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            currentKey.set(ret.get());
            return ret.get();
        }
    }, new CommandElement(Text.of("data")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            args.next();
            final String content = args.getRaw().substring(args.getRawPosition()).trim();
            while (args.hasNext()) {
                args.next();
            }
            final Object data;
            try {
                // Don't be too strict
                data = JsonDataFormat.read(content, true).orElse(null);
            } catch (IOException e) {
                throw args.createError(t("Invalid json data: %s\nError: %s", content, e.getMessage()));
            }
            final Key key = currentKey.get();
            final TypeToken<?> typeToken = key.getElementToken();
            if (content.isEmpty()) {
                return null;
            }
            final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
            if (dataTypeSerializer == null) {
                throw args.createError(Text.of("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId()));
            } else {
                final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
                try {
                    // Put it in a holder object, the command element separates iterable objects
                    return new ValueHolder(dataTypeSerializer.deserialize(typeToken, context, data));
                } catch (InvalidDataException e) {
                    throw args.createError(t("Invalid data: %s", e.getMessage()));
                }
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return new ArrayList<>();
        }
    }).executor((src, args) -> {
        final Player target = args.<Player>getOne("player").get();
        final Key key = args.<Key>getOne("key").get();
        final Object data = args.<ValueHolder>getOne("data").get().data;
        target.offer(key, data);
        src.sendMessage(t("Successfully offered the data for the key %s to the player %s", key.getId(), target.getName()));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CommandSource(org.spongepowered.api.command.CommandSource) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Key(org.spongepowered.api.data.key.Key)

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