Search in sources :

Example 31 with DataContainer

use of org.spongepowered.api.data.persistence.DataContainer 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)

Example 32 with DataContainer

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

the class MemoryDataView method set.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(final DataQuery path, final Object value) {
    Objects.requireNonNull(path, "path");
    Objects.requireNonNull(value, "value");
    checkState(this.container != null);
    checkState(!path.parts().isEmpty(), "The path is empty");
    @Nullable DataManager manager;
    // TODO: this call to dataManager each set can be cleaned up
    try {
        manager = Sponge.dataManager();
    } catch (final Exception e) {
        manager = null;
    }
    final List<String> parts = path.parts();
    final String key = parts.get(0);
    if (parts.size() > 1) {
        final DataQuery subQuery = DataQuery.of(key);
        final Optional<DataView> subViewOptional = this.getUnsafeView(subQuery);
        final DataView subView;
        if (!subViewOptional.isPresent()) {
            this.createView(subQuery);
            subView = (DataView) this.map.get(key);
        } else {
            subView = subViewOptional.get();
        }
        subView.set(path.popFirst(), value);
        return this;
    }
    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.
        this.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
        this.copyDataView(path, valueContainer);
    } else if (SpongeDataManager.INSTANCE.findRegistryTypeFor(value.getClass()).isPresent()) {
        final RegistryType<Object> registry = SpongeDataManager.INSTANCE.findRegistryTypeFor(value.getClass()).get();
        final ResourceKey valueKey = Sponge.game().registry(registry).valueKey(value);
        // view.set(DataQuery.of("scope"), scope);
        return this.set(path, valueKey);
    } else if (value instanceof ResourceKey) {
        return this.set(path, value.toString());
    } else if (manager != null && manager.translator(value.getClass()).isPresent()) {
        final DataTranslator serializer = manager.translator(value.getClass()).get();
        final DataContainer container = serializer.translate(value);
        checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
        // see above for why this is copied
        this.copyDataView(path, container);
    } else if (value instanceof Collection) {
        this.setCollection(key, (Collection) value);
    } else if (value instanceof Map) {
        this.setMap(key, (Map) value);
    } else if (value.getClass().isArray()) {
        if (this.safety == org.spongepowered.api.data.persistence.DataView.SafetyMode.ALL_DATA_CLONED || this.safety == org.spongepowered.api.data.persistence.DataView.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 : DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) DataManager(org.spongepowered.api.data.DataManager) DataSerializable(org.spongepowered.api.data.persistence.DataSerializable) ResourceKey(org.spongepowered.api.ResourceKey) DataView(org.spongepowered.api.data.persistence.DataView) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Collection(java.util.Collection) DataQuery(org.spongepowered.api.data.persistence.DataQuery) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 33 with DataContainer

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

the class DataUtil method deserializeSpongeData.

public static <T extends SpongeDataHolderBridge & DataCompoundHolder> void deserializeSpongeData(final T dataHolder) {
    final CompoundTag compound = dataHolder.data$getCompound();
    if (compound == null) {
        return;
    }
    final DataContainer allData = NBTTranslator.INSTANCE.translate(compound);
    // Upgrade v2->v3
    DataUtil.upgradeDataVersion(compound, allData);
    // Run content-updaters and collect failed data
    final Class<? extends DataHolder> typeToken = dataHolder.getClass().asSubclass(DataHolder.class);
    allData.getView(Constants.Sponge.Data.V3.SPONGE_DATA_ROOT).ifPresent(customData -> {
        for (final DataQuery keyNamespace : customData.keys(false)) {
            final DataView keyedData = customData.getView(keyNamespace).get();
            for (final DataQuery keyValue : keyedData.keys(false)) {
                final ResourceKey dataStoreKey = ResourceKey.of(keyNamespace.asString("."), keyValue.asString("."));
                final DataView dataStoreData = keyedData.getView(keyValue).get();
                final Integer contentVersion = dataStoreData.getInt(Constants.Sponge.Data.V3.CONTENT_VERSION).orElse(1);
                final Optional<DataStore> dataStore = SpongeDataManager.getDatastoreRegistry().getDataStore(dataStoreKey, typeToken);
                if (dataStore.isPresent()) {
                    if (dataStore.get() instanceof SpongeDataStore) {
                        ((SpongeDataStore) dataStore.get()).getUpdaterFor(contentVersion).ifPresent(updater -> {
                            dataStoreData.set(Constants.Sponge.Data.V3.CONTENT, updater.update(dataStoreData.getView(Constants.Sponge.Data.V3.CONTENT).get()));
                            SpongeCommon.logger().info("Updated datastore {} from {} to {} ", dataStoreKey.asString(), contentVersion, ((SpongeDataStore) dataStore.get()).getVersion());
                        });
                    }
                } else {
                    dataHolder.bridge$addFailedData(keyNamespace.then(keyValue), dataStoreData);
                }
            }
        }
    });
    // Initialize sponge data holder
    dataHolder.bridge$mergeDeserialized(DataManipulator.mutableOf());
    for (final DataStore dataStore : SpongeDataManager.getDatastoreRegistry().getDataStoresForType(typeToken)) {
        // Deserialize to Manipulator
        final DataManipulator.Mutable deserialized = dataStore.deserialize(allData);
        try {
            // and set data in CustomDataHolderBridge
            dataHolder.bridge$mergeDeserialized(deserialized);
        } catch (final Exception e) {
            SpongeCommon.logger().error("Could not merge data from datastore: {}", deserialized, e);
        }
    }
}
Also used : DataManipulator(org.spongepowered.api.data.DataManipulator) ResourceKey(org.spongepowered.api.ResourceKey) DataView(org.spongepowered.api.data.persistence.DataView) DataContainer(org.spongepowered.api.data.persistence.DataContainer) SpongeDataStore(org.spongepowered.common.data.persistence.datastore.SpongeDataStore) DataStore(org.spongepowered.api.data.persistence.DataStore) SpongeDataStore(org.spongepowered.common.data.persistence.datastore.SpongeDataStore) DataQuery(org.spongepowered.api.data.persistence.DataQuery) CompoundTag(net.minecraft.nbt.CompoundTag)

Example 34 with DataContainer

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

the class MemoryDataView method copy.

@Override
public DataContainer copy(final org.spongepowered.api.data.persistence.DataView.SafetyMode safety) {
    final DataContainer container = new MemoryDataContainer(safety);
    this.keys(false).forEach(query -> this.get(query).ifPresent(obj -> container.set(query, obj)));
    return container;
}
Also used : DataManager(org.spongepowered.api.data.DataManager) DataContainer(org.spongepowered.api.data.persistence.DataContainer) Arrays(java.util.Arrays) RegistryHolder(org.spongepowered.api.registry.RegistryHolder) KeyProvider(org.spongepowered.common.registry.provider.KeyProvider) ArrayUtils(org.apache.commons.lang3.ArrayUtils) DataView(org.spongepowered.api.data.persistence.DataView) Supplier(java.util.function.Supplier) Value(org.spongepowered.api.data.value.Value) ArrayList(java.util.ArrayList) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) DataQuery(org.spongepowered.api.data.persistence.DataQuery) Map(java.util.Map) ResourceKey(org.spongepowered.api.ResourceKey) Nullable(org.checkerframework.checker.nullness.qual.Nullable) ImmutableSet(com.google.common.collect.ImmutableSet) DataSerializable(org.spongepowered.api.data.persistence.DataSerializable) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) MoreObjects(com.google.common.base.MoreObjects) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) RegistryType(org.spongepowered.api.registry.RegistryType) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Key(org.spongepowered.api.data.Key) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Coerce(org.spongepowered.api.util.Coerce) DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) Optional(java.util.Optional) DataContainer(org.spongepowered.api.data.persistence.DataContainer)

Example 35 with DataContainer

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

the class SpongeParticleEffect method toContainer.

@Override
public DataContainer toContainer() {
    DataContainer dataContainer = DataContainer.createNew();
    dataContainer.set(Constants.Particles.PARTICLE_TYPE, this.type);
    dataContainer.set(Constants.Particles.PARTICLE_OPTIONS, this.options.entrySet().stream().map(entry -> DataContainer.createNew().set(Constants.Particles.PARTICLE_OPTION_KEY, entry.getKey()).set(Constants.Particles.PARTICLE_OPTION_VALUE, entry.getValue())).collect(Collectors.toList()));
    return dataContainer;
}
Also used : DataContainer(org.spongepowered.api.data.persistence.DataContainer)

Aggregations

DataContainer (org.spongepowered.api.data.persistence.DataContainer)43 ResourceKey (org.spongepowered.api.ResourceKey)14 DataView (org.spongepowered.api.data.persistence.DataView)12 CompoundTag (net.minecraft.nbt.CompoundTag)9 Test (org.junit.jupiter.api.Test)9 ArrayList (java.util.ArrayList)7 DataQuery (org.spongepowered.api.data.persistence.DataQuery)7 BasicConfigurationNode (org.spongepowered.configurate.BasicConfigurationNode)7 CommentedConfigurationNode (org.spongepowered.configurate.CommentedConfigurationNode)7 ConfigurationNode (org.spongepowered.configurate.ConfigurationNode)7 Optional (java.util.Optional)6 Nullable (org.checkerframework.checker.nullness.qual.Nullable)6 Map (java.util.Map)5 NonNull (org.checkerframework.checker.nullness.qual.NonNull)5 Sponge (org.spongepowered.api.Sponge)5 DataTranslator (org.spongepowered.api.data.persistence.DataTranslator)5 ImmutableList (com.google.common.collect.ImmutableList)4 ImmutableMap (com.google.common.collect.ImmutableMap)4 Collection (java.util.Collection)4 DataManager (org.spongepowered.api.data.DataManager)4