Refactor of clipboard to separate out file saving/loading (#641)

* Refactor of clipboard to separate out file saving/loading

There's now a clipboard manager to handle file system loading and saving
so that the clipboard works purely in blocks (YAML).

* Fixes a few bugs

* Renamed getClipBoard to getClipboard
This commit is contained in:
tastybento 2019-04-28 04:41:24 -07:00 committed by Florian CUNY
parent 6100420bae
commit 8a885eac7f
15 changed files with 467 additions and 429 deletions

View File

@ -13,8 +13,8 @@ import org.bukkit.Particle;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.commands.ConfirmableCommand; import world.bentobox.bentobox.api.commands.ConfirmableCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.managers.SchemsManager; import world.bentobox.bentobox.managers.SchemsManager;
import world.bentobox.bentobox.schems.Clipboard;
public class AdminSchemCommand extends ConfirmableCommand { public class AdminSchemCommand extends ConfirmableCommand {
// Clipboards // Clipboards

View File

@ -4,7 +4,7 @@ import java.util.List;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
public class AdminSchemCopyCommand extends CompositeCommand { public class AdminSchemCopyCommand extends CompositeCommand {
@ -27,7 +27,7 @@ public class AdminSchemCopyCommand extends CompositeCommand {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
boolean copyAir = (args.size() == 1 && args.get(0).equalsIgnoreCase("air")); boolean copyAir = (args.size() == 1 && args.get(0).equalsIgnoreCase("air"));
return clipboard.copy(user, copyAir); return clipboard.copy(user, copyAir);
} }

View File

@ -6,7 +6,7 @@ import java.util.Optional;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.managers.ClipboardManager;
import world.bentobox.bentobox.util.Util; import world.bentobox.bentobox.util.Util;
public class AdminSchemLoadCommand extends CompositeCommand { public class AdminSchemLoadCommand extends CompositeCommand {
@ -30,9 +30,9 @@ public class AdminSchemLoadCommand extends CompositeCommand {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); ClipboardManager bp = new ClipboardManager(getPlugin(), parent.getSchemsFolder());
if (clipboard.load(user, args.get(0))) { if (bp.load(user, args.get(0))) {
parent.getClipboards().put(user.getUniqueId(), clipboard); parent.getClipboards().put(user.getUniqueId(), bp.getClipboard());
return true; return true;
} }

View File

@ -8,7 +8,7 @@ import org.bukkit.block.Block;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
public class AdminSchemOriginCommand extends CompositeCommand { public class AdminSchemOriginCommand extends CompositeCommand {
@ -26,7 +26,7 @@ public class AdminSchemOriginCommand extends CompositeCommand {
public boolean execute(User user, String label, List<String> args) { public boolean execute(User user, String label, List<String> args) {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
if (clipboard.getPos1() == null || clipboard.getPos2() == null) { if (clipboard.getPos1() == null || clipboard.getPos2() == null) {
user.sendMessage("commands.admin.schem.need-pos1-pos2"); user.sendMessage("commands.admin.schem.need-pos1-pos2");
return false; return false;

View File

@ -4,7 +4,8 @@ import java.util.List;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.blueprints.Paster;
public class AdminSchemPasteCommand extends CompositeCommand { public class AdminSchemPasteCommand extends CompositeCommand {
@ -21,11 +22,10 @@ public class AdminSchemPasteCommand extends CompositeCommand {
@Override @Override
public boolean execute(User user, String label, List<String> args) { public boolean execute(User user, String label, List<String> args) {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder()));
if (clipboard.isFull()) { if (clipboard.isFull()) {
clipboard.pasteClipboard(user.getLocation()); new Paster(getPlugin(), clipboard, user.getLocation(), () -> user.sendMessage("general.success"));
user.sendMessage("general.success"); user.sendMessage("commands.admin.schem.paste.pasting");
return true; return true;
} }

View File

@ -4,7 +4,7 @@ import java.util.List;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.util.Util; import world.bentobox.bentobox.util.Util;
public class AdminSchemPos1Command extends CompositeCommand { public class AdminSchemPos1Command extends CompositeCommand {
@ -22,7 +22,7 @@ public class AdminSchemPos1Command extends CompositeCommand {
@Override @Override
public boolean execute(User user, String label, List<String> args) { public boolean execute(User user, String label, List<String> args) {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
if (user.getLocation().equals(clipboard.getPos2())) { if (user.getLocation().equals(clipboard.getPos2())) {
user.sendMessage("commands.admin.schem.set-different-pos"); user.sendMessage("commands.admin.schem.set-different-pos");

View File

@ -4,7 +4,7 @@ import java.util.List;
import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.util.Util; import world.bentobox.bentobox.util.Util;
public class AdminSchemPos2Command extends CompositeCommand { public class AdminSchemPos2Command extends CompositeCommand {
@ -22,7 +22,7 @@ public class AdminSchemPos2Command extends CompositeCommand {
@Override @Override
public boolean execute(User user, String label, List<String> args) { public boolean execute(User user, String label, List<String> args) {
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
if (user.getLocation().equals(clipboard.getPos1())) { if (user.getLocation().equals(clipboard.getPos1())) {
user.sendMessage("commands.admin.schem.set-different-pos"); user.sendMessage("commands.admin.schem.set-different-pos");

View File

@ -5,7 +5,8 @@ import java.util.List;
import world.bentobox.bentobox.api.commands.ConfirmableCommand; import world.bentobox.bentobox.api.commands.ConfirmableCommand;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.schems.Clipboard; import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.managers.ClipboardManager;
public class AdminSchemSaveCommand extends ConfirmableCommand { public class AdminSchemSaveCommand extends ConfirmableCommand {
@ -27,7 +28,7 @@ public class AdminSchemSaveCommand extends ConfirmableCommand {
} }
AdminSchemCommand parent = (AdminSchemCommand) getParent(); AdminSchemCommand parent = (AdminSchemCommand) getParent();
Clipboard clipboard = parent.getClipboards().getOrDefault(user.getUniqueId(), new Clipboard(getPlugin(), parent.getSchemsFolder())); Clipboard clipboard = parent.getClipboards().computeIfAbsent(user.getUniqueId(), v -> new Clipboard());
if (clipboard.isFull()) { if (clipboard.isFull()) {
// Check if file exists // Check if file exists
@ -35,12 +36,12 @@ public class AdminSchemSaveCommand extends ConfirmableCommand {
if (newFile.exists()) { if (newFile.exists()) {
this.askConfirmation(user, user.getTranslation("commands.admin.schem.file-exists"), () -> { this.askConfirmation(user, user.getTranslation("commands.admin.schem.file-exists"), () -> {
parent.hideClipboard(user); parent.hideClipboard(user);
clipboard.save(user, args.get(0)); new ClipboardManager(getPlugin(), parent.getSchemsFolder(), clipboard).save(user, args.get(0));
}); });
return false; return false;
} else { } else {
parent.hideClipboard(user); parent.hideClipboard(user);
return clipboard.save(user, args.get(0)); return new ClipboardManager(getPlugin(), parent.getSchemsFolder(), clipboard).save(user, args.get(0));
} }
} else { } else {
user.sendMessage("commands.admin.schem.copy-first"); user.sendMessage("commands.admin.schem.copy-first");

View File

@ -1,20 +1,9 @@
package world.bentobox.bentobox.schems; package world.bentobox.bentobox.blueprints;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -38,12 +27,9 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Attachable; import org.bukkit.material.Attachable;
import org.bukkit.material.Colorable; import org.bukkit.material.Colorable;
import org.bukkit.util.BoundingBox; import org.bukkit.util.BoundingBox;
import org.bukkit.util.Vector;
import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island;
/** /**
* @author tastybento * @author tastybento
@ -56,66 +42,27 @@ public class Clipboard {
private static final String BLOCKS_YAML_PREFIX = "blocks."; private static final String BLOCKS_YAML_PREFIX = "blocks.";
private static final String BEDROCK = "bedrock"; private static final String BEDROCK = "bedrock";
private static final String COLOR = "color"; private static final String COLOR = "color";
private static final String LOAD_ERROR = "Could not load schems file - does not exist : ";
private static final String LINES = "lines"; private static final String LINES = "lines";
private YamlConfiguration blockConfig = new YamlConfiguration(); private YamlConfiguration blockConfig;
private Location pos1; private Location pos1;
private Location pos2; private Location pos2;
private Location origin; private Location origin;
private BentoBox plugin;
private boolean copied;
private File schemFolder; public Clipboard(String contents) throws InvalidConfigurationException {
public Clipboard(BentoBox plugin, File schemFolder) {
super(); super();
this.plugin = plugin; set(contents);
if (!schemFolder.exists()) {
schemFolder.mkdirs();
}
this.schemFolder = schemFolder;
} }
/** public Clipboard(YamlConfiguration config) {
* @return the pos1 super();
*/ blockConfig = config;
public Location getPos1() {
return pos1;
}
/**
* @param pos1 the pos1 to set
*/
public void setPos1(Location pos1) {
origin = null;
this.pos1 = pos1;
}
/**
* @return the pos2
*/
public Location getPos2() {
return pos2;
}
/**
* @param pos2 the pos2 to set
*/
public void setPos2(Location pos2) {
origin = null;
this.pos2 = pos2;
} }
/** public Clipboard() {
* @return the origin super();
*/
public Location getOrigin() {
return origin;
}
/**
* @param origin the origin to set
*/
public void setOrigin(Location origin) {
this.origin = origin;
} }
/** /**
* Copy the blocks between pos1 and pos2 to the clipboard * Copy the blocks between pos1 and pos2 to the clipboard
* @param user - user * @param user - user
@ -151,46 +98,9 @@ public class Clipboard {
blockConfig.set("size.ysize", toCopy.getHeight()); blockConfig.set("size.ysize", toCopy.getHeight());
blockConfig.set("size.zsize", toCopy.getWidthZ()); blockConfig.set("size.zsize", toCopy.getWidthZ());
user.sendMessage("commands.admin.schem.copied-blocks", TextVariables.NUMBER, String.valueOf(count)); user.sendMessage("commands.admin.schem.copied-blocks", TextVariables.NUMBER, String.valueOf(count));
copied = true;
return true; return true;
} }
/**
* Pastes the clipboard to island location.
* If pos1 and pos2 are not set already, they are automatically set to the pasted coordinates
* @param world - world in which to paste
* @param island - location to paste
* @param task - task to run after pasting
*/
public void pasteIsland(World world, Island island, Runnable task) {
// Offset due to bedrock
Vector off = new Vector(0,0,0);
if (blockConfig.contains(BEDROCK)) {
String[] offset = blockConfig.getString(BEDROCK).split(",");
off = new Vector(Integer.valueOf(offset[0]), Integer.valueOf(offset[1]), Integer.valueOf(offset[2]));
}
// Calculate location for pasting
Location loc = island.getCenter().toVector().subtract(off).toLocation(world);
// Paste
paste(world, island, loc, task);
}
private void paste(World world, Island island, Location loc, Runnable task) {
new Paster(plugin, this, blockConfig, world, island, loc, task);
}
/**
* Paste clipboard at this location
* @param location - location
*/
public void pasteClipboard(Location location) {
if (blockConfig.contains(BLOCKS_YAML_PREFIX)) {
paste(location.getWorld(), null, location, null);
} else {
plugin.logError("Clipboard has no block data in it to paste!");
}
}
private boolean copyBlock(Block block, Location copyOrigin, boolean copyAir, Collection<LivingEntity> entities) { private boolean copyBlock(Block block, Location copyOrigin, boolean copyAir, Collection<LivingEntity> entities) {
if (!copyAir && block.getType().equals(Material.AIR) && entities.isEmpty()) { if (!copyAir && block.getType().equals(Material.AIR) && entities.isEmpty()) {
return false; return false;
@ -301,142 +211,88 @@ public class Clipboard {
/** /**
* @return the blockConfig * @return the blockConfig
*/ */
private YamlConfiguration getBlockConfig() { public YamlConfiguration getBlockConfig() {
return blockConfig; return blockConfig;
} }
private void unzip(final String zipFilePath) throws IOException { /**
Path path = Paths.get(zipFilePath); * @return the origin
if (!(path.toFile().exists())) { */
throw new IOException("No file exists!"); public Location getOrigin() {
} return origin;
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
Path filePath = Paths.get(path.getParent().toString(), entry.getName());
if (!entry.isDirectory()) {
unzipFiles(zipInputStream, filePath);
} else {
Files.createDirectories(filePath);
}
zipInputStream.closeEntry();
entry = zipInputStream.getNextEntry();
}
}
} }
/**
private static void unzipFiles(final ZipInputStream zipInputStream, final Path unzipFilePath) throws IOException { * @return the pos1
*/
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(unzipFilePath.toAbsolutePath().toString()))) { public Location getPos1() {
byte[] bytesIn = new byte[1024]; return pos1;
int read;
while ((read = zipInputStream.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
}
} }
/**
private void zip(File targetFile) throws IOException { * @return the pos2
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(targetFile.getAbsolutePath() + ".schem"))) { */
zipOutputStream.putNextEntry(new ZipEntry(targetFile.getName())); public Location getPos2() {
try (FileInputStream inputStream = new FileInputStream(targetFile)) { return pos2;
final byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer)) >= 0) {
zipOutputStream.write(buffer, 0, length);
}
try {
Files.delete(targetFile.toPath());
} catch (Exception e) {
plugin.logError(e.getMessage());
}
}
}
} }
public boolean isFull() { public boolean isFull() {
return copied; return blockConfig != null;
} }
/** /**
* Load a file to clipboard * Set the clipboard from a YAML string
* @param fileName - filename in schems folder * @param contents
* @throws IOException - if there's a load error with unziping or name * @return
* @throws InvalidConfigurationException - the YAML of the schem is at fault * @throws InvalidConfigurationException
*/ */
public void load(String fileName) throws IOException, InvalidConfigurationException { public Clipboard set(String contents) throws InvalidConfigurationException {
File zipFile = new File(schemFolder, fileName + ".schem"); this.blockConfig.loadFromString(contents);
if (!zipFile.exists()) {
plugin.logError(LOAD_ERROR + zipFile.getName());
throw new IOException(LOAD_ERROR + zipFile.getName());
}
unzip(zipFile.getAbsolutePath());
File file = new File(schemFolder, fileName);
if (!file.exists()) {
plugin.logError(LOAD_ERROR + file.getName());
throw new IOException(LOAD_ERROR + file.getName());
}
blockConfig = new YamlConfiguration();
blockConfig.load(file);
copied = true;
Files.delete(file.toPath());
// Clear pos1 and 2
setPos1(null); setPos1(null);
setPos2(null); setPos2(null);
} return this;
/*
Load a file to clipboard
*/
/**
* @param user - use trying to load
* @param fileName - filename
* @return - <tt>true</tt> if load is successful, <tt>false</tt> if not
*/
public boolean load(User user, String fileName) {
try {
load(fileName);
} catch (IOException e1) {
user.sendMessage("commands.admin.schem.could-not-load");
plugin.logError("Could not load schems file: " + fileName + " " + e1.getMessage());
return false;
} catch (InvalidConfigurationException e1) {
user.sendMessage("commands.admin.schem.could-not-load");
plugin.logError("Could not load schems file - YAML error : " + fileName + " " + e1.getMessage());
return false;
}
user.sendMessage("general.success");
return true;
} }
/** /**
* Save the clipboard to a file * Set the clipboard contents from a YAML configuration
* @param user - user who is copying * @param set the blockConfig
* @param newFile - filename
* @return - true if successful, false if error
*/ */
public boolean save(User user, String newFile) { public Clipboard set(YamlConfiguration blockConfig) {
File file = new File(schemFolder, newFile); this.blockConfig = blockConfig;
try { setPos1(null);
getBlockConfig().save(file); setPos2(null);
} catch (IOException e) { return this;
user.sendMessage("commands.admin.schem.could-not-save", "[message]", "Could not save temp schems file.");
plugin.logError("Could not save temporary schems file: " + file.getName());
return false;
}
try {
zip(file);
} catch (IOException e) {
user.sendMessage("commands.admin.schem.could-not-save", "[message]", "Could not zip temp schems file.");
plugin.logError("Could not zip temporary schems file: " + file.getName());
return false;
}
user.sendMessage("general.success");
return true;
} }
/**
* @param origin the origin to set
*/
public void setOrigin(Location origin) {
this.origin = origin;
}
/**
* @param pos1 the pos1 to set
*/
public void setPos1(Location pos1) {
origin = null;
this.pos1 = pos1;
}
/**
* @param pos2 the pos2 to set
*/
public void setPos2(Location pos2) {
origin = null;
this.pos2 = pos2;
}
/**
* Get the clipboard
* @return the clipboard as a string
*/
@Override
public String toString() {
return blockConfig.saveToString();
}
} }

View File

@ -1,4 +1,4 @@
package world.bentobox.bentobox.schems; package world.bentobox.bentobox.blueprints;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -14,7 +14,6 @@ import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner; import org.bukkit.block.CreatureSpawner;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.AbstractHorse; import org.bukkit.entity.AbstractHorse;
import org.bukkit.entity.Ageable; import org.bukkit.entity.Ageable;
import org.bukkit.entity.ChestedHorse; import org.bukkit.entity.ChestedHorse;
@ -28,6 +27,8 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Colorable; import org.bukkit.material.Colorable;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.localization.TextVariables;
@ -50,48 +51,78 @@ public class Paster {
CANCEL CANCEL
} }
private BentoBox plugin; private static final String BEDROCK = "bedrock";
// The minimum block position (x,y,z)
private Location pos1;
// The maximum block position (x,y,z)
private Location pos2;
// Speed of pasting
private int pasteSpeed;
private PasteState pasteState;
private BukkitTask pastingTask;
// Commonly used texts along this class. // Commonly used texts along this class.
private static final String ATTACHED_YAML_PREFIX = "attached."; private static final String ATTACHED_YAML_PREFIX = "attached.";
private static final String ENTITIES_YAML_PREFIX = "entities."; private static final String ENTITIES_YAML_PREFIX = "entities.";
private static final String BLOCKS_YAML_PREFIX = "blocks."; private static final String BLOCKS_YAML_PREFIX = "blocks.";
private static final String INVENTORY = "inventory"; private static final String INVENTORY = "inventory";
private static final String ENTITY = "entity"; private static final String ENTITY = "entity";
private static final String COLOR = "color"; private static final String COLOR = "color";
private static final String LINES = "lines"; private static final String LINES = "lines";
private BentoBox plugin;
// The minimum block position (x,y,z)
private Location pos1;
// The maximum block position (x,y,z)
private Location pos2;
// Speed of pasting
private int pasteSpeed;
private PasteState pasteState;
private BukkitTask pastingTask;
/** /**
* Pastes a schem * Paste a clipboard
* @param plugin - BentoBox instance * @param plugin - BentoBox
* @param clipboard - the clipboard that called this paster * @param clipboard - clipboard to paste
* @param blockConfig - the schem Yaml File * @param location - location to paste to
* @param world - the world to paste into
* @param island - the island object
* @param loc - the location to paste to
* @param task - the task the run after pasting
*/ */
public Paster(final BentoBox plugin, Clipboard clipboard, final YamlConfiguration blockConfig, final World world, final Island island, final Location loc, final Runnable task) { public Paster(@NonNull BentoBox plugin, @NonNull Clipboard clipboard, @NonNull Location location) {
this.plugin = plugin; this.plugin = plugin;
if (!blockConfig.contains(BLOCKS_YAML_PREFIX)) { paste(location.getWorld(), null, location, clipboard, null);
plugin.logError("Clipboard has no block data in it to paste!"); }
return;
/**
* Paste a clipboard
* @param plugin - BentoBox
* @param clipboard - clipboard to paste
* @param location - location to paste to
* @param task - task to run after pasting
*/
public Paster(@NonNull BentoBox plugin, @NonNull Clipboard clipboard, @NonNull Location location, @Nullable Runnable task) {
this.plugin = plugin;
paste(location.getWorld(), null, location, clipboard, task);
}
/**
* Pastes a clipboard
* @param plugin - BentoBox
* @param clipboard - clipboard to paste
* @param world - world to paste to
* @param island - island related to this paste
* @param task - task to run after pasting
*/
public Paster(@NonNull BentoBox plugin, @NonNull Clipboard clipboard, @NonNull World world, @NonNull Island island, @Nullable Runnable task) {
this.plugin = plugin;
// Offset due to bedrock
Vector off = new Vector(0,0,0);
if (clipboard.getBlockConfig().contains(BEDROCK)) {
String[] offset = clipboard.getBlockConfig().getString(BEDROCK).split(",");
off = new Vector(Integer.valueOf(offset[0]), Integer.valueOf(offset[1]), Integer.valueOf(offset[2]));
} }
// Calculate location for pasting
Location loc = island.getCenter().toVector().subtract(off).toLocation(world);
// Paste
paste(world, island, loc, clipboard, task);
}
private void paste(@NonNull World world, @Nullable Island island, @NonNull Location loc, @NonNull Clipboard clipboard, @Nullable Runnable task) {
// Iterators for the various schem sections // Iterators for the various schem sections
Iterator<String> it = blockConfig.getConfigurationSection(BLOCKS_YAML_PREFIX).getKeys(false).iterator(); Iterator<String> it = clipboard.getBlockConfig().getConfigurationSection(BLOCKS_YAML_PREFIX).getKeys(false).iterator();
Iterator<String> it2 = blockConfig.contains(ATTACHED_YAML_PREFIX) ? blockConfig.getConfigurationSection(ATTACHED_YAML_PREFIX).getKeys(false).iterator() : null; Iterator<String> it2 = clipboard.getBlockConfig().contains(ATTACHED_YAML_PREFIX) ? clipboard.getBlockConfig().getConfigurationSection(ATTACHED_YAML_PREFIX).getKeys(false).iterator() : null;
Iterator<String> it3 = blockConfig.contains(ENTITIES_YAML_PREFIX) ? blockConfig.getConfigurationSection(ENTITIES_YAML_PREFIX).getKeys(false).iterator() : null; Iterator<String> it3 = clipboard.getBlockConfig().contains(ENTITIES_YAML_PREFIX) ? clipboard.getBlockConfig().getConfigurationSection(ENTITIES_YAML_PREFIX).getKeys(false).iterator() : null;
// Initial state & speed // Initial state & speed
pasteState = PasteState.BLOCKS; pasteState = PasteState.BLOCKS;
@ -100,15 +131,15 @@ public class Paster {
pastingTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> { pastingTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
int count = 0; int count = 0;
while (pasteState.equals(PasteState.BLOCKS) && count < pasteSpeed && it.hasNext()) { while (pasteState.equals(PasteState.BLOCKS) && count < pasteSpeed && it.hasNext()) {
pasteBlock(world, island, loc, blockConfig.getConfigurationSection(BLOCKS_YAML_PREFIX + it.next())); pasteBlock(world, island, loc, clipboard.getBlockConfig().getConfigurationSection(BLOCKS_YAML_PREFIX + it.next()));
count++; count++;
} }
while (it2 != null && pasteState.equals(PasteState.ATTACHMENTS) && count < pasteSpeed && it2.hasNext()) { while (it2 != null && pasteState.equals(PasteState.ATTACHMENTS) && count < pasteSpeed && it2.hasNext()) {
pasteBlock(world, island, loc, blockConfig.getConfigurationSection(ATTACHED_YAML_PREFIX + it2.next())); pasteBlock(world, island, loc, clipboard.getBlockConfig().getConfigurationSection(ATTACHED_YAML_PREFIX + it2.next()));
count++; count++;
} }
while (it3 != null && pasteState.equals(PasteState.ENTITIES) && count < pasteSpeed && it3.hasNext()) { while (it3 != null && pasteState.equals(PasteState.ENTITIES) && count < pasteSpeed && it3.hasNext()) {
pasteEntity(world, loc, blockConfig.getConfigurationSection(ENTITIES_YAML_PREFIX + it3.next())); pasteEntity(world, loc, clipboard.getBlockConfig().getConfigurationSection(ENTITIES_YAML_PREFIX + it3.next()));
count++; count++;
} }
// STATE SHIFT // STATE SHIFT
@ -168,40 +199,6 @@ public class Paster {
updatePos(world, x,y,z); updatePos(world, x,y,z);
} }
/**
* Tracks the minimum and maximum block positions
* @param world - world
* @param x - x
* @param y - y
* @param z - z
*/
private void updatePos(World world, int x, int y, int z) {
if (pos1 == null) {
pos1 = new Location(world, x, y, z);
}
if (pos2 == null) {
pos2 = new Location(world, x, y, z);
}
if (x < pos1.getBlockX()) {
pos1.setX(x);
}
if (x > pos2.getBlockX()) {
pos2.setX(x);
}
if (y < pos1.getBlockY()) {
pos1.setY(y);
}
if (y > pos2.getBlockY()) {
pos2.setY(y);
}
if (z < pos1.getBlockZ()) {
pos1.setZ(z);
}
if (z > pos2.getBlockZ()) {
pos2.setZ(z);
}
}
private void pasteEntity(World world, Location location, ConfigurationSection config) { private void pasteEntity(World world, Location location, ConfigurationSection config) {
String[] pos = config.getName().split(","); String[] pos = config.getName().split(",");
int x = location.getBlockX() + Integer.valueOf(pos[0]); int x = location.getBlockX() + Integer.valueOf(pos[0]);
@ -217,6 +214,47 @@ public class Paster {
setBlockState(island, block, config); setBlockState(island, block, config);
} }
/**
* Handles signs, chests and mob spawner blocks
* @param island - island
* @param block - block
* @param config - config
*/
private void setBlockState(Island island, Block block, ConfigurationSection config) {
// Get the block state
BlockState bs = block.getState();
// Signs
if (bs instanceof Sign) {
List<String> lines = config.getStringList(LINES);
writeSign(island, block, lines);
}
// Chests, in general
if (bs instanceof InventoryHolder) {
bs.update(true, false);
Inventory ih = ((InventoryHolder)bs).getInventory();
if (config.isConfigurationSection(INVENTORY)) {
ConfigurationSection inv = config.getConfigurationSection(INVENTORY);
// Double chests are pasted as two blocks so inventory is filled twice. This code stops over filling for the first block.
inv.getKeys(false).stream()
.filter(i -> Integer.valueOf(i) < ih.getSize())
.forEach(i -> ih.setItem(Integer.valueOf(i), (ItemStack)inv.get(i)));
}
}
// Mob spawners
if (bs instanceof CreatureSpawner) {
CreatureSpawner spawner = ((CreatureSpawner) bs);
spawner.setSpawnedType(EntityType.valueOf(config.getString("spawnedType", "PIG")));
spawner.setMaxNearbyEntities(config.getInt("maxNearbyEntities", 16));
spawner.setMaxSpawnDelay(config.getInt("maxSpawnDelay", 2*60*20));
spawner.setMinSpawnDelay(config.getInt("minSpawnDelay", 5*20));
spawner.setDelay(config.getInt("delay", -1));
spawner.setRequiredPlayerRange(config.getInt("requiredPlayerRange", 16));
spawner.setSpawnRange(config.getInt("spawnRange", 4));
bs.update(true, false);
}
}
/** /**
* Sets any entity that is in this location * Sets any entity that is in this location
* @param location - location * @param location - location
@ -263,43 +301,36 @@ public class Paster {
} }
/** /**
* Handles signs, chests and mob spawner blocks * Tracks the minimum and maximum block positions
* @param island - island * @param world - world
* @param block - block * @param x - x
* @param config - config * @param y - y
* @param z - z
*/ */
private void setBlockState(Island island, Block block, ConfigurationSection config) { private void updatePos(World world, int x, int y, int z) {
// Get the block state if (pos1 == null) {
BlockState bs = block.getState(); pos1 = new Location(world, x, y, z);
// Signs
if (bs instanceof Sign) {
List<String> lines = config.getStringList(LINES);
writeSign(island, block, lines);
} }
// Chests, in general if (pos2 == null) {
if (bs instanceof InventoryHolder) { pos2 = new Location(world, x, y, z);
bs.update(true, false);
Inventory ih = ((InventoryHolder)bs).getInventory();
if (config.isConfigurationSection(INVENTORY)) {
ConfigurationSection inv = config.getConfigurationSection(INVENTORY);
// Double chests are pasted as two blocks so inventory is filled twice. This code stops over filling for the first block.
inv.getKeys(false).stream()
.filter(i -> Integer.valueOf(i) < ih.getSize())
.forEach(i -> ih.setItem(Integer.valueOf(i), (ItemStack)inv.get(i)));
}
} }
// Mob spawners if (x < pos1.getBlockX()) {
if (bs instanceof CreatureSpawner) { pos1.setX(x);
CreatureSpawner spawner = ((CreatureSpawner) bs); }
spawner.setSpawnedType(EntityType.valueOf(config.getString("spawnedType", "PIG"))); if (x > pos2.getBlockX()) {
spawner.setMaxNearbyEntities(config.getInt("maxNearbyEntities", 16)); pos2.setX(x);
spawner.setMaxSpawnDelay(config.getInt("maxSpawnDelay", 2*60*20)); }
spawner.setMinSpawnDelay(config.getInt("minSpawnDelay", 5*20)); if (y < pos1.getBlockY()) {
pos1.setY(y);
spawner.setDelay(config.getInt("delay", -1)); }
spawner.setRequiredPlayerRange(config.getInt("requiredPlayerRange", 16)); if (y > pos2.getBlockY()) {
spawner.setSpawnRange(config.getInt("spawnRange", 4)); pos2.setY(y);
bs.update(true, false); }
if (z < pos1.getBlockZ()) {
pos1.setZ(z);
}
if (z > pos2.getBlockZ()) {
pos2.setZ(z);
} }
} }

View File

@ -0,0 +1,208 @@
package world.bentobox.bentobox.managers;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.blueprints.Paster;
import world.bentobox.bentobox.database.objects.Island;
/**
* @author tastybento
*/
public class ClipboardManager {
private static final String LOAD_ERROR = "Could not load schems file - does not exist : ";
private static void unzipFiles(final ZipInputStream zipInputStream, final Path unzipFilePath) throws IOException {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(unzipFilePath.toAbsolutePath().toString()))) {
byte[] bytesIn = new byte[1024];
int read;
while ((read = zipInputStream.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
}
}
private BentoBox plugin;
private File schemFolder;
private Clipboard clipboard;
public ClipboardManager(BentoBox plugin, File schemFolder) {
this(plugin, schemFolder, null);
}
public ClipboardManager(BentoBox plugin, File schemFolder, Clipboard clipboard) {
super();
this.plugin = plugin;
if (!schemFolder.exists()) {
schemFolder.mkdirs();
}
this.schemFolder = schemFolder;
this.clipboard = clipboard;
}
/**
* @return the clipboard
*/
public Clipboard getClipboard() {
return clipboard;
}
/**
* Load a file to clipboard
* @param fileName - filename in schems folder
* @throws IOException - if there's a load error with unziping or name
* @throws InvalidConfigurationException - the YAML of the schem is at fault
*/
public void load(String fileName) throws IOException, InvalidConfigurationException {
File zipFile = new File(schemFolder, fileName + ".schem");
if (!zipFile.exists()) {
plugin.logError(LOAD_ERROR + zipFile.getName());
throw new IOException(LOAD_ERROR + zipFile.getName());
}
unzip(zipFile.getAbsolutePath());
File file = new File(schemFolder, fileName);
if (!file.exists()) {
plugin.logError(LOAD_ERROR + file.getName());
throw new IOException(LOAD_ERROR + file.getName());
}
YamlConfiguration blockConfig = new YamlConfiguration();
blockConfig.load(file);
clipboard = new Clipboard(blockConfig);
Files.delete(file.toPath());
}
/*
Load a file to clipboard
*/
/**
* @param user - user trying to load
* @param fileName - filename
* @return - <tt>true</tt> if load is successful, <tt>false</tt> if not
*/
public boolean load(User user, String fileName) {
try {
load(fileName);
} catch (IOException e1) {
user.sendMessage("commands.admin.schem.could-not-load");
plugin.logError("Could not load schems file: " + fileName + " " + e1.getMessage());
return false;
} catch (InvalidConfigurationException e1) {
user.sendMessage("commands.admin.schem.could-not-load");
plugin.logError("Could not load schems file - YAML error : " + fileName + " " + e1.getMessage());
return false;
}
user.sendMessage("general.success");
return true;
}
/**
* Paste clipboard to this location
* @param location - location
*/
public void pasteClipboard(Location location) {
if (clipboard != null) {
new Paster(plugin, clipboard, location);
} else {
plugin.logError("Clipboard has no block data in it to paste!");
}
}
/**
* Pastes the clipboard to island location.
* If pos1 and pos2 are not set already, they are automatically set to the pasted coordinates
* @param world - world in which to paste
* @param island - location to paste
* @param task - task to run after pasting
*/
public void pasteIsland(World world, Island island, Runnable task) {
new Paster(plugin, clipboard, world, island, task);
}
/**
* Save the clipboard to a file
* @param user - user who is copying
* @param newFile - filename
* @return - true if successful, false if error
*/
public boolean save(User user, String newFile) {
File file = new File(schemFolder, newFile);
try {
clipboard.getBlockConfig().save(file);
} catch (IOException e) {
user.sendMessage("commands.admin.schem.could-not-save", "[message]", "Could not save temp schems file.");
plugin.logError("Could not save temporary schems file: " + file.getName());
return false;
}
try {
zip(file);
} catch (IOException e) {
user.sendMessage("commands.admin.schem.could-not-save", "[message]", "Could not zip temp schems file.");
plugin.logError("Could not zip temporary schems file: " + file.getName());
return false;
}
user.sendMessage("general.success");
return true;
}
private void unzip(final String zipFilePath) throws IOException {
Path path = Paths.get(zipFilePath);
if (!(path.toFile().exists())) {
throw new IOException("No file exists!");
}
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
Path filePath = Paths.get(path.getParent().toString(), entry.getName());
if (!entry.isDirectory()) {
unzipFiles(zipInputStream, filePath);
} else {
Files.createDirectories(filePath);
}
zipInputStream.closeEntry();
entry = zipInputStream.getNextEntry();
}
}
}
private void zip(File targetFile) throws IOException {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(targetFile.getAbsolutePath() + ".schem"))) {
zipOutputStream.putNextEntry(new ZipEntry(targetFile.getName()));
try (FileInputStream inputStream = new FileInputStream(targetFile)) {
final byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer)) >= 0) {
zipOutputStream.write(buffer, 0, length);
}
try {
Files.delete(targetFile.toPath());
} catch (Exception e) {
plugin.logError(e.getMessage());
}
}
}
}
}

View File

@ -1,16 +1,5 @@
package world.bentobox.bentobox.managers; package world.bentobox.bentobox.managers;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.schems.Clipboard;
import world.bentobox.bentobox.util.Util;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
@ -22,6 +11,19 @@ import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.blueprints.Paster;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.util.Util;
public class SchemsManager { public class SchemsManager {
/** /**
@ -71,9 +73,9 @@ public class SchemsManager {
} }
/** /**
* Get all the schems for this world * Get all the blueprints for this world
* @param world world * @param world world
* @return map of schems for this world or an empty map if there are none registered * @return map of blueprints for this world or an empty map if there are none registered
*/ */
public Map<String, Clipboard> get(World world) { public Map<String, Clipboard> get(World world) {
return islandSchems.getOrDefault(world, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); return islandSchems.getOrDefault(world, new TreeMap<>(String.CASE_INSENSITIVE_ORDER));
@ -120,9 +122,9 @@ public class SchemsManager {
plugin.log("Loading " + name + ".schem for " + world.getName()); plugin.log("Loading " + name + ".schem for " + world.getName());
Map<String, Clipboard> schemList = islandSchems.getOrDefault(world, new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); Map<String, Clipboard> schemList = islandSchems.getOrDefault(world, new TreeMap<>(String.CASE_INSENSITIVE_ORDER));
try { try {
Clipboard cb = new Clipboard(plugin, schems); ClipboardManager cb = new ClipboardManager(plugin, schems);
cb.load(name); cb.load(name);
schemList.put(name, cb); schemList.put(name, cb.getClipboard());
islandSchems.put(world, schemList); islandSchems.put(world, schemList);
} catch (IOException | InvalidConfigurationException e) { } catch (IOException | InvalidConfigurationException e) {
plugin.logError("Could not load " + name + " schem, skipping!"); plugin.logError("Could not load " + name + " schem, skipping!");
@ -150,7 +152,7 @@ public class SchemsManager {
*/ */
public void paste(World world, Island island, String name, Runnable task) { public void paste(World world, Island island, String name, Runnable task) {
if (islandSchems.containsKey(world) && islandSchems.get(world).containsKey(name)) { if (islandSchems.containsKey(world) && islandSchems.get(world).containsKey(name)) {
islandSchems.get(world).get(name).pasteIsland(world, island, task); new Paster(plugin, islandSchems.get(world).get(name), world, island, task);
} else { } else {
plugin.logError("Tried to paste schem '" + name + "' for " + world.getName() + " but the schem is not loaded!"); plugin.logError("Tried to paste schem '" + name + "' for " + world.getName() + " but the schem is not loaded!");
plugin.log("This might be due to an invalid schem format. Keep in mind that schems are not schematics."); plugin.log("This might be due to an invalid schem format. Keep in mind that schems are not schematics.");

View File

@ -213,6 +213,7 @@ commands:
description: "set the schem's origin to your position" description: "set the schem's origin to your position"
paste: paste:
description: "paste the clipboard to your location" description: "paste the clipboard to your location"
pasting: "&aPasting..."
pos1: pos1:
description: "set 1st corner of cuboid clipboard" description: "set 1st corner of cuboid clipboard"
pos2: pos2:

View File

@ -37,6 +37,7 @@ import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.events.island.IslandEvent.Reason; import world.bentobox.bentobox.api.events.island.IslandEvent.Reason;
import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.Clipboard;
import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.managers.CommandsManager; import world.bentobox.bentobox.managers.CommandsManager;
import world.bentobox.bentobox.managers.IslandWorldManager; import world.bentobox.bentobox.managers.IslandWorldManager;
@ -45,7 +46,6 @@ import world.bentobox.bentobox.managers.PlayersManager;
import world.bentobox.bentobox.managers.SchemsManager; import world.bentobox.bentobox.managers.SchemsManager;
import world.bentobox.bentobox.managers.island.NewIsland; import world.bentobox.bentobox.managers.island.NewIsland;
import world.bentobox.bentobox.managers.island.NewIsland.Builder; import world.bentobox.bentobox.managers.island.NewIsland.Builder;
import world.bentobox.bentobox.schems.Clipboard;
/** /**
* @author tastybento * @author tastybento

View File

@ -1,9 +1,7 @@
package world.bentobox.bentobox.schems; package world.bentobox.bentobox.schems;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -51,7 +49,7 @@ import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.Settings; import world.bentobox.bentobox.Settings;
import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.blueprints.Clipboard;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@ -173,15 +171,12 @@ public class ClipboardTest {
@Test @Test
public void testClipboard() { public void testClipboard() {
when(schemFolder.exists()).thenReturn(false); new Clipboard();
new Clipboard(plugin, schemFolder);
Mockito.verify(schemFolder).mkdirs();
} }
@Test @Test
public void testSetGetPos1() { public void testSetGetPos1() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
assertNull(cb.getPos1()); assertNull(cb.getPos1());
cb.setPos1(loc); cb.setPos1(loc);
assertEquals(loc, cb.getPos1()); assertEquals(loc, cb.getPos1());
@ -190,7 +185,7 @@ public class ClipboardTest {
@Test @Test
public void testSetGetPos2() { public void testSetGetPos2() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
assertNull(cb.getPos2()); assertNull(cb.getPos2());
cb.setPos2(loc); cb.setPos2(loc);
assertEquals(loc, cb.getPos2()); assertEquals(loc, cb.getPos2());
@ -198,7 +193,7 @@ public class ClipboardTest {
@Test @Test
public void testSetGetOrigin() { public void testSetGetOrigin() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
assertNull(cb.getOrigin()); assertNull(cb.getOrigin());
cb.setOrigin(loc); cb.setOrigin(loc);
assertEquals(loc, cb.getOrigin()); assertEquals(loc, cb.getOrigin());
@ -206,14 +201,14 @@ public class ClipboardTest {
@Test @Test
public void testCopyNoPos1Pos2() { public void testCopyNoPos1Pos2() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.copy(user, false); cb.copy(user, false);
Mockito.verify(user).sendMessage(Mockito.eq("commands.admin.schem.need-pos1-pos2")); Mockito.verify(user).sendMessage(Mockito.eq("commands.admin.schem.need-pos1-pos2"));
} }
@Test @Test
public void testCopyNoPos2() { public void testCopyNoPos2() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.copy(user, false); cb.copy(user, false);
Mockito.verify(user).sendMessage(Mockito.eq("commands.admin.schem.need-pos1-pos2")); Mockito.verify(user).sendMessage(Mockito.eq("commands.admin.schem.need-pos1-pos2"));
@ -221,7 +216,7 @@ public class ClipboardTest {
@Test @Test
public void testCopy() { public void testCopy() {
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.setPos2(loc2); cb.setPos2(loc2);
cb.copy(user, false); cb.copy(user, false);
@ -235,7 +230,7 @@ public class ClipboardTest {
String[] lines = {"line1", "line2", "line3", "line4"}; String[] lines = {"line1", "line2", "line3", "line4"};
when(bs.getLines()).thenReturn(lines); when(bs.getLines()).thenReturn(lines);
when(block.getState()).thenReturn(bs); when(block.getState()).thenReturn(bs);
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.setPos2(loc2); cb.setPos2(loc2);
cb.copy(user, false); cb.copy(user, false);
@ -253,7 +248,7 @@ public class ClipboardTest {
when(inv.getContents()).thenReturn(contents); when(inv.getContents()).thenReturn(contents);
when(bs.getInventory()).thenReturn(inv); when(bs.getInventory()).thenReturn(inv);
when(block.getState()).thenReturn(bs); when(block.getState()).thenReturn(bs);
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.setPos2(loc2); cb.setPos2(loc2);
cb.copy(user, false); cb.copy(user, false);
@ -268,7 +263,7 @@ public class ClipboardTest {
CreatureSpawner bs = mock(CreatureSpawner.class); CreatureSpawner bs = mock(CreatureSpawner.class);
when(bs.getSpawnedType()).thenReturn(EntityType.CAVE_SPIDER); when(bs.getSpawnedType()).thenReturn(EntityType.CAVE_SPIDER);
when(block.getState()).thenReturn(bs); when(block.getState()).thenReturn(bs);
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.setPos2(loc2); cb.setPos2(loc2);
cb.copy(user, false); cb.copy(user, false);
@ -284,7 +279,7 @@ public class ClipboardTest {
when(block.getType()).thenReturn(Material.AIR); when(block.getType()).thenReturn(Material.AIR);
BlockState bs = mock(BlockState.class); BlockState bs = mock(BlockState.class);
when(block.getState()).thenReturn(bs); when(block.getState()).thenReturn(bs);
Clipboard cb = new Clipboard(plugin, schemFolder); Clipboard cb = new Clipboard();
cb.setPos1(loc); cb.setPos1(loc);
cb.setPos2(loc2); cb.setPos2(loc2);
// Do not copy air // Do not copy air
@ -294,60 +289,4 @@ public class ClipboardTest {
Mockito.verify(user).sendMessage("commands.admin.schem.copied-blocks", TextVariables.NUMBER, "8"); Mockito.verify(user).sendMessage("commands.admin.schem.copied-blocks", TextVariables.NUMBER, "8");
} }
@Test
public void testPasteIslandNoData() {
Clipboard cb = new Clipboard(plugin, schemFolder);
Island island = mock(Island.class);
when(island.getCenter()).thenReturn(loc);
cb.pasteIsland(world, island, () -> {});
Mockito.verify(plugin).logError(Mockito.eq("Clipboard has no block data in it to paste!"));
// Verify the task is run
Mockito.verify(sched, Mockito.never()).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
}
@Test
public void testPasteIslandWithData() {
Clipboard cb = new Clipboard(plugin, schemFolder);
Island island = mock(Island.class);
when(island.getCenter()).thenReturn(loc);
cb.setPos1(loc);
cb.setPos2(loc2);
cb.copy(user, false);
cb.pasteIsland(world, island, () -> {});
// Verify the task is run
Mockito.verify(sched).runTaskTimer(Mockito.any(), Mockito.any(Runnable.class), Mockito.eq(0L), Mockito.eq(1L));
}
@Test
public void testPasteClipboardNoData() {
Clipboard cb = new Clipboard(plugin, schemFolder);
cb.pasteClipboard(loc);
Mockito.verify(plugin).logError(Mockito.eq("Clipboard has no block data in it to paste!"));
}
@Test
public void testPasteClipboard() {
Clipboard cb = new Clipboard(plugin, schemFolder);
cb.setPos1(loc);
cb.setPos2(loc2);
cb.copy(user, false);
cb.pasteClipboard(loc);
// No verification possible on the new constructor
}
@Test
public void testIsFull() {
Clipboard cb = new Clipboard(plugin, schemFolder);
assertFalse(cb.isFull());
cb.setPos1(loc);
cb.setPos2(loc2);
cb.copy(user, false);
assertTrue(cb.isFull());
}
/*
* Will not test the file system methods
*/
} }