|
| 1 | +package net.md_5.bungee.api.plugin; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.io.OutputStream; |
| 7 | +import java.util.logging.Level; |
| 8 | +import javax.inject.Inject; |
| 9 | + |
| 10 | +import com.google.common.io.ByteStreams; |
| 11 | +import com.google.common.io.Files; |
| 12 | +import net.md_5.bungee.config.Configuration; |
| 13 | +import net.md_5.bungee.config.ConfigurationProvider; |
| 14 | +import net.md_5.bungee.config.YamlConfiguration; |
| 15 | + |
| 16 | +public class PluginConfigurationLoader { |
| 17 | + private static final String CONFIG_FILENAME = "config.yml"; |
| 18 | + |
| 19 | + private final Plugin plugin; |
| 20 | + |
| 21 | + @Inject PluginConfigurationLoader(Plugin plugin) { |
| 22 | + this.plugin = plugin; |
| 23 | + } |
| 24 | + |
| 25 | + public Configuration loadConfig() { |
| 26 | + final String pluginName = plugin.getDescription().getName(); |
| 27 | + try { |
| 28 | + File configFile = new File(plugin.getDataFolder(), CONFIG_FILENAME); |
| 29 | + |
| 30 | + if(!configFile.exists()) { |
| 31 | + InputStream resourceStream = plugin.getResourceAsStream(CONFIG_FILENAME); |
| 32 | + if(resourceStream != null) { |
| 33 | + plugin.getLogger().info(String.format("[{0}] No config file detected. Copying default config from jar", pluginName)); |
| 34 | + |
| 35 | + if(!plugin.getDataFolder().mkdirs()) { |
| 36 | + throw new IOException("Failed to create plugin data folder"); |
| 37 | + } |
| 38 | + |
| 39 | + try(OutputStream os = Files.asByteSink(configFile).openStream()) { |
| 40 | + ByteStreams.copy(resourceStream, os); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); |
| 46 | + } catch (IOException e) { |
| 47 | + plugin.getLogger().log(Level.SEVERE, String.format("[{0}] Failed to read configuration file: {1}", pluginName, e.getMessage()), e); |
| 48 | + return new Configuration(); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments