@Test public void testFallbackExceptionTranslation() throws HibernateException { SQLException sqlEx = new SQLException("argh", "27"); final GenericJDBCException gjex = new GenericJDBCException("mymsg", sqlEx); try { hibernateTemplate.execute(new HibernateCallback<Object>() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw gjex; } }); fail("Should have thrown DataIntegrityViolationException"); } catch (DataIntegrityViolationException ex) { // expected assertEquals(sqlEx, ex.getCause()); assertTrue(ex.getMessage().indexOf("mymsg") != -1); } }
/** * Run query. * * @param <T> * the generic type * @param query * the query * @param type * the type * @return the vector */ @SuppressWarnings("unchecked") <T> Vector<T> runQuery(final Query query, final Class<T> type) { HibernateHelper.logger.debug("runSQL: " + query); // TODO create prepared statements Vector<?> returnVal = null; try { returnVal = new Vector<T>(query.list()); } catch (final GenericJDBCException dbe) { throw dbe; } catch (final HibernateException e) { HibernateHelper.logger.error("Error fetching " + NewsGroup.class.getName(), e); } if (null == returnVal) { returnVal = new Vector<>(); } return (Vector<T>) returnVal; }
/** * Generate an exception related to create a new DB connection. * * @param e * exception * @param txId * @param resource * @return */ public static Response catchNewConnectionJson(UriInfo ui, GenericJDBCException e, String resource, String txId) { // ALARM DETECTED FactoryResponse.logger.error(Constants.LOG_ALARM + " Cannot open connection with the database"); // Write response String[] args = {"Cannot open connection with the database"}; 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); }
/** * Generate an exception related to create a new DB connection. * * @param e * exception * @param txId * @param resource * @return */ public static Response catchNewConnectionJson(UriInfo ui, GenericJDBCException e, String resource, String txId) { // ALARM DETECTED FactoryResponse.logger.error(Constants.LOG_ALARM + " Cannot open connection with the database"); // Write response String[] args = {"Cannot open connection with the database"}; 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); }
@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); } }; }
@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 returnsGenericJDBCExceptionForEverythingElse() { when(JdbcExceptionHelper.extractErrorCode(sqlException)).thenReturn(41); JDBCException exception = conversionDelegate.convert(sqlException, "message", "sql"); assertTrue(exception instanceof GenericJDBCException); assertEquals("message", exception.getMessage()); assertEquals("sql", exception.getSQL()); }
@Override protected int determineRowCount(int reportedRowCount, PreparedStatement statement) { try { return toCallableStatement( statement ).getInt( parameterPosition ); } catch( SQLException sqle ) { sqlExceptionHelper.logExceptions( sqle, "could not extract row counts from CallableStatement" ); throw new GenericJDBCException( "could not extract row counts from CallableStatement", sqle ); } }
/** * Builds a minimal converter. The instance returned here just always converts to * {@link org.hibernate.exception.GenericJDBCException}. * * @return The minimal converter. */ public static SQLExceptionConverter buildMinimalSQLExceptionConverter() { return new SQLExceptionConverter() { public JDBCException convert(SQLException sqlException, String message, String sql) { return new GenericJDBCException( message, sqlException, sql ); } }; }
@Override public JDBCException convert(SQLException sqlException, String message, String sql) { for ( SQLExceptionConversionDelegate delegate : delegates ) { final JDBCException jdbcException = delegate.convert( sqlException, message, sql ); if ( jdbcException != null ) { return jdbcException; } } return new GenericJDBCException( message, sqlException, sql ); }
protected DataAccessException convertHibernateAccessException(HibernateException ex) { if (ex instanceof JDBCException) { return convertJdbcAccessException((JDBCException) ex, jdbcExceptionTranslator); } if (GenericJDBCException.class.equals(ex.getClass())) { return convertJdbcAccessException((GenericJDBCException) ex, jdbcExceptionTranslator); } return SessionFactoryUtils.convertHibernateAccessException(ex); }
protected int determineRowCount(int reportedRowCount, PreparedStatement statement) { try { return toCallableStatement( statement ).getInt( parameterPosition ); } catch( SQLException sqle ) { JDBCExceptionReporter.logExceptions( sqle, "could not extract row counts from CallableStatement" ); throw new GenericJDBCException( "could not extract row counts from CallableStatement", sqle ); } }
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 ); } }
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 ); } }
/** {@inheritDoc} */ @Override public boolean deleteByRecordId(String recId) throws ServiceException { if (StringUtils.isEmpty(recId)) { throw new IllegalArgumentException("Array FixedSystemCost must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; boolean isDeleted = Boolean.FALSE; try { tx = session.beginTransaction(); String sql = " DELETE FROM FixedSystemCost a WHERE a.recID = :recID"; Query query = fixedSystemCostRepository.getQuery(session, sql).setParameter("recID", recId); // isDeleted = query.executeUpdate() > 0; // Release transaction tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An error occurred while delete FixedSystemCost list"); } finally { HibernateSessionManager.closeSession(session); } return isDeleted; }
/** {@inheritDoc} */ @Override public boolean checkAvailableByOrgCodeAndMonthly(String orgCode, String monthly) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Can not check budget performance available with oraganization code empty"); } if (StringUtils.isEmpty(monthly)) { throw new IllegalArgumentException("Can not check budget performance available with current month in action empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; boolean isAvailable = Boolean.FALSE; try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder(" SELECT COUNT(YosanKingaku) + COUNT(JisekiKingaku) "); sql.append(" FROM " + TblConstants.TBL_BUDGET_PERFORMANCE); sql.append(" WHERE StrCode=:orgCode AND GetSudo=:monthly "); Query query = repository.getSQLQuery(session, sql.toString()); query.setString("orgCode", orgCode); query.setString("monthly", monthly); Object count = query.uniqueResult(); isAvailable = Double.valueOf(count.toString()) > 0; tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while get budget performance data by organization code " + orgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return isAvailable; }
/** {@inheritDoc} */ @Override public double findStampedLackingByOrgCodeAndBusinessDay(String orgCode, Date businessDay) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Organization's code must not be null or empty"); } if (businessDay == null) { throw new IllegalArgumentException("Business day must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; double isStamped = 0; try { tx = session.beginTransaction(); String hql = "SELECT at021.Ninzu FROM at021 WHERE at021.StrCode = :StrCode " + " AND at021.SrDate = (SELECT at051.EigDateY FROM at051 WHERE at051.EigDate = :EigDate)" + " AND at021.DelKbn = 2 "; Query query = repository.getSQLQuery(session, hql); query.setString("StrCode", orgCode); query.setDate("EigDate", businessDay); Object result = query.uniqueResult(); if (result != null) { isStamped = Double.parseDouble(result.toString()); } tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An error occurred when getting all the number of stamped lacking " + "for the organization's code " + orgCode + " of day " + businessDay, ex); } finally { HibernateSessionManager.closeSession(session); } return isStamped; }
/** {@inheritDoc}*/ @Override public List<VJiseki> findByOrgCodeAndMonthies(String orgCode, String... monthlies) throws ServiceException { if (StringUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Organization must not be null or empty"); } if (ArrayUtils.isEmpty(monthlies)) { throw new IllegalArgumentException("The monthlies must not be null"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<VJiseki> jisekis = new ArrayList<>(); try { tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, "SELECT UriSkKG as uriSkKG, KtSkKG as ktSkKG, IdoSkKGU as idoSkKGU, IdoSkKGH as idoSkKGH, UriKrKG as uriKrKG," + " KtKrKG as ktKrKG, KnSrKG as knSrKG, KtSrKG as ktSrKG, KgcSrKG as kgcSrKG, IdoSrKGU as idoSrKGU, IdoSrKGH as idoSrKGH, KtJkKG as ktJkKG, JkJkKG as jkJkKG, KgcJkKG as kgcJkKG, IdoJkKGU as idoJkKGU, IdoJkKGH as idoJkKGH, HelpJkKGU as helpJkKGU, " + " HelpJkKGH as helpJkKGH, KtKhKG as ktKhKG, KnKhKG as knKhKG, KgcKhKG as kgcKhKG, IdoKhKGU as idoKhKGU, IdoKhKGH as idoKhKGH, UriKhKG as uriKhKG FROM V_JISEKI WHERE StrCode = :strCode AND Getsudo in (:monthlies)"); query.setParameter("strCode", orgCode); query.setParameterList("monthlies", monthlies); query.setResultTransformer(Transformers.aliasToBean(VJiseki.class)); jisekis = repository.findByQuery(query); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(jisekis)) { throw new ObjectNotFoundException("There is no actual view object"); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while getting VJiseki data for the organization " + orgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return jisekis; }
/** {@inheritDoc} */ @Override public boolean checkAvailableByOrgCodeAndMonthly(String orgCode, String... monthlies) throws ServiceException { if (StringUtils.isEmpty(orgCode) || monthlies == null) { throw new IllegalArgumentException("Can not check month available with organization code or monthly empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; boolean isAvailable = Boolean.FALSE; try { tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, "SELECT count(StrCode) FROM v_jiseki WHERE StrCode = :orgCode AND GetSudo in (:monthlies)"); query.setParameter("orgCode", orgCode); query.setParameterList("monthlies", monthlies); Object count = query.uniqueResult(); if (count != null) { isAvailable = Long.parseLong(count.toString()) > 0; } tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex ) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while checking data for the organization " + orgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return isAvailable; }
/** {@inheritDoc} */ @Override public boolean checkAvailableByOrgCodesAndMonthlies(List<String> orgCode, String... monthlies) throws ServiceException { if (CollectionUtils.isEmpty(orgCode)) { throw new IllegalArgumentException("Can not check month available with organization code empty"); } if (ArrayUtils.isEmpty(monthlies)) { throw new IllegalArgumentException("Can not check month available with monthlies empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; boolean isAvailable = Boolean.FALSE; try { tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, "SELECT count(StrCode) FROM v_jiseki WHERE StrCode in (:orgCode) AND GetSudo in (:monthlies)"); query.setParameterList("orgCode", orgCode); query.setParameterList("monthlies", monthlies); Object count = query.uniqueResult(); if (count != null) { isAvailable = Long.parseLong(count.toString()) > 0; } tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex ) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while checking data for the organization " + orgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return isAvailable; }
/** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public PettyCashBookReport findDistrictByShop(String shopID) throws ServiceException { if (StringUtils.isEmpty(shopID)) { throw new IllegalArgumentException("ShopIDがNULLべきではない"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; PettyCashBookReport organization = null; try { tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, SqlConstants.SQL_FIND_ORGANIZATION_BY_SHOP); query.setParameter("StrCode", shopID); query.setResultTransformer(Transformers.aliasToBean(PettyCashBookReport.class)); List<PettyCashBookReport> organizations = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(organizations)) { throw new ObjectNotFoundException("部門コード " + shopID + " のデータが見つけなかった "); } organization = organizations.get(0); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while finding Organization list with ShopID " + shopID, ex); } finally { HibernateSessionManager.closeSession(session); } return organization; }
/** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<String> findOrgsByDepartmentCode(String strCode) throws ServiceException { if (StringUtils.isEmpty(strCode)) { throw new IllegalArgumentException("Can not find department with the strCode empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<String> organizations = new ArrayList<String>(); try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder("SELECT ifnull(t5.StrCode,ifnull(t4.StrCode,ifnull(t3.StrCode,ifnull(t2.StrCode,t1.StrCode)))) as strcode FROM at102 AS t1"); sql.append(" LEFT JOIN at102 AS t2 ON t2.StrCodeUp = t1.StrCode "); sql.append(" LEFT JOIN at102 AS t3 ON t3.StrCodeUp = t2.StrCode "); sql.append(" LEFT JOIN at102 AS t4 ON t4.StrCodeUp = t3.StrCode "); sql.append(" LEFT JOIN at102 AS t5 ON t5.StrCodeUp = t4.StrCode "); sql.append(" where t1.StrCode = :strcode "); // executed sql to get list data orgazation's codes with kaisobango = 5 Query query = repository.getSQLQuery(session, sql.toString()); query.setParameter("strcode", strCode); organizations = query.list(); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(organizations)) { throw new ObjectNotFoundException("Can not find organizations with strCode " + strCode); } } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while finding Organization list with strCode " + strCode, ex); } finally { HibernateSessionManager.closeSession(session); } return organizations; }
/** {@inheritDoc} */ @Override public boolean checkEmptyPurchase(String orgCode, String getSudo) throws ServiceException { if (StringUtils.isEmpty(getSudo)) { throw new IllegalArgumentException("orginazation code must not be null or empty"); } if (StringUtils.isEmpty(getSudo)) { throw new IllegalArgumentException("Month must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; long count = 0; try { StringBuilder sql = new StringBuilder(); sql.append(" SELECT count(ctgCode) "); sql.append(" FROM AT007 "); sql.append(" WHERE strCode=:strCode AND getSudo=:getSudo AND delKbn=2"); tx = session.beginTransaction(); Query query = repository.getSQLQuery(session, sql.toString()); query.setString("strCode", orgCode); query.setString("getSudo", getSudo); Object obj = query.uniqueResult(); count = Long.parseLong(obj.toString()); tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("Hibernate runtime exception when check data available", ex); } finally { HibernateSessionManager.closeSession(session); } return (count > 0); }
/** {@inheritDoc} */ @Override public boolean checkAvailable(String orgCode, Date getSudo) throws ServiceException { if (StringUtils.isEmpty(orgCode) || getSudo == null) { throw new IllegalArgumentException("To check month's data available, The input parameter organization code or business day must not be empty."); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; boolean isAvailable = false; try { tx = session.beginTransaction(); StringBuilder sql = new StringBuilder(); sql.append(" SELECT count(recID) "); sql.append(" FROM AT009 "); sql.append(" WHERE strCode=:strCode AND getSudo=:getSudo AND delKbn=2"); // String strBusinessDay = DateFormatUtil.format(getSudo, DateFormat.DATE_WITHOUT_DAY); Query query = pettyCashRepository.getSQLQuery(session, sql.toString()) .setString("strCode", orgCode) .setString("getSudo", strBusinessDay); BigInteger count = (BigInteger)query.uniqueResult(); isAvailable = (count.floatValue() > 0); tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("Hibernate runtime exception when check data available", ex); } finally { HibernateSessionManager.closeSession(session); } return isAvailable; }
/** {@inheritDoc} */ @Override public List<PettyCash> findUpdateNoById(String... recIDs) throws ServiceException { if (ArrayUtils.isEmpty(recIDs)) { throw new IllegalArgumentException("To get petty cash update number, its record id must not be empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<PettyCash> pettyCashes = new ArrayList<PettyCash>(); try { tx = session.beginTransaction(); Query query = pettyCashRepository.getSQLQuery(session, " SELECT UpdNo FROM AT009 WHERE RecID in (:recIDs) AND DelKbn=2 ") .setParameterList("recIDs", recIDs); pettyCashes = pettyCashRepository.findByQuery(query); tx.commit(); } catch (SQLGrammarException | GenericJDBCException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("Hibernate runtime exception when get update no of petty cash list ", ex); } finally { HibernateSessionManager.closeSession(session); } return pettyCashes; }
@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; }
@Override public String getErrorDescription() { if(getCause() != null && getCause() instanceof GenericJDBCException) { String SQL = ((GenericJDBCException)getCause()).getSQL(); return String.format("A JPA error occurred (%s): <strong>%s</strong>. This is likely because the batch has broken some referential integrity. Check your cascade delete, in case of ...", getMessage(), getCause() == null ? "" : getCause().getMessage(), SQL); } return String.format("A JPA error occurred (%s): <strong>%s</strong>", getMessage(), getCause() == null ? "" : getCause().getMessage()); }
public List<String> getSource() { List<String> sql = new ArrayList<String>(); if(getCause() != null && getCause() instanceof GenericJDBCException) { sql.add(((GenericJDBCException)getCause()).getSQL()); } return sql; }
public void _save() { if (!em().contains(this)) { em().persist(this); PlayPlugin.postEvent("JPASupport.objectPersisted", this); } avoidCascadeSaveLoops.set(new HashSet<JPABase>()); try { saveAndCascade(true); } finally { avoidCascadeSaveLoops.get().clear(); } try { em().flush(); } catch (PersistenceException e) { if (e.getCause() instanceof GenericJDBCException) { throw new PersistenceException(((GenericJDBCException) e.getCause()).getSQL(), e); } else { throw e; } } avoidCascadeSaveLoops.set(new HashSet<JPABase>()); try { saveAndCascade(false); } finally { avoidCascadeSaveLoops.get().clear(); } }
/** * */ @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()); } } }
@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); }
/** * */ @Test public void catchNewConnectionJson() throws Exception { UriInfo mockUriInfo = Mockito.mock(UriInfo.class); Mockito.when(mockUriInfo.getBaseUri()).thenReturn(new URI("http://www.test.com/go")); GenericJDBCException exception = new GenericJDBCException("sql", new SQLException("reason")); Response bean = FactoryResponse.catchNewConnectionJson(mockUriInfo, exception, "message", "resource"); Assert.assertTrue(true); }
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); }
private Session getHibernateSession() { if (session == null) { try { session = HibernateUtil.getSessionFactory().openSession(); } catch (GenericJDBCException e) { //FIXME Show exception message and hide or disable all database based content e.printStackTrace(); } } return session; }
public JobLogView(ChipsterAdminUI app) { this.app = app; // do this before data source is attached to avoid one data update setSizeFull(); table = new JobLogTable(this); this.addComponent(getToolbar()); this.addComponent(table); this.setExpandRatio(table, 1); try { dataSource = new JobLogContainer(this); table.setContainerDataSource(dataSource); table.setVisibleColumns(JobLogContainer.NATURAL_COL_ORDER); table.setColumnHeaders(JobLogContainer.COL_HEADERS_ENGLISH); table.setSortAscending(false); table.setSortContainerPropertyId(JobLogContainer.END_TIME); addFilter(JobLogContainer.END_TIME, DateContainerFilter.getToday()); } catch (GenericJDBCException e) { logger.error("unable to read job database", e); //FIXME Show exception message and hide or disable all database based content return; } }
@Override public void doExecute(ProcessBundle bundle) throws Exception { OBError msg = new OBError(); msg.setType("Success"); msg.setTitle(OBMessageUtils.messageBD("Success")); try { // retrieve standard params String strProductId = (String) bundle.getParams().get("mProductId"); String strChValueId = (String) bundle.getParams().get("mChValueId"); update(strProductId, strChValueId); bundle.setResult(msg); // Postgres wraps the exception into a GenericJDBCException } catch (GenericJDBCException ge) { log4j.error("Exception processing variant generation", ge); msg.setType("Error"); msg.setTitle(OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext() .getLanguage())); msg.setMessage(ge.getSQLException().getMessage()); bundle.setResult(msg); OBDal.getInstance().rollbackAndClose(); // Oracle wraps the exception into a QueryTimeoutException } catch (QueryTimeoutException qte) { log4j.error("Exception processing variant generation", qte); msg.setType("Error"); msg.setTitle(OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext() .getLanguage())); msg.setMessage(qte.getSQLException().getMessage().split("\n")[0]); bundle.setResult(msg); OBDal.getInstance().rollbackAndClose(); } catch (final Exception e) { log4j.error("Exception processing variant generation", e); msg.setType("Error"); msg.setTitle(OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext() .getLanguage())); msg.setMessage(FIN_Utility.getExceptionMessage(e)); bundle.setResult(msg); OBDal.getInstance().rollbackAndClose(); } }
/** * Hibernate data. * * @param article * the article * @param session * the session * @return true, if successful */ public synchronized boolean hibernateData(final NewsArticle article, final Session session) { Transaction tx = null; HibernateHelper.logger.debug("hibernateData: " + article.getArticleId()); final Location location = null; final String gender = null; try { tx = session.beginTransaction(); tx.begin(); final UsenetUser poster = this.createUsenetUser(article, session, location, gender); final Message message = this.createMessage(article, null, poster); this.storeNewsgroups(article.getNewsgroupsList(), message, session); tx.commit(); } catch (Exception e) { if (e instanceof GenericJDBCException) { e = (Exception) e.getCause(); } if (e instanceof BatchUpdateException) { final BatchUpdateException buex = (BatchUpdateException) e; System.err.println("Contents of BatchUpdateException:"); System.err.println(" Update counts: "); final int[] updateCounts = buex.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.println(" Statement " + i + ":" + updateCounts[i]); } System.err.println(" Message: " + buex.getMessage()); System.err.println(" SQLSTATE: " + buex.getSQLState()); System.err.println(" Error code: " + buex.getErrorCode()); System.err.println(" Article: " + article); SQLException ex = buex.getNextException(); while (ex != null) { System.err.println("SQL exception:"); System.err.println(" Message: " + ex.getMessage()); System.err.println(" SQLSTATE: " + ex.getSQLState()); System.err.println(" Error code: " + ex.getErrorCode()); System.err.println(" Error code: " + ex.getErrorCode()); ex = ex.getNextException(); } } HibernateHelper.logger.error("Failed to store message", e); e.printStackTrace(); if (tx != null) { try { tx.rollback(); } catch (final HibernateException e1) { e1.printStackTrace(); return false; } } } return true; }