1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.omid;
19
20 import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
21 import org.apache.phoenix.thirdparty.com.google.common.io.Resources;
22 import org.apache.commons.beanutils.BeanUtils;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.yaml.snakeyaml.Yaml;
26
27 import java.io.IOException;
28 import java.lang.reflect.InvocationTargetException;
29 import java.nio.charset.Charset;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 @SuppressWarnings("WeakerAccess")
34 public class YAMLUtils {
35
36 private static final Logger LOG = LoggerFactory.getLogger(YAMLUtils.class);
37
38 public void loadSettings(String resourcePath, String defaultResourcePath, Object bean) {
39 try {
40 Map properties = loadSettings(resourcePath, defaultResourcePath);
41 BeanUtils.populate(bean, properties);
42 } catch (IllegalAccessException | InvocationTargetException | IOException e) {
43 throw new IllegalStateException(e);
44 }
45 }
46
47 public void loadSettings(String resourcePath, Object bean) {
48 try {
49 Map properties = loadSettings(null, resourcePath);
50 BeanUtils.populate(bean, properties);
51 } catch (IllegalAccessException | InvocationTargetException | IOException e) {
52 throw new IllegalStateException(e);
53 }
54 }
55
56 @SuppressWarnings("unchecked")
57 public Map loadSettings(String resourcePath, String defaultResourcePath) throws IOException {
58 Map defaultSetting = loadAsMap(defaultResourcePath);
59 Preconditions.checkState(defaultSetting.size() > 0, String.format("Failed to load file '%s' from classpath", defaultResourcePath));
60 if (resourcePath != null) {
61 Map userSetting = loadAsMap(resourcePath);
62 defaultSetting.putAll(userSetting);
63 }
64 return defaultSetting;
65 }
66
67 @SuppressWarnings("unchecked")
68 public Map loadAsMap(String path) throws IOException {
69 try {
70 String content = Resources.toString(Resources.getResource(path), Charset.forName("UTF-8"));
71 LOG.debug("Loaded resource file '{}'\n{}", path, content);
72 return loadStringAsMap(content);
73 } catch (IllegalArgumentException e) {
74 return new HashMap();
75 }
76 }
77
78 @SuppressWarnings("unchecked")
79 public Map loadStringAsMap(String content) {
80 try {
81 Map settings = new Yaml().loadAs(content, Map.class);
82 return (settings != null) ? settings : new HashMap(0);
83 } catch (IllegalArgumentException e) {
84 return new HashMap();
85 }
86 }
87
88 }