1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.sovt;
29
30 import java.util.*;
31
32 /***
33 * This is container for validation results.
34 *
35 * @author Vilmantas Baranauskas (vb, vilmantas.baranauskas)
36 */
37 public class SimpleValidationResult implements ValidationResult {
38
39 /***
40 * Delimeter used to concatenate messages in {@link #toString} method.
41 */
42 public static final String MESSAGE_DELIMETER = "\n";
43
44
45 /***
46 * Keeps state if validation is still successful.
47 */
48 private boolean valid = true;
49
50 /***
51 * Keeps list of messages.
52 */
53 private List messages = new ArrayList();
54 private Map specificErrors = new HashMap();
55 private Map specificMessages = new HashMap();
56
57
58 /***
59 * Creates instance of ValidationResult.
60 */
61 public SimpleValidationResult() {
62 }
63
64
65 /***
66 * Adds message to the validation result.
67 *
68 * @param msg Message to add.
69 */
70 public void addMessage(String msg) {
71 messages.add(msg);
72 }
73
74 public void addMessage(String key, String msg) {
75 specificMessages.put(key, msg);
76 }
77
78 /***
79 * Sets status of validation to false.
80 *
81 * @param msg Message to add.
82 */
83 public void fail(String msg) {
84 addMessage(msg);
85 valid = false;
86 }
87
88 public void fail(String key, String msg) {
89 specificErrors.put(key, msg);
90 valid = false;
91 }
92
93 /***
94 * Returns true if validation has not yet failed.
95 *
96 * @return true if validation has not yet failed.
97 */
98 public boolean isValid() {
99 return valid;
100 }
101
102 /***
103 * Returns true if there is no error for a given key.
104 *
105 * @param key Key to check.
106 * @return true if there is no error for a given key.
107 */
108 public boolean isValid(String key) {
109 Object error = specificErrors.get(key);
110 return error == null;
111 }
112
113 /***
114 * Returns set of messages concatenaited with {@link #MESSAGE_DELIMETER}.
115 * Both - global and specific messages are included. Result contains no
116 * duplicate messages.
117 *
118 * @return set of messages concatenaited with {@link #MESSAGE_DELIMETER}.
119 */
120 public String toString() {
121
122 Set allMessages = new HashSet(messages);
123 allMessages.addAll(specificMessages.values());
124 allMessages.addAll(specificErrors.values());
125
126 StringBuffer str = new StringBuffer();
127 for (Iterator iterator = allMessages.iterator(); iterator.hasNext();) {
128 str.append(MESSAGE_DELIMETER).append(iterator.next());
129 }
130 if (str.length() > 0) {
131 return str.substring(MESSAGE_DELIMETER.length());
132 } else {
133 return "";
134 }
135 }
136
137 }