Search in sources :

Example 16 with DataView

use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.

the class SpongeDataStoreBuilder method getDeserializer.

@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> BiFunction<DataView, DataQuery, Optional<T>> getDeserializer(final Type elementType) {
    final Class<?> rawType = GenericTypeReflector.erase(elementType);
    if (DataView.class.isAssignableFrom(rawType)) {
        return (view, dataQuery) -> (Optional<T>) view.getView(dataQuery);
    }
    if (DataSerializable.class.isAssignableFrom(rawType)) {
        return (view, dataQuery) -> (Optional<T>) view.getSerializable(dataQuery, (Class<? extends DataSerializable>) rawType);
    }
    final Optional<RegistryType<Object>> registryTypeForValue = SpongeDataManager.INSTANCE.findRegistryTypeFor(rawType);
    if (registryTypeForValue.isPresent()) {
        return (view, dataQuery) -> (Optional<T>) registryTypeForValue.flatMap(regType -> view.getRegistryValue(dataQuery, regType));
    }
    if (ResourceKey.class.isAssignableFrom(rawType)) {
        return (view, dataQuery) -> (Optional<T>) view.getString(dataQuery).map(ResourceKey::resolve);
    }
    if (Sponge.game().dataManager().translator(rawType).isPresent()) {
        return (view, dataQuery) -> (Optional<T>) view.getObject(dataQuery, rawType);
    }
    if (Set.class.isAssignableFrom(rawType)) {
        final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0];
        return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) listType, view, dataQuery).map(list -> new HashSet(list));
    }
    if (List.class.isAssignableFrom(rawType)) {
        final Type listType = ((ParameterizedType) elementType).getActualTypeArguments()[0];
        return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) listType, view, dataQuery);
    }
    if (Collection.class.isAssignableFrom(rawType)) {
        throw new UnsupportedOperationException("Collection deserialization is not supported. Provide the deserializer for it.");
    }
    if (Types.isArray(elementType)) {
        final Class arrayType = GenericTypeReflector.erase(GenericTypeReflector.getArrayComponentType(elementType));
        return (view, dataQuery) -> (Optional<T>) SpongeDataStoreBuilder.deserializeList((Class<?>) arrayType, view, dataQuery).map(list -> this.listToArray(arrayType, list));
    }
    if (Map.class.isAssignableFrom(rawType)) {
        final Type[] parameterTypes = ((ParameterizedType) elementType).getActualTypeArguments();
        final Type keyType = parameterTypes[0];
        final Type valueType = parameterTypes[1];
        if (!(keyType instanceof Class)) {
            throw new UnsupportedOperationException("Unsupported map-key type " + keyType);
        }
        final Function<DataQuery, Optional<?>> keyDeserializer;
        final Optional<RegistryType<Object>> registryTypeForKey = SpongeDataManager.INSTANCE.findRegistryTypeFor((Class) keyType);
        if (registryTypeForKey.isPresent()) {
            keyDeserializer = key -> registryTypeForKey.flatMap(regType -> Sponge.game().findRegistry(regType)).flatMap(r -> r.findValue(ResourceKey.resolve(key.toString())));
        } else if (((Class<?>) keyType).isEnum()) {
            keyDeserializer = key -> Optional.ofNullable(Enum.valueOf(((Class<? extends Enum>) keyType), key.toString()));
        } else if (keyType == String.class) {
            keyDeserializer = key -> Optional.of(key.toString());
        } else if (keyType == UUID.class) {
            keyDeserializer = key -> Optional.of(UUID.fromString(key.toString()));
        } else if (keyType == ResourceKey.class) {
            keyDeserializer = key -> Optional.of(ResourceKey.resolve(key.toString()));
        } else {
            throw new UnsupportedOperationException("Unsupported map-key type " + keyType);
        }
        final BiFunction<DataView, DataQuery, Optional<Object>> valueDeserializer = this.getDeserializer(valueType);
        return (view, dataQuery) -> (Optional<T>) view.getView(dataQuery).map(mapView -> {
            final Map<Object, Object> resultMap = new HashMap<>();
            for (final DataQuery key : mapView.keys(false)) {
                final Object mapKey = keyDeserializer.apply(key).orElseThrow(() -> new UnsupportedOperationException("Key not found " + key + " as " + keyType));
                final Optional<?> mapValue = valueDeserializer.apply(mapView, key);
                resultMap.put(mapKey, mapValue.get());
            }
            return resultMap;
        });
    }
    return (view, dataQuery) -> (Optional<T>) view.get(dataQuery);
}
Also used : DataContainer(org.spongepowered.api.data.persistence.DataContainer) Array(java.lang.reflect.Array) BiFunction(java.util.function.BiFunction) HashMap(java.util.HashMap) DataView(org.spongepowered.api.data.persistence.DataView) Function(java.util.function.Function) Value(org.spongepowered.api.data.value.Value) SpongeDataManager(org.spongepowered.common.data.SpongeDataManager) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DataStore(org.spongepowered.api.data.persistence.DataStore) ImmutableList(com.google.common.collect.ImmutableList) DataQuery(org.spongepowered.api.data.persistence.DataQuery) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) ResourceKey(org.spongepowered.api.ResourceKey) Nullable(org.checkerframework.checker.nullness.qual.Nullable) DataContentUpdater(org.spongepowered.api.data.persistence.DataContentUpdater) Types(org.spongepowered.configurate.util.Types) IdentityHashMap(java.util.IdentityHashMap) DataSerializable(org.spongepowered.api.data.persistence.DataSerializable) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) DataHolder(org.spongepowered.api.data.DataHolder) RegistryType(org.spongepowered.api.registry.RegistryType) Tuple(org.spongepowered.api.util.Tuple) UUID(java.util.UUID) TypeToken(io.leangen.geantyref.TypeToken) DataUtil(org.spongepowered.common.data.DataUtil) Key(org.spongepowered.api.data.Key) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Optional(java.util.Optional) GenericTypeReflector(io.leangen.geantyref.GenericTypeReflector) Collections(java.util.Collections) Optional(java.util.Optional) RegistryType(org.spongepowered.api.registry.RegistryType) DataSerializable(org.spongepowered.api.data.persistence.DataSerializable) ParameterizedType(java.lang.reflect.ParameterizedType) DataView(org.spongepowered.api.data.persistence.DataView) RegistryType(org.spongepowered.api.registry.RegistryType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) DataQuery(org.spongepowered.api.data.persistence.DataQuery) UUID(java.util.UUID) HashMap(java.util.HashMap) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashSet(java.util.HashSet)

Example 17 with DataView

use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.

the class NBTTranslator method containerToCompound.

private static void containerToCompound(final DataView container, final CompoundTag compound) {
    // We don't need to get deep values since all nested DataViews will be found
    // from the instance of checks.
    checkNotNull(container);
    checkNotNull(compound);
    for (Map.Entry<DataQuery, Object> entry : container.values(false).entrySet()) {
        Object value = entry.getValue();
        String key = entry.getKey().asString('.');
        if (value instanceof DataView) {
            CompoundTag inner = new CompoundTag();
            NBTTranslator.containerToCompound(container.getView(entry.getKey()).get(), inner);
            compound.put(key, inner);
        } else if (value instanceof Boolean) {
            compound.put(key + NBTTranslator.BOOLEAN_IDENTIFIER, ByteTag.valueOf((Boolean) value));
        } else {
            compound.put(key, NBTTranslator.getBaseFromObject(value));
        }
    }
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) DataQuery(org.spongepowered.api.data.persistence.DataQuery) Map(java.util.Map) CompoundTag(net.minecraft.nbt.CompoundTag)

Example 18 with DataView

use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.

the class VanillaDataStore method serialize.

@Override
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public DataView serialize(DataManipulator dataManipulator, DataView view) {
    for (Map.Entry<Key<?>, Tuple<BiConsumer<DataView, ?>, Function<DataView, Optional<?>>>> entry : this.queriesByKey.entrySet()) {
        final BiConsumer serializer = entry.getValue().first();
        dataManipulator.get((Key) entry.getKey()).ifPresent(value -> serializer.accept(view, value));
    }
    return view;
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) Optional(java.util.Optional) Map(java.util.Map) Key(org.spongepowered.api.data.Key) Tuple(org.spongepowered.api.util.Tuple) BiConsumer(java.util.function.BiConsumer)

Example 19 with DataView

use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.

the class DataUtil method getPosition3i.

public static Vector3i getPosition3i(final DataView view) {
    DataUtil.checkDataExists(view, Constants.Sponge.SNAPSHOT_WORLD_POSITION);
    final DataView internal = view.getView(Constants.Sponge.SNAPSHOT_WORLD_POSITION).orElseThrow(DataUtil.dataNotFound());
    final int x = internal.getInt(Queries.POSITION_X).orElseThrow(DataUtil.dataNotFound());
    final int y = internal.getInt(Queries.POSITION_Y).orElseThrow(DataUtil.dataNotFound());
    final int z = internal.getInt(Queries.POSITION_Z).orElseThrow(DataUtil.dataNotFound());
    return new Vector3i(x, y, z);
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) Vector3i(org.spongepowered.math.vector.Vector3i)

Example 20 with DataView

use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.

the class BaseContainerBlockEntityMixin_API method toContainer.

// @formatter:off
@Override
public DataContainer toContainer() {
    final DataContainer container = super.toContainer();
    if (this.lockKey != null) {
        container.set(Constants.TileEntity.LOCK_CODE, ((LockCodeAccessor) this.lockKey).accessor$key());
    }
    final List<DataView> items = Lists.newArrayList();
    for (int i = 0; i < ((Container) this).getContainerSize(); i++) {
        final ItemStack stack = ((Container) this).getItem(i);
        if (!stack.isEmpty()) {
            // todo make a helper object for this
            final DataContainer stackView = DataContainer.createNew().set(Queries.CONTENT_VERSION, 1).set(Constants.TileEntity.SLOT, i).set(Constants.TileEntity.SLOT_ITEM, ((org.spongepowered.api.item.inventory.ItemStack) (Object) stack).toContainer());
            items.add(stackView);
        }
    }
    if (this.name != null) {
        container.set(Constants.TileEntity.LOCKABLE_CONTAINER_CUSTOM_NAME, this.name);
    }
    container.set(Constants.TileEntity.ITEM_CONTENTS, items);
    return container;
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) DataContainer(org.spongepowered.api.data.persistence.DataContainer) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Container(net.minecraft.world.Container) ItemStack(net.minecraft.world.item.ItemStack)

Aggregations

DataView (org.spongepowered.api.data.persistence.DataView)32 DataQuery (org.spongepowered.api.data.persistence.DataQuery)16 DataContainer (org.spongepowered.api.data.persistence.DataContainer)10 CompoundTag (net.minecraft.nbt.CompoundTag)9 ResourceKey (org.spongepowered.api.ResourceKey)8 Map (java.util.Map)6 InvalidDataException (org.spongepowered.api.data.persistence.InvalidDataException)6 Optional (java.util.Optional)5 Nullable (org.checkerframework.checker.nullness.qual.Nullable)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Collection (java.util.Collection)3 DataContentUpdater (org.spongepowered.api.data.persistence.DataContentUpdater)3 DataSerializable (org.spongepowered.api.data.persistence.DataSerializable)3 DataStore (org.spongepowered.api.data.persistence.DataStore)3 DataTranslator (org.spongepowered.api.data.persistence.DataTranslator)3 Vector3i (org.spongepowered.math.vector.Vector3i)3 ImmutableList (com.google.common.collect.ImmutableList)2 TypeToken (io.leangen.geantyref.TypeToken)2