List of usage examples for java.sql SQLException getSQLState
public String getSQLState()
SQLException
object. From source file:com.egt.core.db.xdp.RecursoCachedRowSet.java
/** * {@inheritDoc}//www . ja v a 2 s. c om */ @Override public void acceptChanges() throws SyncProviderException { try { this.getFilasConflictivas().clear(); super.acceptChanges(); } catch (SyncProviderException spe) { SyncResolver resolver = spe.getSyncResolver(); if (resolver != null && resolver instanceof SyncResolverX) { boolean showDeleted = this.tryToGetShowDeleted(); boolean sinDuplicados = TLC.getBitacora().isSinDuplicados(); int conflictos = 0; int row; int status = SyncResolver.NO_ROW_CONFLICT; String transaction = DBUtils.getTransactionLabel(status); SQLException sqlException; int errorCode; String message; String localizedMessage; String sqlState; String heading; String clave = CBM2.COMMIT_CHANGES_UNKNOWN_EXCEPTION; int tipoError; /* OJO con la constante, 1 -> fila con un error desconocido */ String mensaje; String prefijo = Global.PREFIJO_ETIQUETA_ID_RECURSO; try { this.tryToSetShowDeleted(true); TLC.getBitacora().setSinDuplicados(true); while (resolver.nextConflict()) { conflictos++; row = resolver.getRow(); status = resolver.getStatus(); transaction = DBUtils.getTransactionLabel(status); sqlException = ((SyncResolverX) resolver).getSQLException(); errorCode = sqlException.getErrorCode(); message = sqlException.getMessage(); localizedMessage = StringUtils.substringBefore(sqlException.getLocalizedMessage(), " Where: "); sqlState = sqlException.getSQLState(); heading = "Row:" + row + ", Status:" + status + ", Code:" + errorCode + ", State:" + sqlState; Bitacora.trace(heading + message); if (TLC.getInterpreteSql().isCommandIgnoredException(sqlException)) { clave = CBM2.COMMIT_CHANGES_COMMAND_IGNORED_EXCEPTION; tipoError = 0; /* OJO con la constante, 0 -> fila "ignorada" (no se sabe si tiene o no errores) */ mensaje = tipoError + Bitacora.getTextoMensaje(clave, transaction, prefijo + row); TLC.getBitacora().error(CBM2.COMMIT_CHANGES_COMMAND_IGNORED); if (status == SyncResolver.DELETE_ROW_CONFLICT) { this.tryToSetShowDeleted(false); } } else { String columna = TLC.getInterpreteSql() .getNotNullConstraintViolationColumn(sqlException); if (StringUtils.isNotBlank(columna)) { clave = CBM2.DATABASE_NOT_NULL_CONSTRAINT_VIOLATION; tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row, columna); } else { clave = DBUtils.getConstraintMessageKey(message, status); if (clave == null) { clave = CBM2.COMMIT_CHANGES_UNKNOWN_EXCEPTION; tipoError = 1; /* OJO con la constante, 1 -> fila con un error desconocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row, localizedMessage); } else { tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row); } } } this.getFilasConflictivas().put(String.valueOf(row - 1), mensaje); // if (status == SyncResolver.DELETE_ROW_CONFLICT) // if (this.absolute(row)) // if (this.rowDeleted()) // RETORNA FALSO! // this.undoDelete(); } if (conflictos == 0) { /* esto parece un BUG, y pasa cuando se elimina la ultima fila y showDeleted==false */ TLC.getBitacora().error(clave, transaction, "", spe.getLocalizedMessage()); } } catch (SQLException ex) { TLC.getBitacora().fatal(ex); } finally { this.tryToSetShowDeleted(showDeleted); TLC.getBitacora().setSinDuplicados(sinDuplicados); throw new SyncProviderException(this.getSyncProviderExceptionString(spe)); } } throw spe; } }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
private static String getMessage(SQLException ex) { return ex.getMessage() + " (SQLState=" + ex.getSQLState() + ", ErrorCode=" + ex.getErrorCode() + ")"; }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
/** * Returns true if {@code ex} should be retried *///ww w .ja v a 2s .c om static boolean isRetryable(HiveConf conf, Exception ex) { if (ex instanceof SQLException) { SQLException sqlException = (SQLException) ex; if ("08S01".equalsIgnoreCase(sqlException.getSQLState())) { //in MSSQL this means Communication Link Failure return true; } if ("ORA-08176".equalsIgnoreCase(sqlException.getSQLState()) || sqlException.getMessage().contains("consistent read failure; rollback data not available")) { return true; } String regex = HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_TXN_RETRYABLE_SQLEX_REGEX); if (regex != null && !regex.isEmpty()) { String[] patterns = regex.split(",(?=\\S)"); String message = getMessage((SQLException) ex); for (String p : patterns) { if (Pattern.matches(p, message)) { return true; } } } //see also https://issues.apache.org/jira/browse/HIVE-9938 } return false; }
From source file:ips1ap101.lib.core.db.xdp.RecursoCachedRowSet.java
/** * {@inheritDoc}//ww w .j ava 2 s .c om */ @Override public void acceptChanges() throws SyncProviderException { try { this.getFilasConflictivas().clear(); super.acceptChanges(); } catch (SyncProviderException spe) { SyncResolver resolver = spe.getSyncResolver(); if (resolver != null && resolver instanceof SyncResolverX) { boolean showDeleted = this.tryToGetShowDeleted(); boolean sinDuplicados = TLC.getBitacora().isSinDuplicados(); int conflictos = 0; int row; int status = SyncResolver.NO_ROW_CONFLICT; String transaction = DBUtils.getTransactionLabel(status); SQLException sqlException; int errorCode; String message; String localizedMessage; String sqlState; String clave = CBM.COMMIT_CHANGES_UNKNOWN_EXCEPTION; int tipoError; /* OJO con la constante, 1 -> fila con un error desconocido */ String mensaje; String prefijo = Global.PREFIJO_ETIQUETA_ID_RECURSO; try { this.tryToSetShowDeleted(true); TLC.getBitacora().setSinDuplicados(true); while (resolver.nextConflict()) { conflictos++; row = resolver.getRow(); status = resolver.getStatus(); transaction = DBUtils.getTransactionLabel(status); sqlException = ((SyncResolverX) resolver).getSQLException(); errorCode = sqlException.getErrorCode(); message = sqlException.getMessage(); localizedMessage = DBUtils.getProperErrorMessage(sqlException.getLocalizedMessage()); sqlState = sqlException.getSQLState(); Bitacora.trace("SQLException Message = " + message); Bitacora.trace("SQLException Localized Message = " + localizedMessage); Bitacora.trace("SQLException Row = " + row + ", Status = " + status + ", Code = " + errorCode + ", State = " + sqlState); if (TLC.getInterpreteSql().isCommandIgnoredException(sqlException)) { clave = CBM.COMMIT_CHANGES_COMMAND_IGNORED_EXCEPTION; tipoError = 0; /* OJO con la constante, 0 -> fila "ignorada" (no se sabe si tiene o no errores) */ mensaje = tipoError + Bitacora.getTextoMensaje(clave, transaction, prefijo + row); TLC.getBitacora().error(CBM.COMMIT_CHANGES_COMMAND_IGNORED); if (status == SyncResolver.DELETE_ROW_CONFLICT) { this.tryToSetShowDeleted(false); } } else { String columna = TLC.getInterpreteSql() .getNotNullConstraintViolationColumn(sqlException); if (StringUtils.isNotBlank(columna)) { clave = CBM.DATABASE_NOT_NULL_CONSTRAINT_VIOLATION; tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row, columna); } else { clave = DBUtils.getConstraintMessageKey(message, status); if (clave == null) { clave = CBM.COMMIT_CHANGES_UNKNOWN_EXCEPTION; tipoError = 1; /* OJO con la constante, 1 -> fila con un error desconocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row, localizedMessage); } else { tipoError = 2; /* OJO con la constante, 2 -> fila con un error conocido */ mensaje = tipoError + TLC.getBitacora().error(clave, transaction, prefijo + row); } } } this.getFilasConflictivas().put(String.valueOf(row - 1), mensaje); // if (status == SyncResolver.DELETE_ROW_CONFLICT) // if (this.absolute(row)) // if (this.rowDeleted()) // RETORNA FALSO! // this.undoDelete(); } if (conflictos == 0) { /* esto parece un BUG, y pasa cuando se elimina la ultima fila y showDeleted==false */ TLC.getBitacora().error(clave, transaction, "", spe.getLocalizedMessage()); } } catch (SQLException ex) { TLC.getBitacora().fatal(ex); } finally { this.tryToSetShowDeleted(showDeleted); TLC.getBitacora().setSinDuplicados(sinDuplicados); throw new SyncProviderException(this.getSyncProviderExceptionString(spe)); } } throw spe; } }
From source file:org.apache.hive.beeline.BeeLine.java
void handleSQLException(SQLException e) { if (e instanceof SQLWarning && !(getOpts().getShowWarnings())) { return;// w w w . j a v a2s. co m } if (e.getCause() instanceof TTransportException) { switch (((TTransportException) e.getCause()).getType()) { case TTransportException.ALREADY_OPEN: error(loc("hs2-connection-already-open")); break; case TTransportException.END_OF_FILE: error(loc("hs2-unexpected-end-of-file")); break; case TTransportException.NOT_OPEN: error(loc("hs2-could-not-open-connection")); break; case TTransportException.TIMED_OUT: error(loc("hs2-connection-timed-out")); break; case TTransportException.UNKNOWN: error(loc("hs2-unknown-connection-problem")); break; default: error(loc("hs2-unexpected-error")); } } error(loc(e instanceof SQLWarning ? "Warning" : "Error", new Object[] { e.getMessage() == null ? "" : e.getMessage().trim(), e.getSQLState() == null ? "" : e.getSQLState().trim(), new Integer(e.getErrorCode()) })); if (getOpts().getVerbose()) { e.printStackTrace(getErrorStream()); } if (!getOpts().getShowNestedErrs()) { return; } for (SQLException nested = e.getNextException(); nested != null && nested != e; nested = nested.getNextException()) { handleSQLException(nested); } }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
/** * By calling removeReport above, you can't remove the last or default * report. However, sometimes we may need to internally remove the last * report, for example if we're removing a table all reports need to be * removed. This method is there for private use in these situations *///from w w w .j av a 2s. c o m private void removeReportWithoutChecks(SessionDataInfo sessionData, HttpServletRequest request, BaseReportInfo reportToRemove, Connection conn) throws DisallowedException, SQLException, CodingErrorException, CantDoThatException, ObjectNotFoundException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE, reportToRemove.getParentTable()))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE, reportToRemove.getParentTable()); } // Remove the report from any 'hidden report' lists belonging to users // and from being the default report of any user CompanyInfo company = this.getAuthManager().getCompanyForLoggedInUser(request); for (AppUserInfo user : company.getUsers()) { HibernateUtil.activateObject(user); user.unhideReport(reportToRemove); user.removeOperationalDashboardReport(reportToRemove); if (reportToRemove.equals(user.getDefaultReport())) { logger.warn("Default report " + reportToRemove.getModule() + " - " + reportToRemove + " removed for user " + user); user.setDefaultReport(null); } } TableInfo parentTable = reportToRemove.getParentTable(); HibernateUtil.activateObject(parentTable); String internalReportName = reportToRemove.getInternalReportName(); try { // Drop database view // Note: IF EXISTS added temporarily(?) to help when dropping // problem tables PreparedStatement statement = conn.prepareStatement("DROP VIEW IF EXISTS " + internalReportName); statement.execute(); statement.close(); HibernateUtil.currentSession().delete(reportToRemove); } catch (SQLException sqlex) { String errorCode = sqlex.getSQLState(); if (errorCode.equals("42P01")) { throw new SQLException( "Can't delete report " + reportToRemove + " because it doesn't exist in the data store", sqlex); } else { throw new SQLException(sqlex + ": error code " + errorCode, sqlex); } } }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public void removeTable(SessionDataInfo sessionData, HttpServletRequest request, TableInfo tableToRemove, Connection conn) throws SQLException, DisallowedException, CantDoThatException, TableDependencyException, CodingErrorException, ObjectNotFoundException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.ADMINISTRATE))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.ADMINISTRATE); }// w ww . j av a 2 s . c om // Check the table doesn't have any user-added fields for (BaseField field : tableToRemove.getFields()) { if (!(field.equals(tableToRemove.getPrimaryKey()) || field.getHidden())) { throw new CantDoThatException("Please remove all fields before removing the table"); } } // Check that it doesn't have any reports if (tableToRemove.getReports().size() > 1) { throw new CantDoThatException( "Please remove reports " + tableToRemove.getReports() + " before removing the table"); } // Get a set of dependent tables. If empty proceed with the deletion of // the table, otherwise, raise an exception LinkedHashSet<TableInfo> dependentTables = new LinkedHashSet<TableInfo>(); this.getDependentTables(tableToRemove, dependentTables, request); if (dependentTables.size() > 0) { LinkedHashSet<BaseReportInfo> dependentReports = new LinkedHashSet<BaseReportInfo>(); for (TableInfo dependentTable : dependentTables) { dependentReports.addAll(dependentTable.getReports()); } throw new TableDependencyException( "Unable to remove table - other tables are linked to it, that need to be removed first", dependentTables, dependentReports); } // No dependencies exist so remove the table & its default report: BaseReportInfo defaultReport = tableToRemove.getDefaultReport(); this.removeReportWithoutChecks(sessionData, request, defaultReport, conn); // Remove any privileges on the table this.getAuthManager().removePrivilegesOnTable(request, tableToRemove); this.tableCache.remove(tableToRemove.getInternalTableName()); // Delete from persistent store HibernateUtil.currentSession().delete(tableToRemove); try { // Delete the table from the relational database. // The CASCADE is to drop the related sequence. // TODO: replace this with a specific sequence drop PreparedStatement statement = conn .prepareStatement("DROP TABLE " + tableToRemove.getInternalTableName() + " CASCADE"); statement.execute(); statement.close(); } catch (SQLException sqlex) { String errorCode = sqlex.getSQLState(); if (errorCode.equals("42P01")) { logger.warn("Can't delete table " + tableToRemove + " from relational database, it's not there"); // TODO: review why we're swallowing this error } else { throw new SQLException(sqlex + ": error code " + errorCode, sqlex); } } this.authManager.getCompanyForLoggedInUser(request).removeTable(tableToRemove); UsageLogger usageLogger = new UsageLogger(this.relationalDataSource); AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser()); usageLogger.logTableSchemaChange(user, tableToRemove, AppAction.REMOVE_TABLE, ""); UsageLogger.startLoggingThread(usageLogger); }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
/** * Updates the definition of a view within the DB. This method should only * be used if updateViewDbActionWithDropAndCreate and * updateViewDbActionWithCreateOrReplace fails. Drops any dependent views so * that 'report' can be updated. Once report has been updated, all dependent * views are recreated./* w w w . j ava 2 s .c o m*/ */ private void updateViewDbActionWithDropAndCreateDependencies(Connection conn, BaseReportInfo report, HttpServletRequest request) throws SQLException, ObjectNotFoundException, CodingErrorException, CantDoThatException { Savepoint savepoint = null; PreparedStatement statement = null; try { savepoint = conn.setSavepoint("dropAndCreateDependenciesSavepoint"); Map<String, List<String>> reportDependencyMap = new HashMap<String, List<String>>(); this.fillViewDependencyMap(conn, report.getInternalReportName(), reportDependencyMap, true); // Remove reports... List<String> deletedReports = new ArrayList<String>(); while (deletedReports.size() < reportDependencyMap.size()) { for (String reportInternalName : reportDependencyMap.keySet()) { if (!deletedReports.contains(reportInternalName)) { boolean cannotDelete = false; for (String dependentReportInternalName : reportDependencyMap.get(reportInternalName)) { if (!deletedReports.contains(dependentReportInternalName)) { cannotDelete = true; } } if (!cannotDelete) { PreparedStatement dropViewStatement = conn .prepareStatement("DROP VIEW " + reportInternalName); dropViewStatement.execute(); dropViewStatement.close(); deletedReports.add(reportInternalName); } } } } // Recreate reports... Collections.reverse(deletedReports); for (String reportInternalName : deletedReports) { TableInfo table = this.findTableContainingReportWithoutChecks(reportInternalName, request); HibernateUtil.activateObject(table); BaseReportInfo reportToRecreate = table.getReport(reportInternalName); String CreateViewSQL = "CREATE VIEW " + reportInternalName + " AS (" + reportToRecreate.getSQLForDetail() + ")"; statement = conn.prepareStatement(CreateViewSQL); statement.execute(); statement.close(); } } catch (SQLException sqlex) { conn.rollback(savepoint); throw new SQLException("The requested change would cause an error in the report: " + sqlex.getMessage() + ". SQL = " + statement, sqlex.getSQLState(), sqlex); } }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public TableInfo addTable(SessionDataInfo sessionData, HttpServletRequest request, Connection conn, String internalTableName, String internalDefaultReportName, String tableName, String internalPrimaryKeyName, String tableDesc) throws SQLException, DisallowedException, CantDoThatException, ObjectNotFoundException, CodingErrorException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.ADMINISTRATE))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.ADMINISTRATE); }//from ww w. j av a2 s . co m TableInfo newTable = new TableDefn(internalTableName, tableName, tableDesc); HibernateUtil.currentSession().save(newTable); try { String SQLCode = "CREATE TABLE " + newTable.getInternalTableName() + " ()"; PreparedStatement statement = conn.prepareStatement(SQLCode); statement.execute(); statement.close(); // Create an initial report for the table SimpleReportInfo defaultReport = new SimpleReportDefn(newTable, internalDefaultReportName, "Default report", "A simple report of all items in the '" + tableName + "' data store", null); // The true passed means it is the default report newTable.addReport(defaultReport, true); // Add an auto-generated primary key to act as a row identifier SequenceField primaryKeyField = new SequenceFieldDefn(newTable, internalPrimaryKeyName, "ID:" + tableName, PRIMARY_KEY_DESCRIPTION, FieldPrintoutSetting.NO_PRINTOUT); HibernateUtil.currentSession().save(primaryKeyField); newTable.addField(primaryKeyField); newTable.setPrimaryKey(primaryKeyField); this.addFieldToRelationalDb(conn, newTable, primaryKeyField); setPrimaryKeyDbAction(conn, newTable); // Update the default report to add the primary key ReportFieldInfo primaryKeyReportField = defaultReport.addTableField(primaryKeyField); // Sort the default report by primary key descending, i.e. show new // records at the top defaultReport.addSort(primaryKeyReportField, false); // Save default report definition to the database this.updateViewDbAction(conn, defaultReport, request); // Add hidden table fields this.addDateCreatedFieldToTable(conn, newTable); this.addCreatedByFieldToTable(conn, newTable); this.addLastModifiedFieldToTable(conn, newTable); this.addModifiedByFieldToTable(conn, newTable); this.addRecordLockedFieldToTable(conn, newTable); this.addViewCountFieldToTable(conn, newTable); this.addCommentsFeedFieldToTable(conn, newTable); } catch (SQLException sqlex) { // Reformat the error message to be more user friendly. // Use SQLState as an error identifier because it is standard across // databases String errorCode = sqlex.getSQLState(); if (errorCode.equals("42P07")) { // A table with that name already exists throw new SQLException( "The internal table name '" + newTable.getInternalTableName() + "' already exists", errorCode); } else if (errorCode.equals("42601")) { throw new SQLException("Table couldn't be created", sqlex); } else { throw new SQLException(sqlex + ": error code " + errorCode, sqlex); } } // Cache the table in the company object this.authManager.getCompanyForLoggedInUser(request).addTable(newTable); UsageLogger usageLogger = new UsageLogger(this.relationalDataSource); AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser()); usageLogger.logTableSchemaChange(user, newTable, AppAction.ADD_TABLE, ""); UsageLogger.startLoggingThread(usageLogger); return newTable; // this.dataManagement.logLastSchemaChangeTime(request); }
From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java
/** * Cette fonction permet d'ajouter une relation la table * hierarchicalRelationship//from w w w . j a v a 2 s . c om * * @param conn * @param hierarchicalRelationship * @param idUser * @return */ public boolean addLinkHierarchicalRelation(Connection conn, HierarchicalRelationship hierarchicalRelationship, int idUser) { // Connection conn; Statement stmt; try { //conn.setAutoCommit(false); // Get connection from pool // conn = ds.getConnection(); try { stmt = conn.createStatement(); try { if (!new RelationsHelper().addRelationHistorique(conn, hierarchicalRelationship.getIdConcept1(), hierarchicalRelationship.getIdThesaurus(), hierarchicalRelationship.getIdConcept2(), hierarchicalRelationship.getRole(), idUser, "ADD")) { conn.rollback(); conn.close(); return false; } String query = "Insert into hierarchical_relationship" + "(id_concept1, id_thesaurus, role, id_concept2)" + " values (" + "'" + hierarchicalRelationship.getIdConcept1() + "'" + ",'" + hierarchicalRelationship.getIdThesaurus() + "'" + ",'" + hierarchicalRelationship.getRole() + "'" + ",'" + hierarchicalRelationship.getIdConcept2() + "')"; stmt.executeUpdate(query); // conn.commit(); } finally { stmt.close(); } } finally { // conn.close(); } } catch (SQLException sqle) { // To avoid dupplicate Key // System.out.println(sqle.toString()); if (!sqle.getSQLState().equalsIgnoreCase("23505")) { return false; } } return true; }