Search in sources :

Example 1 with CommentedFileConfiguration

use of dev.rosewood.rosegarden.config.CommentedFileConfiguration in project RoseGarden by Rosewood-Development.

the class RoseCommandWrapper method register.

public void register() {
    try {
        // Load commands
        List<Class<? extends RoseCommand>> commandClasses = new ArrayList<>();
        if (this.includeBaseCommand())
            commandClasses.add(BaseCommand.class);
        if (this.includeHelpCommand())
            commandClasses.add(HelpCommand.class);
        if (this.includeReloadCommand())
            commandClasses.add(ReloadCommand.class);
        this.getCommandPackages().stream().map(x -> ClassUtils.getClassesOf(this.rosePlugin, x, RoseCommand.class)).forEach(commandClasses::addAll);
        for (Class<? extends RoseCommand> commandClass : commandClasses) {
            // Ignore abstract/interface classes
            if (Modifier.isAbstract(commandClass.getModifiers()) || Modifier.isInterface(commandClass.getModifiers()))
                continue;
            // Subcommands get loaded within commands
            if (RoseSubCommand.class.isAssignableFrom(commandClass))
                continue;
            RoseCommand command = commandClass.getConstructor(RosePlugin.class, RoseCommandWrapper.class).newInstance(this.rosePlugin, this);
            this.commands.add(command);
        }
        // Register commands
        File commandsDirectory = new File(this.rosePlugin.getDataFolder(), "commands");
        commandsDirectory.mkdirs();
        File commandConfigFile = new File(commandsDirectory, this.getDefaultName() + ".yml");
        boolean exists = commandConfigFile.exists();
        CommentedFileConfiguration commandConfig = CommentedFileConfiguration.loadConfiguration(commandConfigFile);
        boolean modified = false;
        if (!exists) {
            commandConfig.addComments("This file lets you change the name and aliases for the " + this.getDefaultName() + " command.", "If you edit the name/aliases at the top of this file, you will need to restart the server to see all the changes applied properly.");
            modified = true;
        }
        // Write default config values if they don't exist
        if (!commandConfig.contains("name")) {
            commandConfig.set("name", this.getDefaultName());
            modified = true;
        }
        // Write default alias values if they don't exist
        if (!commandConfig.contains("aliases")) {
            commandConfig.set("aliases", new ArrayList<>(this.getDefaultAliases()));
            modified = true;
        }
        // Write subcommands
        if (!this.commands.isEmpty()) {
            ConfigurationSection subcommandsSection = commandConfig.getConfigurationSection("subcommands");
            if (subcommandsSection == null) {
                subcommandsSection = commandConfig.createSection("subcommands");
                modified = true;
            }
            for (RoseCommand command : this.commands) {
                // Skip base command
                if (command.getDefaultName().isEmpty()) {
                    command.setNameAndAliases("", Collections.emptyList());
                    this.commandLookupMap.put("", command);
                    continue;
                }
                ConfigurationSection commandSection = subcommandsSection.getConfigurationSection(command.getDefaultName());
                if (commandSection == null) {
                    commandSection = subcommandsSection.createSection(command.getDefaultName());
                    modified = true;
                }
                if (!commandSection.contains("name")) {
                    commandSection.set("name", command.getDefaultName());
                    modified = true;
                }
                if (!commandSection.contains("aliases")) {
                    commandSection.set("aliases", new ArrayList<>(command.getDefaultAliases()));
                    modified = true;
                }
                String name = commandSection.getString("name", command.getDefaultName());
                List<String> aliases = commandSection.getStringList("aliases");
                command.setNameAndAliases(name, aliases);
                // Add to command lookup map
                this.commandLookupMap.put(name.toLowerCase(), command);
                aliases.forEach(x -> this.commandLookupMap.put(x.toLowerCase(), command));
            }
        }
        if (modified)
            commandConfig.save();
        // Load command config values
        this.activeName = commandConfig.getString("name");
        this.activeAliases = commandConfig.getStringList("aliases");
        // Finally, register the command with the server
        CommandMapUtils.registerCommand(this.rosePlugin.getName().toLowerCase(), this);
    } catch (Exception e) {
        this.rosePlugin.getLogger().severe("Fatal error initializing command argument handlers");
        e.printStackTrace();
    }
}
Also used : Arrays(java.util.Arrays) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) ClassUtils(dev.rosewood.rosegarden.utils.ClassUtils) HashMap(java.util.HashMap) Player(org.bukkit.entity.Player) ArrayList(java.util.ArrayList) ReloadCommand(dev.rosewood.rosegarden.command.command.ReloadCommand) Map(java.util.Map) AbstractLocaleManager(dev.rosewood.rosegarden.manager.AbstractLocaleManager) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) LinkedList(java.util.LinkedList) BaseCommand(dev.rosewood.rosegarden.command.command.BaseCommand) StringPlaceholders(dev.rosewood.rosegarden.utils.StringPlaceholders) CommandSender(org.bukkit.command.CommandSender) StringUtil(org.bukkit.util.StringUtil) CommandMapUtils(dev.rosewood.rosegarden.utils.CommandMapUtils) Collectors(java.util.stream.Collectors) RosePlugin(dev.rosewood.rosegarden.RosePlugin) File(java.io.File) BukkitCommand(org.bukkit.command.defaults.BukkitCommand) List(java.util.List) Stream(java.util.stream.Stream) Modifier(java.lang.reflect.Modifier) AbstractCommandManager(dev.rosewood.rosegarden.manager.AbstractCommandManager) Comparator(java.util.Comparator) HelpCommand(dev.rosewood.rosegarden.command.command.HelpCommand) Collections(java.util.Collections) BaseCommand(dev.rosewood.rosegarden.command.command.BaseCommand) HelpCommand(dev.rosewood.rosegarden.command.command.HelpCommand) ArrayList(java.util.ArrayList) ReloadCommand(dev.rosewood.rosegarden.command.command.ReloadCommand) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) RosePlugin(dev.rosewood.rosegarden.RosePlugin) File(java.io.File) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Example 2 with CommentedFileConfiguration

use of dev.rosewood.rosegarden.config.CommentedFileConfiguration in project RoseStacker by Rosewood-Development.

the class RoseCommand method onTranslate.

@Subcommand("translate")
@CommandPermission("rosestacker.translate")
@CommandCompletion("@translationLocales *")
public void onTranslate(CommandSender sender, String locale, @Optional String spawnerFormat) {
    LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
    StackSettingManager stackSettingManager = this.rosePlugin.getManager(StackSettingManager.class);
    if (spawnerFormat == null) {
        spawnerFormat = "{}";
        localeManager.sendMessage(sender, "command-translate-spawner-format");
    }
    if (!spawnerFormat.contains("{}")) {
        localeManager.sendMessage(sender, "command-translate-spawner-format-invalid");
        return;
    }
    localeManager.sendMessage(sender, "command-translate-loading");
    String finalSpawnerFormat = spawnerFormat;
    localeManager.getMinecraftTranslationValues(locale, response -> {
        if (response.getResult() == Result.FAILURE) {
            localeManager.sendMessage(sender, "command-translate-failure");
            return;
        }
        if (response.getResult() == Result.INVALID_LOCALE) {
            localeManager.sendMessage(sender, "command-translate-invalid-locale");
            return;
        }
        CommentedFileConfiguration blockStackConfig = CommentedFileConfiguration.loadConfiguration(stackSettingManager.getBlockSettingsFile());
        CommentedFileConfiguration entityStackConfig = CommentedFileConfiguration.loadConfiguration(stackSettingManager.getEntitySettingsFile());
        CommentedFileConfiguration itemStackConfig = CommentedFileConfiguration.loadConfiguration(stackSettingManager.getItemSettingsFile());
        CommentedFileConfiguration spawnerStackConfig = CommentedFileConfiguration.loadConfiguration(stackSettingManager.getSpawnerSettingsFile());
        Map<Material, String> materialValues = response.getMaterialValues();
        Map<EntityType, String> entityValues = response.getEntityValues();
        for (Entry<Material, String> entry : materialValues.entrySet()) {
            Material material = entry.getKey();
            String value = entry.getValue();
            if (blockStackConfig.isConfigurationSection(material.name()))
                blockStackConfig.set(material.name() + ".display-name", value);
            if (itemStackConfig.isConfigurationSection(material.name()))
                itemStackConfig.set(material.name() + ".display-name", value);
        }
        for (Entry<EntityType, String> entry : entityValues.entrySet()) {
            EntityType entityType = entry.getKey();
            String value = entry.getValue();
            if (entityStackConfig.isConfigurationSection(entityType.name()))
                entityStackConfig.set(entityType.name() + ".display-name", value);
            if (spawnerStackConfig.isConfigurationSection(entityType.name())) {
                String name = finalSpawnerFormat.replaceAll(Pattern.quote("{}"), value);
                spawnerStackConfig.set(entityType.name() + ".display-name", name);
            }
        }
        blockStackConfig.save();
        entityStackConfig.save();
        itemStackConfig.save();
        spawnerStackConfig.save();
        Bukkit.getScheduler().runTask(this.rosePlugin, () -> {
            this.rosePlugin.reload();
            localeManager.sendMessage(sender, "command-translate-success");
        });
    });
}
Also used : EntityType(org.bukkit.entity.EntityType) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) StackSettingManager(dev.rosewood.rosestacker.manager.StackSettingManager) Material(org.bukkit.Material) LocaleManager(dev.rosewood.rosestacker.manager.LocaleManager) Subcommand(co.aikar.commands.annotation.Subcommand) CommandCompletion(co.aikar.commands.annotation.CommandCompletion) CommandPermission(co.aikar.commands.annotation.CommandPermission)

Example 3 with CommentedFileConfiguration

use of dev.rosewood.rosegarden.config.CommentedFileConfiguration in project RoseStacker by Rosewood-Development.

the class StackSettingManager method reload.

@Override
public void reload() {
    // Settings files
    File blockSettingsFile = this.getBlockSettingsFile();
    File entitySettingsFile = this.getEntitySettingsFile();
    File itemSettingsFile = this.getItemSettingsFile();
    File spawnerSettingsFile = this.getSpawnerSettingsFile();
    // Flags for if we should save the files
    AtomicBoolean saveBlockSettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveEntitySettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveItemSettingsFile = new AtomicBoolean(false);
    AtomicBoolean saveSpawnerSettingsFile = new AtomicBoolean(false);
    // Load block settings
    CommentedFileConfiguration blockSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(blockSettingsFile);
    StackerUtils.getPossibleStackableBlockMaterials().forEach(x -> {
        BlockStackSettings blockStackSettings = new BlockStackSettings(blockSettingsConfiguration, x);
        this.blockSettings.put(x, blockStackSettings);
        if (blockStackSettings.hasChanges())
            saveBlockSettingsFile.set(true);
    });
    // Load entity settings and data from entity_data.json
    CommentedFileConfiguration entitySettingsConfiguration = CommentedFileConfiguration.loadConfiguration(entitySettingsFile);
    try (InputStream entityDataStream = this.getClass().getResourceAsStream("/entity_data.json");
        Reader entityDataReader = new InputStreamReader(entityDataStream)) {
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = jsonParser.parse(entityDataReader).getAsJsonObject();
        List<Class<EntityStackSettings>> classes = ClassUtils.getClassesOf(this.rosePlugin, PACKAGE_PATH, EntityStackSettings.class);
        List<String> ignoredLoading = new ArrayList<>();
        for (Class<EntityStackSettings> clazz : classes) {
            try {
                EntityStackSettings entityStackSetting = clazz.getConstructor(CommentedFileConfiguration.class, JsonObject.class).newInstance(entitySettingsConfiguration, jsonObject);
                this.entitySettings.put(entityStackSetting.getEntityType(), entityStackSetting);
                if (entityStackSetting.hasChanges())
                    saveEntitySettingsFile.set(true);
            } catch (Exception e) {
                // Log entity settings that failed to load
                // This should only be caused by version incompatibilities
                String className = clazz.getSimpleName();
                ignoredLoading.add(className.substring(0, className.length() - 13));
            }
        }
        if (!ignoredLoading.isEmpty())
            this.rosePlugin.getLogger().warning("Ignored loading stack settings for entities: " + ignoredLoading);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Load item settings
    CommentedFileConfiguration itemSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(itemSettingsFile);
    Stream.of(Material.values()).sorted(Comparator.comparing(Enum::name)).forEach(x -> {
        ItemStackSettings itemStackSettings = new ItemStackSettings(itemSettingsConfiguration, x);
        this.itemSettings.put(x, itemStackSettings);
        if (itemStackSettings.hasChanges())
            saveItemSettingsFile.set(true);
    });
    // Load spawner settings
    boolean addSpawnerHeaderComments = !spawnerSettingsFile.exists();
    CommentedFileConfiguration spawnerSettingsConfiguration = CommentedFileConfiguration.loadConfiguration(spawnerSettingsFile);
    if (addSpawnerHeaderComments) {
        saveSpawnerSettingsFile.set(true);
        Map<String, String> conditionTags = ConditionTags.getTagDescriptionMap();
        spawnerSettingsConfiguration.addComments("Available Spawn Requirements:", "");
        for (Entry<String, String> entry : conditionTags.entrySet()) {
            String tag = entry.getKey();
            String description = entry.getValue();
            spawnerSettingsConfiguration.addComments(tag + " - " + description);
        }
        spawnerSettingsConfiguration.addComments("", "Valid Blocks: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html", "Valid Biomes: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/block/Biome.html", "", "Want to remove all requirements? Set the value to the following:", "spawn-requirements: []");
    }
    StackerUtils.getAlphabeticalStackableEntityTypes().forEach(x -> {
        SpawnerStackSettings spawnerStackSettings = new SpawnerStackSettings(spawnerSettingsConfiguration, x);
        this.spawnerSettings.put(x, spawnerStackSettings);
        if (spawnerStackSettings.hasChanges())
            saveSpawnerSettingsFile.set(true);
    });
    // Save files if changes were made
    if (saveBlockSettingsFile.get())
        blockSettingsConfiguration.save(true);
    if (saveEntitySettingsFile.get())
        entitySettingsConfiguration.save(true);
    if (saveItemSettingsFile.get())
        itemSettingsConfiguration.save(true);
    if (saveSpawnerSettingsFile.get())
        spawnerSettingsConfiguration.save(true);
    // Register dynamic permissions on first load
    if (!this.registeredPermissions) {
        PluginManager pluginManager = Bukkit.getPluginManager();
        List<Permission> silktouch = new ArrayList<>();
        List<Permission> nosilk = new ArrayList<>();
        List<Permission> spawnerplace = new ArrayList<>();
        for (EntityType entityType : this.entitySettings.keySet()) {
            String type = entityType.name().toLowerCase();
            silktouch.add(new Permission("rosestacker.silktouch." + type));
            nosilk.add(new Permission("rosestacker.nosilk." + type));
            spawnerplace.add(new Permission("rosestacker.spawnerplace." + type));
        }
        // Register silktouch permissions
        silktouch.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.silktouch.*", silktouch.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        // Register nosilk permissions
        nosilk.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.nosilk.*", nosilk.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        // Register spawnerplace permissions
        spawnerplace.forEach(pluginManager::addPermission);
        pluginManager.addPermission(new Permission("rosestacker.spawnerplace.*", spawnerplace.stream().collect(Collectors.toMap(Permission::getName, x -> true))));
        this.registeredPermissions = true;
    }
}
Also used : JsonObject(com.google.gson.JsonObject) Manager(dev.rosewood.rosegarden.manager.Manager) Item(org.bukkit.entity.Item) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClassUtils(dev.rosewood.rosegarden.utils.ClassUtils) HashMap(java.util.HashMap) JsonParser(com.google.gson.JsonParser) ItemUtils(dev.rosewood.rosestacker.utils.ItemUtils) ArrayList(java.util.ArrayList) EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) Block(org.bukkit.block.Block) Map(java.util.Map) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) ItemStackSettings(dev.rosewood.rosestacker.stack.settings.ItemStackSettings) Material(org.bukkit.Material) Bukkit(org.bukkit.Bukkit) CreatureSpawner(org.bukkit.block.CreatureSpawner) Set(java.util.Set) Reader(java.io.Reader) EntityType(org.bukkit.entity.EntityType) LivingEntity(org.bukkit.entity.LivingEntity) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) RosePlugin(dev.rosewood.rosegarden.RosePlugin) ConditionTags(dev.rosewood.rosestacker.spawner.conditions.ConditionTags) File(java.io.File) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) Permission(org.bukkit.permissions.Permission) List(java.util.List) Stream(java.util.stream.Stream) Entry(java.util.Map.Entry) StackerUtils(dev.rosewood.rosestacker.utils.StackerUtils) Comparator(java.util.Comparator) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) InputStream(java.io.InputStream) PluginManager(org.bukkit.plugin.PluginManager) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) ItemStackSettings(dev.rosewood.rosestacker.stack.settings.ItemStackSettings) PluginManager(org.bukkit.plugin.PluginManager) CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) Permission(org.bukkit.permissions.Permission) JsonParser(com.google.gson.JsonParser) EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) EntityType(org.bukkit.entity.EntityType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) File(java.io.File)

Example 4 with CommentedFileConfiguration

use of dev.rosewood.rosegarden.config.CommentedFileConfiguration in project RoseGarden by Rosewood-Development.

the class AbstractLocaleManager method registerLocale.

/**
 * Creates a .lang file if one doesn't exist
 * Cross merges values between files into the .lang file, the .lang values take priority
 *
 * @param locale The Locale to register
 */
private void registerLocale(Locale locale) {
    File file = new File(this.rosePlugin.getDataFolder() + "/locale", locale.getLocaleName() + ".lang");
    boolean newFile = false;
    if (!file.exists()) {
        try {
            file.createNewFile();
            newFile = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    boolean changed = false;
    CommentedFileConfiguration configuration = CommentedFileConfiguration.loadConfiguration(file);
    if (newFile) {
        configuration.addComments(locale.getLocaleName() + " translation by " + locale.getTranslatorName());
        Map<String, Object> defaultLocaleStrings = locale.getDefaultLocaleValues();
        for (String key : defaultLocaleStrings.keySet()) {
            Object value = defaultLocaleStrings.get(key);
            if (key.startsWith("#")) {
                configuration.addComments((String) value);
            } else {
                configuration.set(key, value);
            }
        }
        changed = true;
    } else {
        Map<String, Object> defaultLocaleStrings = locale.getDefaultLocaleValues();
        for (String key : defaultLocaleStrings.keySet()) {
            if (key.startsWith("#"))
                continue;
            Object value = defaultLocaleStrings.get(key);
            if (!configuration.contains(key)) {
                configuration.set(key, value);
                changed = true;
            }
        }
    }
    if (changed)
        configuration.save();
}
Also used : CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) IOException(java.io.IOException) File(java.io.File)

Example 5 with CommentedFileConfiguration

use of dev.rosewood.rosegarden.config.CommentedFileConfiguration in project RoseGarden by Rosewood-Development.

the class PluginUpdateManager method reload.

@Override
public void reload() {
    File configFile = new File(this.rosePlugin.getRoseGardenDataFolder(), "config.yml");
    CommentedFileConfiguration configuration = CommentedFileConfiguration.loadConfiguration(configFile);
    if (!configuration.contains("check-updates")) {
        configuration.set("check-updates", true, "Should all plugins running RoseGarden check for updates?", "RoseGarden is a core library created by Rosewood Development");
        configuration.save();
    }
    if (!configuration.getBoolean("check-updates") || this.rosePlugin.getSpigotId() == -1)
        return;
    // Check for updates
    Bukkit.getScheduler().runTaskAsynchronously(this.rosePlugin, () -> {
        try {
            String latestVersion = this.getLatestVersion();
            String currentVersion = this.rosePlugin.getDescription().getVersion();
            if (RoseGardenUtils.isUpdateAvailable(latestVersion, currentVersion)) {
                this.updateVersion = latestVersion;
                RoseGardenUtils.getLogger().info("An update for " + this.rosePlugin.getName() + " (v" + this.updateVersion + ") is available! You are running v" + currentVersion + ".");
            }
        } catch (Exception e) {
            RoseGardenUtils.getLogger().warning("An error occurred checking for an update. There is either no established internet connection or the Spigot API is down.");
        }
    });
}
Also used : CommentedFileConfiguration(dev.rosewood.rosegarden.config.CommentedFileConfiguration) File(java.io.File) IOException(java.io.IOException)

Aggregations

CommentedFileConfiguration (dev.rosewood.rosegarden.config.CommentedFileConfiguration)5 File (java.io.File)4 RosePlugin (dev.rosewood.rosegarden.RosePlugin)2 ClassUtils (dev.rosewood.rosegarden.utils.ClassUtils)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Comparator (java.util.Comparator)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 Material (org.bukkit.Material)2 EntityType (org.bukkit.entity.EntityType)2 CommandCompletion (co.aikar.commands.annotation.CommandCompletion)1 CommandPermission (co.aikar.commands.annotation.CommandPermission)1 Subcommand (co.aikar.commands.annotation.Subcommand)1 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 BaseCommand (dev.rosewood.rosegarden.command.command.BaseCommand)1