db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject cvs commit: db-ojb/src/java/org/apache/ojb/broker/util ExceptionHelper.java
Date Sat, 22 Oct 2005 12:21:41 GMT
arminw      2005/10/22 05:21:41

  Modified:    src/java/org/apache/ojb/broker/accesslayer Tag:
                        OJB_1_0_RELEASE JdbcAccessImpl.java
  Added:       src/java/org/apache/ojb/broker/util Tag: OJB_1_0_RELEASE
                        ExceptionHelper.java
  Log:
  backport from HEAD, add exception helper class to generate more detailed messages on SQLException
  
  Revision  Changes    Path
  No                   revision
  No                   revision
  1.22.2.9  +60 -124   db-ojb/src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java
  
  Index: JdbcAccessImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/accesslayer/JdbcAccessImpl.java,v
  retrieving revision 1.22.2.8
  retrieving revision 1.22.2.9
  diff -u -r1.22.2.8 -r1.22.2.9
  --- JdbcAccessImpl.java	9 Oct 2005 23:50:45 -0000	1.22.2.8
  +++ JdbcAccessImpl.java	22 Oct 2005 12:21:40 -0000	1.22.2.9
  @@ -24,7 +24,6 @@
   import java.util.Map;
   
   import org.apache.ojb.broker.Identity;
  -import org.apache.ojb.broker.KeyConstraintViolatedException;
   import org.apache.ojb.broker.OptimisticLockException;
   import org.apache.ojb.broker.PersistenceBroker;
   import org.apache.ojb.broker.PersistenceBrokerException;
  @@ -39,6 +38,7 @@
   import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
   import org.apache.ojb.broker.platforms.Platform;
   import org.apache.ojb.broker.query.Query;
  +import org.apache.ojb.broker.util.ExceptionHelper;
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
   import org.apache.ojb.broker.util.sequence.SequenceManagerException;
  @@ -53,18 +53,6 @@
    */
   public class JdbcAccessImpl implements JdbcAccess
   {
  -    private static final String SQL_STATE_KEY_VIOLATED = "23000";
  -    private static final String SQL_STATE_FK_VIOLATED = "23505";
  -    /*
  -        X/OPEN codes within class 23:
  -            23000	INTEGRITY CONSTRAINT VIOLATION
  -            23001	RESTRICT VIOLATION
  -            23502	NOT NULL VIOLATION
  -            23503	FOREIGN KEY VIOLATION
  -            23505	UNIQUE VIOLATION
  -            23514	CHECK VIOLATION
  -    */
  -
       /**
        * The logger used.
        */
  @@ -107,7 +95,7 @@
               logger.debug("executeDelete: " + obj);
           }
   
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           PreparedStatement stmt = null;
           try
           {
  @@ -150,11 +138,8 @@
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of the delete (for "
  -                + cld.getClassOfObject().getName()
  -                + "): " + e.getMessage();
  -            logger.error(msg, e);
  -            throw new PersistenceBrokerSQLException("JdbcAccessImpl: " + msg, e);
  +            final String sql = broker.serviceSqlGenerator().getPreparedDeleteStatement(cld).getStatement();
  +            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
           }
           finally
           {
  @@ -173,12 +158,11 @@
           {
               logger.debug("executeDelete (by Query): " + query);
           }
  -
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           PreparedStatement stmt = null;
  +        final String sql = this.broker.serviceSqlGenerator().getPreparedDeleteStatement(query,
cld).getStatement();
           try
           {
  -            final String sql = this.broker.serviceSqlGenerator().getPreparedDeleteStatement(query,
cld).getStatement();
               stmt = sm.getPreparedStatement(cld, sql,
                       false, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, cld.getDeleteProcedure()!=null);
   
  @@ -190,11 +174,7 @@
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of delete by query (for "
  -                + cld.getClassOfObject().getName()
  -                + "): " + e.getMessage();
  -            logger.error(msg,e);
  -            throw new PersistenceBrokerSQLException(msg, e);
  +            throw ExceptionHelper.generateException(e, sql, cld, null, logger);
           }
           finally
           {
  @@ -213,7 +193,7 @@
           {
               logger.debug("executeInsert: " + obj);
           }
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           PreparedStatement stmt = null;
           try
           {
  @@ -247,43 +227,8 @@
           }
           catch (SQLException e)
           {
  -            final String stateCode = e.getSQLState();
  -            // Build a detailed error message
  -            StringBuffer msg = new StringBuffer("SQL failure while insert object data for
class ");
  -            try
  -            {
  -                msg.append(cld.getClassNameOfObject())
  -                        .append(", PK of the given object is [");
  -                FieldDescriptor[] fields = cld.getPkFields();
  -                for (int i = 0; i < fields.length; i++)
  -                {
  -                    msg.append(" ")
  -                            .append(fields[i].getPersistentField().getName())
  -                            .append("=")
  -                            .append(fields[i].getPersistentField().get(obj));
  -                }
  -                msg.append("], object was ").append(obj);
  -                msg.append(", exception message is [").append(e.getMessage()).append("]");
  -                msg.append(", SQL code [").append(stateCode).append("]");
  -            }
  -            catch (Exception ignore)
  -            {
  -                msg.append("- Sorry, can't generate a more detailed message");
  -            }
  -
  -            /**
  -             * throw a specific type of runtime exception for a key constraint.
  -             */
  -            if (SQL_STATE_KEY_VIOLATED.equals(stateCode)
  -                ||
  -                SQL_STATE_FK_VIOLATED.equals(stateCode))
  -            {
  -                throw new KeyConstraintViolatedException(msg.toString(), e);
  -            }
  -            else
  -            {
  -                throw new PersistenceBrokerSQLException(msg.toString(), e);
  -            }
  +            final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
  +            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
           }
           finally
           {
  @@ -314,13 +259,12 @@
           {
               scrollable = true;
           }
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           ResultSetAndStatement retval = null;
  -        SelectStatement sql;
  +        final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query,
cld);
           try
           {
               final int queryFetchSize = query.getFetchSize();
  -            sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);
               final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());
               final PreparedStatement stmt;
               stmt = sm.getPreparedStatement(cld, sql.getStatement() ,
  @@ -370,10 +314,6 @@
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of the query (for "
  -                    + cld.getClassOfObject().getName()
  -                    + "): " + e.getMessage();
  -            logger.error(msg, e);
               /*
   			 * MBAIRD: error condition could result in our
   			 * ResultSetAndStatement not being returned, and not being closed
  @@ -384,7 +324,7 @@
               {
                   retval.close();
               }
  -            throw new PersistenceBrokerSQLException(msg, e);
  +            throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger,
null);
           }
       }
   
  @@ -411,7 +351,7 @@
       {
           if (logger.isDebugEnabled()) logger.debug("executeSQL: " + sql);
           final boolean isStoredprocedure = isStoredProcedure(sql);
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           ResultSetAndStatement retval = null;
           try
           {
  @@ -471,9 +411,6 @@
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of the SQL query: " + sql
  -                    + ", message is: " + e.getMessage();
  -            logger.error(msg, e);
               /**
                * MBAIRD: error condition could result in our ResultSetAndStatement not being
returned, and not being closed
                * since it is opened before the try loop, we should release it if there is
a problem.
  @@ -482,7 +419,7 @@
               {
                   retval.close();
               }
  -            throw new PersistenceBrokerSQLException(msg, e);
  +            throw ExceptionHelper.generateException(e, sql, cld, values, logger, null);
           }
       }
   
  @@ -511,7 +448,7 @@
           int result;
           int index;
           PreparedStatement stmt = null;
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
           try
           {
               stmt = sm.getPreparedStatement(cld, sqlStatement,
  @@ -527,22 +464,38 @@
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of the update SQL query: "
+ sqlStatement;
  -            logger.error(msg, e);
  -            if (SQL_STATE_KEY_VIOLATED.equals(e.getSQLState()))
  +            ValueContainer[] tmp = addValues(values1, values2);
  +            throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger,
null);
  +        }
  +        finally
  +        {
  +            sm.closeResources(stmt, null);
  +        }
  +        return result;
  +    }
  +
  +    /** Helper method, returns the addition of both arrays (add source to target array)
*/
  +    private ValueContainer[] addValues(ValueContainer[] target, ValueContainer[] source)
  +    {
  +        ValueContainer[] newArray;
  +        if(source != null && source.length > 0)
  +        {
  +            if(target != null)
               {
  -                throw new KeyConstraintViolatedException(msg, e);
  +                newArray = new ValueContainer[target.length + source.length];
  +                System.arraycopy(target, 0, newArray, 0, target.length);
  +                System.arraycopy(source, 0, newArray, target.length, source.length);
               }
               else
               {
  -                throw new PersistenceBrokerSQLException(msg, e);
  +                newArray = source;
               }
           }
  -        finally
  +        else
           {
  -            sm.closeResources(stmt, null);
  +            newArray = target;
           }
  -        return result;
  +        return newArray;
       }
   
       /**
  @@ -557,21 +510,20 @@
               logger.debug("executeUpdate: " + obj);
           }
   
  -        PreparedStatement stmt = null;
  -
           // obj with nothing but key fields is not updated
           if (cld.getNonPkRwFields().length == 0)
           {
               return;
           }
   
  -        StatementManagerIF sm = broker.serviceStatementManager();
  +        final StatementManagerIF sm = broker.serviceStatementManager();
  +        PreparedStatement stmt = null;
           // BRJ: preserve current locking values
           // locking values will be restored in case of exception
           ValueContainer[] oldLockingValues;
           oldLockingValues = cld.getCurrentLockingValues(obj);
           try
  -        {           
  +        {
               stmt = sm.getUpdateStatement(cld);
               if (stmt == null)
               {
  @@ -612,21 +564,11 @@
           }
           catch (SQLException e)
           {
  -            // BRJ: restore old locking values
  -            setLockingValues(cld, obj, oldLockingValues);
  -            String msg = "SQLException during the execution of the update (for a "
  -                + cld.getClassOfObject().getName()
  -                + "): "
  -                + e.getMessage();
  -            logger.error(msg,e);
  -            if (SQL_STATE_KEY_VIOLATED.equals(e.getSQLState()))
  -            {
  -                throw new KeyConstraintViolatedException(msg, e);
  -            }
  -            throw new PersistenceBrokerSQLException(msg, e);
  +            final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();
  +            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
           }
           finally
  -        {           
  +        {
               sm.closeResources(stmt, null);
           }
       }
  @@ -644,13 +586,12 @@
           throws PersistenceBrokerException
       {
           final StatementManagerIF sm = broker.serviceStatementManager();
  -        SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);
  +        final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);
           ResultSetAndStatement rs_stmt = null;
  +        Object result = null;
           try
           {
  -            ResultSet rs;
  -            PreparedStatement stmt;
  -            stmt = sm.getSelectByPKStatement(cld);
  +            PreparedStatement stmt = sm.getSelectByPKStatement(cld);
               if (stmt == null)
               {
                   logger.error("getSelectByPKStatement returned a null statement");
  @@ -661,7 +602,8 @@
               thus we can always set 'false'. Is this correct??
               */
               sm.bindSelect(stmt, oid, cld, false);
  -            rs = stmt.executeQuery();
  +            ResultSet rs = stmt.executeQuery();
  +            // let OJB handle the resources
               rs_stmt = new ResultSetAndStatement(sm, stmt, rs, sql);
   
               // data available read object, else return null
  @@ -669,30 +611,24 @@
               {
                   Map row = new HashMap();
                   cld.getRowReader().readObjectArrayFrom(rs_stmt, row);
  -                return cld.getRowReader().readObjectFrom(row);
  -            }
  -            else
  -            {
  -                return null;
  +                result = cld.getRowReader().readObjectFrom(row);
               }
           }
           catch (PersistenceBrokerException e)
           {
  -            logger.error(
  -                "PersistenceBrokerException during the execution of materializeObject:
" + e.getMessage(), e);
  +            logger.error("PersistenceBrokerException during the execution of materializeObject:
" + e.getMessage(), e);
               throw e;
           }
           catch (SQLException e)
           {
  -            String msg = "SQLException during the execution of materializeObject (for a
"
  -                    + cld.getClassOfObject().getName() + "): " + e.getMessage();
  -            logger.error(msg,e);
  -            throw new PersistenceBrokerSQLException(msg, e);
  +            throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger,
null);
           }
           finally
           {
  +            // close all resources
               if(rs_stmt != null) rs_stmt.close();
           }
  +        return result;
       }
   
       /**
  @@ -704,16 +640,16 @@
       private void setLockingValues(ClassDescriptor cld, Object obj, ValueContainer[] oldLockingValues)
       {
           FieldDescriptor fields[] = cld.getLockingFields();
  -        
  +
           for (int i=0; i<fields.length; i++)
           {
               PersistentField field = fields[i].getPersistentField();
               Object lockVal = oldLockingValues[i].getValue();
  -            
  +
               field.set(obj, lockVal);
           }
       }
  -    
  +
       /**
        * Harvest any values that may have been returned during the execution
        * of a procedure.
  
  
  
  No                   revision
  No                   revision
  1.2.2.1   +20 -2     db-ojb/src/java/org/apache/ojb/broker/util/ExceptionHelper.java
  
  Index: ExceptionHelper.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/util/ExceptionHelper.java,v
  retrieving revision 1.2
  retrieving revision 1.2.2.1
  diff -u -r1.2 -r1.2.2.1
  --- ExceptionHelper.java	22 Oct 2005 12:20:15 -0000	1.2
  +++ ExceptionHelper.java	22 Oct 2005 12:21:41 -0000	1.2.2.1
  @@ -43,14 +43,32 @@
        * @param ex The exception to convert (mandatory).
        * @param sql The used sql-statement or <em>null</em>.
        * @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target
object or <em>null</em>.
  -     * @param values The values set in prepared statement or <em>null</em>.
  +     * @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed
message
  +     * to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em>
to skip logging message.
        * @param obj The target object or <em>null</em>.
  +     * @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException}
based on the specified
  +     *         arguments.
  +     */
  +    public static PersistenceBrokerSQLException generateException(SQLException ex,  String
sql, ClassDescriptor cld, Logger logger, Object obj)
  +    {
  +        return generateException(ex, sql, cld, null, logger, obj);
  +    }
  +
  +    /**
  +     * Method which support the conversion of {@link java.sql.SQLException} to
  +     * OJB's runtime exception (with additional message details).
  +     *
  +     * @param ex The exception to convert (mandatory).
  +     * @param sql The used sql-statement or <em>null</em>.
  +     * @param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor} of the target
object or <em>null</em>.
  +     * @param values The values set in prepared statement or <em>null</em>.
        * @param logger The {@link org.apache.ojb.broker.util.logging.Logger} to log an detailed
message
        * to the specified {@link org.apache.ojb.broker.util.logging.Logger} or <em>null</em>
to skip logging message.
  +     * @param obj The target object or <em>null</em>.
        * @return A new created {@link org.apache.ojb.broker.PersistenceBrokerSQLException}
based on the specified
        *         arguments.
        */
  -    public static PersistenceBrokerSQLException generateException(SQLException ex,  String
sql, ClassDescriptor cld, ValueContainer[] values, Object obj, Logger logger)
  +    public static PersistenceBrokerSQLException generateException(SQLException ex,  String
sql, ClassDescriptor cld, ValueContainer[] values, Logger logger, Object obj)
       {
           /*
           X/OPEN codes within class 23:
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: ojb-dev-unsubscribe@db.apache.org
For additional commands, e-mail: ojb-dev-help@db.apache.org


Mime
View raw message