Author: hardy.ferentschik
Date: 2010-05-20 18:13:26 -0400 (Thu, 20 May 2010)
New Revision: 19573
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ConstructorInstance.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsField.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefinition.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ConstraintValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/resolver/DefaultTraversableResolver.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/ReflectionHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationFactory.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationProxy.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsMethod.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetAnnotationParameter.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetMethodFromPropertyName.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/NewInstance.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/SetAccessibility.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/ValidationXmlParser.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/XmlMappingParser.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/metadata/ConstraintHelperTest.java
Log:
HV-274 Centralized the PriviligedAction use into ReflectionHelper
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefinition.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefinition.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefinition.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -19,12 +19,11 @@
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
-import java.security.AccessController;
+import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import javax.validation.ValidationException;
-import org.hibernate.validator.util.privilegedactions.NewInstance;
import org.hibernate.validator.util.ReflectionHelper;
/**
@@ -78,7 +77,15 @@
}
public <A extends Annotation, T extends ConstraintDefinition<A>> T
constraint(Class<T> definition) {
- T constraintDefinition = createConstraintDefinition( definition );
+
+ final Constructor<T> constructor = ReflectionHelper.getConstructor(
+ definition, Class.class, String.class, ElementType.class, ConstraintMapping.class
+ );
+
+ final T constraintDefinition = ReflectionHelper.newConstructorInstance(
+ constructor, beanType, property, elementType, mapping
+ );
+
mapping.addConstraintConfig( constraintDefinition );
return constraintDefinition;
}
@@ -115,19 +122,6 @@
return property;
}
- private <A extends Annotation, T extends ConstraintDefinition<A>> T
createConstraintDefinition(Class<T> definition) {
- T constraintDefinition;
- NewInstance<T> newInstance = NewInstance.action( definition, "",
beanType, property, elementType, mapping );
-
- if ( System.getSecurityManager() != null ) {
- constraintDefinition = AccessController.doPrivileged( newInstance );
- }
- else {
- constraintDefinition = newInstance.run();
- }
- return constraintDefinition;
- }
-
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -19,9 +19,9 @@
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
-import java.security.AccessController;
+import java.lang.reflect.Constructor;
-import org.hibernate.validator.util.privilegedactions.NewInstance;
+import org.hibernate.validator.util.ReflectionHelper;
import static java.lang.annotation.ElementType.TYPE;
@@ -46,7 +46,13 @@
}
public <A extends Annotation, T extends ConstraintDefinition<A>> T
constraint(Class<T> definition) {
- T constraintDefinition = createConstraintDefinition( definition );
+ final Constructor<T> constructor = ReflectionHelper.getConstructor(
+ definition, Class.class, String.class, ElementType.class, ConstraintMapping.class
+ );
+
+ final T constraintDefinition = ReflectionHelper.newConstructorInstance(
+ constructor, beanClass, property, elementType, mapping
+ );
mapping.addConstraintConfig( constraintDefinition );
return constraintDefinition;
}
@@ -58,19 +64,6 @@
public ConstraintsForType valid(String property, ElementType type) {
return null;
}
-
- private <A extends Annotation, T extends ConstraintDefinition<A>> T
createConstraintDefinition(Class<T> definition) {
- T constraintDefinition;
- NewInstance<T> newInstance = NewInstance.action( definition, "",
beanClass, property, elementType, mapping );
-
- if ( System.getSecurityManager() != null ) {
- constraintDefinition = AccessController.doPrivileged( newInstance );
- }
- else {
- constraintDefinition = newInstance.run();
- }
- return constraintDefinition;
- }
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ConstraintValidatorFactoryImpl.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ConstraintValidatorFactoryImpl.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ConstraintValidatorFactoryImpl.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -17,11 +17,10 @@
*/
package org.hibernate.validator.engine;
-import java.security.AccessController;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
-import org.hibernate.validator.util.privilegedactions.NewInstance;
+import org.hibernate.validator.util.ReflectionHelper;
/**
* Default <code>ConstraintValidatorFactory</code> using a no-arg
constructor.
@@ -32,12 +31,6 @@
public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T>
key) {
- NewInstance<T> newInstance = NewInstance.action( key, "" );
- if ( System.getSecurityManager() != null ) {
- return AccessController.doPrivileged( newInstance );
- }
- else {
- return newInstance.run();
- }
+ return ReflectionHelper.newInstance( key, "" );
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/resolver/DefaultTraversableResolver.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/resolver/DefaultTraversableResolver.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/resolver/DefaultTraversableResolver.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -18,7 +18,6 @@
package org.hibernate.validator.engine.resolver;
import java.lang.annotation.ElementType;
-import java.security.AccessController;
import javax.validation.Path;
import javax.validation.TraversableResolver;
import javax.validation.ValidationException;
@@ -26,8 +25,7 @@
import org.slf4j.Logger;
import org.hibernate.validator.util.LoggerFactory;
-import org.hibernate.validator.util.privilegedactions.NewInstance;
-import org.hibernate.validator.util.privilegedactions.LoadClass;
+import org.hibernate.validator.util.ReflectionHelper;
/**
* A JPA 2 aware <code>TraversableResolver</code>.
@@ -64,7 +62,7 @@
*/
private void detectJPA() {
try {
- loadClass( PERSISTENCE_UTIL_CLASS_NAME, this.getClass() );
+ ReflectionHelper.loadClass( PERSISTENCE_UTIL_CLASS_NAME, this.getClass() );
log.debug( "Found {} on classpath.", PERSISTENCE_UTIL_CLASS_NAME );
}
catch ( ValidationException e ) {
@@ -76,16 +74,10 @@
}
try {
- @SuppressWarnings( "unchecked" )
- Class<? extends TraversableResolver> jpaAwareResolverClass = (Class<? extends
TraversableResolver>)
- loadClass(JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, this.getClass() );
- NewInstance<? extends TraversableResolver> newInstance = NewInstance.action(
jpaAwareResolverClass, "" );
- if ( System.getSecurityManager() != null ) {
- jpaTraversableResolver = AccessController.doPrivileged( newInstance );
- }
- else {
- jpaTraversableResolver = newInstance.run();
- }
+ @SuppressWarnings("unchecked")
+ Class<? extends TraversableResolver> jpaAwareResolverClass = ( Class<?
extends TraversableResolver> )
+ ReflectionHelper.loadClass( JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME,
this.getClass() );
+ jpaTraversableResolver = ReflectionHelper.newInstance( jpaAwareResolverClass,
"" );
log.info(
"Instantiated an instance of {}.",
JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME
);
@@ -98,16 +90,6 @@
}
}
- private Class<?> loadClass(String className, Class<?> caller) {
- LoadClass action = LoadClass.action( className, caller );
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged( action );
- }
- else {
- return action.run();
- }
- }
-
public boolean isReachable(Object traversableObject, Path.Node traversableProperty,
Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
return jpaTraversableResolver == null || jpaTraversableResolver.isReachable(
traversableObject, traversableProperty, rootBeanType, pathToTraversableObject,
elementType
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/BeanMetaDataImpl.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/BeanMetaDataImpl.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/BeanMetaDataImpl.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -24,7 +24,6 @@
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -42,11 +41,8 @@
import org.slf4j.Logger;
-import org.hibernate.validator.util.privilegedactions.GetDeclaredFields;
-import org.hibernate.validator.util.privilegedactions.GetDeclaredMethods;
import org.hibernate.validator.util.LoggerFactory;
import org.hibernate.validator.util.ReflectionHelper;
-import org.hibernate.validator.util.privilegedactions.SetAccessibility;
/**
@@ -128,7 +124,7 @@
}
for ( Map.Entry<Class<?>, List<MetaConstraint<T, ?>>> entry :
xmlConfiguredConstraints.entrySet() ) {
Class<?> clazz = entry.getKey();
- for(MetaConstraint<T,?> constraint : entry.getValue()) {
+ for ( MetaConstraint<T, ?> constraint : entry.getValue() ) {
addMetaConstraint( clazz, constraint );
}
}
@@ -237,7 +233,7 @@
}
private void addCascadedMember(Member member) {
- setAccessibility( member );
+ ReflectionHelper.setAccessibility( member );
cascadedMembers.add( member );
addPropertyDescriptorForMember( member, true );
}
@@ -282,14 +278,7 @@
}
private void initFieldConstraints(Class<?> clazz, AnnotationIgnores
annotationIgnores, BeanMetaDataCache beanMetaDataCache) {
- GetDeclaredFields action = GetDeclaredFields.action( clazz );
- final Field[] fields;
- if ( System.getSecurityManager() != null ) {
- fields = AccessController.doPrivileged( action );
- }
- else {
- fields = action.run();
- }
+ final Field[] fields = ReflectionHelper.getFields( clazz );
for ( Field field : fields ) {
addToPropertyNameList( field );
@@ -322,7 +311,7 @@
}
for ( ConstraintDescriptorImpl<?> constraintDescription : fieldMetaData ) {
- setAccessibility( field );
+ ReflectionHelper.setAccessibility( field );
MetaConstraint<T, ?> metaConstraint = createMetaConstraint( field,
constraintDescription );
addMetaConstraint( clazz, metaConstraint );
}
@@ -340,26 +329,8 @@
}
}
- private void setAccessibility(Member member) {
- SetAccessibility action = SetAccessibility.action( member );
- if ( System.getSecurityManager() != null ) {
- AccessController.doPrivileged( action );
- }
- else {
- action.run();
- }
- }
-
private void initMethodConstraints(Class<?> clazz, AnnotationIgnores
annotationIgnores, BeanMetaDataCache beanMetaDataCache) {
- GetDeclaredMethods action = GetDeclaredMethods.action( clazz );
- final Method[] declaredMethods;
- if ( System.getSecurityManager() != null ) {
- declaredMethods = AccessController.doPrivileged( action );
- }
- else {
- declaredMethods = action.run();
- }
-
+ final Method[] declaredMethods = ReflectionHelper.getMethods( clazz );
for ( Method method : declaredMethods ) {
addToPropertyNameList( method );
@@ -392,7 +363,7 @@
}
for ( ConstraintDescriptorImpl<?> constraintDescription : methodMetaData ) {
- setAccessibility( method );
+ ReflectionHelper.setAccessibility( method );
MetaConstraint<T, ?> metaConstraint = createMetaConstraint( method,
constraintDescription );
addMetaConstraint( clazz, metaConstraint );
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintDescriptorImpl.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintDescriptorImpl.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintDescriptorImpl.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -43,11 +43,8 @@
import org.slf4j.Logger;
-import org.hibernate.validator.util.privilegedactions.GetAnnotationParameter;
-import org.hibernate.validator.util.privilegedactions.GetDeclaredMethods;
-import org.hibernate.validator.util.privilegedactions.GetMethod;
-import org.hibernate.validator.util.privilegedactions.GetMethods;
import org.hibernate.validator.util.LoggerFactory;
+import org.hibernate.validator.util.ReflectionHelper;
import org.hibernate.validator.util.annotationfactory.AnnotationDescriptor;
import org.hibernate.validator.util.annotationfactory.AnnotationFactory;
@@ -147,15 +144,7 @@
Class<Payload>[] payloadFromAnnotation;
try {
//TODO be extra safe and make sure this is an array of Payload
- GetAnnotationParameter<Class[]> action = GetAnnotationParameter.action(
- annotation, PAYLOAD, Class[].class
- );
- if ( System.getSecurityManager() != null ) {
- payloadFromAnnotation = AccessController.doPrivileged( action );
- }
- else {
- payloadFromAnnotation = action.run();
- }
+ payloadFromAnnotation = ReflectionHelper.getAnnotationParameter( annotation, PAYLOAD,
Class[].class );
}
catch ( ValidationException e ) {
//ignore people not defining payloads
@@ -169,14 +158,9 @@
private Set<Class<?>> buildGroupSet(Class<?> implicitGroup) {
Set<Class<?>> groupSet = new HashSet<Class<?>>();
- final Class<?>[] groupsFromAnnotation;
- GetAnnotationParameter<Class[]> action = GetAnnotationParameter.action(
annotation, GROUPS, Class[].class );
- if ( System.getSecurityManager() != null ) {
- groupsFromAnnotation = AccessController.doPrivileged( action );
- }
- else {
- groupsFromAnnotation = action.run();
- }
+ final Class<?>[] groupsFromAnnotation = ReflectionHelper.getAnnotationParameter(
+ annotation, GROUPS, Class[].class
+ );
if ( groupsFromAnnotation.length == 0 ) {
groupSet.add( Default.class );
}
@@ -277,20 +261,13 @@
sb.append( ", elementType=" ).append( elementType );
sb.append( ", definedOn=" ).append( definedOn );
sb.append( ", groups=" ).append( groups );
- sb.append( ", attributes=" ).append( attributes );
+ sb.append( ", attributes=" ).append( attributes );
sb.append( '}' );
return sb.toString();
}
private Map<String, Object> buildAnnotationParameterMap(Annotation annotation) {
- GetDeclaredMethods action = GetDeclaredMethods.action( annotation.annotationType() );
- final Method[] declaredMethods;
- if ( System.getSecurityManager() != null ) {
- declaredMethods = AccessController.doPrivileged( action );
- }
- else {
- declaredMethods = action.run();
- }
+ final Method[] declaredMethods = ReflectionHelper.getMethods(
annotation.annotationType() );
Map<String, Object> parameters = new HashMap<String, Object>(
declaredMethods.length );
for ( Method m : declaredMethods ) {
try {
@@ -323,15 +300,7 @@
private Map<ClassIndexWrapper, Map<String, Object>>
parseOverrideParameters() {
Map<ClassIndexWrapper, Map<String, Object>> overrideParameters = new
HashMap<ClassIndexWrapper, Map<String, Object>>();
- final Method[] methods;
- final GetMethods getMethods = GetMethods.action( annotation.annotationType() );
- if ( System.getSecurityManager() != null ) {
- methods = AccessController.doPrivileged( getMethods );
- }
- else {
- methods = getMethods.run();
- }
-
+ final Method[] methods = ReflectionHelper.getMethods( annotation.annotationType() );
for ( Method m : methods ) {
if ( m.getAnnotation( OverridesAttribute.class ) != null ) {
addOverrideAttributes(
@@ -368,14 +337,7 @@
}
private void ensureAttributeIsOverridable(Method m, OverridesAttribute
overridesAttribute) {
- final GetMethod getMethod = GetMethod.action( overridesAttribute.constraint(),
overridesAttribute.name() );
- final Method method;
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( getMethod );
- }
- else {
- method = getMethod.run();
- }
+ final Method method = ReflectionHelper.getMethod( overridesAttribute.constraint(),
overridesAttribute.name() );
if ( method == null ) {
throw new ConstraintDefinitionException(
"Overridden constraint does not define an attribute with name " +
overridesAttribute.name()
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintHelper.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintHelper.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/metadata/ConstraintHelper.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
-import java.security.AccessController;
import javax.validation.Constraint;
import javax.validation.ConstraintDefinitionException;
import javax.validation.ConstraintValidator;
@@ -72,9 +71,7 @@
import org.hibernate.validator.constraints.impl.SizeValidatorForCollection;
import org.hibernate.validator.constraints.impl.SizeValidatorForMap;
import org.hibernate.validator.constraints.impl.SizeValidatorForString;
-import org.hibernate.validator.util.privilegedactions.GetMethods;
-import org.hibernate.validator.util.privilegedactions.GetMethod;
-import org.hibernate.validator.util.privilegedactions.GetAnnotationParameter;
+import org.hibernate.validator.util.ReflectionHelper;
/**
* Keeps track of builtin constraints and their validator implementations, as well as
already resolved validator definitions.
@@ -196,15 +193,8 @@
public boolean isMultiValueConstraint(Annotation annotation) {
boolean isMultiValueConstraint = false;
try {
- final GetMethod getMethod = GetMethod.action( annotation.getClass(), "value"
);
- final Method method;
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( getMethod );
- }
- else {
- method = getMethod.run();
- }
- if (method != null) {
+ final Method method = ReflectionHelper.getMethod( annotation.getClass(),
"value" );
+ if ( method != null ) {
Class returnType = method.getReturnType();
if ( returnType.isArray() && returnType.getComponentType().isAnnotation() )
{
Annotation[] annotations = ( Annotation[] ) method.invoke( annotation );
@@ -241,15 +231,8 @@
public <A extends Annotation> List<Annotation> getMultiValueConstraints(A
annotation) {
List<Annotation> annotationList = new ArrayList<Annotation>();
try {
- final GetMethod getMethod = GetMethod.action( annotation.getClass(), "value"
);
- final Method method;
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( getMethod );
- }
- else {
- method = getMethod.run();
- }
- if (method != null) {
+ final Method method = ReflectionHelper.getMethod( annotation.getClass(),
"value" );
+ if ( method != null ) {
Class returnType = method.getReturnType();
if ( returnType.isArray() && returnType.getComponentType().isAnnotation() )
{
Annotation[] annotations = ( Annotation[] ) method.invoke( annotation );
@@ -302,14 +285,7 @@
}
private void assertNoParameterStartsWithValid(Annotation annotation) {
- final Method[] methods;
- final GetMethods getMethods = GetMethods.action( annotation.annotationType() );
- if ( System.getSecurityManager() != null ) {
- methods = AccessController.doPrivileged( getMethods );
- }
- else {
- methods = getMethods.run();
- }
+ final Method[] methods = ReflectionHelper.getMethods( annotation.annotationType() );
for ( Method m : methods ) {
if ( m.getName().startsWith( "valid" ) ) {
String msg = "Parameters starting with 'valid' are not allowed in a
constraint.";
@@ -320,17 +296,10 @@
private void assertPayloadParameterExists(Annotation annotation) {
try {
- final GetMethod getMethod = GetMethod.action( annotation.annotationType(),
"payload" );
- final Method method;
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( getMethod );
- }
- else {
- method = getMethod.run();
- }
- if (method == null) {
+ final Method method = ReflectionHelper.getMethod( annotation.annotationType(),
"payload" );
+ if ( method == null ) {
String msg = annotation.annotationType().getName() + " contains Constraint
annotation, but does " +
- "not contain a payload parameter.";
+ "not contain a payload parameter.";
throw new ConstraintDefinitionException( msg );
}
Class<?>[] defaultPayload = ( Class<?>[] ) method.getDefaultValue();
@@ -350,17 +319,10 @@
private void assertGroupsParameterExists(Annotation annotation) {
try {
- final GetMethod getMethod = GetMethod.action( annotation.annotationType(),
"groups" );
- final Method method;
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( getMethod );
- }
- else {
- method = getMethod.run();
- }
- if (method == null) {
+ final Method method = ReflectionHelper.getMethod( annotation.annotationType(),
"groups" );
+ if ( method == null ) {
String msg = annotation.annotationType().getName() + " contains Constraint
annotation, but does " +
- "not contain a groups parameter.";
+ "not contain a groups parameter.";
throw new ConstraintDefinitionException( msg );
}
Class<?>[] defaultGroups = ( Class<?>[] ) method.getDefaultValue();
@@ -380,13 +342,7 @@
private void assertMessageParameterExists(Annotation annotation) {
try {
- GetAnnotationParameter<?> action = GetAnnotationParameter.action( annotation,
"message", String.class );
- if (System.getSecurityManager() != null) {
- AccessController.doPrivileged( action );
- }
- else {
- action.run();
- }
+ ReflectionHelper.getAnnotationParameter( annotation, "message", String.class
);
}
catch ( Exception e ) {
String msg = annotation.annotationType().getName() + " contains Constraint
annotation, but does " +
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -17,15 +17,14 @@
*/
package org.hibernate.validator.resourceloading;
-import java.security.AccessController;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.slf4j.Logger;
-import org.hibernate.validator.util.privilegedactions.GetClassLoader;
import org.hibernate.validator.util.LoggerFactory;
+import org.hibernate.validator.util.ReflectionHelper;
/**
* A resource bundle locator, that loads resource bundles by simply
@@ -53,11 +52,7 @@
*/
public ResourceBundle getResourceBundle(Locale locale) {
ResourceBundle rb = null;
- boolean isSecured = System.getSecurityManager() != null;
- GetClassLoader action = GetClassLoader.fromContext();
- ClassLoader classLoader = isSecured ? AccessController
- .doPrivileged( action ) : action.run();
-
+ ClassLoader classLoader = ReflectionHelper.getClassLoaderFromContext();
if ( classLoader != null ) {
rb = loadBundle(
classLoader, locale, bundleName
@@ -65,10 +60,7 @@
);
}
if ( rb == null ) {
- action = GetClassLoader
- .fromClass( PlatformResourceBundleLocator.class );
- classLoader = isSecured ? AccessController.doPrivileged( action )
- : action.run();
+ classLoader = ReflectionHelper.getClassLoaderFromClass(
PlatformResourceBundleLocator.class );
rb = loadBundle(
classLoader, locale, bundleName
+ " not found by validator classloader"
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/ReflectionHelper.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/ReflectionHelper.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/ReflectionHelper.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -20,12 +20,11 @@
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
-import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
@@ -40,11 +39,22 @@
import com.googlecode.jtype.TypeUtils;
+import org.hibernate.validator.util.privilegedactions.ConstructorInstance;
+import org.hibernate.validator.util.privilegedactions.GetAnnotationParameter;
+import org.hibernate.validator.util.privilegedactions.GetClassLoader;
+import org.hibernate.validator.util.privilegedactions.GetConstructor;
import org.hibernate.validator.util.privilegedactions.GetDeclaredField;
+import org.hibernate.validator.util.privilegedactions.GetDeclaredFields;
+import org.hibernate.validator.util.privilegedactions.GetDeclaredMethods;
import org.hibernate.validator.util.privilegedactions.GetMethod;
+import org.hibernate.validator.util.privilegedactions.GetMethodFromPropertyName;
+import org.hibernate.validator.util.privilegedactions.LoadClass;
+import org.hibernate.validator.util.privilegedactions.NewInstance;
+import org.hibernate.validator.util.privilegedactions.SetAccessibility;
/**
- * Some reflection utility methods.
+ * Some reflection utility methods. Where necessary calls will be performed as {@code
PrivilegedAction} which is necessary
+ * for situations where a security manager is in place.
*
* @author Hardy Ferentschik
*/
@@ -56,34 +66,89 @@
private ReflectionHelper() {
}
- @SuppressWarnings("unchecked")
- public static <T> T getAnnotationParameter(Annotation annotation, String
parameterName, Class<T> type) {
- try {
- Method m = annotation.getClass().getMethod( parameterName );
- m.setAccessible( true );
- Object o = m.invoke( annotation );
- if ( o.getClass().getName().equals( type.getName() ) ) {
- return ( T ) o;
- }
- else {
- String msg = "Wrong parameter type. Expected: " + type.getName() + "
Actual: " + o.getClass().getName();
- throw new ValidationException( msg );
- }
+ public static ClassLoader getClassLoaderFromContext() {
+ ClassLoader loader;
+ GetClassLoader action = GetClassLoader.fromContext();
+ if ( System.getSecurityManager() != null ) {
+ loader = AccessController.doPrivileged( action );
}
- catch ( NoSuchMethodException e ) {
- String msg = "The specified annotation defines no parameter '" +
parameterName + "'.";
- throw new ValidationException( msg, e );
+ else {
+ loader = action.run();
}
- catch ( IllegalAccessException e ) {
- String msg = "Unable to get '" + parameterName + "' from "
+ annotation.getClass().getName();
- throw new ValidationException( msg, e );
+ return loader;
+ }
+
+ public static ClassLoader getClassLoaderFromClass(Class<?> clazz) {
+ ClassLoader loader;
+ GetClassLoader action = GetClassLoader.fromClass( clazz );
+ if ( System.getSecurityManager() != null ) {
+ loader = AccessController.doPrivileged( action );
}
- catch ( InvocationTargetException e ) {
- String msg = "Unable to get '" + parameterName + "' from "
+ annotation.getClass().getName();
- throw new ValidationException( msg, e );
+ else {
+ loader = action.run();
}
+ return loader;
}
+ public static Class<?> loadClass(String className, Class<?> caller) {
+ LoadClass action = LoadClass.action( className, caller );
+ if ( System.getSecurityManager() != null ) {
+ return AccessController.doPrivileged( action );
+ }
+ else {
+ return action.run();
+ }
+ }
+
+ public static <T> Constructor<T> getConstructor(Class<T> clazz,
Class<?>... params) {
+ Constructor<T> constructor;
+ GetConstructor<T> action = GetConstructor.action( clazz, params );
+ if ( System.getSecurityManager() != null ) {
+ constructor = AccessController.doPrivileged( action );
+ }
+ else {
+ constructor = action.run();
+ }
+ return constructor;
+ }
+
+ public static <T> T newInstance(Class<T> clazz, String message) {
+ T instance;
+ NewInstance<T> newInstance = NewInstance.action( clazz, message );
+ if ( System.getSecurityManager() != null ) {
+ instance = AccessController.doPrivileged( newInstance );
+ }
+ else {
+ instance = newInstance.run();
+ }
+ return instance;
+ }
+
+ public static <T> T newConstructorInstance(Constructor<T> constructor,
Object... initArgs) {
+ T instance;
+ ConstructorInstance<T> newInstance = ConstructorInstance.action( constructor,
initArgs );
+ if ( System.getSecurityManager() != null ) {
+ instance = AccessController.doPrivileged( newInstance );
+ }
+ else {
+ instance = newInstance.run();
+ }
+ return instance;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T getAnnotationParameter(Annotation annotation, String
parameterName, Class<T> type) {
+ T result;
+ GetAnnotationParameter<T> action = GetAnnotationParameter.action( annotation,
parameterName, type );
+ if ( System.getSecurityManager() != null ) {
+ result = AccessController.doPrivileged( action );
+ }
+ else {
+ result = action.run();
+ }
+ return result;
+ }
+
/**
* Process bean properties getter by applying the JavaBean naming conventions.
*
@@ -187,7 +252,6 @@
* @return Returns the type of the field of return type of a method.
*/
public static Class<?> getType(Member member) {
-
Class<?> type = null;
if ( member instanceof Field ) {
type = ( ( Field ) member ).getType();
@@ -252,15 +316,13 @@
}
public static void setAccessibility(Member member) {
- // HV-257
- // Also set accessibility in case of public abstract members. If you proxy an interface
using java.lang.reflect.Proxy
- // per default you will get a IllegalAccessException since you are not allowed to
access public abstract methods.
- // Seems odd. One could argue that the proxy 'is' the implementation for the
interface method and hence they
- // should be accessible. Maybe this is a JVM bug !?
- if ( !Modifier.isPublic( member.getModifiers() )
- || ( Modifier.isPublic( member.getModifiers() ) && Modifier.isAbstract(
member.getModifiers() ) ) ) {
- ( ( AccessibleObject ) member ).setAccessible( true );
+ SetAccessibility action = SetAccessibility.action( member );
+ if ( System.getSecurityManager() != null ) {
+ AccessController.doPrivileged( action );
}
+ else {
+ action.run();
+ }
}
/**
@@ -404,33 +466,143 @@
return map.get( key );
}
+
/**
- * Returns the method with the specified name or <code>null</code> if it
does not exist.
+ * Returns the field with the specified name or <code>null</code> if it does
not exist.
*
* @param clazz The class to check.
- * @param methodName The method name.
+ * @param fieldName The field name.
*
- * @return Returns the method with the specified name or <code>null</code>
if it does not exist.
+ * @return Returns the field with the specified name or <code>null</code> if
it does not exist.
*/
- //run client in privileged block
+ public static Field getField(Class<?> clazz, String fieldName) {
+ GetDeclaredField action = GetDeclaredField.action( clazz, fieldName );
+ final Field field;
+ if ( System.getSecurityManager() != null ) {
+ field = AccessController.doPrivileged( action );
+ }
+ else {
+ field = action.run();
+ }
+ return field;
+ }
+
+ /**
+ * Checks whether the specified class contains a field with the given name.
+ *
+ * @param clazz The class to check.
+ * @param fieldName The field name.
+ *
+ * @return Returns {@code true} if the field exists, {@code false} otherwise.
+ */
+ public static boolean containsField(Class<?> clazz, String fieldName) {
+ return getField( clazz, fieldName ) != null;
+ }
+
+ /**
+ * Returns the fields of the specified class.
+ *
+ * @param clazz The class for which to retrieve the fields.
+ *
+ * @return Returns the fields for this class.
+ */
+ public static Field[] getFields(Class<?> clazz) {
+ GetDeclaredFields action = GetDeclaredFields.action( clazz );
+ final Field[] fields;
+ if ( System.getSecurityManager() != null ) {
+ fields = AccessController.doPrivileged( action );
+ }
+ else {
+ fields = action.run();
+ }
+ return fields;
+ }
+
+ /**
+ * Returns the method with the specified property name or {@code null} if it does not
exist. This method will
+ * prepend 'is' and 'get' to the property name and capitalize the first
letter.
+ *
+ * @param clazz The class to check.
+ * @param methodName The property name.
+ *
+ * @return Returns the method with the specified property or {@code null} if it does not
exist.
+ */
+ public static Method getMethodFromPropertyName(Class<?> clazz, String methodName)
{
+ Method method;
+ GetMethodFromPropertyName action = GetMethodFromPropertyName.action( clazz, methodName
);
+ if ( System.getSecurityManager() != null ) {
+ method = AccessController.doPrivileged( action );
+ }
+ else {
+ method = action.run();
+ }
+ return method;
+ }
+
+ /**
+ * Checks whether the specified class contains a method for the specified property.
+ *
+ * @param clazz The class to check.
+ * @param property The property name.
+ *
+ * @return Returns {@code true} if the method exists, {@code false} otherwise.
+ */
+ public static boolean containsMethodWithPropertyName(Class<?> clazz, String
property) {
+ return getMethodFromPropertyName( clazz, property ) != null;
+ }
+
+ /**
+ * Returns the method with the specified name or {@code null} if it does not exist.
+ *
+ * @param clazz The class to check.
+ * @param methodName The property name.
+ *
+ * @return Returns the method with the specified property or {@code null}if it does not
exist.
+ */
public static Method getMethod(Class<?> clazz, String methodName) {
- try {
- char string[] = methodName.toCharArray();
- string[0] = Character.toUpperCase( string[0] );
- methodName = new String( string );
- try {
- return clazz.getMethod( "get" + methodName );
- }
- catch ( NoSuchMethodException e ) {
- return clazz.getMethod( "is" + methodName );
- }
+ Method method;
+ GetMethod action = GetMethod.action( clazz, methodName );
+ if ( System.getSecurityManager() != null ) {
+ method = AccessController.doPrivileged( action );
}
- catch ( NoSuchMethodException e ) {
- return null;
+ else {
+ method = action.run();
}
+ return method;
}
/**
+ * Returns the methods of the specified class.
+ *
+ * @param clazz The class for which to retrieve the methods.
+ *
+ * @return Returns the methods for this class.
+ */
+ public static Method[] getMethods(Class<?> clazz) {
+ GetDeclaredMethods action = GetDeclaredMethods.action( clazz );
+ final Method[] methods;
+ if ( System.getSecurityManager() != null ) {
+ methods = AccessController.doPrivileged( action );
+ }
+ else {
+ methods = action.run();
+ }
+ return methods;
+ }
+
+ /**
+ * Checks whether the specified class contains a method with the given name.
+ *
+ * @param clazz The class to check.
+ * @param methodName The method name.
+ *
+ * @return Returns {@code true} if the method exists, {@code false} otherwise.
+ */
+ public static boolean containsMethod(Class<?> clazz, String methodName) {
+ return getMethodFromPropertyName( clazz, methodName ) != null;
+ }
+
+ /**
* Returns the autoboxed type of a primitive type.
*
* @param primitiveType the primitive type
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationFactory.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationFactory.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationFactory.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -22,36 +22,31 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
-import java.security.AccessController;
-import org.hibernate.validator.util.privilegedactions.GetConstructor;
-import org.hibernate.validator.util.privilegedactions.GetClassLoader;
+import org.hibernate.validator.util.ReflectionHelper;
-
/**
* Creates live annotations (actually <code>AnnotationProxies</code>) from
<code>AnnotationDescriptors</code>.
*
* @author Paolo Perrotta
* @author Davide Marchignoli
+ * @author Hardy Ferentschik
* @see AnnotationProxy
*/
public class AnnotationFactory {
@SuppressWarnings("unchecked")
public static <T extends Annotation> T create(AnnotationDescriptor<T>
descriptor) {
- boolean isSecured = System.getSecurityManager() != null;
- GetClassLoader action = GetClassLoader.fromContext();
- ClassLoader classLoader = isSecured ? AccessController.doPrivileged( action ) :
action.run();
- //TODO round 34ms to generate the proxy, hug! is Javassist Faster?
- Class<T> proxyClass = (Class<T>) Proxy.getProxyClass( classLoader,
descriptor.type() );
+ ClassLoader classLoader = ReflectionHelper.getClassLoaderFromContext();
+ Class<T> proxyClass = ( Class<T> ) Proxy.getProxyClass( classLoader,
descriptor.type() );
InvocationHandler handler = new AnnotationProxy( descriptor );
try {
return getProxyInstance( proxyClass, handler );
}
- catch (RuntimeException e) {
+ catch ( RuntimeException e ) {
throw e;
}
- catch (Exception e) {
+ catch ( Exception e ) {
throw new RuntimeException( e );
}
}
@@ -59,14 +54,7 @@
private static <T extends Annotation> T getProxyInstance(Class<T>
proxyClass, InvocationHandler handler) throws
SecurityException, NoSuchMethodException, IllegalArgumentException,
InstantiationException,
IllegalAccessException, InvocationTargetException {
- GetConstructor<T> action = GetConstructor.action( proxyClass,
InvocationHandler.class );
- final Constructor<T> constructor;
- if ( System.getSecurityManager() != null ) {
- constructor = AccessController.doPrivileged( action );
- }
- else {
- constructor = action.run();
- }
- return constructor.newInstance( handler );
+ final Constructor<T> constructor = ReflectionHelper.getConstructor( proxyClass,
InvocationHandler.class );
+ return ReflectionHelper.newConstructorInstance( constructor, handler );
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationProxy.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationProxy.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/annotationfactory/AnnotationProxy.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -21,14 +21,14 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
-import java.security.AccessController;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
-import org.hibernate.validator.util.privilegedactions.GetDeclaredMethods;
+import org.hibernate.validator.util.ReflectionHelper;
+
/**
* A concrete implementation of <code>Annotation</code> that pretends it is
a
* "real" source code annotation. It's also an
<code>InvocationHandler</code>.
@@ -68,14 +68,7 @@
private Map<String, Object> getAnnotationValues(AnnotationDescriptor descriptor)
{
Map<String, Object> result = new HashMap<String, Object>();
int processedValuesFromDescriptor = 0;
- GetDeclaredMethods action = GetDeclaredMethods.action( annotationType );
- final Method[] declaredMethods;
- if ( System.getSecurityManager() != null ) {
- declaredMethods = AccessController.doPrivileged( action );
- }
- else {
- declaredMethods = action.run();
- }
+ final Method[] declaredMethods = ReflectionHelper.getMethods( annotationType );
for ( Method m : declaredMethods ) {
if ( descriptor.containsElement( m.getName() ) ) {
result.put( m.getName(), descriptor.valueOf( m.getName() ) );
Copied:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ConstructorInstance.java
(from rev 19566,
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/NewInstance.java)
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ConstructorInstance.java
(rev 0)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ConstructorInstance.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -0,0 +1,63 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// $Id$
+
+package org.hibernate.validator.util.privilegedactions;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.security.PrivilegedAction;
+import javax.validation.ValidationException;
+
+/**
+ * Execute instance creation as privileged action.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class ConstructorInstance<T> implements PrivilegedAction<T> {
+ private final Constructor<T> constructor;
+ private final Object[] initArgs;
+
+ public static <T> ConstructorInstance<T> action(Constructor<T>
constructor, Object... initArgs) {
+ return new ConstructorInstance<T>( constructor, initArgs );
+ }
+
+ private ConstructorInstance(Constructor<T> constructor, Object... initArgs) {
+ this.constructor = constructor;
+ this.initArgs = initArgs;
+ }
+
+ public T run() {
+ try {
+ return constructor.newInstance( initArgs );
+ }
+ catch ( InstantiationException e ) {
+ throw new ValidationException( "Unable to instantiate" +
constructor.getName(), e );
+ }
+ catch ( IllegalAccessException e ) {
+ throw new ValidationException( "Unable to instantiate" +
constructor.getName(), e );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new ValidationException( "Unable to instantiate" +
constructor.getName(), e );
+ }
+ catch ( RuntimeException e ) {
+ throw new ValidationException( "Unable to instantiate" +
constructor.getName(), e );
+ }
+ }
+}
\ No newline at end of file
Deleted:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsField.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsField.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsField.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -1,47 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validator.util.privilegedactions;
-
-import java.security.PrivilegedAction;
-
-/**
- * @author Emmanuel Bernard
- */
-public class ContainsField implements PrivilegedAction<Boolean> {
- private final Class<?> clazz;
- private final String property;
-
- public static ContainsField action(Class<?> clazz, String property) {
- return new ContainsField( clazz, property );
- }
-
- private ContainsField(Class<?> clazz, String property) {
- this.clazz = clazz;
- this.property = property;
- }
-
- public Boolean run() {
- try {
- clazz.getDeclaredField( property );
- return true;
- }
- catch ( NoSuchFieldException e ) {
- return false;
- }
- }
-}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsMethod.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsMethod.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/ContainsMethod.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -38,6 +38,6 @@
}
public Boolean run() {
- return ReflectionHelper.getMethod( clazz, property ) != null;
+ return ReflectionHelper.getMethodFromPropertyName( clazz, property ) != null;
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetAnnotationParameter.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetAnnotationParameter.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetAnnotationParameter.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -18,12 +18,14 @@
package org.hibernate.validator.util.privilegedactions;
import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.security.PrivilegedAction;
+import javax.validation.ValidationException;
-import org.hibernate.validator.util.ReflectionHelper;
-
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class GetAnnotationParameter<T> implements PrivilegedAction<T> {
private final Annotation annotation;
@@ -42,6 +44,29 @@
}
public T run() {
- return ReflectionHelper.getAnnotationParameter( annotation, parameterName, type );
+ try {
+ Method m = annotation.getClass().getMethod( parameterName );
+ m.setAccessible( true );
+ Object o = m.invoke( annotation );
+ if ( o.getClass().getName().equals( type.getName() ) ) {
+ return ( T ) o;
+ }
+ else {
+ String msg = "Wrong parameter type. Expected: " + type.getName() + "
Actual: " + o.getClass().getName();
+ throw new ValidationException( msg );
+ }
+ }
+ catch ( NoSuchMethodException e ) {
+ String msg = "The specified annotation defines no parameter '" +
parameterName + "'.";
+ throw new ValidationException( msg, e );
+ }
+ catch ( IllegalAccessException e ) {
+ String msg = "Unable to get '" + parameterName + "' from "
+ annotation.getClass().getName();
+ throw new ValidationException( msg, e );
+ }
+ catch ( InvocationTargetException e ) {
+ String msg = "Unable to get '" + parameterName + "' from "
+ annotation.getClass().getName();
+ throw new ValidationException( msg, e );
+ }
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetMethodFromPropertyName.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetMethodFromPropertyName.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/GetMethodFromPropertyName.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -20,10 +20,9 @@
import java.lang.reflect.Method;
import java.security.PrivilegedAction;
-import org.hibernate.validator.util.ReflectionHelper;
-
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class GetMethodFromPropertyName implements PrivilegedAction<Method> {
private final Class<?> clazz;
@@ -39,6 +38,19 @@
}
public Method run() {
- return ReflectionHelper.getMethod( clazz, property );
+ try {
+ char string[] = property.toCharArray();
+ string[0] = Character.toUpperCase( string[0] );
+ String fullMethodName = new String( string );
+ try {
+ return clazz.getMethod( "get" + fullMethodName );
+ }
+ catch ( NoSuchMethodException e ) {
+ return clazz.getMethod( "is" + fullMethodName );
+ }
+ }
+ catch ( NoSuchMethodException e ) {
+ return null;
+ }
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/NewInstance.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/NewInstance.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/NewInstance.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -17,8 +17,6 @@
*/
package org.hibernate.validator.util.privilegedactions;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
import java.security.PrivilegedAction;
import javax.validation.ValidationException;
@@ -31,27 +29,19 @@
public class NewInstance<T> implements PrivilegedAction<T> {
private final Class<T> clazz;
private final String message;
- private final Class<?>[] parameterTypes;
- private final Object[] initArgs;
- public static <T> NewInstance<T> action(Class<T> clazz, String
message, Object... initArgs) {
- return new NewInstance<T>( clazz, message, initArgs );
+ public static <T> NewInstance<T> action(Class<T> clazz, String
message) {
+ return new NewInstance<T>( clazz, message );
}
- private NewInstance(Class<T> clazz, String message, Object... initArgs) {
+ private NewInstance(Class<T> clazz, String message) {
this.clazz = clazz;
this.message = message;
- this.initArgs = initArgs;
- this.parameterTypes = new Class<?>[initArgs.length];
- for ( int i = 0; i < initArgs.length; i++ ) {
- this.parameterTypes[i] = initArgs[i].getClass();
- }
}
public T run() {
try {
- Constructor<T> constructor = clazz.getConstructor( parameterTypes );
- return constructor.newInstance( initArgs );
+ return clazz.newInstance();
}
catch ( InstantiationException e ) {
throw new ValidationException( "Unable to instantiate " + message + ":
" + clazz, e );
@@ -59,12 +49,6 @@
catch ( IllegalAccessException e ) {
throw new ValidationException( "Unable to instantiate " + clazz, e );
}
- catch ( NoSuchMethodException e ) {
- throw new ValidationException( "Unable to instantiate " + clazz, e );
- }
- catch ( InvocationTargetException e ) {
- throw new ValidationException( "Unable to instantiate " + clazz, e );
- }
catch ( RuntimeException e ) {
throw new ValidationException( "Unable to instantiate " + clazz, e );
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/SetAccessibility.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/SetAccessibility.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/util/privilegedactions/SetAccessibility.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -17,13 +17,13 @@
*/
package org.hibernate.validator.util.privilegedactions;
+import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.security.PrivilegedAction;
-import org.hibernate.validator.util.ReflectionHelper;
-
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class SetAccessibility implements PrivilegedAction<Object> {
private final Member member;
@@ -37,7 +37,7 @@
}
public Object run() {
- ReflectionHelper.setAccessibility( member );
+ ( ( AccessibleObject ) member ).setAccessible( true );
return member;
}
}
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/ValidationXmlParser.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/ValidationXmlParser.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/ValidationXmlParser.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -20,7 +20,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
-import java.security.AccessController;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.MessageInterpolator;
import javax.validation.TraversableResolver;
@@ -37,10 +36,8 @@
import org.slf4j.Logger;
import org.xml.sax.SAXException;
-import org.hibernate.validator.util.privilegedactions.GetClassLoader;
-import org.hibernate.validator.util.privilegedactions.LoadClass;
import org.hibernate.validator.util.LoggerFactory;
-import org.hibernate.validator.util.privilegedactions.NewInstance;
+import org.hibernate.validator.util.ReflectionHelper;
/**
* Parser for <i>validation.xml</i> using JAXB.
@@ -79,18 +76,12 @@
if ( constraintFactoryClass != null ) {
try {
@SuppressWarnings("unchecked")
- Class<ConstraintValidatorFactory> clazz = (
Class<ConstraintValidatorFactory> ) loadClass(
+ Class<ConstraintValidatorFactory> clazz = (
Class<ConstraintValidatorFactory> ) ReflectionHelper.loadClass(
constraintFactoryClass, this.getClass()
);
- NewInstance<ConstraintValidatorFactory> newInstance = NewInstance.action(
+ xmlParameters.constraintValidatorFactory = ReflectionHelper.newInstance(
clazz, "constraint factory class"
);
- if ( System.getSecurityManager() != null ) {
- xmlParameters.constraintValidatorFactory = AccessController.doPrivileged(
newInstance );
- }
- else {
- xmlParameters.constraintValidatorFactory = newInstance.run();
- }
log.info( "Using {} as constraint factory.", constraintFactoryClass );
}
catch ( ValidationException e ) {
@@ -101,16 +92,6 @@
}
}
- private Class<?> loadClass(String className, Class<?> caller) {
- LoadClass action = LoadClass.action( className, caller );
- if ( System.getSecurityManager() != null ) {
- return AccessController.doPrivileged( action );
- }
- else {
- return action.run();
- }
- }
-
private void setPropertiesFromXml(ValidationConfigType config,
ValidationBootstrapParameters xmlParameters) {
for ( PropertyType property : config.getProperty() ) {
if ( log.isDebugEnabled() ) {
@@ -144,7 +125,7 @@
if ( messageInterpolatorClass != null ) {
try {
@SuppressWarnings("unchecked")
- Class<MessageInterpolator> clazz = ( Class<MessageInterpolator> )
loadClass(
+ Class<MessageInterpolator> clazz = ( Class<MessageInterpolator> )
ReflectionHelper.loadClass(
messageInterpolatorClass, this.getClass()
);
xmlParameters.messageInterpolator = clazz.newInstance();
@@ -173,7 +154,7 @@
if ( traversableResolverClass != null ) {
try {
@SuppressWarnings("unchecked")
- Class<TraversableResolver> clazz = ( Class<TraversableResolver> )
loadClass(
+ Class<TraversableResolver> clazz = ( Class<TraversableResolver> )
ReflectionHelper.loadClass(
traversableResolverClass, this.getClass()
);
xmlParameters.traversableResolver = clazz.newInstance();
@@ -202,7 +183,7 @@
String providerClassName = config.getDefaultProvider();
if ( providerClassName != null ) {
try {
- xmlParamters.providerClass = ( Class<? extends ValidationProvider<?>> )
loadClass(
+ xmlParamters.providerClass = ( Class<? extends ValidationProvider<?>> )
ReflectionHelper.loadClass(
providerClassName, this.getClass()
);
log.info( "Using {} as validation provider.", providerClassName );
@@ -239,9 +220,10 @@
finally {
try {
inputStream.close();
- } catch ( IOException io) {
- log.warn( "Unable to close input stream for " + VALIDATION_XML_FILE);
}
+ catch ( IOException io ) {
+ log.warn( "Unable to close input stream for " + VALIDATION_XML_FILE );
+ }
}
return validationConfig;
}
@@ -253,34 +235,27 @@
path = path.substring( 1 );
}
-
- boolean isSecured = System.getSecurityManager() != null;
boolean isContextCL = true;
// try the context class loader first
- GetClassLoader action = GetClassLoader.fromContext();
- ClassLoader loader = isSecured ? AccessController.doPrivileged( action ) :
action.run();
+ ClassLoader loader = ReflectionHelper.getClassLoaderFromContext();
if ( loader == null ) {
log.debug( "No default context class loader, fall back to Bean Validation's
loader" );
- action = GetClassLoader.fromClass( ValidationXmlParser.class );
- loader = isSecured ? AccessController.doPrivileged( action ) : action.run();
+ loader = ReflectionHelper.getClassLoaderFromClass( ValidationXmlParser.class );
isContextCL = false;
}
InputStream inputStream = loader.getResourceAsStream( path );
// try the current class loader
if ( isContextCL && inputStream == null ) {
- action = GetClassLoader.fromClass( ValidationXmlParser.class );
- loader = isSecured ? AccessController.doPrivileged( action ) : action.run();
+ loader = ReflectionHelper.getClassLoaderFromClass( ValidationXmlParser.class );
inputStream = loader.getResourceAsStream( path );
}
return inputStream;
}
private Schema getValidationConfigurationSchema() {
- boolean isSecured = System.getSecurityManager() != null;
- GetClassLoader action = GetClassLoader.fromClass( ValidationXmlParser.class );
- ClassLoader loader = isSecured ? AccessController.doPrivileged( action ) :
action.run();
+ ClassLoader loader = ReflectionHelper.getClassLoaderFromClass(
ValidationXmlParser.class );
URL schemaUrl = loader.getResource( VALIDATION_CONFIGURATION_XSD );
SchemaFactory sf = SchemaFactory.newInstance(
javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schema = null;
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/XmlMappingParser.java
===================================================================
---
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/XmlMappingParser.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/xml/XmlMappingParser.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -25,7 +25,6 @@
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.net.URL;
-import java.security.AccessController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -54,14 +53,8 @@
import org.hibernate.validator.metadata.ConstraintHelper;
import org.hibernate.validator.metadata.ConstraintOrigin;
import org.hibernate.validator.metadata.MetaConstraint;
-import org.hibernate.validator.util.privilegedactions.ContainsField;
-import org.hibernate.validator.util.privilegedactions.ContainsMethod;
-import org.hibernate.validator.util.privilegedactions.GetClassLoader;
-import org.hibernate.validator.util.privilegedactions.GetDeclaredField;
-import org.hibernate.validator.util.privilegedactions.GetMethod;
-import org.hibernate.validator.util.privilegedactions.GetMethodFromPropertyName;
-import org.hibernate.validator.util.privilegedactions.LoadClass;
import org.hibernate.validator.util.LoggerFactory;
+import org.hibernate.validator.util.ReflectionHelper;
import org.hibernate.validator.util.annotationfactory.AnnotationDescriptor;
import org.hibernate.validator.util.annotationfactory.AnnotationFactory;
@@ -170,7 +163,7 @@
}
for ( String validatorClassName : validatedByType.getValue() ) {
Class<? extends ConstraintValidator<?, ?>> validatorClass;
- validatorClass = ( Class<? extends ConstraintValidator<?, ?>> )
loadClass(
+ validatorClass = ( Class<? extends ConstraintValidator<?, ?>> )
ReflectionHelper.loadClass(
validatorClassName,
this.getClass()
);
@@ -188,16 +181,6 @@
}
}
- private Class<?> loadClass(String className, Class<?> caller) {
- LoadClass action = LoadClass.action( className, caller );
- if ( System.getSecurityManager() != null ) {
- return AccessController.doPrivileged( action );
- }
- else {
- return action.run();
- }
- }
-
private List<Class<? extends ConstraintValidator<? extends Annotation,
?>>> findConstraintValidatorClasses(Class<? extends Annotation>
annotationType) {
List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>
constraintValidatorDefinitionClasses = new ArrayList<Class<? extends
ConstraintValidator<? extends Annotation, ?>>>();
if ( constraintHelper.isBuiltinConstraint( annotationType ) ) {
@@ -228,25 +211,11 @@
else {
fieldNames.add( fieldName );
}
- final boolean containsField;
- ContainsField containsAction = ContainsField.action( beanClass, fieldName );
- if ( System.getSecurityManager() != null ) {
- containsField = AccessController.doPrivileged( containsAction );
- }
- else {
- containsField = containsAction.run();
- }
+ final boolean containsField = ReflectionHelper.containsField( beanClass, fieldName );
if ( !containsField ) {
throw new ValidationException( beanClass.getName() + " does not contain the
fieldType " + fieldName );
}
- GetDeclaredField action = GetDeclaredField.action( beanClass, fieldName );
- final Field field;
- if ( System.getSecurityManager() != null ) {
- field = AccessController.doPrivileged( action );
- }
- else {
- field = action.run();
- }
+ final Field field = ReflectionHelper.getField( beanClass, fieldName );
// ignore annotations
boolean ignoreFieldAnnotation = fieldType.isIgnoreAnnotations() == null ? false :
fieldType.isIgnoreAnnotations();
@@ -279,25 +248,11 @@
else {
getterNames.add( getterName );
}
- ContainsMethod cmAction = ContainsMethod.action( beanClass, getterName );
- boolean containsMethod;
- if ( System.getSecurityManager() != null ) {
- containsMethod = AccessController.doPrivileged( cmAction );
- }
- else {
- containsMethod = cmAction.run();
- }
+ boolean containsMethod = ReflectionHelper.containsMethod( beanClass, getterName );
if ( !containsMethod ) {
throw new ValidationException( beanClass.getName() + " does not contain the
property " + getterName );
}
- final Method method;
- GetMethodFromPropertyName action = GetMethodFromPropertyName.action( beanClass,
getterName );
- if ( System.getSecurityManager() != null ) {
- method = AccessController.doPrivileged( action );
- }
- else {
- method = action.run();
- }
+ final Method method = ReflectionHelper.getMethodFromPropertyName( beanClass,
getterName );
// ignore annotations
boolean ignoreGetterAnnotation = getterType.isIgnoreAnnotations() == null ? false :
getterType.isIgnoreAnnotations();
@@ -423,15 +378,7 @@
}
private <A extends Annotation> Class<?>
getAnnotationParameterType(Class<A> annotationClass, String name) {
- Method m;
- GetMethod action = GetMethod.action( annotationClass, name );
- if ( System.getSecurityManager() != null ) {
- m = AccessController.doPrivileged( action );
- }
- else {
- m = action.run();
- }
-
+ Method m = ReflectionHelper.getMethod( annotationClass, name );
if ( m == null ) {
throw new ValidationException( "Annotation of type " +
annotationClass.getName() + " does not contain a parameter " + name +
"." );
}
@@ -574,7 +521,7 @@
returnValue = value;
}
else if ( returnType.getName().equals( Class.class.getName() ) ) {
- returnValue = loadClass( value, this.getClass() );
+ returnValue = ReflectionHelper.loadClass( value, this.getClass() );
}
else {
try {
@@ -634,7 +581,7 @@
else {
fullyQualifiedClass = defaultPackage + PACKAGE_SEPARATOR + clazz;
}
- return loadClass( fullyQualifiedClass, this.getClass() );
+ return ReflectionHelper.loadClass( fullyQualifiedClass, this.getClass() );
}
private boolean isQualifiedClass(String clazz) {
@@ -661,9 +608,7 @@
}
private Schema getMappingSchema() {
- boolean isSecured = System.getSecurityManager() != null;
- GetClassLoader action = GetClassLoader.fromClass( XmlMappingParser.class );
- ClassLoader loader = isSecured ? AccessController.doPrivileged( action ) :
action.run();
+ ClassLoader loader = ReflectionHelper.getClassLoaderFromClass( XmlMappingParser.class
);
URL schemaUrl = loader.getResource( VALIDATION_MAPPING_XSD );
SchemaFactory sf = SchemaFactory.newInstance(
javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schema = null;
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/metadata/ConstraintHelperTest.java
===================================================================
---
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/metadata/ConstraintHelperTest.java 2010-05-20
21:55:28 UTC (rev 19572)
+++
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/metadata/ConstraintHelperTest.java 2010-05-20
22:13:26 UTC (rev 19573)
@@ -19,19 +19,19 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
-import java.lang.reflect.Member;
import java.util.List;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.hibernate.validator.metadata.ConstraintHelper;
-import org.hibernate.validator.util.privilegedactions.SetAccessibility;
+import org.hibernate.validator.util.ReflectionHelper;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+
/**
* @author Hardy Ferentschik
*/
@@ -50,7 +50,7 @@
Field[] fields = engine.getClass().getDeclaredFields();
assertNotNull( fields );
assertTrue( fields.length == 1 );
- setAccessibility( fields[0] );
+ ReflectionHelper.setAccessibility( fields[0] );
Annotation annotation = fields[0].getAnnotation( Pattern.List.class );
assertNotNull( annotation );
@@ -64,15 +64,11 @@
fields = order.getClass().getDeclaredFields();
assertNotNull( fields );
assertTrue( fields.length == 1 );
- setAccessibility( fields[0] );
+ ReflectionHelper.setAccessibility( fields[0] );
annotation = fields[0].getAnnotation( NotNull.class );
assertNotNull( annotation );
multiValueConstraintAnnotations = constraintHelper.getMultiValueConstraints( annotation
);
assertTrue( multiValueConstraintAnnotations.size() == 0, "There should be no
constraint annotations" );
}
-
- void setAccessibility(Member member) {
- SetAccessibility.action( member ).run();
- }
}