01: package org.jreform.internal;
02:
03: import java.util.HashMap;
04: import java.util.Iterator;
05: import java.util.Map;
06:
07: import javax.servlet.http.HttpServletRequest;
08:
09: import org.jreform.DuplicateNameException;
10: import org.jreform.Form;
11: import org.jreform.Group;
12:
13: /**
14: * A form that contains a set of its own inputs, errors and input groups.
15: * It also contains references to inputs of its child groups.
16: * Input names and input group names must be unique within a form.
17: *
18: * @author armandino (at) gmail.com
19: */
20: class AbstractForm extends AbstractInputCollection implements Form {
21: private final Map<String, Group> groups;
22:
23: AbstractForm() {
24: groups = new HashMap<String, Group>();
25: }
26:
27: /**
28: * Adds the passed in group to the form.
29: *
30: * @throws DuplicateNameException if there is an existing group
31: * with the same name.
32: */
33: final void addGroup(Group group) {
34: String name = group.getName();
35:
36: if (groups.containsKey(name))
37: throw new DuplicateNameException(
38: "Duplicate group name within the same form: "
39: + name);
40:
41: groups.put(name, group);
42: }
43:
44: public final Group getGroup(String name) {
45: return groups.get(name);
46: }
47:
48: public final boolean validate(HttpServletRequest req) {
49: validateInputs(req);
50:
51: Iterator<String> groupIter = groups.keySet().iterator();
52: Group group;
53:
54: // validate input groups
55: while (groupIter.hasNext()) {
56: group = groups.get(groupIter.next());
57:
58: if (!group.validate(req))
59: getErrors().addAll(group.getErrors());
60: }
61:
62: additionalValidate();
63:
64: setValid(getErrors().isEmpty());
65:
66: return isValid();
67: }
68:
69: final void validateInputs(HttpServletRequest req) {
70: Iterator<String> iter = getInputs().keySet().iterator();
71: AbstractInputControl<?> input;
72:
73: while (iter.hasNext()) {
74: input = (AbstractInputControl<?>) getInputs().get(
75: iter.next());
76:
77: // an input that belongs to a group is validated by its parent group
78: if (!input.isGroupInput() && !input.validate(req))
79: getErrors().add(input.getInputName());
80: }
81: }
82:
83: }
|