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 org.spongepowered.configurate.examples;
018
019import org.spongepowered.configurate.ConfigurateException;
020import org.spongepowered.configurate.ConfigurationNode;
021import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
022import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
023
024import java.nio.file.Paths;
025
026/**
027 * An example of how to convert a configuration between two formats.
028 */
029public final class FormatConversion {
030
031    private FormatConversion() {}
032
033    public static void main(final String[] args) {
034        // First off: we build two loaders, one with our old format pointing to the old location
035        final YamlConfigurationLoader oldFormat = YamlConfigurationLoader.builder()
036                .path(Paths.get("widgets.yml"))
037                .build();
038
039        // and a second one for our target format, pointing to the new location
040        final HoconConfigurationLoader newFormat = HoconConfigurationLoader.builder()
041                .path(Paths.get("widgets.conf"))
042                .build();
043
044        // We try to load the file into a node using the source format
045        final ConfigurationNode oldNode;
046        try {
047            oldNode = oldFormat.load();
048        } catch (final ConfigurateException e) {
049            System.err.println("Unable to read YAML configuration: " + e.getMessage());
050            if (e.getCause() != null) {
051                e.getCause().printStackTrace();
052            }
053            System.exit(1);
054            return;
055        }
056
057        // And if we're successful, we save the loaded node using the new loader
058        try {
059            newFormat.save(oldNode);
060        } catch (final ConfigurateException e) {
061            System.out.println("Unable to save HOCON format configuration: " + e.getMessage());
062            System.exit(2);
063            return;
064        }
065        System.out.println("Successfully converted widgets.yml to widgets.conf!");
066    }
067
068}