Java Code Examples for org.bukkit.configuration.ConfigurationSection#getString()

The following examples show how to use org.bukkit.configuration.ConfigurationSection#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChallengeFactory.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
private static Reward createReward(ConfigurationSection section) {
    if (section == null) {
        return null;
    }
    List<String> items = new ArrayList<>();
    if (!section.getStringList("items").isEmpty()) {
        items.addAll(section.getStringList("items"));
    } else if (section.getString("items", null) != null) {
        items.addAll(Arrays.asList(section.getString("items").split(" ")));
    }
    return new Reward(
            section.getString("text", "\u00a74Unknown"),
            ItemStackUtil.createItemsWithProbabilty(items),
            section.getString("permission"),
            section.getInt("currency", 0),
            section.getInt("xp", 0),
            section.getStringList("commands"));
}
 
Example 2
Source File: HologramFormat.java    From ShopChest with MIT License 6 votes vote down vote up
/**
 * Get the format for the given line of the hologram
 * @param line Line of the hologram
 * @param reqMap Values of the requirements that might be needed by the format (contains {@code null} if not comparable)
 * @param plaMap Values of the placeholders that might be needed by the format
 * @return  The format of the first working option, or an empty String if no option is working
 *          because of not fulfilled requirements
 */
public String getFormat(int line, Map<Requirement, Object> reqMap, Map<Placeholder, Object> plaMap) {
    ConfigurationSection options = config.getConfigurationSection("lines." + line + ".options");

    optionLoop:
    for (String key : options.getKeys(false)) {
        ConfigurationSection option = options.getConfigurationSection(key);
        List<String> requirements = option.getStringList("requirements");

        String format = option.getString("format");

        for (String sReq : requirements) {
            for (Requirement req : reqMap.keySet()) {
                if (sReq.contains(req.toString())) {
                    if (!evalRequirement(sReq, reqMap)) {
                        continue optionLoop;
                    }
                }
            }
        }

        return evalPlaceholder(format, plaMap);
    }

    return "";
}
 
Example 3
Source File: GuildHandler.java    From Guilds with MIT License 6 votes vote down vote up
/**
 * Load all the roles
 */
private void loadRoles() {
    final YamlConfiguration conf = YamlConfiguration.loadConfiguration(new File(guildsPlugin.getDataFolder(), "roles.yml"));
    final ConfigurationSection roleSec = conf.getConfigurationSection("roles");

    for (String s : roleSec.getKeys(false)) {
        final String path = s + ".permissions.";
        final String name = roleSec.getString(s + ".name");
        final String perm = roleSec.getString(s + ".permission-node");
        final int level = Integer.parseInt(s);

        final GuildRole role = new GuildRole(name, perm, level);

        for (GuildRolePerm rolePerm: GuildRolePerm.values()) {
            final String valuePath = path + rolePerm.name().replace("_", "-").toLowerCase();
            if (roleSec.getBoolean(valuePath)) {
                role.addPerm(rolePerm);
            }
        }
        this.roles.add(role);
    }
}
 
Example 4
Source File: HologramFormat.java    From ShopChest with MIT License 6 votes vote down vote up
/**
 * @return Whether the hologram text has to change dynamically without reloading
 */
public boolean isDynamic() {
    int count = getLineCount();
    for (int i = 0; i < count; i++) {
        ConfigurationSection options = config.getConfigurationSection("lines." + i + ".options");

        for (String key : options.getKeys(false)) {
            ConfigurationSection option = options.getConfigurationSection(key);

            String format = option.getString("format");
            if (format.contains(Placeholder.STOCK.toString()) || format.contains(Placeholder.CHEST_SPACE.toString())) {
                return true;
            }

            for (String req : option.getStringList("requirements")) {
                if (req.contains(Requirement.IN_STOCK.toString()) || req.contains(Requirement.CHEST_SPACE.toString())) {
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example 5
Source File: DPortal.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
public DPortal(DungeonsXL plugin, World world, int id, ConfigurationSection config) {
    super(plugin, world, id);

    block1 = world.getBlockAt(config.getInt("loc1.x"), config.getInt("loc1.y"), config.getInt("loc1.z"));
    block2 = world.getBlockAt(config.getInt("loc2.x"), config.getInt("loc2.y"), config.getInt("loc2.z"));
    material = plugin.getCaliburn().getExItem(config.getString("material"));
    if (material == null) {
        material = VanillaItem.NETHER_PORTAL;
    }
    String axis = config.getString("axis");
    zAxis = axis != null && axis.equalsIgnoreCase("z");
    active = true;
    create(null);
}
 
Example 6
Source File: CivPotionEffect.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
public CivPotionEffect(Spell spell, String key, Object target, Entity origin, int level, ConfigurationSection section) {
    super(spell, key, target, origin, level, section);
    this.type = PotionEffectType.getByName(section.getString("type", "POISON"));
    this.ticks = (int) Math.round(Spell.getLevelAdjustedValue("" + section.getInt("ticks", 40), level, target, spell));
    this.level = (int) Math.round(Spell.getLevelAdjustedValue("" + section.getInt("level", 1), level, target, spell));
    String tempTarget = section.getString("target", "not-a-string");
    if (!tempTarget.equals("not-a-string")) {
        this.target = tempTarget;
    } else {
        this.target = "self";
    }
    this.config = section;

    this.potion = new PotionEffect(type, ticks, this.level);
}
 
Example 7
Source File: AdminShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void load(ConfigurationSection config) throws ShopkeeperCreateException {
	super.load(config);
	// load trade permission:
	tradePermission = config.getString("tradePerm", null);
	// load offers:
	recipes.clear();
	// legacy: load offers from old format
	recipes.addAll(this.loadRecipesOld(config, "recipes"));
	recipes.addAll(this.loadRecipes(config, "recipes"));
}
 
Example 8
Source File: PGMConfig.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public Group(ConfigurationSection config) throws TextException {
  this.id = config.getName();
  final String prefix = config.getString("prefix");
  this.prefix = prefix == null ? null : parseComponentLegacy(prefix);
  final PermissionDefault def =
      id.equalsIgnoreCase("op")
          ? PermissionDefault.OP
          : id.equalsIgnoreCase("default") ? PermissionDefault.TRUE : PermissionDefault.FALSE;
  this.permission = getPermission(config, id, def, "permissions");
  this.observerPermission =
      getPermission(config, id, PermissionDefault.FALSE, "observer-permissions");
  this.participantPermission =
      getPermission(config, id, PermissionDefault.FALSE, "participant-permissions");
}
 
Example 9
Source File: Extra.java    From TradePlus with GNU General Public License v3.0 5 votes vote down vote up
Extra(String name, Player player1, Player player2, TradePlus pl, Trade trade) {
  this.pl = pl;
  this.name = name;
  ConfigurationSection section =
      Preconditions.checkNotNull(pl.getConfig().getConfigurationSection("extras." + name));
  this.displayName = section.getString("name");
  this.player1 = player1;
  this.player2 = player2;
  this.increment = section.getDouble("increment", 1D);
  this.increment1 = increment;
  this.increment2 = increment;
  ItemFactory factory =
      new ItemFactory(section.getString("material", "PAPER"), Material.PAPER)
          .display('&', section.getString("display", "&4ERROR"))
          .customModelData(section.getInt("customModelData", 0));
  if (section.contains("lore")) factory.lore('&', section.getStringList("lore"));
  this.icon = factory.flag("HIDE_ATTRIBUTES").build();
  this.theirIcon =
      new ItemFactory(section.getString("material", "PAPER"), Material.PAPER)
          .display('&', section.getString("theirdisplay", "&4ERROR"))
          .customModelData(section.getInt("customModelData", 0))
          .build();
  this.taxPercent = section.getDouble("taxpercent", 0);
  this.mode = section.getString("mode", "chat").toLowerCase();
  if (mode.equals("type") || mode.equals("anvil")) {
    mode = "chat";
    section.set("mode", "chat");
    pl.saveConfig();
  }
  this.trade = trade;
}
 
Example 10
Source File: CancelEffect.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
public CancelEffect(Spell spell, String key, Object target, Entity origin, int level, ConfigurationSection section) {
    super(spell, key, target, origin, level, section);
    this.silent = section.getBoolean("silent", false);
    this.target = section.getString("target", "self");
    this.abilityName = section.getString("ability", "self");
    this.whitelist = section.getStringList("whitelist");
    this.blacklist = section.getStringList("blacklist");
    this.config = section;
}
 
Example 11
Source File: Currency.java    From SaneEconomy with GNU General Public License v3.0 5 votes vote down vote up
public static Currency fromConfig(ConfigurationSection config) {
    DecimalFormat format = new DecimalFormat(config.getString("format", "0.00"));

    if (config.getInt("grouping", 0) > 0) {
        DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();
        if (symbols.getDecimalSeparator() == ',') { // French
            symbols.setGroupingSeparator(' ');
        } else {
            symbols.setGroupingSeparator(',');
        }

        String groupingSeparator = config.getString("grouping-separator", null);

        if (!Strings.isNullOrEmpty(groupingSeparator)) {
            symbols.setGroupingSeparator(groupingSeparator.charAt(0));
        }

        String decimalSeparator = config.getString("decimal-separator", ".");

        if (!Strings.isNullOrEmpty(decimalSeparator)) {
            symbols.setDecimalSeparator(decimalSeparator.charAt(0));
        }

        format.setDecimalFormatSymbols(symbols);
        format.setGroupingUsed(true);
        format.setGroupingSize(3);
    }

    return new Currency(
               config.getString("name.singular", "dollar"),
               config.getString("name.plural", "dollars"),
               format,
               config.getString("balance-format", "{1} {2}")
           );
}
 
Example 12
Source File: ChallengeFactory.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public static Challenge createChallenge(Rank rank, ConfigurationSection section, ChallengeDefaults defaults) {
    String name = section.getName().toLowerCase();
    if (section.getBoolean("disabled", false)) {
        return null; // Skip this challenge
    }
    String displayName = section.getString("name", name);
    Challenge.Type type = Challenge.Type.from(section.getString("type", "onPlayer"));
    List<String> requiredItems = section.isList("requiredItems") ? section.getStringList("requiredItems") : Arrays.asList(section.getString("requiredItems", "").split(" "));
    List<EntityMatch> requiredEntities = createEntities(section.getStringList("requiredEntities"));
    int resetInHours = section.getInt("resetInHours", rank.getResetInHours());
    String description = section.getString("description");
    ItemStack displayItem = createItemStack(
            section.getString("displayItem", defaults.displayItem),
            normalize(displayName), description);
    ItemStack lockedItem = section.isString("lockedDisplayItem") ? createItemStack(section.getString("lockedDisplayItem", "BARRIER"), displayName, description) : null;
    boolean takeItems = section.getBoolean("takeItems", true);
    int radius = section.getInt("radius", 10);
    Reward reward = createReward(section.getConfigurationSection("reward"));
    Reward repeatReward = createReward(section.getConfigurationSection("repeatReward"));
    if (repeatReward == null && section.getBoolean("repeatable", false)) {
        repeatReward = reward;
    }
    List<String> requiredChallenges = section.getStringList("requiredChallenges");
    int offset = section.getInt("offset", 0);
    int repeatLimit = section.getInt("repeatLimit", 0);
    return new Challenge(name, displayName, description, type,
            requiredItems, requiredEntities, requiredChallenges, section.getDouble("requiredLevel", 0d), rank,
            resetInHours, displayItem, section.getString("tool", null), lockedItem, offset, takeItems,
            radius, reward, repeatReward, repeatLimit);
}
 
Example 13
Source File: ConfigUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static URL getUrl(ConfigurationSection section, String key, URL def) {
    String value = section.getString(key);
    try {
        return value == null ? def : new URL(value);
    } catch(MalformedURLException e) {
        throw new IllegalArgumentException("Invalid URL format '" + value + "'", e);
    }
}
 
Example 14
Source File: StaticEvents.java    From BetonQuest with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates new instance of a StaticEvents object, scheduling static events
 * to run at specified times
 */
public StaticEvents() {
    LogUtils.getLogger().log(Level.FINE, "Initializing static events");
    // old timers need to be deleted in case of reloading the plugin
    boolean deleted = false;
    for (EventTimer eventTimer : timers) {
        eventTimer.cancel();
        deleted = true;
    }
    if (deleted) {
        LogUtils.getLogger().log(Level.FINE, "Previous timers has been canceled");
    }
    for (ConfigPackage pack : Config.getPackages().values()) {
        String packName = pack.getName();
        LogUtils.getLogger().log(Level.FINE, "Searching package " + packName);
        // get those hours and events
        ConfigurationSection config = pack.getMain().getConfig().getConfigurationSection("static");
        if (config == null) {
            LogUtils.getLogger().log(Level.FINE, "There are no static events defined, skipping");
            continue;
        }
        // for each hour, create an event timer
        for (String key : config.getKeys(false)) {
            String value = config.getString(key);
            long timeStamp = getTimestamp(key);
            if (timeStamp < 0) {
                LogUtils.getLogger().log(Level.WARNING, "Incorrect time value in static event declaration (" + key + "), skipping this one");
                continue;
            }
            LogUtils.getLogger().log(Level.FINE, "Scheduling static event " + value + " at hour " + key + ". Current timestamp: "
                    + new Date().getTime() + ", target timestamp: " + timeStamp);
            // add the timer to static list, so it can be canceled if needed
            try {
                timers.add(new EventTimer(timeStamp, new EventID(pack, value)));
            } catch (ObjectNotFoundException e) {
                LogUtils.getLogger().log(Level.WARNING, "Could not load static event '" + packName + "." + key + "': " + e.getMessage());
                LogUtils.logThrowable(e);
            }
        }
    }
    LogUtils.getLogger().log(Level.FINE, "Static events initialization done");
}
 
Example 15
Source File: ControlPanel.java    From askyblock with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This loads the control panel from the controlpanel.yml file
 */
public static void loadControlPanel() {
    ASkyBlock plugin = ASkyBlock.getPlugin();
    // Map of known panel contents by name
    panels.clear();
    // Map of panel inventories by name
    controlPanel.clear();
    cpFile = Util.loadYamlFile("controlpanel.yml");
    ConfigurationSection controlPanels = cpFile.getRoot();
    if (controlPanels == null) {
        plugin.getLogger().severe("Controlpanel.yml is corrupted! Delete so it can be regenerated or fix!");
        return;
    }
    // Go through the yml file and create inventories and panel maps
    for (String panel : controlPanels.getKeys(false)) {
        // plugin.getLogger().info("DEBUG: Panel " + panel);
        ConfigurationSection panelConf = cpFile.getConfigurationSection(panel);
        if (panelConf != null) {
            // New panel map
            HashMap<Integer, CPItem> cp = new HashMap<Integer, CPItem>();
            String panelName = ChatColor.translateAlternateColorCodes('&', panelConf.getString("panelname", "Commands"));
            if (panel.equalsIgnoreCase("default")) {
                defaultPanelName = panelName;
            }
            ConfigurationSection buttons = cpFile.getConfigurationSection(panel + ".buttons");
            if (buttons != null) {
                // Get how many buttons can be in the CP
                int size = buttons.getKeys(false).size() + 8;
                size -= (size % 9);
                // Add inventory to map of inventories
                controlPanel.put(panelName, Bukkit.createInventory(null, size, panelName));
                // Run through buttons
                int slot = 0;
                for (String item : buttons.getKeys(false)) {
                    try {
                        String m = buttons.getString(item + ".material", "BOOK");
                        // Split off damage
                        String[] icon = m.split(":");
                        Material material = Material.matchMaterial(icon[0]);
                        if (material == null) {
                            material = Material.PAPER;
                            plugin.getLogger().severe("Error in controlpanel.yml " + icon[0] + " is an unknown material, using paper.");
                        }
                        String description = ChatColor.translateAlternateColorCodes('&',buttons.getString(item + ".description", ""));
                        String command = buttons.getString(item + ".command", "").replace("[island]", Settings.ISLANDCOMMAND);
                        String nextSection = buttons.getString(item + ".nextsection", "");
                        ItemStack i = new ItemStack(material);
                        if (icon.length == 2) {
                            i.setDurability(Short.parseShort(icon[1]));
                        }
                        CPItem cpItem = new CPItem(i, description, command, nextSection);
                        cp.put(slot, cpItem);
                        controlPanel.get(panelName).setItem(slot, cpItem.getItem());
                        slot++;
                    } catch (Exception e) {
                        plugin.getLogger().warning("Problem loading control panel " + panel + " item #" + slot);
                        plugin.getLogger().warning(e.getMessage());
                        e.printStackTrace();
                    }
                }
                // Add overall control panel
                panels.put(panelName, cp);
            }
        }
    }
}
 
Example 16
Source File: Reward.java    From PlayTimeTracker with MIT License 4 votes vote down vote up
public Reward(ConfigurationSection s) {
    description = ChatColor.translateAlternateColorCodes('&', s.getString("description"));
    command = s.getString("command");
}
 
Example 17
Source File: SkyBlockMenu.java    From uSkyBlock with GNU General Public License v3.0 4 votes vote down vote up
private void addExtraMenus(Player player, Inventory menu) {
    ConfigurationSection extras = plugin.getConfig().getConfigurationSection("options.extra-menus");
    if (extras == null) {
        return;
    }
    for (String sIndex : extras.getKeys(false)) {
        ConfigurationSection menuSection = extras.getConfigurationSection(sIndex);
        if (menuSection == null) {
            continue;
        }
        try {
            int index = Integer.parseInt(sIndex, 10);
            String title = menuSection.getString("title", "\u00a9Unknown");
            String icon = menuSection.getString("displayItem", "CHEST");
            List<String> lores = new ArrayList<>();
            for (String l : menuSection.getStringList("lore")) {
                Matcher matcher = PERM_VALUE_PATTERN.matcher(l);
                if (matcher.matches()) {
                    String perm = matcher.group("perm");
                    String lore = matcher.group("value");
                    boolean not = matcher.group("not") != null;
                    if (perm != null) {
                        boolean hasPerm = player.hasPermission(perm);
                        if ((hasPerm && !not) || (!hasPerm && not)) {
                            lores.add(lore);
                        }
                    } else {
                        lores.add(lore);
                    }
                }
            }
            // Only SIMPLE icons supported...
            ItemStack item = new ItemStack(Material.matchMaterial(icon), 1);
            ItemMeta meta = item.getItemMeta();
            meta.setDisplayName(title);
            meta.setLore(lores);
            item.setItemMeta(meta);
            menu.setItem(index, item);
        } catch (Exception e) {
            log(Level.INFO, "\u00a79[uSkyBlock]\u00a7r Unable to add extra-menu " + sIndex + ": " + e);
        }
    }
}
 
Example 18
Source File: ConfigUpdater.java    From BetonQuest with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unused")
private void update_from_v48() {
    for (ConfigPackage pack : Config.getPackages().values()) {
        String packName = pack.getName();
        List<ConfigAccessor> sections = new ArrayList<>();
        // the idea is to get index of location argument for every type
        // and use a method to replace last semicolon with a space, because
        // all range arguments are right next to location arguments
        sections.add(pack.getConditions());
        sections.add(pack.getEvents());
        sections.add(pack.getObjectives());
        for (ConfigAccessor acc : sections) {
            AccessorType type = acc.getType();
            ConfigurationSection sec = acc.getConfig();
            for (String key : sec.getKeys(false)) {
                String value = sec.getString(key);
                int i = value.indexOf(' ');
                if (i < 0) {
                    continue;
                }
                String object = value.substring(0, i).toLowerCase();
                int index = -1;
                switch (type) {
                    case CONDITIONS:
                        switch (object) {
                            case "location":
                                index = 1;
                                break;
                            case "monsters":
                                index = 2;
                                break;
                        }
                        break;
                    case EVENTS:
                        switch (object) {
                            case "clear":
                                index = 2;
                                break;
                        }
                        break;
                    case OBJECTIVES:
                        switch (object) {
                            case "action":
                                // action objective uses optional argument, so convert it manually
                                String[] parts = value.split(" ");
                                String loc = null;
                                for (String part : parts) {
                                    if (part.startsWith("loc:")) {
                                        loc = part;
                                        break;
                                    }
                                }
                                if (loc != null) {
                                    int j = loc.lastIndexOf(';');
                                    if (j < 0 || j >= loc.length() - 1) {
                                        continue;
                                    }
                                    String front = loc.substring(0, j);
                                    String back = loc.substring(j + 1);
                                    String newLoc = front + " range:" + back;
                                    sec.set(key, value.replace(loc, newLoc));
                                }
                                break;
                            case "arrow":
                                index = 1;
                                break;
                            case "location":
                                index = 1;
                                break;
                        }
                        break;
                    default:
                        break;
                }
                if (index >= 0) {
                    sec.set(key, semicolonToSpace(value, index));
                }
            }
            acc.saveConfig();
        }
    }
    LogUtils.getLogger().log(Level.INFO, "Converted additional location arguments to the new format");
    config.set("version", "v49");
    instance.saveConfig();
}
 
Example 19
Source File: Config.java    From MCAuthenticator with GNU General Public License v3.0 4 votes vote down vote up
public Config(MCAuthenticator auth, ConfigurationSection section) throws SQLException, IOException {
    List<String> authenticators = section.getStringList("authenticators");
    this.authenticators = new HashSet<>();
    if (authenticators.contains("2fa")) {
        auth.getLogger().info("Using RFC6238 (Google Authenticator 2FA) based authentication.");
        String tempServerIP;
        tempServerIP = section.getString("2fa.serverIp", section.getString("serverIp"));
        if (tempServerIP == null) {
            auth.getLogger().info("Your serverIp within your MCAuthenticator configuration is not set! It defaults " +
                    "'MCAuthenticator', but you should consider changing it to your server name!");
            tempServerIP = "MCAuthenticator";
        }
        this.authenticators.add(new RFC6238(tempServerIP, auth));
    }
    if (authenticators.contains("yubikey")) {
        Integer clientId = section.getInt("yubikey.clientId");
        String clientSecret = section.getString("yubikey.clientSecret");
        auth.getLogger().info("Using Yubikey based authenticator.");
        if(clientSecret == null || (clientId == -1 && "secret".equals(clientSecret))) {
            auth.getLogger().warning("The Yubikey configuration appears to be the default configuration/not configured!" +
                    " In order for the Yubikey authentication to work, you must retrieve a client id and secret.");
            auth.getLogger().warning("These may be retrieved from here: https://upgrade.yubico.com/getapikey/");
        }
        this.authenticators.add(new Yubikey(clientId, clientSecret, auth));
    }

    String backing = section.getString("dataBacking.type", "single");
    switch (backing) {
        case "single":
            this.dataSource = new SingleFileUserDataSource(new File(auth.getDataFolder(), section.getString("dataBacking.file", "playerData.json")));
            break;
        case "directory":
            this.dataSource = new DirectoryUserDataSource(new File(auth.getDataFolder(), section.getString("dataBacking.directory", "playerData")));
            break;
        case "mysql":
            ConfigurationSection mysql = section.getConfigurationSection("dataBacking.mysql");
            this.dataSource = new MySQLUserDataSource(mysql.getString("url", "jdbc:mysql://localhost:3306/db"),
                    mysql.getString("username"),
                    mysql.getString("password"),
                    mysql.getInt("queryTimeout", 0));
            break;
        default:
            throw new IllegalArgumentException("The dataBacking type '" + backing + "' doesn't exist.");
    }

    auth.getLogger().info("Using data source: " + dataSource.toString());

    this.enforceSameIPAuth = section.getBoolean("forceSameIPAuthentication", false);

    this.inventoryTampering = section.getBoolean("inventoryTampering", true);

    if (section.getBoolean("bungee.enabled", false))
        this.bungeePluginChannel = section.getString("bungee.channel", "MCAuthenticator");
    else this.bungeePluginChannel = null;

    this.messages = new HashMap<>();
    ConfigurationSection msgCfg = section.getConfigurationSection("messages");
    for (String key : msgCfg.getKeys(false)) {
        if (key.equals("prefix")) {
            this.prefix = color(msgCfg.getString(key));
        }
        this.messages.put(key, color(msgCfg.getString(key)));
    }
}
 
Example 20
Source File: NovaGroupImpl.java    From NovaGuilds with GNU General Public License v3.0 4 votes vote down vote up
/**
 * The constructor
 *
 * @param group group name
 */
public NovaGroupImpl(String group) {
	name = group;
	LoggerUtils.info("Loading group '" + name + "'...");

	//setting all values
	ConfigurationSection section = plugin.getConfig().getConfigurationSection("groups." + group);

	for(NovaGroup.Key<?> key : Key.values()) {
		String path = paths.get(key);

		if(!section.contains(path) && values.get(key) != null) {
			continue;
		}

		Object value = null;

		if(key.getType() == Double.class) {
			value = section.getDouble(path);
		}
		else if(key.getType() ==  Integer.class) {
			value = section.getInt(path);
		}
		else if(key.getType() == List.class) {
			value = ItemStackUtils.stringToItemStackList(section.getStringList(path));

			if(value == null) {
				value = new ArrayList<ItemStack>();
			}
		}
		else if(key.getType() == Schematic.class) {
			String schematicName = section.getString(path);
			if(schematicName != null && !schematicName.isEmpty()) {
				try {
					value = new SchematicImpl(schematicName);
				}
				catch(FileNotFoundException e) {
					LoggerUtils.error("Schematic not found: schematic/" + schematicName);
				}
			}
		}

		values.put(key, value);
	}

	int autoRegionWidth = get(Key.REGION_AUTOSIZE) * 2 + 1;
	if(autoRegionWidth > Config.REGION_MAXSIZE.getInt()) {
		values.put(Key.REGION_AUTOSIZE, Config.REGION_MAXSIZE.getInt() / 2 - 1);
		LoggerUtils.error("Group " + name + " has too big autoregion. Reset to " + get(Key.REGION_AUTOSIZE));
	}

	if(get(Key.REGION_AUTOSIZE) != 0 && autoRegionWidth < Config.REGION_MINSIZE.getInt()) {
		values.put(Key.REGION_AUTOSIZE, Config.REGION_MINSIZE.getInt() / 2);
		LoggerUtils.error("Group " + name + " has too small autoregion. Reset to " + get(Key.REGION_AUTOSIZE));
	}
}