Search in sources :

Example 1 with BukkitCommandManager

use of co.aikar.commands.BukkitCommandManager in project map-ads by cerus-mc.

the class MapAdsPlugin method onEnable.

@Override
public void onEnable() {
    if (enabled) {
        this.getLogger().severe("DO NOT RELOAD YOUR SERVER.");
        this.getLogger().severe("This plugin will probably not work correctly now. Disabling.");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    enabled = true;
    // Misc init
    Premium.init();
    this.closeables.add(TransitionRegistry::cleanup);
    // Init config
    this.saveDefaultConfig();
    this.configModel = new ConfigModel(this.getConfig());
    // Init color cache
    ColorCache colorCache = null;
    if (this.configModel.useColorCache && Premium.isPremium()) {
        final File file = new File(this.getDataFolder(), "colors.cache");
        if (!file.exists()) {
            this.getLogger().info("Color cache does not exist. Generating new cache... This will take a while");
            colorCache = ColorCache.generate();
            try (final OutputStream outputStream = new FileOutputStream(file)) {
                colorCache.write(outputStream);
                outputStream.flush();
            } catch (final IOException e) {
                e.printStackTrace();
                this.getLogger().severe("Failed to save color cache");
            }
        } else {
            try (final InputStream inputStream = new FileInputStream(file)) {
                colorCache = ColorCache.fromInputStream(inputStream);
            } catch (final IOException e) {
                e.printStackTrace();
                this.getLogger().severe("Failed to load color cache");
            }
        }
    }
    // Init L10n
    this.saveResource("lang.yml", false);
    final File l10nFile = new File(this.getDataFolder(), "lang.yml");
    final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(l10nFile);
    this.update(configuration, l10nFile);
    for (final String key : configuration.getKeys(false)) {
        final Object o = configuration.get(key);
        if (o instanceof List) {
            L10n.put(key.replace(",", "."), ((List<String>) o).stream().map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList()));
        } else if (o instanceof String) {
            L10n.put(key.replace(",", "."), ChatColor.translateAlternateColorCodes('&', (String) o));
        } else {
            this.getLogger().warning("Invalid lang mapping: " + key + "->" + o.getClass().getName());
        }
    }
    // Init help book
    this.saveResource("helpbook.yml", false);
    final HelpBookConfiguration helpBookConfiguration = new HelpBookConfiguration();
    helpBookConfiguration.load();
    HelpBook.init(helpBookConfiguration);
    // Init Vault
    final RegisteredServiceProvider<Economy> registration = this.getServer().getServicesManager().getRegistration(Economy.class);
    if (registration == null) {
        this.getLogger().severe("Please install an economy plugin!");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    final Economy economy = registration.getProvider();
    // Init image storage
    final ImageStorage imageStorage = this.loadImageStorage();
    if (imageStorage == null) {
        this.getLogger().severe("Invalid image storage configuration");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    this.closeables.add(imageStorage);
    // Init advert storage
    final AdvertStorage advertStorage = this.loadAdvertStorage(imageStorage);
    if (advertStorage == null) {
        this.getLogger().severe("Invalid advert storage configuration");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    this.closeables.add(advertStorage);
    // Init Discord bot
    boolean discordEnabled = false;
    if (this.getServer().getPluginManager().isPluginEnabled("map-ads-discord-bot")) {
        final DiscordHook discordHook = new DiscordHook(this, advertStorage, imageStorage, economy);
        final AutoCloseable closeable = discordHook.load();
        if (closeable != null) {
            this.closeables.add(closeable);
            this.getLogger().info("Discovered Discord extension");
            discordEnabled = true;
        }
    }
    final boolean finalDiscordEnabled = discordEnabled;
    // Init misc services
    final AdScreenStorage adScreenStorage = this.loadAdScreenStorage();
    this.closeables.add(adScreenStorage);
    final DefaultImageController defaultImageController = new DefaultImageController(this, imageStorage);
    final AdvertController advertController = new AdvertController(this, advertStorage, imageStorage, defaultImageController);
    final ImageRetriever imageRetriever = new ImageRetriever();
    final ImageConverter imageConverter = new ImageConverter(colorCache);
    // Register commands & dependencies, init completions
    final BukkitCommandManager commandManager = new BukkitCommandManager(this);
    final CommandCompletions<BukkitCommandCompletionContext> completions = commandManager.getCommandCompletions();
    completions.registerCompletion("mapads_names", context -> adScreenStorage.getScreens().stream().map(AdScreen::getId).collect(Collectors.toList()));
    completions.registerCompletion("mapads_transitions", context -> TransitionRegistry.names());
    completions.registerCompletion("mapads_adverts", context -> advertStorage.getPendingAdvertisements().stream().map(advertisement -> advertisement.getAdvertId().toString()).collect(Collectors.toSet()));
    completions.registerCompletion("maps_ids", context -> MapScreenRegistry.getScreenIds().stream().map(String::valueOf).collect(Collectors.toList()));
    completions.registerCompletion("mapads_commondim", context -> {
        final List<String> list = new ArrayList<>();
        for (int x = 1; x <= 20; x++) {
            for (int y = 1; y <= 20; y++) {
                list.add(x + "x" + y);
            }
        }
        return list;
    });
    commandManager.getCommandContexts().registerContext(UUID.class, ctx -> {
        final String s = ctx.popFirstArg();
        try {
            return UUID.fromString(s);
        } catch (final IllegalArgumentException ignored) {
            throw new InvalidCommandArgument("Not a UUID");
        }
    });
    commandManager.registerDependency(ImageStorage.class, imageStorage);
    commandManager.registerDependency(AdvertStorage.class, advertStorage);
    commandManager.registerDependency(AdScreenStorage.class, adScreenStorage);
    commandManager.registerDependency(ImageRetriever.class, imageRetriever);
    commandManager.registerDependency(ImageConverter.class, imageConverter);
    commandManager.registerDependency(DefaultImageController.class, defaultImageController);
    commandManager.registerDependency(AdvertController.class, advertController);
    commandManager.registerDependency(ConfigModel.class, this.configModel);
    commandManager.registerDependency(Economy.class, economy);
    commandManager.registerCommand(new MapAdsCommand());
    commandManager.registerCommand(new PremiumCommand());
    commandManager.registerCommand(new ScreenCommand());
    commandManager.registerCommand(new DefaultImageCommand());
    commandManager.registerCommand(new ReviewCommand());
    commandManager.registerCommand(new HelpCommand());
    commandManager.registerCommand(new PreviewCommand());
    commandManager.registerCommand(new AdvertCommand());
    // Register listeners
    final PluginManager pluginManager = this.getServer().getPluginManager();
    pluginManager.registerEvents(new PlayerJoinListener(this, adScreenStorage, advertStorage), this);
    // Start tasks
    final BukkitScheduler scheduler = this.getServer().getScheduler();
    scheduler.runTaskTimerAsynchronously(this, new FrameSendTask(adScreenStorage), 4 * 20, 2 * 20);
    scheduler.runTaskTimerAsynchronously(this, () -> adScreenStorage.getScreens().forEach(advertController::update), 4 * 20, 60 * 20);
    scheduler.runTaskLater(this, () -> this.screensLoaded = true, 4 * 20);
    // Register services
    final ServicesManager servicesManager = this.getServer().getServicesManager();
    servicesManager.register(AdvertStorage.class, advertStorage, this, ServicePriority.Normal);
    servicesManager.register(AdScreenStorage.class, adScreenStorage, this, ServicePriority.Normal);
    servicesManager.register(ImageStorage.class, imageStorage, this, ServicePriority.Normal);
    servicesManager.register(DefaultImageController.class, defaultImageController, this, ServicePriority.Normal);
    servicesManager.register(ImageConverter.class, imageConverter, this, ServicePriority.Normal);
    servicesManager.register(ImageRetriever.class, imageRetriever, this, ServicePriority.Normal);
    // Init metrics
    final Metrics metrics = new Metrics(this, 13063);
    metrics.addCustomChart(new SimplePie("premium", () -> Premium.isPremium() ? "Yes" : "No"));
    metrics.addCustomChart(new SimplePie("discord_integration_enabled", () -> finalDiscordEnabled ? "Yes" : "No"));
    metrics.addCustomChart(new AdvancedPie("transition_usage", () -> {
        final Map<String, Integer> map = new HashMap<>();
        for (final String name : TransitionRegistry.names()) {
            map.put(name, 0);
        }
        for (final AdScreen screen : adScreenStorage.getScreens()) {
            if (map.containsKey(screen.getTransition())) {
                map.put(screen.getTransition(), map.get(screen.getTransition()) + 1);
            }
        }
        return map;
    }));
}
Also used : ScreenCommand(dev.cerus.mapads.command.ScreenCommand) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) AdvertController(dev.cerus.mapads.advert.AdvertController) ArrayList(java.util.ArrayList) SimplePie(org.bstats.charts.SimplePie) FrameSendTask(dev.cerus.mapads.task.FrameSendTask) AdvertStorage(dev.cerus.mapads.advert.storage.AdvertStorage) PluginManager(org.bukkit.plugin.PluginManager) ReviewCommand(dev.cerus.mapads.command.ReviewCommand) Metrics(org.bstats.bukkit.Metrics) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) List(java.util.List) ArrayList(java.util.ArrayList) DefaultImageCommand(dev.cerus.mapads.command.DefaultImageCommand) HelpCommand(dev.cerus.mapads.command.HelpCommand) PlayerJoinListener(dev.cerus.mapads.listener.PlayerJoinListener) FileInputStream(java.io.FileInputStream) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext) FileOutputStream(java.io.FileOutputStream) BukkitScheduler(org.bukkit.scheduler.BukkitScheduler) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ImageConverter(dev.cerus.mapads.image.ImageConverter) YamlConfiguration(org.bukkit.configuration.file.YamlConfiguration) ImageRetriever(dev.cerus.mapads.image.ImageRetriever) PreviewCommand(dev.cerus.mapads.command.PreviewCommand) Economy(net.milkbowl.vault.economy.Economy) AdvancedPie(org.bstats.charts.AdvancedPie) PremiumCommand(dev.cerus.mapads.command.PremiumCommand) AdvertCommand(dev.cerus.mapads.command.AdvertCommand) ColorCache(dev.cerus.mapads.image.ColorCache) TransitionRegistry(dev.cerus.mapads.image.transition.TransitionRegistry) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) ImageStorage(dev.cerus.mapads.image.storage.ImageStorage) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdScreen(dev.cerus.mapads.screen.AdScreen) HelpBookConfiguration(dev.cerus.mapads.helpbook.HelpBookConfiguration) IOException(java.io.IOException) AdScreenStorage(dev.cerus.mapads.screen.storage.AdScreenStorage) ServicesManager(org.bukkit.plugin.ServicesManager) DefaultImageController(dev.cerus.mapads.image.DefaultImageController) MapAdsCommand(dev.cerus.mapads.command.MapAdsCommand) DiscordHook(dev.cerus.mapads.hook.DiscordHook)

Example 2 with BukkitCommandManager

use of co.aikar.commands.BukkitCommandManager in project VoxelGamesLibv2 by VoxelGamesLib.

the class VoxelGamesLib method onEnable.

@Override
public void onEnable() {
    try {
        // logging first, only changes prefixes anyways
        loggingHandler = new LoggingHandler();
        loggingHandler.setErrorHandler(errorHandler);
        loggingHandler.enable();
        // enable by enabling external stuff. they don't require any VGL stuff
        // timings
        timingManager = TimingManager.of(this);
        // commands
        commandManager = new BukkitCommandManager(this);
        commandManager.setDefaultExceptionHandler((scope, registeredCommand, sender, args, t) -> {
            errorHandler.handle(sender, args, t);
            return false;
        });
        // living on the edge!
        commandManager.enableUnstableAPI("help");
        // task chain
        taskChainFactory = BukkitTaskChainFactory.create(this);
        taskChainFactory.setDefaultErrorHandler((e, t) -> {
            log.severe("Task " + t.hashCode() + " generated an exception:");
            e.printStackTrace();
        });
        // chat menu api
        ChatMenuAPI.init(this);
        // menu builder (excuse the hack, but we want to shade you)
        MenuBuilderPlugin menuBuilderPluginFake = new ObjenesisStd().getInstantiatorOf(MenuBuilderPlugin.class).newInstance();
        menuBuilderPluginFake.inventoryListener = new InventoryListener(menuBuilderPluginFake);
        MenuBuilderPlugin.instance = menuBuilderPluginFake;
        Bukkit.getPluginManager().registerEvents(menuBuilderPluginFake.inventoryListener, this);
        // guice
        VoxelGamesLibModule module = new VoxelGamesLibModule(this, loggingHandler, timingManager, commandManager, getVersion(), getDataFolder(), ModuleHandler.getOfferedModules(), errorHandler);
        injector = module.createInjector();
        injector.injectMembers(this);
        // startup handler
        startupHandler.registerService("onEnable");
        Bukkit.getPluginManager().registerEvents(injector.getInstance(StartupListener.class), this);
        // then enable all VGL stuff
        try (final Timing timing = new Timing("EnableAllHandlers")) {
            eventHandler.enable();
            configHandler.enable();
            persistenceHandler.enable();
            langHandler.enable();
            tickHandler.enable();
            chatHandler.enable();
            userHandler.enable();
            roleHandler.enable();
            mapHandler.enable();
            worldHandler.enable();
            teamHandler.enable();
            eloHandler.enable();
            matchmakingHandler.enable();
            signHandler.enable();
            metricHandler.enable();
            pointHandler.enable();
            kitHandler.enable();
            commandHandler.enable();
            textureHandler.enable();
            statsHandler.enable();
            gameHandler.enable();
        }
        registerListeners();
    } catch (Exception ex) {
        errorHandler.handle(ex, Severity.ERROR, true);
        startupHandler.interrupt();
        return;
    }
    // register commands
    registerCommandContexts();
    registerCommandReplacements();
    registerCommands();
    registerCommandCompletions();
    moduleHandler.enable();
    gameHandler.startDefaultGame();
    getServer().getPluginManager().callEvent(new VoxelGamesLibEnableEvent());
    testStuff.test();
    startupHandler.unregisterService("onEnable");
    enabledCleanly = true;
}
Also used : MenuBuilderPlugin(org.inventivetalent.menubuilder.MenuBuilderPlugin) LoggingHandler(com.voxelgameslib.voxelgameslib.internal.log.LoggingHandler) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) ObjenesisStd(org.objenesis.ObjenesisStd) InventoryListener(org.inventivetalent.menubuilder.inventory.InventoryListener) VoxelGamesLibEnableEvent(com.voxelgameslib.voxelgameslib.api.event.events.VoxelGamesLibEnableEvent) Timing(com.voxelgameslib.voxelgameslib.internal.timings.Timing) StartupListener(com.voxelgameslib.voxelgameslib.internal.startup.StartupListener)

Example 3 with BukkitCommandManager

use of co.aikar.commands.BukkitCommandManager in project ArmorSwap by taggernation.

the class ArmorSwap method onEnable.

@Override
public void onEnable() {
    try {
        configData = new ConfigData(this);
        configData.updateConfig(this.getDescription().getVersion(), ConfigDataType.VERSION.getName());
    } catch (IOException | InvalidConfigurationException e) {
        e.printStackTrace();
    }
    new UpdateChecker(this, 97332).getVersion(version -> {
        if (this.getDescription().getVersion().equals(version)) {
            getLogger().info("There is not a new update available.");
        } else {
            getLogger().info("There is a new update available." + "\n" + ChatColor.RED + "https://www.spigotmc.org/resources/armorswap-swap-items-by-right-clicking.97332/");
        }
    });
    // bStats metrics
    // https://bstats.org/what-is-my-plugin-id
    Metrics metrics = new Metrics(this, 14140);
    setPlugin(this);
    // Events
    getServer().getPluginManager().registerEvents(new OnJoin(), this);
    try {
        getServer().getPluginManager().registerEvents(new ClickEvent(configData, this), this);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Checks if server is running on Paper or not
    boolean isOnPaper = false;
    try {
        Class.forName("com.destroystokyo.paper");
        isOnPaper = true;
    } catch (ClassNotFoundException ignored) {
    }
    // Initializing Command manager
    if (isOnPaper) {
        PaperCommandManager pcm = new PaperCommandManager(this);
        pcm.registerCommand(new CommandManager(configData, this));
    } else {
        BukkitCommandManager bcm = new BukkitCommandManager(this);
        bcm.registerCommand(new CommandManager(configData, this));
    }
    // Config
    getLogger().info(ChatColor.AQUA + "ArmorSwap " + ChatColor.UNDERLINE + "Successfully loaded.");
}
Also used : BukkitCommandManager(co.aikar.commands.BukkitCommandManager) PaperCommandManager(co.aikar.commands.PaperCommandManager) ClickEvent(com.toonystank.armorswap.Events.ClickEvent) OnJoin(com.toonystank.armorswap.Events.OnJoin) IOException(java.io.IOException) InvalidConfigurationException(org.bukkit.configuration.InvalidConfigurationException) Metrics(com.toonystank.armorswap.utils.Metrics) CommandManager(com.toonystank.armorswap.Commands.CommandManager) PaperCommandManager(co.aikar.commands.PaperCommandManager) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) ConfigData(com.toonystank.armorswap.utils.ConfigData) UpdateChecker(com.toonystank.armorswap.utils.UpdateChecker)

Example 4 with BukkitCommandManager

use of co.aikar.commands.BukkitCommandManager in project buildinggame by stefvanschie.

the class Main method loadPlugin.

/**
 * Loads the entire plugin
 *
 * @since 2.1.0
 */
public void loadPlugin(boolean reload) {
    long start = System.currentTimeMillis();
    // this has to be done quite early
    if (!reload) {
        Gui.registerProperty("particle-type", Particle::valueOf);
        Gui.registerProperty("biome", Biome::valueOf);
        Gui.registerProperty("dye-color", DyeColor::valueOf);
        Gui.registerProperty("material", Material::valueOf);
    }
    getLogger().info("Loading files");
    SettingsManager.getInstance().setup(this, false);
    getLogger().info("Loading arenas");
    ArenaManager.getInstance().setup();
    ArenaModeManager.getInstance().setup();
    BuildTimerManager.getInstance().setup();
    LobbyManager.getInstance().setup();
    LobbyTimerManager.getInstance().setup();
    MinPlayersManager.getInstance().setup();
    MatchesManager.getInstance().setup();
    VoteTimerManager.getInstance().setup();
    WinTimerManager.getInstance().setup();
    getLogger().info("Loading plots");
    PlotManager.getInstance().setup();
    // has to be down here for some config stuff
    MaxPlayersManager.getInstance().setup();
    LocationManager.getInstance().setup();
    BoundaryManager.getInstance().setup();
    FloorManager.getInstance().setup();
    getLogger().info("Loading main spawn");
    MainSpawnManager.getInstance().setup();
    PluginManager pm = Bukkit.getPluginManager();
    getLogger().info("Loading soft dependencies");
    if (pm.isPluginEnabled("Vault"))
        SDVault.getInstance().setup();
    if (pm.isPluginEnabled("PlaceholderAPI")) {
        try {
            String version = pm.getPlugin("PlaceholderAPI").getDescription().getVersion();
            var number = Integer.parseInt(version.replace(".", ""));
            // This ensures the versions don't get mixed up (e.g. 2.7.5 being bigger than 2.9).
            for (var i = version.split("\\.").length; i < 3; i++) number *= 10;
            // 290 is the first version with offline player support
            if (number >= 290) {
                if (!new PlaceholderAPIPlaceholders().register())
                    getLogger().warning("Unable to register placeholders for PlaceholderAPI");
            } else
                getLogger().warning("PlaceholderAPI is outdated, update to a later version to keep BuildingGame compatible with PlaceholderAPI.");
        } catch (NumberFormatException e) {
            getLogger().warning("Unable to get PlaceholderAPI version, contact the plugin author about this.");
            e.printStackTrace();
        }
    }
    if (pm.isPluginEnabled("MVdWPlaceholderAPI")) {
        PlaceholderSupplier.getPlaceholderReplacements().forEach((placeholder, biFunction) -> PlaceholderAPI.registerPlaceholder(this, placeholder, event -> biFunction.apply(event.getOfflinePlayer(), event.getPlaceholder())));
    }
    getLogger().info("Loading commands");
    if (!reload) {
        var manager = new BukkitCommandManager(this);
        // noinspection deprecation
        manager.enableUnstableAPI("help");
        // register contexts
        manager.getCommandContexts().registerContext(Arena.class, context -> {
            var arena = ArenaManager.getInstance().getArena(context.popFirstArg());
            if (arena == null)
                throw new InvalidCommandArgument("This arena doesn't exist");
            return arena;
        });
        manager.getCommandContexts().registerContext(ArenaMode.class, context -> {
            var mode = ArenaMode.valueOf(context.popFirstArg().toUpperCase(Locale.getDefault()));
            if (mode == null)
                throw new InvalidCommandArgument("This game mode doesn't exist");
            return mode;
        });
        manager.getCommandContexts().registerContext(StatType.class, context -> {
            var type = StatType.valueOf(context.popFirstArg().toUpperCase(Locale.getDefault()));
            if (type == null)
                throw new InvalidCommandArgument("This statistic type doesn't exist");
            return type;
        });
        // register completions
        manager.getCommandCompletions().registerCompletion("arenas", context -> ArenaManager.getInstance().getArenas().stream().map(Arena::getName).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("arenamodes", context -> Stream.of(ArenaMode.values()).map(mode -> mode.toString().toUpperCase(Locale.getDefault())).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("stattypes", context -> Stream.of(StatType.values()).map(Enum::toString).collect(Collectors.toList()));
        manager.getCommandCompletions().registerCompletion("holograms", context -> TopStatHologram.getHolograms().stream().map(TopStatHologram::getName).collect(Collectors.toList()));
        // register conditions
        manager.getCommandConditions().addCondition(String.class, "arenanotexist", (context, executionContext, string) -> {
            if (ArenaManager.getInstance().getArena(string) != null || string.equals("main-spawn"))
                throw new ConditionFailedException("Arena already exists");
        });
        // hd stands for Holographic Displays, but it's shorten to hd since the full name is a bit long
        manager.getCommandConditions().addCondition("hdenabled", context -> pm.isPluginEnabled("HolographicDisplays"));
        manager.registerCommand(new CommandManager());
    }
    getLogger().info("Loading stats");
    StatManager.getInstance().setup();
    // loading achievements should happen after the statistics have been loaded
    Achievement.loadAchievements();
    getLogger().info("Loading listeners");
    if (!reload) {
        pm.registerEvents(new BlockDispenseItem(), this);
        pm.registerEvents(new BlockEdit(), this);
        pm.registerEvents(new JoinSignCreate(), this);
        pm.registerEvents(new LeaveSignCreate(), this);
        pm.registerEvents(new StatSignCreate(), this);
        pm.registerEvents(new UpdateLoadedSigns(), this);
        pm.registerEvents(new SpectateSignCreate(), this);
        pm.registerEvents(new SignBreak(), this);
        pm.registerEvents(new LiquidFlow(), this);
        pm.registerEvents(new PistonBlockMove(), this);
        // starts the connection to bungeecord
        if (SettingsManager.getInstance().getConfig().getBoolean("bungeecord.enable"))
            BungeeCordHandler.getInstance();
        // per world inventory compatibility fix
        if (pm.isPluginEnabled("PerWorldInventory")) {
            try {
                String version = pm.getPlugin("PerWorldInventory").getDescription().getVersion();
                var number = Integer.parseInt(version.replace(".", ""));
                // This ensures the versions don't get mixed up (e.g. 1.7.5 being bigger than 1.11).
                for (var i = version.split("\\.").length; i < 3; i++) number *= 10;
                // 200 is the first version with the new package name
                if (number >= 200)
                    pm.registerEvents(new PerWorldInventoryCancel(), this);
                else
                    getLogger().warning("PerWorldInventory is outdated, update to a later version to keep BuildingGame compatible with PerWorldInventory.");
            } catch (NumberFormatException e) {
                getLogger().warning("Unable to get PerWorldInventory version, contact the plugin author about this.");
                e.printStackTrace();
            }
        }
        if (pm.isPluginEnabled("WorldEdit"))
            WorldEdit.getInstance().getEventBus().register(new WorldEditBoundaryAssertion());
        if (pm.isPluginEnabled("Citizens")) {
            pm.registerEvents(new NPCCreate(), this);
            TraitInfo traitInfo = TraitInfo.create(NPCFloorChangeTrait.class).withName("buildinggame:floorchange");
            CitizensAPI.getTraitFactory().registerTrait(traitInfo);
        }
        pm.registerEvents(new ClickJoinSign(), this);
        pm.registerEvents(new ClickLeaveSign(), this);
        pm.registerEvents(new ClickSpectateSign(), this);
        pm.registerEvents(new Drop(), this);
        pm.registerEvents(new Interact(), this);
        pm.registerEvents(new Leave(), this);
        pm.registerEvents(new Move(), this);
        pm.registerEvents(new PlaceBucket(), this);
        pm.registerEvents(new PlaceIgnoreSpectators(), this);
        if (SettingsManager.getInstance().getConfig().getBoolean("chat.adjust"))
            pm.registerEvents(new Chat(), this);
        pm.registerEvents(new CommandBlocker(), this);
        pm.registerEvents(new EntityDamage(), this);
        pm.registerEvents(new TakeDamage(), this);
        pm.registerEvents(new LoseFood(), this);
        // entity events
        pm.registerEvents(new ChickenSpawnByEgg(), this);
        pm.registerEvents(new EntityExplode(), this);
        pm.registerEvents(new EntityOptionsMenu(), this);
        pm.registerEvents(new EntitySpawn(), this);
        // scoreboards
        pm.registerEvents(new MainScoreboardJoinShow(), this);
        pm.registerEvents(new MainScoreboardWorldChange(), this);
        // stats
        // saved
        pm.registerEvents(new BreakStat(), this);
        pm.registerEvents(new FirstStat(), this);
        pm.registerEvents(new PlaceStat(), this);
        pm.registerEvents(new PlaysStat(), this);
        pm.registerEvents(new SecondStat(), this);
        pm.registerEvents(new ThirdStat(), this);
        // unsaved
        pm.registerEvents(new UnsavedStatsPlace(), this);
        // structure
        pm.registerEvents(new TreeGrow(), this);
        if (StatManager.getInstance().getMySQLDatabase() != null) {
            pm.registerEvents(new JoinPlayerStats(), this);
            pm.registerEvents(new QuitPlayerStats(), this);
        }
    }
    getLogger().info("Loading signs");
    SignManager.getInstance().setup();
    getLogger().info("Loading timer");
    new ParticleRender().runTaskTimer(this, 0L, 10L);
    new ScoreboardUpdater().runTaskTimer(this, 0L, SettingsManager.getInstance().getConfig().getLong("scoreboard-update-delay"));
    new StatSaveTimer().runTaskTimerAsynchronously(this, 0L, SettingsManager.getInstance().getConfig().getLong("stats.save-delay"));
    new EntityTimer().runTaskTimer(this, 0L, 20L);
    new StatSignUpdater().runTaskTimerAsynchronously(this, 0L, 1L);
    long end = System.currentTimeMillis();
    long duration = end - start;
    String time;
    if (duration < 1000) {
        time = duration + " milliseconds";
    } else if (duration < 60000) {
        time = duration / 1000.0 + " seconds";
    } else {
        time = (duration / 60000) + ":" + (duration % 60000) / 1000.0 + " minutes";
    }
    getLogger().info("BuildingGame has been enabled in " + time + '!');
}
Also used : CommandManager(com.gmail.stefvanschiedev.buildinggame.managers.commands.CommandManager) LocationManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.LocationManager) EntityExplode(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityExplode) Biome(org.bukkit.block.Biome) UnsavedStatsPlace(com.gmail.stefvanschiedev.buildinggame.events.stats.unsaved.UnsavedStatsPlace) CitizensAPI(net.citizensnpcs.api.CitizensAPI) PerWorldInventoryCancel(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.PerWorldInventoryCancel) EntitySpawn(com.gmail.stefvanschiedev.buildinggame.events.entity.EntitySpawn) LiquidFlow(com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow) PlotManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.PlotManager) TopStatHologram(com.gmail.stefvanschiedev.buildinggame.utils.TopStatHologram) NPCFloorChangeTrait(com.gmail.stefvanschiedev.buildinggame.utils.NPCFloorChangeTrait) ClickSpectateSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickSpectateSign) Gui(com.github.stefvanschie.inventoryframework.gui.type.util.Gui) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) JoinPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.JoinPlayerStats) EntityOptionsMenu(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityOptionsMenu) ArenaMode(com.gmail.stefvanschiedev.buildinggame.utils.arena.ArenaMode) com.gmail.stefvanschiedev.buildinggame.events.block.signs(com.gmail.stefvanschiedev.buildinggame.events.block.signs) FirstStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.FirstStat) SettingsManager(com.gmail.stefvanschiedev.buildinggame.managers.files.SettingsManager) Collectors(java.util.stream.Collectors) MainScoreboardJoinShow(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardJoinShow) ThirdStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.ThirdStat) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) Contract(org.jetbrains.annotations.Contract) Stream(java.util.stream.Stream) com.gmail.stefvanschiedev.buildinggame.managers.arenas(com.gmail.stefvanschiedev.buildinggame.managers.arenas) TreeGrow(com.gmail.stefvanschiedev.buildinggame.events.structure.TreeGrow) FloorManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.FloorManager) Achievement(com.gmail.stefvanschiedev.buildinggame.utils.Achievement) NotNull(org.jetbrains.annotations.NotNull) StatType(com.gmail.stefvanschiedev.buildinggame.utils.stats.StatType) QuitPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.QuitPlayerStats) PlaysStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaysStat) java.util(java.util) BreakStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.BreakStat) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) com.gmail.stefvanschiedev.buildinggame.events.player(com.gmail.stefvanschiedev.buildinggame.events.player) PlaceholderAPIPlaceholders(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.PlaceholderAPIPlaceholders) MetricsLite(org.bstats.bukkit.MetricsLite) BlockDispenseItem(com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem) ChickenSpawnByEgg(com.gmail.stefvanschiedev.buildinggame.events.entity.ChickenSpawnByEgg) WorldEditBoundaryAssertion(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.WorldEditBoundaryAssertion) BungeeCordHandler(com.gmail.stefvanschiedev.buildinggame.utils.bungeecord.BungeeCordHandler) Interact(com.gmail.stefvanschiedev.buildinggame.events.player.voting.Interact) NPCCreate(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.NPCCreate) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) ConditionFailedException(co.aikar.commands.ConditionFailedException) WorldEdit(com.sk89q.worldedit.WorldEdit) SDVault(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.SDVault) BoundaryManager(com.gmail.stefvanschiedev.buildinggame.managers.plots.BoundaryManager) BlockEdit(com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit) PlaceholderAPI(be.maximvdw.placeholderapi.PlaceholderAPI) Particle(org.bukkit.Particle) TraitInfo(net.citizensnpcs.api.trait.TraitInfo) ClickJoinSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign) MainScoreboardWorldChange(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardWorldChange) PlaceholderSupplier(com.gmail.stefvanschiedev.buildinggame.utils.PlaceholderSupplier) StatManager(com.gmail.stefvanschiedev.buildinggame.managers.stats.StatManager) com.gmail.stefvanschiedev.buildinggame.timers(com.gmail.stefvanschiedev.buildinggame.timers) PlaceStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaceStat) Arena(com.gmail.stefvanschiedev.buildinggame.utils.arena.Arena) DyeColor(org.bukkit.DyeColor) ClickLeaveSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickLeaveSign) SecondStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.SecondStat) MainSpawnManager(com.gmail.stefvanschiedev.buildinggame.managers.mainspawn.MainSpawnManager) PluginManager(org.bukkit.plugin.PluginManager) BlockDispenseItem(com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem) BreakStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.BreakStat) TreeGrow(com.gmail.stefvanschiedev.buildinggame.events.structure.TreeGrow) PlaysStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaysStat) JoinPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.JoinPlayerStats) Interact(com.gmail.stefvanschiedev.buildinggame.events.player.voting.Interact) Particle(org.bukkit.Particle) PluginManager(org.bukkit.plugin.PluginManager) CommandManager(com.gmail.stefvanschiedev.buildinggame.managers.commands.CommandManager) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) TraitInfo(net.citizensnpcs.api.trait.TraitInfo) EntitySpawn(com.gmail.stefvanschiedev.buildinggame.events.entity.EntitySpawn) SecondStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.SecondStat) PlaceStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.PlaceStat) TopStatHologram(com.gmail.stefvanschiedev.buildinggame.utils.TopStatHologram) ChickenSpawnByEgg(com.gmail.stefvanschiedev.buildinggame.events.entity.ChickenSpawnByEgg) DyeColor(org.bukkit.DyeColor) Arena(com.gmail.stefvanschiedev.buildinggame.utils.arena.Arena) ClickSpectateSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickSpectateSign) QuitPlayerStats(com.gmail.stefvanschiedev.buildinggame.events.stats.database.QuitPlayerStats) ThirdStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.ThirdStat) WorldEditBoundaryAssertion(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.WorldEditBoundaryAssertion) MainScoreboardWorldChange(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardWorldChange) PerWorldInventoryCancel(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.PerWorldInventoryCancel) ClickLeaveSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickLeaveSign) PlaceholderAPIPlaceholders(com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.PlaceholderAPIPlaceholders) Biome(org.bukkit.block.Biome) ConditionFailedException(co.aikar.commands.ConditionFailedException) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) ClickJoinSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign) EntityExplode(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityExplode) FirstStat(com.gmail.stefvanschiedev.buildinggame.events.stats.saved.FirstStat) NPCFloorChangeTrait(com.gmail.stefvanschiedev.buildinggame.utils.NPCFloorChangeTrait) NPCCreate(com.gmail.stefvanschiedev.buildinggame.events.softdependencies.NPCCreate) EntityOptionsMenu(com.gmail.stefvanschiedev.buildinggame.events.entity.EntityOptionsMenu) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) LiquidFlow(com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow) Material(org.bukkit.Material) PistonBlockMove(com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove) UnsavedStatsPlace(com.gmail.stefvanschiedev.buildinggame.events.stats.unsaved.UnsavedStatsPlace) BlockEdit(com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit) MainScoreboardJoinShow(com.gmail.stefvanschiedev.buildinggame.events.scoreboards.MainScoreboardJoinShow)

Example 5 with BukkitCommandManager

use of co.aikar.commands.BukkitCommandManager in project buildinggame by stefvanschie.

the class Main method onEnable.

/**
 * Called whenever this plugin is being enabled
 *
 * @since 2.1.0
 */
@Override
public void onEnable() {
    instance = this;
    SettingsManager.getInstance().setup(this);
    JoinSign.load();
    new BukkitCommandManager(this).registerCommand(new BuildingGameCommand());
    Bukkit.getPluginManager().registerEvents(new JoinSignBreak(), this);
    Bukkit.getPluginManager().registerEvents(new JoinSignCreate(), this);
    Bukkit.getPluginManager().registerEvents(new ClickJoinSign(), this);
    // connects the client to the server
    BungeeCordHandler.getInstance();
    getLogger().info("BuildingGame - BungeeCord Addon has been enabled");
}
Also used : BukkitCommandManager(co.aikar.commands.BukkitCommandManager) JoinSignCreate(com.gmail.stefvanschiedev.buildinggame.events.block.JoinSignCreate) JoinSignBreak(com.gmail.stefvanschiedev.buildinggame.events.block.JoinSignBreak) ClickJoinSign(com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign) BuildingGameCommand(com.gmail.stefvanschiedev.buildinggame.command.BuildingGameCommand)

Aggregations

BukkitCommandManager (co.aikar.commands.BukkitCommandManager)7 InvalidCommandArgument (co.aikar.commands.InvalidCommandArgument)3 ConditionFailedException (co.aikar.commands.ConditionFailedException)2 ClickJoinSign (com.gmail.stefvanschiedev.buildinggame.events.player.signs.ClickJoinSign)2 Stream (java.util.stream.Stream)2 Metrics (org.bstats.bukkit.Metrics)2 Bukkit (org.bukkit.Bukkit)2 Material (org.bukkit.Material)2 Player (org.bukkit.entity.Player)2 PlaceholderAPI (be.maximvdw.placeholderapi.PlaceholderAPI)1 BukkitCommandCompletionContext (co.aikar.commands.BukkitCommandCompletionContext)1 PaperCommandManager (co.aikar.commands.PaperCommandManager)1 Gui (com.github.stefvanschie.inventoryframework.gui.type.util.Gui)1 BuildingGameCommand (com.gmail.stefvanschiedev.buildinggame.command.BuildingGameCommand)1 BlockDispenseItem (com.gmail.stefvanschiedev.buildinggame.events.block.BlockDispenseItem)1 BlockEdit (com.gmail.stefvanschiedev.buildinggame.events.block.BlockEdit)1 JoinSignBreak (com.gmail.stefvanschiedev.buildinggame.events.block.JoinSignBreak)1 JoinSignCreate (com.gmail.stefvanschiedev.buildinggame.events.block.JoinSignCreate)1 LiquidFlow (com.gmail.stefvanschiedev.buildinggame.events.block.LiquidFlow)1 PistonBlockMove (com.gmail.stefvanschiedev.buildinggame.events.block.PistonBlockMove)1