001/*
002 * Configurate
003 * Copyright (C) zml and Configurate contributors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package ninja.leaping.configurate.examples;
018
019import ninja.leaping.configurate.ConfigurationNode;
020import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
021import ninja.leaping.configurate.yaml.YAMLConfigurationLoader;
022
023import java.io.IOException;
024import java.nio.file.Paths;
025
026/**
027 * An example of how to convert a configuration between two formats.
028 */
029public class FormatConversion {
030    public static void main(String[] args) {
031        // First off: we build two loaders, one with our old format pointing to the old location
032        final YAMLConfigurationLoader oldFormat = YAMLConfigurationLoader.builder()
033                .setPath(Paths.get("widgets.yml"))
034                .build();
035
036        // and a second one for our target format, pointing to the new location
037        final HoconConfigurationLoader newFormat = HoconConfigurationLoader.builder()
038                .setPath(Paths.get("widgets.conf"))
039                .build();
040
041        // We try to load the file into a node using the source format
042        final ConfigurationNode oldNode;
043        try {
044            oldNode = oldFormat.load();
045        } catch (IOException e) {
046            System.err.println("Unable to read YAML configuration: " + e.getMessage());
047            if (e.getCause() != null) {
048                e.getCause().printStackTrace();
049            }
050            System.exit(1);
051            return;
052        }
053
054        // And if we're successful, we save the loaded node using the new loader
055        try {
056            newFormat.save(oldNode);
057        } catch (IOException e) {
058            System.out.println("Unable to save HOCON format configuration: " + e.getMessage());
059            System.exit(2);
060            return;
061        }
062
063        System.out.println("Successfully converted widgets.yml to widgets.conf!");
064    }
065}