• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.testng.mustache;
2 
3 import java.lang.reflect.Field;
4 import java.util.Map;
5 import java.util.Stack;
6 
7 public class Model {
8   private Map<String, Object> m_model;
9   private Stack<SubModel> m_subModels = new Stack<>();
10   private static class SubModel {
11     String variable;
12     Object subModel;
13   }
14 
Model(Map<String, Object> model)15   public Model(Map<String, Object> model) {
16     m_model = model;
17   }
18 
push(String variable, Object subModel)19   public void push(String variable, Object subModel) {
20     SubModel sl = new SubModel();
21     sl.variable = variable;
22     sl.subModel = subModel;
23     m_subModels.push(sl);
24   }
25 
resolveValue(String variable)26   public Value resolveValue(String variable) {
27     if (! m_subModels.isEmpty()) {
28       for (SubModel object : m_subModels) {
29         Value value = resolveOnClass(object.subModel, variable);
30         if (value != null) {
31           return value;
32         }
33       }
34     }
35 
36     return new Value(m_model.get(variable));
37   }
38 
resolveOnClass(Object object, String variable)39   private Value resolveOnClass(Object object, String variable) {
40 //    if (object instanceof Iterable) {
41 //      Iterable it = (Iterable) object;
42 //      List<Object> result = Lists.newArrayList();
43 //      for (Object o : it) {
44 //        List<Object> values = resolveOnClass(o, variable);
45 //        result.addAll(values);
46 //      }
47 //      return result;
48 //    } else {
49       Class<? extends Object> cls = object.getClass();
50       try {
51         Field f = cls.getField(variable);
52         return new Value(f.get(object));
53       } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
54 //        e.printStackTrace();
55       }
56 //    }
57 
58     return null;
59   }
60 
getTopSubModel()61   public Object getTopSubModel() {
62     return m_subModels.peek().variable;
63   }
64 
popSubModel()65   public void popSubModel() {
66     m_subModels.pop();
67   }
68 
resolveValueToString(String variable)69   public String resolveValueToString(String variable) {
70     StringBuilder result = new StringBuilder();
71     Value value = resolveValue(variable);
72     if (value.get() != null) {
73       return value.get().toString();
74     } else {
75       return "";
76     }
77   }
78 
79   @Override
toString()80   public String toString() {
81     return "[Model " + m_model + " subModel:" + m_subModels + "]";
82   }
83 }
84