Java Code Examples for ninja.leaping.configurate.hocon.HoconConfigurationLoader

The following are top voted examples for showing how to use ninja.leaping.configurate.hocon.HoconConfigurationLoader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Amicus   File: HoconConfigFile.java   View source code 6 votes vote down vote up
public static HoconConfigFile load(@Nonnull final Path path,
                                   @Nonnull final String resource,
                                   final boolean overwrite) throws IOException {
    if (overwrite) {
        Files.deleteIfExists(path);
    }

    if (!Files.exists(path)) {
        Files.createDirectories(path.getParent());

        if (!resource.isEmpty()) {
            Files.copy(HoconConfigFile.class.getResourceAsStream(resource), path);
        }
    }

    final HoconConfigurationLoader fileLoader = HoconConfigurationLoader.builder().setPath(path).build();

    return new HoconConfigFile(path, fileLoader, fileLoader.load());
}
 
Example 2
Project: gwm_Crates   File: Config.java   View source code 6 votes vote down vote up
public Config(String name, boolean auto_save) {
    this.name = name;
    try {
        file = new File(GWMCrates.getInstance().getConfigDirectory(), name);
        loader = HoconConfigurationLoader.builder().setFile(file).build();
        node = loader.load();
        if (!file.exists()) {
            file.createNewFile();
            URL defaultsURL = GWMCrates.class.getResource("/" + name);
            ConfigurationLoader<CommentedConfigurationNode> defaultsLoader =
                    HoconConfigurationLoader.builder().setURL(defaultsURL).build();
            ConfigurationNode defaultsNode = defaultsLoader.load();
            node.mergeValuesFrom(defaultsNode);
            Sponge.getScheduler().createTaskBuilder().delayTicks(1).execute(this::save).
                    submit(GWMCrates.getInstance());
        }
        if (auto_save) {
            Sponge.getScheduler().createTaskBuilder().async().execute(this::save).
                    interval(AUTO_SAVE_INTERVAL, TimeUnit.SECONDS).submit(GWMCrates.getInstance());
        }
    } catch (Exception e) {
        GWMCrates.getInstance().getLogger().warn("Failed initialize config \"" + getName() + "\"!", e);
    }
}
 
Example 3
Project: EagleFactions   File: PowerService.java   View source code 6 votes vote down vote up
public static void addPlayer(UUID playerUUID)
{
    Path playerFile = Paths.get(EagleFactions.getEagleFactions ().getConfigDir().resolve("players") +  "/" + playerUUID.toString() + ".conf");

    try
    {
        Files.createFile(playerFile);

        ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(playerFile).build();

        CommentedConfigurationNode playerNode = configLoader.load();

        playerNode.getNode("power").setValue(MainLogic.getStartingPower());
        playerNode.getNode("maxpower").setValue(MainLogic.getGlobalMaxPower());
        configLoader.save(playerNode);
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
}
 
Example 4
Project: EagleFactions   File: PowerService.java   View source code 6 votes vote down vote up
public static BigDecimal getPlayerMaxPower(UUID playerUUID)
{
    Path playerFile = Paths.get(EagleFactions.getEagleFactions ().getConfigDir().resolve("players") +  "/" + playerUUID.toString() + ".conf");

    try
    {
        ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(playerFile).build();

        CommentedConfigurationNode playerNode = configLoader.load();

        BigDecimal playerMaxPower =  new BigDecimal(playerNode.getNode("maxpower").getString());

        return playerMaxPower;
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }

    return BigDecimal.ZERO;
}
 
Example 5
Project: EagleFactions   File: PowerService.java   View source code 6 votes vote down vote up
public static void setPower(UUID playerUUID, BigDecimal power)
{
    Path playerFile = Paths.get(EagleFactions.getEagleFactions ().getConfigDir().resolve("players") +  "/" + playerUUID.toString() + ".conf");

    try
    {
        ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(playerFile).build();

        CommentedConfigurationNode playerNode = configLoader.load();

        playerNode.getNode("power").setValue(power);
        configLoader.save(playerNode);
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
}
 
Example 6
Project: EagleFactions   File: PowerService.java   View source code 6 votes vote down vote up
public static void setMaxPower(UUID playerUUID, BigDecimal power)
{
    Path playerFile = Paths.get(EagleFactions.getEagleFactions ().getConfigDir().resolve("players") +  "/" + playerUUID.toString() + ".conf");

    try
    {
        ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(playerFile).build();

        CommentedConfigurationNode playerNode = configLoader.load();

        playerNode.getNode("maxpower").setValue(power);
        configLoader.save(playerNode);
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
}
 
Example 7
Project: EagleFactions   File: PlayerService.java   View source code 6 votes vote down vote up
public static void setPlayerChunkPosition(UUID playerUUID, Vector3i chunk)
{
    Path playerFile = Paths.get(EagleFactions.getEagleFactions ().getConfigDir().resolve("players") +  "/" + playerUUID.toString() + ".conf");

    try
    {
        ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setPath(playerFile).build();

        CommentedConfigurationNode playerNode = configLoader.load();

        if(chunk != null)
        {
            playerNode.getNode("chunkPosition").setValue(chunk.toString());
        }
        else
        {
            playerNode.getNode("chunkPosition").setValue(null);
        }

        configLoader.save(playerNode);
    }
    catch (Exception exception)
    {
        exception.printStackTrace();
    }
}
 
Example 8
Project: ObfuscationMapper   File: ObfConfigManager.java   View source code 6 votes vote down vote up
/**
 * Loads the given configuration file.
 */
public static void load(Path path) {
    System.out.println("Loading config from " + path.toString());
    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        loader = HoconConfigurationLoader.builder().setPath(path).build();
        configMapper = ObjectMapper.forClass(ObfConfig.class).bindToNew();
        node = loader.load(ConfigurationOptions.defaults().setHeader(HEADER));
        config = configMapper.populate(node);
        configMapper.serialize(node);
        loader.save(node);
    } catch (Exception e) {
        System.err.println("Error loading configuration:");
        e.printStackTrace();
    }
}
 
Example 9
Project: Despector   File: ConfigManager.java   View source code 6 votes vote down vote up
/**
 * Loads the given configuration file.
 */
public static void load(Path path) {
    System.out.println("Loading config from " + path.toString());
    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        loader = HoconConfigurationLoader.builder().setPath(path).build();
        configMapper = ObjectMapper.forClass(ConfigBase.class).bindToNew();
        node = loader.load(ConfigurationOptions.defaults().setHeader(HEADER));
        config = configMapper.populate(node);
        configMapper.serialize(node);
        loader.save(node);
    } catch (Exception e) {
        System.err.println("Error loading configuration:");
        e.printStackTrace();
    }
}
 
Example 10
Project: CatClearLag   File: ConfigLoader.java   View source code 6 votes vote down vote up
public boolean loadConfig() {
    try {
        File file = new File(plugin.getConfigDir(), "catclearlag.conf");
        if (!file.exists()) {
            file.createNewFile();
        }
        ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(file).build();
        CommentedConfigurationNode config = loader.load(ConfigurationOptions.defaults().setObjectMapperFactory(plugin.getFactory()).setShouldCopyDefaults(true));
        cclConfig = config.getValue(TypeToken.of(CCLConfig.class), new CCLConfig());
        loader.save(config);
        return true;
    } catch (Exception e) {
        plugin.getLogger().error("Could not load config.", e);
        return false;
    }
}
 
Example 11
Project: CatClearLag   File: ConfigLoader.java   View source code 6 votes vote down vote up
public boolean loadMessages() {
    try {
        File file = new File(plugin.getConfigDir(), "messages.conf");
        if (!file.exists()) {
            file.createNewFile();
        }
        ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(file).build();
        CommentedConfigurationNode config = loader.load(ConfigurationOptions.defaults().setObjectMapperFactory(plugin.getFactory()).setShouldCopyDefaults(true));
        messagesConfig = config.getValue(TypeToken.of(MessagesConfig.class), new MessagesConfig());
        loader.save(config);
        return true;
    } catch (Exception e) {
        plugin.getLogger().error("Could not load config.", e);
        return false;
    }
}
 
Example 12
Project: Bedrock   File: NamedConfiguration.java   View source code 6 votes vote down vote up
public NamedConfiguration(String name) {
    try {
        File conf = new File(Bedrock.getParentDirectory().getAbsolutePath() + "/" + name + ".conf");
        boolean fileCreated = false;

        if (!conf.exists()) {
            conf.createNewFile();
            fileCreated = true;
        }

        configLoader = HoconConfigurationLoader.builder().setFile(conf).build();
        if (fileCreated) {
            rootNode = configLoader.createEmptyNode(ConfigurationOptions.defaults());
        } else {
            rootNode = configLoader.load();
        }

        // Save
        save();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: Nations   File: LanguageHandler.java   View source code 6 votes vote down vote up
public static void init(File rootDir)
{
	languageFile = new File(rootDir, "language.conf");
	languageManager = HoconConfigurationLoader.builder().setPath(languageFile.toPath()).build();
	
	try
	{
		if (!languageFile.exists())
		{
			languageFile.getParentFile().mkdirs();
			languageFile.createNewFile();
			language = languageManager.load();
			languageManager.save(language);
		}
		language = languageManager.load();
	}
	catch (IOException e)
	{
		NationsPlugin.getLogger().error("Could not load or create language file !");
		e.printStackTrace();
	}
	
}
 
Example 14
Project: BetterKits   File: BetterKits.java   View source code 6 votes vote down vote up
synchronized public void loadData() throws IOException, ObjectMappingException {
	HoconConfigurationLoader loader = getDataLoader();
	ConfigurationNode rootNode = loader.load();

	List<Kit> kitsList = rootNode.getNode("Kits").getList(TypeToken.of(Kit.class));
	this.kits = new HashMap<String, Kit>();
	for (Kit kit : kitsList) {
		this.kits.put(kit.getName().toLowerCase(), kit);
	}

	List<PlayerData> playersDataList = rootNode.getNode("PlayersData").getList(TypeToken.of(PlayerData.class));
	this.playersData = new HashMap<UUID, PlayerData>();
	for (PlayerData pd : playersDataList) {
		this.playersData.put(pd.getPlayerUUID(), pd);
	}
}
 
Example 15
Project: BetterKits   File: Messages.java   View source code 6 votes vote down vote up
public static void load(BetterKits instance) {
	//load defaults
	try {
		URL defaultsInJarURL = CommonUtils.class.getResource("messages.yml");
		YAMLConfigurationLoader defaultsLoader = YAMLConfigurationLoader.builder().setURL(defaultsInJarURL).build();
		ConfigurationNode defaults = defaultsLoader.load();
		
		HoconConfigurationLoader loader = HoconConfigurationLoader.builder().setPath(instance.getConfigDir().resolve("messages.conf")).build();
		ConfigurationNode root = loader.load();
		root.mergeValuesFrom(defaults);
		loader.save(root);
		
		for (Entry<Object, ? extends ConfigurationNode> entry : root.getChildrenMap().entrySet()) {
			messages.put(entry.getKey().toString(), entry.getValue().getString());
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Project: replay-restrictions   File: SpongePlugin.java   View source code 6 votes vote down vote up
@Subscribe
public void onServerStarted(GameStartingServerEvent event) throws IOException {
    channel = game.getChannelRegistrar().createRawChannel(this, CHANNEL);

    if (!defaultConfig.exists()) {
        InputStream in = getClass().getResourceAsStream("/config.conf");
        FileOutputStream out = new FileOutputStream(defaultConfig);
        out.getChannel().transferFrom(Channels.newChannel(in), 0, Long.MAX_VALUE);
        out.close();
        in.close();
    }

    ConfigurationNode config = HoconConfigurationLoader.builder().setFile(defaultConfig).build().load();
    global.putAll(loadRestrictions(config));
    ConfigurationNode worlds = config.getNode("worlds");
    if (!worlds.isVirtual()) {
        for (ConfigurationNode world : worlds.getChildrenList()) {
            Map<String, Object> worldRestrictions = new HashMap<>(global);
            worldRestrictions.putAll(loadRestrictions(world));
            this.worlds.put(world.getKey().toString(), worldRestrictions);
        }
    }
}
 
Example 17
Project: EverPermissions   File: EConfigSubjectStorage.java   View source code 6 votes vote down vote up
@Override
protected void loadDefault() {
	if (!this.isNewDirs()) return;
	
	String collection = this.name.split("/")[0];
	Optional<Asset> asset = this.plugin.getPluginContainer().getAsset("collections/" + collection + ".conf");
	if (!asset.isPresent()) {
		this.plugin.getELogger().debug("Asset 'collections/" + collection + ".conf' not found");
		return;
	}
	
	URL jarConfigFile = asset.get().getUrl();
	ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setURL(jarConfigFile).build();
	try {
		this.getNode().setValue(loader.load());
		this.save(true);
	} catch (IOException e) {}
}
 
Example 18
Project: UniversalMinecraftAPI   File: SpongeUniversalMinecraftAPI.java   View source code 6 votes vote down vote up
private void reloadConfig() throws IOException {
    checkConfigDir();

    Path configFile = Paths.get(configDir + "/config.conf");

    if (Files.notExists(configFile)) {
        InputStream defaultConfig = getClass().getResourceAsStream("defaultConfig.conf");

        try (FileWriter writer = new FileWriter(configFile.toFile())) {
            IOUtils.copy(defaultConfig, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setPath(configFile).build();

    rootNode = loader.load();
}
 
Example 19
Project: UniversalMinecraftAPI   File: SpongeUniversalMinecraftAPI.java   View source code 6 votes vote down vote up
private void reloadUserConfig() throws IOException {
    checkConfigDir();

    Path usersConfigFile = Paths.get(configDir + "/users.conf");

    if (Files.notExists(usersConfigFile)) {
        InputStream defaultConfig = getClass().getResourceAsStream("defaultUsers.conf");

        try (FileWriter writer = new FileWriter(usersConfigFile.toFile())) {
            IOUtils.copy(defaultConfig, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ConfigurationLoader<CommentedConfigurationNode> usersLoader = HoconConfigurationLoader.builder().setPath(usersConfigFile).build();

    usersNode = usersLoader.load();
}
 
Example 20
Project: UniversalMinecraftAPI   File: SpongeConfigurationLoaderTest.java   View source code 6 votes vote down vote up
@Test
public void testDefaultUsersConfigLoads() throws Exception {
    ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder()
            .setPath(Paths.get(getClass().getResource("defaultUsers.conf").toURI()))
            .build();
    CommentedConfigurationNode root = loader.load();
    UsersConfiguration configuration = SpongeConfigurationLoader.loadUsersConfiguration(root);

    assertEquals(2, configuration.getUsers().size());

    assertEquals(2, configuration.getGroups().size());

    GroupSection firstGroup = configuration.getGroups().get(0);
    assertEquals("default", firstGroup.getName());
    assertEquals(0, firstGroup.getDefaultPermission());
    assertEquals(0, firstGroup.getInheritsFrom().size());
    assertEquals(3, firstGroup.getPermissions().size());

    assertThat(firstGroup.getPermissions(), hasItem(PermissionSection.builder().name("players").value(10).build()));
    assertThat(firstGroup.getPermissions(), hasItem(PermissionSection.builder().name("players.get").value(1).build()));
    assertThat(firstGroup.getPermissions(), hasItem(PermissionSection.builder().name("uma").value(1).build()));
}
 
Example 21
Project: Destinations   File: Config.java   View source code 6 votes vote down vote up
/**
 * Config constructor
 *
 * @param directory File
 * @param filename  String
 * @throws IOException maybe thrown if there was an error loading the file, or creating the file for the first time.
 */
Config(File directory, String filename) throws IOException {
	Preconditions.checkNotNull(directory);
	Preconditions.checkNotNull(filename);

	this.file = new File(directory, filename);
	this.loader = HoconConfigurationLoader.builder().setFile(this.file).build();

	if (!this.file.isFile() && this.file.createNewFile()) {
		this.config = this.loader.load();
		this.setDefaults();
		this.save();
	} else {
		this.config = this.loader.load();
	}
}
 
Example 22
Project: GriefPrevention   File: GriefPreventionConfig.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public GriefPreventionConfig(Type type, Path path) {

    this.type = type;
    this.path = path;

    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(this.type.clazz).bindToNew();

        reload();
        save();
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize configuration", e);
    }
}
 
Example 23
Project: GriefPrevention   File: ClaimTemplateStorage.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public ClaimTemplateStorage(Path path) {
    this.filePath = path;
    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(ClaimTemplateConfig.class).bindToNew();

        reload();
        save();
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize claim template data", e);
    }
}
 
Example 24
Project: GriefPrevention   File: PlayerStorageData.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public PlayerStorageData(Path path) {

    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(PlayerDataConfig.class).bindToNew();

        reload();
        save();
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize configuration", e);
    }
}
 
Example 25
Project: GriefPrevention   File: MessageStorage.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public MessageStorage(Path path) {

    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(MessageDataConfig.class).bindToNew();

        reload();
        save();
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize configuration", e);
    }
}
 
Example 26
Project: GriefPrevention   File: ClaimStorageData.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public ClaimStorageData(Path path, UUID worldUniqueId, ClaimDataConfig claimData) {
    this.filePath = path;
    this.folderPath = path.getParent();
    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(ClaimDataConfig.class).bind(claimData);
        this.configMapper.getInstance().setClaimStorageData(this);
        reload();
        ((EconomyDataConfig) this.configMapper.getInstance().getEconomyData()).activeConfig = GriefPreventionPlugin.getActiveConfig(worldUniqueId);
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize configuration", e);
    }
}
 
Example 27
Project: GriefPrevention   File: ClaimStorageData.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public ClaimStorageData(Path path, UUID worldUniqueId) {
    this.filePath = path;
    this.folderPath = path.getParent();
    try {
        Files.createDirectories(path.getParent());
        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(path).build();
        if (path.getParent().endsWith("town")) {
            this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(TownDataConfig.class).bindToNew();
        } else {
            this.configMapper = (ObjectMapper.BoundInstance) ObjectMapper.forClass(ClaimDataConfig.class).bindToNew();
        }
        this.configMapper.getInstance().setClaimStorageData(this);
        reload();
        ((EconomyDataConfig) this.configMapper.getInstance().getEconomyData()).activeConfig = GriefPreventionPlugin.getActiveConfig(worldUniqueId);
    } catch (Exception e) {
        SpongeImpl.getLogger().error("Failed to initialize configuration", e);
    }
}
 
Example 28
Project: FastAsyncWorldedit   File: SpongeMetrics.java   View source code 6 votes vote down vote up
/**
 * Loads the configuration
 */
private void loadConfiguration() {
    configurationFile = getConfigFile();
    configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();

    try {
        if (!configurationFile.exists()) {
            configurationFile.createNewFile();
            config = configurationLoader.load();

            config.setComment("This contains settings for MCStats: http://mcstats.org");
            config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
            config.getNode("mcstats.opt-out").setValue(false);
            config.getNode("mcstats.debug").setValue(false);

            configurationLoader.save(config);
        } else {
            config = configurationLoader.load();
        }

        guid = config.getNode("mcstats.guid").getString();
        debug = config.getNode("mcstats.debug").getBoolean();
    } catch (final IOException e) {
        MainUtil.handleError(e);
    }
}
 
Example 29
Project: FastAsyncWorldedit   File: SpongeMetrics.java   View source code 6 votes vote down vote up
/**
 * Loads the configuration
 */
private void loadConfiguration() {
    configurationFile = getConfigFile();
    configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();

    try {
        if (!configurationFile.exists()) {
            configurationFile.createNewFile();
            config = configurationLoader.load();

            config.setComment("This contains settings for MCStats: http://mcstats.org");
            config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
            config.getNode("mcstats.opt-out").setValue(false);
            config.getNode("mcstats.debug").setValue(false);

            configurationLoader.save(config);
        } else {
            config = configurationLoader.load();
        }

        guid = config.getNode("mcstats.guid").getString();
        debug = config.getNode("mcstats.debug").getBoolean();
    } catch (final IOException e) {
        MainUtil.handleError(e);
    }
}
 
Example 30
Project: Zephyr   File: SpongeSpellManager.java   View source code 6 votes vote down vote up
@Override
public void onEnable() {
	super.onEnable();
	
	File potentialFile = new File(ZephyrPlugin.getConfigDirectory(), "spells.cfg");
	if (!potentialFile.exists()) {
		potentialFile.getParentFile().mkdirs();
		try {
			potentialFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	this.loader = HoconConfigurationLoader.builder().setFile(potentialFile).build();
	
	registerSpell(new PunchSpell());
}
 
Example 31
Project: ModularFramework   File: ModuleInjector.java   View source code 6 votes vote down vote up
@Override
public ConfigurationNode get() {
    ConfigurationNode configNode = null;

    if(((SpongeModuleController) moduleWrapper.getOwner()).getConfigurationDirectory() != null) {
        try {
            File legacyConfig = new File(((SpongeModuleController) moduleWrapper.getOwner()).getConfigurationDirectory(), moduleWrapper.getName() + ".conf");
            File config = new File(((SpongeModuleController) moduleWrapper.getOwner()).getConfigurationDirectory(), moduleWrapper.getId()+ ".conf");
            if(!moduleWrapper.getName().equals(moduleWrapper.getId()) && legacyConfig.exists()) {
                legacyConfig.renameTo(config);
            }
            if(!config.exists())
                config.createNewFile();
            ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setFile(config).build();
            configNode = configLoader.load(((SpongeModuleController) moduleWrapper.getOwner()).getConfigurationOptions());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return configNode;
}
 
Example 32
Project: ModularFramework   File: SpongeModuleWrapper.java   View source code 6 votes vote down vote up
private void loadAndSaveConfiguration() throws ClassNotFoundException, IllegalAccessException, IOException {
    for(Field field : module.getClass().getFields()) {
        if(field.isAnnotationPresent(ModuleConfiguration.class)) {
            File legacyConfig = new File(((SpongeModuleController<T>) this.getOwner()).getConfigurationDirectory(), getName() + ".conf");
            File config = new File(((SpongeModuleController<T>) this.getOwner()).getConfigurationDirectory(), getId() + ".conf");
            if(!getAnnotation().name().equals(getAnnotation().id()) && legacyConfig.exists()) {
                legacyConfig.renameTo(config);
            }
            if(!config.exists())
                config.createNewFile();
            ConfigurationLoader<CommentedConfigurationNode> configLoader = HoconConfigurationLoader.builder().setFile(config).build();
            if(((SpongeModuleController<T>) this.getOwner()).isOverrideConfigurationNode()) {
                field.set(module, configLoader.load(((SpongeModuleController<T>) this.getOwner()).getConfigurationOptions()));
            }
            configLoader.save((ConfigurationNode) field.get(module));
        }
    }
}
 
Example 33
Project: Graveyards   File: ConfigManager.java   View source code 6 votes vote down vote up
public static void saveGraveyards(Graveyards plugin) {

        File graveyardsFile = new File(plugin.getDefaultConfigDir().toFile(), "graveyardsData.conf");
        ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(graveyardsFile).build();

        try {
            CommentedConfigurationNode graveyardsData = loader.load();

            graveyardsData.setValue(new TypeToken<Map<String, GraveyardGroup>>() {
                                    },
                    plugin.getGraveyardGroupManager().getGraveyardGroupMap());

            loader.save(graveyardsData);
        } catch (IOException | ObjectMappingException e) {
            plugin.getLogger().error("Error saving graveyard data! Error:" + e.getMessage());
        }
    }
 
Example 34
Project: Graveyards   File: ConfigManager.java   View source code 6 votes vote down vote up
public static void saveRespawnPackets(Graveyards plugin) {

        File respawnDataFile = new File(plugin.getDefaultConfigDir().toFile(), "respawnData.conf");
        ConfigurationLoader<CommentedConfigurationNode> loader = HoconConfigurationLoader.builder().setFile(respawnDataFile).build();

        try {
            CommentedConfigurationNode respawnData = loader.load();

            respawnData.setValue(new TypeToken<Map<UUID, RespawnDataPacket>>() {
                                 },
                    plugin.getRespawnDataPacketMap());

            loader.save(respawnData);
        } catch (IOException | ObjectMappingException e) {
            plugin.getLogger().error("Error saving respawn data! Error:" + e.getMessage());
        }
    }
 
Example 35
Project: FlexibleLogin   File: Settings.java   View source code 6 votes vote down vote up
public void load() {
    Path configFile = dataFolder.resolve("config.conf");
    Path textFile = dataFolder.resolve("messages.conf");

    try {
        Files.createDirectories(dataFolder);

        if (Files.notExists(configFile)) {
            Files.createFile(configFile);
        }

        if (Files.notExists(textFile)) {
            Files.createFile(textFile);
        }
    } catch (IOException ioEx) {
        logger.error("Failed to create default config file", ioEx);
    }

    loadMapper(configMapper, HoconConfigurationLoader.builder().setPath(configFile).build());
    loadMapper(textMapper, HoconConfigurationLoader.builder().setPath(textFile).build());
}
 
Example 36
Project: PlotSquared   File: SpongeMetrics.java   View source code 6 votes vote down vote up
/**
 * Loads the configuration
 */
private void loadConfiguration() {
    configurationFile = getConfigFile();
    configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();

    try {
        if (!configurationFile.exists()) {
            configurationFile.createNewFile();
            config = configurationLoader.load();

            config.setComment("This contains settings for MCStats: http://mcstats.org");
            config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
            config.getNode("mcstats.opt-out").setValue(false);
            config.getNode("mcstats.debug").setValue(false);

            configurationLoader.save(config);
        } else {
            config = configurationLoader.load();
        }

        guid = config.getNode("mcstats.guid").getString();
        debug = config.getNode("mcstats.debug").getBoolean();
    } catch (final IOException e) {
        e.printStackTrace();
    }
}
 
Example 37
Project: UltimateCore   File: RawFileConfig.java   View source code 6 votes vote down vote up
public void reload() {
    try {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            if (asset == null) {
                file.createNewFile();
            } else {
                asset.copyToFile(file.toPath());
            }
        }
        loader = HoconConfigurationLoader.builder().setPath(file.toPath()).build();
        node = loader.load();
    } catch (IOException e) {
        ErrorLogger.log(e, "Failed to config for " + file);
    }
}
 
Example 38
Project: UltimateCore   File: ConfigCompleter.java   View source code 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 39
Project: ServerTools-CORE   File: STConfig.java   View source code 6 votes vote down vote up
/**
 * Construct a new STConfig instance
 *
 * @param file  The file to save to
 * @param clazz The type that holds the configuration values
 */
public STConfig(final Path file, final Class<T> clazz) {
    this.file = file;
    try {
        if (!Files.exists(file.getParent())) {
            Files.createDirectories(file.getParent());
        }

        if (!Files.exists(file)) {
            Files.createFile(file);
        }

        this.loader = HoconConfigurationLoader.builder().setPath(file).build();
        this.configMapper = ObjectMapper.forClass(clazz).bindToNew();

        load();
        save();
    } catch (Exception e) {
        log.error("Failed to create config file {}", file, e);
        throw new RuntimeException(e);
    }
}
 
Example 40
Project: ServerTools-CORE   File: CommandManager.java   View source code 6 votes vote down vote up
public CommandManager(final Path configFile) {
    this.configFile = configFile;
    try {
        if (!Files.exists(configFile.getParent())) {
            Files.createDirectories(configFile.getParent());
        }
        if (!Files.exists(configFile)) {
            Files.createFile(configFile);
        }

        loader = HoconConfigurationLoader.builder().setFile(configFile.toFile()).build();
        node = loader.load(ConfigurationOptions.defaults().setHeader(HEADER));

    } catch (IOException e) {
        log.fatal("Failed to initialize command manager");
        throw new LoaderException(e);
    }
}