Search in sources :

Example 56 with DataContainer

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

the class LanternLoadingTicketIO method load.

static Multimap<String, LanternLoadingTicket> load(Path worldFolder, LanternChunkManager chunkManager, LanternChunkTicketManager service) throws IOException {
    final Multimap<String, LanternLoadingTicket> tickets = HashMultimap.create();
    final Path file = worldFolder.resolve(TICKETS_FILE);
    if (!Files.exists(file)) {
        return tickets;
    }
    final DataContainer dataContainer = NbtStreamUtils.read(Files.newInputStream(file), true);
    final Set<String> callbacks = service.getCallbacks().keySet();
    final List<DataView> ticketHolders = dataContainer.getViewList(HOLDER_LIST).get();
    for (DataView ticketHolder : ticketHolders) {
        final String holderName = ticketHolder.getString(HOLDER_NAME).get();
        if (!Sponge.getPluginManager().isLoaded(holderName)) {
            Lantern.getLogger().warn("Found chunk loading data for plugin {} which is currently not available or active" + " - it will be removed from the world save", holderName);
            continue;
        }
        if (!callbacks.contains(holderName)) {
            Lantern.getLogger().warn("The plugin {} has registered persistent chunk loading data but doesn't seem" + " to want to be called back with it - it will be removed from the world save", holderName);
            continue;
        }
        final int maxNumChunks = chunkManager.getMaxChunksForPluginTicket(holderName);
        final List<DataView> ticketEntries = ticketHolder.getViewList(TICKETS).get();
        for (DataView ticketEntry : ticketEntries) {
            final int type = ticketEntry.getInt(TICKET_TYPE).get();
            UUID playerUUID = null;
            if (ticketEntry.contains(PLAYER_UUID)) {
                playerUUID = UUID.fromString(ticketEntry.getString(PLAYER_UUID).get());
            }
            int numChunks = maxNumChunks;
            if (ticketEntry.contains(CHUNK_NUMBER)) {
                numChunks = ticketEntry.getInt(CHUNK_NUMBER).get();
            } else if (ticketEntry.contains(CHUNK_LIST_DEPTH)) {
                numChunks = ticketEntry.getInt(CHUNK_LIST_DEPTH).get();
            }
            final LanternLoadingTicket ticket;
            if (type == TYPE_NORMAL) {
                if (playerUUID != null) {
                    ticket = new LanternPlayerLoadingTicket(holderName, chunkManager, playerUUID, maxNumChunks, numChunks);
                } else {
                    ticket = new LanternLoadingTicket(holderName, chunkManager, maxNumChunks, numChunks);
                }
            } else if (type == TYPE_ENTITY) {
                final LanternEntityLoadingTicket ticket0;
                if (playerUUID != null) {
                    ticket0 = new LanternPlayerEntityLoadingTicket(holderName, chunkManager, playerUUID, maxNumChunks, numChunks);
                } else {
                    ticket0 = new LanternEntityLoadingTicket(holderName, chunkManager, maxNumChunks, numChunks);
                }
                final int chunkX = ticketEntry.getInt(CHUNK_X).get();
                final int chunkZ = ticketEntry.getInt(CHUNK_Z).get();
                final long uuidMost = ticketEntry.getLong(ENTITY_UUID_MOST).get();
                final long uuidLeast = ticketEntry.getLong(ENTITY_UUID_LEAST).get();
                final Vector2i chunkCoords = new Vector2i(chunkX, chunkZ);
                final UUID uuid = new UUID(uuidMost, uuidLeast);
                ticket0.setEntityReference(new EntityReference(chunkCoords, uuid));
                ticket = ticket0;
            } else {
                Lantern.getLogger().warn("Unknown ticket entry type {} for {}, skipping...", type, holderName);
                continue;
            }
            if (ticketEntry.contains(MOD_DATA)) {
                ticket.extraData = ticketEntry.getView(MOD_DATA).get().copy();
            }
            tickets.put(holderName, ticket);
            chunkManager.attach(ticket);
        }
    }
    return tickets;
}
Also used : Path(java.nio.file.Path) DataView(org.spongepowered.api.data.DataView) DataContainer(org.spongepowered.api.data.DataContainer) Vector2i(com.flowpowered.math.vector.Vector2i) UUID(java.util.UUID)

Example 57 with DataContainer

use of org.spongepowered.api.data.DataContainer in project Nucleus by NucleusPowered.

the class CreateWorldCommand method onImport.

private void onImport(Path world, String name) {
    // Get the file
    Path level = world.resolve("level.dat");
    Path levelSponge = world.resolve("level_sponge.dat");
    if (Files.exists(level)) {
        DataContainer dc;
        boolean gz = false;
        try {
            try (InputStream is = Files.newInputStream(level, StandardOpenOption.READ)) {
                // Open it, get the Dimension ID
                dc = DataFormats.NBT.readFrom(is);
            } catch (EOFException ex) {
                try (GZIPInputStream gzip = new GZIPInputStream(Files.newInputStream(level, StandardOpenOption.READ))) {
                    dc = DataFormats.NBT.readFrom(gzip);
                    gz = true;
                }
            }
            Files.copy(level, world.resolve("level.dat.nbak"), StandardCopyOption.REPLACE_EXISTING);
            dc.set(this.levelName, name);
            try (OutputStream os = getOutput(gz, level)) {
                DataFormats.NBT.writeTo(os, dc);
                os.flush();
            }
        } catch (IOException e) {
            if (Nucleus.getNucleus().isDebugMode()) {
                e.printStackTrace();
            }
            Nucleus.getNucleus().getLogger().warn("Could not read the level.dat. Ignoring.");
        }
    }
    if (Files.exists(levelSponge)) {
        DataContainer dc;
        boolean gz = false;
        try {
            try (InputStream is = Files.newInputStream(levelSponge, StandardOpenOption.READ)) {
                // Open it, get the Dimension ID
                dc = DataFormats.NBT.readFrom(is);
            } catch (EOFException ex) {
                try (GZIPInputStream gzip = new GZIPInputStream(Files.newInputStream(levelSponge, StandardOpenOption.READ))) {
                    dc = DataFormats.NBT.readFrom(gzip);
                    gz = true;
                }
            }
        } catch (IOException e) {
            if (Nucleus.getNucleus().isDebugMode()) {
                e.printStackTrace();
            }
            Nucleus.getNucleus().getLogger().warn("Could not read the level_sponge.dat. Ignoring.");
            return;
        }
        // For each world, get the dim ID.
        Set<Integer> si = Sponge.getServer().getAllWorldProperties().stream().map(x -> x.getAdditionalProperties().getInt(this.toId).orElse(0)).collect(Collectors.toSet());
        if (!dc.getInt(this.toId).map(si::contains).orElse(false)) {
            for (int i = 2; i < Integer.MAX_VALUE; i++) {
                if (!si.contains(i)) {
                    dc.set(this.toId, i);
                    break;
                }
            }
        }
        UUID uuid = UUID.randomUUID();
        dc.set(this.uuidLeast, uuid.getLeastSignificantBits());
        dc.set(this.uuidMost, uuid.getMostSignificantBits());
        try {
            Files.copy(levelSponge, world.resolve("level_sponge.dat.nbak"), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            if (Nucleus.getNucleus().isDebugMode()) {
                e.printStackTrace();
            }
            Nucleus.getNucleus().getLogger().warn("Could not backup the level_sponge.dat. Ignoring.");
            return;
        }
        try (OutputStream os = getOutput(gz, levelSponge)) {
            DataFormats.NBT.writeTo(os, dc);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            Nucleus.getNucleus().getLogger().warn("Could not save the level_sponge.dat. Ignoring.");
        }
    }
}
Also used : Path(java.nio.file.Path) GZIPInputStream(java.util.zip.GZIPInputStream) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) DimensionType(org.spongepowered.api.world.DimensionType) GenericArguments(org.spongepowered.api.command.args.GenericArguments) ImprovedGameModeArgument(io.github.nucleuspowered.nucleus.argumentparsers.ImprovedGameModeArgument) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Difficulties(org.spongepowered.api.world.difficulty.Difficulties) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) WorldGeneratorModifier(org.spongepowered.api.world.gen.WorldGeneratorModifier) Path(java.nio.file.Path) CommandSource(org.spongepowered.api.command.CommandSource) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) UUID(java.util.UUID) CommandElement(org.spongepowered.api.command.args.CommandElement) EOFException(java.io.EOFException) Collectors(java.util.stream.Collectors) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) World(org.spongepowered.api.world.World) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Optional(java.util.Optional) GZIPOutputStream(java.util.zip.GZIPOutputStream) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) HashMap(java.util.HashMap) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) DataQuery(org.spongepowered.api.data.DataQuery) GameModes(org.spongepowered.api.entity.living.player.gamemode.GameModes) StandardCopyOption(java.nio.file.StandardCopyOption) WorldArchetype(org.spongepowered.api.world.WorldArchetype) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) DataFormats(org.spongepowered.api.data.persistence.DataFormats) CatalogTypes(org.spongepowered.api.CatalogTypes) DimensionTypes(org.spongepowered.api.world.DimensionTypes) Nullable(javax.annotation.Nullable) ImprovedCatalogTypeArgument(io.github.nucleuspowered.nucleus.argumentparsers.ImprovedCatalogTypeArgument) GeneratorTypes(org.spongepowered.api.world.GeneratorTypes) OutputStream(java.io.OutputStream) CommandResult(org.spongepowered.api.command.CommandResult) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) Files(java.nio.file.Files) GeneratorType(org.spongepowered.api.world.GeneratorType) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) IOException(java.io.IOException) WorldConfigAdapter(io.github.nucleuspowered.nucleus.modules.world.config.WorldConfigAdapter) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) DifficultyArgument(io.github.nucleuspowered.nucleus.argumentparsers.DifficultyArgument) Difficulty(org.spongepowered.api.world.difficulty.Difficulty) InputStream(java.io.InputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) DataContainer(org.spongepowered.api.data.DataContainer) EOFException(java.io.EOFException) UUID(java.util.UUID)

Example 58 with DataContainer

use of org.spongepowered.api.data.DataContainer 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));
}
Also used : DataContainer(org.spongepowered.api.data.DataContainer) DataQuery(org.spongepowered.api.data.DataQuery) List(java.util.List) Map(java.util.Map)

Example 59 with DataContainer

use of org.spongepowered.api.data.DataContainer in project Nucleus by NucleusPowered.

the class NucleusItemStackSnapshotSerialiser method deserialize.

@Override
public NucleusItemStackSnapshot deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
    // Process enchantments, temporary fix before Sponge gets a more general fix in.
    boolean emptyEnchant = false;
    ConfigurationNode ench = value.getNode("UnsafeData", "ench");
    if (!ench.isVirtual()) {
        List<? extends ConfigurationNode> enchantments = ench.getChildrenList();
        if (enchantments.isEmpty()) {
            // Remove empty enchantment list.
            value.getNode("UnsafeData").removeChild("ench");
        } else {
            enchantments.forEach(x -> {
                try {
                    short id = Short.parseShort(x.getNode("id").getString());
                    short lvl = Short.parseShort(x.getNode("lvl").getString());
                    x.getNode("id").setValue(id);
                    x.getNode("lvl").setValue(lvl);
                } catch (NumberFormatException e) {
                    x.setValue(null);
                }
            });
        }
    }
    ConfigurationNode data = value.getNode("Data");
    if (!data.isVirtual() && data.hasListChildren()) {
        List<? extends ConfigurationNode> n = data.getChildrenList().stream().filter(x -> !x.getNode("DataClass").getString("").endsWith("SpongeEnchantmentData") || (!x.getNode("ManipulatorData", "ItemEnchantments").isVirtual() && x.getNode("ManipulatorData", "ItemEnchantments").hasListChildren())).collect(Collectors.toList());
        emptyEnchant = n.size() != data.getChildrenList().size();
        if (emptyEnchant) {
            if (n.isEmpty()) {
                value.removeChild("Data");
            } else {
                value.getNode("Data").setValue(n);
            }
        }
    }
    DataContainer dataContainer = DataTranslators.CONFIGURATION_NODE.translate(value);
    Set<DataQuery> ldq = dataContainer.getKeys(true);
    for (DataQuery dataQuery : ldq) {
        String el = dataQuery.asString(".");
        if (el.contains("$Array$")) {
            try {
                Tuple<DataQuery, Object> r = TypeHelper.getArray(dataQuery, dataContainer);
                dataContainer.set(r.getFirst(), r.getSecond());
            } catch (Exception e) {
                e.printStackTrace();
            }
            dataContainer.remove(dataQuery);
        }
    }
    ItemStack snapshot;
    try {
        snapshot = ItemStack.builder().fromContainer(dataContainer).build();
    } catch (Exception e) {
        return NucleusItemStackSnapshot.NONE;
    }
    if (emptyEnchant) {
        snapshot.offer(Keys.ITEM_ENCHANTMENTS, Lists.newArrayList());
        return new NucleusItemStackSnapshot(snapshot.createSnapshot());
    }
    if (snapshot.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
        // Reset the data.
        snapshot.offer(Keys.ITEM_ENCHANTMENTS, snapshot.get(Keys.ITEM_ENCHANTMENTS).get());
        return new NucleusItemStackSnapshot(snapshot.createSnapshot());
    }
    return new NucleusItemStackSnapshot(snapshot.createSnapshot());
}
Also used : TypeHelper(io.github.nucleuspowered.nucleus.util.TypeHelper) Keys(org.spongepowered.api.data.key.Keys) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) TypeToken(com.google.common.reflect.TypeToken) NucleusItemStackSnapshot(io.github.nucleuspowered.nucleus.configurate.wrappers.NucleusItemStackSnapshot) Tuple(org.spongepowered.api.util.Tuple) TypeSerializer(ninja.leaping.configurate.objectmapping.serialize.TypeSerializer) DataQuery(org.spongepowered.api.data.DataQuery) Collectors(java.util.stream.Collectors) ItemStack(org.spongepowered.api.item.inventory.ItemStack) List(java.util.List) Lists(com.google.common.collect.Lists) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) DataTranslators(org.spongepowered.api.data.persistence.DataTranslators) Map(java.util.Map) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) NucleusItemStackSnapshot(io.github.nucleuspowered.nucleus.configurate.wrappers.NucleusItemStackSnapshot) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) DataContainer(org.spongepowered.api.data.DataContainer) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) DataQuery(org.spongepowered.api.data.DataQuery) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 60 with DataContainer

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

the class MixinGameProfile method profile$toContainer.

public DataContainer profile$toContainer() {
    final DataContainer container = DataContainer.createNew();
    container.set(DataQueries.CONTENT_VERSION, this.profile$getContentVersion());
    container.set(DataQueries.USER_UUID, this.profile$getUniqueId().toString());
    if (this.profile$getName().isPresent()) {
        container.set(DataQueries.USER_NAME, this.profile$getName().get());
    }
    return container;
}
Also used : DataContainer(org.spongepowered.api.data.DataContainer)

Aggregations

DataContainer (org.spongepowered.api.data.DataContainer)110 DataView (org.spongepowered.api.data.DataView)30 DataQuery (org.spongepowered.api.data.DataQuery)28 Test (org.junit.Test)24 List (java.util.List)15 Map (java.util.Map)15 ArrayList (java.util.ArrayList)13 Nullable (javax.annotation.Nullable)11 Collection (java.util.Collection)10 ImmutableList (com.google.common.collect.ImmutableList)9 ImmutableMap (com.google.common.collect.ImmutableMap)9 IOException (java.io.IOException)9 Path (java.nio.file.Path)9 Optional (java.util.Optional)9 CatalogType (org.spongepowered.api.CatalogType)9 Sponge (org.spongepowered.api.Sponge)8 Set (java.util.Set)7 Collectors (java.util.stream.Collectors)7 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)7 DataSerializable (org.spongepowered.api.data.DataSerializable)7