下面列出了怎么用org.bukkit.configuration.InvalidConfigurationException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* creates a config file in the specified folder
*
* @param folder The name of the folder
* @param file The name of the file
*/
public static void loadConfig(String folder, String file) {
File customConfigFile = new File(MineTinker.getPlugin().getDataFolder(), folder + file);
FileConfiguration fileConfiguration = configs.getOrDefault(file, new YamlConfiguration());
configsFolder.put(fileConfiguration, customConfigFile);
configs.put(file, fileConfiguration);
if (customConfigFile.exists()) {
try {
fileConfiguration.load(customConfigFile);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
/**
* Loads this {@link FileConfiguration} from the specified reader.
* <p>
* All the values contained within this configuration will be removed,
* leaving only settings and defaults, and the new values will be loaded
* from the given stream.
*
* @param reader the reader to load from
* @throws IOException thrown when underlying reader throws an IOException
* @throws InvalidConfigurationException thrown when the reader does not
* represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null
*/
public void load(Reader reader) throws IOException, InvalidConfigurationException {
BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
try {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
} finally {
input.close();
}
loadFromString(builder.toString());
}
public static void init(File configFile) {
CONFIG_FILE = configFile;
config = new YamlConfiguration();
try {
config.load(CONFIG_FILE);
} catch (IOException ignored) {
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Could not load kettle.yml, please correct your syntax errors", ex);
throw Throwables.propagate(ex);
}
config.options().header(HEADER);
config.options().copyDefaults(true);
verbose = getBoolean("verbose", false);
commands = new HashMap<>();
commands.put("kettle", new KettleCommand("kettle"));
version = getInt("config-version", 1);
set("config-version", 1);
readConfig(KettleConfig.class, null);
}
public static void init(File configFile) {
CONFIG_FILE = configFile;
config = new YamlConfiguration();
try {
config.load(CONFIG_FILE);
} catch (IOException ignored) {
} catch (InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Could not load spigot.yml, please correct your syntax errors", ex);
throw Throwables.propagate(ex);
}
config.options().header(HEADER);
config.options().copyDefaults(true);
commands = new HashMap<>();
version = getInt("config-version", 11);
set("config-version", 11);
readConfig(SpigotConfig.class, null);
}
@Override
public void load(Reader reader) throws IOException, InvalidConfigurationException {
StringBuilder builder = new StringBuilder();
String line;
try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) {
int index = 0;
while ((line = input.readLine()) != null) {
if (line.startsWith("#") || line.trim().isEmpty()) {
comments.put(index, line);
}
builder.append(line);
builder.append(System.lineSeparator());
index++;
}
}
this.loadFromString(builder.toString());
}
public static YamlConfiguration loadConfiguration(File file) {
Validate.notNull(file, "File cannot be null");
YamlConfiguration config = new CommentYamlConfiguration();
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
config.load(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException | InvalidConfigurationException var4) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, var4);
}
return config;
}
/**
* Deserialize the inventory from JSON
* @param jsons the JSON string
* @param title the name of the inventory
* @return the deserialized string
* @throws InvalidConfigurationException
*/
public static Inventory deserializeInventory(String jsons, String title, SettingsManager settingsManager) throws InvalidConfigurationException {
try {
JsonConfiguration json = new JsonConfiguration();
json.loadFromString(jsons);
int size = json.getInt("size", 54);
title = StringUtils.color(settingsManager.getProperty(GuildVaultSettings.VAULT_NAME));
Inventory inventory = Bukkit.createInventory(null, size, title);
Map<String, Object> items = json.getConfigurationSection("items").getValues(false);
for (Map.Entry<String, Object> item : items.entrySet()) {
ItemStack itemstack = (ItemStack) item.getValue();
int idx = Integer.parseInt(item.getKey());
inventory.setItem(idx, itemstack);
}
return inventory;
} catch (InvalidConfigurationException e) {
return null;
}
}
private void loadScenarioOptions(Scenario scenario, ScenarioListener listener) throws ReflectiveOperationException, IOException, InvalidConfigurationException{
List<Field> optionFields = NMSUtils.getAnnotatedFields(listener.getClass(), Option.class);
if (optionFields.isEmpty()){
return;
}
YamlFile cfg = FileUtils.saveResourceIfNotAvailable("scenarios.yml");
for (Field field : optionFields){
Option option = field.getAnnotation(Option.class);
String key = option.key().isEmpty() ? field.getName() : option.key();
Object value = cfg.get(scenario.name().toLowerCase() + "." + key, field.get(listener));
field.set(listener, value);
}
if (cfg.addedDefaultValues()){
cfg.saveWithComments();
}
}
public void loadFile(){
YamlFile cfg;
try{
cfg = FileUtils.saveResourceIfNotAvailable("scoreboard.yml");
}catch (InvalidConfigurationException ex){
ex.printStackTrace();
// Set default values.
waiting = new ArrayList<>();
playing = new ArrayList<>();
deathmatch = new ArrayList<>();
spectating = new ArrayList<>();
title = ChatColor.RED + "Error";
return;
}
waiting = getOpsideDownLines(cfg.getStringList("waiting"));
playing = getOpsideDownLines(cfg.getStringList("playing"));
deathmatch = getOpsideDownLines(cfg.getStringList("deathmatch"));
spectating = getOpsideDownLines(cfg.getStringList("spectating"));
title = ChatColor.translateAlternateColorCodes('&', cfg.getString("title", ""));
}
public final void reloadConfig(String fileName) {
try {
File dataFolder = getDataFolder();
File file = new File(dataFolder, fileName);
File realFile = file.getCanonicalFile();
String realName = realFile.getName();
YamlConfiguration config = new YamlConfiguration();
config.load(realFile);
InputStream jarStream = getResource(fileName);
if(jarStream != null) {
InputStreamReader reader = new InputStreamReader(jarStream, StandardCharsets.UTF_8);
YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(reader);
config.setDefaults(defaultConfig);
}
fileNameToConfigMap.put(realName, config);
} catch(IOException | InvalidConfigurationException ex) {
Logger logger = getLogger();
logger.log(Level.SEVERE, "An error ocurred while loading a config named '" + fileName + "'.", ex);
}
}
@Override
public void initialize() throws InvalidConfigurationException {
if (!config.contains(MULTIPLIER_KEY)) {
config.set(MULTIPLIER_KEY, DEFAULT_MULTIPLIER);
}
if (!config.isDouble(MULTIPLIER_KEY) && !config.isInt(MULTIPLIER_KEY)) {
throw new InvalidConfigurationException(
"Invalid value at " + config.getCurrentPath() + ".multiplier (" + config.get(MULTIPLIER_KEY) + ")"
);
}
multiplier = config.getDouble(MULTIPLIER_KEY);
super.initialize();
}
@Override
public void initialize() throws InvalidConfigurationException {
if (!config.contains(DROP_COUNT_LOWER_KEY)) {
config.set(DROP_COUNT_LOWER_KEY, DEFAULT_LOWER_RANGE);
}
if (!config.contains(DROP_COUNT_HIGHER_KEY)) {
config.set(DROP_COUNT_HIGHER_KEY, DEFAULT_HIGHER_RANGE);
}
lower = config.getInt(DROP_COUNT_LOWER_KEY);
higher = config.getInt(DROP_COUNT_HIGHER_KEY);
Preconditions.checkArgument(lower >= 0, "Min value must be >= 0");
Preconditions.checkArgument(higher >= 0, "Max value must be >= 0");
Preconditions.checkArgument(higher >= lower, "Max but be >= min");
super.initialize();
}
@Override
public void initialize() throws InvalidConfigurationException {
if (!config.contains(FORMAT_KEY)) {
config.set(FORMAT_KEY, "&c{{original}} at {{player.world}},{{player.blockCoords}}");
}
if (!config.contains(FORMAT_EXPLANATION_KEY)) {
config.set(FORMAT_EXPLANATION_KEY, "<message> at <coords>");
}
final String format = config.getString(FORMAT_KEY);
formatExplanation = config.getString(FORMAT_EXPLANATION_KEY);
final MustacheFactory mf = new DefaultMustacheFactory();
try {
template = mf.compile(
new StringReader(ChatColor.translateAlternateColorCodes('&', format)),
"death-message"
);
} catch (Exception ex) {
throw new InvalidConfigurationException("Error parsing death message template", ex);
}
super.initialize();
}
@Override
public void initialize() throws InvalidConfigurationException {
if (!config.contains(DROP_CHANCE_KEY)) {
config.set(DROP_CHANCE_KEY, DEFAULT_DROP_CHANCE);
}
if (!config.isDouble(DROP_CHANCE_KEY) && !config.isInt(DROP_CHANCE_KEY)) {
throw new InvalidConfigurationException(
"Invalid value at " + config.getCurrentPath() + ".drop chance (" + config.get(DROP_CHANCE_KEY)
);
}
dropRate = config.getDouble(DROP_CHANCE_KEY) / PERCENT_MULTIPLIER;
super.initialize();
}
@Override
public void load(File file) throws IOException, InvalidConfigurationException {
this.file = file;
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
fis.close();
isr.close();
br.close();
loadFromString(sb.toString());
}
@Test
public void testTranslations() throws NullPointerException, InvalidConfigurationException, IOException {
File langDir = new File(resourcesDirectory, "/lang");
if(langDir.isDirectory()) {
File[] list = langDir.listFiles();
if(list != null) {
for(File lang : list) {
try {
Lang.loadConfiguration(lang);
}
catch(NullPointerException e) {
throw new InvalidConfigurationException("Invalid YAML file (" + lang.getPath() + ")");
}
}
}
}
else {
throw new FileNotFoundException("Lang dir does not exist.");
}
}
private static void loadConfigFiles() throws FileNotFoundException, IOException, InvalidConfigurationException {
townConfig = loadCivConfig("town.yml");
civConfig = loadCivConfig("civ.yml");
cultureConfig = loadCivConfig("culture.yml");
structureConfig = loadCivConfig("structures.yml");
techsConfig = loadCivConfig("techs.yml");
goodsConfig = loadCivConfig("goods.yml");
buffConfig = loadCivConfig("buffs.yml");
governmentConfig = loadCivConfig("governments.yml");
warConfig = loadCivConfig("war.yml");
wonderConfig = loadCivConfig("wonders.yml");
unitConfig = loadCivConfig("units.yml");
espionageConfig = loadCivConfig("espionage.yml");
scoreConfig = loadCivConfig("score.yml");
perkConfig = loadCivConfig("perks.yml");
enchantConfig = loadCivConfig("enchantments.yml");
campConfig = loadCivConfig("camp.yml");
marketConfig = loadCivConfig("market.yml");
happinessConfig = loadCivConfig("happiness.yml");
materialsConfig = loadCivConfig("materials.yml");
randomEventsConfig = loadCivConfig("randomevents.yml");
nocheatConfig = loadCivConfig("nocheat.yml");
arenaConfig = loadCivConfig("arena.yml");
fishingConfig = loadCivConfig("fishing.yml");
}
public void load() throws IOException, InvalidConfigurationException {
if (!file.isFile()) {
if (plugin.getResource(file.getName()) != null) {
plugin.saveResource(file.getName(), false);
} else {
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
}
// To reset all the values when loading
for (String section : this.getKeys(false)) {
set(section, null);
}
load(file);
}
/**
* Gets the YAML file configuration from the disk while loading it
* explicit with UTF-8. This allows umlauts and other UTF-8 characters
* for all Bukkit versions.
* <p>
* Bukkit add also this feature since
* https://github.com/Bukkit/Bukkit/commit/24883a61704f78a952e948c429f63c4a2ab39912
* To be allow the same feature for all Bukkit version, this method was
* created.
*
* @return the loaded file configuration
*/
public FileConfiguration getConfigFromDisk() {
Path file = dataFolder.resolve(FILE_NAME);
YamlConfiguration newConf = new YamlConfiguration();
newConf.setDefaults(getDefaults());
try {
//UTF-8 should be available on all java running systems
List<String> lines = Files.readAllLines(file);
load(lines, newConf);
} catch (InvalidConfigurationException | IOException ex) {
logger.error("Couldn't load the configuration", ex);
}
return newConf;
}
public BukkitTranslateContainer(String key, Plugin plugin, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
InputStream in = plugin.getResource("languages/language_" + key + ".yml");
if (in != null) {
try {
config.load(new InputStreamReader(in, StandardCharsets.UTF_8));
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
public BukkitTranslateContainer(String key, File file, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
if (file.exists()) {
try {
config.load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
public BukkitTranslateContainer(String key, InputStreamReader reader, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
try {
config.load(reader);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
/**
* Empties the queue of messages a player has and sends them to the player.
*
* @param p The player to message
* @return True if success, False if the player is offline or null
*/
public static boolean flush(@NotNull OfflinePlayer p) {
Player player = p.getPlayer();
if (player != null) {
UUID pName = p.getUniqueId();
LinkedList<String> msgs = player_messages.get(pName);
if (msgs != null) {
for (String msg : msgs) {
if (p.getPlayer() != null) {
Util.debugLog("Accepted the msg for player " + p.getName() + " : " + msg);
String[] msgData = msg.split("##########");
try {
ItemStack data = Util.deserialize(msgData[1]);
if (data == null) {
throw new InvalidConfigurationException();
}
sendItemholochat(player, msgData[0], data, msgData[2]);
} catch (InvalidConfigurationException e) {
MsgUtil.sendMessage(p.getPlayer(), msgData[0] + msgData[1] + msgData[2]);
} catch (ArrayIndexOutOfBoundsException e2) {
MsgUtil.sendMessage(p.getPlayer(), msg);
}
}
}
plugin.getDatabaseHelper().cleanMessageForPlayer(pName);
msgs.clear();
return true;
}
}
return false;
}
/**
* @param player The name of the player to message
* @param message The message to send them Sends the given player a message if they're online.
* Else, if they're not online, queues it for them in the database.
* @param isUnlimited The shop is or unlimited
*/
public static void send(@NotNull UUID player, @NotNull String message, boolean isUnlimited) {
if (plugin.getConfig().getBoolean("shop.ignore-unlimited-shop-messages") && isUnlimited) {
return; // Ignore unlimited shops messages.
}
Util.debugLog(message);
String[] msgData = message.split("##########");
OfflinePlayer p = Bukkit.getOfflinePlayer(player);
if (!p.isOnline()) {
LinkedList<String> msgs = player_messages.get(player);
if (msgs == null) {
msgs = new LinkedList<>();
}
player_messages.put(player, msgs);
msgs.add(message);
plugin.getDatabaseHelper().sendMessage(player, message, System.currentTimeMillis());
} else {
if (p.getPlayer() != null) {
try {
sendItemholochat(p.getPlayer(), msgData[0], Objects.requireNonNull(Util.deserialize(msgData[1])), msgData[2]);
} catch (InvalidConfigurationException e) {
Util.debugLog("Unknown error, send by plain text.");
MsgUtil.sendMessage(p.getPlayer(),msgData[0] + msgData[1] + msgData[2]);
} catch (ArrayIndexOutOfBoundsException e2) {
try {
sendItemholochat(p.getPlayer(), msgData[0], Objects.requireNonNull(Util.deserialize(msgData[1])), "");
} catch (Exception any) {
// Normal msg
MsgUtil.sendMessage(p.getPlayer(),message);
}
}
}
}
}
private @Nullable ItemStack deserializeItem(@NotNull String itemConfig) {
try {
return Util.deserialize(itemConfig);
} catch (InvalidConfigurationException e) {
e.printStackTrace();
plugin
.getLogger()
.warning(
"Failed load shop data, because target config can't deserialize the ItemStack.");
Util.debugLog("Failed to load data to the ItemStack: " + itemConfig);
return null;
}
}
@NotNull
public static JSONConfiguration loadConfiguration(@NotNull File file) {
final JSONConfiguration config = new JSONConfiguration();
try {
config.load(file);
} catch (FileNotFoundException ignored) {
// ignored...
} catch (IOException | InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex);
}
return config;
}
@NotNull
public static JSONConfiguration loadConfiguration(@NotNull Reader reader) {
final JSONConfiguration config = new JSONConfiguration();
try {
config.load(reader);
} catch (IOException | InvalidConfigurationException ex) {
Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex);
}
return config;
}
public BukkitTranslateContainer(String key, Plugin plugin, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
InputStream in = plugin.getResource("languages/language_" + key + ".yml");
if (in != null) {
try {
config.load(new InputStreamReader(in, StandardCharsets.UTF_8));
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
public BukkitTranslateContainer(String key, File file, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
if (file.exists()) {
try {
config.load(file);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
public BukkitTranslateContainer(String key, InputStreamReader reader, ITranslateContainer fallback) {
this.key = key;
this.fallback = fallback;
try {
config.load(reader);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}