0 Replies Latest reply on Jan 18, 2008 10:52 AM by lpmon

    Handy class to get Hibernate entity validation failures

    lpmon Novice

      Hopefully it is useful to you!

      This would be used when an exception is thrown in a method that saves an entity bean, the Hibernate validator is being used, and you are using the Seam FacesMessages object. It tries to find the Hibernate InvalidStateException object, which may be wrapped in the "cause" of another exception object. Note: I did not write this to go down the "cause" stack trace to find the InvalidStateException. I have not seen that need in my experiments. Notice the 2 different signatures (different exception classes) for the method.

      package com.shockwatch.jsf;
      import org.hibernate.validator.InvalidStateException;
      import org.hibernate.validator.InvalidValue;
      import org.jboss.seam.core.FacesMessages;

      public class ValidationUtil {

      // add error messages from Hibernate Validator
      public static void addInvalids(FacesMessages fMsgs, InvalidStateException ex)
      {
      for (InvalidValue error : ex.getInvalidValues())
      {
      fMsgs.add(error.getPropertyName() + " " + error.getMessage());
      }
      }

      /* Sometimes another exception type is thrown by EJB container, like EJBTransactionRolledbackException
      Attempt to find InvalidStateException and add validation failure if found,otherwise add exception message
      */
      public static void addInvalids(FacesMessages fMsgs, Exception ex)
      {
      if (ex instanceof InvalidStateException) // just add messages
      {
      addInvalids(fMsgs, (InvalidStateException)ex);
      return;
      }

      try
      { // try to extract Hibernate Validator exception, cast exception if not found
      InvalidStateException ise = (InvalidStateException)ex.getCause();
      addInvalids(fMsgs, ise);
      }
      catch (ClassCastException castEx) // not a validation exception
      {
      fMsgs.add(ex.getLocalizedMessage() + " Caused by: " + ex.getCause().getLocalizedMessage());
      }
      }
      }