bval-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rmannibu...@apache.org
Subject svn commit: r1613845 - in /bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval: cdi/BValExtension.java jsr/ApacheValidatorFactory.java jsr/ConfigurationImpl.java jsr/xml/ValidationParser.java
Date Sun, 27 Jul 2014 21:12:50 GMT
Author: rmannibucau
Date: Sun Jul 27 21:12:50 2014
New Revision: 1613845

URL: http://svn.apache.org/r1613845
Log:
use an internal factory to know if we need to wrap cdi bean with BvalInterceptor or not

Modified:
    bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/cdi/BValExtension.java
    bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ApacheValidatorFactory.java
    bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ConfigurationImpl.java
    bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/xml/ValidationParser.java

Modified: bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/cdi/BValExtension.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/cdi/BValExtension.java?rev=1613845&r1=1613844&r2=1613845&view=diff
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/cdi/BValExtension.java (original)
+++ bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/cdi/BValExtension.java Sun
Jul 27 21:12:50 2014
@@ -18,10 +18,13 @@
  */
 package org.apache.bval.cdi;
 
+import org.apache.bval.jsr.parameter.DefaultParameterNameProvider;
+
 import javax.enterprise.context.spi.CreationalContext;
 import javax.enterprise.event.Observes;
 import javax.enterprise.inject.spi.AfterBeanDiscovery;
 import javax.enterprise.inject.spi.AfterDeploymentValidation;
+import javax.enterprise.inject.spi.AnnotatedCallable;
 import javax.enterprise.inject.spi.AnnotatedType;
 import javax.enterprise.inject.spi.Bean;
 import javax.enterprise.inject.spi.BeanManager;
@@ -36,11 +39,16 @@ import javax.naming.NamingException;
 import javax.validation.BootstrapConfiguration;
 import javax.validation.Configuration;
 import javax.validation.Validation;
+import javax.validation.ValidationException;
 import javax.validation.Validator;
 import javax.validation.ValidatorFactory;
 import javax.validation.executable.ExecutableType;
+import javax.validation.executable.ValidateOnExecution;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.MethodType;
 import java.lang.reflect.Modifier;
 import java.lang.reflect.Type;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Map;
 import java.util.Set;
@@ -61,7 +69,14 @@ public class BValExtension implements Ex
     private boolean validatorFound = Boolean.getBoolean("bval.in-container");
     private boolean validatorFactoryFound = Boolean.getBoolean("bval.in-container");
 
+    private boolean validBean;
+    private boolean validConstructors;
+    private boolean validBusinessMethods;
+    private boolean validGetterMethods;
+
     private final Configuration<?> config;
+    private ValidatorFactory factory;
+    private Validator validator;
 
     private Set<ExecutableType> globalExecutableTypes;
     private boolean isExecutableValidationEnabled;
@@ -72,6 +87,11 @@ public class BValExtension implements Ex
             final BootstrapConfiguration bootstrap = config.getBootstrapConfiguration();
             globalExecutableTypes = convertToRuntimeTypes(bootstrap.getDefaultValidatedExecutableTypes());
             isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled();
+
+            validBean = globalExecutableTypes.contains(ExecutableType.IMPLICIT) || globalExecutableTypes.contains(ExecutableType.ALL);
+            validConstructors =validBean || globalExecutableTypes.contains(ExecutableType.CONSTRUCTORS);
+            validBusinessMethods = validBean || globalExecutableTypes.contains(ExecutableType.NON_GETTER_METHODS);
+            validGetterMethods = globalExecutableTypes.contains(ExecutableType.ALL) || globalExecutableTypes.contains(ExecutableType.GETTER_METHODS);
         } catch (final Exception e) { // custom providers can throw an exception
             LOGGER.log(Level.SEVERE, e.getMessage(), e);
 
@@ -80,6 +100,16 @@ public class BValExtension implements Ex
         }
     }
 
+    // lazily to get a small luck to have CDI in place
+    private void ensureFactoryValidator() {
+        if (validator != null) {
+            return;
+        }
+        config.addProperty("bval.before.cdi", "true"); // ignore parts of the config relying
on CDI since we didn't start yet
+        factory = factory != null ? factory : config.buildValidatorFactory();
+        validator = factory.getValidator();
+    }
+
     private static Set<ExecutableType> convertToRuntimeTypes(final Set<ExecutableType>
defaultValidatedExecutableTypes) {
         final Set<ExecutableType> types = new CopyOnWriteArraySet<ExecutableType>();
         for (final ExecutableType type : defaultValidatedExecutableTypes) {
@@ -107,10 +137,6 @@ public class BValExtension implements Ex
     }
 
     public void addBvalBinding(final @Observes BeforeBeanDiscovery beforeBeanDiscovery, final
BeanManager beanManager) {
-        if (!isExecutableValidationEnabled) {
-            return;
-        }
-
         beforeBeanDiscovery.addInterceptorBinding(BValBinding.class);
         beforeBeanDiscovery.addAnnotatedType(beanManager.createAnnotatedType(BValInterceptor.class));
     }
@@ -120,14 +146,42 @@ public class BValExtension implements Ex
             return;
         }
 
-        final Class<A> javaClass = pat.getAnnotatedType().getJavaClass();
+        final AnnotatedType<A> annotatedType = pat.getAnnotatedType();
+        final Class<A> javaClass = annotatedType.getJavaClass();
         final int modifiers = javaClass.getModifiers();
         if (!javaClass.getName().startsWith("javax.") && !javaClass.getName().startsWith("org.apache.bval")
                 && !javaClass.isInterface() && !Modifier.isFinal(modifiers)
&& !Modifier.isAbstract(modifiers)) {
-            pat.setAnnotatedType(new BValAnnotatedType<A>(pat.getAnnotatedType()));
+            ensureFactoryValidator();
+            try {
+                final BeanDescriptor classConstraints = validator.getConstraintsForClass(javaClass);
+                if (annotatedType.isAnnotationPresent(ValidateOnExecution.class)
+                    || hasValidationAnnotation(annotatedType.getMethods())
+                    || hasValidationAnnotation(annotatedType.getConstructors())
+                    || (validBean && classConstraints.isBeanConstrained())
+                    || (validConstructors && !classConstraints.getConstrainedConstructors().isEmpty())
+                    || (validBusinessMethods && !classConstraints.getConstrainedMethods(MethodType.NON_GETTER).isEmpty())
+                    || (validGetterMethods && !classConstraints.getConstrainedMethods(MethodType.GETTER).isEmpty()))
{
+                    // TODO: keep track of bValAnnotatedType and remove @BValBinding in
+                    // ProcessBean event if needed cause here we can't really add @ValidateOnExecution
+                    // through an extension
+                    final BValAnnotatedType<A> bValAnnotatedType = new BValAnnotatedType<A>(annotatedType);
+                    pat.setAnnotatedType(bValAnnotatedType);
+                }
+            } catch (final ValidationException ve) {
+                LOGGER.log(Level.SEVERE, ve.getMessage(), ve);
+            }
         }
     }
 
+    private static <A> boolean hasValidationAnnotation(final Collection<? extends
AnnotatedCallable<? super A>> methods) {
+        for (final AnnotatedCallable<? super A> m : methods) {
+            if (m.isAnnotationPresent(ValidateOnExecution.class)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     public <A> void processBean(final @Observes ProcessBean<A> processBeanEvent)
{
         if (validatorFound && validatorFactoryFound) {
             return;
@@ -148,35 +202,47 @@ public class BValExtension implements Ex
     }
 
     public void addBValBeans(final @Observes AfterBeanDiscovery afterBeanDiscovery, final
BeanManager beanManager) {
-        captureBeanManager(beanManager);
+        if (factory != null) { // cleanup cache used to discover ValidateOnException before
factory is recreated
+            factory.close();
+        }
+
+        captureBeanManager(beanManager); // next method will need it
         cdiIntegration(afterBeanDiscovery, beanManager);
     }
 
     private void captureBeanManager(final BeanManager beanManager) {
         // bean manager holder
         if (bmpSingleton == null) {
-            bmpSingleton = this;
+            synchronized (LOGGER) { // a static instance
+                if (bmpSingleton == null) {
+                    bmpSingleton = this;
+                }
+            }
         }
+
         final BeanManagerInfo bmi = getBeanManagerInfo(loader());
         bmi.loadTimeBm = beanManager;
     }
 
     private void cdiIntegration(final AfterBeanDiscovery afterBeanDiscovery, final BeanManager
beanManager) {
-        // add validator and validatorFactory if needed
-        ValidatorFactory factory = null;
+        try {
+            config.addProperty("bval.before.cdi", "false"); // now take into account all
the config
+        } catch (final Exception e) {
+            // no-op: sadly tck does it
+        }
+
         if (!validatorFactoryFound) {
-            try {
-                factory = config.buildValidatorFactory();
-                afterBeanDiscovery.addBean(new ValidatorFactoryBean(factory));
+            try { // recreate the factory
+                afterBeanDiscovery.addBean(new ValidatorFactoryBean(factory = config.buildValidatorFactory()));
             } catch (final Exception e) { // can throw an exception with custom providers
                 LOGGER.log(Level.SEVERE, e.getMessage(), e);
             }
         }
         if (!validatorFound) {
             try {
-                if (factory == null) {
+                if (validatorFactoryFound) {
                     factory = config.buildValidatorFactory();
-                }
+                } // else fresh factory already created in previous if
                 afterBeanDiscovery.addBean(new ValidatorBean(factory.getValidator()));
                 validatorFound = true;
             } catch (final Exception e) { // getValidator can throw an exception with custom
providers
@@ -216,14 +282,14 @@ public class BValExtension implements Ex
         return result;
     }
 
-    public void cleanupFinalBeanManagers(final @Observes AfterDeploymentValidation adv) {
+    public void cleanupFinalBeanManagers(final @Observes AfterDeploymentValidation ignored)
{
         for (final BeanManagerInfo bmi : bmpSingleton.bmInfos.values()) {
             bmi.finalBm = null;
         }
     }
 
-    public void cleanupStoredBeanManagerOnShutdown(final @Observes BeforeShutdown beforeShutdown)
{
-        if (bmpSingleton.bmInfos != null) {
+    public void cleanupStoredBeanManagerOnShutdown(final @Observes BeforeShutdown ignored)
{
+        if (bmpSingleton != null && bmpSingleton.bmInfos != null) {
             bmpSingleton.bmInfos.remove(loader());
         }
     }

Modified: bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ApacheValidatorFactory.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ApacheValidatorFactory.java?rev=1613845&r1=1613844&r2=1613845&view=diff
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ApacheValidatorFactory.java
(original)
+++ bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ApacheValidatorFactory.java
Sun Jul 27 21:12:50 2014
@@ -54,7 +54,7 @@ import java.util.concurrent.ConcurrentMa
  */
 public class ApacheValidatorFactory implements ValidatorFactory, Cloneable {
     private static volatile ApacheValidatorFactory DEFAULT_FACTORY;
-    private static final ConstraintDefaults defaultConstraints = new ConstraintDefaults();
+    private static final ConstraintDefaults DEFAULT_CONSTRAINTS = new ConstraintDefaults();
 
     private MessageInterpolator messageResolver;
     private TraversableResolver traversableResolver;
@@ -76,6 +76,7 @@ public class ApacheValidatorFactory impl
     private final ConcurrentMap<Class<?>, List<MetaConstraint<?, ? extends
Annotation>>> constraintMap;
 
     private final Collection<Closeable> toClose = new ArrayList<Closeable>();
+    private volatile boolean init;
 
     /**
      * Convenience method to retrieve a default global ApacheValidatorFactory
@@ -122,10 +123,11 @@ public class ApacheValidatorFactory impl
      */
     protected void configure(final ConfigurationState configuration) {
         getProperties().putAll(configuration.getProperties());
-        setParameterNameProvider(configuration.getParameterNameProvider());
-        setMessageInterpolator(configuration.getMessageInterpolator());
-        setTraversableResolver(configuration.getTraversableResolver());
-        setConstraintValidatorFactory(configuration.getConstraintValidatorFactory());
+
+        parameterNameProvider = configuration.getParameterNameProvider();
+        messageResolver = configuration.getMessageInterpolator();
+        traversableResolver = configuration.getTraversableResolver();
+        constraintValidatorFactory = configuration.getConstraintValidatorFactory();
 
         if (ConfigurationImpl.class.isInstance(configuration)) {
             final ConfigurationImpl impl = ConfigurationImpl.class.cast(configuration);
@@ -305,7 +307,7 @@ public class ApacheValidatorFactory impl
      * @return ConstraintDefaults
      */
     public ConstraintDefaults getDefaultConstraints() {
-        return defaultConstraints;
+        return DEFAULT_CONSTRAINTS;
     }
 
     /**

Modified: bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ConfigurationImpl.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ConfigurationImpl.java?rev=1613845&r1=1613844&r2=1613845&view=diff
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ConfigurationImpl.java
(original)
+++ bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/ConfigurationImpl.java
Sun Jul 27 21:12:50 2014
@@ -18,7 +18,7 @@
  */
 package org.apache.bval.jsr;
 
-
+import org.apache.bval.cdi.BValExtension;
 import org.apache.bval.jsr.parameter.DefaultParameterNameProvider;
 import org.apache.bval.jsr.resolver.DefaultTraversableResolver;
 import org.apache.bval.jsr.util.IOs;
@@ -37,6 +37,7 @@ import javax.validation.spi.BootstrapSta
 import javax.validation.spi.ConfigurationState;
 import javax.validation.spi.ValidationProvider;
 import java.io.Closeable;
+import java.io.IOException;
 import java.io.InputStream;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
@@ -46,7 +47,7 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.logging.Logger;
+import java.util.concurrent.CopyOnWriteArrayList;
 
 /**
  * Description: used to configure apache-validation for jsr.
@@ -55,8 +56,6 @@ import java.util.logging.Logger;
  * <br/>
  */
 public class ConfigurationImpl implements ApacheValidatorConfiguration, ConfigurationState
{
-    private static final Logger log = Logger.getLogger(ConfigurationImpl.class.getName());
-
     /**
      * Configured {@link ValidationProvider}
      */
@@ -78,23 +77,31 @@ public class ConfigurationImpl implement
      */
     protected MessageInterpolator defaultMessageInterpolator = new DefaultMessageInterpolator();
     protected MessageInterpolator messageInterpolator = defaultMessageInterpolator;
+    protected Class<? extends MessageInterpolator> messageInterpolatorClass = null;
 
     /**
      * Configured {@link ConstraintValidatorFactory}
      */
     protected ConstraintValidatorFactory defaultConstraintValidatorFactory = new DefaultConstraintValidatorFactory();
     protected ConstraintValidatorFactory constraintValidatorFactory = defaultConstraintValidatorFactory;
+    protected Class<? extends ConstraintValidatorFactory> constraintValidatorFactoryClass
= null;
 
-    private TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
-    private TraversableResolver traversableResolver = defaultTraversableResolver;
+    protected TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
+    protected TraversableResolver traversableResolver = defaultTraversableResolver;
+    protected Class<? extends TraversableResolver> traversableResolverClass = null;
 
     protected ParameterNameProvider defaultParameterNameProvider = new DefaultParameterNameProvider();
     protected ParameterNameProvider parameterNameProvider = defaultParameterNameProvider;
+    protected Class<? extends ParameterNameProvider> parameterNameProviderClass = null;
 
     protected BootstrapConfiguration  bootstrapConfiguration;
 
     protected Collection<ExecutableType> executableValidation;
 
+    private Collection<BValExtension.Releasable> releasables = new CopyOnWriteArrayList<BValExtension.Releasable>();
+
+    private boolean beforeCdi = false;
+
     // BEGIN DEFAULTS
     /**
      * false = dirty flag (to prevent from multiple parsing validation.xml)
@@ -110,8 +117,8 @@ public class ConfigurationImpl implement
 
     /**
      * Create a new ConfigurationImpl instance.
-     * @param aState
-     * @param aProvider
+     * @param aState bootstrap state
+     * @param aProvider provider
      */
     public ConfigurationImpl(BootstrapState aState, ValidationProvider<?> aProvider)
{
         if (aProvider != null) {
@@ -136,7 +143,9 @@ public class ConfigurationImpl implement
         if (resolver == null) {
             return this;
         }
-        traversableResolver = resolver;
+
+        this.traversableResolverClass = null;
+        this.traversableResolver = resolver;
         this.prepared = false;
         return this;
     }
@@ -160,6 +169,8 @@ public class ConfigurationImpl implement
         if (resolver == null) {
             return this;
         }
+
+        this.messageInterpolatorClass = null;
         this.messageInterpolator = resolver;
         this.prepared = false;
         return this;
@@ -174,6 +185,7 @@ public class ConfigurationImpl implement
             return this;
         }
 
+        this.constraintValidatorFactoryClass = null;
         this.constraintValidatorFactory = constraintFactory;
         this.prepared = false;
         return this;
@@ -183,6 +195,7 @@ public class ConfigurationImpl implement
         if (parameterNameProvider == null) {
             return this;
         }
+        this.parameterNameProviderClass = null;
         this.parameterNameProvider = parameterNameProvider;
         return this;
     }
@@ -211,7 +224,11 @@ public class ConfigurationImpl implement
      * @return this
      */
     public ApacheValidatorConfiguration addProperty(String name, String value) {
-        properties.put(name, value);
+        if ("bval.before.cdi".equals(name)) {
+            beforeCdi = Boolean.parseBoolean(value);
+        } else {
+            properties.put(name, value);
+        }
         return this;
     }
 
@@ -263,6 +280,17 @@ public class ConfigurationImpl implement
      * {@inheritDoc}
      */
     public MessageInterpolator getMessageInterpolator() {
+        if (beforeCdi) {
+            return defaultMessageInterpolator;
+        }
+
+        if (messageInterpolator == defaultMessageInterpolator && messageInterpolatorClass
!= null) {
+            synchronized (this) {
+                if (messageInterpolator == defaultMessageInterpolator && messageInterpolatorClass
!= null) {
+                    messageInterpolator = newInstance(messageInterpolatorClass);
+                }
+            }
+        }
         return messageInterpolator;
     }
 
@@ -332,6 +360,17 @@ public class ConfigurationImpl implement
      * @return the constraint validator factory of this configuration.
      */
     public ConstraintValidatorFactory getConstraintValidatorFactory() {
+        if (beforeCdi) {
+            return constraintValidatorFactory;
+        }
+
+        if (constraintValidatorFactory == defaultConstraintValidatorFactory && constraintValidatorFactoryClass
!= null) {
+            synchronized (this) {
+                if (constraintValidatorFactory == defaultConstraintValidatorFactory &&
constraintValidatorFactoryClass != null) {
+                    constraintValidatorFactory = newInstance(constraintValidatorFactoryClass);
+                }
+            }
+        }
         return constraintValidatorFactory;
     }
 
@@ -339,10 +378,32 @@ public class ConfigurationImpl implement
      * {@inheritDoc}
      */
     public TraversableResolver getTraversableResolver() {
+        if (beforeCdi) {
+            return defaultTraversableResolver;
+        }
+
+        if (traversableResolver == defaultTraversableResolver && traversableResolverClass
!= null) {
+            synchronized (this) {
+                if (traversableResolver == defaultTraversableResolver && traversableResolverClass
!= null) {
+                    traversableResolver = newInstance(traversableResolverClass);
+                }
+            }
+        }
         return traversableResolver;
     }
 
     public ParameterNameProvider getParameterNameProvider() {
+        if (beforeCdi) {
+            return defaultParameterNameProvider;
+        }
+
+        if (parameterNameProvider == defaultParameterNameProvider && parameterNameProviderClass
!= null) {
+            synchronized (this) {
+                if (parameterNameProvider == defaultParameterNameProvider && parameterNameProviderClass
!= null) {
+                    parameterNameProvider = newInstance(parameterNameProviderClass);
+                }
+            }
+        }
         return parameterNameProvider;
     }
 
@@ -372,7 +433,7 @@ public class ConfigurationImpl implement
 
     /**
      * Set {@link ValidationProvider} class.
-     * @param providerClass
+     * @param providerClass the provider type
      */
     public void setProviderClass(Class<? extends ValidationProvider<?>> providerClass)
{
         this.providerClass = providerClass;
@@ -400,14 +461,64 @@ public class ConfigurationImpl implement
     }
 
     public Closeable getClosable() {
-        return parser;
+        return new Closeable() {
+            public void close() throws IOException {
+                for (final BValExtension.Releasable<?> releasable : releasables) {
+                    releasable.release();
+                }
+                releasables.clear();
+            }
+        };
+    }
+
+    private <T> T newInstance(final Class<T> cls) {
+        if (System.getSecurityManager() == null) {
+            return createInstance(cls);
+        }
+        return AccessController.doPrivileged(new PrivilegedAction<T>() {
+            public T run() {
+                return createInstance(cls);
+            }
+        });
+    }
+
+    private <T> T createInstance(final Class<T> cls) {
+        try {
+            final BValExtension.Releasable<T> releasable = BValExtension.inject(cls);
+            releasables.add(releasable);
+            return releasable.getInstance();
+        } catch (final Exception e) {
+            try {
+                return cls.newInstance();
+            } catch (final InstantiationException e1) {
+                throw new ValidationException(e1.getMessage(), e1);
+            } catch (final IllegalAccessException e1) {
+                throw new ValidationException(e1.getMessage(), e1);
+            }
+        } catch (final NoClassDefFoundError error) {
+            try {
+                return cls.newInstance();
+            } catch (final InstantiationException e1) {
+                throw new ValidationException(e1.getMessage(), e1);
+            } catch (final IllegalAccessException e1) {
+                throw new ValidationException(e1.getMessage(), e1);
+            }
+        }
+    }
+
+    public void traversableResolverClass(final Class<TraversableResolver> clazz) {
+        traversableResolverClass = clazz;
+    }
+
+    public void constraintValidatorFactoryClass(final Class<ConstraintValidatorFactory>
clazz) {
+        constraintValidatorFactoryClass = clazz;
     }
 
-    public ValidationParser getParser() {
-        return parser;
+    public void messageInterpolatorClass(final Class<MessageInterpolator> clazz) {
+        messageInterpolatorClass = clazz;
     }
 
-    public void setParser(ValidationParser parser) {
-        this.parser = parser;
+    public void parameterNameProviderClass(final Class<? extends ParameterNameProvider>
clazz) {
+        parameterNameProviderClass = clazz;
     }
 }

Modified: bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/xml/ValidationParser.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/xml/ValidationParser.java?rev=1613845&r1=1613844&r2=1613845&view=diff
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/xml/ValidationParser.java
(original)
+++ bval/branches/bval-11/bval-jsr/src/main/java/org/apache/bval/jsr/xml/ValidationParser.java
Sun Jul 27 21:12:50 2014
@@ -18,8 +18,6 @@
  */
 package org.apache.bval.jsr.xml;
 
-
-import org.apache.bval.cdi.BValExtension;
 import org.apache.bval.jsr.BootstrapConfigurationImpl;
 import org.apache.bval.jsr.ConfigurationImpl;
 import org.apache.bval.jsr.util.IOs;
@@ -41,7 +39,6 @@ import javax.xml.bind.Unmarshaller;
 import javax.xml.transform.stream.StreamSource;
 import javax.xml.validation.Schema;
 import javax.xml.validation.SchemaFactory;
-import java.io.Closeable;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
@@ -63,7 +60,7 @@ import java.util.logging.Logger;
  * Description: uses jaxb to parse validation.xml<br/>
  */
 @SuppressWarnings("restriction")
-public class ValidationParser implements Closeable {
+public class ValidationParser {
     private static final String DEFAULT_VALIDATION_XML_FILE = "META-INF/validation.xml";
     private static final String VALIDATION_CONFIGURATION_XSD = "META-INF/validation-configuration-1.1.xsd";
     private static final Logger log = Logger.getLogger(ValidationParser.class.getName());
@@ -72,7 +69,6 @@ public class ValidationParser implements
     private ValidationConfigType xmlConfig;
     private BootstrapConfigurationImpl bootstrap;
     private Collection<ValidationException> exceptions = new CopyOnWriteArrayList<ValidationException>();
-    private Collection<BValExtension.Releasable> releasables = new CopyOnWriteArrayList<BValExtension.Releasable>();
 
     private ValidationParser() {
         // no-op
@@ -273,7 +269,7 @@ public class ValidationParser implements
         if (targetConfig.getParameterNameProvider() == targetConfig.getDefaultParameterNameProvider())
{ // ref ==
             if (parameterNameProvider != null) {
                 final Class<? extends ParameterNameProvider> clazz = Class.class.cast(loadClass(parameterNameProvider));
-                targetConfig.parameterNameProvider(newInstance(clazz));
+                targetConfig.parameterNameProviderClass(clazz);
                 log.log(Level.INFO, String.format("Using %s as validation provider.", parameterNameProvider));
             }
         }
@@ -298,7 +294,7 @@ public class ValidationParser implements
             if (messageInterpolatorClass != null) {
                 Class<MessageInterpolator> clazz = (Class<MessageInterpolator>)
                         loadClass(messageInterpolatorClass);
-                target.messageInterpolator(newInstance(clazz));
+                target.messageInterpolatorClass(clazz);
                 log.log(Level.INFO, String.format("Using %s as message interpolator.", messageInterpolatorClass));
             }
         }
@@ -312,40 +308,12 @@ public class ValidationParser implements
             if (traversableResolverClass != null) {
                 Class<TraversableResolver> clazz = (Class<TraversableResolver>)
                         loadClass(traversableResolverClass);
-                target.traversableResolver(newInstance(clazz));
+                target.traversableResolverClass(clazz);
                 log.log(Level.INFO, String.format("Using %s as traversable resolver.", traversableResolverClass));
             }
         }
     }
 
-    private <T> T newInstance(final Class<T> cls) {
-        if (System.getSecurityManager() == null) {
-            return doNewInstance(cls);
-        }
-        return AccessController.doPrivileged(new PrivilegedAction<T>() {
-            public T run() {
-                return doNewInstance(cls);
-            }
-        });
-    }
-
-    private <T> T doNewInstance(final Class<T> cls) {
-        try {
-            try {
-                final BValExtension.Releasable<T> releasable = BValExtension.inject(cls);
-                releasables.add(releasable);
-                return releasable.getInstance();
-            } catch (final Exception e) {
-                return cls.newInstance();
-            } catch (final NoClassDefFoundError error) {
-                return cls.newInstance();
-            }
-        } catch (final Exception ex) {
-            exceptions.add(new ValidationException("Cannot instantiate : " + cls, ex));
-            return null; // ensure BootstrapConfiguration can be read even if class can't
be instantiated
-        }
-    }
-
     @SuppressWarnings("unchecked")
     private void applyConstraintFactory(ValidationConfigType xmlConfig,
                                         ConfigurationImpl target) {
@@ -354,7 +322,7 @@ public class ValidationParser implements
             if (constraintFactoryClass != null) {
                 Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>)
                         loadClass(constraintFactoryClass);
-                target.constraintValidatorFactory(newInstance(clazz));
+                target.constraintValidatorFactoryClass(clazz);
                 log.log(Level.INFO, String.format("Using %s as constraint factory.", constraintFactoryClass));
             }
         }
@@ -402,11 +370,4 @@ public class ValidationParser implements
             throw  exceptions.iterator().next();
         }
     }
-
-    public void close() throws IOException {
-        for (final BValExtension.Releasable<?> releasable : releasables) {
-            releasable.release();
-        }
-        releasables.clear();
-    }
 }



Mime
View raw message