Java 类org.hibernate.exception.JDBCConnectionException 实例源码

项目:convertigo-engine    文件:HibernateHelper.java   
public void retry(Runnable run) {
    for (long retry = this.retry; retry > 0; retry--) {
        try {
            run.run();
            retry = -1;
        } catch (JDBCConnectionException e) {
            clearSessionFactory();
            if (retry > 0) {                            
                log.debug("(SecurityTokenManager) JDBCConnectionException for removeExpired, retry left: " + retry);
                ThreadUtils.sleep(200);
            } else {
                log.warn("(SecurityTokenManager) JDBCConnectionException for removeExpired, no more retry", e);
            }                   
        }
    }
}
项目:vsDiaryWriter    文件:SQLiteDialect.java   
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
    return new SQLExceptionConversionDelegate() {
        @Override
        public JDBCException convert(SQLException sqlException, String message, String sql) {
            final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
            if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
                return new DataException(message, sqlException, sql);
            } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
                return new LockAcquisitionException(message, sqlException, sql);
            } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
                return new JDBCConnectionException(message, sqlException, sql);
            }

            // returning null allows other delegates to operate
            return null;
        }
    };
}
项目:spletne-seje    文件:SQLiteDialect.java   
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
    return new SQLExceptionConversionDelegate() {
        @Override
        public JDBCException convert(SQLException sqlException, String message, String sql) {
            final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
            if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
                return new DataException(message, sqlException, sql);
            } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
                return new LockAcquisitionException(message, sqlException, sql);
            } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
                return new JDBCConnectionException(message, sqlException, sql);
            }
            return null;
        }
    };
}
项目:yawl    文件:HibernateEngine.java   
public List execQuery(String queryString) {
   List result = null;
   Transaction tx = null;
   try {
       Session session = _factory.getCurrentSession();
       tx = session.beginTransaction();
       Query query = session.createQuery(queryString);
       if (query != null) result = query.list();
   }
   catch (JDBCConnectionException jce) {
       _log.error("Caught Exception: Couldn't connect to datasource - " +
               "starting with an empty dataset");
   }
   catch (HibernateException he) {
       _log.error("Caught Exception: Error executing query: " + queryString, he);
       if (tx != null) tx.rollback();
   }

   return result;
}
项目:yawl    文件:HibernateEngine.java   
/**
 * executes a Query object based on the hql string passed
 * @param queryString - the hibernate query to execute
 * @return the List of objects returned, or null if the query has some problem
 */
public List execQuery(String queryString) {
    List result = null;
    Transaction tx = null;
    try {
        tx = getOrBeginTransaction();
        Query query = getSession().createQuery(queryString);
        if (query != null) result = query.list();
    }
    catch (JDBCConnectionException jce) {
        _log.error("Caught Exception: Couldn't connect to datasource - " +
                "continuing with an empty dataset");
        if (tx != null) tx.rollback();
    }
    catch (HibernateException he) {
        _log.error("Caught Exception: Error executing query: " + queryString, he);
        if (tx != null) tx.rollback();
    }

    return result;
}
项目:yawl    文件:HibernateEngine.java   
/**
 * executes a plain SQL Query
 * @param queryString - the SQL query to execute
 * @return the List of objects returned, or null if the query has some problem
 */
public List execSQLQuery(String queryString) {
    List result = null;
    Transaction tx = null;
    try {
        tx = getOrBeginTransaction();
        Query query = getSession().createSQLQuery(queryString);
        if (query != null) result = query.list();
        commit();
    }
    catch (JDBCConnectionException jce) {
        _log.error("Caught Exception: Couldn't connect to datasource - " +
                "starting with an empty dataset");
        if (tx != null) tx.rollback();
    }
    catch (HibernateException he) {
        _log.error("Caught Exception: Error executing query: " + queryString, he);
        rollback();
    }

    return result;
}
项目:yawl    文件:HibernateEngine.java   
public int execUpdate(String queryString, boolean commit) {
    int result = -1;
    Transaction tx = null;
    try {
        tx = getOrBeginTransaction();
        result = getSession().createQuery(queryString).executeUpdate();
        if (commit) commit();
    }
    catch (JDBCConnectionException jce) {
        _log.error("Caught Exception: Couldn't connect to datasource - " +
                "starting with an empty dataset");
    }
    catch (HibernateException he) {
        _log.error("Caught Exception: Error executing query: " + queryString, he);
        if (tx != null) tx.rollback();
    }

    return result;
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
public void execute(TransactionalOperation operation) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            operation.execute(dbSession);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar executar operação transacional apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
@Override
public void persist(Serializable entity) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            dbSession.persist(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar salvar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
@Override
public Serializable save(Serializable entity) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            Serializable id = dbSession.save(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return id;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar salvar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
@Override
public void update(Serializable entity) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            dbSession.update(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar atualizar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
@Override
public void delete(Serializable entity) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            dbSession.delete(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar deletar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:HibernateDAO.java   
@Override
public int bulkUpdate(String sqlStatement) {
    JDBCConnectionException last = null;
    Transaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        Session dbSession = this.getSession();
        try {
            tx = dbSession.beginTransaction();
            SQLQuery query = dbSession.createSQLQuery(sqlStatement);
            int affected = query.executeUpdate();
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return affected;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar atualizar entidade em massa apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:JPADAO.java   
public void execute(TransactionalOperation operation) {
    JDBCConnectionException last = null;
    EntityTransaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        EntityManager dbSession = this.getSession();
        try {
            tx = dbSession.getTransaction();
            operation.execute(dbSession);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar executar operação transacional apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:JPADAO.java   
@Override
public void persist(Serializable entity) {
    JDBCConnectionException last = null;
    EntityTransaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        EntityManager dbSession = this.getSession();
        try {
            tx = dbSession.getTransaction();
            dbSession.persist(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar salvar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:JPADAO.java   
@Override
public void update(Serializable entity) {
    JDBCConnectionException last = null;
    EntityTransaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        EntityManager dbSession = this.getSession();
        try {
            tx = dbSession.getTransaction();
            dbSession.merge(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar atualizar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:JPADAO.java   
@Override
public void delete(Serializable entity) {
    JDBCConnectionException last = null;
    EntityTransaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        EntityManager dbSession = this.getSession();
        try {
            tx = dbSession.getTransaction();
            dbSession.remove(entity);
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar deletar entidade: "+entity.getClass().getCanonicalName()+" apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:vraptor-boilerplate    文件:JPADAO.java   
@Override
public int bulkUpdate(String sqlStatement) {
    JDBCConnectionException last = null;
    EntityTransaction tx = null;
    for (int retry = 0; retry < TRANSACTIONS_MAX_RETRIES; retry++) {
        EntityManager dbSession = this.getSession();
        try {
            tx = dbSession.getTransaction();
            Query query = dbSession.createNativeQuery(sqlStatement);
            int affected = query.executeUpdate();
            tx.commit();
            if (retry > 0)
                LOG.warn("Transacao realizada apos "+String.valueOf(retry+1)+" tentativas.");
            return affected;
        } catch (JDBCConnectionException ex) {
            last = ex;
            if (tx != null)
                tx.rollback();
            tx = null;
            this.closeSession();
        }
    }
    LOG.error("Erro ao tentar atualizar entidade em massa apos "+
            String.valueOf(TRANSACTIONS_MAX_RETRIES)+" tentativas.", last);
    throw new RuntimeException("Erro no banco de dados.", last);
}
项目:Introspect-Framework    文件:SQLiteDialect.java   
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
  return new SQLExceptionConversionDelegate() {
    @Override
    public JDBCException convert(SQLException sqlException, String message, String sql) {
      final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
      if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
        return new DataException(message, sqlException, sql);
      } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
        return new LockAcquisitionException(message, sqlException, sql);
      } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
        return new JDBCConnectionException(message, sqlException, sql);
      }

      // returning null allows other delegates to operate
      return null;
    }
  };
}
项目:fiware-rss    文件:FactoryResponse.java   
/**
 * Generate an exception related to get a DB connection.
 * 
 * @param e
 *            exception
 * @param txId
 * @param resource
 * @return
 */
public static Response catchConnectionJDBCJson(UriInfo ui, JDBCConnectionException e,
    String resource, String txId) {
    // ALARM DETECTED
    FactoryResponse.logger.error(Constants.LOG_ALARM + " Problems connecting to the database: {}", resource);

    // Write response
    String[] args = {"Problems connecting to the database: " + resource};
    RSSException newException = new RSSException(UNICAExceptionType.GENERIC_SERVER_FAULT, args, e, txId, null);
    FactoryResponse.logger.error("Return GRETAException: [" + newException.getExceptionType().getExceptionId()
        + "] "
        + newException.getMessage(), e);
    ExceptionTypeBean exceptObj = FactoryResponse.exceptionJson(ui,
        newException, resource);
    return FactoryResponse.createResponseError(newException, exceptObj);
}
项目:fiware-rss    文件:FactoryResponse.java   
/**
 * Generate an exception related to get a DB connection.
 * 
 * @param e
 *            exception
 * @param txId
 * @param resource
 * @return
 */
public static Response catchConnectionJDBCJson(UriInfo ui, JDBCConnectionException e,
    String resource, String txId) {
    // ALARM DETECTED
    FactoryResponse.logger.error(Constants.LOG_ALARM + " Problems connecting to the database: {}", resource);

    // Write response
    String[] args = {"Problems connecting to the database: " + resource};
    RSSException newException = new RSSException(UNICAExceptionType.GENERIC_SERVER_FAULT, args, e, txId, null);
    FactoryResponse.logger.error("Return GRETAException: [" + newException.getExceptionType().getExceptionId()
        + "] "
        + newException.getMessage(), e);
    ExceptionTypeBean exceptObj = FactoryResponse.exceptionJson(ui,
        newException, resource);
    return FactoryResponse.createResponseError(newException, exceptObj);
}
项目:yeti    文件:SQLiteDialect.java   
@Override
public SQLExceptionConverter buildSQLExceptionConverter() {
    return new SQLExceptionConverter() {
        @Override
        public JDBCException convert(SQLException sqlException, String message, String sql) {
            final int errorCode = sqlException.getErrorCode();
            if (errorCode == SQLITE_CONSTRAINT) {
                final String constraintName = EXTRACTER.extractConstraintName(sqlException);
                return new ConstraintViolationException(message, sqlException, sql, constraintName);
            } else if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
                return new DataException(message, sqlException, sql);
            } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
                return new LockAcquisitionException(message, sqlException, sql);
            } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
                return new JDBCConnectionException(message, sqlException, sql);
            }
            return new GenericJDBCException(message, sqlException, sql);
        }
    };
}
项目:sqlite-dialect    文件:SQLiteSQLExceptionConversionDelegate.java   
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
    if (errorCode == SQLITE_CONSTRAINT) {
        final String constraintName = EXTRACTER.extractConstraintName(sqlException);
        return new ConstraintViolationException(message, sqlException, sql, constraintName);
    } else if (errorCode == SQLITE_TOO_BIG || errorCode == SQLITE_MISMATCH) {
        return new DataException(message, sqlException, sql);
    } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
        return new LockAcquisitionException(message, sqlException, sql);
    } else if ((errorCode >= SQLITE_IO_ERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOT_ADB) {
        return new JDBCConnectionException(message, sqlException, sql);
    }
    return new GenericJDBCException(message, sqlException, sql);
}
项目:sqlite-dialect    文件:SQLiteSQLExceptionConversionDelegateTest.java   
@Test
public void returnsJDBCConnectionExceptionForSqliteCorrupt() {
    when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(11);

    JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql");
    assertTrue(exception instanceof JDBCConnectionException);
    assertEquals("message", exception.getMessage());
    assertEquals("sql", exception.getSQL());
}
项目:sqlite-dialect    文件:SQLiteSQLExceptionConversionDelegateTest.java   
@Test
public void returnsJDBCConnectionExceptionForSqliteNotAbd() {
    when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(26);

    JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql");
    assertTrue(exception instanceof JDBCConnectionException);
    assertEquals("message", exception.getMessage());
    assertEquals("sql", exception.getSQL());
}
项目:lams    文件:SQLExceptionTypeDelegate.java   
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    if ( SQLClientInfoException.class.isInstance( sqlException )
            || SQLInvalidAuthorizationSpecException.class.isInstance( sqlException )
            || SQLNonTransientConnectionException.class.isInstance( sqlException )
            || SQLTransientConnectionException.class.isInstance( sqlException ) ) {
        return new JDBCConnectionException( message, sqlException, sql );
    }
    else if ( DataTruncation.class.isInstance( sqlException ) ||
            SQLDataException.class.isInstance( sqlException ) ) {
        throw new DataException( message, sqlException, sql );
    }
    else if ( SQLIntegrityConstraintViolationException.class.isInstance( sqlException ) ) {
        return new ConstraintViolationException(
                message,
                sqlException,
                sql,
                getConversionContext().getViolatedConstraintNameExtracter().extractConstraintName( sqlException )
        );
    }
    else if ( SQLSyntaxErrorException.class.isInstance( sqlException ) ) {
        return new SQLGrammarException( message, sqlException, sql );
    }
    else if ( SQLTimeoutException.class.isInstance( sqlException ) ) {
        return new QueryTimeoutException( message, sqlException, sql );
    }
    else if ( SQLTransactionRollbackException.class.isInstance( sqlException ) ) {
        // Not 100% sure this is completely accurate.  The JavaDocs for SQLTransactionRollbackException state that
        // it indicates sql states starting with '40' and that those usually indicate that:
        //      <quote>
        //          the current statement was automatically rolled back by the database because of deadlock or
        //          other transaction serialization failures.
        //      </quote>
        return new LockAcquisitionException( message, sqlException, sql );
    }

    return null; // allow other delegates the chance to look
}
项目:angular-spring-boot-micro-services-docker    文件:GlobalExceptionHandler.java   
@ResponseBody
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler({ SQLException.class, DataAccessException.class, DataAccessResourceFailureException.class, JDBCConnectionException.class})
public Map<String,Object> dbError(Exception exception,HttpServletResponse response,HttpServletRequest request) throws IOException
{
    Map<String,Object> m = new HashMap<>();

    m.put("errorId",Long.valueOf(201));
    m.put("state",HttpStatus.SERVICE_UNAVAILABLE.value());
    m.put("url", request.getRequestURL().toString());
    m.put("message", exception.getMessage());
    m.put("devMessage", "db server connection error");
    m.put("time", new Date().toString());
    return m;
}
项目:mad-java    文件:HibernateExceptionHandler.java   
public static void rethrowAsDatastoreLogAll( final HibernateException he, final Log log, final String message )
        throws DatastoreException
{
    final String internalMess = concMess( message, he );
    if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException
            || he instanceof SQLGrammarException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof ConstraintViolationException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof LockAcquisitionException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof QuerySyntaxException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof QueryException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
}
项目:mad-java    文件:HibernateExceptionHandler.java   
public static void rethrowJdbcAsDatastore( final HibernateException he, final Log log, final String message, final int logErrorMask ) // NOPMD by dan on 01/02/15 07:21
        throws DatastoreException
{
    final String internalMess = concMess( message, he );
    if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException
            || he instanceof SQLGrammarException)
    {
        if ((logErrorMask & JDBC_IS_ERROR) != 0)
        {
            log.error( internalMess, he );
        }
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof ConstraintViolationException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof LockAcquisitionException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof QuerySyntaxException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
}
项目:appengine-hibernate    文件:CloudSqlFilter.java   
private boolean isDatabaseProblem(Throwable e) {
    if(e instanceof PersistenceException) {
        return e instanceof javax.persistence.QueryTimeoutException ||
                isDatabaseProblem(e.getCause());
    }
    return e instanceof QueryTimeoutException ||
            e instanceof JDBCConnectionException;
}
项目:java-retry    文件:HibernateTransientExceptionDetector.java   
@Override
public boolean isTransient(Exception e) {
    if (e instanceof LockAcquisitionException || e instanceof PessimisticLockException || e instanceof JDBCConnectionException) {
        return true;
    }
    if (e instanceof GenericJDBCException) {
        JDBCException se = (JDBCException) e;
        return super.isTransient(se.getSQLException());
    }
    return false;
}
项目:fiware-rss    文件:JsonExceptionMapper.java   
/**
 * 
 */
@Override
public Response toResponse(Exception e) {

    if (e instanceof RSSException) {
        logger.error("Return GRETAException: [" + ((RSSException) e).getExceptionType().getExceptionId()
            + "] " + e.getMessage(), e);
        ExceptionTypeBean exceptObj = FactoryResponse.exceptionJson(uriInfo,
            ((RSSException) e), uriInfo.getAbsolutePath().getPath());
        return FactoryResponse.createResponseError(((RSSException) e), exceptObj);
    } else if (e instanceof GenericJDBCException) {
        return FactoryResponse.catchNewConnectionJson(uriInfo, (GenericJDBCException) e,
            uriInfo.getAbsolutePath().getPath(), null);
    } else if (e instanceof JDBCConnectionException) {
        return FactoryResponse.catchConnectionJDBCJson(uriInfo, (JDBCConnectionException) e,
            uriInfo.getAbsolutePath().getPath(), null);
    } else if (e instanceof NotFoundException) {
        return Response.status(404).build();
    } else {
        logger.error("Return Exception: " + e.getMessage(), e);

        // Write response
        if (e.getCause() instanceof GenericJDBCException) {
            return FactoryResponse.catchNewConnectionJson(uriInfo,
                (GenericJDBCException) e.getCause(),
                uriInfo.getAbsolutePath().getPath(), null);
        } else if (e.getCause() instanceof JDBCConnectionException) {
            return FactoryResponse.catchConnectionJDBCJson(uriInfo,
                (JDBCConnectionException) e.getCause(),
                uriInfo.getAbsolutePath().getPath(), null);
        } else {
            logger.error("Return Exception: " + e.getMessage(), e);

            // Write response
            return FactoryResponse.createResponseErrorJson(uriInfo,
                FactoryResponse.createErrorMsg(e), uriInfo.getAbsolutePath().getPath());
        }
    }
}
项目:fiware-rss    文件:JsonExceptionMapperTest.java   
@Test
public void toResponse() throws Exception {
    UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
    Mockito.when(mockUriInfo.getAbsolutePath()).thenReturn(new URI("http://www.test.com/go"));
    ReflectionTestUtils.setField(mapper, "uriInfo", mockUriInfo);

    RSSException e = new RSSException("RssException");
    Response response = mapper.toResponse(e);
    Assert.assertTrue(true);

    GenericJDBCException ex = new GenericJDBCException("sql", new SQLException("reason"));
    response = mapper.toResponse(ex);
    Assert.assertTrue(true);

    JDBCConnectionException ex1 = new JDBCConnectionException("sql", new SQLException("reason"));
    response = mapper.toResponse(ex1);
    Assert.assertTrue(true);

    NotFoundException ex2 = new NotFoundException();
    response = mapper.toResponse(ex2);
    Assert.assertTrue(true);

    Exception ex3 = new Exception("RssException");
    response = mapper.toResponse(ex3);
    Assert.assertTrue(true);

    Exception ex4 = new Exception("RssException", ex);
    response = mapper.toResponse(ex4);
    Assert.assertTrue(true);

    Exception ex5 = new Exception("RssException", ex1);
    response = mapper.toResponse(ex5);
    Assert.assertTrue(true);

}
项目:fiware-rss    文件:FactoryResponseTest.java   
/**
 * 
 */
@Test
public void catchConnectionJDBCJson() throws Exception {
    UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
    Mockito.when(mockUriInfo.getBaseUri()).thenReturn(new URI("http://www.test.com/go"));
    JDBCConnectionException exception = new JDBCConnectionException("sql", new SQLException("reason"));
    Response bean = FactoryResponse.catchConnectionJDBCJson(mockUriInfo,
        exception, "resource", "txId");
    Assert.assertTrue(true);
}
项目:fiware-rss    文件:FactoryResponseTest.java   
/**
 * 
 */
@Test
public void catchConnectionJDBCJson() throws Exception {
    UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
    Mockito.when(mockUriInfo.getBaseUri()).thenReturn(new URI("http://www.test.com/go"));
    JDBCConnectionException exception = new JDBCConnectionException("sql", new SQLException("reason"));
    Response bean = FactoryResponse.catchConnectionJDBCJson(mockUriInfo,
        exception, "resource", "txId");
    Assert.assertTrue(true);
}
项目:fiware-rss    文件:ExpenditureLimitExceptionMapperTest.java   
public void toResponse() throws Exception {
    UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
    Mockito.when(mockUriInfo.getAbsolutePath()).thenReturn(new URI("http://www.test.com/go"));
    ReflectionTestUtils.setField(mapper, "ui", mockUriInfo);

    RSSException e = new RSSException("RssException");
    Response response = mapper.toResponse(e);
    Assert.assertTrue(true);

    GenericJDBCException ex = new GenericJDBCException("sql", new SQLException("reason"));
    response = mapper.toResponse(ex);
    Assert.assertTrue(true);

    JDBCConnectionException ex1 = new JDBCConnectionException("sql", new SQLException("reason"));
    response = mapper.toResponse(ex1);
    Assert.assertTrue(true);

    NotFoundException ex2 = new NotFoundException();
    response = mapper.toResponse(ex2);
    Assert.assertTrue(true);

    Exception ex3 = new Exception("RssException");
    response = mapper.toResponse(ex3);
    Assert.assertTrue(true);

    Exception ex4 = new Exception("RssException", ex);
    response = mapper.toResponse(ex4);
    Assert.assertTrue(true);

    Exception ex5 = new Exception("RssException", ex1);
    response = mapper.toResponse(ex5);
    Assert.assertTrue(true);

}
项目:convertigo-engine    文件:BillingManager.java   
public void init() throws EngineException {
    customer_name = Engine.isCloudMode() ? Engine.cloud_customer_name : (Engine.isStudioMode() ? "CONVERTIGO Studio" : "CONVERTIGO Server");
    Engine.theApp.eventManager.addListener(this, PropertyChangeEventListener.class);
    if (EnginePropertiesManager.getPropertyAsBoolean(PropertyName.ANALYTICS_PERSISTENCE_ENABLED) ||
        EnginePropertiesManager.getPropertyAsBoolean(PropertyName.ANALYTICS_GOOGLE_ENABLED)) {
        isDestroying = false;
        tickets = new LinkedList<Ticket>();
        consumer = new Thread(new Runnable() {
            public void run() {
                while (!isDestroying && consumer == Thread.currentThread()) {
                    Ticket ticket = null;
                    try {
                        synchronized (tickets) {
                            if (tickets.isEmpty()) {
                                tickets.wait();
                            } else {
                                Iterator<Ticket> iTicketData = tickets.iterator();
                                ticket = iTicketData.next();
                                iTicketData.remove();
                            }
                        }
                        if (ticket != null) {
                            for (ITicketManager manager: managers) {
                                manager.addTicket(ticket);
                            }
                        }
                    } catch (JDBCConnectionException e) {
                        Throwable cause = e.getCause();
                        Engine.logBillers.info("JDBCConnectionException on ticket insertion" + (cause == null ? "" : " (cause by " + cause.getClass().getSimpleName() + ")") + ": " + ticket);
                    } catch (Exception e) {
                        Engine.logBillers.error("Something failed in ticket insertion : " + ticket, e);
                    }
                }
            }
        });

        renewManager(false);
        consumer.setName("BillingManager consumer");
        consumer.setDaemon(true);
        consumer.start();
    }
}
项目:lams    文件:SQLStateConversionDelegate.java   
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
    final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );

    if ( sqlState != null ) {
        String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode( sqlState );

        if ( sqlStateClassCode != null ) {
            if ( SQL_GRAMMAR_CATEGORIES.contains( sqlStateClassCode ) ) {
                return new SQLGrammarException( message, sqlException, sql );
            }
            else if ( INTEGRITY_VIOLATION_CATEGORIES.contains( sqlStateClassCode ) ) {
                final String constraintName = getConversionContext()
                        .getViolatedConstraintNameExtracter()
                        .extractConstraintName( sqlException );
                return new ConstraintViolationException( message, sqlException, sql, constraintName );
            }
            else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
                return new JDBCConnectionException( message, sqlException, sql );
            }
            else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
                return new DataException( message, sqlException, sql );
            }
        }

        if ( "40001".equals( sqlState ) ) {
            return new LockAcquisitionException( message, sqlException, sql );
        }

        if ( "40XL1".equals( sqlState ) || "40XL2".equals( sqlState )) {
            // Derby "A lock could not be obtained within the time requested."
            return new PessimisticLockException( message, sqlException, sql );
        }

        // MySQL Query execution was interrupted
        if ( "70100".equals( sqlState ) ||
                // Oracle user requested cancel of current operation
                ( "72000".equals( sqlState ) && errorCode == 1013 ) ) {
            throw new QueryTimeoutException(  message, sqlException, sql );
        }
    }

    return null;
}
项目:mad-java    文件:HibernateExceptionHandler.java   
public static void rethrowJdbcAsDatastoreAndConstraintAsItself( final HibernateException he, final Log log, final String message,
        final int logErrorMask ) throws DatastoreException, MAConstraintViolationException
{
    final String internalMess = concMess( message, he );
    if (he instanceof JDBCConnectionException || he instanceof GenericJDBCException
            || he instanceof SQLGrammarException)
    {
        if ((logErrorMask & JDBC_IS_ERROR) != 0)
        {
            log.error( internalMess, he );
        }
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof ConstraintViolationException)
    {
        if ((logErrorMask & CONSTRAINT_IS_ERROR) != 0)
        {
            log.error( internalMess, he );
        }
        throw new MAConstraintViolationException( internalMess, he );
    }
    else if (he instanceof LockAcquisitionException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof QuerySyntaxException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof IdentifierGenerationException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else if (he instanceof PropertyValueException)
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
    else
    {
        log.error( internalMess, he );
        throw new DatastoreException( internalMess, he );
    }
}
项目:uimaster    文件:HibernateUtil2.java   
public static Session getSession() {
    if (sessionFactoryTL.get() != null) {
        return sessionFactoryTL.get();
    }

    /*
     * getCurrentSession() creates the session and bound to the current thread. OpenSession() won't.
     * getCurrentSession()'s session will be closed after either doing 'commit' or 'rollback'. OpenSession() won't.
     */
    Session session = HibernateUtil2.getSessionFactory().getCurrentSession();
    try {
        // hibernate transaction is thread bound or thread safe.
        // we must to promise the transaction being 'commit' or 'rollback' in the same thread where begins.
        if (session.getTransaction() == null || !session.getTransaction().isActive()) {
            session.beginTransaction();
        }
    } catch (TransactionException e) {
        logger.warn("Hibernate TransactionException error: " + e.getMessage());
        logger.warn("Hibernate Session Info: collections-{},entities-{},transaction-{}", 
                new Object[] { session.getStatistics().getCollectionCount(), 
                                session.getStatistics().getEntityCount(),
                                session.getTransaction().getLocalStatus()});
        try {
            session.getTransaction().rollback();
        } catch (Exception e0) {}
        // break transaction before rebuild.
        session = HibernateUtil2.getSessionFactory().getCurrentSession();
        session.beginTransaction();
    } catch (JDBCConnectionException e1) {
        // unable to resolve the re-connect DB problem. rebuild session here!
        //IServerServiceManager.INSTANCE.setHibernateSessionFactory(buildSessionFactory());
        sessionFactoryTL.set(null);
        throw e1;
    }

    sessionFactoryTL.set(session);
    if (logger.isDebugEnabled()) {
        logger.debug("Start Hibernate Transaction: collections-{},entities-{}", 
                new Object[] { session.getStatistics().getCollectionCount(), 
                                session.getStatistics().getEntityCount()});
    }
    return session;
}