01: /*******************************************************************************
02: * Portions created by Sebastian Thomschke are copyright (c) 2005-2007 Sebastian
03: * Thomschke.
04: *
05: * All Rights Reserved. This program and the accompanying materials
06: * are made available under the terms of the Eclipse Public License v1.0
07: * which accompanies this distribution, and is available at
08: * http://www.eclipse.org/legal/epl-v10.html
09: *
10: * Contributors:
11: * Sebastian Thomschke - initial implementation.
12: *******************************************************************************/package net.sf.oval.integration.spring;
13:
14: import net.sf.oval.ConstraintViolation;
15: import net.sf.oval.Validator;
16: import net.sf.oval.context.FieldContext;
17: import net.sf.oval.context.OValContext;
18: import net.sf.oval.exception.ValidationFailedException;
19: import net.sf.oval.internal.Log;
20:
21: import org.springframework.beans.factory.InitializingBean;
22: import org.springframework.util.Assert;
23: import org.springframework.validation.Errors;
24:
25: /**
26: * @author Sebastian Thomschke
27: */
28: public class SpringValidator implements
29: org.springframework.validation.Validator, InitializingBean {
30: private final static Log LOG = Log.getLog(SpringValidator.class);
31:
32: private Validator validator;
33:
34: public SpringValidator() {
35: //
36: }
37:
38: public SpringValidator(final Validator validator) {
39: this .validator = validator;
40: }
41:
42: public void afterPropertiesSet() throws Exception {
43: Assert.notNull(validator, "Property [validator] must be set");
44: }
45:
46: /**
47: * @return the validator
48: */
49: public Validator getValidator() {
50: return validator;
51: }
52:
53: /**
54: * @param validator the validator to set
55: */
56: public void setValidator(final Validator validator) {
57: this .validator = validator;
58: }
59:
60: public boolean supports(final Class clazz) {
61: return true;
62: }
63:
64: public void validate(final Object objectToValidate,
65: final Errors errors) {
66: try {
67: for (final ConstraintViolation violation : validator
68: .validate(objectToValidate)) {
69: final OValContext ctx = violation.getContext();
70: final String errorCode = violation.getErrorCode();
71: final String errorMessage = violation.getMessage();
72:
73: if (ctx instanceof FieldContext) {
74: final String fieldName = ((FieldContext) ctx)
75: .getField().getName();
76: errors.rejectValue(fieldName, errorCode,
77: errorMessage);
78: } else {
79: errors.reject(errorCode, errorMessage);
80: }
81: }
82: } catch (final ValidationFailedException ex) {
83: LOG.error("Unexpected error during validation", ex);
84:
85: errors.reject(ex.getMessage());
86: }
87: }
88: }
|