01: /* ValidationUtil.java
02: {{IS_NOTE
03: Purpose:
04:
05: Description:
06:
07: History:
08: Jul 29, 2007 11:04:28 AM , Created by Dennis Chen
09: }}IS_NOTE
10:
11: Copyright (C) 2007 Potix Corporation. All Rights Reserved.
12:
13: {{IS_RIGHT
14: This program is distributed under GPL Version 2.0 in the hope that
15: it will be useful, but WITHOUT ANY WARRANTY.
16: }}IS_RIGHT
17: */
18: package org.zkoss.seam;
19:
20: import java.util.Collections;
21: import java.util.LinkedList;
22: import java.util.List;
23:
24: import org.hibernate.validator.InvalidValue;
25: import org.jboss.seam.core.Expressions;
26: import org.zkoss.zk.ui.Component;
27: import org.zkoss.zk.ui.Execution;
28: import org.zkoss.zk.ui.Executions;
29: import org.zkoss.zk.ui.WrongValueException;
30: import org.zkoss.zk.ui.event.Event;
31: import org.zkoss.zkplus.databind.Binding;
32: import org.zkoss.zkplus.databind.BindingSaveEvent;
33:
34: /**
35: * This class helps developers to do validation when Data Binding Events is sent by Seam's rule
36: * @author Dennis.Chen
37: */
38: public class ValidationUtil {
39:
40: static private String WRONG_VALUE_KEY = "zk.seam.ValidationUtil_WV";
41:
42: /**
43: * Validate input value when onBindingSave, the validation result will be stored in current Execution,
44: * and will be throw out when afterValidate();
45: * @param event
46: * @throws WrongValueException
47: */
48: static public void validate(BindingSaveEvent event)
49: throws WrongValueException {
50: Component comp = event.getTarget();
51: Object value = event.getValue();
52: Binding binding = event.getBinding();
53:
54: String jsfexpress = "#{" + binding.getExpression() + "}";
55: InvalidValue[] ivs;
56: try {
57: ivs = Expressions.instance().validate(jsfexpress, value);
58: } catch (Exception e) {
59: throw new WrongValueException("model validation failed:"
60: + e.getMessage(), null);
61: }
62: if (ivs != null) {
63: Execution exec = Executions.getCurrent();
64: List wvList = (List) exec.getAttribute(WRONG_VALUE_KEY);
65: if (wvList == null) {
66: wvList = (List) Collections
67: .synchronizedList(new LinkedList());
68: exec.setAttribute(WRONG_VALUE_KEY, wvList);
69: }
70: for (int i = 0; i < ivs.length; i++) {
71: wvList.add(new WrongValueException(comp, ivs[i]
72: .getMessage()));
73: }
74: }
75: }
76:
77: /**
78: * Validate input when onBindingValidate,
79: * if there are any WrongValueExecption was crated when validate(),
80: * then a WrongValueException will be throw out.
81: * @param event
82: * @throws WrongValueException
83: */
84: static public void afterValidate(Event event)
85: throws WrongValueException {
86: Execution exec = Executions.getCurrent();
87: List wvList = (List) exec.getAttribute(WRONG_VALUE_KEY);
88: if (wvList == null)
89: return;
90: exec.removeAttribute(WRONG_VALUE_KEY);
91: if (wvList.size() > 0)
92: throw (WrongValueException) wvList.get(0);
93: }
94: }
|