Search in sources :

Example 31 with DataContainer

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

the class CopyPasta method onGamePreInitialization.

@Listener
public void onGamePreInitialization(GamePreInitializationEvent event) {
    this.schematicsDir = new File(this.config, "schematics");
    this.schematicsDir.mkdirs();
    this.logger.info("Saving schematics to " + this.schematicsDir.getAbsolutePath());
    Sponge.getCommandManager().register(this, CommandSpec.builder().description(Text.of("Copies a region of the world to your clipboard")).permission(PLUGIN_ID + ".command.copy").executor((src, args) -> {
        if (!(src instanceof Player)) {
            src.sendMessage(Text.of(TextColors.RED, "Player only."));
            return CommandResult.success();
        }
        Player player = (Player) src;
        PlayerData data = get(player);
        if (data.getPos1() == null || data.getPos2() == null) {
            player.sendMessage(Text.of(TextColors.RED, "You must set both positions before copying"));
            return CommandResult.success();
        }
        Vector3i min = data.getPos1().min(data.getPos2());
        Vector3i max = data.getPos1().max(data.getPos2());
        ArchetypeVolume volume = player.getWorld().createArchetypeVolume(min, max, player.getLocation().getPosition().toInt());
        data.setClipboard(volume);
        player.sendMessage(Text.of(TextColors.GREEN, "Saved to clipboard."));
        return CommandResult.success();
    }).build(), "copy");
    Sponge.getCommandManager().register(this, CommandSpec.builder().description(Text.of("Pastes your clipboard at your current position")).permission(PLUGIN_ID + ".command.paste").executor((src, args) -> {
        if (!(src instanceof Player)) {
            src.sendMessage(Text.of(TextColors.RED, "Player only."));
            return CommandResult.success();
        }
        Player player = (Player) src;
        PlayerData data = get(player);
        ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Text.of(TextColors.RED, "You must copy something before pasting"));
            return CommandResult.success();
        }
        Sponge.getCauseStackManager().pushCause(this);
        volume.apply(player.getLocation(), BlockChangeFlags.ALL);
        Sponge.getCauseStackManager().popCause();
        player.sendMessage(Text.of(TextColors.GREEN, "Pasted clipboard into world."));
        return CommandResult.success();
    }).build(), "paste");
    Sponge.getCommandManager().register(this, CommandSpec.builder().description(Text.of("Saves your clipboard to disk")).permission(PLUGIN_ID + ".command.save").arguments(seq(string(Text.of("format")), string(Text.of("name")))).executor((src, args) -> {
        if (!(src instanceof Player)) {
            src.sendMessage(Text.of(TextColors.RED, "Player only."));
            return CommandResult.success();
        }
        String format = args.getOne("format").get().toString();
        String name = args.getOne("name").get().toString();
        Player player = (Player) src;
        PlayerData data = get(player);
        ArchetypeVolume volume = data.getClipboard();
        if (volume == null) {
            player.sendMessage(Text.of(TextColors.RED, "You must copy something before saving"));
            return CommandResult.success();
        }
        if (!"legacy".equalsIgnoreCase(format) && !"sponge".equalsIgnoreCase(format)) {
            player.sendMessage(Text.of(TextColors.RED, "Unsupported schematic format, supported formats are [legacy, sponge]"));
            return CommandResult.success();
        }
        Schematic schematic = Schematic.builder().volume(data.getClipboard()).metaValue(Schematic.METADATA_AUTHOR, player.getName()).metaValue(Schematic.METADATA_NAME, name).paletteType(BlockPaletteTypes.LOCAL).build();
        DataContainer schematicData = null;
        if ("legacy".equalsIgnoreCase(format)) {
            schematicData = DataTranslators.LEGACY_SCHEMATIC.translate(schematic);
        } else if ("sponge".equalsIgnoreCase(format)) {
            schematicData = DataTranslators.SCHEMATIC.translate(schematic);
        }
        File outputFile = new File(this.schematicsDir, name + ".schematic");
        try {
            DataFormats.NBT.writeTo(new GZIPOutputStream(new FileOutputStream(outputFile)), schematicData);
            player.sendMessage(Text.of(TextColors.GREEN, "Saved schematic to " + outputFile.getAbsolutePath()));
        } catch (Exception e) {
            e.printStackTrace();
            player.sendMessage(Text.of(TextColors.DARK_RED, "Error saving schematic: " + e.getMessage()));
            return CommandResult.success();
        }
        return CommandResult.success();
    }).build(), "save");
    Sponge.getCommandManager().register(this, CommandSpec.builder().description(Text.of("Loads a schematic from disk to your clipboard")).permission(PLUGIN_ID + ".command.load").arguments(seq(string(Text.of("format")), string(Text.of("name")))).executor((src, args) -> {
        if (!(src instanceof Player)) {
            src.sendMessage(Text.of(TextColors.RED, "Player only."));
            return CommandResult.success();
        }
        String format = args.getOne("format").get().toString();
        String name = args.getOne("name").get().toString();
        Player player = (Player) src;
        PlayerData data = get(player);
        if (!"legacy".equalsIgnoreCase(format) && !"sponge".equalsIgnoreCase(format)) {
            player.sendMessage(Text.of(TextColors.RED, "Unsupported schematic format, supported formats are [legacy, sponge]"));
            return CommandResult.success();
        }
        File inputFile = new File(this.schematicsDir, name + ".schematic");
        if (!inputFile.exists()) {
            player.sendMessage(Text.of(TextColors.RED, "Schematic at " + inputFile.getAbsolutePath() + " not found."));
            return CommandResult.success();
        }
        DataContainer schematicData = null;
        try {
            schematicData = DataFormats.NBT.readFrom(new GZIPInputStream(new FileInputStream(inputFile)));
        } catch (Exception e) {
            e.printStackTrace();
            player.sendMessage(Text.of(TextColors.DARK_RED, "Error loading schematic: " + e.getMessage()));
            return CommandResult.success();
        }
        Schematic schematic = null;
        if ("legacy".equalsIgnoreCase(format)) {
            schematic = DataTranslators.LEGACY_SCHEMATIC.translate(schematicData);
        } else if ("sponge".equalsIgnoreCase(format)) {
            schematic = DataTranslators.SCHEMATIC.translate(schematicData);
        }
        player.sendMessage(Text.of(TextColors.GREEN, "Loaded schematic from " + inputFile.getAbsolutePath()));
        data.setClipboard(schematic);
        return CommandResult.success();
    }).build(), "load");
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) FileInputStream(java.io.FileInputStream) ArchetypeVolume(org.spongepowered.api.world.extent.ArchetypeVolume) GZIPInputStream(java.util.zip.GZIPInputStream) DataContainer(org.spongepowered.api.data.DataContainer) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) Vector3i(com.flowpowered.math.vector.Vector3i) File(java.io.File) Schematic(org.spongepowered.api.world.schematic.Schematic) Listener(org.spongepowered.api.event.Listener)

Example 32 with DataContainer

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

the class ImmutableHomeDataImpl method toContainer.

@Override
public DataContainer toContainer() {
    DataContainer container = super.toContainer();
    // This is the simplest, but use whatever structure you want!
    if (this.defaultHome != null) {
        container.set(MyHomes.DEFAULT_HOME, this.defaultHome);
    }
    container.set(MyHomes.HOMES, this.homes);
    return container;
}
Also used : DataContainer(org.spongepowered.api.data.DataContainer)

Example 33 with DataContainer

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

the class MemoryDataView method copy.

@Override
public DataContainer copy() {
    final DataContainer container = new MemoryDataContainer(this.safety);
    getKeys(false).forEach(query -> get(query).ifPresent(obj -> container.set(query, obj)));
    return container;
}
Also used : DataManager(org.spongepowered.api.data.DataManager) Arrays(java.util.Arrays) ArrayUtils(org.apache.commons.lang3.ArrayUtils) 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) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Lists(com.google.common.collect.Lists) 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) Maps(com.google.common.collect.Maps) 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) Coerce(org.spongepowered.api.util.Coerce) DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) Optional(java.util.Optional) DataContainer(org.spongepowered.api.data.DataContainer)

Example 34 with DataContainer

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

the class MemoryDataView method copy.

@Override
public DataContainer copy(SafetyMode safety) {
    final DataContainer container = new MemoryDataContainer(safety);
    getKeys(false).forEach(query -> get(query).ifPresent(obj -> container.set(query, obj)));
    return container;
}
Also used : DataManager(org.spongepowered.api.data.DataManager) Arrays(java.util.Arrays) ArrayUtils(org.apache.commons.lang3.ArrayUtils) 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) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Lists(com.google.common.collect.Lists) 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) Maps(com.google.common.collect.Maps) 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) Coerce(org.spongepowered.api.util.Coerce) DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) Optional(java.util.Optional) DataContainer(org.spongepowered.api.data.DataContainer)

Example 35 with DataContainer

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

the class MemoryDataView method setCollection.

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCollection(String key, Collection<?> value) {
    ImmutableList.Builder<Object> builder = ImmutableList.builder();
    @Nullable DataManager manager;
    try {
        manager = Sponge.getDataManager();
    } catch (Exception e) {
        manager = null;
    }
    for (Object object : value) {
        if (object instanceof DataSerializable) {
            builder.add(((DataSerializable) object).toContainer());
        } else if (object instanceof DataView) {
            if (this.safety == SafetyMode.ALL_DATA_CLONED || this.safety == SafetyMode.CLONED_ON_SET) {
                MemoryDataView view = new MemoryDataContainer(this.safety);
                DataView internalView = (DataView) object;
                for (Map.Entry<DataQuery, Object> entry : internalView.getValues(false).entrySet()) {
                    view.set(entry.getKey(), entry.getValue());
                }
                builder.add(view);
            } else {
                builder.add(object);
            }
        } else if (object instanceof CatalogType) {
            builder.add(((CatalogType) object).getId());
        } else if (object instanceof Map) {
            builder.add(ensureSerialization((Map) object));
        } else if (object instanceof Collection) {
            builder.add(ensureSerialization((Collection) object));
        } else {
            if (manager != null) {
                final Optional<? extends DataTranslator<?>> translatorOptional = manager.getTranslator(object.getClass());
                if (translatorOptional.isPresent()) {
                    DataTranslator translator = translatorOptional.get();
                    final DataContainer container = translator.translate(object);
                    checkArgument(!container.equals(this), "Cannot insert self-referencing Objects!");
                    builder.add(container);
                } else {
                    builder.add(object);
                }
            } else {
                builder.add(object);
            }
        }
    }
    this.map.put(key, builder.build());
}
Also used : DataTranslator(org.spongepowered.api.data.persistence.DataTranslator) ImmutableList(com.google.common.collect.ImmutableList) DataManager(org.spongepowered.api.data.DataManager) DataSerializable(org.spongepowered.api.data.DataSerializable) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) DataContainer(org.spongepowered.api.data.DataContainer) Collection(java.util.Collection) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Nullable(javax.annotation.Nullable)

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