ninja.leaping.configurate.loader.ConfigurationLoader Java Examples

The following examples show how to use ninja.leaping.configurate.loader.ConfigurationLoader. 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: ConfigCompleter.java    From UltimateCore with MIT License 6 votes vote down vote up
/**
     * This method completes a datafile.
     * Any fields that are in the asset provided but not in the datafile will be set in the datafile.
     *
     * @param file  The file to complete
     * @param asset The asset with the default values
     * @return Whether anything was added to the file
     */
    public static boolean complete(RawConfig file, Asset asset) {
        try {
            ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setURL(asset.getUrl()).build();
            CommentedConfigurationNode assetnode = loader.load();
            CommentedConfigurationNode sourcenode = file.get();

//            if (complete(assetnode, sourcenode)) {
//                file.save(assetnode);
//                return true;
//            }
            return false;
        } catch (Exception ex) {
            ErrorLogger.log(ex, "Config completion failed for " + file + " / " + asset);
            return false;
        }
    }
 
Example #2
Source File: ConfigLoader.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
public static void loadConfig(NuVotifier pl) {
    if (!pl.getConfigDir().exists()) {
        if (!pl.getConfigDir().mkdirs()) {
            throw new RuntimeException("Unable to create the plugin data folder " + pl.getConfigDir());
        }
    }
    try {
        File config = new File(pl.getConfigDir(), "config.yml");
        if (!config.exists() && !config.createNewFile()) {
            throw new IOException("Unable to create the config file at " + config);
        }
        ConfigurationLoader loader = YAMLConfigurationLoader.builder().setFile(config).build();
        ConfigurationNode configNode = loader.load(ConfigurationOptions.defaults().setShouldCopyDefaults(true));
        spongeConfig = configNode.getValue(TypeToken.of(SpongeConfig.class), new SpongeConfig());
        loader.save(configNode);
    } catch (Exception e) {
        pl.getLogger().error("Could not load config.", e);
    }
}
 
Example #3
Source File: ConfigurationFileUtil.java    From AntiVPN with MIT License 5 votes vote down vote up
public static Configuration getConfig(Object plugin, String resourcePath, File fileOnDisk) throws IOException {
    File parentDir = fileOnDisk.getParentFile();
    if (parentDir.exists() && !parentDir.isDirectory()) {
        Files.delete(parentDir.toPath());
    }
    if (!parentDir.exists()) {
        if (!parentDir.mkdirs()) {
            throw new IOException("Could not create parent directory structure.");
        }
    }
    if (fileOnDisk.exists() && fileOnDisk.isDirectory()) {
        Files.delete(fileOnDisk.toPath());
    }

    if (!fileOnDisk.exists()) {
        try (InputStreamReader reader = new InputStreamReader(plugin.getClass().getClassLoader().getResourceAsStream(resourcePath));
             BufferedReader in = new BufferedReader(reader);
             FileWriter writer = new FileWriter(fileOnDisk);
             BufferedWriter out = new BufferedWriter(writer)) {
            String line;
            while ((line = in.readLine()) != null) {
                out.write(line + System.lineSeparator());
            }
        }
    }

    ConfigurationLoader<ConfigurationNode> loader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setFile(fileOnDisk).build();
    ConfigurationNode root = loader.load(ConfigurationOptions.defaults().setHeader("Comments are gone because update :(. Click here for new config + comments: https://forums.velocitypowered.com/t/anti-vpn-get-the-best-save-money-on-overpriced-plugins-and-block-vpn-users/207"));
    Configuration config = new Configuration(root);
    ConfigurationVersionUtil.conformVersion(loader, config, fileOnDisk);

    return config;
}
 
Example #4
Source File: ConfigurateConfigAdapter.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void reload() {
    ConfigurationLoader<? extends ConfigurationNode> loader = createLoader(this.path);
    try {
        this.root = loader.load();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: TomlLoader.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ConfigurationLoader<? extends ConfigurationNode> loader(Path path) {
    return TOMLConfigurationLoader.builder()
            .setKeyIndent(2)
            .setTableIndent(2)
            .setSource(() -> Files.newBufferedReader(path, StandardCharsets.UTF_8))
            .setSink(() -> Files.newBufferedWriter(path, StandardCharsets.UTF_8))
            .build();
}
 
Example #6
Source File: YamlLoader.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ConfigurationLoader<? extends ConfigurationNode> loader(Path path) {
    return YAMLConfigurationLoader.builder()
            .setFlowStyle(DumperOptions.FlowStyle.BLOCK)
            .setIndent(2)
            .setSource(() -> Files.newBufferedReader(path, StandardCharsets.UTF_8))
            .setSink(() -> Files.newBufferedWriter(path, StandardCharsets.UTF_8))
            .build();
}
 
Example #7
Source File: BiomeConfig.java    From BlueMap with MIT License 5 votes vote down vote up
public BiomeConfig(ConfigurationNode node, ConfigurationLoader<? extends ConfigurationNode> autopoulationConfigLoader) {
	this.autopoulationConfigLoader = autopoulationConfigLoader;
	
	biomes = new ConcurrentHashMap<>(200, 0.5f, 8);

	for (Entry<Object, ? extends ConfigurationNode> e : node.getChildrenMap().entrySet()){
		String id = e.getKey().toString();
		Biome biome = Biome.create(id, e.getValue());
		biomes.put(biome.getNumeralId(), biome);
	}
	
}
 
Example #8
Source File: JsonLoader.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ConfigurationLoader<? extends ConfigurationNode> loader(Path path) {
    return GsonConfigurationLoader.builder()
            .setIndent(2)
            .setSource(() -> Files.newBufferedReader(path, StandardCharsets.UTF_8))
            .setSink(() -> Files.newBufferedWriter(path, StandardCharsets.UTF_8))
            .build();
}
 
Example #9
Source File: HoconLoader.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public ConfigurationLoader<? extends ConfigurationNode> loader(Path path) {
    return HoconConfigurationLoader.builder()
            .setSource(() -> Files.newBufferedReader(path, StandardCharsets.UTF_8))
            .setSink(() -> Files.newBufferedWriter(path, StandardCharsets.UTF_8))
            .build();
}
 
Example #10
Source File: PluginServlet.java    From Web-API with MIT License 5 votes vote down vote up
@GET
@Path("/{plugin}/config")
@Permission({ "config", "get" })
@ApiOperation(value = "Get plugin configs", notes = "Gets a map containing the plugin config file names as keys, " +
        "and their config file contents as their values.")
public Map<String, Object> getPluginConfig(
        @PathParam("plugin") @ApiParam("The id of the plugin") String pluginName)
        throws NotFoundException {
    Optional<CachedPluginContainer> optPlugin = cacheService.getPlugin(pluginName);
    if (!optPlugin.isPresent()) {
        throw new NotFoundException("Plugin with id '" + pluginName + "' could not be found");
    }

    List<java.nio.file.Path> paths = getConfigFiles(optPlugin.get());

    Map<String, Object> configs = new HashMap<>();
    for (java.nio.file.Path path : paths) {
        String key = path.getFileName().toString();

        try {
            ConfigurationLoader<CommentedConfigurationNode> loader =
                    HoconConfigurationLoader.builder().setPath(path).build();
            CommentedConfigurationNode config = loader.load();
            configs.put(key, parseConfiguration(config));
        } catch (IOException e) {
            configs.put(key, e);
        }
    }

    return configs;
}
 
Example #11
Source File: HOCONFactionStorage.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public @Nullable Faction getFaction(final String factionName)
{
    ConfigurationLoader<? extends ConfigurationNode> configurationLoader = this.factionLoaders.get(factionName.toLowerCase() + ".conf");
    if (configurationLoader == null)
    {
        final Path filePath = this.factionsDir.resolve(factionName.toLowerCase() + ".conf");

        // Check if file exists, if not then return null
        if (Files.notExists(filePath))
            return null;

        // Create configuration loader
        configurationLoader = HoconConfigurationLoader.builder().setDefaultOptions(ConfigurateHelper.getDefaultOptions()).setPath(this.factionsDir.resolve(filePath)).build();
    }

    if (configurationLoader == null)
        return null;

    try
    {
        final ConfigurationNode configurationNode = configurationLoader.load();
        return ConfigurateHelper.getFactionFromNode(configurationNode);
    }
    catch (IOException | ObjectMappingException e)
    {
        Sponge.getServer().getConsole().sendMessage(Text.of(TextColors.RED, "Could not deserialize faction object from file! faction name = " + factionName));
        e.printStackTrace();
    }
    return null;
}
 
Example #12
Source File: HOCONFactionStorage.java    From EagleFactions with MIT License 5 votes vote down vote up
@Override
public boolean saveFaction(final Faction faction)
{
    ConfigurationLoader<? extends ConfigurationNode> configurationLoader = this.factionLoaders.get(faction.getName().toLowerCase() + ".conf");
    try
    {
        if (configurationLoader == null)
        {
            final Path factionFilePath = this.factionsDir.resolve(faction.getName().toLowerCase() + ".conf");
            Files.createFile(factionFilePath);
            configurationLoader = HoconConfigurationLoader.builder().setDefaultOptions(ConfigurateHelper.getDefaultOptions()).setPath(factionFilePath).build();
            this.factionLoaders.put(factionFilePath.getFileName().toString(), configurationLoader);
        }

        final ConfigurationNode configurationNode = configurationLoader.load();
        final boolean didSucceed = ConfigurateHelper.putFactionInNode(configurationNode, faction);
        if (didSucceed)
        {
            configurationLoader.save(configurationNode);
            return true;
        }
        else return false;
    }
    catch (final IOException e)
    {
        e.printStackTrace();
    }
    return false;
}
 
Example #13
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public int SingleToFiles() {
    int saved = 0;
    for (World w : Sponge.getServer().getWorlds()) {
        Set<Region> regions = RedProtect.get().rm.getRegionsByWorld(w.getName());
        for (Region r : regions) {
            File wf = new File(RedProtect.get().configDir + File.separator + "data", w.getName() + File.separator + r.getName() + ".conf");
            ConfigurationLoader<CommentedConfigurationNode> regionManager = HoconConfigurationLoader.builder().setPath(wf.toPath()).build();
            CommentedConfigurationNode fileDB = regionManager.createEmptyNode();

            File f = new File(RedProtect.get().configDir + File.separator + "data", w.getName());
            if (!f.exists()) {
                f.mkdir();
            }

            saved++;
            addProps(fileDB, r);
            saveConf(fileDB, regionManager);
        }

        File oldf = new File(RedProtect.get().configDir + File.separator + "data", "data_" + w.getName() + ".conf");
        if (oldf.exists()) {
            oldf.delete();
        }
    }

    if (!RedProtect.get().config.configRoot().flat_file.region_per_file) {
        RedProtect.get().config.configRoot().flat_file.region_per_file = true;
    }
    RedProtect.get().config.save();
    return saved;
}
 
Example #14
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
private void saveConf(CommentedConfigurationNode fileDB, ConfigurationLoader<CommentedConfigurationNode> regionManager) {
    try {
        regionManager.save(fileDB);
    } catch (IOException e) {
        printJarVersion();
        e.printStackTrace();
    }
}
 
Example #15
Source File: ConfigurationFileUtil.java    From AntiVPN with MIT License 5 votes vote down vote up
public static Configuration getConfig(Plugin plugin, String resourcePath, File fileOnDisk) throws IOException {
    File parentDir = fileOnDisk.getParentFile();
    if (parentDir.exists() && !parentDir.isDirectory()) {
        Files.delete(parentDir.toPath());
    }
    if (!parentDir.exists()) {
        if (!parentDir.mkdirs()) {
            throw new IOException("Could not create parent directory structure.");
        }
    }
    if (fileOnDisk.exists() && fileOnDisk.isDirectory()) {
        Files.delete(fileOnDisk.toPath());
    }

    if (!fileOnDisk.exists()) {
        try (InputStreamReader reader = new InputStreamReader(plugin.getResource(resourcePath));
             BufferedReader in = new BufferedReader(reader);
             FileWriter writer = new FileWriter(fileOnDisk);
             BufferedWriter out = new BufferedWriter(writer)) {
            String line;
            while ((line = in.readLine()) != null) {
                out.write(line + System.lineSeparator());
            }
        }
    }

    ConfigurationLoader<ConfigurationNode> loader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setFile(fileOnDisk).build();
    ConfigurationNode root = loader.load(ConfigurationOptions.defaults().setHeader("Comments are gone because update :(. Click here for new config + comments: https://www.spigotmc.org/resources/anti-vpn.58291/"));
    Configuration config = new Configuration(root);
    ConfigurationVersionUtil.conformVersion(loader, config, fileOnDisk);

    return config;
}
 
Example #16
Source File: WorldFlatFileRegionManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
private void load(String path) {

        if (!RedProtect.get().config.configRoot().file_type.equalsIgnoreCase("mysql")) {
            RedProtect.get().logger.debug(LogLevel.DEFAULT, "Load world " + this.world + ". File type: conf");

            try {
                File tempRegionFile = new File(path);
                if (!tempRegionFile.exists()) {
                    tempRegionFile.createNewFile();
                }

                ConfigurationLoader<CommentedConfigurationNode> regionManager = HoconConfigurationLoader.builder().setPath(tempRegionFile.toPath()).build();
                CommentedConfigurationNode region = regionManager.load();

                for (Object key : region.getChildrenMap().keySet()) {
                    String rname = key.toString();
                    if (!region.getNode(rname).hasMapChildren()) {
                        continue;
                    }
                    Region newr = loadRegion(region, rname, Sponge.getServer().getWorld(world).get());
                    newr.setToSave(false);
                    regions.put(rname, newr);
                }
            } catch (IOException e) {
                CoreUtil.printJarVersion();
                e.printStackTrace();
            }
        }
    }
 
Example #17
Source File: WorldFlatFileRegionManager.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
private void saveConf(CommentedConfigurationNode fileDB, ConfigurationLoader<CommentedConfigurationNode> regionManager) {
    try {
        regionManager.save(fileDB);
    } catch (IOException e) {
        RedProtect.get().logger.severe("Error during save database file for world " + world + ": ");
        CoreUtil.printJarVersion();
        e.printStackTrace();
    }
}
 
Example #18
Source File: ConfigurationFileUtil.java    From AntiVPN with MIT License 5 votes vote down vote up
public static Configuration getConfig(Plugin plugin, String resourcePath, File fileOnDisk) throws IOException {
    File parentDir = fileOnDisk.getParentFile();
    if (parentDir.exists() && !parentDir.isDirectory()) {
        Files.delete(parentDir.toPath());
    }
    if (!parentDir.exists()) {
        if (!parentDir.mkdirs()) {
            throw new IOException("Could not create parent directory structure.");
        }
    }
    if (fileOnDisk.exists() && fileOnDisk.isDirectory()) {
        Files.delete(fileOnDisk.toPath());
    }

    if (!fileOnDisk.exists()) {
        try (InputStreamReader reader = new InputStreamReader(plugin.getResourceAsStream(resourcePath));
             BufferedReader in = new BufferedReader(reader);
             FileWriter writer = new FileWriter(fileOnDisk);
             BufferedWriter out = new BufferedWriter(writer)) {
            String line;
            while ((line = in.readLine()) != null) {
                out.write(line + System.lineSeparator());
            }
        }
    }

    ConfigurationLoader<ConfigurationNode> loader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setFile(fileOnDisk).build();
    ConfigurationNode root = loader.load(ConfigurationOptions.defaults().setHeader("Comments are gone because update :(. Click here for new config + comments: https://www.spigotmc.org/resources/anti-vpn-bungee.58716/"));
    Configuration config = new Configuration(root);
    ConfigurationVersionUtil.conformVersion(loader, config, fileOnDisk);

    return config;
}
 
Example #19
Source File: ConfigManager.java    From BlueMap with MIT License 5 votes vote down vote up
private ConfigurationLoader<? extends ConfigurationNode> getLoader(String filename, InputStream is){
	BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
	
	if (filename.endsWith(".json")) return GsonConfigurationLoader.builder().setSource(() -> reader).build();
	if (filename.endsWith(".yaml") || filename.endsWith(".yml")) return YAMLConfigurationLoader.builder().setSource(() -> reader).build();
	else return HoconConfigurationLoader.builder().setSource(() -> reader).build();
}
 
Example #20
Source File: SpongeConfigAdapter.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
protected ConfigurationLoader<? extends ConfigurationNode> createLoader(Path path) {
    return HoconConfigurationLoader.builder().setPath(path).build();
}
 
Example #21
Source File: BaseConfig.java    From Web-API with MIT License 4 votes vote down vote up
public void setLoader(ConfigurationLoader<CommentedConfigurationNode> loader) {
    this.loader = loader;
}
 
Example #22
Source File: RawFileConfig.java    From UltimateCore with MIT License 4 votes vote down vote up
@Override
public ConfigurationLoader<CommentedConfigurationNode> getLoader() {
    return loader;
}
 
Example #23
Source File: Configuration.java    From Prism with MIT License 4 votes vote down vote up
private ConfigurationLoader<CommentedConfigurationNode> getConfigurationLoader() {
    return configurationLoader;
}
 
Example #24
Source File: VelocityConfigAdapter.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
protected ConfigurationLoader<? extends ConfigurationNode> createLoader(Path path) {
    return YAMLConfigurationLoader.builder().setPath(path).build();
}
 
Example #25
Source File: UCConfig.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
public void addChannel(UCChannel ch) throws IOException {
    CommentedConfigurationNode chFile;
    ConfigurationLoader<CommentedConfigurationNode> channelManager;
    File defch = new File(UChat.get().configDir(), "channels" + File.separator + ch.getName().toLowerCase() + ".conf");

    channelManager = HoconConfigurationLoader.builder().setFile(defch).build();
    chFile = channelManager.load();

    chFile.getNode("across-worlds").setComment(""
            + "###################################################\n"
            + "############## Channel Configuration ##############\n"
            + "###################################################\n"
            + "\n"
            + "This is the channel configuration.\n"
            + "You can change and copy this file to create as many channels you want.\n"
            + "This is the default options:\n"
            + "\n"
            + "name: Global - The name of channel.\n"
            + "alias: g - The alias to use the channel\n"
            + "across-worlds: true - Send messages of this channel to all worlds?\n"
            + "distance: 0 - If across worlds is false, distance to receive this messages.\n"
            + "color: &b - The color of channel\n"
            + "tag-builder: ch-tags,world,clan-tag,marry-tag,group-prefix,nickname,group-suffix,message - Tags of this channel\n"
            + "need-focus: false - Player can use the alias or need to use '/ch g' to use this channel?\n"
            + "canLock: true - Change if the player can use /<channel> to lock on channel.\n"
            + "receivers-message: true - Send chat messages like if no player near to receive the message?\n"
            + "cost: 0.0 - Cost to player use this channel.\n"
            + "use-this-builder: false - Use this tag builder or use the 'config.yml' tag-builder?\n"
            + "\n"
            + "channelAlias - Use this channel as a command alias.\n"
            + "  enable: true - Enable this execute a command alias?\n"
            + "  sendAs: player - Send the command alias as 'player' or 'console'?\n"
            + "  cmd: '' - Command to send on every message send by this channel.\n"
            + "available-worlds - Worlds and only this world where this chat can be used and messages sent/received.\n"
            + "discord:\n"
            + "  mode: NONE - The options are NONE, SEND, LISTEN, BOTH. If enabled and token code set and the channel ID matches with one discord channel, will react according the choosen mode.\n"
            + "  hover: &3Discord Channel: &a{dd-channel}\n"
            + "  format-to-mc: {ch-color}[{ch-alias}]&b{dd-rolecolor}[{dd-rolename}]{sender}&r: \n"
            + "  format-to-dd: :thought_balloon: **{sender}**: {message} \n"
            + "  allow-server-cmds: false - Use this channel to send commands from discord > minecraft.\n"
            + "  channelID: '' - The IDs of your Discord Channels. Enable debug on your discord to get the channel ID.\n"
            + "  Note: You can add more than one discord id, just separate by \",\" like: 13246579865498,3216587898754\n");

    ch.getProperties().forEach((key, value) -> chFile.getNode((Object[]) key.toString().split("\\.")).setValue(value));
    channelManager.save(chFile);

    if (UChat.get().getChannel(ch.getName()) != null) {
        ch.setMembers(UChat.get().getChannel(ch.getName()).getMembers());
        UChat.get().getChannels().remove(Arrays.asList(ch.getName().toLowerCase(), ch.getAlias().toLowerCase()));
    }
    UChat.get().getChannels().put(Arrays.asList(ch.getName().toLowerCase(), ch.getAlias().toLowerCase()), ch);
}
 
Example #26
Source File: UCConfig.java    From UltimateChat with GNU General Public License v3.0 4 votes vote down vote up
private void loadChannels() throws IOException {
    File chfolder = new File(UChat.get().configDir(), "channels");

    if (!chfolder.exists()) {
        chfolder.mkdir();
        UChat.get().getLogger().info("Created folder: " + chfolder.getPath());
    }

    //--------------------------------------- Load Aliases -----------------------------------//

    if (UChat.get().getChannels() == null) {
        UChat.get().setChannels(new HashMap<>());
    }

    File[] listOfFiles = chfolder.listFiles();

    CommentedConfigurationNode channel;
    ConfigurationLoader<CommentedConfigurationNode> channelManager;

    if (listOfFiles.length == 0) {
        //create default channels
        File g = new File(chfolder, "global.conf");
        channelManager = HoconConfigurationLoader.builder().setFile(g).build();
        channel = channelManager.load();
        channel.getNode("name").setValue("Global");
        channel.getNode("alias").setValue("g");
        channel.getNode("color").setValue("&2");
        channel.getNode("jedis").setValue(true);
        channelManager.save(channel);

        File l = new File(chfolder, "local.conf");
        channelManager = HoconConfigurationLoader.builder().setFile(l).build();
        channel = channelManager.load();
        channel.getNode("name").setValue("Local");
        channel.getNode("alias").setValue("l");
        channel.getNode("across-worlds").setValue(false);
        channel.getNode("distance").setValue(40);
        channel.getNode("color").setValue("&e");
        channelManager.save(channel);

        File ad = new File(chfolder, "admin.conf");
        channelManager = HoconConfigurationLoader.builder().setFile(ad).build();
        channel = channelManager.load();
        channel.getNode("name").setValue("Admin");
        channel.getNode("alias").setValue("ad");
        channel.getNode("color").setValue("&b");
        channel.getNode("jedis").setValue(true);
        channelManager.save(channel);

        listOfFiles = chfolder.listFiles();
    }

    for (File file : listOfFiles) {
        if (file.getName().endsWith(".conf")) {
            channelManager = HoconConfigurationLoader.builder().setFile(file).build();
            channel = channelManager.load();

            Map<String, Object> chProps = new HashMap<>();
            channel.getChildrenMap().forEach((key, value) -> {
                if (value.hasMapChildren()) {
                    String rkey = key.toString();
                    for (Entry<Object, ? extends CommentedConfigurationNode> vl : value.getChildrenMap().entrySet()) {
                        chProps.put(rkey + "." + vl.getKey(), vl.getValue().getValue());
                    }
                } else {
                    chProps.put(key.toString(), value.getValue());
                }
            });

            UCChannel ch = new UCChannel(chProps);
            addChannel(ch);
        }
    }
}
 
Example #27
Source File: Config.java    From ChatUI with MIT License 4 votes vote down vote up
public static void init(ConfigurationLoader<CommentedConfigurationNode> confLoader, Logger logger) {
    Config.confLoader = confLoader;
    Config.logger = logger;
    loadConfig();
}
 
Example #28
Source File: LibConfig.java    From ChatUI with MIT License 4 votes vote down vote up
public static void init(ConfigurationLoader<CommentedConfigurationNode> confLoader, Logger logger) {
    LibConfig.confLoader = confLoader;
    LibConfig.logger = logger;
    loadConfig();
}
 
Example #29
Source File: LanguageFileUtil.java    From AntiVPN with MIT License 4 votes vote down vote up
public static Optional<File> getLanguage(Object plugin, PluginDescription description, Locale locale, boolean ignoreCountry) throws IOException {
    // Build resource path & file path for language
    // Use country is specified (and lang provides country)
    String resourcePath = ignoreCountry || locale.getCountry() == null || locale.getCountry().isEmpty() ? "lang_" + locale.getLanguage() + ".yml" : "lang_" + locale.getLanguage() + "_" + locale.getCountry() + ".yml";
    File langDir = new File(new File(description.getSource().get().getParent().toFile(), description.getName().get()), "lang");
    File fileOnDisk = new File(langDir, resourcePath);

    // Clean up/build language path on disk
    if (langDir.exists() && !langDir.isDirectory()) {
        Files.delete(langDir.toPath());
    }
    if (!langDir.exists()) {
        if (!langDir.mkdirs()) {
            throw new IOException("Could not create parent directory structure.");
        }
    }
    if (fileOnDisk.exists() && fileOnDisk.isDirectory()) {
        Files.delete(fileOnDisk.toPath());
    }

    // Check language version
    if (fileOnDisk.exists()) {
        try (InputStream inStream = plugin.getClass().getClassLoader().getResourceAsStream(resourcePath)) {
            if (inStream != null) {
                ConfigurationLoader<ConfigurationNode> fileLoader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setFile(fileOnDisk).build();
                ConfigurationNode fileRoot = fileLoader.load();
                double fileVersion = fileRoot.getNode("acf-minecraft", "version").getDouble(1.0d);

                try (InputStreamReader reader = new InputStreamReader(inStream);
                     BufferedReader in = new BufferedReader(reader)) {
                    ConfigurationLoader<ConfigurationNode> streamLoader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setSource(() -> in).build();
                    ConfigurationNode streamRoot = streamLoader.load();
                    double streamVersion = streamRoot.getNode("acf-minecraft", "version").getDouble(1.0d);

                    if (streamVersion > fileVersion) {
                        // Version update, backup & delete file on disk
                        File backupFile = new File(fileOnDisk.getParent(), fileOnDisk.getName() + ".bak");
                        if (backupFile.exists()) {
                            Files.delete(backupFile.toPath());
                        }

                        com.google.common.io.Files.copy(fileOnDisk, backupFile);
                        Files.delete(fileOnDisk.toPath());
                    }
                }
            }
        }
    }

    // Write language file to disk if not exists
    if (!fileOnDisk.exists()) {
        try (InputStream inStream = plugin.getClass().getClassLoader().getResourceAsStream(resourcePath)) {
            if (inStream != null) {
                try (InputStreamReader reader = new InputStreamReader(inStream);
                     BufferedReader in = new BufferedReader(reader);
                     FileWriter writer = new FileWriter(fileOnDisk);
                     BufferedWriter out = new BufferedWriter(writer)) {
                    String line;
                    while ((line = in.readLine()) != null) {
                        out.write(line + System.lineSeparator());
                    }
                }
            }
        }
    }

    if (fileOnDisk.exists()) {
        // Return file on disk
        return Optional.of(fileOnDisk);
    } else {
        // If we need a more generic language (eg. if we have "en_US" and we don't have "en_US.yml" but we do have "en.yml") then return the more generic language file
        // Otherwise, no language found
        return ignoreCountry ? Optional.empty() : getLanguage(plugin, description, locale, true);
    }
}
 
Example #30
Source File: AntiVPN.java    From AntiVPN with MIT License 4 votes vote down vote up
public boolean loadYamlLanguageFile(VelocityLocales locales, File file, Locale locale) throws IOException {
    ConfigurationLoader<ConfigurationNode> fileLoader = YAMLConfigurationLoader.builder().setFlowStyle(DumperOptions.FlowStyle.BLOCK).setIndent(2).setFile(file).build();
    return loadLanguage(locales, fileLoader.load(), locale);
}