001package com.mrivanplays.annotationconfig.yaml; 002 003import com.mrivanplays.annotationconfig.core.resolver.ConfigResolver; 004import com.mrivanplays.annotationconfig.core.resolver.ValueReader; 005import com.mrivanplays.annotationconfig.core.resolver.ValueWriter; 006import com.mrivanplays.annotationconfig.core.resolver.key.DottedResolver; 007import com.mrivanplays.annotationconfig.core.resolver.settings.LoadSettings; 008import java.io.File; 009import java.io.Reader; 010import java.util.Collections; 011import java.util.LinkedHashMap; 012import java.util.Map; 013import org.yaml.snakeyaml.Yaml; 014 015/** 016 * Represents configuration, utilising YAML 017 * 018 * @since 1.0 019 * @author MrIvanPlays 020 */ 021public final class YamlConfig { 022 023 private static final Yaml YAML = new Yaml(); 024 025 private static ConfigResolver configResolver; 026 027 /** 028 * Returns the {@link ConfigResolver} instance of YamlConfig 029 * 030 * @return config resolver 031 */ 032 public static ConfigResolver getConfigResolver() { 033 if (configResolver == null) { 034 generateConfigResolver(); 035 } 036 return configResolver; 037 } 038 039 private static final ValueWriter YAML_VALUE_WRITER = new YamlValueWriter(); 040 041 private static void generateConfigResolver() { 042 configResolver = 043 ConfigResolver.newBuilder() 044 .withKeyResolver(DottedResolver.getInstance()) 045 .withValueWriter(YAML_VALUE_WRITER) 046 .shouldReverseFields(true) 047 .withCommentPrefix("# ") 048 .withValueReader( 049 new ValueReader() { 050 @Override 051 public Map<String, Object> read(Reader reader) { 052 Map<String, Object> values = YAML.loadAs(reader, LinkedHashMap.class); 053 if (values == null) { 054 return Collections.emptyMap(); 055 } 056 return values; 057 } 058 }) 059 .build(); 060 } 061 062 /** 063 * Loads the config object from the file. If the file does not exist, it creates one. 064 * 065 * @param annotatedConfig annotated config 066 * @param file file 067 * @deprecated use {@link #getConfigResolver()}. it has a much better description of methods. the 068 * equivalent of this method there is {@link ConfigResolver#loadOrDump(Object, File, 069 * LoadSettings)} 070 */ 071 @Deprecated 072 public static void load(Object annotatedConfig, File file) { 073 getConfigResolver().loadOrDump(annotatedConfig, file); 074 } 075}