001 /******************************************************************************* 002 * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian 003 * Thomschke. 004 * 005 * All Rights Reserved. This program and the accompanying materials 006 * are made available under the terms of the Eclipse Public License v1.0 007 * which accompanies this distribution, and is available at 008 * http://www.eclipse.org/legal/epl-v10.html 009 * 010 * Contributors: 011 * Sebastian Thomschke - initial implementation. 012 *******************************************************************************/ 013 package net.sf.oval.integration.spring; 014 015 import net.sf.oval.ConstraintViolation; 016 import net.sf.oval.Validator; 017 import net.sf.oval.context.FieldContext; 018 import net.sf.oval.context.OValContext; 019 import net.sf.oval.exception.ValidationFailedException; 020 import net.sf.oval.internal.Log; 021 022 import org.springframework.beans.factory.InitializingBean; 023 import org.springframework.util.Assert; 024 import org.springframework.validation.Errors; 025 026 /** 027 * @author Sebastian Thomschke 028 */ 029 public class SpringValidator implements org.springframework.validation.Validator, InitializingBean 030 { 031 private static final Log LOG = Log.getLog(SpringValidator.class); 032 033 private Validator validator; 034 035 public SpringValidator() 036 { 037 super(); 038 } 039 040 public SpringValidator(final Validator validator) 041 { 042 this.validator = validator; 043 } 044 045 /** 046 * {@inheritDoc} 047 */ 048 public void afterPropertiesSet() throws Exception 049 { 050 Assert.notNull(validator, "Property [validator] must be set"); 051 } 052 053 /** 054 * @return the validator 055 */ 056 public Validator getValidator() 057 { 058 return validator; 059 } 060 061 /** 062 * @param validator the validator to set 063 */ 064 public void setValidator(final Validator validator) 065 { 066 this.validator = validator; 067 } 068 069 /** 070 * {@inheritDoc} 071 */ 072 public boolean supports(@SuppressWarnings("rawtypes") final Class clazz) 073 { 074 return true; 075 } 076 077 /** 078 * {@inheritDoc} 079 */ 080 public void validate(final Object objectToValidate, final Errors errors) 081 { 082 try 083 { 084 for (final ConstraintViolation violation : validator.validate(objectToValidate)) 085 { 086 final OValContext ctx = violation.getContext(); 087 final String errorCode = violation.getErrorCode(); 088 final String errorMessage = violation.getMessage(); 089 090 if (ctx instanceof FieldContext) 091 { 092 final String fieldName = ((FieldContext) ctx).getField().getName(); 093 errors.rejectValue(fieldName, errorCode, errorMessage); 094 } 095 else 096 errors.reject(errorCode, errorMessage); 097 } 098 } 099 catch (final ValidationFailedException ex) 100 { 101 LOG.error("Unexpected error during validation", ex); 102 103 errors.reject(ex.getMessage()); 104 } 105 } 106 }