use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.
the class MemoryDataView method set.
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DataView set(DataQuery path, Object value) {
checkNotNull(path, "path");
checkNotNull(value, "value");
final LanternDataManager manager = getDataManager();
final List<String> parts = path.getParts();
final String key = parts.get(0);
if (parts.size() > 1) {
final DataQuery subQuery = of(key);
final Optional<DataView> subViewOptional = getUnsafeView(subQuery);
final DataView subView;
if (!subViewOptional.isPresent()) {
createView(subQuery);
subView = (DataView) this.map.get(key);
} else {
subView = subViewOptional.get();
}
subView.set(path.popFirst(), value);
return this;
}
Optional<DataTypeSerializer> optDataTypeSerializer;
TypeToken typeToken;
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.
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
copyDataView(path, valueContainer);
} else if (value instanceof CatalogType) {
return set(path, ((CatalogType) value).getId());
} else if (value instanceof Integer || value instanceof Byte || value instanceof Short || value instanceof Float || value instanceof Double || value instanceof Long || value instanceof String || value instanceof Character || value instanceof Boolean) {
this.map.put(key, value);
return this;
} else if (manager != null && (optDataTypeSerializer = manager.getTypeSerializer(typeToken = TypeToken.of(value.getClass()))).isPresent()) {
final DataTypeSerializer serializer = optDataTypeSerializer.get();
final Object serialized = serializer.serialize(typeToken, manager.getTypeSerializerContext(), value);
if (serialized instanceof DataContainer) {
final DataContainer container = (DataContainer) serialized;
checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
// see above for why this is copied
copyDataView(path, container);
} else {
this.map.put(key, serialized);
}
} else if (value instanceof Collection) {
setCollection(key, (Collection) value);
} else if (value instanceof Map) {
setMap(key, (Map) value);
} else if (value.getClass().isArray()) {
if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == 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.DataQuery in project LanternServer by LanternPowered.
the class CompositeValueContainerStore method deserialize.
@SuppressWarnings("unchecked")
@Override
public void deserialize(T object, DataView dataView) {
if (object instanceof IValueContainer) {
final IValueContainer<S> valueContainer = (IValueContainer<S>) object;
final SimpleValueContainer simpleValueContainer = new SimpleValueContainer(new HashMap<>());
deserializeValues(object, simpleValueContainer, dataView);
final Optional<DataView> optDataView = dataView.getView(VALUES);
if (optDataView.isPresent()) {
final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
final DataView valuesView = optDataView.get();
for (Map.Entry<DataQuery, Object> entry : valuesView.getValues(false).entrySet()) {
final Key key = KeyRegistryModule.get().getById(entry.getKey().toString()).orElse(null);
if (key == null) {
Lantern.getLogger().warn("Unable to deserialize the data value with key: {} because it doesn't exist.", entry.getKey().toString());
} else {
final TypeToken<?> typeToken = key.getElementToken();
final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
if (dataTypeSerializer == null) {
Lantern.getLogger().warn("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId());
} else {
if (simpleValueContainer.get(key).isPresent()) {
Lantern.getLogger().warn("Duplicate usage of the key: {}", key.getId());
} else {
simpleValueContainer.set(key, dataTypeSerializer.deserialize(typeToken, context, entry.getValue()));
}
}
}
}
}
for (Map.Entry<Key<?>, Object> entry : simpleValueContainer.getValues().entrySet()) {
final Element element = (Element) valueContainer.getValueCollection().getElement((Key) entry.getKey()).orElse(null);
if (element != null) {
element.set(entry.getValue());
} else {
Lantern.getLogger().warn("Attempted to offer a unsupported value with key \"{}\" to the object {}", entry.getKey().toString(), object.toString());
}
}
dataView.getView(DataQueries.SPONGE_DATA).ifPresent(view -> DataHelper.deserializeRawContainerData(dataView, valueContainer, DataQueries.CUSTOM_MANIPULATORS));
} else {
// Not sure what to do
}
}
use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.
the class JsonDataFormat method readView.
private static void readView(JsonReader reader, DataView view) throws IOException {
reader.beginObject();
while (reader.hasNext()) {
DataQuery key = DataQuery.of(reader.nextName());
if (reader.peek() == JsonToken.BEGIN_OBJECT) {
// Check this early so we don't need to copy the view
readView(reader, view.createView(key));
} else {
view.set(key, read0(reader));
}
}
reader.endObject();
}
use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method convert.
static LanternWorldProperties convert(LevelData levelData, WorldConfig worldConfig, boolean copyLevelSettingsToConfig) {
final LanternWorldProperties properties = new LanternWorldProperties(levelData.uniqueId, levelData.worldName, worldConfig);
final DataView dataView = levelData.worldData.getView(DATA).get();
final DataView spongeRootDataView = levelData.spongeWorldData;
final DataView spongeDataView;
if (spongeRootDataView != null) {
spongeDataView = spongeRootDataView.getView(DataQueries.SPONGE_DATA).orElse(null);
spongeDataView.remove(DataQueries.SPONGE_DATA);
} else {
spongeDataView = null;
}
final DataView lanternDataView = spongeDataView == null ? null : spongeDataView.getView(LANTERN).orElse(null);
properties.setLastPlayedTime(dataView.getLong(LAST_PLAYED).get());
properties.mapFeatures = dataView.getInt(MAP_FEATURES).get() > 0;
properties.setInitialized(dataView.getInt(INITIALIZED).get() > 0);
dataView.getInt(DIFFICULTY_LOCKED).ifPresent(v -> properties.setDifficultyLocked(v > 0));
final LanternWorldBorder border = properties.getWorldBorder();
dataView.getDouble(BORDER_CENTER_X).ifPresent(v -> border.centerX = v);
dataView.getDouble(BORDER_CENTER_Z).ifPresent(v -> border.centerZ = v);
dataView.getDouble(BORDER_SIZE_START).ifPresent(v -> border.diameterStart = v);
dataView.getDouble(BORDER_SIZE_END).ifPresent(v -> border.diameterEnd = v);
dataView.getLong(BORDER_SIZE_LERP_TIME).ifPresent(v -> border.lerpTime = v);
dataView.getDouble(BORDER_DAMAGE).ifPresent(v -> border.damage = v);
dataView.getDouble(BORDER_DAMAGE_THRESHOLD).ifPresent(v -> border.damageThreshold = v);
dataView.getInt(BORDER_WARNING_BLOCKS).ifPresent(v -> border.warningDistance = v);
dataView.getInt(BORDER_WARNING_TIME).ifPresent(v -> border.warningTime = v);
if (spongeRootDataView != null) {
properties.setAdditionalProperties(spongeRootDataView.copy().remove(DataQueries.SPONGE_DATA));
}
// Get the sponge properties
if (spongeDataView != null) {
// This can be null, this is provided in the lantern-server
final String dimensionTypeId = spongeDataView.getString(DIMENSION_TYPE).get();
if (dimensionTypeId.equalsIgnoreCase(OVERWORLD)) {
properties.setDimensionType(DimensionTypes.OVERWORLD);
} else if (dimensionTypeId.equalsIgnoreCase(NETHER)) {
properties.setDimensionType(DimensionTypes.NETHER);
} else if (dimensionTypeId.equalsIgnoreCase(END)) {
properties.setDimensionType(DimensionTypes.THE_END);
} else {
final DimensionType dimensionType = Sponge.getRegistry().getType(DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
Lantern.getLogger().warn("Could not find a dimension type with id {} for the world {}, falling back to overworld...", dimensionTypeId, levelData.worldName);
}
properties.setDimensionType(dimensionType == null ? DimensionTypes.OVERWORLD : dimensionType);
}
PortalAgentType portalAgentType = null;
if (spongeDataView.contains(PORTAL_AGENT_TYPE)) {
final String portalAgentTypeId = spongeDataView.getString(PORTAL_AGENT_TYPE).get();
portalAgentType = Sponge.getRegistry().getType(PortalAgentType.class, portalAgentTypeId).orElse(null);
if (portalAgentType == null) {
Lantern.getLogger().warn("Could not find a portal agent type with id {} for the world {}, falling back to default...", portalAgentTypeId, levelData.worldName);
}
}
properties.setPortalAgentType(portalAgentType == null ? PortalAgentTypes.DEFAULT : portalAgentType);
spongeDataView.getInt(GENERATE_BONUS_CHEST).ifPresent(v -> properties.setGenerateBonusChest(v > 0));
spongeDataView.getInt(SERIALIZATION_BEHAVIOR).ifPresent(v -> properties.setSerializationBehavior(v == 0 ? SerializationBehaviors.MANUAL : v == 1 ? SerializationBehaviors.AUTOMATIC : SerializationBehaviors.NONE));
// Tracker
final Optional<List<DataView>> optTrackerUniqueIdViews = spongeDataView.getViewList(TRACKER_UUID_TABLE);
if (optTrackerUniqueIdViews.isPresent()) {
final List<DataView> trackerUniqueIdViews = optTrackerUniqueIdViews.get();
final Object2IntMap<UUID> trackerUniqueIds = properties.getTrackerIdAllocator().getUniqueIds();
final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
for (DataView view : trackerUniqueIdViews) {
UUID uniqueId = null;
if (!view.isEmpty()) {
final long most = view.getLong(UUID_MOST).get();
final long least = view.getLong(UUID_LEAST).get();
uniqueId = new UUID(most, least);
trackerUniqueIds.put(uniqueId, uniqueIdsByIndex.size());
}
uniqueIdsByIndex.add(uniqueId);
}
}
}
// Weather
final WeatherData weatherData = properties.getWeatherData();
if (lanternDataView != null) {
final DataView weatherView = lanternDataView.getView(WEATHER).get();
final String weatherTypeId = weatherView.getString(WEATHER_TYPE).get();
final Optional<Weather> weatherType = Sponge.getRegistry().getType(Weather.class, weatherTypeId);
if (weatherType.isPresent()) {
weatherData.setWeather((LanternWeather) weatherType.get());
} else {
Lantern.getLogger().info("Unknown weather type: {}, the server will default to {}", weatherTypeId, weatherData.getWeather().getId());
}
weatherData.setRunningDuration(weatherView.getLong(WEATHER_RUNNING_DURATION).get());
weatherData.setRemainingDuration(weatherView.getLong(WEATHER_REMAINING_DURATION).get());
} else {
final boolean raining = dataView.getInt(RAINING).get() > 0;
final long rainTime = dataView.getLong(RAIN_TIME).get();
final boolean thundering = dataView.getInt(THUNDERING).get() > 0;
final long thunderTime = dataView.getLong(THUNDER_TIME).get();
final long clearWeatherTime = dataView.getLong(CLEAR_WEATHER_TIME).get();
if (thundering) {
weatherData.setWeather((LanternWeather) Weathers.THUNDER_STORM);
weatherData.setRemainingDuration(thunderTime);
} else if (raining) {
weatherData.setWeather((LanternWeather) Weathers.RAIN);
weatherData.setRemainingDuration(rainTime);
} else {
weatherData.setRemainingDuration(clearWeatherTime);
}
}
// Time
final TimeData timeData = properties.getTimeData();
final long age = dataView.getLong(AGE).get();
timeData.setAge(age);
final long time = dataView.getLong(TIME).orElse(age);
timeData.setDayTime(time);
if (lanternDataView != null && lanternDataView.contains(MOON_PHASE)) {
timeData.setMoonPhase(MoonPhase.valueOf(lanternDataView.getString(MOON_PHASE).get().toUpperCase()));
} else {
timeData.setMoonPhase(MoonPhase.values()[(int) (time / TimeUniverse.TICKS_IN_A_DAY) % 8]);
}
// Get the spawn position
final Optional<Integer> spawnX = dataView.getInt(SPAWN_X);
final Optional<Integer> spawnY = dataView.getInt(SPAWN_Y);
final Optional<Integer> spawnZ = dataView.getInt(SPAWN_Z);
if (spawnX.isPresent() && spawnY.isPresent() && spawnZ.isPresent()) {
properties.setSpawnPosition(new Vector3i(spawnX.get(), spawnY.get(), spawnZ.get()));
}
// Get the game rules
final DataView rulesView = dataView.getView(GAME_RULES).orElse(null);
if (rulesView != null) {
for (Entry<DataQuery, Object> en : rulesView.getValues(false).entrySet()) {
try {
properties.getRules().getOrCreateRule(RuleType.getOrCreate(en.getKey().toString(), RuleDataTypes.STRING, "")).setRawValue((String) en.getValue());
} catch (IllegalArgumentException e) {
Lantern.getLogger().warn("An error occurred while loading a game rule ({}) this one will be skipped", en.getKey().toString(), e);
}
}
}
if (copyLevelSettingsToConfig) {
worldConfig.getGeneration().setSeed(dataView.getLong(SEED).get());
worldConfig.setGameMode(GameModeRegistryModule.get().getByInternalId(dataView.getInt(GAME_MODE).get()).orElse(GameModes.SURVIVAL));
worldConfig.setHardcore(dataView.getInt(HARDCORE).get() > 0);
worldConfig.setDifficulty(DifficultyRegistryModule.get().getByInternalId(dataView.getInt(DIFFICULTY).get()).orElse(Difficulties.NORMAL));
if (dataView.contains(GENERATOR_NAME)) {
final String genName0 = dataView.getString(GENERATOR_NAME).get();
final String genName = genName0.indexOf(':') == -1 ? "minecraft:" + genName0 : genName0;
final GeneratorType generatorType = Sponge.getRegistry().getType(GeneratorType.class, genName).orElse(properties.getDimensionType().getDefaultGeneratorType());
DataContainer generatorSettings = null;
if (dataView.contains(GENERATOR_OPTIONS)) {
String options = dataView.getString(GENERATOR_OPTIONS).get();
String customSettings = null;
if (genName0.equalsIgnoreCase("flat")) {
customSettings = options;
// custom generator options to the flat generator
if (dataView.contains(GENERATOR_OPTIONS_EXTRA)) {
options = dataView.getString(GENERATOR_OPTIONS_EXTRA).get();
} else {
options = "";
}
}
if (!options.isEmpty()) {
try {
generatorSettings = JsonDataFormat.readContainer(options, false);
} catch (Exception e) {
Lantern.getLogger().warn("Unknown generator settings format \"{}\" for type {}, using defaults...", options, genName, e);
}
}
if (generatorSettings == null) {
generatorSettings = generatorType.getGeneratorSettings();
}
if (customSettings != null) {
generatorSettings.set(AbstractFlatGeneratorType.SETTINGS, customSettings);
}
} else {
generatorSettings = generatorType.getGeneratorSettings();
}
worldConfig.getGeneration().setGeneratorType(generatorType);
worldConfig.getGeneration().setGeneratorSettings(generatorSettings);
worldConfig.setLowHorizon(generatorType == GeneratorTypes.FLAT);
}
if (spongeDataView != null) {
spongeDataView.getInt(ENABLED).ifPresent(v -> worldConfig.setWorldEnabled(v > 0));
worldConfig.setKeepSpawnLoaded(spongeDataView.getInt(KEEP_SPAWN_LOADED).map(v -> v > 0).orElse(properties.getDimensionType().doesKeepSpawnLoaded()));
spongeDataView.getInt(LOAD_ON_STARTUP).ifPresent(v -> worldConfig.setKeepSpawnLoaded(v > 0));
spongeDataView.getStringList(GENERATOR_MODIFIERS).ifPresent(v -> {
final List<String> modifiers = worldConfig.getGeneration().getGenerationModifiers();
modifiers.clear();
modifiers.addAll(v);
properties.updateWorldGenModifiers(modifiers);
});
} else {
final LanternDimensionType dimensionType = properties.getDimensionType();
worldConfig.setKeepSpawnLoaded(dimensionType.doesKeepSpawnLoaded());
worldConfig.setDoesWaterEvaporate(dimensionType.doesWaterEvaporate());
}
}
return properties;
}
use of org.spongepowered.api.data.DataQuery in project Nucleus by NucleusPowered.
the class NucleusItemStackSnapshotSerialiser method serialize.
@Override
public void serialize(TypeToken<?> type, NucleusItemStackSnapshot obj, ConfigurationNode value) throws ObjectMappingException {
DataContainer view = obj.getSnapshot().toContainer();
Map<DataQuery, Object> dataQueryObjectMap = view.getValues(true);
for (Map.Entry<DataQuery, Object> entry : dataQueryObjectMap.entrySet()) {
if (entry.getValue().getClass().isArray()) {
// Convert to a list with type, make it the key.
if (entry.getValue().getClass().getComponentType().isPrimitive()) {
// Create the list of the primitive type.
DataQuery old = entry.getKey();
Tuple<DataQuery, List<?>> dqo = TypeHelper.getList(old, entry.getValue());
view.remove(old);
view.set(dqo.getFirst(), dqo.getSecond());
} else {
// create a list type
view.set(entry.getKey(), Lists.newArrayList((Object[]) entry.getValue()));
}
}
}
value.setValue(DataTranslators.CONFIGURATION_NODE.translate(view));
}
Aggregations