List of usage examples for java.sql SQLException getErrorCode
public int getErrorCode()
SQLException
object. From source file:RSAccounts.java
public void connectToDB() { try {//from ww w . ja v a2 s . c o m connection = DriverManager .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider"); statement = connection.createStatement(); } catch (SQLException connectException) { System.out.println(connectException.getMessage()); System.out.println(connectException.getSQLState()); System.out.println(connectException.getErrorCode()); System.exit(1); } }
From source file:com.hangum.tadpole.rdb.core.editors.main.composite.MessageComposite.java
/** * SQLException to pretty message//w ww . ja v a 2 s. c o m * * @param sqlException * @param tadpoleMessageDAO * @return */ private String sqlExceptionToMsg(SQLException sqlException, TadpoleMessageDAO tadpoleMessageDAO) { String strNewMessage = ""; try { StringBuffer sbMsg = new StringBuffer(); sbMsg.append(String.format(Messages.get().MessageComposite_5, sqlException.getSQLState(), sqlException.getErrorCode())); sbMsg.append(String.format(Messages.get().MessageComposite_4, sqlException.getMessage())); strNewMessage = sbMsg.toString(); } catch (Exception e) { logger.error("SQLException to striing", e); //$NON-NLS-1$ strNewMessage = tadpoleMessageDAO.getStrMessage(); } return strNewMessage; }
From source file:com.yahoo.dba.perf.myperf.springmvc.VardiffController.java
@Override protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception { int status = Constants.STATUS_OK; String message = "OK"; logger.info("receive url " + req.getQueryString()); QueryParameters qps = null;/* w ww . j a va 2s .c om*/ DBInstanceInfo dbinfo = null; DBInstanceInfo dbinfo2 = null; DBConnectionWrapper connWrapper = null; DBConnectionWrapper connWrapper2 = null; qps = WebAppUtil.parseRequestParameter(req); qps.setSql("mysql_global_variables"); qps.getSqlParams().put("p_1", ""); String group2 = req.getParameter("p_1"); String host2 = req.getParameter("p_2"); //validation input String validation = qps.validate(); if (validation == null || validation.isEmpty()) { //do we have such query? try { QueryInputValidator.validateSql(this.frameworkContext.getSqlManager(), qps); } catch (Exception ex) { validation = ex.getMessage(); } } if (validation != null && !validation.isEmpty()) return this.respondFailure(validation, req); dbinfo = this.frameworkContext.getDbInfoManager().findDB(qps.getGroup(), qps.getHost()); if (dbinfo == null) return this.respondFailure("Cannot find record for DB (" + qps.getGroup() + ", " + qps.getHost() + ")", req); dbinfo2 = this.frameworkContext.getDbInfoManager().findDB(group2, host2); if (dbinfo2 == null) return this.respondFailure("Cannot find record for DB (" + group2 + ", " + host2 + ")", req); try { connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo); if (connWrapper == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo + ")"; } else { connWrapper2 = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo2); if (connWrapper2 == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo2 + ")"; } } } catch (Throwable th) { logger.log(Level.SEVERE, "Exception", th); status = Constants.STATUS_BAD; message = "Failed to get connection to target db (" + dbinfo + "): " + th.getMessage(); } if (status == -1) return this.respondFailure(message, req); //when we reach here, at least we have valid query and can connect to db WebAppUtil.storeLastDbInfoRequest(qps.getGroup(), qps.getHost(), req); ModelAndView mv = null; ResultList rList = null; ResultList rList2 = null; try { rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper, qps.getMaxRows()); rList2 = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper2, qps.getMaxRows()); logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0) + " records, " + (rList2 != null ? rList2.getRows().size() : 0) + " records"); WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } catch (Throwable ex) { logger.log(Level.SEVERE, "Exception", ex); if (ex instanceof SQLException) { SQLException sqlEx = SQLException.class.cast(ex); String msg = ex.getMessage(); logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg); //check if the connection is still good if (!DBUtils.checkConnection(connWrapper.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper, true); } else WebAppUtil.closeDBConnection(req, connWrapper, true); if (!DBUtils.checkConnection(connWrapper2.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper2, true); } else WebAppUtil.closeDBConnection(req, connWrapper2, true); } else { WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } status = Constants.STATUS_BAD; message = "Exception: " + ex.getMessage(); } if (status == Constants.STATUS_BAD) return this.respondFailure(message, req); HashMap<String, String> param1 = new HashMap<String, String>(rList.getRows().size()); HashMap<String, String> param2 = new HashMap<String, String>(rList2.getRows().size()); for (ResultRow r : rList.getRows()) { param1.put(r.getColumns().get(0), r.getColumns().get(1)); } for (ResultRow r : rList2.getRows()) { param2.put(r.getColumns().get(0), r.getColumns().get(1)); } ColumnDescriptor desc = new ColumnDescriptor(); desc.addColumn("VARIABLE_NAME", false, 1); desc.addColumn("DB1", false, 2); desc.addColumn("DB2", false, 3); ResultList fList = new ResultList(); fList.setColumnDescriptor(desc); HashSet<String> diffSet = new HashSet<String>(); for (Map.Entry<String, String> e : param1.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v != null) v = v.trim(); else v = ""; String v2 = null; if (param2.containsKey(k)) v2 = param2.get(k); if (v2 != null) v2 = v2.trim(); else v2 = ""; if (!v.equals(v2)) { ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(v); cols.add(v2); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); diffSet.add(k); } } for (Map.Entry<String, String> e : param2.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v == null || v.isEmpty()) continue; if (diffSet.contains(k) || param1.containsKey(k)) continue; ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(""); cols.add(v); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); } mv = new ModelAndView(this.jsonView); if (req.getParameter("callback") != null && req.getParameter("callback").trim().length() > 0) mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding mv.addObject("json_result", ResultListUtil.toJSONString(fList, qps, status, message)); return mv; }
From source file:com.ironiacorp.persistence.hibernate.HibernateBootstrap.java
/** * Check the exceptions thrown while running the update or create scripts * for the current Hibernate configuration. * //from w w w .j a v a 2 s . c o m * @param ddl * The SchemaExport or SchemaUpdate used. * @throws IllegalArgumentException * If the argument is not a SchemaExport or SchemaUpdate * instance. */ @SuppressWarnings("unchecked") private List<Exception> handleExceptions(Object ddl) { if (!(ddl instanceof SchemaExport ^ ddl instanceof SchemaUpdate)) { throw new IllegalArgumentException(); } List<Exception> exceptions = null; List<Exception> errors = new LinkedList<Exception>(); if (ddl instanceof SchemaExport) { SchemaExport schema = (SchemaExport) ddl; exceptions = schema.getExceptions(); } else { SchemaUpdate schema = (SchemaUpdate) ddl; exceptions = schema.getExceptions(); } if (!exceptions.isEmpty()) { for (Object o : exceptions) { Exception e = (Exception) o; SQLException sqle = null; String dialect = null; log.debug(e); if (e instanceof SQLException) { sqle = (SQLException) e; log.debug("SQL error code: " + sqle.getErrorCode()); log.debug("SQL state: " + sqle.getSQLState()); // Filter exceptions. dialect = config.getProperty("dialect"); if (dialect.equals("org.hibernate.dialect.MySQLDialect") || dialect.equals("org.hibernate.dialect.MySQLInnoDBDialect") || dialect.equals("org.hibernate.dialect.MySQLMyISAMDialect")) { e = handleMySQLError(sqle); } } if (e != null) { errors.add(e); } } } return errors; }
From source file:com.bbm.common.aspect.ExceptionTransfer.java
/** * ? Exception ? ? ?? ?? ? .//from w w w .j av a 2s. c om * @param thisJoinPoint joinPoint ? * @param exception ? Exception */ public void transfer(JoinPoint thisJoinPoint, Exception exception) throws Exception { log.debug("execute ExceptionTransfer.transfer "); Class clazz = thisJoinPoint.getTarget().getClass(); Signature signature = thisJoinPoint.getSignature(); Locale locale = LocaleContextHolder.getLocale(); /** * BizException ? ?? ? ?. * Exception ?? ? ?? Exception? ? ? ?. * ? . * ? ?? Handler ? ?. */ String servicename = ""; // String errorCode = ""; // ? String errorMessage = ""; // ? String classname = ""; // ?? int servicepos = clazz.getCanonicalName().lastIndexOf("."); // .? if (servicepos > 0) { String tempStr = clazz.getCanonicalName().substring(servicepos + 1); servicepos = tempStr.lastIndexOf("Impl"); // Impl? servicename = tempStr.substring(0, servicepos); } else { servicename = clazz.getCanonicalName(); } classname = exception.getClass().getName(); //EgovBizException ? ? if (exception instanceof EgovBizException) { log.debug("Exception case :: EgovBizException "); EgovBizException be = (EgovBizException) exception; getLog(clazz).error(be.getMessage(), be.getCause()); // Exception Handler ? ?? Package Exception . (runtime ? ExceptionHandlerService ) processHandling(clazz, signature.getName(), exception, pm, exceptionHandlerServices); throw be; //RuntimeException ? ? ? DataAccessException ? ?? throw . } else if (exception instanceof RuntimeException) { log.debug("RuntimeException case :: RuntimeException "); RuntimeException be = (RuntimeException) exception; getLog(clazz).error(be.getMessage(), be.getCause()); // Exception Handler ? ?? Package Exception . processHandling(clazz, signature.getName(), exception, pm, exceptionHandlerServices); if (be instanceof DataAccessException) { /* log.debug("RuntimeException case :: DataAccessException "); DataAccessException sqlEx = (DataAccessException) be; throw sqlEx; */ log.debug("RuntimeException case :: DataAccessException "); DataAccessException dataEx = (DataAccessException) be; Throwable t = dataEx.getRootCause(); String exceptionname = t.getClass().getName(); if (exceptionname.equals("java.sql.SQLException")) { java.sql.SQLException sqlException = (java.sql.SQLException) t; errorCode = String.valueOf(sqlException.getErrorCode()); errorMessage = sqlException.getMessage(); } else if (exception instanceof org.springframework.jdbc.BadSqlGrammarException) { org.springframework.jdbc.BadSqlGrammarException sqlEx = (org.springframework.jdbc.BadSqlGrammarException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else if (exception instanceof org.springframework.jdbc.UncategorizedSQLException) { org.springframework.jdbc.UncategorizedSQLException sqlEx = (org.springframework.jdbc.UncategorizedSQLException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else if (exception instanceof org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException) { org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException sqlEx = (org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException) exception; errorCode = String.valueOf(sqlEx.getActualRowsAffected()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.SQLWarningException) { org.springframework.jdbc.SQLWarningException sqlEx = (org.springframework.jdbc.SQLWarningException) exception; errorCode = String.valueOf(sqlEx.SQLWarning().getErrorCode()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.CannotGetJdbcConnectionException) { org.springframework.jdbc.CannotGetJdbcConnectionException sqlEx = (org.springframework.jdbc.CannotGetJdbcConnectionException) exception; errorCode = String.valueOf(sqlEx.getMessage()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.InvalidResultSetAccessException) { org.springframework.jdbc.InvalidResultSetAccessException sqlEx = (org.springframework.jdbc.InvalidResultSetAccessException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else { if (exception instanceof java.lang.reflect.InvocationTargetException) { java.lang.reflect.InvocationTargetException ce = (java.lang.reflect.InvocationTargetException) exception; errorCode = ""; errorMessage = ce.getTargetException().getMessage(); //strErrorMessage = getValue(ce.getTargetException().toString(), ""); } } // , ?, ?, , String[] messages = new String[] { "DataAccessException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); } // , ?, ?, , errorMessage = exception.getMessage(); String[] messages = new String[] { "RuntimeException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); //throw be; // ? ? Exception (: ) :: ? ?. } else if (exception instanceof FdlException) { log.debug("FdlException case :: FdlException "); FdlException fe = (FdlException) exception; getLog(clazz).error(fe.getMessage(), fe.getCause()); errorMessage = exception.getMessage(); // , ?, ?, , String[] messages = new String[] { "FdlException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); //throw fe; } else { //? ? Exception ? BaseException (: fail.common.msg) ?. //:: ? ?. log.debug("case :: Exception "); getLog(clazz).error(exception.getMessage(), exception.getCause()); errorMessage = exception.getMessage(); // , ?, ?, , String[] messages = new String[] { "Exception", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); } }
From source file:com.viettel.logistic.wms.dao.GoodsDAO.java
public ResultDTO insertListGoods(List<Goods> lstGoods) { ResultDTO resultDTO = new ResultDTO(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); ResultDTO result = new ResultDTO(); Goods goods = null;/*from ww w.ja va2s.com*/ String lstGoodsId = ""; long cusID = lstGoods.get(0).getCustId(); try { for (int i = 0; i < lstGoods.size(); i++) { goods = lstGoods.get(i); lstGoodsId = lstGoodsId + "," + goods.getCode(); session.save(goods); if (i % 50 == 0) { // Same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); lstGoodsId = ""; } } tx.commit(); result.setMessage(ParamUtils.SUCCESS); } catch (HibernateException ex) { if (ex.getCause() != null && ex.getCause() instanceof SQLException) { SQLException se = (SQLException) ex.getCause(); // Transaction tx2 = session.beginTransaction(); if (se.getErrorCode() == 1) { session.clear(); ConditionBean condition = new ConditionBean("code", ParamUtils.OP_IN, lstGoodsId.replaceFirst(",", ""), ParamUtils.TYPE_STRING); ConditionBean condition1 = new ConditionBean("custId", ParamUtils.OP_EQUAL, String.valueOf(cusID), ParamUtils.TYPE_NUMBER); List<ConditionBean> lstConditionBeans = new ArrayList<>(); lstConditionBeans.add(condition); lstConditionBeans.add(condition1); List<Goods> lstGoodsViolated = findSession("Goods", lstConditionBeans, "code", 0, Integer.MAX_VALUE, null, getSession()); if (lstGoodsViolated != null && !lstGoodsViolated.isEmpty()) { String id = ""; for (Goods item : lstGoodsViolated) { id = id + "," + item.getCode(); } result.setKey(id.replaceFirst(",", "")); } } } tx.rollback(); result.setMessage(ParamUtils.FAIL); } finally { session.close(); } return result; }
From source file:it.cnr.icar.eric.server.container.DerbyHelper.java
/** * Log appropriate information about a SQLException. In some cases, * the exception may be a normal consequence of connecting to the * shutdown URL. Logs something (message.stoppedDatabase at least) in * all cases.//from ww w .j av a 2s . co m * * @param sqlException the {@link java.sql.SQLException} which should * be discarded (as normal) or logged */ protected void logDatabaseException(SQLException sqlException) { // In general, we do not know much about what these exceptions mean if (log.isDebugEnabled()) { while (null != sqlException) { // ??? add a message for unrecognized SQL exceptions log.error(sqlException); log.debug("Error Code: " + sqlException.getErrorCode()); log.debug("SQL State: " + sqlException.getSQLState()); sqlException = sqlException.getNextException(); } } else { // ??? add a message for unrecognized SQL exceptions log.error(sqlException); } }
From source file:com.googlecode.fascinator.sequences.SequenceService.java
/** * Shuts down the plugin//www. ja v a 2s . c om * * @throws AccessControlException * if there was an error during shutdown */ public void shutdown() throws SQLException { // Derby can only be shutdown from one thread, // we'll catch errors from the rest. String threadedShutdownMessage = DERBY_DRIVER + " is not registered with the JDBC driver manager"; try { // Tell the database to close DriverManager.getConnection(DERBY_PROTOCOL + ";shutdown=true"); // Shutdown just this database (but not the engine) // DriverManager.getConnection(DERBY_PROTOCOL + SECURITY_DATABASE + // ";shutdown=true"); } catch (SQLException ex) { // These test values are used if the engine is NOT shutdown // if (ex.getErrorCode() == 45000 && // ex.getSQLState().equals("08006")) { // Valid response if (ex.getErrorCode() == 50000 && ex.getSQLState().equals("XJ015")) { // Error response } else { // Make sure we ignore simple thread issues if (!ex.getMessage().equals(threadedShutdownMessage)) { log.error("Error during database shutdown:", ex); throw new SQLException("Error during database shutdown:", ex); } } } finally { try { // Close our connection if (connection != null) { connection.close(); connection = null; } } catch (SQLException ex) { log.error("Error closing connection:", ex); } } }
From source file:seava.j4e.web.controller.AbstractBaseController.java
/** * Exception// ww w. j ava 2 s .co m * * @param e * @param response * @return * @throws IOException */ @ResponseBody protected String handleManagedException(IErrorCode errorCode, Exception e, HttpServletResponse response, String outputType) throws IOException { IErrorCode err = errorCode; Map<String, String> result = new HashMap<String, String>(); if (!(e instanceof BusinessException)) { e.printStackTrace(); } if (err == null) { err = ErrorCode.G_RUNTIME_ERROR; } // if (e instanceof BusinessException) { // err = ((BusinessException) e).getErrorCode(); // } else { // if (e.getCause() != null) { // Throwable t = e; // while (t.getCause() != null) { // t = t.getCause(); // if (t instanceof BusinessException) { // err = ((BusinessException) t).getErrorCode(); // break; // } // } // } // } result.put("err_group", err.getErrGroup()); result.put("err_no", err.getErrNo() + ""); result.put("err_msg", err.getErrMsg()); // -------------------- if (e.getCause() != null) { Throwable t = e; while (t.getCause() != null) { t = t.getCause(); } if (t instanceof SQLException) { SQLException sqlException = (SQLException) t; result.put("msg", sqlException.getErrorCode() + " - " + sqlException.getSQLState() + " - " + sqlException.getLocalizedMessage()); } else { result.put("msg", t.getMessage()); } } // --------------------- if (!result.containsKey("msg")) { result.put("msg", e.getMessage()); } else { result.put("details", e.getMessage()); } StringBuffer sb = new StringBuffer(); if (outputType.matches("txt")) { sb.append(result.get("err_group") + "-" + result.get("err_no") + "\n||\n"); sb.append(result.get("err_msg") + "\n||\n"); sb.append(result.get("msg") + "\n||\n"); sb.append(result.get("details") + "\n||\n"); } else if (outputType.matches("html")) { sb.append("<html><body><div>" + result.get("msg") + "</div></body></html>"); } response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); response.getOutputStream().print(sb.toString()); return null; }
From source file:com.hangum.tadpole.rdb.core.editors.objectmain.ObjectEditor.java
/** * mssql after process/*from www.j av a 2 s . c o m*/ * @param reqResultDAO * @param reqQuery */ private void mssqlAfterProcess(RequestResultDAO reqResultDAO, RequestQuery reqQuery) { if (reqResultDAO.getException() == null) return; String strSQLState = ""; int intSQLErrorCode = -1; Throwable cause = reqResultDAO.getException(); ; if (cause instanceof SQLException) { try { SQLException sqlException = (SQLException) cause; strSQLState = sqlException.getSQLState(); intSQLErrorCode = sqlException.getErrorCode(); if (logger.isDebugEnabled()) logger.debug("==========> SQLState : " + strSQLState + "\t SQLErrorCode : " + intSQLErrorCode); } catch (Exception e) { logger.error("SQLException to striing", e); //$NON-NLS-1$ } } if (strSQLState.equals("S0001") && intSQLErrorCode == 2714) { //$NON-NLS-1$ String cmd = String.format("DROP %s %s", reqQuery.getSqlDDLType(), reqQuery.getSqlObjectName()); //$NON-NLS-1$ if (MessageDialog.openConfirm(null, Messages.get().Confirm, String.format(Messages.get().ObjectEditor_13, reqQuery.getSqlObjectName()))) { RequestResultDAO reqReResultDAO = new RequestResultDAO(); try { reqReResultDAO = ExecuteDDLCommand.executSQL(userDB, cmd); //$NON-NLS-1$ afterProcess(reqQuery, reqReResultDAO, Messages.get().ObjectEditor_2); reqReResultDAO = ExecuteDDLCommand.executSQL(userDB, reqQuery.getOriginalSql()); //$NON-NLS-1$ afterProcess(reqQuery, reqReResultDAO, Messages.get().ObjectEditor_2); } catch (Exception ee) { afterProcess(reqQuery, reqResultDAO, ""); //$NON-NLS-1$ } } } }