You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@bval.apache.org by mb...@apache.org on 2012/04/02 21:31:17 UTC
svn commit: r1308497 [1/2] - in /bval/branches/privileged/bval-jsr303: ./
src/main/java/org/apache/bval/jsr303/
src/main/java/org/apache/bval/jsr303/resolver/
src/main/java/org/apache/bval/jsr303/util/
src/main/java/org/apache/bval/jsr303/xml/ src/test...
Author: mbenson
Date: Mon Apr 2 19:31:16 2012
New Revision: 1308497
URL: http://svn.apache.org/viewvc?rev=1308497&view=rev
Log:
refactor privileged work to satisfy security AND convenience, at the cost of requiring users to grant a custom permission; some occasional refactorings I was too lazy to separate :o
Added:
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java (with props)
bval/branches/privileged/bval-jsr303/src/test/resources/java.policy
Removed:
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/SecureActions.java
Modified:
bval/branches/privileged/bval-jsr303/pom.xml
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationConstraintBuilder.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationProcessor.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidationProvider.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidatorFactory.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConfigurationImpl.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintAnnotationAttributes.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDefaults.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultMessageInterpolator.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultValidationProviderResolver.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/Jsr303MetaBeanFactory.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/resolver/DefaultTraversableResolver.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ClassHelper.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ConstraintDefinitionValidator.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationMappingParser.java
bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/ValidationParser.java
bval/branches/privileged/bval-jsr303/src/test/java/org/apache/bval/jsr303/BootstrapTest.java
bval/branches/privileged/bval-jsr303/src/test/java/org/apache/bval/jsr303/util/TestUtils.java
Modified: bval/branches/privileged/bval-jsr303/pom.xml
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/pom.xml?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/pom.xml (original)
+++ bval/branches/privileged/bval-jsr303/pom.xml Mon Apr 2 19:31:16 2012
@@ -74,7 +74,7 @@
</profile>
<!--
optional profile using javax.validation/validation-api.jar from RI
- manually active when property "-Pri" is provided.
+ manually active when property "-Dri" is provided.
-->
<profile>
<id>ri</id>
@@ -92,6 +92,24 @@
</dependency>
</dependencies>
</profile>
+ <profile>
+ <id>sec</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <includes>
+ <include>**/*Test.java</include>
+ <include>**/*TestCase.java</include>
+ </includes>
+ <argLine>-Djava.security.manager -Djava.security.policy=${project.basedir}/src/test/resources/java.policy</argLine>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
</profiles>
<dependencies>
@@ -107,6 +125,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <version>3.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -193,7 +212,8 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
- <version>2.6</version>
+ <!-- 2.12 has http://jira.codehaus.org/browse/SUREFIRE-836 -->
+ <version>2.11</version>
<configuration>
<includes>
<include>**/*Test.java</include>
@@ -204,4 +224,3 @@
</plugins>
</build>
</project>
-
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationConstraintBuilder.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationConstraintBuilder.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationConstraintBuilder.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationConstraintBuilder.java Mon Apr 2 19:31:16 2012
@@ -40,7 +40,7 @@ import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import org.apache.bval.jsr303.groups.GroupsComputer;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.bval.jsr303.xml.AnnotationProxyBuilder;
import org.apache.bval.util.AccessStrategy;
@@ -51,6 +51,7 @@ import org.apache.bval.util.AccessStrate
*/
final class AnnotationConstraintBuilder<A extends Annotation> {
private static final Logger log = Logger.getLogger(AnnotationConstraintBuilder.class.getName());
+ private static final Privileged PRIVILEGED = new Privileged();
private final ConstraintValidation<?> constraintValidation;
private List<ConstraintOverrides> overrides;
@@ -77,7 +78,7 @@ final class AnnotationConstraintBuilder<
/** build attributes, payload, groups from 'annotation' */
private void buildFromAnnotation() {
if (constraintValidation.getAnnotation() != null) {
- SecureActions.run(new PrivilegedAction<Object>() {
+ PRIVILEGED.run(new PrivilegedAction<Object>() {
public Object run() {
for (Method method : constraintValidation.getAnnotation().annotationType().getDeclaredMethods()) {
// groups + payload must also appear in attributes (also
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationProcessor.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationProcessor.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationProcessor.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/AnnotationProcessor.java Mon Apr 2 19:31:16 2012
@@ -38,7 +38,7 @@ import javax.validation.ValidationExcept
import javax.validation.groups.Default;
import org.apache.bval.jsr303.util.ConstraintDefinitionValidator;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.bval.model.Features;
import org.apache.bval.model.MetaBean;
import org.apache.bval.model.MetaProperty;
@@ -48,13 +48,14 @@ import org.apache.commons.lang3.ClassUti
import org.apache.commons.lang3.reflect.TypeUtils;
/**
- * Description: implements uniform handling of JSR303 {@link Constraint}
- * annotations, including composed constraints and the resolution of
- * {@link ConstraintValidator} implementations.
+ * Description: implements uniform handling of JSR303 {@link Constraint} annotations, including composed constraints and
+ * the resolution of {@link ConstraintValidator} implementations.
*
* @version $Rev: 996992 $ $Date: 2010-09-14 12:05:40 -0500 (Tue, 14 Sep 2010) $
*/
public final class AnnotationProcessor {
+ private static final Privileged PRIVILEGED = new Privileged();
+
/** {@link ApacheFactoryContext} used */
private final ApacheFactoryContext factoryContext;
@@ -109,8 +110,8 @@ public final class AnnotationProcessor {
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
- public final <A extends Annotation> boolean processAnnotation(A annotation, Class<?> owner, AppendValidation appender)
- throws IllegalAccessException, InvocationTargetException {
+ public final <A extends Annotation> boolean processAnnotation(A annotation, Class<?> owner,
+ AppendValidation appender) throws IllegalAccessException, InvocationTargetException {
return processAnnotation(annotation, null, owner, null, appender);
}
@@ -139,9 +140,8 @@ public final class AnnotationProcessor {
return addAccessStrategy(prop, access);
}
/**
- * An annotation is considered a constraint definition if its retention
- * policy contains RUNTIME and if the annotation itself is annotated
- * with javax.validation.Constraint.
+ * An annotation is considered a constraint definition if its retention policy contains RUNTIME and if the
+ * annotation itself is annotated with javax.validation.Constraint.
*/
Constraint vcAnno = annotation.annotationType().getAnnotation(Constraint.class);
if (vcAnno != null) {
@@ -151,13 +151,12 @@ public final class AnnotationProcessor {
return applyConstraint(annotation, validatorClasses, prop, owner, access, appender);
}
/**
- * Multi-valued constraints: To support this requirement, the bean
- * validation provider treats regular annotations (annotations not
- * annotated by @Constraint) whose value element has a return type of an
- * array of constraint annotations in a special way.
+ * Multi-valued constraints: To support this requirement, the bean validation provider treats regular
+ * annotations (annotations not annotated by @Constraint) whose value element has a return type of an array of
+ * constraint annotations in a special way.
*/
Object result =
- SecureActions.getAnnotationValue(annotation, ConstraintAnnotationAttributes.VALUE.getAttributeName());
+ PRIVILEGED.getAnnotationValue(annotation, ConstraintAnnotationAttributes.VALUE.getAttributeName());
if (result instanceof Annotation[]) {
boolean changed = false;
for (Annotation each : (Annotation[]) result) {
@@ -169,8 +168,7 @@ public final class AnnotationProcessor {
}
/**
- * Add the specified {@link AccessStrategy} to <code>prop</code>; noop if
- * <code>prop == null</code>.
+ * Add the specified {@link AccessStrategy} to <code>prop</code>; noop if <code>prop == null</code>.
*
* @param prop
* @param access
@@ -191,8 +189,7 @@ public final class AnnotationProcessor {
}
/**
- * Find available {@link ConstraintValidation} classes for a given
- * constraint annotation.
+ * Find available {@link ConstraintValidation} classes for a given constraint annotation.
*
* @param annotation
* @param vcAnno
@@ -223,8 +220,7 @@ public final class AnnotationProcessor {
* @param annotation
* constraint annotation
* @param constraintClasses
- * known {@link ConstraintValidator} implementation classes for
- * <code>annotation</code>
+ * known {@link ConstraintValidator} implementation classes for <code>annotation</code>
* @param prop
* meta-property
* @param owner
@@ -288,12 +284,10 @@ public final class AnnotationProcessor {
if (constraintClasses != null && constraintClasses.length > 0) {
Type type = determineTargetedType(owner, access);
/**
- * spec says in chapter 3.5.3.: The ConstraintValidator chosen to
- * validate a declared type T is the one where the type supported by
- * the ConstraintValidator is a supertype of T and where there is no
- * other ConstraintValidator whose supported type is a supertype of
- * T and not a supertype of the chosen ConstraintValidator supported
- * type.
+ * spec says in chapter 3.5.3.: The ConstraintValidator chosen to validate a declared type T is the one
+ * where the type supported by the ConstraintValidator is a supertype of T and where there is no other
+ * ConstraintValidator whose supported type is a supertype of T and not a supertype of the chosen
+ * ConstraintValidator supported type.
*/
Map<Type, Class<? extends ConstraintValidator<A, ?>>> validatorTypes =
getValidatorsTypes(constraintClasses);
@@ -323,15 +317,15 @@ public final class AnnotationProcessor {
if (types.isEmpty()) {
StringBuilder buf =
new StringBuilder().append("No validator could be found for type ").append(stringForType(targetType))
- .append(". See: @").append(anno.annotationType().getSimpleName()).append(" at ").append(
- stringForLocation(owner, access));
+ .append(". See: @").append(anno.annotationType().getSimpleName()).append(" at ")
+ .append(stringForLocation(owner, access));
throw new UnexpectedTypeException(buf.toString());
} else if (types.size() > 1) {
StringBuilder buf = new StringBuilder();
buf.append("Ambiguous validators for type ");
buf.append(stringForType(targetType));
- buf.append(". See: @").append(anno.annotationType().getSimpleName()).append(" at ").append(
- stringForLocation(owner, access));
+ buf.append(". See: @").append(anno.annotationType().getSimpleName()).append(" at ")
+ .append(stringForLocation(owner, access));
buf.append(". Validators are: ");
boolean comma = false;
for (Type each : types) {
@@ -391,9 +385,8 @@ public final class AnnotationProcessor {
* Tries to reduce all assignable classes down to a single class.
*
* @param assignableTypes
- * The set of all classes which are assignable to the class of
- * the value to be validated and which are handled by at least
- * one of the validators for the specified constraint.
+ * The set of all classes which are assignable to the class of the value to be validated and which are
+ * handled by at least one of the validators for the specified constraint.
*/
private static void reduceAssignableTypes(List<Type> assignableTypes) {
if (assignableTypes.size() <= 1) {
@@ -419,8 +412,7 @@ public final class AnnotationProcessor {
}
/**
- * Given a set of {@link ConstraintValidator} implementation classes, map
- * those to their target types.
+ * Given a set of {@link ConstraintValidator} implementation classes, map those to their target types.
*
* @param constraintValidatorClasses
* @return {@link Map} of {@link Type} : {@link ConstraintValidator} subtype
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheFactoryContext.java Mon Apr 2 19:31:16 2012
@@ -19,7 +19,6 @@
package org.apache.bval.jsr303;
import java.lang.reflect.Constructor;
-import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
@@ -36,8 +35,7 @@ import org.apache.bval.MetaBeanBuilder;
import org.apache.bval.MetaBeanFactory;
import org.apache.bval.MetaBeanFinder;
import org.apache.bval.MetaBeanManager;
-import org.apache.bval.jsr303.util.SecureActions;
-import org.apache.bval.util.PrivilegedActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.bval.xml.XMLMetaBeanBuilder;
import org.apache.bval.xml.XMLMetaBeanFactory;
import org.apache.bval.xml.XMLMetaBeanManager;
@@ -45,10 +43,11 @@ import org.apache.commons.lang3.StringUt
import org.apache.commons.lang3.reflect.ConstructorUtils;
/**
- * Description: Represents the context that is used to create
- * <code>ClassValidator</code> instances.<br/>
+ * Description: Represents the context that is used to create <code>ClassValidator</code> instances.<br/>
*/
public class ApacheFactoryContext implements ValidatorContext {
+ private static final Privileged PRIVILEGED = new Privileged();
+
private final ApacheValidatorFactory factory;
private final MetaBeanFinder metaBeanFinder;
@@ -78,8 +77,7 @@ public class ApacheFactoryContext implem
}
/**
- * Get the {@link ApacheValidatorFactory} used by this
- * {@link ApacheFactoryContext}.
+ * Get the {@link ApacheValidatorFactory} used by this {@link ApacheFactoryContext}.
*
* @return {@link ApacheValidatorFactory}
*/
@@ -163,17 +161,13 @@ public class ApacheFactoryContext implem
/**
* Create MetaBeanManager that uses factories:
* <ol>
- * <li>if enabled by
- * {@link ApacheValidatorConfiguration.Properties#ENABLE_INTROSPECTOR}, an
+ * <li>if enabled by {@link ApacheValidatorConfiguration.Properties#ENABLE_INTROSPECTOR}, an
* {@link IntrospectorMetaBeanFactory}</li>
* <li>{@link MetaBeanFactory} types (if any) specified by
- * {@link ApacheValidatorConfiguration.Properties#METABEAN_FACTORY_CLASSNAMES}
- * </li>
- * <li>if no {@link Jsr303MetaBeanFactory} has yet been specified (this
- * allows factory order customization), a {@link Jsr303MetaBeanFactory}
- * which handles both JSR303-XML and JSR303-Annotations</li>
- * <li>if enabled by
- * {@link ApacheValidatorConfiguration.Properties#ENABLE_METABEANS_XML}, an
+ * {@link ApacheValidatorConfiguration.Properties#METABEAN_FACTORY_CLASSNAMES}</li>
+ * <li>if no {@link Jsr303MetaBeanFactory} has yet been specified (this allows factory order customization), a
+ * {@link Jsr303MetaBeanFactory} which handles both JSR303-XML and JSR303-Annotations</li>
+ * <li>if enabled by {@link ApacheValidatorConfiguration.Properties#ENABLE_METABEANS_XML}, an
* {@link XMLMetaBeanFactory}</li>
* </ol>
*
@@ -186,8 +180,8 @@ public class ApacheFactoryContext implem
builders.add(new IntrospectorMetaBeanFactory());
}
String[] factoryClassNames =
- StringUtils.split(
- factory.getProperties().get(ApacheValidatorConfiguration.Properties.METABEAN_FACTORY_CLASSNAMES));
+ StringUtils.split(factory.getProperties().get(
+ ApacheValidatorConfiguration.Properties.METABEAN_FACTORY_CLASSNAMES));
if (factoryClassNames != null) {
for (String clsName : factoryClassNames) {
// cast, relying on #createMetaBeanFactory to throw the exception if incompatible:
@@ -204,8 +198,9 @@ public class ApacheFactoryContext implem
builders.add(new Jsr303MetaBeanFactory(this));
}
@SuppressWarnings("deprecation")
- boolean enableMetaBeansXml = Boolean.parseBoolean(factory.getProperties().get(
- ApacheValidatorConfiguration.Properties.ENABLE_METABEANS_XML));
+ boolean enableMetaBeansXml =
+ Boolean.parseBoolean(factory.getProperties().get(
+ ApacheValidatorConfiguration.Properties.ENABLE_METABEANS_XML));
if (enableMetaBeansXml) {
XMLMetaBeanManagerCreator.addFactory(builders);
}
@@ -230,11 +225,12 @@ public class ApacheFactoryContext implem
}
private <F extends MetaBeanFactory> F createMetaBeanFactory(final Class<F> cls) {
- return PrivilegedActions.run(new PrivilegedAction<F>() {
+ return PRIVILEGED.run(new PrivilegedAction<F>() {
public F run() {
try {
- Constructor<F> c = ConstructorUtils.getMatchingAccessibleConstructor(cls, ApacheFactoryContext.this.getClass());
+ Constructor<F> c =
+ ConstructorUtils.getMatchingAccessibleConstructor(cls, ApacheFactoryContext.this.getClass());
if (c != null) {
return c.newInstance(ApacheFactoryContext.this);
}
@@ -251,9 +247,8 @@ public class ApacheFactoryContext implem
}
/**
- * separate class to prevent the classloader to immediately load optional
- * classes: XMLMetaBeanManager, XMLMetaBeanFactory, XMLMetaBeanBuilder that
- * might not be available in the classpath
+ * separate class to prevent the classloader to immediately load optional classes: XMLMetaBeanManager,
+ * XMLMetaBeanFactory, XMLMetaBeanBuilder that might not be available in the classpath
*/
private static class XMLMetaBeanManagerCreator {
@@ -262,8 +257,7 @@ public class ApacheFactoryContext implem
}
/**
- * Create the {@link MetaBeanManager} to process JSR303 XML. Requires
- * bval-xstream at RT.
+ * Create the {@link MetaBeanManager} to process JSR303 XML. Requires bval-xstream at RT.
*
* @param builders
* @return {@link MetaBeanManager}
@@ -277,23 +271,12 @@ public class ApacheFactoryContext implem
}
}
- private static <T> T doPrivileged(final PrivilegedAction<T> action) {
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged(action);
- } else {
- return action.run();
- }
- }
-
private Class<?> loadClass(final String className) {
- ClassLoader loader = doPrivileged(SecureActions.getContextClassLoader());
- if (loader == null)
- loader = getClass().getClassLoader();
-
try {
- return Class.forName(className, true, loader);
+ return PRIVILEGED.getClass(PRIVILEGED.getClassLoader(getClass()), className);
} catch (ClassNotFoundException ex) {
- throw new ValidationException("Unable to load class: " + className, ex);
+ throw new ValidationException(String.format("Unable to load class: %s", className), ex);
}
}
+
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidationProvider.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidationProvider.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidationProvider.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidationProvider.java Mon Apr 2 19:31:16 2012
@@ -18,7 +18,6 @@
*/
package org.apache.bval.jsr303;
-import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.validation.Configuration;
@@ -28,11 +27,11 @@ import javax.validation.spi.BootstrapSta
import javax.validation.spi.ConfigurationState;
import javax.validation.spi.ValidationProvider;
-import org.apache.commons.lang3.ClassUtils;
+import org.apache.bval.jsr303.util.Privileged;
/**
- * Description: Implementation of {@link ValidationProvider} for jsr303
- * implementation of the apache-validation framework.
+ * Description: Implementation of {@link ValidationProvider} for jsr303 implementation of the apache-validation
+ * framework.
* <p/>
* <br/>
* User: roman.stumm <br/>
@@ -40,10 +39,10 @@ import org.apache.commons.lang3.ClassUti
* Time: 14:45:41 <br/>
*/
public class ApacheValidationProvider implements ValidationProvider<ApacheValidatorConfiguration> {
+ private static final Privileged PRIVILEGED = new Privileged();
/**
- * Learn whether a particular builder class is suitable for this
- * {@link ValidationProvider}.
+ * Learn whether a particular builder class is suitable for this {@link ValidationProvider}.
*
* @param builderClass
* @return boolean suitability
@@ -81,10 +80,10 @@ public class ApacheValidationProvider im
if (validatorFactoryClassname == null)
validatorFactoryClass = ApacheValidatorFactory.class;
- else
- {
- validatorFactoryClass
- = (Class<? extends ValidatorFactory>) ClassUtils.getClass(validatorFactoryClassname);
+ else {
+ validatorFactoryClass =
+ (Class<? extends ValidatorFactory>) PRIVILEGED.getClass(PRIVILEGED.getClassLoader(getClass()),
+ validatorFactoryClassname);
validatorFactoryClass.asSubclass(ValidatorFactory.class);
}
} catch (ValidationException ex) {
@@ -102,29 +101,20 @@ public class ApacheValidationProvider im
// No privileges should be required to access the constructor,
// because the classloader of ApacheValidationProvider will always
// be an ancestor of the loader of validatorFactoryClass.
- return (System.getSecurityManager() == null)
- ? instantiateValidatorFactory(validatorFactoryClass, configuration)
- : AccessController.doPrivileged(new PrivilegedAction<ValidatorFactory>() {
- public ValidatorFactory run() {
- return instantiateValidatorFactory(validatorFactoryClass, configuration);
- }
- });
+ return PRIVILEGED.run(new PrivilegedAction<ValidatorFactory>() {
+ public ValidatorFactory run() {
+ return instantiateValidatorFactory(validatorFactoryClass, configuration);
+ }
+ });
}
-
-
private static ValidatorFactory instantiateValidatorFactory(
- final Class<? extends ValidatorFactory> validatorFactoryClass,
- final ConfigurationState configuration
- ) {
- try
- {
- return validatorFactoryClass.getConstructor(ConfigurationState.class).newInstance(configuration);
- }
- catch (final Exception ex)
- {
- throw new ValidationException("Cannot instantiate : " + validatorFactoryClass, ex);
- }
+ final Class<? extends ValidatorFactory> validatorFactoryClass, final ConfigurationState configuration) {
+ try {
+ return validatorFactoryClass.getConstructor(ConfigurationState.class).newInstance(configuration);
+ } catch (final Exception ex) {
+ throw new ValidationException(String.format("Cannot instantiate %s", validatorFactoryClass), ex);
+ }
}
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidatorFactory.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidatorFactory.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidatorFactory.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ApacheValidatorFactory.java Mon Apr 2 19:31:16 2012
@@ -43,9 +43,9 @@ public class ApacheValidatorFactory impl
private static final ConstraintDefaults defaultConstraints =
new ConstraintDefaults();
- private MessageInterpolator messageResolver;
- private TraversableResolver traversableResolver;
- private ConstraintValidatorFactory constraintValidatorFactory;
+ private final MessageInterpolator messageResolver;
+ private final TraversableResolver traversableResolver;
+ private final ConstraintValidatorFactory constraintValidatorFactory;
private final Map<String, String> properties;
/**
@@ -89,28 +89,16 @@ public class ApacheValidatorFactory impl
* Create a new ApacheValidatorFactory instance.
*/
public ApacheValidatorFactory(ConfigurationState configurationState) {
- properties = new HashMap<String, String>();
+ properties = new HashMap<String, String>(configurationState.getProperties());
+
+ messageResolver = configurationState.getMessageInterpolator();
+ traversableResolver = configurationState.getTraversableResolver();
+ constraintValidatorFactory = configurationState.getConstraintValidatorFactory();
+
defaultSequences = new HashMap<Class<?>, Class<?>[]>();
validAccesses = new HashMap<Class<?>, List<AccessStrategy>>();
- constraintMap =
- new HashMap<Class<?>, List<MetaConstraint<?, ? extends Annotation>>>();
- configure(configurationState);
- }
-
- /**
- * Configure this {@link ApacheValidatorFactory} from a
- * {@link ConfigurationState}.
- *
- * @param configuration
- */
- protected void configure(ConfigurationState configuration) {
- getProperties().putAll(configuration.getProperties());
- setMessageInterpolator(configuration.getMessageInterpolator());
- setTraversableResolver(configuration.getTraversableResolver());
- setConstraintValidatorFactory(configuration
- .getConstraintValidatorFactory());
- ValidationMappingParser parser = new ValidationMappingParser(this);
- parser.processMappingConfig(configuration.getMappingStreams());
+ constraintMap = new HashMap<Class<?>, List<MetaConstraint<?, ? extends Annotation>>>();
+ new ValidationMappingParser(this).processMappingConfig(configurationState.getMappingStreams());
}
/**
@@ -123,16 +111,6 @@ public class ApacheValidatorFactory impl
}
/**
- * Get the default {@link MessageInterpolator} used by this
- * {@link ApacheValidatorFactory}.
- *
- * @return {@link MessageInterpolator}
- */
- protected MessageInterpolator getDefaultMessageInterpolator() {
- return messageResolver;
- }
-
- /**
* Shortcut method to create a new Validator instance with factory's
* settings
*
@@ -164,30 +142,10 @@ public class ApacheValidatorFactory impl
}
/**
- * Set the {@link MessageInterpolator} used.
- *
- * @param messageResolver
- */
- public final void setMessageInterpolator(MessageInterpolator messageResolver) {
- this.messageResolver = messageResolver;
- }
-
- /**
* {@inheritDoc}
*/
public MessageInterpolator getMessageInterpolator() {
- return ((messageResolver != null) ? messageResolver
- : getDefaultMessageInterpolator());
- }
-
- /**
- * Set the {@link TraversableResolver} used.
- *
- * @param traversableResolver
- */
- public final void setTraversableResolver(
- TraversableResolver traversableResolver) {
- this.traversableResolver = traversableResolver;
+ return messageResolver;
}
/**
@@ -198,16 +156,6 @@ public class ApacheValidatorFactory impl
}
/**
- * Set the {@link ConstraintValidatorFactory} used.
- *
- * @param constraintValidatorFactory
- */
- public final void setConstraintValidatorFactory(
- ConstraintValidatorFactory constraintValidatorFactory) {
- this.constraintValidatorFactory = constraintValidatorFactory;
- }
-
- /**
* {@inheritDoc}
*/
public ConstraintValidatorFactory getConstraintValidatorFactory() {
@@ -299,16 +247,12 @@ public class ApacheValidatorFactory impl
*/
public void addMetaConstraint(Class<?> beanClass,
MetaConstraint<?, ?> metaConstraint) {
- List<MetaConstraint<?, ? extends Annotation>> slot =
- constraintMap.get(beanClass);
- if (slot != null) {
- slot.add(metaConstraint);
- } else {
- List<MetaConstraint<?, ? extends Annotation>> constraintList =
- new ArrayList<MetaConstraint<?, ? extends Annotation>>();
- constraintList.add(metaConstraint);
- constraintMap.put(beanClass, constraintList);
+ List<MetaConstraint<?, ? extends Annotation>> slot = constraintMap.get(beanClass);
+ if (slot == null) {
+ slot = new ArrayList<MetaConstraint<?, ? extends Annotation>>();
+ constraintMap.put(beanClass, slot);
}
+ slot.add(metaConstraint);
}
/**
@@ -320,13 +264,11 @@ public class ApacheValidatorFactory impl
*/
public void addValid(Class<?> beanClass, AccessStrategy accessStrategy) {
List<AccessStrategy> slot = validAccesses.get(beanClass);
- if (slot != null) {
- slot.add(accessStrategy);
- } else {
- List<AccessStrategy> tmpList = new ArrayList<AccessStrategy>();
- tmpList.add(accessStrategy);
- validAccesses.put(beanClass, tmpList);
+ if (slot == null) {
+ slot = new ArrayList<AccessStrategy>();
+ validAccesses.put(beanClass, slot);
}
+ slot.add(accessStrategy);
}
/**
@@ -335,7 +277,7 @@ public class ApacheValidatorFactory impl
* @param beanClass
* @param groupSequence
*/
- public void addDefaultSequence(Class<?> beanClass, Class<?>[] groupSequence) {
+ public void addDefaultSequence(Class<?> beanClass, Class<?>... groupSequence) {
defaultSequences.put(beanClass, groupSequence);
}
@@ -350,14 +292,8 @@ public class ApacheValidatorFactory impl
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<MetaConstraint<T, ? extends Annotation>> getMetaConstraints(
Class<T> beanClass) {
- List<MetaConstraint<?, ? extends Annotation>> slot =
- constraintMap.get(beanClass);
- if (slot != null) {
- // noinspection RedundantCast
- return (List) slot;
- } else {
- return Collections.EMPTY_LIST;
- }
+ return constraintMap.containsKey(beanClass) ? (List) constraintMap.get(beanClass) : Collections
+ .<MetaConstraint<T, ?>> emptyList();
}
/**
@@ -369,12 +305,8 @@ public class ApacheValidatorFactory impl
* @return {@link List} of {@link AccessStrategy}
*/
public List<AccessStrategy> getValidAccesses(Class<?> beanClass) {
- List<AccessStrategy> slot = validAccesses.get(beanClass);
- if (slot != null) {
- return slot;
- } else {
- return Collections.<AccessStrategy>emptyList();
- }
+ return validAccesses.containsKey(beanClass) ? validAccesses.get(beanClass) : Collections
+ .<AccessStrategy> emptyList();
}
/**
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConfigurationImpl.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConfigurationImpl.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConfigurationImpl.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConfigurationImpl.java Mon Apr 2 19:31:16 2012
@@ -18,27 +18,43 @@
*/
package org.apache.bval.jsr303;
+import java.io.InputStream;
+import java.security.PrivilegedAction;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Logger;
-import org.apache.bval.jsr303.resolver.DefaultTraversableResolver;
-import org.apache.bval.jsr303.util.SecureActions;
-import org.apache.bval.jsr303.xml.ValidationParser;
-
-import javax.validation.*;
+import javax.validation.Configuration;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.TraversableResolver;
+import javax.validation.ValidationException;
+import javax.validation.ValidationProviderResolver;
+import javax.validation.ValidatorFactory;
import javax.validation.spi.BootstrapState;
import javax.validation.spi.ConfigurationState;
import javax.validation.spi.ValidationProvider;
-import java.io.InputStream;
-import java.util.*;
-import java.util.logging.Logger;
+
+import org.apache.bval.jsr303.resolver.DefaultTraversableResolver;
+import org.apache.bval.jsr303.util.Privileged;
+import org.apache.bval.jsr303.xml.ValidationParser;
/**
- * Description: used to configure apache-validation for jsr303.
- * Implementation of Configuration that also implements ConfigurationState,
- * hence this can be passed to buildValidatorFactory(ConfigurationState).
- * <br/>
+ * Description: used to configure {@link ApacheValidatorFactory}. Implementation
+ * of {@link Configuration} that also implements {@link ConfigurationState},
+ * hence this can be passed to
+ * {@link ValidationProvider#buildValidatorFactory(ConfigurationState)}.
*/
public class ConfigurationImpl implements ApacheValidatorConfiguration, ConfigurationState {
private static final Logger log = Logger.getLogger(ConfigurationImpl.class.getName());
+ private static final Privileged PRIVILEGED = new Privileged();
+
+ private static volatile TraversableResolver defaultTraversableResolver;
+ private static volatile MessageInterpolator defaultMessageInterpolator;
+ private static volatile ConstraintValidatorFactory defaultConstraintValidatorFactory;
/**
* Configured {@link ValidationProvider}
@@ -73,42 +89,31 @@ public class ConfigurationImpl implement
* false = dirty flag (to prevent from multiple parsing validation.xml)
*/
private boolean prepared = false;
- private final TraversableResolver defaultTraversableResolver =
- new DefaultTraversableResolver();
- /**
- * Default {@link MessageInterpolator}
- */
- protected final MessageInterpolator defaultMessageInterpolator =
- new DefaultMessageInterpolator();
-
- private final ConstraintValidatorFactory defaultConstraintValidatorFactory =
- new DefaultConstraintValidatorFactory();
- // END DEFAULTS
+ private final Set<InputStream> mappingStreams = new HashSet<InputStream>();
+ private final Map<String, String> properties = new HashMap<String, String>();
- private Set<InputStream> mappingStreams = new HashSet<InputStream>();
- private Map<String, String> properties = new HashMap<String, String>();
private boolean ignoreXmlConfiguration = false;
/**
* Create a new ConfigurationImpl instance.
- * @param aState
- * @param aProvider
+ * @param bootstrapState
+ * @param provider
*/
- public ConfigurationImpl(BootstrapState aState, ValidationProvider<?> aProvider) {
- if (aProvider != null) {
- this.provider = aProvider;
+ public ConfigurationImpl(BootstrapState bootstrapState, ValidationProvider<?> provider) {
+ this.provider = provider;
+ if (provider != null) {
this.providerResolver = null;
- } else if (aState != null) {
- this.provider = null;
- if (aState.getValidationProviderResolver() == null) {
- providerResolver = aState.getDefaultValidationProviderResolver();
- } else {
- providerResolver = aState.getValidationProviderResolver();
- }
- } else {
- throw new ValidationException("either provider or state are required");
+ return;
+ }
+ if (bootstrapState != null) {
+ ValidationProviderResolver validationProviderResolver = bootstrapState.getValidationProviderResolver();
+ this.providerResolver =
+ validationProviderResolver == null ? bootstrapState.getDefaultValidationProviderResolver()
+ : validationProviderResolver;
+ return;
}
+ throw new ValidationException("either ValidationProvider or BootstrapState is required");
}
/**
@@ -116,7 +121,7 @@ public class ConfigurationImpl implement
*/
public ApacheValidatorConfiguration traversableResolver(TraversableResolver resolver) {
traversableResolver = resolver;
- this.prepared = false;
+ prepared = false;
return this;
}
@@ -137,7 +142,7 @@ public class ConfigurationImpl implement
*/
public ConfigurationImpl messageInterpolator(MessageInterpolator resolver) {
this.messageInterpolator = resolver;
- this.prepared = false;
+ prepared = false;
return this;
}
@@ -147,7 +152,7 @@ public class ConfigurationImpl implement
public ConfigurationImpl constraintValidatorFactory(
ConstraintValidatorFactory constraintFactory) {
this.constraintValidatorFactory = constraintFactory;
- this.prepared = false;
+ prepared = false;
return this;
}
@@ -215,6 +220,9 @@ public class ConfigurationImpl implement
* {@inheritDoc}
*/
public MessageInterpolator getDefaultMessageInterpolator() {
+ if (defaultMessageInterpolator == null) {
+ defaultMessageInterpolator = new DefaultMessageInterpolator();
+ }
return defaultMessageInterpolator;
}
@@ -222,6 +230,9 @@ public class ConfigurationImpl implement
* {@inheritDoc}
*/
public TraversableResolver getDefaultTraversableResolver() {
+ if (defaultTraversableResolver == null) {
+ defaultTraversableResolver = new DefaultTraversableResolver();
+ }
return defaultTraversableResolver;
}
@@ -229,6 +240,9 @@ public class ConfigurationImpl implement
* {@inheritDoc}
*/
public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() {
+ if (defaultConstraintValidatorFactory == null) {
+ defaultConstraintValidatorFactory = new DefaultConstraintValidatorFactory();
+ }
return defaultConstraintValidatorFactory;
}
@@ -239,20 +253,16 @@ public class ConfigurationImpl implement
* @throws ValidationException if the ValidatorFactory cannot be built
*/
public ValidatorFactory buildValidatorFactory() {
- return SecureActions.run(SecureActions.doPrivBuildValidatorFactory(this));
- }
-
- public ValidatorFactory doPrivBuildValidatorFactory() {
+ // execute with privileges where necessary:
prepare();
- if (provider != null) {
- return provider.buildValidatorFactory(this);
- } else {
- return findProvider().buildValidatorFactory(this);
- }
+ return findProvider().buildValidatorFactory(this);
}
- private void prepare() {
- if (prepared) return;
+ private synchronized void prepare() {
+ if (prepared) {
+ return;
+ }
+ // TODO refactor xml vs. java bootstrapping priority
parseValidationXml();
applyDefaults();
prepared = true;
@@ -262,22 +272,28 @@ public class ConfigurationImpl implement
private void parseValidationXml() {
if (isIgnoreXmlConfiguration()) {
log.info("ignoreXmlConfiguration == true");
- } else {
- new ValidationParser(getProperties().get(Properties.VALIDATION_XML_PATH))
- .processValidationConfig(this);
+ return;
}
+ PRIVILEGED.run(new PrivilegedAction<Void>() {
+
+ public Void run() {
+ new ValidationParser(getProperties().get(
+ Properties.VALIDATION_XML_PATH))
+ .processValidationConfig(ConfigurationImpl.this);
+ return null;
+ }
+ });
}
private void applyDefaults() {
- // make sure we use the defaults in case they haven't been provided yet
- if (traversableResolver == null) {
- traversableResolver = getDefaultTraversableResolver();
+ if (getMessageInterpolator() == null) {
+ messageInterpolator(getDefaultMessageInterpolator());
}
- if (messageInterpolator == null) {
- messageInterpolator = getDefaultMessageInterpolator();
+ if (getTraversableResolver() == null) {
+ traversableResolver(getDefaultTraversableResolver());
}
- if (constraintValidatorFactory == null) {
- constraintValidatorFactory = getDefaultConstraintValidatorFactory();
+ if (getConstraintValidatorFactory() == null) {
+ constraintValidatorFactory(getDefaultConstraintValidatorFactory());
}
}
@@ -297,35 +313,31 @@ public class ConfigurationImpl implement
}
/**
- * Get the configured {@link ValidationProvider}.
- * @return {@link ValidationProvider}
+ * Set {@link ValidationProvider} class.
+ * @param providerClass
*/
- public ValidationProvider<?> getProvider() {
- return provider;
+ public void setProviderClass(Class<? extends ValidationProvider<?>> providerClass) {
+ this.providerClass = providerClass;
}
private ValidationProvider<?> findProvider() {
- if (providerClass != null) {
- for (ValidationProvider<?> provider : providerResolver
- .getValidationProviders()) {
- if (providerClass.isAssignableFrom(provider.getClass())) {
- return provider;
- }
+ if (provider != null) {
+ return provider;
+ }
+ final Iterator<ValidationProvider<?>> iter = providerResolver.getValidationProviders().iterator();
+ if (!iter.hasNext()) {
+ throw new ValidationException("No available ValidationProvider implementation");
+ }
+ if (providerClass == null) {
+ return iter.next();
+ }
+ while (iter.hasNext()) {
+ ValidationProvider<?> provider = iter.next();
+ if (providerClass.isInstance(provider)) {
+ return provider;
}
- throw new ValidationException(
- "Unable to find suitable provider: " + providerClass);
- } else {
- List<ValidationProvider<?>> providers = providerResolver.getValidationProviders();
- return providers.get(0);
}
- }
-
- /**
- * Set {@link ValidationProvider} class.
- * @param providerClass
- */
- public void setProviderClass(Class<? extends ValidationProvider<?>> providerClass) {
- this.providerClass = providerClass;
+ throw new ValidationException(String.format("Unable to find ValidationProvider of type %s", providerClass));
}
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintAnnotationAttributes.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintAnnotationAttributes.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintAnnotationAttributes.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintAnnotationAttributes.java Mon Apr 2 19:31:16 2012
@@ -30,7 +30,7 @@ import javax.validation.ConstraintDefini
import javax.validation.Payload;
import javax.validation.ValidationException;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.commons.lang3.reflect.TypeUtils;
/**
@@ -67,6 +67,8 @@ public enum ConstraintAnnotationAttribut
Annotation[] value;
}
+ private static final Privileged PRIVILEGED = new Privileged();
+
private Type type;
private boolean permitNullDefaultValue;
@@ -214,7 +216,7 @@ public enum ConstraintAnnotationAttribut
boolean _valid = true;
Object _defaultValue = null;
try {
- method = doPrivileged(SecureActions.getPublicMethod(constraintType, getAttributeName()));
+ method = PRIVILEGED.getPublicMethod(constraintType, getAttributeName());
if (method == null) {
if (quiet) {
_valid = false;
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDefaults.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDefaults.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDefaults.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/ConstraintDefaults.java Mon Apr 2 19:31:16 2012
@@ -18,17 +18,21 @@
*/
package org.apache.bval.jsr303;
-import org.apache.bval.jsr303.util.SecureActions;
-
-import javax.validation.ConstraintValidator;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
-import java.security.PrivilegedAction;
-import java.util.*;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
+import javax.validation.ConstraintValidator;
+
+import org.apache.bval.jsr303.util.Privileged;
+
/**
* Description: Provides access to the default constraints/validator implementation classes built into the framework.
* These are configured in DefaultConstraints.properties.<br/>
@@ -37,6 +41,7 @@ public class ConstraintDefaults {
private static final Logger log = Logger.getLogger(ConstraintDefaults.class.getName());
private static final String DEFAULT_CONSTRAINTS =
"org/apache/bval/jsr303/DefaultConstraints.properties";
+ private static final Privileged PRIVILEGED = new Privileged();
/**
* The default constraint data stored herein.
@@ -72,7 +77,7 @@ public class ConstraintDefaults {
@SuppressWarnings("unchecked")
private Map<String, Class<? extends ConstraintValidator<?, ?>>[]> loadDefaultConstraints(String resource) {
Properties constraintProperties = new Properties();
- final ClassLoader classloader = getClassLoader();
+ final ClassLoader classloader = PRIVILEGED.getClassLoader(getClass());
InputStream stream = classloader.getResourceAsStream(resource);
if (stream != null) {
try {
@@ -93,32 +98,17 @@ public class ConstraintDefaults {
while (tokens.hasMoreTokens()) {
final String eachClassName = tokens.nextToken();
- Class<?> constraintValidatorClass =
- SecureActions.run(new PrivilegedAction<Class<?>>() {
- public Class<?> run() {
- try {
- return Class.forName(eachClassName, true, classloader);
- } catch (ClassNotFoundException e) {
- log.log(Level.SEVERE, String.format("Cannot find class %s", eachClassName), e);
- return null;
- }
- }
- });
-
- if (constraintValidatorClass != null) classes.add(constraintValidatorClass);
-
+ try {
+ classes.add(PRIVILEGED.getClass(classloader, eachClassName));
+ } catch (ClassNotFoundException e) {
+ log.log(Level.SEVERE, String.format("Cannot find class %s", eachClassName), e);
+ }
}
loadedConstraints
.put((String) entry.getKey(),
(Class<? extends ConstraintValidator<?, ?>>[]) classes.toArray(new Class[classes.size()]));
-
}
return loadedConstraints;
}
- private ClassLoader getClassLoader() {
- ClassLoader classloader = Thread.currentThread().getContextClassLoader();
- if (classloader == null) classloader = getClass().getClassLoader();
- return classloader;
- }
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultMessageInterpolator.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultMessageInterpolator.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultMessageInterpolator.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultMessageInterpolator.java Mon Apr 2 19:31:16 2012
@@ -16,8 +16,6 @@
*/
package org.apache.bval.jsr303;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
@@ -30,7 +28,7 @@ import java.util.regex.Pattern;
import javax.validation.MessageInterpolator;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.commons.lang3.ArrayUtils;
/**
@@ -48,6 +46,7 @@ public class DefaultMessageInterpolator
/** Regular expression used to do message interpolation. */
private static final Pattern messageParameterPattern =
Pattern.compile("(\\{[\\w\\.]+\\})");
+ private static final Privileged PRIVILEGED = new Privileged();
/** The default locale for the current user. */
private Locale defaultLocale;
@@ -164,19 +163,24 @@ public class DefaultMessageInterpolator
*/
private ResourceBundle getFileBasedResourceBundle(Locale locale) {
ResourceBundle rb = null;
- final ClassLoader classLoader = doPrivileged(SecureActions.getContextClassLoader());
- if (classLoader != null) {
- rb = loadBundle(classLoader, locale,
- USER_VALIDATION_MESSAGES + " not found by thread local classloader");
- }
-
// 2011-03-27 jw: No privileged action required.
// A class can always access the classloader of itself and of subclasses.
+ /*
+ * MJB: Most BVal code prefers the CCL, then the loader of a particular--usually the calling--class.
+ * the signature of Privileged#getClassLoader() simply expedites this in a syntactically compact
+ * manner, despite potentially (probably very rarely) calling for a classLoader using privileges
+ * it may not precisely need. Patches to improve upon the situation without unduly impacting
+ * code verbosity or runtime performace will certainly be entertained.
+ */
+ final ClassLoader classLoader = PRIVILEGED.getClassLoader(getClass());
+ rb = loadBundle(classLoader, locale,
+ "%s not found by thread local classloader", USER_VALIDATION_MESSAGES);
+
if (rb == null) {
rb = loadBundle(
getClass().getClassLoader(),
locale,
- USER_VALIDATION_MESSAGES + " not found by validator classloader"
+ "%s not found by validator classloader", USER_VALIDATION_MESSAGES
);
}
if (rb != null) {
@@ -188,7 +192,7 @@ public class DefaultMessageInterpolator
}
private ResourceBundle loadBundle(ClassLoader classLoader, Locale locale,
- String message) {
+ String message, Object... params) {
ResourceBundle rb = null;
try {
rb = ResourceBundle.getBundle(USER_VALIDATION_MESSAGES, locale, classLoader);
@@ -301,23 +305,4 @@ public class DefaultMessageInterpolator
private String sanitizeForAppendReplacement(String src) {
return src.replace("\\", "\\\\").replace("$", "\\$");
}
-
-
-
- /**
- * Perform action with AccessController.doPrivileged() if a security manager is installed.
- *
- * @param action
- * the action to run
- * @return
- * result of the action
- */
- private static <T> T doPrivileged(final PrivilegedAction<T> action) {
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged(action);
- } else {
- return action.run();
- }
- }
-
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultValidationProviderResolver.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultValidationProviderResolver.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultValidationProviderResolver.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/DefaultValidationProviderResolver.java Mon Apr 2 19:31:16 2012
@@ -16,83 +16,71 @@
*/
package org.apache.bval.jsr303;
-
-import javax.validation.ValidationException;
-import javax.validation.ValidationProviderResolver;
-import javax.validation.spi.ValidationProvider;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
+import javax.validation.ValidationException;
+import javax.validation.ValidationProviderResolver;
+import javax.validation.spi.ValidationProvider;
+
+import org.apache.bval.jsr303.util.IOUtils;
+import org.apache.bval.jsr303.util.Privileged;
+
public class DefaultValidationProviderResolver implements ValidationProviderResolver {
- //TODO - Spec recommends caching per classloader
- private static final String SPI_CFG =
- "META-INF/services/javax.validation.spi.ValidationProvider";
+ // TODO - Spec recommends caching per classloader
+ private static final String SPI_CFG = "META-INF/services/javax.validation.spi.ValidationProvider";
+ private static final Privileged PRIVILEGED = new Privileged();
/**
* {@inheritDoc}
*/
public List<ValidationProvider<?>> getValidationProviders() {
- List<ValidationProvider<?>> providers = new ArrayList<ValidationProvider<?>>();
+ final List<ValidationProvider<?>> target = new ArrayList<ValidationProvider<?>>();
+
+ // get our classloader
+ final ClassLoader classLoader = PRIVILEGED.getClassLoader(getClass());
+
+ // find all service provider cfgs
+ final Enumeration<URL> cfgs;
try {
- // get our classloader
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null)
- cl = DefaultValidationProviderResolver.class.getClassLoader();
- // find all service provider cfgs
- Enumeration<URL> cfgs = cl.getResources(SPI_CFG);
- while (cfgs.hasMoreElements()) {
- URL url = cfgs.nextElement();
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(url.openStream()), 256);
- String line = br.readLine();
- // cfgs may contain multiple providers and/or comments
- while (line != null) {
- line = line.trim();
- if (!line.startsWith("#")) {
- try {
- // try loading the specified class
- final Class<?> provider = cl.loadClass(line);
- // create an instance to return
- ValidationProvider<?> vp =
- AccessController.doPrivileged(new PrivilegedAction<ValidationProvider<?>>() {
- public ValidationProvider<?> run() {
- try {
- return (ValidationProvider<?>) provider.newInstance();
- } catch (final Exception ex) {
- throw new ValidationException("Cannot instantiate : " + provider, ex);
- }
- }
- });
- providers.add(vp);
-
- } catch (ClassNotFoundException e) {
- throw new ValidationException("Failed to load provider " +
- line + " configured in file " + url, e);
- }
- }
- line = br.readLine();
+ cfgs = classLoader.getResources(SPI_CFG);
+ } catch (IOException e) {
+ throw new ValidationException(String.format("Error trying to read a %s", SPI_CFG), e);
+ }
+
+ while (cfgs.hasMoreElements()) {
+ final URL url = cfgs.nextElement();
+ BufferedReader br = null;
+ try {
+ br = new BufferedReader(new InputStreamReader(url.openStream()), 256);
+ for (String line = br.readLine().trim(); line != null; line = br.readLine().trim()) {
+ if (line.length() == 0 || line.charAt(0) == '#') {
+ continue;
+ }
+ try {
+ @SuppressWarnings("unchecked")
+ Class<? extends ValidationProvider<?>> providerType =
+ (Class<? extends ValidationProvider<?>>) PRIVILEGED.getClass(classLoader, line);
+ target.add(providerType.newInstance());
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new ValidationException(String.format(
+ "Error creating ValidationProvider of type %s configured in resource %s", line, url), e);
}
- br.close();
- } catch (IOException e) {
- throw new ValidationException("Error trying to read " + url, e);
- } finally {
- if (br != null)
- br.close();
}
+ } catch (IOException e) {
+ throw new ValidationException(String.format("Error trying to read url %s", url), e);
+ } finally {
+ IOUtils.closeQuietly(br);
}
- } catch (IOException e) {
- throw new ValidationException("Error trying to read a " + SPI_CFG, e);
}
// caller must handle the case of no providers found
- return providers;
+ return target;
}
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/Jsr303MetaBeanFactory.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/Jsr303MetaBeanFactory.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/Jsr303MetaBeanFactory.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/Jsr303MetaBeanFactory.java Mon Apr 2 19:31:16 2012
@@ -22,8 +22,6 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
@@ -38,7 +36,7 @@ import javax.validation.groups.Default;
import org.apache.bval.MetaBeanFactory;
import org.apache.bval.jsr303.groups.Group;
import org.apache.bval.jsr303.util.ClassHelper;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
import org.apache.bval.jsr303.xml.MetaConstraint;
import org.apache.bval.model.MetaBean;
import org.apache.bval.model.MetaProperty;
@@ -57,6 +55,8 @@ public class Jsr303MetaBeanFactory imple
/** {@link ApacheFactoryContext} used */
protected final ApacheFactoryContext factoryContext;
+
+ private static final Privileged PRIVILEGED = new Privileged();
/**
* {@link AnnotationProcessor} used.
@@ -120,7 +120,7 @@ public class Jsr303MetaBeanFactory imple
metabean));
}
- final Field[] fields = doPrivileged(SecureActions.getDeclaredFields(beanClass));
+ final Field[] fields = PRIVILEGED.getDeclaredFields(beanClass);
for (Field field : fields) {
MetaProperty metaProperty = metabean.getProperty(field.getName());
// create a property for those fields for which there is not yet a
@@ -137,7 +137,7 @@ public class Jsr303MetaBeanFactory imple
}
}
}
- final Method[] methods = doPrivileged(SecureActions.getDeclaredMethods(beanClass));
+ final Method[] methods = PRIVILEGED.getDeclaredMethods(beanClass);
for (Method method : methods) {
String propName = null;
if (method.getParameterTypes().length == 0) {
@@ -296,22 +296,4 @@ public class Jsr303MetaBeanFactory imple
return result;
}
-
-
-
- /**
- * Perform action with AccessController.doPrivileged() if a security manager is installed.
- *
- * @param action
- * the action to run
- * @return
- * result of the action
- */
- private static <T> T doPrivileged(final PrivilegedAction<T> action) {
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged(action);
- } else {
- return action.run();
- }
- }
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/resolver/DefaultTraversableResolver.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/resolver/DefaultTraversableResolver.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/resolver/DefaultTraversableResolver.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/resolver/DefaultTraversableResolver.java Mon Apr 2 19:31:16 2012
@@ -17,17 +17,13 @@
package org.apache.bval.jsr303.resolver;
import java.lang.annotation.ElementType;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.Path;
import javax.validation.TraversableResolver;
-import org.apache.bval.jsr303.util.ClassHelper;
-import org.apache.bval.util.PrivilegedActions;
-import org.apache.commons.lang3.ClassUtils;
+import org.apache.bval.jsr303.util.Privileged;
/** @see javax.validation.TraversableResolver */
public class DefaultTraversableResolver implements TraversableResolver, CachingRelevant {
@@ -41,6 +37,7 @@ public class DefaultTraversableResolver
private static final String JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME =
"org.apache.bval.jsr303.resolver.JPATraversableResolver";
+ private static final Privileged PRIVILEGED = new Privileged();
private TraversableResolver jpaTR;
@@ -72,28 +69,30 @@ public class DefaultTraversableResolver
}
/** Tries to load detect and load JPA. */
- @SuppressWarnings("unchecked")
private void initJpa() {
- final ClassLoader classLoader = getClassLoader();
+ final ClassLoader classLoader = PRIVILEGED.getClassLoader(getClass());
try {
- PrivilegedActions.getUtilClass(classLoader, PERSISTENCE_UTIL_CLASSNAME);
+ PRIVILEGED.getClass(classLoader, PERSISTENCE_UTIL_CLASSNAME);
log.log(Level.FINEST, String.format("Found %s on classpath.", PERSISTENCE_UTIL_CLASSNAME));
} catch (Exception e) {
- log.log(Level.FINEST, String.format("Cannot find %s on classpath. All properties will per default be traversable.", PERSISTENCE_UTIL_CLASSNAME));
+ log.log(Level.FINEST, String.format(
+ "Cannot find %s on classpath. All properties will per default be traversable.",
+ PERSISTENCE_UTIL_CLASSNAME));
return;
}
try {
+ @SuppressWarnings("unchecked")
Class<? extends TraversableResolver> jpaAwareResolverClass =
- (Class<? extends TraversableResolver>)
- ClassUtils.getClass(classLoader, JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME, true);
+ (Class<? extends TraversableResolver>) PRIVILEGED.getClass(classLoader,
+ JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME);
jpaTR = jpaAwareResolverClass.newInstance();
- log.log(Level.FINEST, String.format("Instantiated an instance of %s.", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME));
+ log.log(Level.FINEST,
+ String.format("Instantiated an instance of %s.", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME));
} catch (Exception e) {
- log.log(Level.WARNING,
- String.format(
- "Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable.",
- JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME, e));
+ log.log(Level.WARNING, String.format(
+ "Unable to load or instantiate JPA aware resolver %s. All properties will per default be traversable.",
+ JPA_AWARE_TRAVERSABLE_RESOLVER_CLASSNAME, e));
}
}
@@ -104,20 +103,4 @@ public class DefaultTraversableResolver
return jpaTR != null && CachingTraversableResolver.needsCaching(jpaTR);
}
- private static ClassLoader getClassLoader()
- {
- return (System.getSecurityManager() == null)
- ? getClassLoader0()
- : AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return getClassLoader0();
- }
- });
- }
-
- private static ClassLoader getClassLoader0()
- {
- final ClassLoader loader = Thread.currentThread().getContextClassLoader();
- return (loader != null) ? loader : ClassHelper.class.getClassLoader();
- }
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ClassHelper.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ClassHelper.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ClassHelper.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ClassHelper.java Mon Apr 2 19:31:16 2012
@@ -18,8 +18,6 @@
*/
package org.apache.bval.jsr303.util;
-import org.apache.commons.lang3.ClassUtils;
-
import java.security.AccessController;
import java.util.List;
@@ -57,26 +55,4 @@ public class ClassHelper {
}
}
- /**
- * @deprecated Will be removed for security reasons.
- *
- * Perform ClassUtils.getClass functions with Java 2 Security enabled.
- */
- @Deprecated
- public static Class<?> getClass(String className) throws ClassNotFoundException {
- return getClass(className, true);
- }
-
- /**
- * @deprecated Will be removed for security reasons.
- *
- * Perform ClassUtils.getClass functions with Java 2 Security enabled.
- */
- @Deprecated
- public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if (loader == null)
- loader = ClassHelper.class.getClassLoader();
- return ClassUtils.getClass(loader, className, initialize);
- }
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ConstraintDefinitionValidator.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ConstraintDefinitionValidator.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ConstraintDefinitionValidator.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/ConstraintDefinitionValidator.java Mon Apr 2 19:31:16 2012
@@ -34,6 +34,7 @@ import java.util.Locale;
* @author Carlos Vara
*/
public class ConstraintDefinitionValidator {
+ private static final Privileged PRIVILEGED = new Privileged();
/**
* Ensures that the constraint definition is valid.
@@ -57,9 +58,7 @@ public class ConstraintDefinitionValidat
* The annotation to check.
*/
private static void validAttributes(final Annotation annotation) {
- final Method[] methods = SecureActions.run(
- SecureActions.getDeclaredMethods(annotation.annotationType())
- );
+ final Method[] methods = PRIVILEGED.getDeclaredMethods(annotation.annotationType());
for (Method method : methods ){
// Currently case insensitive, the spec is unclear about this
if (method.getName().toLowerCase(Locale.ENGLISH).startsWith("valid")) {
Added: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java?rev=1308497&view=auto
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java (added)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java Mon Apr 2 19:31:16 2012
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.bval.jsr303.util;
+
+import java.io.InputStream;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedExceptionAction;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+
+/**
+ * Extended utility object for Bean Validation-specific privileged work.
+ */
+@SuppressWarnings("restriction")
+public class Privileged extends org.apache.bval.util.Privileged {
+ /**
+ * Get the named field declared by the specified class. The result of the action will be {@code null} if there is no
+ * such field.
+ */
+ public Field getDeclaredField(final Class<?> clazz, final String fieldName) {
+ return run(new PrivilegedAction<Field>() {
+ public Field run() {
+ try {
+ final Field f = clazz.getDeclaredField(fieldName);
+ f.setAccessible(true);
+ return f;
+ } catch (final NoSuchFieldException ex) {
+ return null;
+ }
+ }
+ });
+ }
+
+ /**
+ * Get all fields declared by the specified class.
+ */
+ public Field[] getDeclaredFields(final Class<?> clazz) {
+ return run(new PrivilegedAction<Field[]>() {
+ public Field[] run() {
+ final Field[] fields = clazz.getDeclaredFields();
+ if (fields.length > 0) {
+ AccessibleObject.setAccessible(fields, true);
+ }
+ return fields;
+ }
+ });
+ }
+
+ /**
+ * Get all methods declared by the specified class.
+ */
+ public Method[] getDeclaredMethods(final Class<?> clazz) {
+ return run(new PrivilegedAction<Method[]>() {
+ public Method[] run() {
+ final Method[] result = clazz.getDeclaredMethods();
+ AccessibleObject.setAccessible(result, true);
+ return result;
+ }
+ });
+ }
+
+ /**
+ * Get the named method declared by the specified class or by one of its ancestors. The result of the action will be
+ * {@code null} if there is no such method.
+ *
+ * @param clazz
+ * @param methodName
+ * @param parameterTypes
+ * @return public method or {@code null}.
+ */
+ public Method getPublicMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterTypes) {
+ return run(new PrivilegedAction<Method>() {
+ public Method run() {
+ try {
+ return clazz.getMethod(methodName, parameterTypes);
+ } catch (final NoSuchMethodException ex) {
+ return null;
+ }
+ }
+ });
+ }
+
+ /**
+ * Unmarshall JAXB XML.
+ *
+ * @param schema
+ * @param inputStream
+ * @param type
+ * @return T
+ * @throws JAXBException
+ */
+ public <T> T unmarshallXml(final Schema schema, final InputStream inputStream, final Class<T> type)
+ throws JAXBException {
+ try {
+ return run(new PrivilegedExceptionAction<T>() {
+
+ public T run() throws JAXBException {
+ JAXBContext jc = JAXBContext.newInstance(type);
+ Unmarshaller unmarshaller = jc.createUnmarshaller();
+ unmarshaller.setSchema(schema);
+ StreamSource stream = new StreamSource(inputStream);
+ JAXBElement<T> root = unmarshaller.unmarshal(stream, type);
+ return root.getValue();
+ }
+ });
+ } catch (Exception e) {
+ throw (JAXBException) e;
+ }
+ }
+
+}
Propchange: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/util/Privileged.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxy.java Mon Apr 2 19:31:16 2012
@@ -20,14 +20,12 @@ import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
/**
* Description: <br/>
@@ -42,6 +40,8 @@ class AnnotationProxy implements Annotat
/** Serialization version */
private static final long serialVersionUID = 1L;
+ private static final Privileged PRIVILEGED = new Privileged();
+
private final Class<? extends Annotation> annotationType;
private final Map<String, Object> values;
@@ -59,9 +59,7 @@ class AnnotationProxy implements Annotat
private <A extends Annotation> Map<String, Object> getAnnotationValues(AnnotationProxyBuilder<A> descriptor) {
Map<String, Object> result = new HashMap<String, Object>();
int processedValuesFromDescriptor = 0;
- final Method[] declaredMethods = doPrivileged(
- SecureActions.getDeclaredMethods(annotationType)
- );
+ final Method[] declaredMethods = PRIVILEGED.getDeclaredMethods(annotationType);
for (Method m : declaredMethods) {
if (descriptor.contains(m.getName())) {
result.put(m.getName(), descriptor.getValue(m.getName()));
@@ -118,13 +116,4 @@ class AnnotationProxy implements Annotat
return result;
}
-
-
- private static <T> T doPrivileged(final PrivilegedAction<T> action) {
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged(action);
- } else {
- return action.run();
- }
- }
}
Modified: bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java
URL: http://svn.apache.org/viewvc/bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java?rev=1308497&r1=1308496&r2=1308497&view=diff
==============================================================================
--- bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java (original)
+++ bval/branches/privileged/bval-jsr303/src/main/java/org/apache/bval/jsr303/xml/AnnotationProxyBuilder.java Mon Apr 2 19:31:16 2012
@@ -22,7 +22,6 @@ import java.lang.reflect.InvocationHandl
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
-import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
@@ -31,7 +30,7 @@ import javax.validation.Payload;
import javax.validation.ValidationException;
import org.apache.bval.jsr303.ConstraintAnnotationAttributes;
-import org.apache.bval.jsr303.util.SecureActions;
+import org.apache.bval.jsr303.util.Privileged;
/**
* Description: Holds the information and creates an annotation proxy during xml
@@ -40,6 +39,8 @@ import org.apache.bval.jsr303.util.Secur
// TODO move this guy up to org.apache.bval.jsr303 or
// org.apache.bval.jsr303.model
final public class AnnotationProxyBuilder<A extends Annotation> {
+ private static final Privileged PRIVILEGED = new Privileged();
+
private final Class<A> type;
private final Map<String, Object> elements = new HashMap<String, Object>();
@@ -75,7 +76,7 @@ final public class AnnotationProxyBuilde
public AnnotationProxyBuilder(A annot) {
this((Class<A>) annot.annotationType());
// Obtain the "elements" of the annotation
- final Method[] methods = doPrivileged(SecureActions.getDeclaredMethods(annot.annotationType()));
+ final Method[] methods = PRIVILEGED.getDeclaredMethods(annot.annotationType());
for (Method m : methods) {
if (!m.isAccessible()) {
m.setAccessible(true);
@@ -176,11 +177,11 @@ final public class AnnotationProxyBuilde
* @return {@link Annotation}
*/
public A createAnnotation() {
- ClassLoader classLoader = SecureActions.getClassLoader(getType());
+ ClassLoader classLoader = PRIVILEGED.getClassLoader(getType());
@SuppressWarnings("unchecked")
final Class<A> proxyClass = (Class<A>) Proxy.getProxyClass(classLoader, getType());
final InvocationHandler handler = new AnnotationProxy(this);
- return doPrivileged(new PrivilegedAction<A>() {
+ return PRIVILEGED.run(new PrivilegedAction<A>() {
public A run() {
try {
Constructor<A> constructor = proxyClass.getConstructor(InvocationHandler.class);
@@ -192,11 +193,4 @@ final public class AnnotationProxyBuilde
});
}
- private static <T> T doPrivileged(final PrivilegedAction<T> action) {
- if (System.getSecurityManager() != null) {
- return AccessController.doPrivileged(action);
- } else {
- return action.run();
- }
- }
}