/** * Saves a scoreboard to a configuration file. * * @param config * The configuration file. * @param scoreboard * The scoreboard. */ public void saveScoreboard(Configuration config, Scoreboard scoreboard) { // Save teams ConfigurationSection teamsSection = config.createSection("teams"); scoreboard.getTeams().forEach(team -> { ConfigurationSection teamSection = teamsSection.createSection(team.getName()); saveTeam(teamSection, team); }); // Save objectives ConfigurationSection objectivesSection = config.createSection("objectives"); scoreboard.getObjectives().forEach(objective -> { ConfigurationSection objectiveSection = objectivesSection.createSection(objective.getName()); objectiveSection.set("criteria", objective.getCriteria()); objectiveSection.set("display_name", objective.getDisplayName()); objectiveSection.set("display_slot", objective.getDisplaySlot().toString().toLowerCase()); }); // Save scores ConfigurationSection scoresSection = config.createSection("scores"); scoreboard.getEntries().forEach(playerName -> { ConfigurationSection playerSection = scoresSection.createSection(playerName); scoreboard.getScores(playerName) .forEach(score -> playerSection.set(score.getObjective().getName(), score.getScore())); }); }
/** * Creates a new map manager with a specified map rotation. */ @Inject MatchManager(Loggers loggers, @Named("pluginData") Path pluginDataFolder, Provider<Configuration> config, MapLibrary mapLibrary, MapLoader mapLoader, MapErrorTracker mapErrorTracker, FileRotationProviderFactory fileRotationProviderFactory, EventBus eventBus, MatchLoader matchLoader) throws MapNotFoundException { this.pluginDataFolder = pluginDataFolder; this.mapErrorTracker = mapErrorTracker; this.fileRotationProviderFactory = fileRotationProviderFactory; this.log = loggers.get(getClass()); this.config = config; this.mapLibrary = mapLibrary; this.mapLoader = mapLoader; this.eventBus = eventBus; this.matchLoader = matchLoader; }
@Inject QuotaConfig(Configuration root) { this.config = root.getConfigurationSection("match-quotas"); if(config == null) { quotas = new TreeSet<>(); } else { quotas = new TreeSet<>(Collections2.transform( config.getKeys(false), new Function<String, Entry>() { @Override public Entry apply(@Nullable String key) { return new Entry(config.getConfigurationSection(key)); } } )); } }
public Set<RotationProviderInfo> parse(MapLibrary mapLibrary, Path dataPath, Configuration config) { ConfigurationSection base = config.getConfigurationSection("rotation.providers.file"); if(base == null) return Collections.emptySet(); Set<RotationProviderInfo> providers = new HashSet<>(); for(String name : base.getKeys(false)) { ConfigurationSection provider = base.getConfigurationSection(name); Path rotationFile = Paths.get(provider.getString("path")); if(!rotationFile.isAbsolute()) rotationFile = dataPath.resolve(rotationFile); int priority = provider.getInt("priority", 0); if(Files.isRegularFile(rotationFile)) { providers.add(new RotationProviderInfo(new FileRotationProvider(mapLibrary, name, rotationFile, dataPath), name, priority)); } else if(minecraftService.getLocalServer().startup_visibility() == ServerDoc.Visibility.PUBLIC) { // This is not a perfect way to decide whether or not to throw an error, but it's the best we can do right now mapLibrary.getLogger().severe("Missing rotation file: " + rotationFile); } } return providers; }
public void loadConfig() { Configuration configuration = YamlConfiguration.loadConfiguration(configFile); ConfigurationSection bungeeSection; if (configuration.contains("bungee")){ bungeeSection = configuration.getConfigurationSection("bungee"); } else { getLogger().warning("The section 'bungee' in the configuration is not found, " + "defaults will be assumed. Delete the config file and restart to have a " + "clean valid configuration file."); bungeeSection = configuration.createSection("bungee"); } boolean serverSocketEnabled = configuration.getBoolean("server-socket", true); boolean serverPortAuto = configuration.getBoolean("port-automatic", true); int serverPort = configuration.getInt("port", 3112); String host = bungeeSection.getString("host"); int port = bungeeSection.getInt("port"); char[] password = bungeeSection.getString("password", "").toCharArray(); int heartbeatSeconds = bungeeSection.getInt("heartbeat-seconds", 30); int reconnectAttempts = bungeeSection.getInt("reconnect-attempts", 7); bungeeMasterSpigotConfig = new BungeeMasterSpigotConfig(serverSocketEnabled, serverPortAuto, serverPort, host, port, password, heartbeatSeconds, reconnectAttempts); }
private void checkConfigVersions(Configuration config, Path dataFolder) { if (config.getInt("config-version", 0) < TradeConfiguration.CURRENT_CONFIG_VERSION) { Path configSource = dataFolder.resolve(TradeConfiguration.DESTINATION_FILE_NAME); Path configTarget = dataFolder.resolve("config_old.yml"); try { Files.move(configSource, configTarget, StandardCopyOption.REPLACE_EXISTING); URL configResource = getClass().getResource(TradeConfiguration.CLASSPATH_RESOURCE_NAME); copyResource(configResource, configSource.toFile()); ConsoleCommandSender sender = Bukkit.getConsoleSender(); sender.sendMessage(ChatColor.RED + "Due to a SimpleTrading update your old configuration has been renamed"); sender.sendMessage(ChatColor.RED + "to config_old.yml and a new one has been generated. Make sure to"); sender.sendMessage(ChatColor.RED + "apply your old changes to the new config!"); } catch (IOException e) { getLogger().log(Level.SEVERE, "Could not create updated configuration due to an IOException", e); } } }
/** * Gets a configuration file from the jar file. * * @param path * Path in the jar file. * @return The configuration file. */ private Configuration getJarConfig(String path) { InputStream resource = getResource(path); if (resource == null) { // Not found return new YamlConfiguration(); } Reader reader = new InputStreamReader(resource, Charsets.UTF_8); Configuration config = YamlConfiguration.loadConfiguration(reader); try { resource.close(); } catch (IOException e) { getLogger().log(Level.SEVERE, "Failed to close stream", e); } return config; }
private Translator loadTranslations(String fileName) { File file = new File(getDataFolder(), fileName); Configuration config = YamlConfiguration.loadConfiguration(file); config.addDefaults(getJarConfig(Config.DEFAULT_TRANSLATIONS_FILE)); ConfigTranslator translator = new ConfigTranslator(config); if (translator.needsSave()) { getLogger().info("Saving translations"); try { translator.save(file); } catch (IOException e) { getLogger().log(Level.SEVERE, "Failed to save translation file", e); } } return translator; }
/** * Initialize mod config based on the configuration file * * @param config */ public ModConfig(Configuration config) { m_isInitialized = false; if (config == null) { m_blocks = null; m_mobs = null; m_modIdRegex = null; m_textureRes = 0; m_versionRegex = null; return; } m_name = config.getString("DisplayName", null); m_blocks = config.getConfigurationSection("Blocks"); m_mobs = config.getConfigurationSection("Mobs"); m_modIdRegex = config.getString("ModId", null); m_alternativeId = config.getString("ModIdAlternative", null); m_versionRegex = config.getString("Version", null); m_textureRes = config.getInt("TextureRes", 0); }
/** * Load palette from file * * @param file * @return */ public static Palette load(File file) { Configuration config = YamlConfiguration.loadConfiguration(file); String name = config.getString("name", null); BlockEntry[] blockEntries = parseBlocksSection(config); if (name == null) { MCPainterMain.log("* " + file.getName() + "...invalid file format, no name palette defined."); return null; } name = name.toLowerCase(); if (blockEntries == null || blockEntries.length < 2) { MCPainterMain.log("* " + name + "...invalid file format, minimum number of blocks in palette is 2."); return null; } MCPainterMain.log("* " + name + "..." + blockEntries.length + " blocks defined."); return new Palette(name, blockEntries); }
/** * Parse blocks section entry * * @param configuration * @return */ private static BlockEntry[] parseBlocksSection(Configuration configuration) { List<BlockEntry> blocks = new ArrayList(); for (String string : configuration.getStringList("blocks")) { try { BlockEntry entry = BlockEntry.parse(string); if (entry == null) { MCPainterMain.log("* Error parsing block entry: " + string); } else { blocks.add(entry); } } catch (Exception e) { MCPainterMain.log("* Error parsing block entry: " + string); } } return blocks.toArray(new BlockEntry[0]); }
public void load() { BukkitScheduler scheduler = plugin.getServer().getScheduler(); if (task != null) { task.cancel(); task = null; } ConfigurationSection arenaConfiguration = loadDataFile("arenas"); load(arenaConfiguration); ConfigurationSection arenaData = loadDataFile("data"); loadData(arenaData); plugin.reloadConfig(); Configuration config = plugin.getConfig(); pathTemplate = config.getString("path_template", pathTemplate); tickInterval = config.getInt("tick_interval", 40); task = scheduler.runTaskTimer(plugin, this, 1, tickInterval); }
@Override public boolean isSTBItem(ItemStack stack, Class<? extends BaseSTBItem> c) { if (stack == null || !stack.hasItemMeta()) { return false; } ItemMeta im = stack.getItemMeta(); if (im.hasLore()) { List<String> lore = im.getLore(); if (!lore.isEmpty() && lore.get(0).startsWith(LORE_PREFIX)) { if (c != null) { Configuration conf = getItemAttributes(stack); ReflectionDetails details = reflectionDetailsMap.get(conf.getString("*TYPE")); return details != null && c.isAssignableFrom(details.clazz); } else { return true; } } } return false; }
private Configuration getItemAttributes(ItemStack stack) { AttributeStorage storage = AttributeStorage.newTarget(stack, STB_ATTRIBUTE_ID); YamlConfiguration conf = new YamlConfiguration(); try { String s = storage.getData(""); if (s != null) { conf.loadFromString(s); if (Debugger.getInstance().getLevel() > 2) { Debugger.getInstance().debug(3, "get item attributes for " + STBUtil.describeItemStack(stack) + ":"); for (String k : conf.getKeys(false)) { Debugger.getInstance().debug(3, "- " + k + " = " + conf.get(k)); } } return conf; } else { throw new IllegalStateException("ItemStack " + stack + " has no STB attribute data!"); } } catch (InvalidConfigurationException e) { e.printStackTrace(); return new MemoryConfiguration(); } }
private RpChar loadCharacter(File playerFile) { OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(playerFile.getName().substring(0, playerFile.getName().length() - 4))); RpChar character = new RpChar(player,plugin); Configuration playerConfig = YamlConfiguration.loadConfiguration(playerFile); for (Field field : plugin.getCharacterManager().getFields().values()) { if (!playerConfig.isSet(field.getName())) continue; character.setField(field.getName(), playerConfig.getString(field.getName())); } return character; }
@Override public void inflateUnsafe(Configuration config, Object[] args) throws ParseException { List<String> lines = Lists.newArrayList(); ConfigurationSection layoutSection = config.getConfigurationSection("layout"); for (int i = 1; i <= SignLayout.LINE_COUNT; i++) { String line = layoutSection.getString(String.valueOf(i)); lines.add(line); } layout = new SignLayout(lines); if (config.contains("options")) { options = config.getConfigurationSection("options"); } }
@Override public void inflate(Configuration config, Object... args) { Validate.isTrue(args.length > 0, "args.length must be greater than 0"); Validate.isTrue(args[0] instanceof File, "args[0] must be an instance of " + File.class.getCanonicalName()); File baseDir = (File) args[0]; ConfigurationSection moduleSection = config.getConfigurationSection("database-modules"); this.statisticsEnabled = moduleSection.getBoolean("statistics.enabled"); this.maxStatisticCacheSize = moduleSection.getInt("statistics.max-cache-size", DEFAULT_MAX_CACHE_SIZE); this.connections = Lists.newArrayList(); ConfigurationSection connectionsSection = config.getConfigurationSection("persistence-connection"); for (String key : connectionsSection.getKeys(false)) { connections.add(new DatabaseConnection(connectionsSection.getConfigurationSection(key), baseDir)); } }
private void checkConfigVersions(Configuration config, Path dataFolder) { if (config.getInt("config-version") < DefaultConfig.CURRENT_CONFIG_VERSION) { Path configSource = dataFolder.resolve(ConfigType.DEFAULT_CONFIG.getDestinationFileName()); Path configTarget = dataFolder.resolve("config_old.yml"); try { Files.move(configSource, configTarget, StandardCopyOption.REPLACE_EXISTING); URL configResource = getClass().getResource(ConfigType.DEFAULT_CONFIG.getClasspathResourceName()); copyResource(configResource, configSource.toFile()); ConsoleCommandSender sender = Bukkit.getConsoleSender(); sender.sendMessage(ChatColor.RED + "Due to a HeavySpleef update your old configuration has been renamed"); sender.sendMessage(ChatColor.RED + "to config_old.yml and a new one has been generated. Make sure to"); sender.sendMessage(ChatColor.RED + "apply your old changes to the new config"); } catch (IOException e) { getLogger().log(Level.SEVERE, "Could not create updated configuration due to an IOException", e); } } }
@Override public final void inflateUnsafe(Configuration config, Object[] args) throws ParseException { ConfigurationSection layoutSection = config.getConfigurationSection("layout"); String title; List<String> lore; if (layoutSection != null) { title = layoutSection.getString("title", DEFAULT_TITLE); lore = layoutSection.getStringList("lore"); if (lore == null || lore.isEmpty()) { lore = DEFAULT_LORE; } } else { title = DEFAULT_TITLE; lore = DEFAULT_LORE; } layout = new InventoryEntryLayout(title, lore); }
private boolean checkCopyConfig() throws IOException { File file = new File(getDataFolder(), CONFIG_FILE_NAME); if (file.exists()) { Configuration config = YamlConfiguration.loadConfiguration(file); int version = config.getInt("config-version"); if (version < BungeemodeConfig.CURRENT_CONFIG_VERSION) { Path dataFolderPath = getDataFolder().toPath(); Files.move(file.toPath(), dataFolderPath.resolve("config_old.yml"), StandardCopyOption.REPLACE_EXISTING); return true; } } else { return true; } return false; }
public static ConcurrentSkipListMap<String, String> loadMapFromConfig(Configuration config ,String sectionKeyName) { if (config == null) { return null; } if (sectionKeyName == null) { return null; } ConfigurationSection configSection = config.getConfigurationSection(sectionKeyName); if (configSection == null) { return null; } ConcurrentSkipListMap<String, String> resultMap =new ConcurrentSkipListMap<String, String>(); Map<String, Object> loadMap = configSection.getValues(false); for (Map.Entry<String, Object> loadMapEntry : loadMap.entrySet()) { resultMap.put(loadMapEntry.getKey(), (String)loadMapEntry.getValue()); } return resultMap; }
private static Configuration loadLanguageFile(final String locale) throws Exception{ final File langDir = getLanguagesDir(); File file = new File(langDir, locale + ".yml"); // check file available if (file == null || !file.isFile() || !file.canRead()){ ActionLog.getInstance().warning("Unknown language file: " + locale); return null; } YamlConfiguration conf = YamlConfiguration.loadConfiguration(file); // check all messages available if (fallbackMessages != null && conf.getKeys(true).size() != fallbackMessages.getKeys(true).size()){ // collect missing message keys for (String key : fallbackMessages.getKeys(true)){ if (!conf.contains(key) && !fallbackMessages.isConfigurationSection(key)){ conf.set(key, fallbackMessages.get(key)); ActionLog.getInstance().warning("Missing message key on " + locale + ".yml: " + key); } } } return conf; }
/** * Loads the CommandSets. * * @param config * @return */ public static Map<String, CommandSet>[] loadSets(Configuration config) { Map<String, CommandSet> sets = new HashMap<String, CommandSet>(); Map<String, CommandSet> commands = new HashMap<String, CommandSet>(); ConfigurationSection setsSection = config.getConfigurationSection("sets"); if (setsSection != null) { for (String key : setsSection.getKeys(false)) { // Get the set section ConfigurationSection setSection = setsSection.getConfigurationSection(key); CommandSet set = loadSet(key, setSection, commands); if (set == null) { log(Level.WARNING, "Invalid set configuration for set '" + key + "'. Skipping."); continue; } sets.put(key, set); // Add the commands to our mapping for (String cmd : set.getCommands()) { commands.put(cmd, set); } } } return new Map[]{sets, commands}; }
/** * Loads all CommandSetGroups. * * @param config * @param sets * @return */ public static Map<String, CommandSetGroup> loadSetGroups(Configuration config, Map<String, CommandSet> sets) { Map<String, CommandSetGroup> groups = new HashMap<String, CommandSetGroup>(); ConfigurationSection groupsSection = config.getConfigurationSection("groups"); if (groupsSection != null) { for (String key : groupsSection.getKeys(false)) { // Get the group section ConfigurationSection groupSection = groupsSection.getConfigurationSection(key); CommandSetGroup group = loadSetGroup(key, groupSection, sets); if (group == null) { log(Level.WARNING, "Invalid group configuration for group '" + key + "'. Skipping."); continue; } groups.put(key, group); } } if (!groups.containsKey("default")) { log(Level.INFO, "There isn't a default group; creating one with no settings."); groups.put("default", new CommandSetGroup("default", new HashMap<CommandSet, Integer>(), new HashMap<CommandSet, Integer>())); } return groups; }
public static Configuration getConfiguration() { PGM pgm = PGM.get(); if(pgm != null) { return pgm.getConfig(); } else { return new YamlConfiguration(); } }
public RotationManager(Logger logger, Configuration config, PGMMap defaultMap, Collection<RotationProviderInfo> providers) { this.logger = ClassLogger.get(checkNotNull(logger, "logger"), getClass()); this.config = config; this.providers = Collections.synchronizedSortedSet(Sets.newTreeSet(providers)); load(defaultMap); }
public I18n(Locale locale, Configuration configuration) { this(locale, new HashMap<String, String>(), null); for (String key : configuration.getKeys(true)) { Object obj = configuration.get(key); if (obj instanceof CharSequence) { this.map.put(key, obj.toString()); } } }
@Override public void onEnable() { this.getCommand("nbtproxy").setExecutor(new InfoCommand(this.getDescription())); this.saveDefaultConfig(); Configuration config = getConfig(); int enabledCommands = 0; for (Permissions perm : Permissions.values()) { if (config.getBoolean("enabled-commands." + perm.CONFIG_KEY)) enabledCommands |= perm.PERM_ENABLED_FLAG; } this.getCommand("nbt").setExecutor(new NBTCommand(enabledCommands)); }
void loadFiles() { // Create config file if not exists File cFile = new File(getDataFolder(), "config.yml"); if (!cFile.exists()) { if (cFile.getParentFile().mkdirs()) { createConfigFile(getResource("config.yml"), cFile); logger.log(Level.INFO, "Configuration file created!"); } } // Check config for right parameters existance this.reloadConfig(); Configuration config = this.getConfig(); UseQuickPortals = Boolean.parseBoolean(config.getString("UseQuickPortals")); config.set("UseQuickPortals", UseQuickPortals); UseMetrics = Boolean.parseBoolean(config.getString("UseMetrics")); config.set("UseMetrics", UseMetrics); this.saveConfig(); logger.log(Level.INFO, "Configuration file reloaded! " + "Using quick portals: " + UseQuickPortals + "; " + "Using metrics: " + UseMetrics); // Now let's check portal data. File pFile = new File(getDataFolder(), "portals.yml"); if (!pFile.exists()) { if (pFile.getParentFile().mkdirs()) { createConfigFile(getResource("portals.yml"), pFile); logger.log(Level.INFO, "Portals file created!"); } } portalsFile = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "portals.yml")); logger.log(Level.INFO, "Portal data file loaded!"); }
@Override protected String buildHeader() { String header = options().header(); if (options().copyHeader()) { Configuration def = getDefaults(); if ((def != null) && (def instanceof FileConfiguration)) { FileConfiguration filedefaults = (FileConfiguration) def; String defaultsHeader = filedefaults.buildHeader(); if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { return defaultsHeader; } } } if (header == null) { return ""; } StringBuilder builder = new StringBuilder(); String[] lines = header.split("\r?\n", -1); boolean startedHeader = false; for (int i = lines.length - 1; i >= 0; i--) { builder.insert(0, "\n"); if ((startedHeader) || (lines[i].length() != 0)) { builder.insert(0, lines[i]); builder.insert(0, COMMENT_PREFIX); startedHeader = true; } } return builder.toString(); }
public StoreModule(final Configuration configuration, final ExtendedDatabaseHandler database, final Locale locale, final PermissionHandler permission, final LastViewed lastViewed, final PlayerMessages playerMessages, final PlayerReport playerReport) { if (log.isDebugEnabled()) { log.info("Initializing service store..."); } configurationStore = new Store<Configuration>(configuration); databaseStore = new Store<ExtendedDatabaseHandler>(database); localeStore = new Store<Locale>(locale); permissionStore = new Store<PermissionHandler>(permission); lastViewedStore = new Store<LastViewed>(lastViewed); playerMessagesStore = new Store<PlayerMessages>(playerMessages); playerReportStore = new Store<PlayerReport>(playerReport); }
public <T> T get(final Entry<T> entry) { final Configuration configuration = getStore().getConfigurationStore().get(); final Object value = configuration.get(entry.getPath(), entry.getDefault()); if (value == null) { return entry.getDefault(); } else if (entry.getDefault().getClass().equals(value.getClass())) { return (T) entry.getDefault().getClass().cast(value); } else { log.warn(String.format("Configuration entry [%s] of class [%s] did not match the returned class of [%s]!", entry.getPath(), entry.getDefault().getClass().getSimpleName(), value.getClass().getSimpleName())); log.warn(String.format("To prevent errors for configuration entry [%s] the default value [%s] will be returned!", entry.getPath(), entry.getDefault())); return entry.getDefault(); } }
public MapManager(Annihilation plugin, MapLoader loader, Configuration config) { mapLoader = loader; for (String s : config.getKeys(false)) { if (!s.equalsIgnoreCase("lobby")) maps.add(s); } WorldCreator wc = new WorldCreator("lobby"); wc.generator(new VoidGenerator()); Bukkit.createWorld(wc); lobbySpawn = parseLocation(config.getString("lobby.spawn")); }
private void loadConfig(Configuration config) { items = new ArrayList<ShopItem>(); List<String> list = config.getStringList(name.toLowerCase()); for (String entry : list) { if (entry.equalsIgnoreCase("nextline")) { int end = 9 * (int) Math.ceil(items.size() / 9.0); for (int i = items.size(); i < end; i++) items.add(null); } else { String[] params = entry.split(","); if (params.length >= 3) { Material type = Material.getMaterial(params[0]); int qty = Integer.valueOf(params[1]); int price = Integer.valueOf(params[2]); ShopItem item = new ShopItem(type, qty, price); if (params.length >= 4) { String itemName = params[3].replace("\"", ""); // Longest method name ever. Great job bukkit team. item.setName(ChatColor.translateAlternateColorCodes( '&', itemName)); } items.add(item); } } } }
/** * Initialize the mod configuration * * @param modsProvider * @param file * @return */ private static ModConfig initializeConfig(ModsProvider modsProvider, DataFile file) { Configuration config = file.getConfig(); ModConfig result = new ModConfig(config); boolean statues = result.getMobs() != null; boolean blocks = result.getBlocks() != null; boolean valid = statues || blocks; if (!result.isValid() && !valid) { MCPainterMain.log("* " + file.getName() + "...bad file format."); return null; } String text = buildAssetsText(statues, blocks); if (result.isValid()) { Mod mod = modsProvider.get(result.getModIdRegex(), result.getVersionRegex()); if (mod == null) { MCPainterMain.log("* " + file.getName() + "...mod not available." + (text.length() > 0 ? (" Using " + text) : "") + "."); } else { result.setMod(mod); MCPainterMain.log("* " + file.getName() + " (" + result.getName() + ") initialized texture" + (text.length() > 0 ? (", " + text) : "") + "."); } } else { MCPainterMain.log("* " + file.getName() + " (" + result.getName() + ") " + text + " definition initialized."); } return result; }