1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package cz.zcu.mre.sparkle.tools;
21
22 import cz.zcu.mre.sparkle.Messages;
23 import org.antlr.v4.runtime.tree.ParseTree;
24 import org.w3c.dom.Document;
25 import org.w3c.dom.Element;
26 import java.util.Collection;
27
28
29
30
31
32
33
34
35 public interface Saveable {
36
37
38
39
40
41
42 void save(Element e);
43
44
45
46
47
48
49
50
51 void load(Object e) throws LoadException;
52
53
54
55
56 String getXMLElementName();
57
58
59
60
61
62
63
64
65 static void defaultSave(final Element rootElement, final Collection<?> children) {
66 final Document doc = rootElement.getOwnerDocument();
67 children.stream().filter(c -> c instanceof Saveable).forEach(c
68 -> {
69 final Saveable s = (Saveable) c;
70 final Element e = doc.createElement(s.getXMLElementName());
71 rootElement.appendChild(e);
72 s.save(e);
73 });
74 }
75
76
77
78
79
80
81
82
83 static void defaultSave(final Element rootElement, final Saveable... saveables) {
84 final Document doc = rootElement.getOwnerDocument();
85 for (final Saveable saveable : saveables) {
86 final Element e = doc.createElement(saveable.getXMLElementName());
87 rootElement.appendChild(e);
88 saveable.save(e);
89 }
90 }
91
92 final class LoadException
93 extends Exception {
94
95 private static final long serialVersionUID = -5502381352773721168L;
96
97 Element element;
98 String attributeName;
99
100 public LoadException(final String elementTagName) {
101 super(String.format(Messages.getString("REQUIRED_ELEMENT_X_NOT_FOUND"), elementTagName));
102 element = null;
103 attributeName = null;
104 }
105
106 public LoadException(final Element e, final String attributeName) {
107 super(getMessage(e, attributeName));
108 this.element = e;
109 this.attributeName = attributeName;
110 }
111
112 public LoadException(final ParseTree e, final String attributeName) {
113 super(getMessageFileQuery(e, attributeName));
114 }
115
116 private static String getMessage(final Element e, final String attributeName) {
117 if (e.hasAttribute(attributeName)) {
118 return String
119 .format(Messages.getString("VALUE_X_NOT_VALID_FOR_ELEMENT_Y"), e.getAttribute(attributeName),
120 e.getTagName());
121 }
122 return String.format(Messages.getString("ELEMENT_X_ATTRIBUTE_Y_IS_MISSING"), e.getTagName(),
123 attributeName);
124 }
125
126 private static String getMessageFileQuery(final ParseTree e, final String attributeName) {
127 return String.format(Messages.getString("ELEMENT_X_ATTRIBUTE_Y_IS_MISSING"), e.getText(),
128 attributeName);
129 }
130 }
131 }