use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.
the class MapTest method blankMapDecorationIds.
private DataView blankMapDecorationIds(final DataView dataView) {
// Blank changes to id since we always change when serializing them to stop conflicts.
final DataQuery decorations = DataQuery.of("MapData", "Decorations");
final List<DataView> newData = dataView.getViewList(decorations).get();
newData.replaceAll(dataView1 -> dataView1.set(DataQuery.of("id"), "fakeid"));
dataView.set(decorations, newData);
return dataView;
}
use of org.spongepowered.api.data.persistence.DataView in project SpongeCommon by SpongePowered.
the class MapTest method testMapSerialization.
private CommandResult testMapSerialization(final CommandContext ctx) {
MapInfo mapInfo = null;
final Audience audience = ctx.cause().audience();
if (audience instanceof Player) {
final Player player = (Player) audience;
mapInfo = player.itemInHand(HandTypes.MAIN_HAND).get(Keys.MAP_INFO).orElse(null);
}
final MapStorage mapStorage = Sponge.server().mapStorage();
if (mapInfo == null) {
mapInfo = mapStorage.allMapInfos().stream().findAny().orElse(mapStorage.createNewMapInfo().get());
}
final DataView mapInfoView = blankMapDecorationIds(mapInfo.toContainer());
mapInfoView.set(DataQuery.of("MapData", "MapLocked"), true).set(DataQuery.of("UnsafeMapId"), 10);
return CommandResult.success();
}
use of org.spongepowered.api.data.persistence.DataView 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;
}
use of org.spongepowered.api.data.persistence.DataView 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);
}
}
}
use of org.spongepowered.api.data.persistence.DataView 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);
}
}
}
Aggregations