Search in sources :

Example 1 with CorrelationLogger

use of mc.dragons.core.logging.correlation.CorrelationLogger 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 CorrelationLogger

use of mc.dragons.core.logging.correlation.CorrelationLogger in project DragonsOnline by UniverseCraft.

the class Dragons method onEnable.

@Override
public void onEnable() {
    BukkitUtil.initRollingSync();
    playerNPCRegistry = new PlayerNPCRegistry(this);
    // Game objects must be loaded from database in a particular sequence, to ensure
    // all dependencies are ready.
    // For example, items cannot be loaded before their item classes have been loaded,
    // and regions cannot be loaded before their associated floors have been loaded.
    getLogger().info("Loading game objects...");
    GameObjectType.getLoader(FloorLoader.class).lazyLoadAll();
    GameObjectType.getLoader(RegionLoader.class).lazyLoadAll();
    GameObjectType.getLoader(ItemClassLoader.class).lazyLoadAll();
    GameObjectType.getLoader(NPCClassLoader.class).lazyLoadAll();
    GameObjectType.getLoader(QuestLoader.class).lazyLoadAll();
    // If the server did not shut down gracefully (and sometimes if it did) there may be
    // entities remaining from the previous instance which are no longer linked to a
    // live game object. These entities need to be purged as they will not be responsive
    // to new game events.
    getLogger().info("Removing stale entities...");
    boolean hasFixed = false;
    for (Entity e : getEntities()) {
        if (e.getPersistentDataContainer().has(FIXED_ENTITY_KEY, PersistentDataType.SHORT)) {
            getLogger().verbose("-Skipping fixed entity #" + e.getEntityId());
            hasFixed = true;
            continue;
        }
        if (e instanceof ItemFrame) {
            getLogger().verbose("-Skipping item frame #" + e.getEntityId());
            continue;
        }
        e.remove();
    }
    if (hasFixed) {
        getLogger().notice("The use of fixed entities is not automatically synced across servers the same way that persistent NPCs are.\n" + "Instead, the appropriate world files must be copied.");
    }
    new BukkitRunnable() {

        @Override
        public void run() {
            GameObjectType.getLoader(NPCLoader.class).lazyLoadAllPermanent();
            getLogger().info("Flushing invalid game objects from initial load...");
            new BukkitRunnable() {

                int i = 1;

                @Override
                public void run() {
                    verifyGameIntegrityRunnable.run(true);
                    i++;
                    if (i >= 5) {
                        cancel();
                        getLogger().info("... flush complete. Entity count: " + getEntities().size());
                        joinable = true;
                        getLogger().info("Server is now joinable");
                    }
                }
            }.runTaskTimer(Dragons.this, 20L, 20L);
        }
    }.runTaskLater(this, 20L);
    getLogger().info("Registering lightweight object loaders...");
    lightweightLoaderRegistry.register(new ChangeLogLoader(mongoConfig));
    lightweightLoaderRegistry.register(new FeedbackLoader(mongoConfig));
    lightweightLoaderRegistry.register(new WarpLoader(mongoConfig));
    lightweightLoaderRegistry.register(new CorrelationLogger(mongoConfig));
    lightweightLoaderRegistry.register(new SystemProfileLoader(this));
    lightweightLoaderRegistry.register(new GlobalVarLoader(mongoConfig));
    lightweightLoaderRegistry.register(new StateLoader(mongoConfig));
    UserLoader.lazyLoadGlobalVarLoader();
    getLogger().info("Registering events...");
    PluginManager pluginManager = getServer().getPluginManager();
    pluginManager.registerEvents(new EntityDeathListener(this), this);
    pluginManager.registerEvents(new EntityDamageListener(this), this);
    pluginManager.registerEvents(new WorldEventListeners(this), this);
    pluginManager.registerEvents(new EntityTargetEventListener(this), this);
    pluginManager.registerEvents(new InventoryEventListeners(), this);
    pluginManager.registerEvents(new PlayerEventListeners(this), this);
    pluginManager.registerEvents(new EntityCombustListener(), this);
    pluginManager.registerEvents(new SlimeSplitEventListener(this), this);
    getLogger().info("Registering packet listeners...");
    if (verifyProtocolLib()) {
        ProtocolLibrary.getProtocolManager().addPacketListener(new EntityMoveListener(this));
        entityHider = new EntityHider(this, EntityHider.Policy.BLACKLIST);
    }
    getLogger().info("Registering commands...");
    getCommand("dragons").setExecutor(new DragonsCommand());
    getCommand("rank").setExecutor(new RankCommand());
    getCommand("autorank").setExecutor(new AutoRankCommand());
    getCommand("syslogon").setExecutor(new SystemLogonCommand());
    getCommand("respawn").setExecutor(new RespawnCommand());
    getCommand("heal").setExecutor(new HealCommand());
    getCommand("feedback").setExecutor(new FeedbackCommand());
    getCommand("myquests").setExecutor(new MyQuestsCommand());
    getCommand("help").setExecutor(new HelpCommand());
    getCommand("stuckquest").setExecutor(new StuckQuestCommand());
    getCommand("restartinstance").setExecutor(new RestartInstanceCommand());
    getCommand("logout").setExecutor(new LogoutCommand());
    CommandExecutor stateCommands = new StateCommands();
    getCommand("getstate").setExecutor(stateCommands);
    getCommand("setstate").setExecutor(stateCommands);
    QuestDialogueCommands questDialogueCommands = new QuestDialogueCommands();
    getCommand("fastforwarddialogue").setExecutor(questDialogueCommands);
    getCommand("questchoice").setExecutor(questDialogueCommands);
    ChangeLogCommands changeLogCommandsExecutor = new ChangeLogCommands();
    getCommand("news").setExecutor(changeLogCommandsExecutor);
    getCommand("newsmanager").setExecutor(changeLogCommandsExecutor);
    CommandExecutor chatCommands = new ChatOptionsCommand();
    getCommand("chatoptions").setExecutor(chatCommands);
    getCommand("chatreply").setExecutor(chatCommands);
    getLogger().info("Scheduling tasks...");
    autoSaveRunnable.runTaskTimer(this, 0L, serverOptions.getAutoSavePeriodTicks());
    spawnEntityRunnable.runTaskTimer(this, 0L, serverOptions.getCustomSpawnRate());
    verifyGameIntegrityRunnable.runTaskTimer(this, 0L, serverOptions.getVerifyIntegritySweepRate());
    lagMeter.runTaskTimer(this, 100L, 1L);
    lagMonitorTask.runTaskAsynchronously(this);
    updateScoreboardTask.runTaskTimer(this, 100L, 20L);
    BukkitUtil.syncPeriodic(() -> Bukkit.getOnlinePlayers().stream().map(p -> UserLoader.fromPlayer(p)).forEach(u -> u.updateTablistHeaders()), 20 * 10, 20 * 5);
    getLogger().info("Registering message handlers...");
    internalMessageHandler = new InternalMessageHandler(this);
    remoteAdminHandler = new RemoteAdminMessageHandler(this);
    staffAlertHandler = new StaffAlertMessageHandler(this);
    getLogger().info("Enabling addons...");
    addonRegistry.enableAll();
}
Also used : Plugin(org.bukkit.plugin.Plugin) NPCLoader(mc.dragons.core.gameobject.npc.NPCLoader) UserHookRegistry(mc.dragons.core.gameobject.user.UserHookRegistry) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) SystemProfileLoader(mc.dragons.core.gameobject.user.permission.SystemProfileLoader) PermissionUtil(mc.dragons.core.util.PermissionUtil) SidebarManager(mc.dragons.core.gameobject.user.SidebarManager) UpdateScoreboardTask(mc.dragons.core.tasks.UpdateScoreboardTask) Bridge(mc.dragons.core.bridge.Bridge) User(mc.dragons.core.gameobject.user.User) DragonsCommand(mc.dragons.core.commands.DragonsCommand) NPCClassLoader(mc.dragons.core.gameobject.npc.NPCClassLoader) PlayerNPCRegistry(mc.dragons.core.gameobject.npc.PlayerNPCRegistry) StaffAlertMessageHandler(mc.dragons.core.networking.StaffAlertMessageHandler) MessageDispatcher(mc.dragons.core.networking.MessageDispatcher) WarpLoader(mc.dragons.core.storage.loader.WarpLoader) LagMonitorTask(mc.dragons.core.tasks.LagMonitorTask) InternalMessageHandler(mc.dragons.core.networking.InternalMessageHandler) PermissionLevel(mc.dragons.core.gameobject.user.permission.PermissionLevel) ItemFrame(org.bukkit.entity.ItemFrame) ObjectUtil(mc.dragons.core.util.ObjectUtil) World(org.bukkit.World) GlobalVarLoader(mc.dragons.core.storage.loader.GlobalVarLoader) Chunk(org.bukkit.Chunk) QuestDialogueCommands(mc.dragons.core.commands.QuestDialogueCommands) AutoRankCommand(mc.dragons.core.commands.AutoRankCommand) EntityMoveListener(mc.dragons.core.events.EntityMoveListener) Bukkit(org.bukkit.Bukkit) StuckQuestCommand(mc.dragons.core.commands.StuckQuestCommand) QuestLoader(mc.dragons.core.gameobject.quest.QuestLoader) ChangeLogCommands(mc.dragons.core.commands.ChangeLogCommands) MyQuestsCommand(mc.dragons.core.commands.MyQuestsCommand) UserLoader(mc.dragons.core.gameobject.user.UserLoader) Entity(org.bukkit.entity.Entity) FloorLoader(mc.dragons.core.gameobject.floor.FloorLoader) SystemLogonCommand(mc.dragons.core.commands.SystemLogonCommand) EntityHider(mc.dragons.core.util.EntityHider) UUID(java.util.UUID) EntityCombustListener(mc.dragons.core.events.EntityCombustListener) ItemClassLoader(mc.dragons.core.gameobject.item.ItemClassLoader) FeedbackLoader(mc.dragons.core.storage.loader.FeedbackLoader) LightweightLoaderRegistry(mc.dragons.core.storage.loader.LightweightLoaderRegistry) List(java.util.List) LogoutCommand(mc.dragons.core.commands.LogoutCommand) ChatMessageRegistry(mc.dragons.core.gameobject.user.chat.ChatMessageRegistry) RankCommand(mc.dragons.core.commands.RankCommand) StorageManager(mc.dragons.core.storage.StorageManager) LagMeter(mc.dragons.core.tasks.LagMeter) SingletonReInstantiationException(mc.dragons.core.util.singletons.SingletonReInstantiationException) ChatOptionsCommand(mc.dragons.core.commands.ChatOptionsCommand) RestartInstanceCommand(mc.dragons.core.commands.RestartInstanceCommand) ProtocolManager(com.comphenix.protocol.ProtocolManager) PersistentDataType(org.bukkit.persistence.PersistentDataType) MongoStorageManager(mc.dragons.core.storage.mongo.MongoStorageManager) AutoSaveTask(mc.dragons.core.tasks.AutoSaveTask) MongoConfig(mc.dragons.core.storage.mongo.MongoConfig) ProtocolLibrary(com.comphenix.protocol.ProtocolLibrary) AddonRegistry(mc.dragons.core.addon.AddonRegistry) HelpCommand(mc.dragons.core.commands.HelpCommand) StateCommands(mc.dragons.core.commands.StateCommands) FeedbackCommand(mc.dragons.core.commands.FeedbackCommand) StateLoader(mc.dragons.core.gameobject.user.StateLoader) BukkitUtil(mc.dragons.core.util.BukkitUtil) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) GameObjectType(mc.dragons.core.gameobject.GameObjectType) RegionLoader(mc.dragons.core.gameobject.region.RegionLoader) HealCommand(mc.dragons.core.commands.HealCommand) CustomLoggingProvider(mc.dragons.core.logging.CustomLoggingProvider) ChangeLogLoader(mc.dragons.core.storage.loader.ChangeLogLoader) GameObjectRegistry(mc.dragons.core.gameobject.GameObjectRegistry) EntityDeathListener(mc.dragons.core.events.EntityDeathListener) BridgeSpigot116R3(mc.dragons.core.bridge.impl.BridgeSpigot116R3) LocalStorageManager(mc.dragons.core.storage.local.LocalStorageManager) RespawnCommand(mc.dragons.core.commands.RespawnCommand) EntityDamageListener(mc.dragons.core.events.EntityDamageListener) NamespacedKey(org.bukkit.NamespacedKey) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) WorldEventListeners(mc.dragons.core.events.WorldEventListeners) SpawnEntityTask(mc.dragons.core.tasks.SpawnEntityTask) CommandExecutor(org.bukkit.command.CommandExecutor) EntityTargetEventListener(mc.dragons.core.events.EntityTargetEventListener) InventoryEventListeners(mc.dragons.core.events.InventoryEventListeners) VerifyGameIntegrityTask(mc.dragons.core.tasks.VerifyGameIntegrityTask) SlimeSplitEventListener(mc.dragons.core.events.SlimeSplitEventListener) Singletons(mc.dragons.core.util.singletons.Singletons) ChatColor(org.bukkit.ChatColor) PluginManager(org.bukkit.plugin.PluginManager) PlayerEventListeners(mc.dragons.core.events.PlayerEventListeners) RemoteAdminMessageHandler(mc.dragons.core.networking.RemoteAdminMessageHandler) Entity(org.bukkit.entity.Entity) RemoteAdminMessageHandler(mc.dragons.core.networking.RemoteAdminMessageHandler) SystemLogonCommand(mc.dragons.core.commands.SystemLogonCommand) WarpLoader(mc.dragons.core.storage.loader.WarpLoader) CommandExecutor(org.bukkit.command.CommandExecutor) ChangeLogLoader(mc.dragons.core.storage.loader.ChangeLogLoader) ItemFrame(org.bukkit.entity.ItemFrame) RegionLoader(mc.dragons.core.gameobject.region.RegionLoader) FeedbackLoader(mc.dragons.core.storage.loader.FeedbackLoader) FeedbackCommand(mc.dragons.core.commands.FeedbackCommand) PluginManager(org.bukkit.plugin.PluginManager) InventoryEventListeners(mc.dragons.core.events.InventoryEventListeners) QuestLoader(mc.dragons.core.gameobject.quest.QuestLoader) EntityMoveListener(mc.dragons.core.events.EntityMoveListener) EntityTargetEventListener(mc.dragons.core.events.EntityTargetEventListener) AutoRankCommand(mc.dragons.core.commands.AutoRankCommand) RankCommand(mc.dragons.core.commands.RankCommand) HelpCommand(mc.dragons.core.commands.HelpCommand) EntityHider(mc.dragons.core.util.EntityHider) SlimeSplitEventListener(mc.dragons.core.events.SlimeSplitEventListener) StaffAlertMessageHandler(mc.dragons.core.networking.StaffAlertMessageHandler) RestartInstanceCommand(mc.dragons.core.commands.RestartInstanceCommand) HealCommand(mc.dragons.core.commands.HealCommand) LogoutCommand(mc.dragons.core.commands.LogoutCommand) GlobalVarLoader(mc.dragons.core.storage.loader.GlobalVarLoader) ItemClassLoader(mc.dragons.core.gameobject.item.ItemClassLoader) EntityDamageListener(mc.dragons.core.events.EntityDamageListener) StateCommands(mc.dragons.core.commands.StateCommands) AutoRankCommand(mc.dragons.core.commands.AutoRankCommand) PlayerEventListeners(mc.dragons.core.events.PlayerEventListeners) FloorLoader(mc.dragons.core.gameobject.floor.FloorLoader) CorrelationLogger(mc.dragons.core.logging.correlation.CorrelationLogger) QuestDialogueCommands(mc.dragons.core.commands.QuestDialogueCommands) DragonsCommand(mc.dragons.core.commands.DragonsCommand) ChatOptionsCommand(mc.dragons.core.commands.ChatOptionsCommand) StateLoader(mc.dragons.core.gameobject.user.StateLoader) ChangeLogCommands(mc.dragons.core.commands.ChangeLogCommands) PlayerNPCRegistry(mc.dragons.core.gameobject.npc.PlayerNPCRegistry) EntityDeathListener(mc.dragons.core.events.EntityDeathListener) InternalMessageHandler(mc.dragons.core.networking.InternalMessageHandler) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) StuckQuestCommand(mc.dragons.core.commands.StuckQuestCommand) MyQuestsCommand(mc.dragons.core.commands.MyQuestsCommand) RespawnCommand(mc.dragons.core.commands.RespawnCommand) NPCClassLoader(mc.dragons.core.gameobject.npc.NPCClassLoader) EntityCombustListener(mc.dragons.core.events.EntityCombustListener) SystemProfileLoader(mc.dragons.core.gameobject.user.permission.SystemProfileLoader) WorldEventListeners(mc.dragons.core.events.WorldEventListeners)

Aggregations

List (java.util.List)2 UUID (java.util.UUID)2 Level (java.util.logging.Level)2 PlayerEventListeners (mc.dragons.core.events.PlayerEventListeners)2 GameObjectType (mc.dragons.core.gameobject.GameObjectType)2 NPCLoader (mc.dragons.core.gameobject.npc.NPCLoader)2 ProtocolLibrary (com.comphenix.protocol.ProtocolLibrary)1 ProtocolManager (com.comphenix.protocol.ProtocolManager)1 ArrayList (java.util.ArrayList)1 Base64 (java.util.Base64)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 Dragons (mc.dragons.core.Dragons)1 AddonRegistry (mc.dragons.core.addon.AddonRegistry)1 Bridge (mc.dragons.core.bridge.Bridge)1 PlayerNPC (mc.dragons.core.bridge.PlayerNPC)1 BridgeSpigot116R3 (mc.dragons.core.bridge.impl.BridgeSpigot116R3)1 AutoRankCommand (mc.dragons.core.commands.AutoRankCommand)1 ChangeLogCommands (mc.dragons.core.commands.ChangeLogCommands)1 ChatOptionsCommand (mc.dragons.core.commands.ChatOptionsCommand)1