Search in sources :

Example 1 with Dragons

use of mc.dragons.core.Dragons in project DragonsOnline by UniverseCraft.

the class DragonsSpells method onLoad.

public void onLoad() {
    enableDebugLogging();
    Dragons dragons = getDragonsInstance();
    getLogger().info("Loading item addons...");
    spellRegistry = new SpellRegistry();
    AddonRegistry registry = dragons.getAddonRegistry();
    registry.register(spellCastAddon = new SpellCastAddon(this));
    registry.register(spellScrollAddon = new SpellScrollAddon());
    dragons.getUserHookRegistry().registerHook(new SpellUserHook(this));
    // Instantiate all spells here
    new TestSpell(this);
}
Also used : Dragons(mc.dragons.core.Dragons) AddonRegistry(mc.dragons.core.addon.AddonRegistry) TestSpell(mc.dragons.spells.spells.TestSpell) SpellRegistry(mc.dragons.spells.spells.SpellRegistry)

Example 2 with Dragons

use of mc.dragons.core.Dragons in project DragonsOnline by UniverseCraft.

the class DragonsSocial method onEnable.

public void onEnable() {
    enableDebugLogging();
    Dragons dragons = getDragonsInstance();
    PartyLoader partyLoader = new PartyLoader(dragons);
    dragons.getLightweightLoaderRegistry().register(partyLoader);
    partyLoader.loadMessenger();
    dragons.getLightweightLoaderRegistry().register(new GuildLoader(dragons.getMongoConfig()));
    socialHook = new SocialUserHook();
    dragons.getUserHookRegistry().registerHook(socialHook);
    ChatChannel.GUILD.setHandler(new GuildChannelHandler(dragons));
    ChatChannel.PARTY.setHandler(new PartyChannelHandler(dragons));
    getCommand("guild").setExecutor(new GuildCommand());
    getCommand("guildadmin").setExecutor(new GuildAdminCommand());
    DuelCommands duelCommands = new DuelCommands();
    getCommand("duel").setExecutor(duelCommands);
    getCommand("listallduelstatus").setExecutor(duelCommands);
    getCommand("testduelwin").setExecutor(duelCommands);
    PrivateMessageCommands privateMessageCommands = new PrivateMessageCommands(this);
    getCommand("msg").setExecutor(privateMessageCommands);
    getCommand("reply").setExecutor(privateMessageCommands);
    getCommand("chatspy").setExecutor(privateMessageCommands);
    getCommand("toggleselfmessage").setExecutor(privateMessageCommands);
    getCommand("togglemsg").setExecutor(privateMessageCommands);
    BlockCommands blockCommands = new BlockCommands();
    getCommand("block").setExecutor(blockCommands);
    getCommand("unblock").setExecutor(blockCommands);
    getCommand("toggleselfblock").setExecutor(blockCommands);
    FriendCommand friendCommand = new FriendCommand(this);
    getCommand("friend").setExecutor(friendCommand);
    getCommand("toggleselffriend").setExecutor(friendCommand);
    getCommand("dumpFriends").setExecutor(friendCommand);
    PartyCommand partyCommand = new PartyCommand(dragons);
    getCommand("party").setExecutor(partyCommand);
    getCommand("toggleselfparty").setExecutor(partyCommand);
    getCommand("dumpParties").setExecutor(partyCommand);
    getCommand("shout").setExecutor(new ShoutCommand());
    getCommand("channel").setExecutor(new ChannelCommand());
}
Also used : PartyLoader(mc.dragons.social.party.PartyLoader) GuildAdminCommand(mc.dragons.social.guild.GuildAdminCommand) GuildCommand(mc.dragons.social.guild.GuildCommand) PrivateMessageCommands(mc.dragons.social.messaging.PrivateMessageCommands) PartyCommand(mc.dragons.social.party.PartyCommand) PartyChannelHandler(mc.dragons.social.party.PartyChannelHandler) GuildLoader(mc.dragons.social.guild.GuildLoader) ShoutCommand(mc.dragons.social.shout.ShoutCommand) Dragons(mc.dragons.core.Dragons) GuildChannelHandler(mc.dragons.social.guild.GuildChannelHandler) DuelCommands(mc.dragons.social.duel.DuelCommands) FriendCommand(mc.dragons.social.friend.FriendCommand)

Example 3 with Dragons

use of mc.dragons.core.Dragons in project DragonsOnline by UniverseCraft.

the class UserLoader method registerNew.

public User registerNew(Player player) {
    LOGGER.trace("Registering new user " + player.getName());
    Document skills = new Document();
    Document skillProgress = new Document();
    for (SkillType skill : SkillType.values()) {
        skills.append(skill.toString(), 0);
        skillProgress.append(skill.toString(), 0.0D);
    }
    Rank rank = Rank.DEFAULT;
    if (VAR.get("autorank") == null) {
        VAR.set("autorank", new Document());
    }
    String autoRank = VAR.getDocument("autorank").getString(player.getUniqueId().toString());
    if (autoRank != null) {
        rank = Rank.valueOf(autoRank);
        Bukkit.getScheduler().runTaskLater(dragons, () -> {
            player.sendMessage(ChatColor.GREEN + "Your rank of " + autoRank + " was successfully applied.");
        }, 20L * 3);
        Document autoRanks = VAR.getDocument("autorank");
        autoRanks.remove(player.getUniqueId().toString());
        VAR.set("autorank", autoRanks);
    }
    Document data = new Document("_id", player.getUniqueId()).append("username", player.getName()).append("maxHealth", player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()).append("xp", 0).append("level", 1).append("rank", rank.toString()).append("gold", 0.0).append("godMode", false).append("firstJoined", System.currentTimeMillis()).append("lastJoined", System.currentTimeMillis()).append("lastSeen", System.currentTimeMillis()).append("skills", skills).append("skillProgress", skillProgress).append("inventory", new Document()).append("quests", new Document()).append("vanished", false).append("punishmentHistory", new ArrayList<>()).append("chatChannels", new ArrayList<>(List.of(ChatChannel.LOCAL.toString(), ChatChannel.PARTY.toString(), ChatChannel.GUILD.toString()))).append("speakingChannel", ChatChannel.LOCAL.toString()).append("gamemode", GameMode.ADVENTURE.toString()).append("lastReadChangeLog", 0).append("ip", player.getAddress().getAddress().getHostAddress()).append("ipHistory", new ArrayList<>(List.of(player.getAddress().getAddress().getHostAddress()))).append("totalOnlineTime", 0L).append("currentServer", dragons.getServerName()).append("verified", false).append("blockedUsers", new ArrayList<>());
    sync(() -> dragons.getUserHookRegistry().getHooks().forEach(h -> h.onCreateStorageAccess(data)));
    StorageAccess storageAccess = storageManager.getNewStorageAccess(GameObjectType.USER, data);
    User user = new User(player, storageManager, storageAccess);
    assign(player, user);
    users.add(user);
    masterRegistry.getRegisteredObjects().add(user);
    return user;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Document(org.bson.Document) MongoStorageManager(mc.dragons.core.storage.mongo.MongoStorageManager) URL(java.net.URL) Player(org.bukkit.entity.Player) FixedMetadataValue(org.bukkit.metadata.FixedMetadataValue) JSONArray(org.json.simple.JSONArray) ArrayList(java.util.ArrayList) GameMode(org.bukkit.GameMode) GameObjectType(mc.dragons.core.gameobject.GameObjectType) ParseException(org.json.simple.parser.ParseException) DataOutputStream(java.io.DataOutputStream) JSONValue(org.json.simple.JSONValue) GameObjectRegistry(mc.dragons.core.gameobject.GameObjectRegistry) GlobalVarLoader(mc.dragons.core.storage.loader.GlobalVarLoader) Bukkit(org.bukkit.Bukkit) Attribute(org.bukkit.attribute.Attribute) Charsets(com.google.common.base.Charsets) DragonsLogger(mc.dragons.core.logging.DragonsLogger) JSONParser(org.json.simple.parser.JSONParser) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) ChatChannel(mc.dragons.core.gameobject.user.chat.ChatChannel) Singleton(mc.dragons.core.util.singletons.Singleton) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) Reader(java.io.Reader) UUID(java.util.UUID) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) InputStreamReader(java.io.InputStreamReader) Dragons(mc.dragons.core.Dragons) Consumer(java.util.function.Consumer) StorageAccess(mc.dragons.core.storage.StorageAccess) List(java.util.List) JSONObject(org.json.simple.JSONObject) GameObjectLoader(mc.dragons.core.gameobject.GameObjectLoader) StorageManager(mc.dragons.core.storage.StorageManager) BukkitUtil.sync(mc.dragons.core.util.BukkitUtil.sync) Singletons(mc.dragons.core.util.singletons.Singletons) ChatColor(org.bukkit.ChatColor) ArrayList(java.util.ArrayList) Document(org.bson.Document) StorageAccess(mc.dragons.core.storage.StorageAccess)

Example 4 with Dragons

use of mc.dragons.core.Dragons in project DragonsOnline by UniverseCraft.

the class PerformanceCommands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!requirePermission(sender, PermissionLevel.DEVELOPER))
        return true;
    if (label.equalsIgnoreCase("worldperformance")) {
        sender.sendMessage(ChatColor.DARK_GREEN + "World performance statistics for " + dragons.getServerName() + " @ " + StringUtil.dateFormatNow());
        TableGenerator tg = new TableGenerator(Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT);
        tg.addRow(COL_FLOOR, COL_ENTITIES, COL_LIVING, COL_PLAYERS, COL_CHUNKS, COL_POPULATED, COL_RATIO);
        String floorPrefix = ChatColor.YELLOW + "";
        String dataPrefix = ChatColor.GRAY + "";
        for (World w : Bukkit.getWorlds()) {
            long populatedChunks = Arrays.stream(w.getLoadedChunks()).filter(ch -> Arrays.stream(ch.getEntities()).filter(e -> e.getType() == EntityType.PLAYER).count() > 0).count();
            tg.addRowEx("/worldmanager " + w.getName(), "Click to manage performance of " + w.getName(), floorPrefix + w.getName(), dataPrefix + w.getEntities().size(), dataPrefix + w.getLivingEntities().size(), dataPrefix + w.getPlayers().size(), dataPrefix + w.getLoadedChunks().length, dataPrefix + populatedChunks, dataPrefix + MathUtil.round(100 * (double) populatedChunks / w.getLoadedChunks().length) + "%");
        }
        tg.display(sender);
    } else if (label.equalsIgnoreCase("worldmanager")) {
        World w = args.length == 0 ? player(sender).getWorld() : Bukkit.getWorld(args[0]);
        if (w == null) {
            sender.sendMessage(ChatColor.RED + "No world named '" + args[0] + "'");
            return true;
        }
        sender.sendMessage(ChatColor.GREEN + "Manage world " + w.getName());
        sender.spigot().sendMessage(StringUtil.clickableHoverableText(ChatColor.GRAY + " [Manage Floor]", "/floor " + FloorLoader.fromWorld(w).getFloorName(), "Click to manage associated floor"), StringUtil.clickableHoverableText(ChatColor.GRAY + " [Unload Chunks]", "/unloadchunks " + w.getName(), "Click to unload all chunks from this world"), StringUtil.clickableHoverableText(ChatColor.GRAY + " [Reload Chunks]", "/reloadchunks " + w.getName(), "Click to reload all chunks from this world"), StringUtil.clickableHoverableText(ChatColor.GRAY + " [Clear Drops]", "/cleardrops " + w.getName(), "Click to remove all dropped items from this world"), StringUtil.clickableHoverableText(ChatColor.GRAY + " [Clear Mobs]", "/clearmobs " + w.getName(), "Click to remove all non-persistent mobs from this world"));
    } else if (label.equalsIgnoreCase("unloadchunks")) {
        World w = args.length == 0 ? player(sender).getWorld() : Bukkit.getWorld(args[0]);
        if (w == null) {
            sender.sendMessage(ChatColor.RED + "No world named '" + args[0] + "'");
            return true;
        }
        int success = 0;
        int total = 0;
        for (Chunk c : w.getLoadedChunks()) {
            if (c.unload(true))
                success++;
            total++;
        }
        sender.sendMessage(ChatColor.GREEN + "" + success + "/" + total + " chunks unloaded in " + w.getName());
    } else if (label.equalsIgnoreCase("reloadchunks")) {
        World w = args.length == 0 ? player(sender).getWorld() : Bukkit.getWorld(args[0]);
        if (w == null) {
            sender.sendMessage(ChatColor.RED + "No world named '" + args[0] + "'");
            return true;
        }
        int success = 0, total = 0;
        for (Chunk c : w.getLoadedChunks()) {
            if (c.unload(true))
                success++;
            c.load(false);
            total++;
        }
        sender.sendMessage(ChatColor.GREEN + "" + success + "/" + total + " chunks reloaded in " + w.getName());
    } else if (label.equalsIgnoreCase("cleardrops")) {
        World w = args.length == 0 ? player(sender).getWorld() : Bukkit.getWorld(args[0]);
        if (w == null) {
            sender.sendMessage(ChatColor.RED + "No world named '" + args[0] + "'");
            return true;
        }
        int total = 0;
        for (Entity e : w.getEntities()) {
            if (e.getType() == EntityType.DROPPED_ITEM) {
                e.remove();
                total++;
            }
        }
        sender.sendMessage(ChatColor.GREEN + "" + total + " drops cleared in " + w.getName());
    } else if (label.equalsIgnoreCase("clearmobs")) {
        World w = args.length == 0 ? player(sender).getWorld() : Bukkit.getWorld(args[0]);
        if (w == null) {
            sender.sendMessage(ChatColor.RED + "No world named '" + args[0] + "'");
            return true;
        }
        int total = 0;
        for (Entity e : w.getEntities()) {
            if (e instanceof Player || e instanceof Item || e instanceof ItemFrame)
                continue;
            if (e.getPersistentDataContainer().has(Dragons.FIXED_ENTITY_KEY, PersistentDataType.SHORT))
                continue;
            if (e.hasMetadata("allow"))
                continue;
            NPC npc = NPCLoader.fromBukkit(e);
            if (npc == null) {
                e.remove();
                total++;
            } else if (!npc.getNPCType().isPersistent()) {
                npc.remove();
                total++;
            }
        }
        sender.sendMessage(ChatColor.GREEN + "" + total + " mobs cleared in " + w.getName());
    } else if (label.equalsIgnoreCase("getsystemproperties")) {
        sender.sendMessage(ChatColor.GREEN + "Listing all system properties:");
        System.getProperties().forEach((key, value) -> {
            sender.sendMessage(ChatColor.GRAY + "" + key + " = " + value);
        });
    } else if (label.equalsIgnoreCase("serverperformance")) {
        new // some OperatingSystemMXBean operations lag the thread, so run asynchronously
        BukkitRunnable() {

            @Override
            public void run() {
                Properties props = System.getProperties();
                sender.sendMessage(ChatColor.DARK_GREEN + "Server performance statistics generated at " + StringUtil.dateFormatNow());
                sender.sendMessage(ChatColor.GREEN + "Bukkit Version: " + ChatColor.GRAY + Bukkit.getVersion());
                sender.sendMessage(ChatColor.GREEN + "Uptime: " + ChatColor.GRAY + StringUtil.parseSecondsToTimespan(dragons.getUptime() / 1000));
                sender.sendMessage(ChatColor.GREEN + "Estimated Current TPS: " + ChatColor.GRAY + LagMeter.getRoundedTPS());
                sender.sendMessage(ChatColor.GREEN + "Server Architecture: " + ChatColor.GRAY + props.getProperty("os.arch", "Unknown"));
                sender.sendMessage(ChatColor.GREEN + "Operating System: " + ChatColor.GRAY + props.getProperty("os.name", "Unknown") + " v" + props.getProperty("os.version", "Unknown") + " (" + props.getProperty("os.arch", "Unknown Architecture") + ")");
                sender.sendMessage(ChatColor.GREEN + "Java Version: " + ChatColor.GRAY + props.getProperty("java.version", "Unknown") + " (" + props.getProperty("java.vendor", "Unknown Vendor") + ")");
                sender.sendMessage(ChatColor.GREEN + "JVM Version: " + ChatColor.GRAY + props.getProperty("java.vm.name", "Unknown Name") + props.getProperty("java.vm.version", "Unknown") + " (" + props.getProperty("java.vm.vendor", "Unknown Vendor") + ")");
                try {
                    OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
                    sender.sendMessage(ChatColor.GREEN + "Available Processors: " + ChatColor.GRAY + osBean.getAvailableProcessors());
                    sender.sendMessage(ChatColor.GREEN + "Process Committed Virtual Memory: " + ChatColor.GRAY + (osBean.getCommittedVirtualMemorySize() / BYTES_IN_MB) + "MB");
                    // sender.sendMessage(ChatColor.GREEN + "Process Free Physical Memory: " + ChatColor.GRAY + (osBean.getFreePhysicalMemorySize() / BYTES_IN_MB) + "MB");
                    sender.sendMessage(ChatColor.GREEN + "Process CPU Load: " + ChatColor.GRAY + Math.round(100 * osBean.getProcessCpuLoad()) + "%");
                    sender.sendMessage(ChatColor.GREEN + "Process CPU Time: " + ChatColor.GRAY + (osBean.getProcessCpuTime() / NS_IN_MS) + "ms");
                    sender.sendMessage(ChatColor.GREEN + "Free Swap Space: " + ChatColor.GRAY + (osBean.getFreeSwapSpaceSize() / BYTES_IN_MB) + "MB");
                    // sender.sendMessage(ChatColor.GREEN + "Total Physical Memory: " + ChatColor.GRAY + (osBean.getTotalPhysicalMemorySize() / BYTES_IN_MB) + "MB");
                    // sender.sendMessage(ChatColor.GREEN + "System CPU Load: " + ChatColor.GRAY + Math.round(100 * osBean.getSystemCpuLoad()) + "%");
                    sender.sendMessage(ChatColor.GREEN + "System Load Average: " + ChatColor.GRAY + Math.round(100 * osBean.getSystemLoadAverage()) + "%");
                    ThreadMXBean threadBean = ManagementFactory.getPlatformMXBean(ThreadMXBean.class);
                    sender.sendMessage(ChatColor.GREEN + "Thread Count: " + ChatColor.GRAY + threadBean.getThreadCount());
                    sender.sendMessage(ChatColor.GREEN + "Daemon Thread Count: " + ChatColor.GRAY + threadBean.getDaemonThreadCount());
                    sender.sendMessage(ChatColor.GREEN + "Peak Thread Count: " + ChatColor.GRAY + threadBean.getPeakThreadCount());
                } catch (Exception e) {
                    sender.sendMessage(ChatColor.GRAY + "Some server statistics are unavailable for this platform: Unsupported MXBean(s)");
                }
            }
        }.runTaskAsynchronously(dragons);
    } else if (label.equalsIgnoreCase("tickperformance") || label.equalsIgnoreCase("tickperf")) {
        if (args.length == 0) {
            sender.sendMessage(ChatColor.RED + "/tickperformance start <recPeriodInSeconds>");
            sender.sendMessage(ChatColor.RED + "/tickperformance clear");
            sender.sendMessage(ChatColor.RED + "/tickperformance view [-verbose]" + ChatColor.GRAY + " (after data has been collected)");
        } else if (args[0].equalsIgnoreCase("start")) {
            if (args.length == 1) {
                sender.sendMessage(ChatColor.RED + "/tickperformance start <recPeriodInSeconds>");
                return true;
            }
            if (tickTimings.size() > 0) {
                sender.sendMessage(ChatColor.RED + "Please clear existing tick performance data before running this again! /tickperformance clear");
                return true;
            }
            Integer seconds = parseInt(sender, args[1]);
            if (seconds == null)
                return true;
            new BukkitRunnable() {

                long start = System.currentTimeMillis();

                @Override
                public void run() {
                    long now = System.currentTimeMillis();
                    tickTimings.add(now);
                    if ((now - start) / 1000 >= seconds) {
                        sender.sendMessage(ChatColor.GREEN + "Tick timings data collection has completed. Do /tickperformance view to view the data.");
                        cancel();
                    }
                }
            }.runTaskTimer(dragons, 1L, 1L);
            sender.sendMessage(ChatColor.GREEN + "Began tick timings data collection. Server may experience mild lag while this runs.");
        } else if (args[0].equalsIgnoreCase("clear")) {
            tickTimings.clear();
            sender.sendMessage(ChatColor.GREEN + "Cleared tick timings data.");
        } else if (args[0].equalsIgnoreCase("view")) {
            if (tickTimings.size() == 0) {
                sender.sendMessage(ChatColor.RED + "No tick performance data available! To gather data, do /tickperformance start <recPeriodInSeconds>");
                return true;
            }
            sender.sendMessage(ChatColor.DARK_GREEN + "Recorded tick data:");
            long prev = tickTimings.get(0);
            long longest = 0;
            long shortest = -1;
            long sum = 0;
            int nLong = 0;
            boolean verbose = args.length > 1 && args[1].equalsIgnoreCase("-verbose");
            for (int i = 1; i < tickTimings.size(); i++) {
                long ms = tickTimings.get(i) - prev;
                sum += ms;
                if (ms > longest)
                    longest = ms;
                if (shortest == -1 || ms < shortest)
                    shortest = ms;
                if (ms > 5 + 1000 / 20)
                    nLong++;
                if (verbose)
                    sender.sendMessage(ChatColor.GRAY + "#" + i + ": " + (ms <= 5 + 1000 / 20 ? ChatColor.GREEN : ChatColor.RED) + ms + "ms");
                prev = tickTimings.get(i);
            }
            double avg = (double) sum / (tickTimings.size() - 1);
            sender.sendMessage(ChatColor.GREEN + "Ticks Recorded: " + ChatColor.GRAY + (tickTimings.size() - 1));
            sender.sendMessage(ChatColor.GREEN + "Long Ticks: " + ChatColor.GRAY + nLong);
            sender.sendMessage(ChatColor.GREEN + "Shortest Tick: " + ChatColor.GRAY + shortest + "ms");
            sender.sendMessage(ChatColor.GREEN + "Longest Tick: " + ChatColor.GRAY + longest + "ms");
            sender.sendMessage(ChatColor.GREEN + "Average Tick: " + ChatColor.GRAY + MathUtil.round(avg) + "ms");
        }
    } else if (label.equalsIgnoreCase("getprocessid")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        sender.sendMessage(ChatColor.GREEN + "Process ID: " + ChatColor.GRAY + ProcessHandle.current().pid());
    } else if (label.equalsIgnoreCase("getstacktrace")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        UUID cid = LOGGER.newCID();
        Thread thread = Thread.currentThread();
        if (args.length > 0) {
            Integer id = parseInt(sender, args[0]);
            for (Thread test : Thread.getAllStackTraces().keySet()) {
                if (test.getId() == id) {
                    thread = test;
                    break;
                }
            }
        }
        LOGGER.info(cid, "Stack trace requested for thread " + thread.getId() + " " + thread.getName() + " (" + thread.getState() + ")");
        sender.sendMessage(ChatColor.GREEN + "Stack trace for thread " + thread.getId() + " " + thread.getName() + " (" + thread.getState() + ")");
        for (StackTraceElement elem : thread.getStackTrace()) {
            sender.sendMessage(ChatColor.GRAY + elem.toString());
            LOGGER.info(cid, elem.toString());
        }
        sender.sendMessage(ChatColor.YELLOW + "Stack trace logged with correlation ID " + StringUtil.toHdFont(cid.toString()));
    } else if (label.equalsIgnoreCase("getactivethreads")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        sender.sendMessage(ChatColor.DARK_GREEN + "" + Thread.getAllStackTraces().size() + " active threads:");
        // adapted from https://stackoverflow.com/a/46979843/8463670
        Thread.getAllStackTraces().keySet().stream().collect(Collectors.groupingBy(Thread::getThreadGroup)).forEach((group, threads) -> {
            sender.sendMessage(ChatColor.YELLOW + "" + ChatColor.BOLD + "GROUP " + group.getName() + " - " + group.activeCount() + " thr, " + group.activeGroupCount() + " sub" + ", par=" + (group.getParent() == null ? "none" : group.getParent().getName()) + ", maxpriority=" + group.getMaxPriority());
            TableGenerator tg = new TableGenerator(Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT, Alignment.LEFT);
            tg.addRow(COL_ID, COL_NAME, COL_STATE, COL_PRIORITY, COL_DAEMON);
            for (Thread thread : threads) {
                tg.addRowEx("/getstacktrace " + thread.getId(), "Click to view stack trace for thread #" + thread.getId() + " " + thread.getName() + " (" + thread.getState() + ")", "" + thread.getId(), StringUtil.truncateWithEllipsis(thread.getName(), 20), thread.getState().toString(), "" + thread.getPriority(), "" + thread.isDaemon());
            }
            tg.display(sender);
        });
    } else if (label.equalsIgnoreCase("requestgc")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        long before = System.currentTimeMillis();
        System.gc();
        sender.sendMessage(ChatColor.GREEN + "Ran garbage collector in " + (System.currentTimeMillis() - before) + "ms");
    } else if (label.equalsIgnoreCase("generatedump")) {
        CommandSender console = Bukkit.getConsoleSender();
        dragons.getLogger().info("");
        dragons.getLogger().info("");
        dragons.getLogger().info("");
        dragons.getLogger().info("==== BEGIN FULL SERVER DATA DUMP ====");
        dragons.getLogger().info("");
        dragons.getLogger().info("=== BEGIN USER DUMP ===");
        for (User user : UserLoader.allUsers()) {
            if (user.getPlayer() == null) {
                dragons.getLogger().info("USER " + user.getName() + " - " + user + " - OFFLINE");
            } else {
                dragons.getLogger().info("USER " + user.getName() + " - " + user + " - World " + user.getPlayer().getWorld() + ", Loc " + StringUtil.locToString(user.getPlayer().getLocation()) + ", Access Level " + user.getActivePermissionLevel());
            }
        }
        dragons.getLogger().info("=== END USER DUMP ===");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "debug dump gameobjects");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "debug dump entities");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "debug dump threads");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "debug dump workers");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "debug dump pendingtasks");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "lag");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "worldperformance");
        dragons.getLogger().info("");
        Bukkit.dispatchCommand(console, "serverperformance");
        dragons.getLogger().info("");
        dragons.getLogger().info("==== END FULL SERVER DATA DUMP ====");
        dragons.getLogger().info("");
        dragons.getLogger().info("");
        dragons.getLogger().info("");
    } else if (label.equalsIgnoreCase("clearnetworkmessagecache") || label.equalsIgnoreCase("clearnmc")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        MongoCollection<Document> messages = dragons.getMongoConfig().getDatabase().getCollection(MessageConstants.MESSAGE_COLLECTION);
        if (args.length == 0) {
            DeleteResult result = messages.deleteMany(new Document());
            sender.sendMessage(ChatColor.GREEN + "Successfully cleared the network-wide message cache (n=" + result.getDeletedCount() + ")");
        } else {
            Integer seconds = parseInt(sender, args[0]);
            if (seconds == null)
                return true;
            DeleteResult result = messages.deleteMany(new Document("timestamp", new Document("$lt", System.currentTimeMillis() - seconds * 1000)));
            sender.sendMessage(ChatColor.GREEN + "Successfully removed " + result.getDeletedCount() + " messages from the cache");
        }
    } else if (label.equalsIgnoreCase("printnetworkmessages")) {
        if (!requirePermission(sender, SystemProfileFlag.DEVELOPMENT))
            return true;
        MessageDispatcher dispatcher = dragons.getMessageDispatcher();
        dispatcher.setDebug(!dispatcher.isDebug());
        sender.sendMessage(ChatColor.GREEN + (dispatcher.isDebug() ? "Enabled" : "Disabled") + " network message logging.");
    } else if (label.equalsIgnoreCase("manifest")) {
        Map<String, List<UUID>> manifest = User.getConnectionMessageHandler().getManifest();
        sender.sendMessage(ChatColor.DARK_GREEN + "Displaying network-wide user manifest.");
        manifest.forEach((server, users) -> {
            sender.sendMessage(ChatColor.YELLOW + "Server " + server + " - " + users.size() + " online");
            sender.sendMessage(ChatColor.GRAY + "  " + StringUtil.parseList(users.stream().map(uuid -> userLoader.loadObject(uuid).getName()).collect(Collectors.toList())));
        });
    }
    return true;
}
Also used : Document(org.bson.Document) NPCLoader(mc.dragons.core.gameobject.npc.NPCLoader) Arrays(java.util.Arrays) Alignment(mc.dragons.core.util.TableGenerator.Alignment) MongoCollection(com.mongodb.client.MongoCollection) MessageConstants(mc.dragons.core.networking.MessageConstants) Item(org.bukkit.entity.Item) ThreadMXBean(com.sun.management.ThreadMXBean) User(mc.dragons.core.gameobject.user.User) Player(org.bukkit.entity.Player) ArrayList(java.util.ArrayList) MessageDispatcher(mc.dragons.core.networking.MessageDispatcher) DragonsCommandExecutor(mc.dragons.core.commands.DragonsCommandExecutor) PermissionLevel(mc.dragons.core.gameobject.user.permission.PermissionLevel) ItemFrame(org.bukkit.entity.ItemFrame) World(org.bukkit.World) Map(java.util.Map) Chunk(org.bukkit.Chunk) ManagementFactory(java.lang.management.ManagementFactory) Bukkit(org.bukkit.Bukkit) StringUtil(mc.dragons.core.util.StringUtil) CommandSender(org.bukkit.command.CommandSender) Properties(java.util.Properties) UserLoader(mc.dragons.core.gameobject.user.UserLoader) Entity(org.bukkit.entity.Entity) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) FloorLoader(mc.dragons.core.gameobject.floor.FloorLoader) UUID(java.util.UUID) EntityType(org.bukkit.entity.EntityType) SystemProfileFlag(mc.dragons.core.gameobject.user.permission.SystemProfile.SystemProfileFlags.SystemProfileFlag) Collectors(java.util.stream.Collectors) Dragons(mc.dragons.core.Dragons) List(java.util.List) OperatingSystemMXBean(com.sun.management.OperatingSystemMXBean) LagMeter(mc.dragons.core.tasks.LagMeter) TableGenerator(mc.dragons.core.util.TableGenerator) DeleteResult(com.mongodb.client.result.DeleteResult) ChatColor(org.bukkit.ChatColor) Command(org.bukkit.command.Command) MathUtil(mc.dragons.core.util.MathUtil) NPC(mc.dragons.core.gameobject.npc.NPC) PersistentDataType(org.bukkit.persistence.PersistentDataType) NPC(mc.dragons.core.gameobject.npc.NPC) Entity(org.bukkit.entity.Entity) User(mc.dragons.core.gameobject.user.User) ItemFrame(org.bukkit.entity.ItemFrame) World(org.bukkit.World) Properties(java.util.Properties) Document(org.bson.Document) Item(org.bukkit.entity.Item) MessageDispatcher(mc.dragons.core.networking.MessageDispatcher) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID) ThreadMXBean(com.sun.management.ThreadMXBean) Player(org.bukkit.entity.Player) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) TableGenerator(mc.dragons.core.util.TableGenerator) Chunk(org.bukkit.Chunk) CommandSender(org.bukkit.command.CommandSender) OperatingSystemMXBean(com.sun.management.OperatingSystemMXBean) DeleteResult(com.mongodb.client.result.DeleteResult)

Example 5 with Dragons

use of mc.dragons.core.Dragons in project DragonsOnline by UniverseCraft.

the class DragonsContentTools method onEnable.

public void onEnable() {
    enableDebugLogging();
    saveDefaultConfig();
    PUSH_FOLDER = getConfig().getString("push-folder", "C:\\DragonsPush\\");
    Dragons dragons = getDragonsInstance();
    COLoader coLoader = new COLoader(dragons);
    dragons.getLightweightLoaderRegistry().register(new AuditLogLoader(dragons.getMongoConfig()));
    dragons.getLightweightLoaderRegistry().register(new HologramLoader(dragons.getMongoConfig()));
    dragons.getLightweightLoaderRegistry().register(coLoader);
    dragons.getUserHookRegistry().registerHook(new ContentUserHook(coLoader));
    getCommand("region").setExecutor(new RegionCommand());
    getCommand("npc").setExecutor(new NPCCommand());
    getCommand("item").setExecutor(new ItemCommand());
    getCommand("floor").setExecutor(new FloorCommand());
    getCommand("clear").setExecutor(new ClearInventoryCommand());
    getCommand("testquest").setExecutor(new TestQuestCommand());
    getCommand("quest").setExecutor(new QuestCommand());
    getCommand("rename").setExecutor(new RenameCommand());
    getCommand("relore").setExecutor(new ReloreCommand());
    getCommand("restat").setExecutor(new RestatCommand());
    getCommand("resetprofile").setExecutor(new ResetProfileCommand());
    getCommand("placeholder").setExecutor(new PlaceholderCommand());
    getCommand("fixed").setExecutor(new FixedCommand());
    getCommand("objmeta").setExecutor(new ObjectMetadataCommand());
    getCommand("deletenpc").setExecutor(new DeleteNPCCommand());
    getCommand("hologram").setExecutor(new HologramCommand(this));
    getCommand("sign").setExecutor(new SignCommand());
    CommandExecutor gamemodeCommandExecutor = new GamemodeCommand();
    getCommand("gamemode").setExecutor(gamemodeCommandExecutor);
    getCommand("gma").setExecutor(gamemodeCommandExecutor);
    getCommand("gmc").setExecutor(gamemodeCommandExecutor);
    getCommand("gms").setExecutor(gamemodeCommandExecutor);
    getCommand("gotofloor").setExecutor(new GoToFloorCommand());
    getCommand("updatestats").setExecutor(new UpdateStatsCommand());
    CommandExecutor speedCommand = new SpeedCommand();
    getCommand("speed").setExecutor(speedCommand);
    getCommand("flyspeed").setExecutor(speedCommand);
    getCommand("walkspeed").setExecutor(speedCommand);
    CommandExecutor warpCommandsExecutor = new WarpCommands();
    getCommand("delwarp").setExecutor(warpCommandsExecutor);
    getCommand("setwarp").setExecutor(warpCommandsExecutor);
    getCommand("warp").setExecutor(warpCommandsExecutor);
    getCommand("warps").setExecutor(warpCommandsExecutor);
    CommandExecutor coCommandsExecutor = new CommunityObjectiveCommands(coLoader);
    getCommand("createobjective").setExecutor(coCommandsExecutor);
    getCommand("listobjectives").setExecutor(coCommandsExecutor);
    getCommand("unlockobjective").setExecutor(coCommandsExecutor);
    getCommand("lockobjective").setExecutor(coCommandsExecutor);
    getCommand("completeobjective").setExecutor(coCommandsExecutor);
    getCommand("failobjective").setExecutor(coCommandsExecutor);
    getCommand("deleteobjective").setExecutor(coCommandsExecutor);
    getCommand("reloadobjectives").setExecutor(coCommandsExecutor);
    Addon npcIdentifierAddon = new NPCIdentifierAddon();
    dragons.getAddonRegistry().register(npcIdentifierAddon);
    npcIdentifierAddon.apply();
    Bukkit.getPluginManager().registerEvents(new ContentToolsListeners(), this);
}
Also used : RestatCommand(mc.dragons.tools.content.command.statistics.RestatCommand) CommunityObjectiveCommands(mc.dragons.tools.content.command.CommunityObjectiveCommands) SignCommand(mc.dragons.tools.content.command.builder.SignCommand) GoToFloorCommand(mc.dragons.tools.content.command.builder.GoToFloorCommand) FloorCommand(mc.dragons.tools.content.command.gameobject.FloorCommand) GoToFloorCommand(mc.dragons.tools.content.command.builder.GoToFloorCommand) CommandExecutor(org.bukkit.command.CommandExecutor) PlaceholderCommand(mc.dragons.tools.content.command.PlaceholderCommand) DeleteNPCCommand(mc.dragons.tools.content.command.internal.DeleteNPCCommand) WarpCommands(mc.dragons.tools.content.command.builder.WarpCommands) ClearInventoryCommand(mc.dragons.tools.content.command.builder.ClearInventoryCommand) UpdateStatsCommand(mc.dragons.tools.content.command.statistics.UpdateStatsCommand) SpeedCommand(mc.dragons.tools.content.command.builder.SpeedCommand) ReloreCommand(mc.dragons.tools.content.command.statistics.ReloreCommand) Dragons(mc.dragons.core.Dragons) HologramCommand(mc.dragons.tools.content.command.builder.HologramCommand) DeleteNPCCommand(mc.dragons.tools.content.command.internal.DeleteNPCCommand) NPCCommand(mc.dragons.tools.content.command.gameobject.NPCCommand) ResetProfileCommand(mc.dragons.tools.content.command.statistics.ResetProfileCommand) ContentToolsListeners(mc.dragons.tools.content.event.ContentToolsListeners) TestQuestCommand(mc.dragons.tools.content.command.testing.TestQuestCommand) NPCIdentifierAddon(mc.dragons.tools.content.addon.NPCIdentifierAddon) Addon(mc.dragons.core.addon.Addon) ItemCommand(mc.dragons.tools.content.command.gameobject.ItemCommand) NPCIdentifierAddon(mc.dragons.tools.content.addon.NPCIdentifierAddon) RegionCommand(mc.dragons.tools.content.command.gameobject.RegionCommand) ObjectMetadataCommand(mc.dragons.tools.content.command.gameobject.ObjectMetadataCommand) TestQuestCommand(mc.dragons.tools.content.command.testing.TestQuestCommand) QuestCommand(mc.dragons.tools.content.command.gameobject.QuestCommand) RenameCommand(mc.dragons.tools.content.command.statistics.RenameCommand) FixedCommand(mc.dragons.tools.content.command.builder.FixedCommand) GamemodeCommand(mc.dragons.tools.content.command.builder.GamemodeCommand)

Aggregations

Dragons (mc.dragons.core.Dragons)5 ArrayList (java.util.ArrayList)2 List (java.util.List)2 UUID (java.util.UUID)2 Document (org.bson.Document)2 Bukkit (org.bukkit.Bukkit)2 ChatColor (org.bukkit.ChatColor)2 Player (org.bukkit.entity.Player)2 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)2 Charsets (com.google.common.base.Charsets)1 MongoCollection (com.mongodb.client.MongoCollection)1 DeleteResult (com.mongodb.client.result.DeleteResult)1 OperatingSystemMXBean (com.sun.management.OperatingSystemMXBean)1 ThreadMXBean (com.sun.management.ThreadMXBean)1 DataOutputStream (java.io.DataOutputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 ManagementFactory (java.lang.management.ManagementFactory)1 HttpURLConnection (java.net.HttpURLConnection)1