项目:openNaEF
文件:AttrNameMapping.java
@Override
protected synchronized Map<String,Mapping> loadInner(Yaml yaml,InputStream is) throws ConfigurationException {
Map<String,Map<String,Object>> flesh = yaml.loadAs(is,Map.class);
Map<String,Mapping> config = new HashMap<>();
for (Map.Entry<String,Object>> entry : flesh.entrySet()) {
Map<String,Object> rawMapping = entry.getValue();
String contextName = entry.getKey();
String mvoClassstr = (String) rawMapping.get("mvo");
String dtoClassstr = (String) rawMapping.get("dto");
Map<String,String>> attrs = (Map<String,String>>) rawMapping.get("attrs");
try {
Mapping mapping = new Mapping(contextName,mvoClassstr,dtoClassstr,attrs);
config.put(contextName,mapping);
} catch (ClassNotFoundException e) {
e.printstacktrace();
}
}
return Collections.unmodifiableMap(config);
}
public static void writeConfigToYaml(ConfigSetting configSetting) {
try {
Yaml yaml = new Yaml();
String output = yaml.dump(configSetting);
byte[] sourceByte = output.getBytes();
File file = new File(Constants.CONfig_FILEPATH);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(sourceByte);
fileOutputStream.close();
} catch (Exception e) {
e.printstacktrace();
}
}
@Test
public void testConfigShouldBuildWithoutQueryRef() {
JdbcConfig config = new JdbcConfig((Map<String,Object>) new Yaml().load("---\n" +
"jobs:\n" +
"- name: \"global\"\n" +
" connections:\n" +
" - url: jdbc\n" +
" username: sys\n" +
" password: sys\n" +
" queries:\n" +
" - name: jdbc\n" +
" values:\n" +
" - v1\n" +
" query: abc\n" +
""));
assertNotNull(config);
}
项目:spring-cloud-skipper
文件:PackageTemplateTests.java
@Test
@SuppressWarnings("unchecked")
public void testMustasche() throws IOException {
Yaml yaml = new Yaml();
Map model = (Map) yaml.load(valuesResource.getInputStream());
String templateAsstring = StreamUtils.copyToString(nestedMapResource.getInputStream(),Charset.defaultCharset());
Template mustacheTemplate = Mustache.compiler().compile(templateAsstring);
String resolvedYml = mustacheTemplate.execute(model);
Map map = (Map) yaml.load(resolvedYml);
logger.info("Resolved yml = " + resolvedYml);
assertthat(map).containsKeys("apiVersion","deployment");
Map deploymentMap = (Map) map.get("deployment");
assertthat(deploymentMap).contains(entry("name","time"))
.contains(entry("count",10));
Map applicationProperties = (Map) deploymentMap.get("applicationProperties");
assertthat(applicationProperties).contains(entry("log.level","DEBUG"),entry("server.port",8089));
Map deploymentProperties = (Map) deploymentMap.get("deploymentProperties");
assertthat(deploymentProperties).contains(entry("app.time.producer.partitionKeyExpression","payload"),entry("app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts",5));
}
public static MediaToolConfig get(Path config)
{
try {
Yaml yaml = new Yaml();
try (InputStream in = Files.newInputStream(config))
{
MediaToolConfig mediaConfig = yaml.loadAs(in,MediaToolConfig.class);
if (logger.isInfoEnabled())
logger.info("{}",mediaConfig.toString());
return mediaConfig;
}
} catch (IOException oie) {
logger.error("{}",oie.getMessage(),oie);
}
return null;
}
项目:spring-cloud-skipper
文件:DefaultYamlConverter.java
private YamlConversionResult convert(Map<String,Collection<String>> properties) {
if (properties.isEmpty()) {
return YamlConversionResult.EMPTY;
}
YamlBuilder root = new YamlBuilder(mode,keyspaceList,status,YamlPath.EMPTY);
for (Entry<String,Collection<String>> e : properties.entrySet()) {
for (String v : e.getValue()) {
root.addProperty(YamlPath.fromProperty(e.getKey()),v);
}
}
Object object = root.build();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(options);
String output = yaml.dump(object);
return new YamlConversionResult(status,output);
}
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueryRefNonExistingQuery() {
new JdbcConfig((Map<String,Object>) new Yaml().load("---\n" +
"jobs:\n" +
"- name: \"global\"\n" +
" connections:\n" +
" - url: jdbc\n" +
" username: sys\n" +
" password: sys\n" +
" queries:\n" +
" - name: jdbc\n" +
" values:\n" +
" - v1\n" +
" query_ref: abc\n" +
""));
}
项目:spring-cloud-skipper
文件:PackageReaderTests.java
@SuppressWarnings("unchecked")
private void assertTickTockPackage(Package pkg) {
PackageMetadata Metadata = pkg.getMetadata();
assertthat(Metadata.getApiVersion()).isEqualTo("skipper.spring.io/v1");
assertthat(Metadata.getKind()).isEqualTo("SkipperPackageMetadata");
assertthat(Metadata.getName()).isEqualTo("ticktock");
assertthat(Metadata.getVersion()).isEqualTo("1.0.0");
assertthat(Metadata.getPackageSourceUrl()).isEqualTo("https://example.com/dataflow/ticktock");
assertthat(Metadata.getPackageHomeUrl()).isEqualTo("http://example.com/dataflow/ticktock");
Set<String> tagSet = convertToSet(Metadata.getTags());
assertthat(tagSet).hasSize(3).contains("stream","time","log");
assertthat(Metadata.getMaintainer()).isEqualTo("https://github.com/markpollack");
assertthat(Metadata.getDescription()).isEqualTo("The ticktock stream sends a time stamp and logs the value.");
String rawYamlString = pkg.getConfigValues().getRaw();
Yaml yaml = new Yaml();
Map<String,String> valuesAsMap = (Map<String,String>) yaml.load(rawYamlString);
assertthat(valuesAsMap).hasSize(2).containsEntry("foo","bar").containsEntry("biz","baz");
assertthat(pkg.getDependencies()).hasSize(2);
assertTimeOrLogPackage(pkg.getDependencies().get(0));
assertTimeOrLogPackage(pkg.getDependencies().get(1));
}
项目:DAWAreplicator
文件:Main.java
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: <file.yml> [iffnit]");
return;
}
Yaml yaml = new Yaml();
try (InputStream in = Files.newInputStream(Paths.get(args[0]))) {
Configuration config = yaml.loadAs(in,Configuration.class);
System.out.println(config.toString());
}
if (args.length > 1 && args[1].equals("init")) {
ReplicaInit replicaInit = new ReplicaInit();
replicaInit.start();
} else if (args.length > 1 && !args[1].equals("init")) {
System.out.println("Usage: <file.yml> [init]");
} else {
ReplicaEvent replicaEvent = new ReplicaEvent();
replicaEvent.start();
}
}
项目:cdep
文件:V3Reader.java
@NotNull
public static io.cdep.cdep.yml.cdepmanifest.CDepManifestYml convertStringToManifest(@NotNull String content) {
Yaml yaml = new Yaml(new Constructor(io.cdep.cdep.yml.cdepmanifest.v3.CDepManifestYml.class));
io.cdep.cdep.yml.cdepmanifest.CDepManifestYml manifest;
try {
CDepManifestYml prior = (CDepManifestYml) yaml.load(
new ByteArrayInputStream(content.getBytes(StandardCharsets
.UTF_8)));
prior.sourceVersion = CDepManifestYmlVersion.v3;
manifest = convert(prior);
require(manifest.sourceVersion == CDepManifestYmlVersion.v3);
} catch (YAMLException e) {
manifest = convert(V2Reader.convertStringToManifest(content));
}
return manifest;
}
项目:cdep
文件:TestCDep.java
@Test
public void testMissingGithubCoordinate() throws Exception {
CDepYml config = new CDepYml();
System.out.printf(new Yaml().dump(config));
File yaml = new File(".test-files/runMathfu/cdep.yml");
yaml.getParentFile().mkdirs();
Files.write("builders: [cmake,cmakeExamples]\ndependencies:\n- compile: com.github.jomof:mathfoo:1.0.2-rev7\n",yaml,StandardCharsets.UTF_8);
try {
String result = main("-wf",yaml.getParent());
System.out.printf(result);
fail("Expected an exception");
} catch (RuntimeException e) {
assertthat(e).hasMessage("Could not resolve 'com.github.jomof:mathfoo:1.0.2-rev7'. It doesn't exist.");
}
}
项目:cdep
文件:TestCDep.java
@Test
public void unfindableLocalFile() throws Exception {
CDepYml config = new CDepYml();
System.out.printf(new Yaml().dump(config));
File yaml = new File(".test-files/unfindableLocalFile/cdep.yml");
yaml.getParentFile().mkdirs();
Files.write("builders: [cmake,cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n",StandardCharsets.UTF_8);
try {
main("-wf",yaml.getParent());
fail("Expected failure");
} catch (RuntimeException e) {
assertthat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist.");
}
}
项目:cdep
文件:TestCDep.java
@Test
public void sqlite() throws Exception {
CDepYml config = new CDepYml();
System.out.printf(new Yaml().dump(config));
File yaml = new File(".test-files/firebase/cdep.yml");
yaml.getParentFile().mkdirs();
Files.write("builders: [cmake,cmakeExamples]\n"
+ "dependencies:\n"
+ "- compile: com.github.jomof:sqlite:3.16.2-rev45\n",StandardCharsets.UTF_8);
String result1 = main("show","manifest","-wf",yaml.getParent());
yaml.delete();
Files.write(result1,StandardCharsets.UTF_8);
System.out.print(result1);
String result = main("-wf",yaml.getParent());
System.out.printf(result);
}
/**
* 加载配置文件
*/
private void loadServerFromConfigFile() {
InputStream inputStream = parseYamlFile(CONfig_FILE_NAME,true);
Yaml yaml = new Yaml();
YamlServerConfig config = yaml.loadAs(inputStream,YamlServerConfig.class);
List<YamlServerList> servers = config.servers;
for (YamlServerList server : servers) {
for (ServerInstance instance : server.getInstances()) {
instance.setServiceName(server.getServiceName());
instance.ready();
}
instanceMap.put(server.getServiceName(),server.getInstances());
}
log.info("成功加载server的配置文件:{},Server:{}",CONfig_FILE_NAME,instanceMap);
}
@SuppressWarnings("unchecked")
@Override
public void reload() {
Config.createConfigFile(this.file);
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
try {
this.list = yaml.loadAs(Utils.readFile(file),Map.class);
} catch (IOException e) {
e.printstacktrace();
}
if (this.list == null) {
this.list = useSynchronization ? new Hashtable<>() : new HashMap<>();
} else {
this.list = useSynchronization ? new Hashtable<>(this.list) : new HashMap<>(this.list);
}
}
项目:TOSCAna
文件:ResourceFileCreatorTest.java
@Test
public void testReplicationControllerCreation() {
ResourceFileCreator resourceFileCreator = new ResourceFileCreator(Pod.getPods(TestNodeStacks.getLampNodeStacks(log)));
HashMap<String,String> result = null;
try {
result = resourceFileCreator.create();
} catch (JsonProcessingException e) {
e.printstacktrace();
fail();
}
String service = result.get(appServiceName);
String deployment = result.get(appDeploymentName);
Yaml yaml = new Yaml();
serviceTest((Map) yaml.load(service));
deploymentTest((Map) yaml.load(deployment));
}
项目:Biliomi
文件:UserSettingsProducer.java
@postconstruct
private void initUserSettingsProducer() {
try {
File coreYml = new File(BiliomiContainer.getParameters().getConfigurationDir(),"core.yml");
Yaml yamlInstance = new Yaml(new Constructor(YamlCoreSettings.class));
yamlCoreSettings = yamlInstance.loadAs(new FileInputStream(coreYml),YamlCoreSettings.class);
String updateMode = yamlCoreSettings.getBiliomi().getCore().getUpdateMode();
// Somehow Yaml thinks "off" means "false"
if (StringUtils.isEmpty(updateMode)) {
this.updateMode = UpdateModeType.OFF;
} else {
this.updateMode = EnumUtils.toEnum(updateMode,UpdateModeType.class);
}
} catch (FileNotFoundException e) {
this.yamlCoreSettings = new YamlCoreSettings();
ObjectGraphs.initializeObjectGraph(this.yamlCoreSettings);
this.updateMode = UpdateModeType.INSTALL;
this.yamlCoreSettings.getBiliomi().getCore().setUpdateMode(this.updateMode.toString());
}
}
项目:datatree-adapters
文件:YamlSnakeYaml.java
public YamlSnakeYaml() {
// Representer
ExtensibleRepresenter representer = new ExtensibleRepresenter();
// Install Java / Apache Cassandra serializers
addDefaultSerializers(representer);
// Install MongoDB / BSON serializers
tryToAddSerializers("io.datatree.dom.adapters.YamlSnakeYamlBsonSerializers",representer);
// Create flow-style YAML mapper
DumperOptions optionsnormal = new DumperOptions();
optionsnormal.setDefaultFlowStyle(FlowStyle.FLOW);
mapper = new Yaml(representer,optionsnormal);
// Create "pretty" YAML mapper
DumperOptions optionspretty = new DumperOptions();
optionspretty.setDefaultFlowStyle(FlowStyle.BLOCK);
prettyMapper = new Yaml(representer,optionspretty);
}
/**
* Read user preferences from a YAML config file.
*/
public AppConfig(File configFile) {
this.configFilePath = configFile.getAbsolutePath();
// Parse YAML file
try {
Yaml yaml = new Yaml();
String yamlStr = FileManager.fileAnyEncodingToString(configFile);
configMap = (new HashMap<String,Object>()).getClass().cast(yaml.load(yamlStr));
} catch (IOException | ClassCastException exc) {
LOGGER.error("Problem reading YAML config {}",configFilePath);
LOGGER.debug("Got exception",exc);
throw new UnexpectedError();
}
// Todo: check type of array values(not done on cast)
dictionary = getConfigValue("dictionary",String.class);
deFinitionSize = getConfigValue("deFinitionSize",Integer.class);
highlightColors = getConfigValue("highlightColors",(new ArrayList<String>()).getClass());
displayOtherLemma = getConfigValue("displayOtherLemma",Boolean.class);
ignoreFrequencies = getConfigValue("ignoreFrequencies",(new ArrayList<Integer>()).getClass());
ignoreWords = getConfigValue("ignoreWords",(new ArrayList<String>()).getClass());
properNouns = new HashMap<>(); // Ignore fo Now
assstyles = getConfigValue("assstyles",String.class);
}
public static ConfigSetting readConfig() {
ConfigSetting configSetting = null;
try {
InputStream configIs = Files.newInputStream(Paths.get(Constants.CONfig_FILEPATH));
Yaml yaml = new Yaml(new Constructor(ConfigSetting.class));
configSetting = yaml.loadAs(configIs,ConfigSetting.class);
} catch (Exception e) {
e.printstacktrace();
}
return configSetting;
}
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueryValuesEmpty() {
new JdbcConfig((Map<String,Object>) new Yaml().load("---\n" +
"jobs:\n" +
"- name: \"global\"\n" +
" connections:\n" +
" - url: jdbc\n" +
" username: sys\n" +
" password: sys\n" +
" queries:\n" +
" - name: jdbc\n" +
" values:\n" +
""));
}
@SuppressWarnings("unchecked")
@Override
public Map<String,Object> readYamlFileAsMap(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
Yaml yaml = new Yaml();
return (Map<String,Object>) yaml.load(fis);
} catch (Exception ex) {
logger.error("Exception occurs when reading Yaml file:" + file.getPath(),ex);
throw new DataValidationException("Error parsing device profile from YAML: " + file.getPath());
}
}
@Test(expected = IllegalArgumentException.class)
public void testConfigShouldFailIfJobQueriesEmpty() {
new JdbcConfig((Map<String,Object>) new Yaml().load("---\n" +
"jobs:\n" +
"- name: \"global\"\n" +
" connections:\n" +
" - url: jdbc\n" +
" username: sys\n" +
" password: sys\n" +
" queries:\n" +
""));
}
项目:flow-platform
文件:NodeUtilYmlTest.java
@Test
public void should_create_node_by_string() throws Throwable {
Node node = NodeUtil.buildFromYml(ymlContent,"flow");
Assert.assertEquals("flow",node.getName());
String yml = new Yaml().dump(node);
Assert.assertNotNull(yml);
}
项目:spring-cloud-skipper
文件:PackageWriterTests.java
private Package createSimplePackage() throws IOException {
Package pkg = new Package();
// Add package Metadata
PackageMetadata packageMetadata = new PackageMetadata();
packageMetadata.setName("myapp");
packageMetadata.setVersion("1.0.0");
packageMetadata.setMaintainer("bob");
pkg.setMetadata(packageMetadata);
// Add ConfigValues
Map<String,String> map = new HashMap<>();
map.put("foo","bar");
map.put("fiz","faz");
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
dumperOptions.setPrettyFlow(true);
Yaml yaml = new Yaml(dumperOptions);
ConfigValues configValues = new ConfigValues();
configValues.setRaw(yaml.dump(map));
pkg.setConfigValues(configValues);
// Add template
Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/io/generic-template.yml");
String genericTempateData = StreamUtils.copyToString(resource.getInputStream(),Charset.defaultCharset());
Template template = new Template();
template.setData(genericTempateData);
template.setName(resource.getURL().toString());
List<Template> templateList = new ArrayList<>();
templateList.add(template);
pkg.setTemplates(templateList);
return pkg;
}
public static Config from(String configString) {
try {
Map<String,Object> newYamlConfig = (Map<String,Object>) new Yaml().load(configString);
Config config = new Config();
from(config,newYamlConfig);
return config;
} catch (Exception ex) {
throw new RuntimeException("Error on loading config from string: " + configString,ex);
}
}
项目:pl
文件:PluginYamlProducer.java
static String generate(Yaml yaml,PluginSpec from) throws Exception {
Map<String,Object> data = new HashMap<>();
data.put("main",from.getPluginClass());
data.put("name",validateName(getName(from)));
data.put("version",validateVersion(getVersion(from)));
Putter<Pl,String,Object> putter = ifNotEmpty(from.getPl(),putter(data));
putter.put("description",Pl::description);
putter.put("authors",Pl::authors,a -> a.length != 0);
putter.put("loadOn",y -> y.loadOn().name(),loadOn -> !loadOn.equals("POSTWORLD"));
putter.put("depend",y -> Stream.of(y.depend())
.filter(d -> !d.soft())
.map(Dep::value)
.collect(Collectors.toList()),list -> list.size() != 0);
putter.put("softdepend",y -> Stream.of(y.depend())
.filter(d -> d.soft())
.map(Dep::value)
.collect(Collectors.toList()),list -> list.size() != 0);
putter.put("loadbefore",Pl::loadbefore,lb -> lb.length != 0);
putter.put("prefix",Pl::prefix);
putter.put("website",Pl::website);
Map<String,Object>> commandMap = new HashMap<>();
putCommands(commandMap,from.getCommands());
if (!commandMap.isEmpty())
data.put("commands",commandMap);
return yaml.dump(data);
}
项目:cdep
文件:TestCDep.java
@Test
public void noDependencies() throws Exception {
CDepYml config = new CDepYml();
System.out.printf(new Yaml().dump(config));
File yaml = new File(".test-files/simpleDependency/cdep.yml");
yaml.getParentFile().mkdirs();
Files.write("builders: [cmake,cmakeExamples]\ndependencies:\n",StandardCharsets.UTF_8);
String result1 = main("-wf",yaml.getParent());
System.out.printf(result1);
assertthat(result1).contains("nothing");
}
项目:CoreX
文件:PluginBase.java
@Override
public void reloadConfig() {
this.config = new Config(this.configFile);
InputStream configStream = this.getResource("config.yml");
if (configStream != null) {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
try {
this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile),LinkedHashMap.class));
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
}
项目:prometheus-jdbc-exporter
文件:JdbcCollector.java
项目:train-simulator
文件:OriginalMapBuilder.java
public void MapImporter() throws IOException{
Resource resource = new ClassPathResource("maps/basic.yaml");
Yaml yaml = new Yaml();
Map<String,Object> map = (Map<String,Object>) yaml.load(resource.getInputStream());
Map<Integer,Object> tracks = (Map<Integer,Object>) map.get("tracks");
/**/
}
项目:train-simulator
文件:MapImporterTest.java
@Test
public void readYaml() {
Yaml yaml = new Yaml();
String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
List<String> list = (List<String>) yaml.load(document);
//System.out.println(list);
}
项目:train-simulator
文件:MapImporterTest.java
@Test
public void readYamlFile() throws IOException {
Resource resource = new ClassPathResource("maps/basic.yaml");
Yaml yaml = new Yaml();
Map<String,Object> list = (Map<String,Object>) yaml.load(resource.getInputStream());
//System.out.println(list);
}
public ConfigService(String configPath,Class<T> constructorClass) {
T loadedConfig = null;
File file = new File(BiliomiContainer.getParameters().getConfigurationDir(),configPath);
Yaml yaml = new Yaml(new Constructor(constructorClass));
try {
loadedConfig = yaml.loadAs(new FileInputStream(file),constructorClass);
} catch (FileNotFoundException e) {
LogManager.getLogger(getClass().getName()).error("Failed loading module configuration from " + file.getAbsolutePath());
}
this.config = loadedConfig;
}
项目:flow-platform
文件:NodeUtil.java
/**
* Verify and create node tree by yml
*
* @param yml raw yml string
* @return root node of yml
* @throws YmlException if yml format is illegal
*/
public static Node buildFromYml(String yml,String rootName) {
try {
Yaml yaml = new Yaml(ROOT_YML_CONSTRUCTOR);
RootYmlWrapper node = yaml.load(yml);
// verify flow node
if (Objects.isNull(node.flow)) {
throw new YmlException("The 'flow' content must be defined");
}
// current version only support single flow
if (node.flow.size() > 1) {
throw new YmlException("Unsupported multiple flows deFinition");
}
// steps must be provided
List<NodeWrapper> steps = node.flow.get(0).steps;
if (Objects.isNull(steps) || steps.isEmpty()) {
throw new YmlException("The 'step' must be defined");
}
node.flow.get(0).name = rootName;
Node root = node.flow.get(0).toNode();
buildNodeRelation(root);
VALIDATOR.validate(root);
return root;
} catch (YAMLException e) {
throw new YmlException(e.getMessage());
}
}
@SuppressWarnings("unchecked")
@Override
protected Map<String,Object> loadData(URL url) throws IOException {
Yaml yaml = new Yaml();
try (InputStream inputStream = url.openStream()) {
return yaml.loadAs(inputStream,Map.class);
}
}
项目:Nukkit-Java9
文件:PluginBase.java
@Override
public void reloadConfig() {
this.config = new Config(this.configFile);
InputStream configStream = this.getResource("config.yml");
if (configStream != null) {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
try {
this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile),LinkedHashMap.class));
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
}
public boolean save(Boolean async) {
if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
if (this.correct) {
String content = "";
switch (this.type) {
case Config.PROPERTIES:
content = this.writeProperties();
break;
case Config.JSON:
content = new GsonBuilder().setPrettyPrinting().create().toJson(this.config);
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
content = yaml.dump(this.config);
break;
case Config.ENUM:
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
content += String.valueOf(entry.getKey()) + "\r\n";
}
break;
}
if (async) {
Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file,content));
} else {
try {
Utils.writeFile(this.file,content);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
return true;
} else {
return false;
}
}
private void parseContent(String content) {
switch (this.type) {
case Config.PROPERTIES:
this.parseProperties(content);
break;
case Config.JSON:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
this.config = new ConfigSection(gson.fromJson(content,new Typetoken<LinkedHashMap<String,Object>>() {
}.getType()));
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
this.config = new ConfigSection(yaml.loadAs(content,LinkedHashMap.class));
if (this.config == null) {
this.config = new ConfigSection();
}
break;
// case Config.SERIALIZED
case Config.ENUM:
this.parseList(content);
break;
default:
this.correct = false;
}
}
private void saveSettings() throws IOException {
// Component and integration settings are saved in separate files,these tags should be null in core.yml
Yaml yamlInstance = new Yaml(new Constructor(YamlCoreSettings.class));
String yamlString = yamlInstance.dumpAs(yamlCoreSettings,new Tag("nl/juraji/biliomi"),DumperOptions.FlowStyle.BLOCK);
FileUtils.writeStringToFile(coreYamlFile,yamlString,"UTF-8",false);
}