incubator-bval-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From simonetrip...@apache.org
Subject svn commit: r1074156 - in /incubator/bval/trunk/bval-guice/src: main/java/org/apache/bval/guice/ test/java/org/apache/bval/guice/
Date Thu, 24 Feb 2011 14:11:35 GMT
Author: simonetripodi
Date: Thu Feb 24 14:11:34 2011
New Revision: 1074156

URL: http://svn.apache.org/viewvc?rev=1074156&view=rev
Log:
added the ability to AOP interceptor to translate exceptions using also custom messages, formatted
using java.util.Formatter, passing invoked method arguments as message format arguments

Modified:
    incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/Validate.java
    incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/ValidateMethodInterceptor.java
    incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyCountryDao.java
    incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyException.java
    incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/GuiceAwareValidationTestCase.java

Modified: incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/Validate.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/Validate.java?rev=1074156&r1=1074155&r2=1074156&view=diff
==============================================================================
--- incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/Validate.java (original)
+++ incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/Validate.java Thu
Feb 24 14:11:34 2011
@@ -58,4 +58,15 @@ public @interface Validate {
      */
     Class<? extends Throwable> rethrowExceptionsAs() default ConstraintViolationException.class;
 
+    /**
+     * A custom error message when throwing the custom exception.
+     *
+     * It supports java.util.Formatter place holders, intercepted method
+     * arguments will be used as message format arguments.
+     *
+     * @return a custom error message when throwing the custom exception.
+     * @see java.util.Formatter#format(String, Object...)
+     */
+    String exceptionMessage() default "";
+
 }

Modified: incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/ValidateMethodInterceptor.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/ValidateMethodInterceptor.java?rev=1074156&r1=1074155&r2=1074156&view=diff
==============================================================================
--- incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/ValidateMethodInterceptor.java
(original)
+++ incubator/bval/trunk/bval-guice/src/main/java/org/apache/bval/guice/ValidateMethodInterceptor.java
Thu Feb 24 14:11:34 2011
@@ -38,6 +38,10 @@ import org.apache.bval.jsr303.extensions
  */
 public final class ValidateMethodInterceptor implements MethodInterceptor {
 
+    private static final Class<?>[] CAUSE_TYPES = new Class[]{ Throwable.class };
+
+    private static final Class<?>[] MESSAGE_CAUSE_TYPES = new Class[]{ String.class,
Throwable.class };
+
     /**
      * The {@link ValidatorProvider} reference.
      */
@@ -74,22 +78,30 @@ public final class ValidateMethodInterce
                 groups));
 
         if (!constraintViolations.isEmpty()) {
-            throw getException(new ConstraintViolationException("Validation error when calling
method '"
-                        + method
-                        + "' with arguments "
-                        + Arrays.deepToString(arguments), constraintViolations),
-                    validate.rethrowExceptionsAs());
+            throw getException(new ConstraintViolationException(
+                    String.format("Validation error when calling method '%s' with arguments
",
+                            method,
+                            Arrays.deepToString(arguments)),
+                    constraintViolations),
+                    validate.rethrowExceptionsAs(),
+                    validate.exceptionMessage(),
+                    arguments);
         }
 
         Object returnedValue = invocation.proceed();
 
         if (validate.validateReturnedValue()) {
             constraintViolations.addAll(methodValidator.validateReturnedValue(clazz, method,
returnedValue, groups));
+
             if (!constraintViolations.isEmpty()) {
-                throw getException(new ConstraintViolationException("Method '"
-                        + method
-                        + "' returned a not valid value "
-                        + returnedValue, constraintViolations), validate.rethrowExceptionsAs());
+                throw getException(new ConstraintViolationException(
+                        String.format("Method '%s' returned a not valid value ",
+                                method,
+                                returnedValue),
+                        constraintViolations),
+                        validate.rethrowExceptionsAs(),
+                        validate.exceptionMessage(),
+                        arguments);
             }
         }
 
@@ -105,7 +117,9 @@ public final class ValidateMethodInterce
      * @return the {@link Throwable} has o be thrown.
      */
     private static Throwable getException(ConstraintViolationException exception,
-            Class<? extends Throwable> exceptionWrapperClass) {
+            Class<? extends Throwable> exceptionWrapperClass,
+            String exceptionMessage,
+            Object[] arguments) {
         // check the thrown exception is of same re-throw type
         if (exceptionWrapperClass == ConstraintViolationException.class) {
             return exception;
@@ -114,16 +128,53 @@ public final class ValidateMethodInterce
         // re-throw the exception as new exception
         Throwable rethrowEx = null;
 
-        try {
-            Constructor<? extends Throwable> constructor = exceptionWrapperClass.getConstructor(Throwable.class);
-            rethrowEx = constructor.newInstance(exception);
-        } catch (Exception e) {
-            rethrowEx = new RuntimeException("Impossible to re-throw '"
-                    + exceptionWrapperClass
-                    + "', it needs the constructor with <Throwable> argument.", e);
+        String errorMessage;
+        Object[] initargs;
+        Class<?>[] initargsType;
+
+        if (exceptionMessage.length() != 0) {
+            errorMessage = String.format(exceptionMessage, arguments);
+            initargs = new Object[]{ errorMessage, exception };
+            initargsType = MESSAGE_CAUSE_TYPES;
+        } else {
+            initargs = new Object[]{ exception };
+            initargsType = CAUSE_TYPES;
+        }
+
+        Constructor<? extends Throwable> exceptionConstructor = getMatchingConstructor(exceptionWrapperClass,
initargsType);
+        if (exceptionConstructor != null) {
+            try {
+                rethrowEx = exceptionConstructor.newInstance(initargs);
+            } catch (Exception e) {
+                errorMessage = String.format("Impossible to re-throw '%s', it needs the constructor
with %s argument(s).",
+                        exceptionWrapperClass.getName(),
+                        Arrays.toString(initargsType));
+                rethrowEx = new RuntimeException(errorMessage, e);
+            }
+        } else {
+            errorMessage = String.format("Impossible to re-throw '%s', it needs the constructor
with %s or %s argument(s).",
+                    exceptionWrapperClass.getName(),
+                    Arrays.toString(CAUSE_TYPES),
+                    Arrays.toString(MESSAGE_CAUSE_TYPES));
+            rethrowEx = new RuntimeException(errorMessage);
         }
 
         return rethrowEx;
     }
 
+    @SuppressWarnings("unchecked")
+    private static <E extends Throwable> Constructor<E> getMatchingConstructor(Class<E>
type,
+            Class<?>[] argumentsType) {
+        Class<? super E> currentType = type;
+        while (Object.class != currentType) {
+            for (Constructor<?> constructor : currentType.getConstructors()) {
+                if (Arrays.equals(argumentsType, constructor.getParameterTypes())) {
+                    return (Constructor<E>) constructor;
+                }
+            }
+            currentType = currentType.getSuperclass();
+        }
+        return null;
+    }
+
 }

Modified: incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyCountryDao.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyCountryDao.java?rev=1074156&r1=1074155&r2=1074156&view=diff
==============================================================================
--- incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyCountryDao.java
(original)
+++ incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyCountryDao.java
Thu Feb 24 14:11:34 2011
@@ -30,8 +30,8 @@ import javax.validation.constraints.Size
 public class DummyCountryDao {
 
     @Validate(
-            groups = { Insert.class },
-            validateReturnedValue = true
+        groups = { Insert.class },
+        validateReturnedValue = true
     )
     public Country insertCountry(@NotNull(groups = { Insert.class }) String name,
             @NotNull(groups = { Insert.class }) @Size(max = 2, groups = { Insert.class, Update.class
}) String iso2Code,
@@ -44,8 +44,9 @@ public class DummyCountryDao {
     }
 
     @Validate(
-            groups = { Update.class },
-            rethrowExceptionsAs = DummyException.class
+        groups = { Update.class },
+        rethrowExceptionsAs = DummyException.class,
+        exceptionMessage = "This is just a dummy message %s"
     )
     public int updateCountry(@Valid Country country) {
         return 0;

Modified: incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyException.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyException.java?rev=1074156&r1=1074155&r2=1074156&view=diff
==============================================================================
--- incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyException.java
(original)
+++ incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/DummyException.java
Thu Feb 24 14:11:34 2011
@@ -29,4 +29,8 @@ public final class DummyException extend
         super(cause);
     }
 
+    public DummyException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
 }

Modified: incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/GuiceAwareValidationTestCase.java
URL: http://svn.apache.org/viewvc/incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/GuiceAwareValidationTestCase.java?rev=1074156&r1=1074155&r2=1074156&view=diff
==============================================================================
--- incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/GuiceAwareValidationTestCase.java
(original)
+++ incubator/bval/trunk/bval-guice/src/test/java/org/apache/bval/guice/GuiceAwareValidationTestCase.java
Thu Feb 24 14:11:34 2011
@@ -88,6 +88,7 @@ public final class GuiceAwareValidationT
             fail("org.apache.bval.guice.DummyException expected");
         } catch (Exception e) {
             assertEquals(DummyException.class, e.getClass());
+            assertTrue(e.getMessage().startsWith("This is just a dummy message "));
         }
     }
 



Mime
View raw message