Search in sources :

Example 1 with StorageManager

use of mc.dragons.core.storage.StorageManager 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)

Example 2 with StorageManager

use of mc.dragons.core.storage.StorageManager in project DragonsOnline by UniverseCraft.

the class ObjectCommands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
        return true;
    GameObjectRegistry registry = dragons.getGameObjectRegistry();
    StorageManager localStorageManager = dragons.getLocalStorageManager();
    if (label.equalsIgnoreCase("autosave")) {
        Dragons.getInstance().getGameObjectRegistry().executeAutoSave(true);
        sender.sendMessage(ChatColor.GREEN + "Auto-save executed successfully.");
    } else if (label.equalsIgnoreCase("invalidate")) {
        if (args.length < 2) {
            sender.sendMessage(ChatColor.RED + "/invalidate <type> <uuid>");
            return true;
        }
        GameObjectType type = StringUtil.parseEnum(sender, GameObjectType.class, args[0].toUpperCase());
        UUID uuid = StringUtil.parseUUID(sender, args[1]);
        if (type == null || uuid == null)
            return true;
        boolean result = registry.getRegisteredObjects().removeIf(obj -> obj.getType() == type && obj.getUUID().equals(uuid));
        if (result) {
            sender.sendMessage(ChatColor.GREEN + "Invalidated game object " + type + "#" + uuid + ".");
        } else {
            sender.sendMessage(ChatColor.RED + "Unable to locate game object (is it registered properly?)");
        }
    } else if (label.equalsIgnoreCase("invalidateall")) {
        registry.getRegisteredObjects().clear();
        sender.sendMessage(ChatColor.GREEN + "Invalidated all game objects.");
    } else if (label.equalsIgnoreCase("invalidatetype")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.RED + "/invalidatetype <type>");
            return true;
        }
        GameObjectType type = StringUtil.parseEnum(sender, GameObjectType.class, args[0].toUpperCase());
        if (type == null)
            return true;
        registry.getRegisteredObjects().removeIf(obj -> obj.getType() == type);
        sender.sendMessage(ChatColor.GREEN + "Invalidated all game objects of type " + type);
    } else if (label.equalsIgnoreCase("invalidateuser")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.RED + "/invalidateuser <player>");
            return true;
        }
        boolean result = UserLoader.allUsers().removeIf(u -> u.getName().equalsIgnoreCase(args[0]));
        result &= registry.getRegisteredObjects(GameObjectType.USER).removeIf(u -> ((User) u).getName().equalsIgnoreCase(args[0]));
        if (result) {
            sender.sendMessage(ChatColor.GREEN + "Invalidated user " + args[0]);
        } else {
            sender.sendMessage(ChatColor.RED + "That user was not found locally!");
        }
    } else if (label.equalsIgnoreCase("localize")) {
        if (args.length < 2) {
            sender.sendMessage(ChatColor.RED + "/localize <type> <uuid>");
            return true;
        }
        GameObjectType type = StringUtil.parseEnum(sender, GameObjectType.class, args[0].toUpperCase());
        UUID uuid = StringUtil.parseUUID(sender, args[1]);
        if (type == null || uuid == null)
            return true;
        registry.getRegisteredObjects().stream().filter(obj -> obj.getType() == type && obj.getUUID().equals(uuid)).forEach(obj -> obj.replaceStorageAccess(localStorageManager.getNewStorageAccess(type, obj.getData())));
        sender.sendMessage(ChatColor.GREEN + "Localized game object " + type + "#" + uuid + ".");
    } else if (label.equalsIgnoreCase("localizeall")) {
        registry.getRegisteredObjects().forEach(obj -> obj.replaceStorageAccess(localStorageManager.getNewStorageAccess(obj.getType(), obj.getData())));
        sender.sendMessage(ChatColor.GREEN + "Localized all game objects.");
    } else if (label.equalsIgnoreCase("localizetype")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.RED + "/localizetype <type>");
            return true;
        }
        GameObjectType type = StringUtil.parseEnum(sender, GameObjectType.class, args[0].toUpperCase());
        if (type == null)
            return true;
        registry.getRegisteredObjects().stream().filter(obj -> obj.getType() == type).forEach(obj -> obj.replaceStorageAccess(localStorageManager.getNewStorageAccess(type, obj.getData())));
        sender.sendMessage(ChatColor.GREEN + "Localized all game objects of type " + type);
    } else if (label.equalsIgnoreCase("localizeuser")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.RED + "/localizeuser <player>");
            return true;
        }
        UserLoader.allUsers().stream().filter(u -> u.getName().equalsIgnoreCase(args[0])).forEach(u -> u.replaceStorageAccess(localStorageManager.getNewStorageAccess(GameObjectType.USER, u.getData())));
        sender.sendMessage(ChatColor.GREEN + "Localized user " + args[0]);
    }
    return true;
}
Also used : StringUtil(mc.dragons.core.util.StringUtil) CommandSender(org.bukkit.command.CommandSender) UserLoader(mc.dragons.core.gameobject.user.UserLoader) User(mc.dragons.core.gameobject.user.User) UUID(java.util.UUID) SystemProfileFlag(mc.dragons.core.gameobject.user.permission.SystemProfile.SystemProfileFlags.SystemProfileFlag) Dragons(mc.dragons.core.Dragons) GameObjectType(mc.dragons.core.gameobject.GameObjectType) DragonsCommandExecutor(mc.dragons.core.commands.DragonsCommandExecutor) StorageManager(mc.dragons.core.storage.StorageManager) GameObjectRegistry(mc.dragons.core.gameobject.GameObjectRegistry) ChatColor(org.bukkit.ChatColor) Command(org.bukkit.command.Command) GameObjectType(mc.dragons.core.gameobject.GameObjectType) StorageManager(mc.dragons.core.storage.StorageManager) UUID(java.util.UUID) GameObjectRegistry(mc.dragons.core.gameobject.GameObjectRegistry)

Example 3 with StorageManager

use of mc.dragons.core.storage.StorageManager in project DragonsOnline by UniverseCraft.

the class IPAnalysisUtil method scanAlts.

public static Set<User> scanAlts(StorageManager storageManager, User target) {
    Set<User> alts = storageManager.getAllStorageAccess(GameObjectType.USER, new Document("ipHistory", new Document("$in", target.getIPHistory()))).stream().map(storageAccess -> userLoader.loadObject(storageAccess)).sorted((u, v) -> WrappedUser.of(u).getPunishmentHistory().size() - WrappedUser.of(v).getPunishmentHistory().size()).collect(Collectors.toSet());
    alts.remove(target);
    return alts;
}
Also used : Document(org.bson.Document) WrappedUser(mc.dragons.tools.moderation.WrappedUser) GameObjectType(mc.dragons.core.gameobject.GameObjectType) UserLoader(mc.dragons.core.gameobject.user.UserLoader) StorageManager(mc.dragons.core.storage.StorageManager) Set(java.util.Set) User(mc.dragons.core.gameobject.user.User) Collectors(java.util.stream.Collectors) WrappedUser(mc.dragons.tools.moderation.WrappedUser) User(mc.dragons.core.gameobject.user.User) Document(org.bson.Document)

Example 4 with StorageManager

use of mc.dragons.core.storage.StorageManager in project DragonsOnline by UniverseCraft.

the class DragonsResidences method resetResWorld.

private void resetResWorld() {
    getLogger().info("Resetting residential world...");
    resetResWorld_recursiveStep(new File("res_temp"));
    WorldCreator creator = WorldCreator.name("res_temp");
    creator.type(WorldType.FLAT);
    Bukkit.createWorld(creator);
    StorageManager lsm = dragons.getLocalStorageManager();
    StorageAccess lsa = lsm.getNewStorageAccess(GameObjectType.FLOOR, new Document("worldName", "res_temp").append("floorName", "RES").append("displayName", "Residence").append("levelMin", 0).append("volatile", true).append("status", FloorStatus.LIVE.toString()));
    Floor resFloor = new Floor(lsm, lsa, true);
    FloorLoader.link(Bukkit.getWorld("res_temp"), resFloor);
    dragons.getGameObjectRegistry().getRegisteredObjects().add(resFloor);
}
Also used : Floor(mc.dragons.core.gameobject.floor.Floor) WorldCreator(org.bukkit.WorldCreator) StorageManager(mc.dragons.core.storage.StorageManager) Document(org.bson.Document) File(java.io.File) StorageAccess(mc.dragons.core.storage.StorageAccess)

Example 5 with StorageManager

use of mc.dragons.core.storage.StorageManager in project DragonsOnline by UniverseCraft.

the class NPCLoader method loadObject.

public NPC loadObject(StorageAccess storageAccess, List<BukkitRunnable> spawnRunnables) {
    lazyLoadAllPermanent();
    UUID uuid = storageAccess.getIdentifier().getUUID();
    if (uuidToNpc.containsKey(uuid)) {
        LOGGER.debug("Prevented spawn of duplicate NPC " + uuid);
        return uuidToNpc.get(uuid);
    }
    LOGGER.trace("Loading NPC " + storageAccess.getIdentifier());
    NPC.NPCType npcType = NPC.NPCType.valueOf((String) storageAccess.get("npcType"));
    Location loc = StorageUtil.docToLoc((Document) storageAccess.get("lastLocation"));
    NPC npc = new NPC(loc, spawnRunnables, npcType.isPersistent() ? storageManager : (StorageManager) localStorageManager, npcType.isPersistent() ? storageAccess : (StorageAccess) localStorageManager.downgrade(storageAccess));
    masterRegistry.getRegisteredObjects().add(npc);
    return npc;
}
Also used : LocalStorageManager(mc.dragons.core.storage.local.LocalStorageManager) StorageManager(mc.dragons.core.storage.StorageManager) UUID(java.util.UUID) NPCType(mc.dragons.core.gameobject.npc.NPC.NPCType) LocalStorageAccess(mc.dragons.core.storage.local.LocalStorageAccess) StorageAccess(mc.dragons.core.storage.StorageAccess) Location(org.bukkit.Location)

Aggregations

StorageManager (mc.dragons.core.storage.StorageManager)6 UUID (java.util.UUID)4 GameObjectType (mc.dragons.core.gameobject.GameObjectType)4 StorageAccess (mc.dragons.core.storage.StorageAccess)4 Document (org.bson.Document)4 Set (java.util.Set)3 Dragons (mc.dragons.core.Dragons)3 User (mc.dragons.core.gameobject.user.User)3 UserLoader (mc.dragons.core.gameobject.user.UserLoader)3 ChatColor (org.bukkit.ChatColor)3 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 DragonsCommandExecutor (mc.dragons.core.commands.DragonsCommandExecutor)2 GameObjectRegistry (mc.dragons.core.gameobject.GameObjectRegistry)2 SystemProfileFlag (mc.dragons.core.gameobject.user.permission.SystemProfile.SystemProfileFlags.SystemProfileFlag)2 BukkitUtil.sync (mc.dragons.core.util.BukkitUtil.sync)2 StringUtil (mc.dragons.core.util.StringUtil)2 Bukkit (org.bukkit.Bukkit)2 Command (org.bukkit.command.Command)2 CommandSender (org.bukkit.command.CommandSender)2