Search in sources :

Example 1 with UserLoader

use of mc.dragons.core.gameobject.user.UserLoader in project DragonsOnline by UniverseCraft.

the class ResCommands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePlayer(sender))
        return true;
    Player player = player(sender);
    User user = user(sender);
    if (label.equalsIgnoreCase("res")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.GRAY + "To create a residence, open the door");
            sender.sendMessage(ChatColor.GRAY + "of the residence you would like to claim.");
            sender.sendMessage(ChatColor.GRAY + "You have claimed " + ChatColor.RESET + resLoader.getAllResidencesOf(user).size() + "/" + DragonsResidences.MAX_RES_PER_USER + " allowed residences.");
            sender.sendMessage(ChatColor.YELLOW + "/res mine");
            sender.sendMessage(ChatColor.YELLOW + "/res exit");
            sender.sendMessage(ChatColor.YELLOW + "/res delete <ID>");
        } else if (args[0].equalsIgnoreCase("mine")) {
            sender.sendMessage(ChatColor.GREEN + "Listing your residences:");
            for (Residence res : resLoader.getAllResidencesOf(user)) {
                Location door = res.getResPoint().getDoorLocation();
                sender.sendMessage(ChatColor.DARK_GREEN + "#" + res.getId() + ChatColor.GRAY + " (" + res.getAccessLevel() + ")" + " (" + FloorLoader.fromWorld(door.getWorld()).getDisplayName() + " " + door.getBlockX() + ", " + door.getBlockZ() + ")");
            }
        } else if (args[0].equalsIgnoreCase("exit")) {
            Document saved = user.getData().get("resExitTo", Document.class);
            if (saved == null) {
                sender.sendMessage(ChatColor.RED + "You're not in a residence right now!");
                return true;
            }
            Location to = StorageUtil.docToLoc(saved);
            player.teleport(to);
            sender.sendMessage(ChatColor.GREEN + "Exited residence successfully.");
            user.getStorageAccess().set("resExitTo", null);
        } else if (args[0].equalsIgnoreCase("delete")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/res delete <ID>");
                return true;
            }
            Integer id = parseInt(sender, args[1]);
            if (id == null)
                return true;
            Residence res = resLoader.getResidenceById(id);
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID! You can see your residences with /res mine");
                return true;
            }
            if (res.isLocked()) {
                sender.sendMessage(ChatColor.RED + "This residence has been locked by an administrator.");
                return true;
            }
            if (!res.getOwner().getIdentifier().equals(user.getIdentifier())) {
                sender.sendMessage(ChatColor.RED + "You do not own this residence! You can see your residences with /res mine");
                return true;
            }
            resLoader.deleteResidence(id);
            resPointLoader.updateResHologramOn(user, res.getResPoint());
            if (player.getWorld().getName().equals("res_temp") && user.getData().getInteger("lastResId") == id) {
                Document saved = user.getData().get("resExitTo", Document.class);
                Location to = StorageUtil.docToLoc(saved);
                player.teleport(to);
                user.getStorageAccess().set("resExitTo", null);
            }
            sender.sendMessage(ChatColor.GREEN + "Deleted residence #" + id + " successfully.");
        }
        return true;
    }
    if (!requirePermission(sender, PermissionLevel.DEVELOPER))
        return true;
    if (label.equalsIgnoreCase("resadmin")) {
        if (!requirePermission(sender, PermissionLevel.ADMIN))
            return true;
        // Res commands for admins
        if (args.length == 0) {
            sender.sendMessage(ChatColor.YELLOW + "/resadmin linkpoint <Name> <Price> <Display Name...>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin setprice <Name> <NewPrice>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin displayname <Name> <New Display Name...>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin delpoint <Name>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin listpoints");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin listowned <Player>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin [un]lock <ID>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin delete <ID>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin flag <ID> <Flag> <Value>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin goto <ID>");
            sender.sendMessage(ChatColor.YELLOW + "/resadmin rebuild <ID>");
        } else if (args[0].equalsIgnoreCase("linkpoint")) {
            if (args.length < 3) {
                sender.sendMessage(ChatColor.RED + "/resadmin linkpoint <Name> <Price> <Display Name...>");
                return true;
            }
            Block target = player.getTargetBlock(null, 5);
            if (target == null) {
                sender.sendMessage(ChatColor.RED + "Please look at the door you want to link!");
                return true;
            }
            if (!(target.getBlockData() instanceof Door)) {
                sender.sendMessage(ChatColor.RED + "Please look at the " + ChatColor.ITALIC + "door " + ChatColor.RED + "you want to link!");
                return true;
            }
            Door door = (Door) target.getBlockData();
            if (door.getHalf() == Half.TOP) {
                target = target.getRelative(BlockFace.DOWN);
            }
            resPointLoader.addResPoint(args[1], StringUtil.concatArgs(args, 3), Double.valueOf(args[2]), target.getLocation());
            sender.sendMessage(ChatColor.GREEN + "Added res point successfully.");
        } else if (args[0].equalsIgnoreCase("setprice")) {
            if (args.length < 2) {
                sender.sendMessage(ChatColor.RED + "/resadmin setprice <Name> <NewPrice>");
                return true;
            }
            ResPoint resPoint = resPointLoader.getResPointByName(args[1]);
            if (resPoint == null) {
                sender.sendMessage(ChatColor.RED + "Invalid res point! /respoint listpoints");
                return true;
            }
            resPoint.setPrice(Double.valueOf(args[2]));
            sender.sendMessage(ChatColor.GREEN + "Updated res point price successfully.");
        } else if (args[0].equalsIgnoreCase("displayname")) {
            if (args.length < 2) {
                sender.sendMessage(ChatColor.RED + "/resadmin displayname <Name> <New Display Name...>");
                return true;
            }
            ResPoint resPoint = resPointLoader.getResPointByName(args[1]);
            if (resPoint == null) {
                sender.sendMessage(ChatColor.RED + "Invalid res point! /respoint listpoints");
                return true;
            }
            resPoint.setDisplayName(StringUtil.concatArgs(args, 2));
            sender.sendMessage(ChatColor.GREEN + "Updated res point display name successfully.");
        } else if (args[0].equalsIgnoreCase("delpoint")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/reasdmin delpoint <Name>");
                return true;
            }
            resPointLoader.deleteResPoint(args[1]);
            sender.sendMessage(ChatColor.GREEN + "If a res point by this name existed, it has been deleted successfully.");
            return true;
        } else if (args[0].equalsIgnoreCase("listpoints")) {
            sender.sendMessage(ChatColor.GREEN + "Listing all res points:");
            for (ResPoint resPoint : resPointLoader.getAllResPoints()) {
                sender.sendMessage(ChatColor.GRAY + "- " + resPoint.getName() + " - " + resPoint.getPrice() + " gold" + " (" + StringUtil.locToString(resPoint.getDoorLocation()) + ")");
                if (!(resPoint.getDoorLocation().getBlock().getBlockData() instanceof Door)) {
                    sender.sendMessage(ChatColor.RED + "   (Invalid: No door at that location!)");
                }
            }
        } else if (args[0].equalsIgnoreCase("listowned")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/resadmin listowned <Player>");
                return true;
            }
            sender.sendMessage(ChatColor.GREEN + "Listing residences owned by " + args[1] + ":");
            for (Residence res : resLoader.getAllResidencesOf(GameObjectType.USER.<User, UserLoader>getLoader().loadObject(args[1]))) {
                sender.sendMessage(ChatColor.DARK_GREEN + "#" + res.getId() + ChatColor.GRAY + ": " + res.getAccessLevel() + (res.isLocked() ? " (Locked)" : ""));
            }
        } else if (args[0].equalsIgnoreCase("lock") || args[0].equalsIgnoreCase("unlock")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/resadmin " + args[0].toLowerCase() + " <ID>");
                return true;
            }
            Residence res = resLoader.getResidenceById(Integer.valueOf(args[1]));
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID!");
                return true;
            }
            res.setLocked(args[0].equalsIgnoreCase("lock"));
            sender.sendMessage(ChatColor.GREEN + (args[0].equalsIgnoreCase("lock") ? "Locked" : "Unlocked") + " residence #" + args[1]);
        } else if (args[0].equalsIgnoreCase("delete")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/resadmin delete <ID>");
                return true;
            }
            Residence res = resLoader.getResidenceById(Integer.valueOf(args[1]));
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID!");
                return true;
            }
            resLoader.deleteResidence(res.getId());
            sender.sendMessage(ChatColor.GREEN + "Deleted residence #" + args[1]);
        } else if (args[0].equalsIgnoreCase("flag")) {
            if (args.length < 3) {
                sender.sendMessage(ChatColor.RED + "/resadmin flag <ID> <Flag> <Value>");
                return true;
            }
            Residence res = resLoader.getResidenceById(Integer.valueOf(args[1]));
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID!");
                return true;
            }
            res.getProperties().append(args[2], args[3]);
            res.save();
            sender.sendMessage(ChatColor.GREEN + "Set flag " + args[2] + " to " + args[3] + " for residence #" + args[1]);
        } else if (args[0].equalsIgnoreCase("goto")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/resadmin goto <ID>");
                return true;
            }
            Residence res = resLoader.getResidenceById(Integer.valueOf(args[1]));
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID!");
                return true;
            }
            resLoader.goToResidence(user, res.getId(), true);
        } else if (args[0].equalsIgnoreCase("rebuild")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/resadmin rebuild <ID>");
                return true;
            }
            int id = Integer.valueOf(args[1]);
            Residence res = resLoader.getResidenceById(id);
            if (res == null) {
                sender.sendMessage(ChatColor.RED + "Invalid residence ID!");
                return true;
            }
            resLoader.removeResidenceLocally(id);
            resLoader.generateResidence(id);
            sender.sendMessage(ChatColor.GREEN + "Rebuilt residence #" + id + " successfully.");
        } else {
            sender.sendMessage(ChatColor.RED + "/resadmin");
        }
    } else if (label.equalsIgnoreCase("testcontextualholograms")) {
        for (ResPoint resPoint : resPointLoader.getAllResPoints()) {
            resPointLoader.updateResHologramOn(user, resPoint);
        }
    } else if (label.equalsIgnoreCase("testschematic")) {
        if (args[1].equalsIgnoreCase("good")) {
            DragonsResidences.pasteSchematic(DragonsResidences.loadSchematic(args[0]), DragonsResidences.getEditSession(new BukkitWorld(player.getWorld())), player.getLocation());
        } else if (args[1].equalsIgnoreCase("bad")) {
            // DragonsResPlugin.pasteSchematic(args[0], DragonsResPlugin.getEditSession(new BukkitWorld(player.getWorld())), player.getLocation());
            sender.sendMessage(ChatColor.RED + "No! Don't be bad");
            sender.sendMessage(ChatColor.GREEN + "Be good instead ;)");
        }
    } else if (label.equalsIgnoreCase("restest")) {
        // Test commands for devs
        if (args.length == 0) {
            sender.sendMessage("/restest new <ResPoint>");
            sender.sendMessage("/restest go <ID>");
            sender.sendMessage("/restest my");
            sender.sendMessage("/restest whatsthatrespoint");
        } else if (args[0].equalsIgnoreCase("new")) {
            Residence res = resLoader.addResidence(user, resPointLoader.getResPointByName(args[1]), ResAccess.PRIVATE);
            sender.sendMessage("Created new residence #" + res.getId());
        } else if (args[0].equalsIgnoreCase("go")) {
            Residence res = resLoader.getResidenceById(Integer.valueOf(args[1]));
            if (res == null) {
                sender.sendMessage("No residence by that ID exists! (highest ID=" + resPointLoader.getCurrentMaxId() + ")");
                return true;
            }
            resLoader.goToResidence(user, res.getId(), true);
        } else if (args[0].equalsIgnoreCase("my")) {
            for (Residence res : resLoader.getAllResidencesOf(user)) {
                sender.sendMessage("#" + res.getId() + " (owner=" + res.getOwner().getName() + ", access=" + res.getAccessLevel() + ")");
            }
        } else if (args[0].equalsIgnoreCase("whatsthatrespoint")) {
            // bottom half only
            Block target = player.getTargetBlock(null, 5);
            if (target == null) {
                sender.sendMessage("No target block");
                return true;
            }
            sender.sendMessage("Target block is " + target.getType());
            sender.sendMessage("Target block location is " + StringUtil.locToString(target.getLocation()));
            ResPoint resPoint = resPointLoader.getResPointByDoorLocation(target.getLocation());
            if (resPoint == null) {
                sender.sendMessage("No res point here");
                return true;
            }
            sender.sendMessage("Res point is " + resPoint.getName());
        }
    }
    return true;
}
Also used : Player(org.bukkit.entity.Player) User(mc.dragons.core.gameobject.user.User) Block(org.bukkit.block.Block) UserLoader(mc.dragons.core.gameobject.user.UserLoader) BukkitWorld(com.sk89q.worldedit.bukkit.BukkitWorld) Residence(mc.dragons.res.ResLoader.Residence) Document(org.bson.Document) Door(org.bukkit.block.data.type.Door) ResPoint(mc.dragons.res.ResPointLoader.ResPoint) Location(org.bukkit.Location)

Example 2 with UserLoader

use of mc.dragons.core.gameobject.user.UserLoader in project DragonsOnline by UniverseCraft.

the class ExperimentalCommands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
        return true;
    Player player = player(sender);
    User user = user(sender);
    if (label.equalsIgnoreCase("testmineregen")) {
        int minutesPerSecond = Integer.valueOf(args[0]);
        int radius = Integer.valueOf(args[1]);
        double alpha = Double.valueOf(args[2]);
        double beta = Double.valueOf(args[3]);
        final Player fPlayer = player;
        final Location center = player.getLocation();
        int maxIterations = Integer.valueOf(args[4]);
        Bukkit.broadcastMessage("==Beginning simulation of mining regen. SimulatedMinutesPerSecond=" + minutesPerSecond + ", Radius=" + radius + ", Alpha=" + alpha + ", Beta=" + beta + ", MaxIterations=" + maxIterations);
        new BukkitRunnable() {

            private int iterations = 0;

            @Override
            public void run() {
                int players = (int) fPlayer.getNearbyEntities(radius, radius, radius).stream().filter(e -> e.getType() == EntityType.PLAYER).count();
                int mined = 0;
                int cX = center.getBlockX();
                int cY = center.getBlockY();
                int cZ = center.getBlockZ();
                for (int x = cX - radius; x <= cX + radius; x++) {
                    for (int y = cY - radius; y <= cY + radius; y++) {
                        for (int z = cZ - radius; z <= cZ + radius; z++) {
                            Block block = center.getWorld().getBlockAt(x, y, z);
                            if (block.getType() == Material.AIR) {
                                mined++;
                            }
                        }
                    }
                }
                if (mined == 0) {
                    Bukkit.broadcastMessage("==No blocks left to regenerate, ending simulation (" + iterations + " iterations)==");
                    this.cancel();
                    return;
                }
                int regen = (int) Math.ceil(mined * (alpha + beta * players));
                Bukkit.broadcastMessage("Regenerating " + regen + " blocks (players=" + players + ", mined=" + mined + ")");
                int done = 0;
                for (int x = cX - radius; x <= cX + radius; x++) {
                    for (int y = cY - radius; y <= cY + radius; y++) {
                        for (int z = cZ - radius; z <= cZ + radius; z++) {
                            Block block = center.getWorld().getBlockAt(x, y, z);
                            if (block.getType() == Material.AIR && done < regen) {
                                done++;
                                block.setType(Material.GOLD_BLOCK);
                            }
                        }
                    }
                }
                iterations++;
                if (iterations >= maxIterations) {
                    Bukkit.broadcastMessage("==Completed simulation==");
                    this.cancel();
                }
            }
        }.runTaskTimer(Dragons.getInstance(), 20L, 20L / minutesPerSecond);
    } else if (label.equalsIgnoreCase("testpermission")) {
        if (player.hasPermission(args[0])) {
            sender.sendMessage("Yes you have it");
        } else {
            sender.sendMessage("No you don't have it");
        }
    } else if (label.equalsIgnoreCase("helditemdata") || label.equalsIgnoreCase("whatamiholding")) {
        ItemStack itemStack = player.getInventory().getItemInMainHand();
        sender.sendMessage("pdc=" + itemStack.getItemMeta().getPersistentDataContainer());
        sender.sendMessage("uuid=" + itemStack.getItemMeta().getPersistentDataContainer().get(Item.ITEM_UUID_KEY, PersistentDataType.STRING));
        sender.sendMessage("bukkit amt=" + itemStack.getAmount());
        Item item = ItemLoader.fromBukkit(itemStack);
        sender.sendMessage("item=" + item);
        if (item != null) {
            sender.sendMessage("db amt=" + item.getQuantity());
            sender.sendMessage("item class=" + item.getClassName());
            sender.sendMessage("item data=" + item.getData().toJson());
        }
        if (args.length > 0 && args[0].equalsIgnoreCase("-verbose")) {
            sender.sendMessage("item stack data=" + itemStack);
        }
    } else if (label.equalsIgnoreCase("getitemuuid")) {
        Item item = ItemLoader.fromBukkit(player.getInventory().getItemInMainHand());
        if (item == null)
            return true;
        sender.spigot().sendMessage(StringUtil.clickableHoverableText("" + item.getUUID(), "" + item.getUUID(), true, "Click to copy"), StringUtil.clickableHoverableText(" (" + item.getClassName() + ")", "/item " + item.getClassName() + " ", true, "Click to manage class"));
    } else if (label.equalsIgnoreCase("testlocaluserstorage")) {
        sender.sendMessage(ChatColor.YELLOW + "METHOD ONE (Full object scan):");
        int n_fullscan = 0;
        for (GameObject gameObject : Dragons.getInstance().getGameObjectRegistry().getRegisteredObjects(GameObjectType.USER)) {
            User u = (User) gameObject;
            sender.sendMessage("- User: " + u);
            sender.sendMessage("    - name=" + u.getName());
            sender.sendMessage("    - player=" + u.getPlayer());
            n_fullscan++;
        }
        int n_cached = 0;
        sender.sendMessage(ChatColor.YELLOW + "METHOD TWO (UserLoader cache):");
        for (User test : UserLoader.allUsers()) {
            sender.sendMessage("- User: " + test);
            sender.sendMessage("    - name=" + test.getName());
            sender.sendMessage("    - player=" + test.getPlayer());
            n_cached++;
        }
        if (n_fullscan != n_cached) {
            sender.sendMessage(ChatColor.RED + "WARNING: Different methods gave different results (fullscan=" + n_fullscan + " vs cached=" + n_cached + ")");
        }
    } else if (label.equalsIgnoreCase("testgui")) {
        GUI gui = new GUI(3, "Test GUI").add(new GUIElement(11, Material.COBBLESTONE, "I matter!", "Multi-line\nlore\n\nis cool", 2, u -> u.debug("Clicked the cobble"))).add(new GUIElement(13, Material.APPLE, "iApple", "", 5, u -> u.debug("Clicked da appel"))).add(itemClassLoader.getItemClassByClassName("GMSword").getAsGuiElement(15, 3, 1999.99, false, u -> u.debug("Purchasing GM Sword!!!")));
        gui.open(user);
    } else if (label.equalsIgnoreCase("testhdfont")) {
        player.sendMessage(StringUtil.toHdFont(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("rawtext")) {
        player.sendMessage(ChatColor.translateAlternateColorCodes('&', StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testtabname")) {
        lookupPlayer(sender, args[0]).setPlayerListName(ChatColor.translateAlternateColorCodes('&', StringUtil.concatArgs(args, 1)));
    } else if (label.equalsIgnoreCase("whoami")) {
        sender.sendMessage("Player=" + player);
        sender.sendMessage("User=" + user);
        for (User test : UserLoader.allUsers()) {
            if (user.getIdentifier().equals(test.getIdentifier()) && !test.equals(user)) {
                sender.sendMessage("-Also user " + test + " => " + test.getPlayer());
            }
        }
        sender.sendMessage("StorageAccess=" + (user == null ? "null" : user.getStorageAccess()));
    } else if (label.equalsIgnoreCase("testpathfinding")) {
        Location spawnLoc = player.getLocation().add(player.getLocation().getDirection().clone().setY(0).normalize().multiply(10.0));
        LivingEntity e = (LivingEntity) Bukkit.getWorld("undead_forest").spawnEntity(spawnLoc, EntityType.VILLAGER);
        Dragons.getInstance().getBridge().setEntityAI(e, false);
        PathfindingUtil.walkToLocation(e, player.getLocation(), 0.2, unused -> {
        });
    } else if (label.equalsIgnoreCase("testphasing")) {
        Entity entity = player.getWorld().spawnEntity(player.getLocation(), EntityType.valueOf(args[0]));
        if (entity instanceof ArmorStand) {
            ((ArmorStand) entity).setCustomName("Test test test");
            ((ArmorStand) entity).setCustomNameVisible(true);
        }
        Dragons.getInstance().getEntityHider().hideEntity(player, entity);
    } else if (label.equalsIgnoreCase("testtpsrecord")) {
        List<Double> record = Dragons.getInstance().getTPSRecord();
        int back = Integer.valueOf(args[0]);
        sender.sendMessage(record.size() + " records");
        sender.sendMessage("starting from " + back + " records back");
        for (int i = record.size() - 1 - back; i < record.size(); i++) {
            sender.sendMessage("#" + i + " = " + record.get(i) + " (" + (record.size() - 1 - i) + " frames back)");
        }
    } else if (label.equalsIgnoreCase("stresstest")) {
        int n = Integer.valueOf(args[0]);
        Location loc = player.getLocation();
        for (int i = 0; i < n; i++) {
            npcLoader.registerNew(loc, "F2-UndeadZombie");
        }
        player.sendMessage(ChatColor.GREEN + "Spawned " + n + " undead zombies at your location.");
    } else if (label.equalsIgnoreCase("killmobs")) {
        int n = 0;
        for (Entity e : player.getWorld().getEntities()) {
            NPC npc = NPCLoader.fromBukkit(e);
            if (npc == null)
                continue;
            if (npc.getNPCType().isPersistent())
                continue;
            npc.remove();
            n++;
        }
        player.sendMessage(ChatColor.GREEN + "Killed " + n + " non-persistent mobs.");
    } else if (label.equalsIgnoreCase("testarmorstandpose")) {
        ArmorStand armorStand = (ArmorStand) player.getWorld().spawnEntity(player.getLocation(), EntityType.ARMOR_STAND);
        armorStand.setLeftLegPose(new EulerAngle(Double.valueOf(args[0]), Double.valueOf(args[1]), Double.valueOf(args[2])));
        armorStand.setRightLegPose(new EulerAngle(Double.valueOf(args[3]), Double.valueOf(args[4]), Double.valueOf(args[5])));
    } else if (label.equalsIgnoreCase("testlogging")) {
        for (Level level : new Level[] { Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, Level.FINE, Level.FINER, Level.FINEST, Level.ALL }) {
            Dragons.getInstance().getLogger().log(level, "Testing log message on level " + level);
        }
    } else if (label.equalsIgnoreCase("testleveling")) {
        player.sendMessage("level=" + user.getLevel());
        player.sendMessage("xp=" + user.getXP());
        int prevMax = User.calculateMaxXP(user.getLevel());
        player.sendMessage("prevMax=" + prevMax);
        int nextMax = User.calculateMaxXP(user.getLevel() + 1);
        player.sendMessage("nextMax=" + nextMax);
        int n = user.getXP() - prevMax;
        int d = nextMax - prevMax;
        player.sendMessage("numerator=" + n);
        player.sendMessage("denominator=" + d);
        player.sendMessage("progress=" + ((float) n / d));
        player.sendMessage("progress=" + ((double) n / d));
        player.sendMessage("progress=" + user.getLevelProgress());
    } else if (label.equalsIgnoreCase("testexceptions")) {
        sender.sendMessage("Throwing an NPE");
        // Throws an NPE
        ((User) null).autoSave();
    } else if (label.equalsIgnoreCase("testuuidlookup")) {
        UserLoader.uuidFromUsername(args[0], uuid -> {
            sender.sendMessage("UUID of " + args[0] + " is " + uuid);
        });
    } else if (label.equalsIgnoreCase("testcorrelationlogging")) {
        CorrelationLogger loader = Dragons.getInstance().getLightweightLoaderRegistry().getLoader(CorrelationLogger.class);
        UUID id = loader.registerNewCorrelationID();
        loader.log(id, Level.INFO, "hewwo uwu");
        loader.log(id, Level.SEVERE, "ouch");
        sender.sendMessage("correlation id=" + id);
    } else if (label.equalsIgnoreCase("testbase64encoding")) {
        String encoded = Base64.getEncoder().encodeToString(StringUtil.concatArgs(args, 0).getBytes());
        sender.sendMessage("encoded: " + encoded);
        String decoded = new String(Base64.getDecoder().decode(encoded));
        sender.sendMessage("decoded: " + decoded);
    } else if (label.equalsIgnoreCase("testnetworkmessage")) {
        debugHandler.send(new Document("payload", new Document("babey", "babey")), args[0]);
    } else if (label.equalsIgnoreCase("testdocumentdelta")) {
        Document a = new Document("a", 1).append("b", 2).append("c", new Document("x", 3).append("y", 4));
        Document b = new Document("a", 2).append("b", 2).append("d", 3).append("c", new Document("x", 3).append("y", 2));
        Document delta = StorageUtil.getDelta(a, b);
        Document result = StorageUtil.applyDelta(b, delta);
        sender.sendMessage("a=" + a.toJson());
        sender.sendMessage("b=" + b.toJson());
        sender.sendMessage("delta=" + delta.toJson());
        sender.sendMessage("result=" + result.toJson());
    } else if (label.equalsIgnoreCase("testnewfonts")) {
        String[] fonts = { "minecraft:default", "minecraft:uniform", "minecraft:alt" };
        String text = StringUtil.concatArgs(args, 0);
        for (String font : fonts) {
            TextComponent tc = new TextComponent(text);
            tc.setFont(font);
            sender.spigot().sendMessage(new TextComponent(font + " "), tc);
        }
    } else if (label.equalsIgnoreCase("testuserlookup")) {
        User target = lookupUser(sender, args[0]);
        if (target == null) {
            sender.sendMessage("Not found");
        } else {
            sender.sendMessage("User is " + target);
        }
    } else if (label.equalsIgnoreCase("writelog")) {
        Level level = this.lookup(sender, () -> Level.parse(args[0].toUpperCase()), ChatColor.RED + "Invalid log level! /writelog <level> <message>");
        String message = StringUtil.concatArgs(args, 1);
        if (level == null || message == null)
            return true;
        dragons.getLogger().log(level, message);
        sender.sendMessage("Log entry written successfully");
    } else if (label.equalsIgnoreCase("testheader")) {
        player.setPlayerListHeader(user.tablistText(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testfooter")) {
        player.setPlayerListFooter(user.tablistText(StringUtil.concatArgs(args, 0)));
    } else if (label.equalsIgnoreCase("testinvisibleslimes")) {
        boolean allOK = true;
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                if (!slime.isInvisible()) {
                    sender.sendMessage(ChatColor.RED + "SLIME #" + slime.getEntityId() + " is NOT invisible (" + StringUtil.locToString(slime.getLocation()) + ")");
                    allOK = false;
                } else {
                    sender.sendMessage(ChatColor.GREEN + "SLIME #" + slime.getEntityId() + " IS invisible (" + StringUtil.locToString(slime.getLocation()) + ")");
                }
            }
        }
        if (!allOK) {
            sender.sendMessage(ChatColor.RED + "-- One or more slimes in this world are visible --");
        }
    } else if (label.equalsIgnoreCase("testrevealslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                slime.setInvisible(false);
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
            }
        }
    } else if (label.equalsIgnoreCase("testhideslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                slime.setInvisible(true);
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
            }
        }
    } else if (label.equalsIgnoreCase("testdestroyslimes")) {
        for (Entity entity : player.getWorld().getEntities()) {
            if (entity instanceof Slime) {
                Slime slime = (Slime) entity;
                player.spawnParticle(Particle.DRIP_LAVA, slime.getLocation(), 10);
                HologramUtil.unclickableifySlime(slime);
                slime.remove();
            }
        }
    } else if (label.equalsIgnoreCase("testbadslimes")) {
        int total = 0;
        for (World world : Bukkit.getWorlds()) {
            total += world.getEntitiesByClass(Slime.class).size();
            for (Slime slime : world.getEntitiesByClass(Slime.class)) {
                Dragons.getInstance().getLogger().severe("BAD SLIME YOU SUCK: " + StringUtil.entityToString(slime) + " - allow:" + slime.hasMetadata("allow") + " - nRClickHandlers:" + PlayerEventListeners.getRightClickHandlers(slime) + " - ClickySlime:" + slime.hasMetadata(HologramUtil.KEY_CLICKABLE_SLIME));
            }
        }
        Dragons.getInstance().getLogger().debug("THERE ARE " + total + " SLIMES");
    } else if (label.equalsIgnoreCase("mockuser")) {
        Document data = Document.parse(user(sender).getData().toJson());
        data.append("_id", UUID.randomUUID());
        data.append("username", args[0]);
        data.append("currentServer", args[1]);
        data.append("mock", true);
        dragons.getMongoConfig().getDatabase().getCollection("gameobjects").insertOne(data);
        sender.sendMessage("UUID: " + data.get("_id", UUID.class));
    } else if (label.equalsIgnoreCase("mocksudo")) {
        Document data = dragons.getMongoConfig().getDatabase().getCollection("gameobjects").find(new Document("username", args[0])).first();
        if (data.getBoolean("mock", false)) {
            dragons.getRemoteAdminHandler().sendRemoteSudo(data.getString("currentServer"), data.get("_id", UUID.class), StringUtil.concatArgs(args, 1));
        }
    } else if (label.equalsIgnoreCase("mockinject")) {
        StorageManager storageManager = dragons.getPersistentStorageManager();
        StorageAccess storageAccess = storageManager.getStorageAccess(GameObjectType.USER, new Document("username", args[0]));
        MockPlayer mockPlayer = new MockPlayer(storageAccess.getIdentifier().getUUID(), args[0]);
        MockUser mockUser = new MockUser(null, storageManager, storageAccess);
        dragons.getGameObjectRegistry().getRegisteredObjects().removeIf(obj -> obj instanceof User && ((User) obj).getName().equalsIgnoreCase(args[0]));
        dragons.getGameObjectRegistry().getRegisteredObjects().add(mockUser);
        UserLoader.allUsers().removeIf(u -> u.getName().equalsIgnoreCase(args[0]));
        UserLoader.allUsers().add(mockUser);
        UserLoader.assign(mockPlayer, mockUser);
        mockUser.setPlayer(mockPlayer);
        sender.sendMessage("UUID: " + mockUser.getUUID());
        sender.sendMessage("Server: " + mockUser.getServerName() + " ?= " + storageAccess.get("currentServer", String.class));
        sender.sendMessage("Player: " + mockPlayer);
        sender.sendMessage("CommandSender: " + mockUser.getCommandSender());
        sender.sendMessage("CommandSender is player: " + (mockUser.getCommandSender() instanceof Player));
        sender.sendMessage("Passes for player: " + (mockPlayer instanceof Player));
        sender.sendMessage("Passes for user:" + (mockUser instanceof User));
        sender.sendMessage("Player casted from sender: " + ((Player) mockUser.getCommandSender()));
        sender.sendMessage("User lookup: " + UserLoader.fromPlayer(mockPlayer));
        sender.sendMessage("User lookup by sender: " + UserLoader.fromPlayer((Player) mockUser.getCommandSender()));
        sender.sendMessage("Exists in UserLoader cache: " + UserLoader.allUsers().contains(mockUser));
        sender.sendMessage("Exists in game object registry: " + dragons.getGameObjectRegistry().getRegisteredObjects().contains(mockUser));
        sender.sendMessage("Exists in filtered game object registry: " + dragons.getGameObjectRegistry().getRegisteredObjects(GameObjectType.USER).contains(mockUser));
    } else if (label.equalsIgnoreCase("mockdelete")) {
        User target = lookupUser(sender, args[0]);
        if (target.getData().getBoolean("mock", false)) {
            dragons.getGameObjectRegistry().removeFromDatabase(target);
            dragons.getGameObjectRegistry().getRegisteredObjects().remove(target);
            UserLoader.allUsers().remove(target);
            sender.sendMessage("Deleted mock user " + target.getName() + " and removed from primary local caches");
        }
    } else if (label.equalsIgnoreCase("mocklist")) {
        Set<User> mocks = dragons.getPersistentStorageManager().getAllStorageAccess(GameObjectType.USER, new Document("mock", true)).stream().map(sa -> userLoader.loadObject(sa)).collect(Collectors.toSet());
        sender.sendMessage("USERNAME  -  UUID  -  CURRENT SERVER");
        for (User mock : mocks) {
            sender.sendMessage(mock.getName() + "  -  " + mock.getUUID() + "  -  " + mock.getServerName());
        }
    } else if (label.equalsIgnoreCase("mockserver")) {
        StorageAccess storageAccess = dragons.getPersistentStorageManager().getStorageAccess(GameObjectType.USER, new Document("username", args[0]));
        storageAccess.set("currentServer", args[1]);
    } else if (label.equalsIgnoreCase("testitemstash")) {
        user.stashItems(questLoader.getQuestByName(args[0]), Material.valueOf(args[1]));
        sender.sendMessage("Stash: " + user.getData().get("questStash", new Document()).toJson());
    } else if (label.equalsIgnoreCase("testitemunstash")) {
        user.unstashItems(questLoader.getQuestByName(args[0]), Material.valueOf(args[1]));
        sender.sendMessage("Stash: " + user.getData().get("questStash", new Document()).toJson());
    } else if (label.equalsIgnoreCase("testmobai")) {
        boolean ai = Boolean.valueOf(args[0]);
        boolean gravity = Boolean.valueOf(args[1]);
        boolean collidable = Boolean.valueOf(args[2]);
        LivingEntity entity = (LivingEntity) player.getWorld().spawnEntity(player.getLocation(), EntityType.ZOMBIE);
        entity.setAI(ai);
        entity.setGravity(gravity);
        entity.setCollidable(collidable);
    } else if (label.equalsIgnoreCase("testtakeitem")) {
        Item item = itemLoader.registerNew(args[0]);
        int quantity = Integer.valueOf(args[1]);
        user.takeItem(item, quantity, true, true, true);
    } else if (label.equalsIgnoreCase("testupdateinventory")) {
        player.updateInventory();
    } else if (label.equalsIgnoreCase("testnametag")) {
        User target = lookupUser(sender, args[0]);
        String prefix = StringUtil.colorize(args[2]);
        String suffix = StringUtil.colorize(StringUtil.concatArgs(args, 3));
        target.setPrimaryNameTag(ChatColor.valueOf(args[1]), prefix, suffix);
    } else if (label.equalsIgnoreCase("testnametag2")) {
        User target = lookupUser(sender, args[0]);
        String text = StringUtil.colorize(StringUtil.concatArgs(args, 1));
        target.setSecondaryNameTag(text);
    } else if (label.equalsIgnoreCase("testupdatenametag")) {
        user.updatePrimaryNameTag();
    } else if (label.equalsIgnoreCase("testrollingasync")) {
        rollingAsync(() -> {
            String name = Thread.currentThread().getName();
            sync(() -> {
                player.sendMessage("hey (" + name + ")");
            });
        });
    } else if (label.equalsIgnoreCase("testinternalnetworkedmsg")) {
        User to = lookupUser(sender, args[0]);
        dragons.getInternalMessageHandler().sendRawMsg(to.getServerName(), to.getUUID(), StringUtil.concatArgs(args, 1));
    } else if (StringUtil.equalsAnyIgnoreCase(label, "testplayernpc", "npctool")) {
        if (args.length == 0) {
            sender.sendMessage("/" + label + " <rot|loc|info|set <pitch> <yaw>>  (all changes are local)");
            return true;
        }
        for (Entity e : player.getNearbyEntities(30, 30, 30)) {
            NPC npc = NPCLoader.fromBukkit(e);
            if (npc == null)
                continue;
            if (npc.getEntityType() == EntityType.PLAYER) {
                PlayerNPC pnpc = npc.getPlayerNPC();
                if (args[0].equalsIgnoreCase("rot")) {
                    pnpc.refreshRotationFor(player);
                } else if (args[0].equalsIgnoreCase("loc")) {
                    pnpc.updateLocationFor(player, e.getLocation().getPitch(), e.getLocation().getYaw());
                } else if (args[0].equalsIgnoreCase("set")) {
                    pnpc.updateLocationFor(player, parseFloat(sender, args[1]), parseFloat(sender, args[2]));
                } else if (args[0].equalsIgnoreCase("info")) {
                    player.sendMessage(e.getEntityId() + ": " + StringUtil.locToString(e.getLocation()) + " [" + e.getLocation().getPitch() + ", " + e.getLocation().getYaw() + "]");
                }
            }
        }
        player.sendMessage("You: " + player.getLocation().getPitch() + ", " + player.getLocation().getYaw());
    } else if (label.equalsIgnoreCase("testrevealallinvisible")) {
        for (Entity e : player.getWorld().getEntities()) {
            if (e instanceof LivingEntity) {
                ((LivingEntity) e).setInvisible(false);
            }
        }
    } else if (label.equalsIgnoreCase("testinventoryreload")) {
        if (args.length == 0) {
            sender.sendMessage("/" + label + " <simple|full>");
        } else if (args[0].equalsIgnoreCase("simple")) {
            player.updateInventory();
        } else if (args[0].equalsIgnoreCase("full")) {
            Document inv = new Document(user.getInventoryAsDocument());
            player.getInventory().clear();
            user.loadInventory(LOGGER.newCID(), inv);
        }
    } else if (label.equalsIgnoreCase("tptoentity")) {
        if (args.length == 0) {
            sender.sendMessage("/tptoentity <entity id>");
            return true;
        }
        int id = parseInt(sender, args[0]);
        for (Entity entity : dragons.getEntities()) {
            if (entity.getEntityId() == id) {
                player.teleport(entity);
                NPC npc = NPCLoader.fromBukkit(entity);
                if (npc != null) {
                    player.sendMessage("NPC: " + npc.getNPCClass().getClassName());
                }
                return true;
            }
        }
        player.sendMessage("Not found");
    } else {
        sender.sendMessage(ChatColor.RED + "Invalid experimental command! Was it removed or registered improperly?");
    }
    return true;
}
Also used : Document(org.bson.Document) MessageHandler(mc.dragons.core.networking.MessageHandler) NPCLoader(mc.dragons.core.gameobject.npc.NPCLoader) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) Slime(org.bukkit.entity.Slime) User(mc.dragons.core.gameobject.user.User) Player(org.bukkit.entity.Player) ItemLoader(mc.dragons.core.gameobject.item.ItemLoader) Block(org.bukkit.block.Block) Location(org.bukkit.Location) World(org.bukkit.World) StorageUtil(mc.dragons.core.storage.StorageUtil) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) StringUtil(mc.dragons.core.util.StringUtil) CommandSender(org.bukkit.command.CommandSender) UserLoader(mc.dragons.core.gameobject.user.UserLoader) Entity(org.bukkit.entity.Entity) Set(java.util.Set) UUID(java.util.UUID) Item(mc.dragons.core.gameobject.item.Item) EntityType(org.bukkit.entity.EntityType) LivingEntity(org.bukkit.entity.LivingEntity) SystemProfileFlag(mc.dragons.core.gameobject.user.permission.SystemProfile.SystemProfileFlags.SystemProfileFlag) Collectors(java.util.stream.Collectors) ItemStack(org.bukkit.inventory.ItemStack) Base64(java.util.Base64) List(java.util.List) EulerAngle(org.bukkit.util.EulerAngle) GameObject(mc.dragons.core.gameobject.GameObject) GUI(mc.dragons.core.gui.GUI) StorageManager(mc.dragons.core.storage.StorageManager) BukkitUtil.sync(mc.dragons.core.util.BukkitUtil.sync) HologramUtil(mc.dragons.core.util.HologramUtil) Command(org.bukkit.command.Command) PersistentDataType(org.bukkit.persistence.PersistentDataType) GUIElement(mc.dragons.core.gui.GUIElement) Level(java.util.logging.Level) TextComponent(net.md_5.bungee.api.chat.TextComponent) GameObjectType(mc.dragons.core.gameobject.GameObjectType) DragonsCommandExecutor(mc.dragons.core.commands.DragonsCommandExecutor) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) PathfindingUtil(mc.dragons.core.util.PathfindingUtil) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) Dragons(mc.dragons.core.Dragons) Particle(org.bukkit.Particle) StorageAccess(mc.dragons.core.storage.StorageAccess) ArmorStand(org.bukkit.entity.ArmorStand) ChatColor(org.bukkit.ChatColor) NPC(mc.dragons.core.gameobject.npc.NPC) BukkitUtil.rollingAsync(mc.dragons.core.util.BukkitUtil.rollingAsync) PlayerEventListeners(mc.dragons.core.events.PlayerEventListeners) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) NPC(mc.dragons.core.gameobject.npc.NPC) Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) User(mc.dragons.core.gameobject.user.User) StorageManager(mc.dragons.core.storage.StorageManager) GUIElement(mc.dragons.core.gui.GUIElement) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) Document(org.bson.Document) World(org.bukkit.World) LivingEntity(org.bukkit.entity.LivingEntity) Item(mc.dragons.core.gameobject.item.Item) ArmorStand(org.bukkit.entity.ArmorStand) GameObject(mc.dragons.core.gameobject.GameObject) GUI(mc.dragons.core.gui.GUI) UUID(java.util.UUID) StorageAccess(mc.dragons.core.storage.StorageAccess) TextComponent(net.md_5.bungee.api.chat.TextComponent) Player(org.bukkit.entity.Player) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) Slime(org.bukkit.entity.Slime) Block(org.bukkit.block.Block) Level(java.util.logging.Level) ItemStack(org.bukkit.inventory.ItemStack) EulerAngle(org.bukkit.util.EulerAngle) PlayerNPC(mc.dragons.core.bridge.PlayerNPC) Location(org.bukkit.Location)

Aggregations

User (mc.dragons.core.gameobject.user.User)2 UserLoader (mc.dragons.core.gameobject.user.UserLoader)2 Document (org.bson.Document)2 Location (org.bukkit.Location)2 Block (org.bukkit.block.Block)2 Player (org.bukkit.entity.Player)2 BukkitWorld (com.sk89q.worldedit.bukkit.BukkitWorld)1 Base64 (java.util.Base64)1 List (java.util.List)1 Set (java.util.Set)1 UUID (java.util.UUID)1 Level (java.util.logging.Level)1 Collectors (java.util.stream.Collectors)1 Dragons (mc.dragons.core.Dragons)1 PlayerNPC (mc.dragons.core.bridge.PlayerNPC)1 DragonsCommandExecutor (mc.dragons.core.commands.DragonsCommandExecutor)1 PlayerEventListeners (mc.dragons.core.events.PlayerEventListeners)1 GameObject (mc.dragons.core.gameobject.GameObject)1 GameObjectType (mc.dragons.core.gameobject.GameObjectType)1 Item (mc.dragons.core.gameobject.item.Item)1