You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@bval.apache.org by mb...@apache.org on 2010/09/03 21:02:19 UTC
svn commit: r992420 [1/3] - in /incubator/bval/trunk:
bval-core/src/main/java/org/apache/bval/
bval-core/src/main/java/org/apache/bval/routines/
bval-core/src/main/java/org/apache/bval/util/
bval-core/src/test/java/org/apache/bval/model/ bval-json/src/...
Author: mbenson
Date: Fri Sep 3 19:02:18 2010
New Revision: 992420
URL: http://svn.apache.org/viewvc?rev=992420&view=rev
Log:
format
Modified:
incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/BeanValidator.java
incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanBuilder.java
incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanManager.java
incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/routines/EMailValidationUtils.java
incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/util/PropertyAccess.java
incubator/bval/trunk/bval-core/src/test/java/org/apache/bval/model/ExampleEnum.java
incubator/bval/trunk/bval-json/src/test/java/org/apache/bval/json/JSONGeneratorTest.java
incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java
incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDescriptorImpl.java
incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintValidation.java
incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/extensions/MethodValidatorImpl.java
incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/extensions/MethodValidatorMetaBeanFactory.java
incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/DecimalMinMaxValidatorsTest.java
incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/constraints/MinMaxValidatorsForNumberTest.java
incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/DefaultMessageInterpolatorTest.java
incubator/bval/trunk/bval-jsr303/src/test/java/org/apache/bval/jsr303/TckReproducerTest.java
incubator/bval/trunk/bval-xstream/src/main/java/org/apache/bval/xml/XMLMetaBeanBuilder.java
incubator/bval/trunk/bval-xstream/src/main/java/org/apache/bval/xml/XMLMetaBeanManager.java
incubator/bval/trunk/bval-xstream/src/test/java/org/apache/bval/xml/XMLMetaBeanManagerTest.java
Modified: incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/BeanValidator.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/BeanValidator.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/BeanValidator.java (original)
+++ incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/BeanValidator.java Fri Sep 3 19:02:18 2010
@@ -32,237 +32,249 @@ import org.apache.bval.util.ValidationHe
// TODO: centralize treatMapsLikeBeans
/**
- * Description: Top-Level API-class to validate objects or object-trees.
- * You can invoke, extend or utilize this class if you need other ways to integrate
+ * Description: Top-Level API-class to validate objects or object-trees. You can
+ * invoke, extend or utilize this class if you need other ways to integrate
* validation in your application.
* <p/>
- * This class supports cyclic object graphs by keeping track of
- * validated instances in the validation context.<br/>
+ * This class supports cyclic object graphs by keeping track of validated
+ * instances in the validation context.<br/>
*/
public class BeanValidator<T extends ValidationListener> {
- private final MetaBeanFinder metaBeanFinder;
+ private final MetaBeanFinder metaBeanFinder;
- /**
- * Create a new BeanValidator instance.
- * Convenience constructor. Use the global instance of MetaBeanManagerFactory.getFinder().
- */
- public BeanValidator() {
- this(MetaBeanManagerFactory.getFinder());
- }
-
- /**
- * Create a new BeanValidator instance.
- * @param metaBeanFinder
- */
- public BeanValidator(MetaBeanFinder metaBeanFinder) {
- this.metaBeanFinder = metaBeanFinder;
- }
-
- /**
- * Convenience API. validate a root object with all related objects
- * with its default metaBean definition.
- *
- * @param bean
- * @return results - validation results found
- */
- public T validate(Object bean) {
- MetaBean metaBean =
- getMetaBeanFinder().findForClass(bean.getClass());
- return validate(bean, metaBean);
- }
-
- /**
- * Convenience API. validate a root object with all related objects
- * according to the metaBean.
- *
- * @param bean - a single bean or a collection of beans (that share the same metaBean!)
- * @param metaBean
- * @return results - validation results found
- */
- public T validate(Object bean, MetaBean metaBean) {
- ValidationContext<T> context = createContext();
- context.setBean(bean, metaBean);
- ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
- return context.getListener();
- }
-
- /**
- * Validate the method parameters based on @Validate annotations.
- * Requirements:
- * Parameter, that are to be validated must be annotated with @Validate
- *
- * @param method - a method
- * @param parameters - the parameters suitable to the method
- * @return a validation result or null when there was nothing to validate
- * @see Validate
- */
- public T validateCall(Method method, Object[] parameters) {
- if (parameters.length > 0) {
- // shortcut (for performance!)
- Annotation[][] annotations = method.getParameterAnnotations();
- ValidationContext<T> context = null;
- for (int i = 0; i < parameters.length; i++) {
- for (Annotation anno : annotations[i]) {
- if (anno instanceof Validate) {
- if (context == null) context = createContext();
- if (determineMetaBean((Validate) anno, parameters[i], context)) {
- ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
- break; // next parameter
+ /**
+ * Create a new BeanValidator instance. Convenience constructor. Use the
+ * global instance of MetaBeanManagerFactory.getFinder().
+ */
+ public BeanValidator() {
+ this(MetaBeanManagerFactory.getFinder());
+ }
+
+ /**
+ * Create a new BeanValidator instance.
+ *
+ * @param metaBeanFinder
+ */
+ public BeanValidator(MetaBeanFinder metaBeanFinder) {
+ this.metaBeanFinder = metaBeanFinder;
+ }
+
+ /**
+ * Convenience API. validate a root object with all related objects with its
+ * default metaBean definition.
+ *
+ * @param bean
+ * @return results - validation results found
+ */
+ public T validate(Object bean) {
+ MetaBean metaBean = getMetaBeanFinder().findForClass(bean.getClass());
+ return validate(bean, metaBean);
+ }
+
+ /**
+ * Convenience API. validate a root object with all related objects
+ * according to the metaBean.
+ *
+ * @param bean
+ * - a single bean or a collection of beans (that share the same
+ * metaBean!)
+ * @param metaBean
+ * @return results - validation results found
+ */
+ public T validate(Object bean, MetaBean metaBean) {
+ ValidationContext<T> context = createContext();
+ context.setBean(bean, metaBean);
+ ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
+ return context.getListener();
+ }
+
+ /**
+ * Validate the method parameters based on @Validate annotations.
+ * Requirements: Parameter, that are to be validated must be annotated with @Validate
+ *
+ * @param method
+ * - a method
+ * @param parameters
+ * - the parameters suitable to the method
+ * @return a validation result or null when there was nothing to validate
+ * @see Validate
+ */
+ public T validateCall(Method method, Object[] parameters) {
+ if (parameters.length > 0) {
+ // shortcut (for performance!)
+ Annotation[][] annotations = method.getParameterAnnotations();
+ ValidationContext<T> context = null;
+ for (int i = 0; i < parameters.length; i++) {
+ for (Annotation anno : annotations[i]) {
+ if (anno instanceof Validate) {
+ if (context == null)
+ context = createContext();
+ if (determineMetaBean((Validate) anno, parameters[i], context)) {
+ ValidationHelper.validateContext(context, new BeanValidatorCallback(context),
+ treatMapsLikeBeans);
+ break; // next parameter
+ }
+ }
+ }
}
- }
+ return context != null ? context.getListener() : null;
}
- }
- return context != null ? context.getListener() : null;
+ return null;
}
- return null;
- }
- /**
- * Determine the metabean for the given object.
- * @param <VL>
- * @param validate
- * @param parameter
- * @param context
- * @return true when validation should happen, false to skip it
- */
- protected <VL extends ValidationListener> boolean determineMetaBean(Validate validate, Object parameter,
- ValidationContext<VL> context) {
- if (validate.value().length() == 0) {
- if (parameter == null) return false;
- Class<?> beanClass;
- if (parameter instanceof Collection<?>) { // do not validate empty collection
- Collection<?> coll = ((Collection<?>) parameter);
- if (coll.isEmpty()) return false;
- beanClass = coll.iterator().next().getClass(); // get first object
- } else if (parameter.getClass().isArray()) {
- beanClass = parameter.getClass().getComponentType();
- } else {
- beanClass = parameter.getClass();
- }
- context.setBean(parameter, getMetaBeanFinder().findForClass(beanClass));
- } else {
- context.setBean(parameter, getMetaBeanFinder().findForId(validate.value()));
- }
- return true;
- }
-
- /**
- * factory method -
- * overwrite in subclasses
- *
- * @return ValidationListener of the proper type
- */
- @SuppressWarnings("unchecked")
- protected T createResults() {
- return (T) new ValidationResults();
- }
-
- /**
- * factory method -
- * overwrite in subclasses
- *
- * @return ValidationContext parameterized with our listener type
- */
- protected ValidationContext<T> createContext() {
- return new BeanValidationContext<T>(createResults());
- }
-
- /**
- * Convenience API. validate a single property.
- *
- * @param bean - the root object
- * @param metaProperty - metadata for the property
- * @return validation results
- */
- public T validateProperty(Object bean, MetaProperty metaProperty) {
- ValidationContext<T> context = createContext();
- context.setBean(bean);
- context.setMetaProperty(metaProperty);
- ValidationHelper.validateProperty(context);
- return context.getListener();
- }
-
- /**
- * {@inheritDoc}
- * internal validate a bean (=not a collection of beans) and its related beans
- */
- protected <VL extends ValidationListener> void validateBeanNet(ValidationContext<VL> context) {
- if (context.collectValidated()) {
- ValidationHelper.validateBean(context);
- for (MetaProperty prop : context.getMetaBean().getProperties()) {
- validateRelatedBean(context, prop);
- }
- }
- }
-
- /**
- * Validate a property of a graph.
- * @param <VL>
- * @param context
- * @param prop
- */
- protected <VL extends ValidationListener> void validateRelatedBean(ValidationContext<VL> context, MetaProperty prop) {
- AccessStrategy[] access = prop.getFeature(Features.Property.REF_CASCADE);
- if (access == null && prop.getMetaBean() != null) { // single property access strategy
- // save old values from context
- final Object bean = context.getBean();
- final MetaBean mbean = context.getMetaBean();
- // modify context state for relationship-target bean
- context.moveDown(prop, new PropertyAccess(bean.getClass(), prop.getName()));
- ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
- // restore old values in context
- context.moveUp(bean, mbean);
- } else if (access != null) { // different accesses to relation
- // save old values from context
- final Object bean = context.getBean();
- final MetaBean mbean = context.getMetaBean();
- for (AccessStrategy each : access) {
- // modify context state for relationship-target bean
- context.moveDown(prop, each);
- ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
- // restore old values in context
- context.moveUp(bean, mbean);
- }
- }
- }
-
- private boolean treatMapsLikeBeans = false;
-
- public boolean isTreatMapsLikeBeans() {
- return treatMapsLikeBeans;
- }
-
- public void setTreatMapsLikeBeans(boolean treatMapsLikeBeans) {
- this.treatMapsLikeBeans = treatMapsLikeBeans;
- }
-
- /**
- * Get the metabean finder associated with this validator.
- *
- * @return a MetaBeanFinder
- * @see org.apache.bval.MetaBeanManagerFactory#getFinder()
- */
- public MetaBeanFinder getMetaBeanFinder() {
- return metaBeanFinder;
- }
-
- /**
- * Dispatches a call from {@link #validate()} to
- * {@link BeanValidator#validateBeanNet(ValidationContext)} with the current
- * context set.
- */
- private class BeanValidatorCallback implements ValidationHelper.ValidateCallback {
-
- private final ValidationContext<?> context;
-
- public BeanValidatorCallback(ValidationContext<?> context) {
- this.context = context;
+ /**
+ * Determine the metabean for the given object.
+ *
+ * @param <VL>
+ * @param validate
+ * @param parameter
+ * @param context
+ * @return true when validation should happen, false to skip it
+ */
+ protected <VL extends ValidationListener> boolean determineMetaBean(Validate validate, Object parameter,
+ ValidationContext<VL> context) {
+ if (validate.value().length() == 0) {
+ if (parameter == null)
+ return false;
+ Class<?> beanClass;
+ if (parameter instanceof Collection<?>) { // do not validate empty
+ // collection
+ Collection<?> coll = ((Collection<?>) parameter);
+ if (coll.isEmpty())
+ return false;
+ beanClass = coll.iterator().next().getClass(); // get first
+ // object
+ } else if (parameter.getClass().isArray()) {
+ beanClass = parameter.getClass().getComponentType();
+ } else {
+ beanClass = parameter.getClass();
+ }
+ context.setBean(parameter, getMetaBeanFinder().findForClass(beanClass));
+ } else {
+ context.setBean(parameter, getMetaBeanFinder().findForId(validate.value()));
+ }
+ return true;
+ }
+
+ /**
+ * factory method - overwrite in subclasses
+ *
+ * @return ValidationListener of the proper type
+ */
+ @SuppressWarnings("unchecked")
+ protected T createResults() {
+ return (T) new ValidationResults();
+ }
+
+ /**
+ * factory method - overwrite in subclasses
+ *
+ * @return ValidationContext parameterized with our listener type
+ */
+ protected ValidationContext<T> createContext() {
+ return new BeanValidationContext<T>(createResults());
+ }
+
+ /**
+ * Convenience API. validate a single property.
+ *
+ * @param bean
+ * - the root object
+ * @param metaProperty
+ * - metadata for the property
+ * @return validation results
+ */
+ public T validateProperty(Object bean, MetaProperty metaProperty) {
+ ValidationContext<T> context = createContext();
+ context.setBean(bean);
+ context.setMetaProperty(metaProperty);
+ ValidationHelper.validateProperty(context);
+ return context.getListener();
+ }
+
+ /**
+ * {@inheritDoc} internal validate a bean (=not a collection of beans) and
+ * its related beans
+ */
+ protected <VL extends ValidationListener> void validateBeanNet(ValidationContext<VL> context) {
+ if (context.collectValidated()) {
+ ValidationHelper.validateBean(context);
+ for (MetaProperty prop : context.getMetaBean().getProperties()) {
+ validateRelatedBean(context, prop);
+ }
+ }
+ }
+
+ /**
+ * Validate a property of a graph.
+ *
+ * @param <VL>
+ * @param context
+ * @param prop
+ */
+ protected <VL extends ValidationListener> void validateRelatedBean(ValidationContext<VL> context, MetaProperty prop) {
+ AccessStrategy[] access = prop.getFeature(Features.Property.REF_CASCADE);
+ if (access == null && prop.getMetaBean() != null) { // single property
+ // access strategy
+ // save old values from context
+ final Object bean = context.getBean();
+ final MetaBean mbean = context.getMetaBean();
+ // modify context state for relationship-target bean
+ context.moveDown(prop, new PropertyAccess(bean.getClass(), prop.getName()));
+ ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
+ // restore old values in context
+ context.moveUp(bean, mbean);
+ } else if (access != null) { // different accesses to relation
+ // save old values from context
+ final Object bean = context.getBean();
+ final MetaBean mbean = context.getMetaBean();
+ for (AccessStrategy each : access) {
+ // modify context state for relationship-target bean
+ context.moveDown(prop, each);
+ ValidationHelper.validateContext(context, new BeanValidatorCallback(context), treatMapsLikeBeans);
+ // restore old values in context
+ context.moveUp(bean, mbean);
+ }
+ }
}
- public void validate() {
- validateBeanNet(context);
+ private boolean treatMapsLikeBeans = false;
+
+ public boolean isTreatMapsLikeBeans() {
+ return treatMapsLikeBeans;
+ }
+
+ public void setTreatMapsLikeBeans(boolean treatMapsLikeBeans) {
+ this.treatMapsLikeBeans = treatMapsLikeBeans;
+ }
+
+ /**
+ * Get the metabean finder associated with this validator.
+ *
+ * @return a MetaBeanFinder
+ * @see org.apache.bval.MetaBeanManagerFactory#getFinder()
+ */
+ public MetaBeanFinder getMetaBeanFinder() {
+ return metaBeanFinder;
+ }
+
+ /**
+ * Dispatches a call from {@link #validate()} to
+ * {@link BeanValidator#validateBeanNet(ValidationContext)} with the current
+ * context set.
+ */
+ private class BeanValidatorCallback implements ValidationHelper.ValidateCallback {
+
+ private final ValidationContext<?> context;
+
+ public BeanValidatorCallback(ValidationContext<?> context) {
+ this.context = context;
+ }
+
+ public void validate() {
+ validateBeanNet(context);
+ }
+
}
- }
-
}
Modified: incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanBuilder.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanBuilder.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanBuilder.java (original)
+++ incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanBuilder.java Fri Sep 3 19:02:18 2010
@@ -16,7 +16,6 @@
*/
package org.apache.bval;
-
import org.apache.bval.model.MetaBean;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.logging.Log;
@@ -26,98 +25,109 @@ import java.util.HashMap;
import java.util.Map;
/**
- * Description: internal implementation class to construct
- * metabeans with factories<br/>
+ * Description: internal implementation class to construct metabeans with
+ * factories<br/>
*/
public class MetaBeanBuilder {
- private static final Log log = LogFactory.getLog(MetaBeanBuilder.class);
+ private static final Log log = LogFactory.getLog(MetaBeanBuilder.class);
+
+ /**
+ * here you can install different kinds of factories to create MetaBeans
+ * from
+ */
+ private MetaBeanFactory[] factories;
+
+ /**
+ * Create a new MetaBeanBuilder instance.
+ */
+ public MetaBeanBuilder() {
+ this(new MetaBeanFactory[] { new IntrospectorMetaBeanFactory() });
+ }
+
+ /**
+ * Create a new MetaBeanBuilder instance.
+ *
+ * @param factories
+ */
+ public MetaBeanBuilder(MetaBeanFactory[] factories) {
+ setFactories(factories);
+ }
+
+ /**
+ * Get the configured set of {@link MetaBeanFactory} objects.
+ *
+ * @return {@link MetaBeanFactory} array
+ */
+ public MetaBeanFactory[] getFactories() {
+ return factories;
+ }
- /**
- * here you can install different kinds of factories to create MetaBeans from
- */
- private MetaBeanFactory[] factories;
-
- /**
- * Create a new MetaBeanBuilder instance.
- */
- public MetaBeanBuilder() {
- this(new MetaBeanFactory[]{new IntrospectorMetaBeanFactory()});
- }
-
- /**
- * Create a new MetaBeanBuilder instance.
- * @param factories
- */
- public MetaBeanBuilder(MetaBeanFactory[] factories) {
- setFactories(factories);
- }
-
- /**
- * Get the configured set of {@link MetaBeanFactory} objects.
- * @return {@link MetaBeanFactory} array
- */
- public MetaBeanFactory[] getFactories() {
- return factories;
- }
-
- /**
- * Set the array of {@link MetaBeanFactory} instances with which to enrich {@link MetaBean}s.
- * @param factories
- */
- public void setFactories(MetaBeanFactory[] factories) {
- this.factories = factories;
- }
-
- /**
- * Build a {@link MetaBean} for a given id.
- * @param beanInfoId
- * @return MetaBean
- * @throws Exception if unable to build
- */
- public MetaBean buildForId(String beanInfoId) throws Exception {
- throw new IllegalArgumentException("MetaBean " + beanInfoId + " not found");
- }
-
- /**
- * Build beans for all known ids. Default implementation returns an empty map.
- * @return Map of String : MetaBean
- */
- public Map<String, MetaBean> buildAll() throws Exception {
- return new HashMap<String, MetaBean>();
- }
-
- /**
- * Find the named class.
- * @param className
- * @return Class found or null
- */
- protected Class<?> findLocalClass(String className) {
- if (className != null) {
- try {
- return ClassUtils.getClass(className);
- } catch (ClassNotFoundException e) {
- log.trace("class not found: " + className, e);
- }
- }
- return null;
- }
-
- /**
- * Build a MetaBean for the specified class.
- * @param clazz
- * @return MetaBean
- * @throws Exception
- */
- public MetaBean buildForClass(Class<?> clazz) throws Exception {
- MetaBean meta = new MetaBean();
- if (clazz != null) { // local class here?
- meta.setBeanClass(clazz);
- meta.setId(clazz.getName()); // default id = full class name!
+ /**
+ * Set the array of {@link MetaBeanFactory} instances with which to enrich
+ * {@link MetaBean}s.
+ *
+ * @param factories
+ */
+ public void setFactories(MetaBeanFactory[] factories) {
+ this.factories = factories;
}
- for (MetaBeanFactory factory : factories) {
- factory.buildMetaBean(meta);
+
+ /**
+ * Build a {@link MetaBean} for a given id.
+ *
+ * @param beanInfoId
+ * @return MetaBean
+ * @throws Exception
+ * if unable to build
+ */
+ public MetaBean buildForId(String beanInfoId) throws Exception {
+ throw new IllegalArgumentException("MetaBean " + beanInfoId + " not found");
+ }
+
+ /**
+ * Build beans for all known ids. Default implementation returns an empty
+ * map.
+ *
+ * @return Map of String : MetaBean
+ */
+ public Map<String, MetaBean> buildAll() throws Exception {
+ return new HashMap<String, MetaBean>();
+ }
+
+ /**
+ * Find the named class.
+ *
+ * @param className
+ * @return Class found or null
+ */
+ protected Class<?> findLocalClass(String className) {
+ if (className != null) {
+ try {
+ return ClassUtils.getClass(className);
+ } catch (ClassNotFoundException e) {
+ log.trace("class not found: " + className, e);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Build a MetaBean for the specified class.
+ *
+ * @param clazz
+ * @return MetaBean
+ * @throws Exception
+ */
+ public MetaBean buildForClass(Class<?> clazz) throws Exception {
+ MetaBean meta = new MetaBean();
+ if (clazz != null) { // local class here?
+ meta.setBeanClass(clazz);
+ meta.setId(clazz.getName()); // default id = full class name!
+ }
+ for (MetaBeanFactory factory : factories) {
+ factory.buildMetaBean(meta);
+ }
+ return meta;
}
- return meta;
- }
}
Modified: incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanManager.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanManager.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanManager.java (original)
+++ incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/MetaBeanManager.java Fri Sep 3 19:02:18 2010
@@ -24,113 +24,120 @@ import static org.apache.bval.model.Feat
/**
* Description: Default implementation for the interface to find, register and
* create MetaBeans. In most situations a single instance of this class is
- * sufficient and you can get this instance from the {@link MetaBeanManagerFactory}.
- * <br/>
+ * sufficient and you can get this instance from the
+ * {@link MetaBeanManagerFactory}. <br/>
*/
public class MetaBeanManager implements MetaBeanFinder {
- /** MetaBean cache */
- protected final MetaBeanCache cache = new MetaBeanCache();
- /** MetaBean builder */
- protected final MetaBeanBuilder builder;
- /** Complete flag */
- protected boolean complete = false;
-
- /**
- * Create a new MetaBeanManager instance.
- */
- public MetaBeanManager() {
- builder = new MetaBeanBuilder();
- }
-
- /**
- * Create a new MetaBeanManager instance.
- * @param builder
- */
- public MetaBeanManager(MetaBeanBuilder builder) {
- this.builder = builder;
- }
-
- /**
- * Get the builder used.
- * @return {@link MetaBeanBuilder}
- */
- public MetaBeanBuilder getBuilder() {
- return builder;
- }
-
- /**
- * Get the cache used.
- * @return {@link MetaBeanCache}
- */
- public MetaBeanCache getCache() {
- return cache;
- }
-
- /**
- * {@inheritDoc}
- */
- public MetaBean findForId(String beanInfoId) {
- MetaBean beanInfo = cache.findForId(beanInfoId);
- if (beanInfo != null) return beanInfo;
- try {
- beanInfo = builder.buildForId(beanInfoId);
- cache.cache(beanInfo);
- computeRelationships(beanInfo);
- return beanInfo;
- } catch (RuntimeException e) {
- throw e; // do not wrap runtime exceptions
- } catch (Exception e) {
- throw new IllegalArgumentException(
- "error creating beanInfo with id: " + beanInfoId, e);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public MetaBean findForClass(Class<?> clazz) {
- if (clazz == null) return null;
- MetaBean beanInfo = cache.findForClass(clazz);
- if (beanInfo != null) return beanInfo;
- try {
- beanInfo = builder.buildForClass(clazz);
- cache.cache(beanInfo);
- computeRelationships(beanInfo);
- return beanInfo;
- } catch (RuntimeException e) {
- throw e; // do not wrap runtime exceptions
- } catch (Exception e) {
- throw new IllegalArgumentException("error creating beanInfo for " + clazz, e);
- }
- }
-
- /**
- * Compute all known relationships for <code>beanInfo</code>.
- * must be called AFTER cache.cache()
- * to avoid endless loop
- *
- * @param beanInfo - the bean for which to compute relationships
- */
- protected void computeRelationships(MetaBean beanInfo) {
- for (MetaProperty prop : beanInfo.getProperties()) {
- String beanRef = (String) prop.getFeature(REF_BEAN_ID);
- computeRelatedMetaBean(prop, beanRef);
- }
- }
-
- /**
- * Compute a single related {@link MetaBean}.
- * @param prop
- * @param beanRef
- */
- protected void computeRelatedMetaBean(MetaProperty prop, String beanRef) {
- Class<?> beanType = prop.getFeature(REF_BEAN_TYPE);
- if (beanType != null) {
- prop.setMetaBean(findForClass(beanType));
- } else if (prop.getFeature(REF_CASCADE) != null) { // dynamic type resolution:
- prop.setMetaBean(new DynamicMetaBean(this));
+ /** MetaBean cache */
+ protected final MetaBeanCache cache = new MetaBeanCache();
+ /** MetaBean builder */
+ protected final MetaBeanBuilder builder;
+ /** Complete flag */
+ protected boolean complete = false;
+
+ /**
+ * Create a new MetaBeanManager instance.
+ */
+ public MetaBeanManager() {
+ builder = new MetaBeanBuilder();
+ }
+
+ /**
+ * Create a new MetaBeanManager instance.
+ *
+ * @param builder
+ */
+ public MetaBeanManager(MetaBeanBuilder builder) {
+ this.builder = builder;
+ }
+
+ /**
+ * Get the builder used.
+ *
+ * @return {@link MetaBeanBuilder}
+ */
+ public MetaBeanBuilder getBuilder() {
+ return builder;
+ }
+
+ /**
+ * Get the cache used.
+ *
+ * @return {@link MetaBeanCache}
+ */
+ public MetaBeanCache getCache() {
+ return cache;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public MetaBean findForId(String beanInfoId) {
+ MetaBean beanInfo = cache.findForId(beanInfoId);
+ if (beanInfo != null)
+ return beanInfo;
+ try {
+ beanInfo = builder.buildForId(beanInfoId);
+ cache.cache(beanInfo);
+ computeRelationships(beanInfo);
+ return beanInfo;
+ } catch (RuntimeException e) {
+ throw e; // do not wrap runtime exceptions
+ } catch (Exception e) {
+ throw new IllegalArgumentException("error creating beanInfo with id: " + beanInfoId, e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public MetaBean findForClass(Class<?> clazz) {
+ if (clazz == null)
+ return null;
+ MetaBean beanInfo = cache.findForClass(clazz);
+ if (beanInfo != null)
+ return beanInfo;
+ try {
+ beanInfo = builder.buildForClass(clazz);
+ cache.cache(beanInfo);
+ computeRelationships(beanInfo);
+ return beanInfo;
+ } catch (RuntimeException e) {
+ throw e; // do not wrap runtime exceptions
+ } catch (Exception e) {
+ throw new IllegalArgumentException("error creating beanInfo for " + clazz, e);
+ }
+ }
+
+ /**
+ * Compute all known relationships for <code>beanInfo</code>. must be called
+ * AFTER cache.cache() to avoid endless loop
+ *
+ * @param beanInfo
+ * - the bean for which to compute relationships
+ */
+ protected void computeRelationships(MetaBean beanInfo) {
+ for (MetaProperty prop : beanInfo.getProperties()) {
+ String beanRef = (String) prop.getFeature(REF_BEAN_ID);
+ computeRelatedMetaBean(prop, beanRef);
+ }
+ }
+
+ /**
+ * Compute a single related {@link MetaBean}.
+ *
+ * @param prop
+ * @param beanRef
+ */
+ protected void computeRelatedMetaBean(MetaProperty prop, String beanRef) {
+ Class<?> beanType = prop.getFeature(REF_BEAN_TYPE);
+ if (beanType != null) {
+ prop.setMetaBean(findForClass(beanType));
+ } else if (prop.getFeature(REF_CASCADE) != null) { // dynamic type
+ // resolution:
+ prop.setMetaBean(new DynamicMetaBean(this));
+ }
}
- }
}
Modified: incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/routines/EMailValidationUtils.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/routines/EMailValidationUtils.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/routines/EMailValidationUtils.java (original)
+++ incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/routines/EMailValidationUtils.java Fri Sep 3 19:02:18 2010
@@ -26,46 +26,49 @@ import java.util.regex.Pattern;
* Time: 10:40:59<br>
*/
public class EMailValidationUtils {
- private static String ATOM =
- "[^\\x00-\\x1F^\\(^\\)^\\<^\\>^\\@^\\,^\\;^\\:^\\\\^\\\"^\\.^\\[^\\]^\\s]";
- private static String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*";
- private static String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
- public static final java.util.regex.Pattern DEFAULT_EMAIL_PATTERN;
+ private static String ATOM = "[^\\x00-\\x1F^\\(^\\)^\\<^\\>^\\@^\\,^\\;^\\:^\\\\^\\\"^\\.^\\[^\\]^\\s]";
+ private static String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*";
+ private static String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
+ public static final java.util.regex.Pattern DEFAULT_EMAIL_PATTERN;
- static {
- DEFAULT_EMAIL_PATTERN = java.util.regex.Pattern.compile(
- "^" + ATOM + "+(\\." + ATOM + "+)*@"
- + DOMAIN
- + "|"
- + IP_DOMAIN
- + ")$",
- java.util.regex.Pattern.CASE_INSENSITIVE
- );
- }
+ static {
+ DEFAULT_EMAIL_PATTERN =
+ java.util.regex.Pattern.compile("^" + ATOM + "+(\\." + ATOM + "+)*@" + DOMAIN + "|" + IP_DOMAIN + ")$",
+ java.util.regex.Pattern.CASE_INSENSITIVE);
+ }
- /**
- * Learn whether a given object is a valid email address.
- * @param value to check
- * @return <code>true</code> if the validation passes
- */
- public static boolean isValid(Object value) {
- return isValid(value, DEFAULT_EMAIL_PATTERN);
- }
+ /**
+ * Learn whether a given object is a valid email address.
+ *
+ * @param value
+ * to check
+ * @return <code>true</code> if the validation passes
+ */
+ public static boolean isValid(Object value) {
+ return isValid(value, DEFAULT_EMAIL_PATTERN);
+ }
- /**
- * Learn whether a particular value matches a given pattern per {@link Matcher#matches()}.
- * @param value
- * @param aPattern
- * @return <code>true</code> if <code>value</code> was a <code>String</code> matching <code>aPattern</code>
- */
- //TODO it would seem to make sense to move or reduce the visibility of this method as it is more general than email.
- public static boolean isValid(Object value, Pattern aPattern) {
- if (value == null) return true;
- if (!(value instanceof CharSequence)) return false;
- CharSequence seq = (CharSequence) value;
- if (seq.length() == 0) return true;
- Matcher m = aPattern.matcher(seq);
- return m.matches();
- }
+ /**
+ * Learn whether a particular value matches a given pattern per
+ * {@link Matcher#matches()}.
+ *
+ * @param value
+ * @param aPattern
+ * @return <code>true</code> if <code>value</code> was a <code>String</code>
+ * matching <code>aPattern</code>
+ */
+ // TODO it would seem to make sense to move or reduce the visibility of this
+ // method as it is more general than email.
+ public static boolean isValid(Object value, Pattern aPattern) {
+ if (value == null)
+ return true;
+ if (!(value instanceof CharSequence))
+ return false;
+ CharSequence seq = (CharSequence) value;
+ if (seq.length() == 0)
+ return true;
+ Matcher m = aPattern.matcher(seq);
+ return m.matches();
+ }
}
Modified: incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/util/PropertyAccess.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/util/PropertyAccess.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/util/PropertyAccess.java (original)
+++ incubator/bval/trunk/bval-core/src/main/java/org/apache/bval/util/PropertyAccess.java Fri Sep 3 19:02:18 2010
@@ -26,171 +26,172 @@ import java.lang.reflect.Type;
import java.util.Map;
/**
- * Description: Undefined dynamic strategy (FIELD or METHOD access)
- * Uses PropertyUtils or tries to determine
- * field to access the value<br/>
+ * Description: Undefined dynamic strategy (FIELD or METHOD access) Uses
+ * PropertyUtils or tries to determine field to access the value<br/>
*/
public class PropertyAccess extends AccessStrategy {
- private final Class<?> beanClass;
- private final String propertyName;
- private Field rememberField;
-
- /**
- * Create a new PropertyAccess instance.
- * @param clazz
- * @param propertyName
- */
- public PropertyAccess(Class<?> clazz, String propertyName) {
- this.beanClass = clazz;
- this.propertyName = propertyName;
- }
-
- /**
- * {@inheritDoc}
- */
- public ElementType getElementType() {
- return (rememberField != null) ? ElementType.FIELD : ElementType.METHOD;
- }
-
- private static Object getPublicProperty(Object bean, String property) throws
- InvocationTargetException, NoSuchMethodException, IllegalAccessException {
- if (bean instanceof Map<?, ?>) {
- return ((Map<?, ?>) bean).get(property);
- } else { // supports DynaBean and standard Objects
- return PropertyUtils.getSimpleProperty(bean, property);
- }
- }
-
- /**
- * Get a named property from <code>bean</code>.
- * @param bean
- * @param propertyName
- * @return Object found
- * @throws InvocationTargetException
- * @throws NoSuchMethodException
- * @throws IllegalAccessException
- */
- public static Object getProperty(Object bean, String propertyName) throws
- InvocationTargetException, NoSuchMethodException, IllegalAccessException {
- return new PropertyAccess(bean.getClass(), propertyName).get(bean);
- }
-
- /**
- * {@inheritDoc}
- */
- public String toString() {
- return "Property{" + beanClass.getName() + '.' + propertyName + '}';
- }
-
- /**
- * {@inheritDoc}
- */
- public Type getJavaType() {
- /*if(Map.class.isAssignableFrom(beanClass)) {
- return beanClass.
- }*/
- if (rememberField != null) { // use cached field of previous access
- return rememberField.getGenericType();
- }
- for (PropertyDescriptor each : PropertyUtils.getPropertyDescriptors(beanClass)) {
- if (each.getName().equals(propertyName) && each.getReadMethod() != null) {
- return each.getReadMethod().getGenericReturnType();
- }
- }
- try { // try public field
- return beanClass.getField(propertyName).getGenericType();
- } catch (NoSuchFieldException ex2) {
- // search for private/protected field up the hierarchy
- Class<?> theClass = beanClass;
- while (theClass != null) {
- try {
- return theClass.getDeclaredField(propertyName).getGenericType();
- } catch (NoSuchFieldException ex3) {
- // do nothing
- }
- theClass = theClass.getSuperclass();
- }
- }
- return Object.class; // unknown type: allow any type??
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPropertyName() {
- return propertyName;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object get(Object bean) {
- try {
- if (rememberField != null) { // cache field of previous access
- return rememberField.get(bean);
- }
-
- try { // try public method
- return getPublicProperty(bean, propertyName);
- } catch (NoSuchMethodException ex) {
- return getFieldValue(bean);
- }
- } catch (IllegalArgumentException e) {
- throw e;
- } catch (Exception e) {
- throw new IllegalArgumentException("cannot access " + propertyName, e);
- }
- }
-
- private Object getFieldValue(Object bean) throws IllegalAccessException {
- Object value;
- try { // try public field
- Field aField = bean.getClass().getField(propertyName);
- value = aField.get(bean);
- rememberField = aField;
- return value;
- } catch (NoSuchFieldException ex2) {
- // search for private/protected field up the hierarchy
- Class<?> theClass = bean.getClass();
- while (theClass != null) {
+ private final Class<?> beanClass;
+ private final String propertyName;
+ private Field rememberField;
+
+ /**
+ * Create a new PropertyAccess instance.
+ *
+ * @param clazz
+ * @param propertyName
+ */
+ public PropertyAccess(Class<?> clazz, String propertyName) {
+ this.beanClass = clazz;
+ this.propertyName = propertyName;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ElementType getElementType() {
+ return (rememberField != null) ? ElementType.FIELD : ElementType.METHOD;
+ }
+
+ private static Object getPublicProperty(Object bean, String property) throws InvocationTargetException,
+ NoSuchMethodException, IllegalAccessException {
+ if (bean instanceof Map<?, ?>) {
+ return ((Map<?, ?>) bean).get(property);
+ } else { // supports DynaBean and standard Objects
+ return PropertyUtils.getSimpleProperty(bean, property);
+ }
+ }
+
+ /**
+ * Get a named property from <code>bean</code>.
+ *
+ * @param bean
+ * @param propertyName
+ * @return Object found
+ * @throws InvocationTargetException
+ * @throws NoSuchMethodException
+ * @throws IllegalAccessException
+ */
+ public static Object getProperty(Object bean, String propertyName) throws InvocationTargetException,
+ NoSuchMethodException, IllegalAccessException {
+ return new PropertyAccess(bean.getClass(), propertyName).get(bean);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String toString() {
+ return "Property{" + beanClass.getName() + '.' + propertyName + '}';
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Type getJavaType() {
+ /*
+ * if(Map.class.isAssignableFrom(beanClass)) { return beanClass. }
+ */
+ if (rememberField != null) { // use cached field of previous access
+ return rememberField.getGenericType();
+ }
+ for (PropertyDescriptor each : PropertyUtils.getPropertyDescriptors(beanClass)) {
+ if (each.getName().equals(propertyName) && each.getReadMethod() != null) {
+ return each.getReadMethod().getGenericReturnType();
+ }
+ }
+ try { // try public field
+ return beanClass.getField(propertyName).getGenericType();
+ } catch (NoSuchFieldException ex2) {
+ // search for private/protected field up the hierarchy
+ Class<?> theClass = beanClass;
+ while (theClass != null) {
+ try {
+ return theClass.getDeclaredField(propertyName).getGenericType();
+ } catch (NoSuchFieldException ex3) {
+ // do nothing
+ }
+ theClass = theClass.getSuperclass();
+ }
+ }
+ return Object.class; // unknown type: allow any type??
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Object get(Object bean) {
try {
- Field aField = theClass
- .getDeclaredField(propertyName);
- if (!aField.isAccessible()) {
- aField.setAccessible(true);
- }
- value = aField.get(bean);
- rememberField = aField;
- return value;
- } catch (NoSuchFieldException ex3) {
- // do nothing
- }
- theClass = theClass.getSuperclass();
- }
- throw new IllegalArgumentException(
- "cannot access field " + propertyName);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- PropertyAccess that = (PropertyAccess) o;
-
- return beanClass.equals(that.beanClass) && propertyName.equals(that.propertyName);
- }
-
- /**
- * {@inheritDoc}
- */
- public int hashCode() {
- int result;
- result = beanClass.hashCode();
- result = 31 * result + propertyName.hashCode();
- return result;
- }
+ if (rememberField != null) { // cache field of previous access
+ return rememberField.get(bean);
+ }
+
+ try { // try public method
+ return getPublicProperty(bean, propertyName);
+ } catch (NoSuchMethodException ex) {
+ return getFieldValue(bean);
+ }
+ } catch (IllegalArgumentException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new IllegalArgumentException("cannot access " + propertyName, e);
+ }
+ }
+
+ private Object getFieldValue(Object bean) throws IllegalAccessException {
+ Object value;
+ try { // try public field
+ Field aField = bean.getClass().getField(propertyName);
+ value = aField.get(bean);
+ rememberField = aField;
+ return value;
+ } catch (NoSuchFieldException ex2) {
+ // search for private/protected field up the hierarchy
+ Class<?> theClass = bean.getClass();
+ while (theClass != null) {
+ try {
+ Field aField = theClass.getDeclaredField(propertyName);
+ if (!aField.isAccessible()) {
+ aField.setAccessible(true);
+ }
+ value = aField.get(bean);
+ rememberField = aField;
+ return value;
+ } catch (NoSuchFieldException ex3) {
+ // do nothing
+ }
+ theClass = theClass.getSuperclass();
+ }
+ throw new IllegalArgumentException("cannot access field " + propertyName);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ PropertyAccess that = (PropertyAccess) o;
+
+ return beanClass.equals(that.beanClass) && propertyName.equals(that.propertyName);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public int hashCode() {
+ int result;
+ result = beanClass.hashCode();
+ result = 31 * result + propertyName.hashCode();
+ return result;
+ }
}
Modified: incubator/bval/trunk/bval-core/src/test/java/org/apache/bval/model/ExampleEnum.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-core/src/test/java/org/apache/bval/model/ExampleEnum.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-core/src/test/java/org/apache/bval/model/ExampleEnum.java (original)
+++ incubator/bval/trunk/bval-core/src/test/java/org/apache/bval/model/ExampleEnum.java Fri Sep 3 19:02:18 2010
@@ -23,5 +23,5 @@ package org.apache.bval.model;
* Time: 18:00:12<br>
*/
public enum ExampleEnum {
- VALUE1, VALUE2, VALUE3
+ VALUE1, VALUE2, VALUE3
}
Modified: incubator/bval/trunk/bval-json/src/test/java/org/apache/bval/json/JSONGeneratorTest.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-json/src/test/java/org/apache/bval/json/JSONGeneratorTest.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-json/src/test/java/org/apache/bval/json/JSONGeneratorTest.java (original)
+++ incubator/bval/trunk/bval-json/src/test/java/org/apache/bval/json/JSONGeneratorTest.java Fri Sep 3 19:02:18 2010
@@ -34,74 +34,71 @@ import java.util.List;
* Author: roman.stumm<br>
*/
public class JSONGeneratorTest extends TestCase {
- private XMLMetaBeanManager mbm;
+ private XMLMetaBeanManager mbm;
- public JSONGeneratorTest(String name) {
- super(name);
- }
-
- public void setUp() throws Exception {
- super.setUp();
- mbm = new XMLMetaBeanManager();
- mbm.addLoader(new XMLMetaBeanURLLoader(
- BusinessObject.class.getResource("test-beanInfos.xml")));
- }
-
- public void testBeanInfosCustomPatchGenerated()
- throws Exception {
- MetaBean mbean = mbm.findForClass(BusinessObject.class);
- MetaProperty mprop = mbean.getProperty("lastName");
- assertTrue(mprop.isMandatory());
-
- mbm.getCache().removeFromCache(mbean);
- mbm.addLoader(new XMLMetaBeanURLLoader(
- BusinessObject.class.getResource("test-beanInfos-custom.xml")));
- mbean = mbm.findForClass(BusinessObject.class);
- mprop = mbean.getProperty("lastName");
- assertTrue(!mprop.isMandatory());
-
- JSONGenerator converter = new JSONGenerator();
-
- List<MetaBean> metaBeans = new ArrayList(2);
- metaBeans.add(mbean);
- MetaBean mbean2 = mbm.findForId("UnknownObject");
- metaBeans.add(mbean2);
- String json = converter.toJSON(metaBeans);
- assertNotNull(json);
- //System.out.println(json);
- }
-
- public void testJSON() throws Exception {
- MetaBean info = mbm.findForClass(BusinessObject.class);
- MetaBean info2 = info.getProperty("address").getMetaBean();
-
- // empty default bean without xml backup
- MetaBean info3 = mbm.findForClass(BusinessObjectAddress.class);
- JSONGenerator converter = new JSONGenerator();
-
- List<MetaBean> metaBeans = new ArrayList(2);
- metaBeans.add(info);
- metaBeans.add(info2);
- metaBeans.add(info3);
- String json = converter.toJSON(metaBeans);
- assertNotNull(json);
- //System.out.println(json);
- }
-
- public void testJSON_dynaTypeEnum() throws Exception {
- MetaBean info = mbm.findForClass(BusinessObject.class);
- MetaProperty choice = info.getProperty("choice");
- choice.setType(new DynaTypeEnum(BusinessEnum.class, "CUSTOM_1", "CUSTOM_2"));
-
- JSONGenerator converter = new JSONGenerator();
-
- List<MetaBean> metaBeans = new ArrayList(1);
- metaBeans.add(info);
- String json = converter.toJSON(metaBeans);
- assertNotNull(json);
-// System.out.println(json);
- assertTrue(json.indexOf("CUSTOM_1") > 0);
- assertTrue(json.indexOf("CUSTOM_2") > 0);
- assertTrue(json.indexOf("VALUE1") < 0);
- }
+ public JSONGeneratorTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ mbm = new XMLMetaBeanManager();
+ mbm.addLoader(new XMLMetaBeanURLLoader(BusinessObject.class.getResource("test-beanInfos.xml")));
+ }
+
+ public void testBeanInfosCustomPatchGenerated() throws Exception {
+ MetaBean mbean = mbm.findForClass(BusinessObject.class);
+ MetaProperty mprop = mbean.getProperty("lastName");
+ assertTrue(mprop.isMandatory());
+
+ mbm.getCache().removeFromCache(mbean);
+ mbm.addLoader(new XMLMetaBeanURLLoader(BusinessObject.class.getResource("test-beanInfos-custom.xml")));
+ mbean = mbm.findForClass(BusinessObject.class);
+ mprop = mbean.getProperty("lastName");
+ assertTrue(!mprop.isMandatory());
+
+ JSONGenerator converter = new JSONGenerator();
+
+ List<MetaBean> metaBeans = new ArrayList(2);
+ metaBeans.add(mbean);
+ MetaBean mbean2 = mbm.findForId("UnknownObject");
+ metaBeans.add(mbean2);
+ String json = converter.toJSON(metaBeans);
+ assertNotNull(json);
+ // System.out.println(json);
+ }
+
+ public void testJSON() throws Exception {
+ MetaBean info = mbm.findForClass(BusinessObject.class);
+ MetaBean info2 = info.getProperty("address").getMetaBean();
+
+ // empty default bean without xml backup
+ MetaBean info3 = mbm.findForClass(BusinessObjectAddress.class);
+ JSONGenerator converter = new JSONGenerator();
+
+ List<MetaBean> metaBeans = new ArrayList(2);
+ metaBeans.add(info);
+ metaBeans.add(info2);
+ metaBeans.add(info3);
+ String json = converter.toJSON(metaBeans);
+ assertNotNull(json);
+ // System.out.println(json);
+ }
+
+ public void testJSON_dynaTypeEnum() throws Exception {
+ MetaBean info = mbm.findForClass(BusinessObject.class);
+ MetaProperty choice = info.getProperty("choice");
+ choice.setType(new DynaTypeEnum(BusinessEnum.class, "CUSTOM_1", "CUSTOM_2"));
+
+ JSONGenerator converter = new JSONGenerator();
+
+ List<MetaBean> metaBeans = new ArrayList(1);
+ metaBeans.add(info);
+ String json = converter.toJSON(metaBeans);
+ assertNotNull(json);
+ // System.out.println(json);
+ assertTrue(json.indexOf("CUSTOM_1") > 0);
+ assertTrue(json.indexOf("CUSTOM_2") > 0);
+ assertTrue(json.indexOf("VALUE1") < 0);
+ }
}
Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java Fri Sep 3 19:02:18 2010
@@ -28,171 +28,178 @@ import java.util.ArrayList;
import java.util.List;
/**
- * Description: Represents the context that is used to create <code>ClassValidator</code>
- * instances.<br/>
+ * Description: Represents the context that is used to create
+ * <code>ClassValidator</code> instances.<br/>
*/
public class ApacheFactoryContext implements ValidatorContext {
- private final ApacheValidatorFactory factory;
- private final MetaBeanFinder metaBeanFinder;
+ private final ApacheValidatorFactory factory;
+ private final MetaBeanFinder metaBeanFinder;
- private MessageInterpolator messageInterpolator;
- private TraversableResolver traversableResolver;
- private ConstraintValidatorFactory constraintValidatorFactory;
-
- /**
- * Create a new ApacheFactoryContext instance.
- * @param factory
- */
- public ApacheFactoryContext(ApacheValidatorFactory factory) {
- this.factory = factory;
- this.metaBeanFinder = buildMetaBeanManager();
- }
-
- /**
- * Create a new ApacheFactoryContext instance.
- * @param factory
- * @param metaBeanFinder
- */
- protected ApacheFactoryContext(ApacheValidatorFactory factory,
- MetaBeanFinder metaBeanFinder) {
- this.factory = factory;
- this.metaBeanFinder = metaBeanFinder;
- }
-
- /**
- * Get the {@link ApacheValidatorFactory} used by this {@link ApacheFactoryContext}.
- * @return {@link ApacheValidatorFactory}
- */
- public ApacheValidatorFactory getFactory() {
- return factory;
- }
-
- /**
- * Get the metaBeanFinder.
- * @return {@link MetaBeanFinder}
- */
- public final MetaBeanFinder getMetaBeanFinder() {
- return metaBeanFinder;
- }
-
- /**
- * {@inheritDoc}
- */
- public ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator) {
- this.messageInterpolator = messageInterpolator;
- return this;
- }
-
- /**
- * {@inheritDoc}
- */
- public ValidatorContext traversableResolver(TraversableResolver traversableResolver) {
- this.traversableResolver = traversableResolver;
- return this;
- }
-
- /**
- * {@inheritDoc}
- */
- public ValidatorContext constraintValidatorFactory(
- ConstraintValidatorFactory constraintValidatorFactory) {
- this.constraintValidatorFactory = constraintValidatorFactory;
- return this;
- }
-
- /**
- * Get the {@link ConstraintValidatorFactory}.
- * @return {@link ConstraintValidatorFactory}
- */
- public ConstraintValidatorFactory getConstraintValidatorFactory() {
- return constraintValidatorFactory == null ? factory.getConstraintValidatorFactory() :
- constraintValidatorFactory;
- }
-
- /**
- * {@inheritDoc}
- */
- public Validator getValidator() {
- ClassValidator validator = new ClassValidator(this);
- if (Boolean.getBoolean(factory.getProperties().get(
- ApacheValidatorConfiguration.Properties.TREAT_MAPS_LIKE_BEANS))) {
- validator.setTreatMapsLikeBeans(true);
- }
- return validator;
- }
-
- /**
- * Get the {@link MessageInterpolator}.
- * @return {@link MessageInterpolator}
- */
- public MessageInterpolator getMessageInterpolator() {
- return messageInterpolator == null ? factory.getMessageInterpolator() :
- messageInterpolator;
- }
-
- /**
- * Get the {@link TraversableResolver}.
- * @return {@link TraversableResolver}
- */
- public TraversableResolver getTraversableResolver() {
- return traversableResolver == null ? factory.getTraversableResolver() :
- traversableResolver;
- }
-
- /**
- * Create MetaBeanManager that
- * uses JSR303-XML + JSR303-Annotations
- * to build meta-data from.
- *
- * @return a new instance of MetaBeanManager with adequate MetaBeanFactories
- */
- @SuppressWarnings("deprecation")
- protected MetaBeanManager buildMetaBeanManager() {
- // this is relevant: xml before annotations
- // (because ignore-annotations settings in xml)
- List<MetaBeanFactory> builders = new ArrayList<MetaBeanFactory>(3);
- if (Boolean.parseBoolean(factory.getProperties().get(
- ApacheValidatorConfiguration.Properties.ENABLE_INTROSPECTOR))) {
- builders.add(new IntrospectorMetaBeanFactory());
- }
- builders.add(new Jsr303MetaBeanFactory(this));
- // as long as we support both: jsr303 and xstream-xml metabeans:
- if (Boolean.parseBoolean(factory.getProperties().get(
- ApacheValidatorConfiguration.Properties.ENABLE_METABEANS_XML))) {
- return XMLMetaBeanManagerCreator.createXMLMetaBeanManager(builders);
- } else {
- return createMetaBeanManager(builders);
- }
- }
-
- /**
- * Create a {@link MetaBeanManager} using the specified builders.
- * @param builders {@link MetaBeanFactory} {@link List}
- * @return {@link MetaBeanManager}
- */
- protected MetaBeanManager createMetaBeanManager(List<MetaBeanFactory> builders) {
- return new MetaBeanManager(
- new MetaBeanBuilder(builders.toArray(new MetaBeanFactory[builders.size()])));
- }
-
- /**
- * separate class to prevent the classloader to immediately load
- * optional classes: XMLMetaBeanManager, XMLMetaBeanFactory, XMLMetaBeanBuilder
- * that might not be available in the classpath
- */
- private static class XMLMetaBeanManagerCreator {
+ private MessageInterpolator messageInterpolator;
+ private TraversableResolver traversableResolver;
+ private ConstraintValidatorFactory constraintValidatorFactory;
/**
- * Create the {@link MetaBeanManager} to process JSR303 XML. Requires bval-xstream at RT.
+ * Create a new ApacheFactoryContext instance.
+ *
+ * @param factory
+ */
+ public ApacheFactoryContext(ApacheValidatorFactory factory) {
+ this.factory = factory;
+ this.metaBeanFinder = buildMetaBeanManager();
+ }
+
+ /**
+ * Create a new ApacheFactoryContext instance.
+ *
+ * @param factory
+ * @param metaBeanFinder
+ */
+ protected ApacheFactoryContext(ApacheValidatorFactory factory, MetaBeanFinder metaBeanFinder) {
+ this.factory = factory;
+ this.metaBeanFinder = metaBeanFinder;
+ }
+
+ /**
+ * Get the {@link ApacheValidatorFactory} used by this
+ * {@link ApacheFactoryContext}.
+ *
+ * @return {@link ApacheValidatorFactory}
+ */
+ public ApacheValidatorFactory getFactory() {
+ return factory;
+ }
+
+ /**
+ * Get the metaBeanFinder.
+ *
+ * @return {@link MetaBeanFinder}
+ */
+ public final MetaBeanFinder getMetaBeanFinder() {
+ return metaBeanFinder;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator) {
+ this.messageInterpolator = messageInterpolator;
+ return this;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorContext traversableResolver(TraversableResolver traversableResolver) {
+ this.traversableResolver = traversableResolver;
+ return this;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorContext constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
+ this.constraintValidatorFactory = constraintValidatorFactory;
+ return this;
+ }
+
+ /**
+ * Get the {@link ConstraintValidatorFactory}.
+ *
+ * @return {@link ConstraintValidatorFactory}
+ */
+ public ConstraintValidatorFactory getConstraintValidatorFactory() {
+ return constraintValidatorFactory == null ? factory.getConstraintValidatorFactory()
+ : constraintValidatorFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Validator getValidator() {
+ ClassValidator validator = new ClassValidator(this);
+ if (Boolean.getBoolean(factory.getProperties().get(
+ ApacheValidatorConfiguration.Properties.TREAT_MAPS_LIKE_BEANS))) {
+ validator.setTreatMapsLikeBeans(true);
+ }
+ return validator;
+ }
+
+ /**
+ * Get the {@link MessageInterpolator}.
+ *
+ * @return {@link MessageInterpolator}
+ */
+ public MessageInterpolator getMessageInterpolator() {
+ return messageInterpolator == null ? factory.getMessageInterpolator() : messageInterpolator;
+ }
+
+ /**
+ * Get the {@link TraversableResolver}.
+ *
+ * @return {@link TraversableResolver}
+ */
+ public TraversableResolver getTraversableResolver() {
+ return traversableResolver == null ? factory.getTraversableResolver() : traversableResolver;
+ }
+
+ /**
+ * Create MetaBeanManager that uses JSR303-XML + JSR303-Annotations to build
+ * meta-data from.
+ *
+ * @return a new instance of MetaBeanManager with adequate MetaBeanFactories
+ */
+ @SuppressWarnings("deprecation")
+ protected MetaBeanManager buildMetaBeanManager() {
+ // this is relevant: xml before annotations
+ // (because ignore-annotations settings in xml)
+ List<MetaBeanFactory> builders = new ArrayList<MetaBeanFactory>(3);
+ if (Boolean.parseBoolean(factory.getProperties().get(
+ ApacheValidatorConfiguration.Properties.ENABLE_INTROSPECTOR))) {
+ builders.add(new IntrospectorMetaBeanFactory());
+ }
+ builders.add(new Jsr303MetaBeanFactory(this));
+ // as long as we support both: jsr303 and xstream-xml metabeans:
+ if (Boolean.parseBoolean(factory.getProperties().get(
+ ApacheValidatorConfiguration.Properties.ENABLE_METABEANS_XML))) {
+ return XMLMetaBeanManagerCreator.createXMLMetaBeanManager(builders);
+ } else {
+ return createMetaBeanManager(builders);
+ }
+ }
+
+ /**
+ * Create a {@link MetaBeanManager} using the specified builders.
+ *
* @param builders
+ * {@link MetaBeanFactory} {@link List}
* @return {@link MetaBeanManager}
*/
- // NOTE - We return MetaBeanManager instead of XMLMetaBeanManager to keep
- // bval-xstream an optional module.
- protected static MetaBeanManager createXMLMetaBeanManager(List<MetaBeanFactory> builders) {
- builders.add(new XMLMetaBeanFactory());
- return new XMLMetaBeanManager(
- new XMLMetaBeanBuilder(builders.toArray(new MetaBeanFactory[builders.size()])));
+ protected MetaBeanManager createMetaBeanManager(List<MetaBeanFactory> builders) {
+ return new MetaBeanManager(new MetaBeanBuilder(builders.toArray(new MetaBeanFactory[builders.size()])));
+ }
+
+ /**
+ * separate class to prevent the classloader to immediately load optional
+ * classes: XMLMetaBeanManager, XMLMetaBeanFactory, XMLMetaBeanBuilder that
+ * might not be available in the classpath
+ */
+ private static class XMLMetaBeanManagerCreator {
+
+ /**
+ * Create the {@link MetaBeanManager} to process JSR303 XML. Requires
+ * bval-xstream at RT.
+ *
+ * @param builders
+ * @return {@link MetaBeanManager}
+ */
+ // NOTE - We return MetaBeanManager instead of XMLMetaBeanManager to
+ // keep
+ // bval-xstream an optional module.
+ protected static MetaBeanManager createXMLMetaBeanManager(List<MetaBeanFactory> builders) {
+ builders.add(new XMLMetaBeanFactory());
+ return new XMLMetaBeanManager(
+ new XMLMetaBeanBuilder(builders.toArray(new MetaBeanFactory[builders.size()])));
+ }
}
- }
}
Modified: incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDescriptorImpl.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDescriptorImpl.java?rev=992420&r1=992419&r2=992420&view=diff
==============================================================================
--- incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDescriptorImpl.java (original)
+++ incubator/bval/trunk/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDescriptorImpl.java Fri Sep 3 19:02:18 2010
@@ -27,103 +27,106 @@ import java.util.Map;
import java.util.Set;
/**
- * Description: immutable, serializable implementation of ConstraintDescriptor interface of JSR303<br>
+ * Description: immutable, serializable implementation of ConstraintDescriptor
+ * interface of JSR303<br>
* User: roman.stumm<br>
* Date: 22.04.2010<br>
* Time: 10:21:23<br>
*/
public class ConstraintDescriptorImpl<T extends Annotation> implements ConstraintDescriptor<T>, Serializable {
- /** Serialization version */
- private static final long serialVersionUID = 1L;
+ /** Serialization version */
+ private static final long serialVersionUID = 1L;
- private final T annotation;
- private final Set<Class<?>> groups;
- private final Set<Class<? extends javax.validation.Payload>> payload;
- private final List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> constraintValidatorClasses;
- private final Map<String, Object> attributes;
- private final Set<ConstraintDescriptor<?>> composingConstraints;
- private final boolean reportAsSingleViolation;
-
- /**
- * Create a new ConstraintDescriptorImpl instance.
- * @param descriptor
- */
- public ConstraintDescriptorImpl(ConstraintDescriptor<T> descriptor) {
- this(descriptor.getAnnotation(), descriptor.getGroups(), descriptor.getPayload(),
- descriptor.getConstraintValidatorClasses(),
- descriptor.getAttributes(), descriptor.getComposingConstraints(), descriptor.isReportAsSingleViolation());
- }
-
- /**
- * Create a new ConstraintDescriptorImpl instance.
- * @param annotation
- * @param groups
- * @param payload
- * @param constraintValidatorClasses
- * @param attributes
- * @param composingConstraints
- * @param reportAsSingleViolation
- */
- public ConstraintDescriptorImpl(T annotation, Set<Class<?>> groups,
- Set<Class<? extends javax.validation.Payload>> payload,
- List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> constraintValidatorClasses,
- Map<String, Object> attributes,
- Set<ConstraintDescriptor<?>> composingConstraints, boolean reportAsSingleViolation) {
- this.annotation = annotation;
- this.groups = groups;
- this.payload = payload;
- this.constraintValidatorClasses = constraintValidatorClasses;
- this.attributes = attributes;
- this.composingConstraints = composingConstraints;
- this.reportAsSingleViolation = reportAsSingleViolation;
- }
-
- /**
- * {@inheritDoc}
- */
- public T getAnnotation() {
- return annotation;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Class<?>> getGroups() {
- return groups;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Class<? extends Payload>> getPayload() {
- return payload;
- }
-
- /**
- * {@inheritDoc}
- */
- public List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
- return constraintValidatorClasses;
- }
-
- /**
- * {@inheritDoc}
- */
- public Map<String, Object> getAttributes() {
- return attributes;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<ConstraintDescriptor<?>> getComposingConstraints() {
- return composingConstraints;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isReportAsSingleViolation() {
- return reportAsSingleViolation;
- }
+ private final T annotation;
+ private final Set<Class<?>> groups;
+ private final Set<Class<? extends javax.validation.Payload>> payload;
+ private final List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> constraintValidatorClasses;
+ private final Map<String, Object> attributes;
+ private final Set<ConstraintDescriptor<?>> composingConstraints;
+ private final boolean reportAsSingleViolation;
+
+ /**
+ * Create a new ConstraintDescriptorImpl instance.
+ *
+ * @param descriptor
+ */
+ public ConstraintDescriptorImpl(ConstraintDescriptor<T> descriptor) {
+ this(descriptor.getAnnotation(), descriptor.getGroups(), descriptor.getPayload(), descriptor
+ .getConstraintValidatorClasses(), descriptor.getAttributes(), descriptor.getComposingConstraints(),
+ descriptor.isReportAsSingleViolation());
+ }
+
+ /**
+ * Create a new ConstraintDescriptorImpl instance.
+ *
+ * @param annotation
+ * @param groups
+ * @param payload
+ * @param constraintValidatorClasses
+ * @param attributes
+ * @param composingConstraints
+ * @param reportAsSingleViolation
+ */
+ public ConstraintDescriptorImpl(T annotation, Set<Class<?>> groups,
+ Set<Class<? extends javax.validation.Payload>> payload,
+ List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> constraintValidatorClasses,
+ Map<String, Object> attributes, Set<ConstraintDescriptor<?>> composingConstraints,
+ boolean reportAsSingleViolation) {
+ this.annotation = annotation;
+ this.groups = groups;
+ this.payload = payload;
+ this.constraintValidatorClasses = constraintValidatorClasses;
+ this.attributes = attributes;
+ this.composingConstraints = composingConstraints;
+ this.reportAsSingleViolation = reportAsSingleViolation;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public T getAnnotation() {
+ return annotation;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<Class<?>> getGroups() {
+ return groups;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<Class<? extends Payload>> getPayload() {
+ return payload;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public List<java.lang.Class<? extends javax.validation.ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
+ return constraintValidatorClasses;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Map<String, Object> getAttributes() {
+ return attributes;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<ConstraintDescriptor<?>> getComposingConstraints() {
+ return composingConstraints;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isReportAsSingleViolation() {
+ return reportAsSingleViolation;
+ }
}