Author: alexsmirnov
Date: 2009-05-01 18:29:01 -0400 (Fri, 01 May 2009)
New Revision: 13986
Added:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/CompositeColor.java
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/HibernateValidator.java
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/NullValidator.java
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/ObjectValidator.java
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/HibernateValidatorTest.java
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/MockValidationProvider.java
trunk/ui/beanValidator/src/test/resources/
trunk/ui/beanValidator/src/test/resources/META-INF/
trunk/ui/beanValidator/src/test/resources/META-INF/services/
trunk/ui/beanValidator/src/test/resources/META-INF/services/javax.validation.spi.ValidationProvider
Removed:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowBackgroundLeft.java
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterBackground.java
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterLeft.java
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderBackground.java
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderLeft.java
trunk/ui/beanValidator/pom.xml
trunk/ui/beanValidator/src/main/java/org/richfaces/component/UIGraphValidator.java
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/AjaxValidatorHandler.java
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/BeanValidatorTag.java
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/FacesBeanValidator.java
Log:
JSR-3903 BeanValidators support was added.
Added: trunk/samples/themes/src/main/java/org/richfaces/theme/images/CompositeColor.java
===================================================================
--- trunk/samples/themes/src/main/java/org/richfaces/theme/images/CompositeColor.java
(rev 0)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/CompositeColor.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,73 @@
+/**
+ *
+ */
+package org.richfaces.theme.images;
+
+import java.awt.Color;
+
+/**
+ * @author asmirnov
+ *
+ */
+@SuppressWarnings("serial")
+public class CompositeColor extends Color {
+
+ private double mix = 0.0f;
+ private Color shadowColor;
+
+ public CompositeColor(int base, int shadow) {
+ super(base);
+
+ this.shadowColor = new Color(shadow);
+ }
+
+ /**
+ * @return the mix
+ */
+ public double getMix() {
+ return mix;
+ }
+
+ /**
+ * @param mix the mix to set
+ */
+ public void setMix(double mix) {
+ this.mix = mix;
+ }
+
+
+ public Color getMixedColor(){
+ return new Color(getRed(),getGreen(),getBlue(),getAlpha());
+ }
+
+ protected int mix(int from, int to){
+ return (int)((double)from*(1.0-mix)+(double)to*mix);
+ }
+
+
+ @Override
+ public int getRed() {
+ return mix(super.getRed(),shadowColor.getRed());
+ }
+
+ @Override
+ public int getGreen() {
+ return mix(super.getGreen(),shadowColor.getGreen());
+ }
+
+ @Override
+ public int getBlue() {
+ return mix(super.getBlue(),shadowColor.getBlue());
+ }
+
+ @Override
+ public int getAlpha() {
+ return mix(super.getAlpha(),shadowColor.getAlpha());
+ }
+
+ @Override
+ public int getRGB() {
+ // TODO Auto-generated method stub
+ return super.getRGB();
+ }
+}
Property changes on:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/CompositeColor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowBackgroundLeft.java
===================================================================
---
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowBackgroundLeft.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowBackgroundLeft.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -31,9 +31,9 @@
Dimension dimensions = getDimensions(null);
if(null != shadowData.getShadowColor()){
// g2d.setColor(new Color(shadowData.getShadowColor()));
- GradientPaint gragient = new GradientPaint( 2.0f,0.0f, new
Color(shadowData.getShadowColor()&0xffffff,true),(float) MARGIN*2, 0, new
Color(shadowData.getShadowColor()));
+ GradientPaint gragient = new GradientPaint( 0.0f,0.0f, new
Color(shadowData.getShadowColor()&0xffffff,true),(float) MARGIN*2, 0, new
Color(shadowData.getShadowColor()));
g2d.setPaint(gragient);
- g2d.fillRect(2, 0, (int) (MARGIN*2.0), dimensions.height);
+ g2d.fillRect(0, 0, (int) (MARGIN*2.0), dimensions.height);
}
if(null != shadowData.getBorderColor()){
g2d.setColor(new Color(shadowData.getBorderColor()));
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterBackground.java
===================================================================
---
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterBackground.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterBackground.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -31,7 +31,7 @@
if(null != shadowData.getShadowColor()){
g2d.setColor(new Color(shadowData.getShadowColor()));
// g2d.fillRect(0, (int) (dim.height-MARGIN), dim.width, (int) MARGIN);
- GradientPaint gragient = new GradientPaint(0.0f, (float) (dim.getHeight()-2.0f),
new Color(shadowData.getHeaderGradientColor()), 0.0f, (float)(dim.getHeight()-MARGIN*2),
new Color(shadowData.getShadowColor()));
+ GradientPaint gragient = new GradientPaint(0.0f, (float) dim.getHeight(), new
Color(shadowData.getHeaderGradientColor()), 0.0f, (float)(dim.getHeight()-MARGIN*2), new
Color(shadowData.getShadowColor()));
g2d.setPaint(gragient);
g2d.fillRect(0, (int) (dim.height-MARGIN), dim.width, (int) MARGIN);
}
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterLeft.java
===================================================================
---
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterLeft.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowFooterLeft.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -22,8 +22,15 @@
// Shadow
ShadowData shadowData = (ShadowData) data;
if(null != shadowData.getShadowColor()){
- g2d.setColor(new Color(shadowData.getShadowColor()));
- g2d.fillRoundRect(0, -dim.height, dim.width*2,
dim.height*2,SHADOW_RADIUS,SHADOW_RADIUS);
+// g2d.setColor(new Color(shadowData.getShadowColor()));
+// g2d.fillRoundRect(0, -dim.height, dim.width*2,
dim.height*2,SHADOW_RADIUS,SHADOW_RADIUS);
+ CompositeColor color = new
CompositeColor(shadowData.getHeaderGradientColor(),shadowData.getShadowColor());
+ for(int dx=0;dx < MARGIN;dx++){
+ int radius = SHADOW_RADIUS+(int)MARGIN-dx;
+ color.setMix((double)dx/MARGIN/2.0);
+ g2d.setColor(color.getMixedColor());
+ g2d.drawRoundRect(dx, -dx-dim.height-1, dim.width*2, dim.height*2,radius,radius);
+ }
}
g2d.translate(0.0, -MARGIN);
RoundRectangle2D clip = new
RoundRectangle2D.Double(MARGIN,-1.0*dim.getHeight(),dim.getWidth()*2.0,dim.getHeight()*2.0,RADIUS,RADIUS);
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderBackground.java
===================================================================
---
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderBackground.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderBackground.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -27,7 +27,7 @@
ShadowData shadowData = (ShadowData) data;
if(null != shadowData.getShadowColor()){
// g2d.setColor(new Color(shadowData.getHeaderGradientColor()));
- GradientPaint gragient = new GradientPaint(0.0f, 2.0f, new
Color(shadowData.getHeaderGradientColor()), 0, (float) MARGIN*2, new
Color(shadowData.getShadowColor()));
+ GradientPaint gragient = new GradientPaint(0.0f, 0.0f, new
Color(shadowData.getHeaderGradientColor()), 0, (float) MARGIN*2, new
Color(shadowData.getShadowColor()));
g2d.setPaint(gragient);
g2d.fillRect(0, 0, getDimensions(null).width, (int) MARGIN);
}
Modified:
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderLeft.java
===================================================================
---
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderLeft.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/samples/themes/src/main/java/org/richfaces/theme/images/ShadowHeaderLeft.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -22,8 +22,13 @@
Dimension dim = getDimensions(null, data);
ShadowData shadowData = (ShadowData) data;
if(null != shadowData.getShadowColor()){
- g2d.setColor(new Color(shadowData.getShadowColor()));
- g2d.fillRoundRect(0, 0, dim.width*2, dim.height*2,SHADOW_RADIUS,SHADOW_RADIUS);
+ CompositeColor color = new
CompositeColor(shadowData.getHeaderGradientColor(),shadowData.getShadowColor());
+ for(int dx=0;dx < MARGIN;dx++){
+ int radius = SHADOW_RADIUS+(int)MARGIN-dx;
+ color.setMix((double)dx/MARGIN/2.0);
+ g2d.setColor(color.getMixedColor());
+ g2d.drawRoundRect(dx, dx, dim.width*2, dim.height*2,radius,radius);
+ }
}
// Paint gradient itself
g2d.translate(0.0, MARGIN);
Modified: trunk/ui/beanValidator/pom.xml
===================================================================
--- trunk/ui/beanValidator/pom.xml 2009-05-01 12:12:30 UTC (rev 13985)
+++ trunk/ui/beanValidator/pom.xml 2009-05-01 22:29:01 UTC (rev 13986)
@@ -64,7 +64,13 @@
</exclusion>
-->
</exclusions>
+ <optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>javax.validation</groupId>
+ <artifactId>validation-api</artifactId>
+ <version>1.0.CR2</version>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
Modified:
trunk/ui/beanValidator/src/main/java/org/richfaces/component/UIGraphValidator.java
===================================================================
---
trunk/ui/beanValidator/src/main/java/org/richfaces/component/UIGraphValidator.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/component/UIGraphValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -51,7 +51,7 @@
import org.ajax4jsf.renderkit.AjaxContainerRenderer;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.richfaces.event.ValidationEvent;
-import org.richfaces.validator.BeanValidator;
+import org.richfaces.validator.HibernateValidator;
import org.richfaces.validator.FacesBeanValidator;
import org.richfaces.validator.GraphValidator;
Modified:
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/AjaxValidatorHandler.java
===================================================================
---
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/AjaxValidatorHandler.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/AjaxValidatorHandler.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -21,6 +21,7 @@
package org.richfaces.taglib;
import java.io.IOException;
+import java.util.Set;
import javax.el.ELException;
import javax.faces.FacesException;
@@ -29,6 +30,7 @@
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.ajax4jsf.webapp.taglib.AjaxComponentHandler;
import org.richfaces.component.UIBeanValidator;
import org.richfaces.validator.FacesBeanValidator;
@@ -61,6 +63,7 @@
private TagAttribute _event;
private TagAttribute _summary;
+ private TagAttribute _profiles;
private AjaxComponentHandler _validatorHandler;
/**
@@ -70,6 +73,7 @@
super(config);
_event = getAttribute("event");
_summary = getAttribute("summary");
+ _profiles = getAttribute("profiles");
_validatorHandler = new AjaxComponentHandler(config);
}
@@ -93,8 +97,21 @@
.getApplication().createValidator(
FacesBeanValidator.BEAN_VALIDATOR_TYPE);
if (null != _summary) {
- validator.setSummary(_summary.getValueExpression(ctx, String.class));
+ if (_summary.isLiteral()) {
+ validator.setSummary(_summary.getValue(ctx));
+
+ } else {
+ validator.setSummary(_summary.getValueExpression(ctx,
+ String.class));
+ }
}
+ if( null != _profiles){
+ if(_profiles.isLiteral()){
+ validator.setProfiles(AjaxRendererUtils.asSet(_profiles.getValue()));
+ } else {
+ validator.setProfiles(_profiles.getValueExpression(ctx, Set.class));
+ }
+ }
((EditableValueHolder) parent).addValidator(validator);
}
if (null != this._event) {
Modified: trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/BeanValidatorTag.java
===================================================================
---
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/BeanValidatorTag.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/taglib/BeanValidatorTag.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -27,7 +27,7 @@
import javax.faces.validator.Validator;
import javax.servlet.jsp.JspException;
-import org.richfaces.validator.BeanValidator;
+import org.richfaces.validator.HibernateValidator;
import org.richfaces.validator.FacesBeanValidator;
public class BeanValidatorTag extends javax.faces.webapp.ValidatorELTag {
@@ -45,7 +45,7 @@
/**
* <p>The {@link javax.el.ValueExpression} that evaluates to an object that
- * implements {@link BeanValidator}.</p>
+ * implements {@link HibernateValidator}.</p>
*/
private ValueExpression binding = null;
@@ -62,7 +62,7 @@
/**
* <p>Set the expression that will be used to create a
* {@link javax.el.ValueExpression} that references a backing bean property
- * of the {@link BeanValidator} instance to be created.</p>
+ * of the {@link HibernateValidator} instance to be created.</p>
*
* @param binding The new expression
*/
Deleted: trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
===================================================================
---
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -1,578 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-package org.richfaces.validator;
-
-import java.beans.FeatureDescriptor;
-import java.util.Collection;
-import java.util.EmptyStackException;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ResourceBundle;
-import java.util.Set;
-import java.util.Stack;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.el.ELContext;
-import javax.el.ELException;
-import javax.el.ELResolver;
-import javax.el.ValueExpression;
-import javax.faces.FacesException;
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-
-import org.ajax4jsf.el.ELContextWrapper;
-import org.hibernate.validator.ClassValidator;
-import org.hibernate.validator.InvalidValue;
-
-/**
- * Perform validation by Hibernate Validator annotations
- *
- * @author asmirnov
- *
- */
-public class BeanValidator {
-
- private static final String RESOURCE_BUNDLE_IS_NOT_REGISTERED_FOR_CURRENT_LOCALE =
"Resource bundle is not registered for current locale";
-
- private static final String FACES_CONTEXT_IS_NULL = "Faces context is null";
-
- private static final String INPUT_PARAMETERS_IS_NOT_CORRECT = "Input parameters is
not correct.";
-
- private static final String LOCALE_IS_NOT_SET = "Locale is not set";
-
- private static final String VIEW_ROOT_IS_NOT_INITIALIZED = "ViewRoot is not
initialized";
-
- public static final String VALIDATOR_PARAM = BeanValidator.class.getName();
-
- private Map<ValidatorKey, ClassValidator<? extends Object>> classValidators
= new ConcurrentHashMap<ValidatorKey, ClassValidator<? extends Object>>();
-
- private BeanValidator() {
- // This is a "singleton"-like class. Only factory methods allowed.
- }
-
- /**
- * Create BeanValidator instance. For a Junit tests only.
- *
- * @return
- */
- static BeanValidator createInstance() {
- // TODO - get instance class name from a "META-INF/service"
- // If the Seam framework is active, use org.jboss.seam.core.Validators
- // component should be used.
- return new BeanValidator();
- }
-
- private static final Object MUTEX = new Object();
-
- /**
- * Return BeanValidator object from a ServletContext attribute. Create new
- * instance if none is defined.
- *
- * @param context
- * @return
- */
- public static BeanValidator getInstance(FacesContext context) {
- ExternalContext externalContext = context.getExternalContext();
- externalContext.getContext();
- BeanValidator instance;
- // TODO - use properly synchronization mutex ?
- synchronized (MUTEX) {
- Map<String, Object> applicationMap = externalContext
- .getApplicationMap();
- instance = (BeanValidator) applicationMap.get(VALIDATOR_PARAM);
- if (null == instance) {
- // Vaildator not initialized - create and store new instance.
- instance = createInstance();
- applicationMap.put(VALIDATOR_PARAM, instance);
- }
- }
- return instance;
- }
-
- /**
- * Perform Validation for a new value.
- *
- * @param context
- * current faces context.
- * @param target
- * {@link ValueExpression} for a value assignment.
- * @param value
- * new value for validation
- * @return null if no validation errors. Array of the validation messages
- * otherwise.
- * @throws FacesException
- * if locale or context not properly initialized
- */
- public String[] validate(FacesContext context, ValueExpression target,
- Object value) {
- // TODO - check null parameters.
- if (null == context) {
- throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT);
- }
- String[] validationMessages = null;
- if (null != target) {
- ELContext elContext = context.getELContext();
- ValidationResolver validationResolver = createValidationResolver(
- elContext.getELResolver(), calculateLocale(context));
- ELContextWrapper wrappedElContext = new ELContextWrapper(elContext,
- validationResolver);
- // TODO - handle ELExceptions ?
- try {
- target.setValue(wrappedElContext, value);
- } catch (ELException e) {
- throw new FacesException(e);
- }
- if (!validationResolver.isValid()) {
- validationMessages = validationResolver.getValidationMessages();
- }
-
- }
- return validationMessages;
- }
-
- protected Locale calculateLocale(FacesContext context) {
- if (null == context.getViewRoot()) {
- throw new FacesException(VIEW_ROOT_IS_NOT_INITIALIZED);
- } else if (null == context.getViewRoot().getLocale()) {
- throw new FacesException(LOCALE_IS_NOT_SET);
- }
- Locale locale = context.getViewRoot().getLocale();
- return locale;
- }
-
- // Method for checking input parameters for prevent NPE
- private void checkInputParameters(FacesContext context,
- ValueExpression target) {
- if (null == context || null == target) {
- throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT);
- }
- }
-
- /**
- * Validate bean property for a new value. TODO - localization ?
- *
- * @param base
- * - bean
- * @param property
- * - bean property name.
- * @param value
- * new value.
- * @return null for a valid value, array of the validation messages
- * othervise.
- */
- public String[] validate(Object base, String property, Object value,
- Locale locale) {
- InvalidValue[] invalidValues = validateBean(base, property, value,
- locale);
- if (null == invalidValues) {
- return null;
- } else {
- String[] result = new String[invalidValues.length];
- for (int i = 0; i < invalidValues.length; i++) {
- InvalidValue invalidValue = invalidValues[i];
- result[i] = invalidValue.getMessage();
- }
- return result;
- }
- }
-
- @SuppressWarnings("unchecked")
- public String[] validateGraph(FacesContext context, Object value,
- Set<String> profiles) {
- if (null == context) {
- throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT);
- }
- String validationMessages[] = null;
- if (null != value) {
- ClassValidator<Object> validator = (ClassValidator<Object>) getValidator(
- value.getClass(), calculateLocale(context));
- if (validator.hasValidationRules()) {
- InvalidValue[] invalidValues = validator
- .getInvalidValues(value);
- if (null != invalidValues && invalidValues.length > 0) {
- validationMessages = new String[invalidValues.length];
- for (int i = 0; i < invalidValues.length; i++) {
- InvalidValue invalidValue = invalidValues[i];
- validationMessages[i] = invalidValue.getMessage();
- }
- }
- }
-
- }
- return validationMessages;
- }
-
- /**
- * Validate bean property of the base object aganist new value
- *
- * @param base
- * @param property
- * @param value
- * @return
- */
- protected InvalidValue[] validateBean(Object base, String property,
- Object value, Locale locale) {
- Class<? extends Object> beanClass = base.getClass();
- InvalidValue[] invalidValues = validateClass(beanClass, property,
- value, locale);
- return invalidValues;
- }
-
- /**
- * Validate bean property in the base class aganist new value.
- *
- * @param beanClass
- * @param property
- * @param value
- * @return
- */
- protected InvalidValue[] validateClass(Class<? extends Object> beanClass,
- String property, Object value, Locale locale) {
- ClassValidator<? extends Object> classValidator = getValidator(
- beanClass, locale);
- InvalidValue[] invalidValues = classValidator
- .getPotentialInvalidValues(property, value);
- return invalidValues;
- }
-
- /**
- * Get ( or create ) {@link ClassValidator} for a given bean class.
- *
- * @param beanClass
- * @return
- */
- @SuppressWarnings("unchecked")
- protected ClassValidator<? extends Object> getValidator(
- Class<? extends Object> beanClass, Locale locale) {
- // TODO - localization support.
- ValidatorKey key = new ValidatorKey(beanClass, locale);
- ClassValidator result = classValidators.get(key);
- if (null == result) {
- result = createValidator(beanClass, locale);
- classValidators.put(key, result);
- }
- return result;
- }
-
- /*
- * This method determine ResourceBundle, used in current request @param
- * locale - user locale @return ResourceBundle instance
- */
- protected ResourceBundle getCurrentResourceBundle(Locale locale) {
- if (null == FacesContext.getCurrentInstance()
- || null == FacesContext.getCurrentInstance().getApplication()) {
- throw new FacesException(FACES_CONTEXT_IS_NULL);
- }
- String appBundle = FacesContext.getCurrentInstance().getApplication()
- .getMessageBundle();
- if (null == appBundle || null == locale) {
- return null;
- }
-
- ResourceBundle bundle;
-
- ClassLoader classLoader = Thread.currentThread()
- .getContextClassLoader();
- if (classLoader != null) {
- bundle = ResourceBundle.getBundle(appBundle, locale, classLoader);
- } else {
- bundle = ResourceBundle.getBundle(appBundle, locale);
- }
-
- return bundle;
- }
-
- /*
- * Method for create new instance of ClassValidator, if same not in cache.
- *
- * @param beanClass - Class to validate @param locale - user Locale, used
- * during validation process @return ClassValidator instance
- */
- @SuppressWarnings("unchecked")
- protected ClassValidator<? extends Object> createValidator(
- Class<? extends Object> beanClass, Locale locale) {
- ResourceBundle bundle = getCurrentResourceBundle(locale);
- return bundle == null ? new ClassValidator(beanClass)
- : new ClassValidator(beanClass, bundle);
- }
-
-
- protected ValidationResolver createValidationResolver(ELResolver parent, Locale locale)
{
- return new ValidationResolver(parent,locale);
- }
- /**
- * Wrapper class for a {@link ELResolver}. For a setValue method, perform
- * validation instead of real assignment.
- *
- * @author asmirnov
- *
- */
- final class ValidationResolver extends ELResolver {
-
- /**
- * Original resolver.
- */
- private final ELResolver parent;
-
- private boolean valid = true;
-
- private String[] validationMessages = null;
-
- private Locale locale = null;
-
- private Stack<BasePropertyPair> valuesStack;
-
- /**
- * @param parent
- */
- public ValidationResolver(ELResolver parent, Locale locale) {
- this.parent = parent;
- this.locale = locale;
- this.valuesStack = new Stack<BasePropertyPair>();
- }
-
- public boolean isValid() {
- // TODO Auto-generated method stub
- return valid;
- }
-
- /**
- * @param context
- * @param base
- * @return
- * @see javax.el.ELResolver#getCommonPropertyType(javax.el.ELContext,
- * java.lang.Object)
- */
- public Class<?> getCommonPropertyType(ELContext context, Object base) {
- return parent.getCommonPropertyType(context, base);
- }
-
- /**
- * @param context
- * @param base
- * @return
- * @see javax.el.ELResolver#getFeatureDescriptors(javax.el.ELContext,
- * java.lang.Object)
- */
- public Iterator<FeatureDescriptor> getFeatureDescriptors(
- ELContext context, Object base) {
- return parent.getFeatureDescriptors(context, base);
- }
-
- /**
- * @param context
- * @param base
- * @param property
- * @return
- * @see javax.el.ELResolver#getType(javax.el.ELContext,
- * java.lang.Object, java.lang.Object)
- */
- public Class<?> getType(ELContext context, Object base, Object property) {
- return parent.getType(context, base, property);
- }
-
- /**
- * @param context
- * @param base
- * @param property
- * @return
- * @see javax.el.ELResolver#getValue(javax.el.ELContext,
- * java.lang.Object, java.lang.Object)
- */
- public Object getValue(ELContext context, Object base, Object property) {
- Object value = parent.getValue(context, base, property);
- valuesStack.push(new BasePropertyPair(base, property));
- return value;
- }
-
- /**
- * @param context
- * @param base
- * @param property
- * @return
- * @see javax.el.ELResolver#isReadOnly(javax.el.ELContext,
- * java.lang.Object, java.lang.Object)
- */
- public boolean isReadOnly(ELContext context, Object base,
- Object property) {
- return parent.isReadOnly(context, base, property);
- }
-
- /**
- * @param context
- * @param base
- * @param property
- * @param value
- * @see javax.el.ELResolver#setValue(javax.el.ELContext,
- * java.lang.Object, java.lang.Object, java.lang.Object)
- */
- public void setValue(ELContext context, Object base, Object property,
- Object value) {
- if (null != base && null != property) {
- context.setPropertyResolved(true);
- // For Arrays, Collection or Map use parent base and property.
- BasePropertyPair basePropertyPair = lookupBeanProperty(new BasePropertyPair(
- base, property));
- base = basePropertyPair.getBase();
- property = basePropertyPair.getProperty();
- if (null != base && null != property) {
- //
https://jira.jboss.org/jira/browse/RF-4034
- // apache el looses locale information during value
- // resolution,
- // so we use our own
- validationMessages = validate(base, property.toString(),
- value, locale);
- valid = null == validationMessages
- || 0 == validationMessages.length;
-
- }
- }
- }
-
- private BasePropertyPair lookupBeanProperty(BasePropertyPair pair) {
- Object base = pair.getBase();
- if (null != base
- && (base instanceof Collection || base instanceof Map || base
- .getClass().isArray())) {
- try {
- pair = lookupBeanProperty(valuesStack.pop());
- } catch (EmptyStackException e) {
- // Do nothing, this is a first item.
- }
- }
- return pair;
- }
-
- /**
- * @return the validationMessages
- */
- public String[] getValidationMessages() {
- return validationMessages;
- }
-
- }
-
- /**
- * @author asmirnov
- *
- */
- static class BasePropertyPair {
- private final Object base;
- private final Object property;
-
- /**
- * @param base
- * @param property
- */
- public BasePropertyPair(Object base, Object property) {
- this.base = base;
- this.property = property;
- }
-
- /**
- * @return the base
- */
- public Object getBase() {
- return base;
- }
-
- /**
- * @return the property
- */
- public Object getProperty() {
- return property;
- }
-
- }
-
- /**
- * Class for identify validator instance by locale
- *
- * @author amarkhel
- *
- */
- static class ValidatorKey {
- private final Class<? extends Object> validatableClass;
- private final Locale locale;
-
- /**
- * Constructor for ValidatorKey object
- *
- * @param validatableClass
- * - class to validate
- * @param locale
- * - User locale to determine Resource bundle, used during
- * validation process
- */
- public ValidatorKey(Class<? extends Object> validatableClass,
- Locale locale) {
- this.validatableClass = validatableClass;
- this.locale = locale;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((locale == null) ? 0 : locale.hashCode());
- result = prime
- * result
- + ((validatableClass == null) ? 0 : validatableClass
- .hashCode());
- return result;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (!(obj instanceof ValidatorKey))
- return false;
- ValidatorKey other = (ValidatorKey) obj;
- if (locale == null) {
- if (other.locale != null)
- return false;
- } else if (!locale.equals(other.locale))
- return false;
- if (validatableClass == null) {
- if (other.validatableClass != null)
- return false;
- } else if (!validatableClass.equals(other.validatableClass))
- return false;
- return true;
- }
-
- }
-}
Added: trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
===================================================================
--- trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
(rev 0)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,147 @@
+/**
+ *
+ */
+package org.richfaces.validator;
+
+import java.util.Locale;
+import java.util.Set;
+
+import javax.faces.FacesException;
+import javax.faces.context.FacesContext;
+import javax.validation.ConstraintViolation;
+import javax.validation.MessageInterpolator;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+import javax.validation.ValidatorFactory;
+
+/**
+ * @author asmirnov
+ *
+ */
+public class BeanValidator extends ObjectValidator {
+
+ private volatile ValidatorFactory validatorFactory = null;
+
+ BeanValidator() {
+ // Enforce class to load
+ ValidatorFactory.class.getName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.richfaces.validator.ObjectValidator#validate(java.lang.Object,
+ * java.lang.String, java.lang.Object, java.util.Locale)
+ */
+ @Override
+ protected String[] validate(Object base, String property, Object value,
+ Locale locale, Set<String> profiles) {
+ return extractMessages(getValidator(locale).validateProperty(base,
+ property, getGroups(profiles)));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.richfaces.validator.ObjectValidator#validateGraph(javax.faces.context
+ * .FacesContext, java.lang.Object, java.util.Set)
+ */
+ @Override
+ public String[] validateGraph(FacesContext context, Object value,
+ Set<String> profiles) {
+ Class<?>[] groups = getGroups(profiles);
+ Set<ConstraintViolation<Object>> violations = getValidator(
+ calculateLocale(context)).validate(value, groups);
+ String[] messages = extractMessages(violations);
+ return messages;
+ }
+
+ private Class<?>[] getGroups(Set<String> profiles) {
+ Class<?> groups[] = null;
+ if (null != profiles) {
+ groups = new Class<?>[profiles.size()];
+ int i = 0;
+ for (String group : profiles) {
+ try {
+ groups[i] = Class.forName(group, false, Thread
+ .currentThread().getContextClassLoader());
+ } catch (ClassNotFoundException e) {
+ try {
+ groups[i] = Class.forName(group);
+ } catch (ClassNotFoundException e1) {
+ throw new FacesException(
+ "Bean validation group not found " + group, e1);
+ }
+ }
+ i++;
+ }
+
+ }
+ return groups;
+ }
+
+ private String[] extractMessages(Set<ConstraintViolation<Object>>
violations) {
+ String[] messages = null;
+ if (null != violations && violations.size() > 0) {
+ messages = new String[violations.size()];
+ int i = 0;
+ for (ConstraintViolation<Object> constraintViolation : violations) {
+ messages[i++] = constraintViolation.getMessage();
+ }
+
+ }
+ return messages;
+ }
+
+ protected Validator getValidator(Locale locale) {
+ validatorFactory = null;
+ if (null == validatorFactory) {
+ synchronized (this) {
+ if (null == validatorFactory) {
+ try {
+ validatorFactory = Validation
+ .buildDefaultValidatorFactory();
+ } catch (ValidationException e) {
+ throw new FacesException(
+ "Could not build a default Bean Validator factory",
+ e);
+ }
+
+ }
+ }
+ }
+
+ ValidatorContext validatorContext = validatorFactory.usingContext();
+ MessageInterpolator jsfMessageInterpolator = new JsfMessageInterpolator(
+ locale, validatorFactory.getMessageInterpolator());
+ validatorContext.messageInterpolator(jsfMessageInterpolator);
+ Validator beanValidator = validatorContext.getValidator();
+ return beanValidator;
+ }
+
+ private static class JsfMessageInterpolator implements MessageInterpolator {
+
+ private Locale locale;
+ private MessageInterpolator delegate;
+
+ public JsfMessageInterpolator(Locale locale,
+ MessageInterpolator delegate) {
+ this.locale = locale;
+ this.delegate = delegate;
+ }
+
+ public String interpolate(String messageTemplate, Context context) {
+ return delegate.interpolate(messageTemplate, context, this.locale);
+ }
+
+ public String interpolate(String messageTemplate, Context context,
+ Locale locale) {
+ return delegate.interpolate(messageTemplate, context, locale);
+ }
+
+ }
+
+}
Property changes on:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/FacesBeanValidator.java
===================================================================
---
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/FacesBeanValidator.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/FacesBeanValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -48,18 +48,22 @@
private static final long serialVersionUID = -264568176252121853L;
public static final String BEAN_VALIDATOR_TYPE =
"org.richfaces.BeanValidator";
- private ValueExpression summary = null;
+ private ValueExpression summaryExpression = null;
- private String summaryString = null;
+ private String summary = null;
+
+ private ValueExpression profilesExpression = null;
+
+ private Set<String> profiles = null;
/**
* @return the summary
*/
public String getSummary() {
String summaryString = null;
- if(null != summary){
- summaryString = (String)
summary.getValue(FacesContext.getCurrentInstance().getELContext());
+ if(null != summaryExpression){
+ summaryString = (String)
summaryExpression.getValue(FacesContext.getCurrentInstance().getELContext());
}else {
- summaryString = this.summaryString;
+ summaryString = this.summary;
}
return summaryString;
}
@@ -68,7 +72,7 @@
* @param summary the summary to set
*/
public void setSummary(ValueExpression summary) {
- this.summary = summary;
+ this.summaryExpression = summary;
}
@@ -76,7 +80,7 @@
* @param summary the summary to set
*/
public void setSummary(String summary) {
- this.summaryString = summary;
+ this.summary = summary;
}
/*
* (non-Javadoc)
@@ -94,8 +98,8 @@
.getValueExpression("value");
if (null != valueExpression) {
// TODO - check EL Exceptions ?
- String[] messages = BeanValidator.getInstance(context)
- .validate(context, valueExpression, convertedValue);
+ String[] messages = HibernateValidator.getInstance(context)
+ .validate(context, valueExpression, convertedValue, getProfiles());
if (null != messages) {
input.setValid(false);
// send all validation messages.
@@ -116,8 +120,33 @@
public String[] validateGraph(FacesContext context, UIComponent component,
Object value, Set<String> profiles) throws ValidatorException {
- BeanValidator beanValidator = BeanValidator.getInstance(context);
+ ObjectValidator beanValidator = HibernateValidator.getInstance(context);
String[] messages = beanValidator.validateGraph(context, value,profiles);
return messages;
}
+
+ /**
+ * @return the profiles
+ */
+ @SuppressWarnings("unchecked")
+ public Set<String> getProfiles() {
+ Set<String> profiles;
+ if(null != profilesExpression){
+ profiles = (Set<String>)
profilesExpression.getValue(FacesContext.getCurrentInstance().getELContext());
+ }else {
+ profiles = this.profiles;
+ }
+ return profiles;
+ }
+
+ /**
+ * @param profiles the profiles to set
+ */
+ public void setProfiles(Set<String> profiles) {
+ this.profiles = profiles;
+ }
+
+ public void setProfiles(ValueExpression profilesExpression) {
+ this.profilesExpression = profilesExpression;
+ }
}
Copied:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/HibernateValidator.java (from
rev 13985,
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/BeanValidator.java)
===================================================================
--- trunk/ui/beanValidator/src/main/java/org/richfaces/validator/HibernateValidator.java
(rev 0)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/HibernateValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,168 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+package org.richfaces.validator;
+
+import java.beans.FeatureDescriptor;
+import java.util.Collection;
+import java.util.EmptyStackException;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.Stack;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.el.ELResolver;
+import javax.faces.FacesException;
+import javax.faces.context.FacesContext;
+
+import org.hibernate.validator.ClassValidator;
+import org.hibernate.validator.InvalidValue;
+
+/**
+ * Perform validation by Hibernate Validator annotations
+ *
+ * @author asmirnov
+ *
+ */
+public class HibernateValidator extends ObjectValidator {
+
+ private Map<ValidatorKey, ClassValidator<? extends Object>> classValidators
= new ConcurrentHashMap<ValidatorKey, ClassValidator<? extends Object>>();
+
+ HibernateValidator() {
+ // This is a "singleton"-like class. Only factory methods allowed.
+ // Enforce class to load
+ ClassValidator.class.getName();
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public String[] validateGraph(FacesContext context, Object value,
+ Set<String> profiles) {
+ if (null == context) {
+ throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT);
+ }
+ String validationMessages[] = null;
+ if (null != value) {
+ ClassValidator<Object> validator = (ClassValidator<Object>) getValidator(
+ value.getClass(), calculateLocale(context));
+ if (validator.hasValidationRules()) {
+ InvalidValue[] invalidValues = validator
+ .getInvalidValues(value);
+ if (null != invalidValues && invalidValues.length > 0) {
+ validationMessages = new String[invalidValues.length];
+ for (int i = 0; i < invalidValues.length; i++) {
+ InvalidValue invalidValue = invalidValues[i];
+ validationMessages[i] = invalidValue.getMessage();
+ }
+ }
+ }
+
+ }
+ return validationMessages;
+ }
+
+ /**
+ * Validate bean property in the base class aganist new value.
+ *
+ * @param beanClass
+ * @param property
+ * @param value
+ * @return
+ */
+ protected InvalidValue[] validateClass(Class<? extends Object> beanClass,
+ String property, Object value, Locale locale) {
+ ClassValidator<? extends Object> classValidator = getValidator(
+ beanClass, locale);
+ InvalidValue[] invalidValues = classValidator
+ .getPotentialInvalidValues(property, value);
+ return invalidValues;
+ }
+
+ /**
+ * Get ( or create ) {@link ClassValidator} for a given bean class.
+ *
+ * @param beanClass
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ protected ClassValidator<? extends Object> getValidator(
+ Class<? extends Object> beanClass, Locale locale) {
+ // TODO - localization support.
+ ValidatorKey key = new ValidatorKey(beanClass, locale);
+ ClassValidator result = classValidators.get(key);
+ if (null == result) {
+ result = createValidator(beanClass, locale);
+ classValidators.put(key, result);
+ }
+ return result;
+ }
+
+ /*
+ * Method for create new instance of ClassValidator, if same not in cache.
+ *
+ * @param beanClass - Class to validate @param locale - user Locale, used
+ * during validation process @return ClassValidator instance
+ */
+ @SuppressWarnings("unchecked")
+ protected ClassValidator<? extends Object> createValidator(
+ Class<? extends Object> beanClass, Locale locale) {
+ ResourceBundle bundle = getCurrentResourceBundle(locale);
+ return bundle == null ? new ClassValidator(beanClass)
+ : new ClassValidator(beanClass, bundle);
+ }
+
+ @Override
+ protected String[] validate(Object base, String property, Object value,
+ Locale locale, Set<String> profiles) {
+ InvalidValue[] invalidValues = validateBean(base, property, value,
+ locale);
+ if (null == invalidValues) {
+ return null;
+ } else {
+ String[] result = new String[invalidValues.length];
+ for (int i = 0; i < invalidValues.length; i++) {
+ InvalidValue invalidValue = invalidValues[i];
+ result[i] = invalidValue.getMessage();
+ }
+ return result;
+ }
+ }
+
+ /**
+ * Validate bean property of the base object aganist new value
+ *
+ * @param base
+ * @param property
+ * @param value
+ * @return
+ */
+ protected InvalidValue[] validateBean(Object base, String property, Object value,
+ Locale locale) {
+ Class<? extends Object> beanClass = base.getClass();
+ InvalidValue[] invalidValues = validateClass(beanClass, property,
+ value, locale);
+ return invalidValues;
+ }
+
+
+}
Added: trunk/ui/beanValidator/src/main/java/org/richfaces/validator/NullValidator.java
===================================================================
--- trunk/ui/beanValidator/src/main/java/org/richfaces/validator/NullValidator.java
(rev 0)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/NullValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,37 @@
+/**
+ *
+ */
+package org.richfaces.validator;
+
+import java.util.Locale;
+import java.util.Set;
+
+import javax.faces.context.FacesContext;
+
+/**
+ * @author asmirnov
+ *
+ */
+public class NullValidator extends ObjectValidator {
+
+ /* (non-Javadoc)
+ * @see org.richfaces.validator.ObjectValidator#validate(java.lang.Object,
java.lang.String, java.lang.Object, java.util.Locale)
+ */
+ @Override
+ protected String[] validate(Object base, String property, Object value,
+ Locale locale, Set<String> profiles) {
+ // do nothing.
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see
org.richfaces.validator.ObjectValidator#validateGraph(javax.faces.context.FacesContext,
java.lang.Object, java.util.Set)
+ */
+ @Override
+ public String[] validateGraph(FacesContext context, Object value,
+ Set<String> profiles) {
+ // do nothing
+ return null;
+ }
+
+}
Property changes on:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/NullValidator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/ui/beanValidator/src/main/java/org/richfaces/validator/ObjectValidator.java
===================================================================
--- trunk/ui/beanValidator/src/main/java/org/richfaces/validator/ObjectValidator.java
(rev 0)
+++
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/ObjectValidator.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,443 @@
+package org.richfaces.validator;
+
+import java.beans.FeatureDescriptor;
+import java.util.Collection;
+import java.util.EmptyStackException;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.Stack;
+
+import javax.el.ELContext;
+import javax.el.ELException;
+import javax.el.ELResolver;
+import javax.el.ValueExpression;
+import javax.faces.FacesException;
+import javax.faces.context.ExternalContext;
+import javax.faces.context.FacesContext;
+
+import org.ajax4jsf.el.ELContextWrapper;
+
+public abstract class ObjectValidator {
+
+ private static final String RESOURCE_BUNDLE_IS_NOT_REGISTERED_FOR_CURRENT_LOCALE =
"Resource bundle is not registered for current locale";
+
+ private static final String FACES_CONTEXT_IS_NULL = "Faces context is null";
+ protected static final String INPUT_PARAMETERS_IS_NOT_CORRECT = "Input parameters
is not correct.";
+ private static final String LOCALE_IS_NOT_SET = "Locale is not set";
+ private static final String VIEW_ROOT_IS_NOT_INITIALIZED = "ViewRoot is not
initialized";
+ public static final String VALIDATOR_PARAM = HibernateValidator.class
+ .getName();
+
+ private static final Object MUTEX = new Object();
+
+ /**
+ * Create BeanValidator instance. For a Junit tests only.
+ *
+ * @return
+ */
+ protected static ObjectValidator createInstance() {
+ // TODO - get instance class name from a "META-INF/service"
+ // If the Seam framework is active, org.jboss.seam.core.Validators
+ // component should be used.
+ ObjectValidator validator;
+ try {
+ validator = new BeanValidator();
+
+ } catch (NoClassDefFoundError e) {
+ try {
+ validator = new HibernateValidator();
+
+ } catch (NoClassDefFoundError e2) {
+ validator = new NullValidator();
+ }
+ }
+ return validator;
+ }
+
+ /**
+ * Return BeanValidator object from a ServletContext attribute. Create new
+ * instance if none is defined.
+ *
+ * @param context
+ * @return
+ */
+ public static ObjectValidator getInstance(FacesContext context) {
+ ExternalContext externalContext = context.getExternalContext();
+ externalContext.getContext();
+ ObjectValidator instance;
+ // TODO - use properly synchronization mutex ?
+ synchronized (MUTEX) {
+ Map<String, Object> applicationMap = externalContext
+ .getApplicationMap();
+ instance = (ObjectValidator) applicationMap.get(VALIDATOR_PARAM);
+ if (null == instance) {
+ // Vaildator not initialized - create and store new instance.
+ instance = createInstance();
+ applicationMap.put(VALIDATOR_PARAM, instance);
+ }
+ }
+ return instance;
+ }
+
+ public abstract String[] validateGraph(FacesContext context, Object value,
+ Set<String> profiles);
+
+ /**
+ * Perform Validation for a new value.
+ *
+ * @param context
+ * current faces context.
+ * @param target
+ * {@link ValueExpression} for a value assignment.
+ * @param value
+ * new value for validation
+ * @param profiles TODO
+ * @return null if no validation errors. Array of the validation messages
+ * otherwise.
+ * @throws FacesException
+ * if locale or context not properly initialized
+ */
+ public String[] validate(FacesContext context, ValueExpression target,
+ Object value, Set<String> profiles) {
+ if (null == context) {
+ throw new FacesException(INPUT_PARAMETERS_IS_NOT_CORRECT);
+ }
+ String[] validationMessages = null;
+ if (null != target) {
+ ELContext elContext = context.getELContext();
+ ValidationResolver validationResolver = createValidationResolver(
+ elContext.getELResolver(), calculateLocale(context),profiles);
+ ELContextWrapper wrappedElContext = new ELContextWrapper(elContext,
+ validationResolver);
+ // TODO - handle ELExceptions ?
+ try {
+ target.setValue(wrappedElContext, value);
+ } catch (ELException e) {
+ throw new FacesException(e);
+ }
+ if (!validationResolver.isValid()) {
+ validationMessages = validationResolver.getValidationMessages();
+ }
+
+ }
+ return validationMessages;
+ }
+
+ protected Locale calculateLocale(FacesContext context) {
+ if (null == context.getViewRoot()) {
+ throw new FacesException(VIEW_ROOT_IS_NOT_INITIALIZED);
+ } else if (null == context.getViewRoot().getLocale()) {
+ throw new FacesException(LOCALE_IS_NOT_SET);
+ }
+ Locale locale = context.getViewRoot().getLocale();
+ return locale;
+ }
+
+ /**
+ * Validate bean property for a new value.
+ *
+ * @param base
+ * - bean
+ * @param property
+ * - bean property name.
+ * @param value
+ * new value.
+ * @param profiles TODO
+ * @return null for a valid value, array of the validation messages
+ * othervise.
+ */
+ protected abstract String[] validate(Object base, String property,
+ Object value, Locale locale, Set<String> profiles);
+
+ protected ResourceBundle getCurrentResourceBundle(Locale locale) {
+ if (null == FacesContext.getCurrentInstance()
+ || null == FacesContext.getCurrentInstance().getApplication()) {
+ throw new FacesException(FACES_CONTEXT_IS_NULL);
+ }
+ String appBundle = FacesContext.getCurrentInstance().getApplication()
+ .getMessageBundle();
+ if (null == appBundle || null == locale) {
+ return null;
+ }
+
+ ResourceBundle bundle;
+
+ ClassLoader classLoader = Thread.currentThread()
+ .getContextClassLoader();
+ if (classLoader != null) {
+ bundle = ResourceBundle.getBundle(appBundle, locale, classLoader);
+ } else {
+ bundle = ResourceBundle.getBundle(appBundle, locale);
+ }
+
+ return bundle;
+ }
+
+ protected ValidationResolver createValidationResolver(ELResolver parent,
+ Locale locale, Set<String> profiles) {
+ return new ValidationResolver(parent, locale, profiles);
+ }
+
+ /**
+ * @author asmirnov
+ *
+ */
+ protected static class BasePropertyPair {
+ private final Object base;
+ private final Object property;
+
+ /**
+ * @param base
+ * @param property
+ */
+ public BasePropertyPair(Object base, Object property) {
+ this.base = base;
+ this.property = property;
+ }
+
+ /**
+ * @return the base
+ */
+ public Object getBase() {
+ return base;
+ }
+
+ /**
+ * @return the property
+ */
+ public Object getProperty() {
+ return property;
+ }
+
+ }
+
+ /**
+ * Class for identify validator instance by locale
+ *
+ * @author amarkhel
+ *
+ */
+ protected static class ValidatorKey {
+ private final Class<? extends Object> validatableClass;
+ private final Locale locale;
+
+ /**
+ * Constructor for ValidatorKey object
+ *
+ * @param validatableClass
+ * - class to validate
+ * @param locale
+ * - User locale to determine Resource bundle, used during
+ * validation process
+ */
+ public ValidatorKey(Class<? extends Object> validatableClass,
+ Locale locale) {
+ this.validatableClass = validatableClass;
+ this.locale = locale;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((locale == null) ? 0 : locale.hashCode());
+ result = prime
+ * result
+ + ((validatableClass == null) ? 0 : validatableClass
+ .hashCode());
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ValidatorKey))
+ return false;
+ ValidatorKey other = (ValidatorKey) obj;
+ if (locale == null) {
+ if (other.locale != null)
+ return false;
+ } else if (!locale.equals(other.locale))
+ return false;
+ if (validatableClass == null) {
+ if (other.validatableClass != null)
+ return false;
+ } else if (!validatableClass.equals(other.validatableClass))
+ return false;
+ return true;
+ }
+
+ }
+
+ /**
+ * Wrapper class for a {@link ELResolver}. For a setValue method, perform
+ * validation instead of real assignment.
+ *
+ * @author asmirnov
+ *
+ */
+ final class ValidationResolver extends ELResolver {
+
+ /**
+ * Original resolver.
+ */
+ private final ELResolver parent;
+
+ private boolean valid = true;
+
+ private String[] validationMessages = null;
+
+ private Locale locale = null;
+
+ private Stack<BasePropertyPair> valuesStack;
+
+ private Set<String> profiles;
+
+ /**
+ * @param parent
+ */
+ public ValidationResolver(ELResolver parent, Locale locale,Set<String> profiles)
{
+ this.parent = parent;
+ this.locale = locale;
+ this.valuesStack = new Stack<BasePropertyPair>();
+ this.profiles = profiles;
+ }
+
+ public boolean isValid() {
+ return valid;
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @return
+ * @see javax.el.ELResolver#getCommonPropertyType(javax.el.ELContext,
+ * java.lang.Object)
+ */
+ public Class<?> getCommonPropertyType(ELContext context, Object base) {
+ return parent.getCommonPropertyType(context, base);
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @return
+ * @see javax.el.ELResolver#getFeatureDescriptors(javax.el.ELContext,
+ * java.lang.Object)
+ */
+ public Iterator<FeatureDescriptor> getFeatureDescriptors(
+ ELContext context, Object base) {
+ return parent.getFeatureDescriptors(context, base);
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @param property
+ * @return
+ * @see javax.el.ELResolver#getType(javax.el.ELContext,
+ * java.lang.Object, java.lang.Object)
+ */
+ public Class<?> getType(ELContext context, Object base, Object property) {
+ return parent.getType(context, base, property);
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @param property
+ * @return
+ * @see javax.el.ELResolver#getValue(javax.el.ELContext,
+ * java.lang.Object, java.lang.Object)
+ */
+ public Object getValue(ELContext context, Object base, Object property) {
+ Object value = parent.getValue(context, base, property);
+ valuesStack.push(new BasePropertyPair(base, property));
+ return value;
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @param property
+ * @return
+ * @see javax.el.ELResolver#isReadOnly(javax.el.ELContext,
+ * java.lang.Object, java.lang.Object)
+ */
+ public boolean isReadOnly(ELContext context, Object base,
+ Object property) {
+ return parent.isReadOnly(context, base, property);
+ }
+
+ /**
+ * @param context
+ * @param base
+ * @param property
+ * @param value
+ * @see javax.el.ELResolver#setValue(javax.el.ELContext,
+ * java.lang.Object, java.lang.Object, java.lang.Object)
+ */
+ public void setValue(ELContext context, Object base, Object property,
+ Object value) {
+ if (null != base && null != property) {
+ context.setPropertyResolved(true);
+ // For Arrays, Collection or Map use parent base and property.
+ BasePropertyPair basePropertyPair = lookupBeanProperty(new BasePropertyPair(
+ base, property));
+ base = basePropertyPair.getBase();
+ property = basePropertyPair.getProperty();
+ if (null != base && null != property) {
+ //
https://jira.jboss.org/jira/browse/RF-4034
+ // apache el looses locale information during value
+ // resolution,
+ // so we use our own
+ validationMessages = validate(base, property.toString(),
+ value, locale, profiles);
+ valid = null == validationMessages
+ || 0 == validationMessages.length;
+
+ }
+ }
+ }
+
+ private BasePropertyPair lookupBeanProperty(BasePropertyPair pair) {
+ Object base = pair.getBase();
+ if (null != base
+ && (base instanceof Collection || base instanceof Map || base
+ .getClass().isArray())) {
+ try {
+ pair = lookupBeanProperty(valuesStack.pop());
+ } catch (EmptyStackException e) {
+ // Do nothing, this is a first item.
+ }
+ }
+ return pair;
+ }
+
+ /**
+ * @return the validationMessages
+ */
+ public String[] getValidationMessages() {
+ return validationMessages;
+ }
+
+ }
+
+}
\ No newline at end of file
Property changes on:
trunk/ui/beanValidator/src/main/java/org/richfaces/validator/ObjectValidator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java
===================================================================
---
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java 2009-05-01
12:12:30 UTC (rev 13985)
+++
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -1,132 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-package org.richfaces.validator;
-
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.ResourceBundle;
-
-import org.ajax4jsf.el.ELContextWrapper;
-import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
-import org.hibernate.validator.ClassValidator;
-import org.hibernate.validator.InvalidValue;
-import org.richfaces.validator.BeanValidator.ValidationResolver;
-
-public class BeanValidatorTest extends AbstractAjax4JsfTestCase {
-
- public BeanValidatorTest(String name) {
- super(name);
- }
-
- public void testValidate() {
-
- }
-
- public void setUp() throws Exception {
- super.setUp();
- }
-
- public void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testGetValidator() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- ClassValidator<? extends Object> validator =
beanValidator.getValidator(ValidableBean.class,Locale.ENGLISH);
- assertNotNull(validator);
- assertTrue(validator.hasValidationRules());
- validator = beanValidator.getValidator(String.class,Locale.getDefault());
- assertNotNull(validator);
- assertFalse(validator.hasValidationRules());
- }
-
- public void testValidateClass() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- InvalidValue[] invalidValues = beanValidator.validateClass(ValidableBean.class,
"integerProperty", new Integer(3),Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(0, invalidValues.length);
- invalidValues = beanValidator.validateClass(ValidableBean.class,
"integerProperty", new Integer(-1),Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(1, invalidValues.length);
- invalidValues = beanValidator.validateClass(UnValidableBean.class,
"integerProperty", new Integer(-1),Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(0, invalidValues.length);
- invalidValues = beanValidator.validateClass(ValidableBean.class,
"nonExistentProperty", new Integer(-1),Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(0, invalidValues.length);
-
- }
-
- public void testValidateBean() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"integerProperty", new Integer(-1),Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(1, invalidValues.length);
- }
-
- public void testValidateArray() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"array", "",Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(2, invalidValues.length);
- System.out.println(invalidValues[0].getMessage());
- System.out.println(invalidValues[1].getMessage());
- }
-
- public void testValidateList() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"list", "",Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(1, invalidValues.length);
- System.out.println(invalidValues[0].getMessage());
- }
- public void testValidateMap() throws Exception {
- BeanValidator beanValidator = BeanValidator.createInstance();
- InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"map", "",Locale.getDefault());
- assertNotNull(invalidValues);
- assertEquals(1, invalidValues.length);
- System.out.println(invalidValues[0].getMessage());
- }
-
- public void testValidationResolver() throws Exception {
- ValidableBean bean = new ValidableBean();
- BeanValidator beanValidator = BeanValidator.createInstance();
- ValidationResolver validationResolver =
beanValidator.createValidationResolver(facesContext.getELContext().getELResolver(),
Locale.US);
- Object list = validationResolver.getValue(elContext, bean, "list");
- assertNotNull(list);
- assertTrue(list instanceof List);
- validationResolver.setValue(elContext, list, new Integer(0), "");
- assertFalse(validationResolver.isValid());
- assertEquals(1, validationResolver.getValidationMessages().length);
- }
- public void testValidationResolverMap() throws Exception {
- ValidableBean bean = new ValidableBean();
- BeanValidator beanValidator = BeanValidator.createInstance();
- ValidationResolver validationResolver =
beanValidator.createValidationResolver(facesContext.getELContext().getELResolver(),
Locale.US);
- Object list = validationResolver.getValue(elContext, bean, "map");
- assertNotNull(list);
- assertTrue(list instanceof Map);
- validationResolver.setValue(elContext, list, new Integer(0), "");
- assertFalse(validationResolver.isValid());
- assertEquals(1, validationResolver.getValidationMessages().length);
- }
-}
Added:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java
===================================================================
--- trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java
(rev 0)
+++
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,76 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+package org.richfaces.validator;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.ResourceBundle;
+
+import javax.validation.constraints.NotNull;
+
+import org.ajax4jsf.el.ELContextWrapper;
+import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+import org.hibernate.validator.ClassValidator;
+import org.hibernate.validator.InvalidValue;
+import org.richfaces.validator.ObjectValidator.ValidationResolver;
+
+public class BeanValidatorTest extends AbstractAjax4JsfTestCase {
+
+ public BeanValidatorTest(String name) {
+ super(name);
+ }
+
+
+ public void setUp() throws Exception {
+ super.setUp();
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testValidate() throws Exception {
+ BeanValidator validator = new BeanValidator();
+ String[] validate = validator.validate(new Bean(), "property", null,
Locale.ENGLISH, null);
+ assertNotNull(validate);
+ assertEquals(1, validate.length);
+ }
+
+ public static class Bean {
+ String property;
+
+ /**
+ * @return the property
+ */
+ public String getProperty() {
+ return property;
+ }
+
+ /**
+ * @param property the property to set
+ */
+ @NotNull
+ public void setProperty(String property) {
+ this.property = property;
+ }
+ }
+}
Copied:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/HibernateValidatorTest.java
(from rev 13985,
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/BeanValidatorTest.java)
===================================================================
---
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/HibernateValidatorTest.java
(rev 0)
+++
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/HibernateValidatorTest.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,132 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+package org.richfaces.validator;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.ResourceBundle;
+
+import org.ajax4jsf.el.ELContextWrapper;
+import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
+import org.hibernate.validator.ClassValidator;
+import org.hibernate.validator.InvalidValue;
+import org.richfaces.validator.ObjectValidator.ValidationResolver;
+
+public class HibernateValidatorTest extends AbstractAjax4JsfTestCase {
+
+ public HibernateValidatorTest(String name) {
+ super(name);
+ }
+
+ public void testValidate() {
+
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testGetValidator() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ ClassValidator<? extends Object> validator =
beanValidator.getValidator(ValidableBean.class,Locale.ENGLISH);
+ assertNotNull(validator);
+ assertTrue(validator.hasValidationRules());
+ validator = beanValidator.getValidator(String.class,Locale.getDefault());
+ assertNotNull(validator);
+ assertFalse(validator.hasValidationRules());
+ }
+
+ public void testValidateClass() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ InvalidValue[] invalidValues = beanValidator.validateClass(ValidableBean.class,
"integerProperty", new Integer(3),Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(0, invalidValues.length);
+ invalidValues = beanValidator.validateClass(ValidableBean.class,
"integerProperty", new Integer(-1),Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(1, invalidValues.length);
+ invalidValues = beanValidator.validateClass(UnValidableBean.class,
"integerProperty", new Integer(-1),Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(0, invalidValues.length);
+ invalidValues = beanValidator.validateClass(ValidableBean.class,
"nonExistentProperty", new Integer(-1),Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(0, invalidValues.length);
+
+ }
+
+ public void testValidateBean() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"integerProperty", new Integer(-1),Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(1, invalidValues.length);
+ }
+
+ public void testValidateArray() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"array", "",Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(2, invalidValues.length);
+ System.out.println(invalidValues[0].getMessage());
+ System.out.println(invalidValues[1].getMessage());
+ }
+
+ public void testValidateList() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"list", "",Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(1, invalidValues.length);
+ System.out.println(invalidValues[0].getMessage());
+ }
+ public void testValidateMap() throws Exception {
+ HibernateValidator beanValidator = new HibernateValidator();
+ InvalidValue[] invalidValues = beanValidator.validateBean(new ValidableBean(),
"map", "",Locale.getDefault());
+ assertNotNull(invalidValues);
+ assertEquals(1, invalidValues.length);
+ System.out.println(invalidValues[0].getMessage());
+ }
+
+ public void testValidationResolver() throws Exception {
+ ValidableBean bean = new ValidableBean();
+ HibernateValidator beanValidator = new HibernateValidator();
+ ValidationResolver validationResolver =
beanValidator.createValidationResolver(facesContext.getELContext().getELResolver(),
Locale.US,null);
+ Object list = validationResolver.getValue(elContext, bean, "list");
+ assertNotNull(list);
+ assertTrue(list instanceof List);
+ validationResolver.setValue(elContext, list, new Integer(0), "");
+ assertFalse(validationResolver.isValid());
+ assertEquals(1, validationResolver.getValidationMessages().length);
+ }
+ public void testValidationResolverMap() throws Exception {
+ ValidableBean bean = new ValidableBean();
+ HibernateValidator beanValidator = new HibernateValidator();
+ ValidationResolver validationResolver =
beanValidator.createValidationResolver(facesContext.getELContext().getELResolver(),
Locale.US,null);
+ Object list = validationResolver.getValue(elContext, bean, "map");
+ assertNotNull(list);
+ assertTrue(list instanceof Map);
+ validationResolver.setValue(elContext, list, new Integer(0), "");
+ assertFalse(validationResolver.isValid());
+ assertEquals(1, validationResolver.getValidationMessages().length);
+ }
+}
Property changes on:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/HibernateValidatorTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/MockValidationProvider.java
===================================================================
---
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/MockValidationProvider.java
(rev 0)
+++
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/MockValidationProvider.java 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1,223 @@
+/**
+ *
+ */
+package org.richfaces.validator;
+
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.Set;
+
+import javax.validation.BeanDescriptor;
+import javax.validation.Configuration;
+import javax.validation.ConstraintDescriptor;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.BootstrapState;
+import javax.validation.spi.ConfigurationState;
+import javax.validation.spi.ValidationProvider;
+
+/**
+ * @author asmirnov
+ *
+ */
+public class MockValidationProvider implements ValidationProvider {
+
+ public <T> ConstraintViolation<T> getDefaultConstraint(){
+ return new ConstraintViolation<T>(){
+
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object getInvalidValue() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Object getLeafBean() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getMessage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getMessageTemplate() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getPropertyPath() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public T getRootBean() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Class<T> getRootBeanClass() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ };
+ }
+
+ /* (non-Javadoc)
+ * @see
javax.validation.spi.ValidationProvider#buildValidatorFactory(javax.validation.spi.ConfigurationState)
+ */
+ public ValidatorFactory buildValidatorFactory(
+ ConfigurationState configurationState) {
+ // TODO Auto-generated method stub
+ return new ValidatorFactory(){
+
+ public MessageInterpolator getMessageInterpolator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Validator getValidator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public ValidatorContext usingContext() {
+ // TODO Auto-generated method stub
+ return new ValidatorContext(){
+
+ public Validator getValidator() {
+ // TODO Auto-generated method stub
+ return new Validator(){
+
+ public BeanDescriptor getConstraintsForClass(
+ Class<?> clazz) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public <T> Set<ConstraintViolation<T>> validate(
+ T object, Class<?>... groups) {
+ // TODO Auto-generated method stub
+ ConstraintViolation<T> constrain = getDefaultConstraint();
+ return Collections.singleton(constrain);
+ }
+
+ public <T> Set<ConstraintViolation<T>> validateProperty(
+ T object, String propertyName,
+ Class<?>... groups) {
+ ConstraintViolation<T> constrain = getDefaultConstraint();
+ return Collections.singleton(constrain);
+ }
+
+ public <T> Set<ConstraintViolation<T>> validateValue(
+ Class<T> beanType, String propertyName,
+ Object value, Class<?>... groups) {
+ ConstraintViolation<T> constrain = getDefaultConstraint();
+ return Collections.singleton(constrain);
+ }
+
+ };
+ }
+
+ public ValidatorContext messageInterpolator(
+ MessageInterpolator messageInterpolator) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public ValidatorContext traversableResolver(
+ TraversableResolver traversableResolver) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ };
+ }
+
+ };
+ }
+
+ /* (non-Javadoc)
+ * @see
javax.validation.spi.ValidationProvider#createGenericConfiguration(javax.validation.spi.BootstrapState)
+ */
+ public Configuration<?> createGenericConfiguration(BootstrapState state) {
+ // TODO Auto-generated method stub
+ return new Configuration<?>(){
+
+ public Configuration<?> addMapping(
+ InputStream stream) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public Configuration<?> addProperty(
+ String name, String value) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public ValidatorFactory buildValidatorFactory() {
+ // TODO Auto-generated method stub
+ return MockValidationProvider.this.buildValidatorFactory(null);
+ }
+
+ public Configuration<?> constraintValidatorFactory(
+ ConstraintValidatorFactory constraintValidatorFactory) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public MessageInterpolator getDefaultMessageInterpolator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Configuration<?> ignoreXmlConfiguration() {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public Configuration<?> messageInterpolator(
+ MessageInterpolator interpolator) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ public Configuration<?> traversableResolver(
+ TraversableResolver resolver) {
+ // TODO Auto-generated method stub
+ return this;
+ }
+
+ };
+ }
+
+ /* (non-Javadoc)
+ * @see
javax.validation.spi.ValidationProvider#createSpecializedConfiguration(javax.validation.spi.BootstrapState,
java.lang.Class)
+ */
+ public <T extends Configuration<T>> T createSpecializedConfiguration(
+ BootstrapState state, Class<T> configurationClass) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see javax.validation.spi.ValidationProvider#isSuitable(java.lang.Class)
+ */
+ public boolean isSuitable(
+ Class<? extends Configuration<?>> configurationClass) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+}
Property changes on:
trunk/ui/beanValidator/src/test/java/org/richfaces/validator/MockValidationProvider.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added:
trunk/ui/beanValidator/src/test/resources/META-INF/services/javax.validation.spi.ValidationProvider
===================================================================
---
trunk/ui/beanValidator/src/test/resources/META-INF/services/javax.validation.spi.ValidationProvider
(rev 0)
+++
trunk/ui/beanValidator/src/test/resources/META-INF/services/javax.validation.spi.ValidationProvider 2009-05-01
22:29:01 UTC (rev 13986)
@@ -0,0 +1 @@
+org.richfaces.validator.MockValidationProvider
\ No newline at end of file