/** * Convert the given SQLException into Hibernate's JDBCException hierarchy. * * @param sqlException The SQLException to be converted. * @param message An optional error message. * @param sql Optionally, the sql being performed when the exception occurred. * @return The resulting JDBCException; returns null if it could not be converted. */ @Override public JDBCException convert(SQLException sqlException, String message, String sql) { String sqlStateClassCode = JdbcExceptionHelper.extractSqlStateClassCode( sqlException ); if ( sqlStateClassCode != null ) { Integer errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); if ( INTEGRITY_VIOLATION_CATEGORIES.contains( errorCode ) ) { String constraintName = getConversionContext() .getViolatedConstraintNameExtracter() .extractConstraintName( sqlException ); return new ConstraintViolationException( message, sqlException, sql, constraintName ); } else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) { return new DataException( message, sqlException, sql ); } } return null; // allow other delegates the chance to look }
@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; } }; }
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new SQLExceptionConversionDelegate() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JDBCExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
@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; } }; }
@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); } }; }
/** * * get all results unpagified. * * @return List of accounts * @throws DataException */ public List<Account> findAll() throws DataException { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); final Criteria crit = session.createCriteria(Account.class); List<Account> accountList; try { accountList = crit.list(); session.flush(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); throw new HibernateException(e.getMessage()); } return accountList; }
/** * * get number of rows in the accounts table * * @return Long - number of rows * @throws DataException */ public Long getRowCount() throws DataException { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); final Criteria crit = session.createCriteria(Account.class); crit.setProjection(Projections.rowCount()); Long count; try { count = (Long) crit.uniqueResult(); session.flush(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); throw new HibernateException(e.getMessage()); } return count; }
/** * * get account data by userName, which is unique. * * @param username * @return Account * @throws DataException */ public Account findByUsername(String username) throws DataException { //validate input if (username == null) { throw new IllegalArgumentException(); } Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Criteria crit = session.createCriteria(Account.class); crit.add(Restrictions.eq("username", username)); Account account; try { account = (Account) crit.uniqueResult(); session.flush(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); throw new HibernateException(e.getMessage()); } return account; }
/** * * search account by a keyword which is then * compared to name and surname fields * * @param text * @return list of accounts * @throws DataException */ public List<Account> textSearch(String text) throws DataException { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Criteria crit = session.createCriteria(Account.class); Criterion name = Restrictions.like("name", text); Criterion surname = Restrictions.like("surname", text); LogicalExpression expression = Restrictions.or(name, surname); crit.add(expression); List<Account> accountList; try { accountList = crit.list(); session.flush(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); throw new HibernateException(e.getMessage()); } return accountList; }
/** * * update an existing generic object * * @param t type of object * @throws DataException */ public void delete(T t) throws DataException { if (t == null) { throw new IllegalArgumentException(); } Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.delete(t); session.flush(); session.getTransaction().commit(); } catch (Exception e) { session.getTransaction().rollback(); throw new HibernateException(e.getMessage()); } }
@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); }
@Test public void returnsDataExceptionForSqliteTooBigError() { when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(18); JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql"); assertTrue(exception instanceof DataException); assertEquals("message", exception.getMessage()); assertEquals("sql", exception.getSQL()); }
@Test public void returnsDataExceptionForSqliteMismatch() { when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(20); JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql"); assertTrue(exception instanceof DataException); assertEquals("message", exception.getMessage()); assertEquals("sql", exception.getSQL()); }
@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 }
@Override public Response toResponse(DataException e) { LOGGER.error("Hibernate error", e); String message = e.getCause().getMessage().contains("EMAIL") ? "Wrong email" : "Wrong input"; return Response.status(Response.Status.BAD_REQUEST) .entity(new ErrorMessage(Response.Status.BAD_REQUEST.getStatusCode(), message)) .build(); }
@Test public void itShouldThrowWhenRawTimeOverflows() { RunHibernateEntity entity = buildUnsavedRun(); entity.setRawTime(BigDecimal.valueOf(1000d)); try { daoTestRule.inTransaction(() -> dao.create(entity)); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (Exception e) { assertThat(e) .isInstanceOf(PersistenceException.class) .hasCauseInstanceOf(DataException.class); } }
@RequestMapping(value = "/") public ModelAndView listAll() { logger.debug("Homepage requested"); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("home"); // add sample data List<Account> accountList = new ArrayList<Account>(); accountList.add(new Account("gurarslan", "Omer", "Gurarslan", "111-222-33-34")); try { for (Account newAccount : accountList) { if (ServiceDispatcher.getAccountService() .getAccountByUsername(newAccount.getUsername()) .getAccount() == null) { ServiceDispatcher.getAccountService().insert(newAccount); } } } catch (DataException e) { logger.debug(e.getMessage()); } ResponseAccountList resultList = accountService .getAllAccountsPagified(0); modelAndView.addObject("accountList", resultList.getAccountList()); modelAndView.addObject("rowCount", resultList.getRowCount()); return modelAndView; }
/** * Adapt the external css. */ private void adaptExternalCss() { for (Element el : externalCssElements) { List<CSSMediaQuery> mediaList = getListOfMediaFromAttributeValue(el); String resourcePath = el.attr("abs:href"); getExternalResourceAndAdapt(resourcePath, mediaList); } Set<Long> relatedCssIdSet = new HashSet<>(); // At the end of the document we link each external css that are // already fetched and that have been encountered in the SSP to the SSP. LOGGER.debug("Found " + relatedExternalCssSet.size() + " external css in "+ getSSP().getURI()); for (StylesheetContent cssContent : relatedExternalCssSet) { if (cssContent.getAdaptedContent() == null) { cssContent.setAdaptedContent(CSS_ON_ERROR); } LOGGER.debug("Create relation between "+getSSP().getURI() + " and " + cssContent.getURI()); // to avoid fatal error when persist weird sourceCode try { // the content is saved only when the id is null which means // that the content hasn't been persisted yet. Otherwise, the // save is uneeded and the id is used to create the relation // with the current SSP if (cssContent.getId() == null) { cssContent = (StylesheetContent)getContentDataService().saveOrUpdate(cssContent); } relatedCssIdSet.add(cssContent.getId()); } catch (PersistenceException | DataException pe) { adaptedContentOnError(cssContent, relatedCssIdSet); } } getContentDataService().saveContentRelationShip(getSSP(), relatedCssIdSet); }
@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; }