Search in sources :

Example 36 with DataQuery

use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.

the class MemoryDataView method getObjectList.

@SuppressWarnings("unchecked")
@Override
public <T> Optional<List<T>> getObjectList(DataQuery path, Class<T> objectClass) {
    return getList(path).flatMap(list -> {
        final TypeToken<T> typeToken = TypeToken.of(objectClass);
        final LanternDataManager dataManager = Lantern.getGame().getDataManager();
        final DataTypeSerializer serializer = dataManager.getTypeSerializer(typeToken).orElse(null);
        if (serializer == null) {
            return Optional.empty();
        }
        return (Optional) Optional.of(list.stream().map(object -> serializer.deserialize(typeToken, dataManager.getTypeSerializerContext(), object)).collect(Collectors.toList()));
    });
}
Also used : Arrays(java.util.Arrays) ArrayUtils(org.apache.commons.lang3.ArrayUtils) TypeToken(com.google.common.reflect.TypeToken) DataQuery(org.spongepowered.api.data.DataQuery) Supplier(java.util.function.Supplier) Key(org.spongepowered.api.data.key.Key) ArrayList(java.util.ArrayList) DataSerializable(org.spongepowered.api.data.DataSerializable) LinkedHashMap(java.util.LinkedHashMap) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Lists(com.google.common.collect.Lists) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Objects(com.google.common.base.Objects) Nullable(javax.annotation.Nullable) ImmutableSet(com.google.common.collect.ImmutableSet) DataQuery.of(org.spongepowered.api.data.DataQuery.of) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) BaseValue(org.spongepowered.api.data.value.BaseValue) MoreObjects(com.google.common.base.MoreObjects) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Stream(java.util.stream.Stream) DataView(org.spongepowered.api.data.DataView) Lantern(org.lanternpowered.server.game.Lantern) Coerce(org.spongepowered.api.util.Coerce) Optional(java.util.Optional) Optional(java.util.Optional) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer)

Example 37 with DataQuery

use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.

the class MemoryDataView method remove.

@Override
public DataView remove(DataQuery path) {
    checkNotNull(path, "path");
    final List<String> parts = path.getParts();
    if (parts.size() > 1) {
        final String subKey = parts.get(0);
        final DataQuery subQuery = of(subKey);
        final Optional<DataView> subViewOptional = 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.DataView) DataQuery(org.spongepowered.api.data.DataQuery)

Example 38 with DataQuery

use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.

the class ScoreboardIO method read.

public static Scoreboard read(Path worldFolder) throws IOException {
    DataView dataView = IOHelper.<DataView>read(worldFolder.resolve(SCOREBOARD_DATA), file -> {
        try {
            return NbtStreamUtils.read(Files.newInputStream(file), true);
        } catch (IOException e) {
            throw new IOException("Unable to access " + file.getFileName() + "!", e);
        }
    }).orElse(null);
    final Scoreboard.Builder scoreboardBuilder = Scoreboard.builder();
    if (dataView == null) {
        return scoreboardBuilder.build();
    }
    final Map<String, Objective> objectives = new HashMap<>();
    dataView = dataView.getView(DATA).orElseThrow(() -> new IllegalStateException("Unable to find the data compound."));
    dataView.getViewList(OBJECTIVES).ifPresent(list -> list.forEach(entry -> {
        final String name = entry.getString(NAME).get();
        final Text displayName = LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get());
        final Criterion criterion = Sponge.getRegistry().getType(Criterion.class, entry.getString(CRITERION_NAME).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a criterion with id: {}, default to dummy.", entry.getString(CRITERION_NAME).get());
            return Criteria.DUMMY;
        });
        final ObjectiveDisplayMode objectiveDisplayMode = Sponge.getRegistry().getType(ObjectiveDisplayMode.class, entry.getString(DISPLAY_MODE).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a display mode with id: {}, default to integer.", entry.getString(CRITERION_NAME).get());
            return ObjectiveDisplayModes.INTEGER;
        });
        objectives.put(name, Objective.builder().name(name).displayName(displayName).criterion(criterion).objectiveDisplayMode(objectiveDisplayMode).build());
    }));
    dataView.getViewList(SCORES).ifPresent(list -> list.forEach(entry -> {
        // We have to keep all the entries to remain compatible with vanilla mc.
        if (entry.getInt(INVALID).orElse(0) > 0) {
            return;
        }
        final Text name = LanternTexts.fromLegacy(entry.getString(NAME).get());
        final int value = entry.getInt(SCORE).get();
        // TODO
        final boolean locked = entry.getInt(LOCKED).orElse(0) > 0;
        final String objectiveName = entry.getString(OBJECTIVE).get();
        Score score = null;
        Objective objective = objectives.get(objectiveName);
        if (objective != null) {
            score = addToObjective(objective, null, name, value);
        }
        final List<String> extraObjectives = entry.getStringList(EXTRA_OBJECTIVES).orElse(null);
        if (extraObjectives != null) {
            for (String extraObjective : extraObjectives) {
                objective = objectives.get(extraObjective);
                if (objective != null) {
                    score = addToObjective(objective, score, name, value);
                }
            }
        }
    }));
    final List<Team> teams = new ArrayList<>();
    dataView.getViewList(TEAMS).ifPresent(list -> list.forEach(entry -> {
        final Team.Builder builder = Team.builder().allowFriendlyFire(entry.getInt(ALLOW_FRIENDLY_FIRE).orElse(0) > 0).canSeeFriendlyInvisibles(entry.getInt(CAN_SEE_FRIENDLY_INVISIBLES).orElse(0) > 0).name(entry.getString(NAME).get()).displayName(LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get())).prefix(LanternTexts.fromLegacy(entry.getString(PREFIX).get())).suffix(LanternTexts.fromLegacy(entry.getString(SUFFIX).get())).members(entry.getStringList(MEMBERS).get().stream().map(LanternTexts::fromLegacy).collect(Collectors.toSet()));
        entry.getString(NAME_TAG_VISIBILITY).ifPresent(value -> builder.nameTagVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a name tag visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(DEATH_MESSAGE_VISIBILITY).ifPresent(value -> builder.deathTextVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a death message visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(COLLISION_RULE).ifPresent(value -> builder.collisionRule(Sponge.getRegistry().getAllOf(CollisionRule.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a collision rule with id: {}, default to never.", value);
            return CollisionRules.NEVER;
        })));
        entry.getString(TEAM_COLOR).ifPresent(color -> {
            TextColor textColor = Sponge.getRegistry().getType(TextColor.class, color).orElseGet(() -> {
                Lantern.getLogger().warn("Unable to find a team color with id: {}, default to none.", color);
                return TextColors.NONE;
            });
            if (textColor != TextColors.NONE && textColor != TextColors.RESET) {
                builder.color(textColor);
            }
        });
        teams.add(builder.build());
    }));
    final Scoreboard scoreboard = scoreboardBuilder.objectives(new ArrayList<>(objectives.values())).teams(teams).build();
    dataView.getView(DISPLAY_SLOTS).ifPresent(displaySlots -> {
        for (DataQuery key : displaySlots.getKeys(false)) {
            final Matcher matcher = DISPLAY_SLOT_PATTERN.matcher(key.getParts().get(0));
            if (matcher.matches()) {
                final int internalId = Integer.parseInt(matcher.group(1));
                Lantern.getRegistry().getRegistryModule(DisplaySlotRegistryModule.class).get().getByInternalId(internalId).ifPresent(slot -> {
                    final Objective objective = objectives.get(displaySlots.getString(key).get());
                    if (objective != null) {
                        scoreboard.updateDisplaySlot(objective, slot);
                    }
                });
            }
        }
    });
    return scoreboard;
}
Also used : CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Visibility(org.spongepowered.api.scoreboard.Visibility) HashMap(java.util.HashMap) LanternTexts(org.lanternpowered.server.text.LanternTexts) DataQuery(org.spongepowered.api.data.DataQuery) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) ArrayList(java.util.ArrayList) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) NbtStreamUtils(org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Objective(org.spongepowered.api.scoreboard.objective.Objective) TextColors(org.spongepowered.api.text.format.TextColors) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Iterator(java.util.Iterator) Files(java.nio.file.Files) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Visibilities(org.spongepowered.api.scoreboard.Visibilities) Set(java.util.Set) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) IOException(java.io.IOException) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) Score(org.spongepowered.api.scoreboard.Score) Criteria(org.spongepowered.api.scoreboard.critieria.Criteria) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) DataView(org.spongepowered.api.data.DataView) CollisionRules(org.spongepowered.api.scoreboard.CollisionRules) Lantern(org.lanternpowered.server.game.Lantern) ObjectiveDisplayModes(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes) Pattern(java.util.regex.Pattern) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) ArrayList(java.util.ArrayList) List(java.util.List) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) DataQuery(org.spongepowered.api.data.DataQuery) TextColor(org.spongepowered.api.text.format.TextColor) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Text(org.spongepowered.api.text.Text) IOException(java.io.IOException) DataView(org.spongepowered.api.data.DataView) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Visibility(org.spongepowered.api.scoreboard.Visibility)

Example 39 with DataQuery

use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.

the class DataHelper method serializeRawRegisteredKeyData.

public static void serializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer, Set<Key> ignoredKeys) {
    DataView view = null;
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || ignoredKeys.contains(key) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Element element = (Element) registration;
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        final Object object = element.get();
        if (object == null) {
            continue;
        }
        final Object value = typeSerializer.serialize(typeToken, context, object);
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        view.set(key.getQuery(), value);
    }
    Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
    if (holder != null) {
        if (view == null) {
            view = dataView.createView(DataQueries.DATA_VALUES);
        }
        for (Map.Entry<DataQuery, Object> entry : holder.get().getValues(false).entrySet()) {
            if (!view.contains(entry.getKey())) {
                view.set(entry.getKey(), entry.getValue());
            }
        }
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Map(java.util.Map)

Example 40 with DataQuery

use of org.spongepowered.api.data.DataQuery in project LanternServer by LanternPowered.

the class DataHelper method deserializeRawRegisteredKeyData.

public static void deserializeRawRegisteredKeyData(DataView dataView, IValueContainer valueContainer) throws InvalidDataException {
    dataView = dataView.getView(DataQueries.DATA_VALUES).orElse(null);
    if (dataView == null) {
        return;
    }
    final ValueCollection valueCollection = valueContainer.getValueCollection();
    final LanternDataManager dataManager = Lantern.getGame().getDataManager();
    final DataTypeSerializerContext context = dataManager.getTypeSerializerContext();
    for (KeyRegistration<?, ?> registration : valueCollection.getAll()) {
        final Key<?> key = registration.getKey();
        if (!(registration instanceof Element) || key == LanternKeys.FAILED_DATA_MANIPULATORS || key == LanternKeys.FAILED_DATA_VALUES) {
            continue;
        }
        final Optional<Object> data = dataView.get(key.getQuery());
        if (!data.isPresent()) {
            continue;
        }
        dataView.remove(key.getQuery());
        final TypeToken<?> typeToken = key.getElementToken();
        final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
        ((Element) registration).set(typeSerializer.deserialize(typeToken, context, data.get()));
    }
    if (valueContainer instanceof CompositeValueStore) {
        final CompositeValueStore store = (CompositeValueStore) valueContainer;
        for (Map.Entry<DataQuery, Object> entry : dataView.getValues(false).entrySet()) {
            final Key<?> key = KeyRegistryModule.get().getByQuery(entry.getKey()).orElse(null);
            if (key == null) {
                continue;
            }
            final TypeToken<?> typeToken = key.getElementToken();
            final DataTypeSerializer typeSerializer = dataManager.getTypeSerializer(typeToken).orElseThrow(() -> new IllegalStateException("Wasn't able to find a type serializer for the element type: " + typeToken.toString()));
            store.offer(key, typeSerializer.deserialize(typeToken, context, entry.getValue()));
            dataView.remove(entry.getKey());
        }
    }
    if (!dataView.isEmpty()) {
        // Should be safe to cast, at least if nobody touches this key
        Element<DataView> holder = valueCollection.getElement(LanternKeys.FAILED_DATA_VALUES).orElse(null);
        if (holder == null) {
            holder = valueCollection.register(LanternKeys.FAILED_DATA_VALUES, null);
        }
        holder.set(dataView);
    }
}
Also used : DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) Element(org.lanternpowered.server.data.element.Element) DataView(org.spongepowered.api.data.DataView) DataQuery(org.spongepowered.api.data.DataQuery) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) CompositeValueStore(org.spongepowered.api.data.value.mutable.CompositeValueStore) Map(java.util.Map)

Aggregations

DataQuery (org.spongepowered.api.data.DataQuery)41 DataContainer (org.spongepowered.api.data.DataContainer)23 DataView (org.spongepowered.api.data.DataView)20 Test (org.junit.Test)14 Map (java.util.Map)12 ArrayList (java.util.ArrayList)7 List (java.util.List)7 DataTypeSerializer (org.lanternpowered.server.data.persistence.DataTypeSerializer)7 ImmutableMap (com.google.common.collect.ImmutableMap)4 TypeToken (com.google.common.reflect.TypeToken)4 Collection (java.util.Collection)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4 Nullable (javax.annotation.Nullable)4 CatalogType (org.spongepowered.api.CatalogType)4 DataSerializable (org.spongepowered.api.data.DataSerializable)4 Vector3i (com.flowpowered.math.vector.Vector3i)3 Lists (com.google.common.collect.Lists)3 LinkedHashMap (java.util.LinkedHashMap)3