Search in sources :

Example 11 with DataQuery

use of org.spongepowered.api.data.persistence.DataQuery 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 12 with DataQuery

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

the class DataUtil method upgradeV2CustomData.

@SuppressWarnings("deprecation")
private static void upgradeV2CustomData(final CompoundTag compound, final DataContainer allData, final DataView spongeDataV2) {
    // convert custom data v2 to v3
    final DataView spongeDataV3 = DataContainer.createNew();
    for (final DataView customDataV2 : spongeDataV2.getViewList(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_LIST).orElse(Collections.emptyList())) {
        try {
            // ForgeData/SpongeData/CustomManipulators[{ContentVersion|ManipulatorId|ManipulatorData}]
            final String id = customDataV2.getString(Constants.Sponge.Data.V2.MANIPULATOR_ID).get();
            final Object data = customDataV2.get(Constants.Sponge.Data.V2.MANIPULATOR_DATA).get();
            final Integer contentVersion = customDataV2.getInt(Queries.CONTENT_VERSION).get();
            // Fetch DataStore key for legacy registration or try to read it as a resouce key
            final ResourceKey key = SpongeDataManager.INSTANCE.getLegacyRegistration(id).orElse(ResourceKey.resolve(id));
            // Build new custom data structure
            // sponeg-data/<datastore-namespace>/<datastore-value>/{version|content}
            final DataView dataStoreData = spongeDataV3.createView(DataQuery.of(key.namespace(), key.value()));
            dataStoreData.set(Constants.Sponge.Data.V3.CONTENT_VERSION, contentVersion);
            dataStoreData.set(Constants.Sponge.Data.V3.CONTENT, data);
            SpongeCommon.logger().info("Upgraded custom data for datastore: {}", key);
        } catch (final Exception e) {
            SpongeCommon.logger().error("Error when upgrading V2 custom data", e);
        }
    }
    spongeDataV2.remove(Constants.Sponge.Data.V2.CUSTOM_MANIPULATOR_LIST);
    // convert sponge data v2 to v3
    for (final DataQuery spongeDataKey : spongeDataV2.keys(false)) {
        final DataQuery query = SpongeDataManager.INSTANCE.legacySpongeDataQuery(spongeDataKey.toString());
        if (query == null) {
            SpongeCommon.logger().error("Missing legacy sponge data query mapping {}", spongeDataKey.toString());
        } else {
            final Object value = spongeDataV2.get(spongeDataKey).get();
            SpongeCommon.logger().info("Upgraded sponge data: {}->{} type {}", spongeDataKey.toString(), query.toString(), value.getClass().getSimpleName());
            spongeDataV3.set(query, value);
        }
    }
    // Setting upgraded v3 data
    allData.set(Constants.Sponge.Data.V3.SPONGE_DATA_ROOT, spongeDataV3);
    // cleanup v2 data
    allData.getView(Constants.Forge.FORGE_DATA_ROOT).ifPresent(forgeData -> {
        forgeData.remove(Constants.Sponge.Data.V2.SPONGE_DATA_ROOT);
        if (forgeData.isEmpty()) {
            allData.remove(Constants.Forge.FORGE_DATA_ROOT);
        }
    });
    // cleanup v2 data on compound
    if (compound.contains(Constants.Forge.FORGE_DATA)) {
        final CompoundTag forgeData = compound.getCompound(Constants.Forge.FORGE_DATA);
        forgeData.remove(Constants.Sponge.Data.V2.SPONGE_DATA);
        if (forgeData.isEmpty()) {
            compound.remove(Constants.Forge.FORGE_DATA);
        }
    }
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) DataQuery(org.spongepowered.api.data.persistence.DataQuery) CompoundTag(net.minecraft.nbt.CompoundTag) ResourceKey(org.spongepowered.api.ResourceKey)

Example 13 with DataQuery

use of org.spongepowered.api.data.persistence.DataQuery 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 14 with DataQuery

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

the class DataUtil method setSpongeData.

public static void setSpongeData(final DataView allData, final DataQuery dataStoreKey, final DataView pluginData, final int version) {
    final DataQuery dataStoreDataQuery = Constants.Sponge.Data.V3.SPONGE_DATA_ROOT.then(dataStoreKey);
    final DataView dataStoreDataView = allData.getView(dataStoreDataQuery).orElseGet(() -> allData.createView(dataStoreDataQuery));
    dataStoreDataView.set(Constants.Sponge.Data.V3.CONTENT_VERSION, version);
    dataStoreDataView.set(Constants.Sponge.Data.V3.CONTENT, pluginData);
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) DataQuery(org.spongepowered.api.data.persistence.DataQuery)

Example 15 with DataQuery

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

the class MemoryDataView method remove.

@Override
public DataView remove(final DataQuery path) {
    Objects.requireNonNull(path, "path");
    final List<String> parts = path.parts();
    if (parts.size() > 1) {
        final String subKey = parts.get(0);
        final DataQuery subQuery = DataQuery.of(subKey);
        final Optional<DataView> subViewOptional = this.getUnsafeView(subQuery);
        if (!subViewOptional.isPresent()) {
            return this;
        }
        final DataView subView = subViewOptional.get();
        subView.remove(path.popFirst());
    } else {
        this.map.remove(parts.get(0));
    }
    return this;
}
Also used : DataView(org.spongepowered.api.data.persistence.DataView) DataQuery(org.spongepowered.api.data.persistence.DataQuery)

Aggregations

DataQuery (org.spongepowered.api.data.persistence.DataQuery)20 DataView (org.spongepowered.api.data.persistence.DataView)15 ResourceKey (org.spongepowered.api.ResourceKey)6 InvalidDataException (org.spongepowered.api.data.persistence.InvalidDataException)6 CompoundTag (net.minecraft.nbt.CompoundTag)5 DataContainer (org.spongepowered.api.data.persistence.DataContainer)5 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Nullable (org.checkerframework.checker.nullness.qual.Nullable)3 Biome (org.spongepowered.api.world.biome.Biome)3 Vector3i (org.spongepowered.math.vector.Vector3i)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 TypeToken (io.leangen.geantyref.TypeToken)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 Collection (java.util.Collection)2 Set (java.util.Set)2