Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.config.parser.impl;
- import com.client.util.FrameType;
- import com.config.object.Attribute;
- import com.config.parser.Provider;
- import com.config.parser.util.DefaultAttributes;
- import com.esotericsoftware.yamlbeans.YamlReader;
- import com.esotericsoftware.yamlbeans.YamlWriter;
- import com.logging.Logger;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.util.*;
- import java.util.logging.Level;
- /**
- * @author Daniel
- */
- public class YAMLProvider implements Provider {
- @Override
- public File getFile() {
- return new File("./Settings.yml");
- }
- @SuppressWarnings("unchecked")
- @Override
- public Collection<Attribute> getAll() {
- final List<Attribute> list = new LinkedList<Attribute>();
- try {
- YamlReader reader = new YamlReader(new FileReader(getFile()));
- Map<String, List<Map<String, Object>>> map = reader.read(HashMap.class);
- for (Map<String, Object> set : map.get("objects")) {
- for (String name : set.keySet()) {
- Class<? extends Attribute> clazz = (Class<? extends Attribute>) Class.forName(name);
- if (clazz != null) {
- final Attribute attribute = clazz.newInstance();
- if (attribute != null) {
- final String value = (String) set.get(attribute.getClass().getCanonicalName());
- if (value != null) {
- attribute.setValue(attribute.getValue() instanceof Boolean ? Boolean.valueOf(value) : attribute.getValue() instanceof Integer ? Integer.valueOf(value) : attribute.getValue() instanceof FrameType ? FrameType.valueOf(value) : value);
- }
- }
- list.add(attribute);
- }
- }
- }
- reader.close();
- return list;
- } catch (Exception ex) {
- Logger.log(YAMLProvider.class, Level.WARNING, "exception encountered while loading settings", ex);
- final Collection<Attribute> collection = new DefaultAttributes().getCollection();
- write(collection);
- return collection;
- }
- }
- @Override
- public void write(Collection<Attribute> collection) {
- try {
- YamlWriter writer = new YamlWriter(new FileWriter(getFile()));
- Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
- map.put("objects", new ArrayList<Map<String, Object>>());
- for (Attribute attribute : collection) {
- Map<String, Object> set = new HashMap<String, Object>();
- set.put(attribute.getClass().getCanonicalName(), attribute.getValue());
- map.get("objects").add(set);
- }
- writer.write(map);
- writer.close();
- } catch (Exception ex) {
- Logger.log(YAMLProvider.class, Level.WARNING, "exception encountered while saving settings", ex);
- write(new DefaultAttributes().getCollection());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement