List of usage examples for org.hibernate.exception ConstraintViolationException getSQL
public String getSQL()
From source file:de.micromata.genome.jpa.EmgrFactory.java
License:Apache License
/** * Convert exception./*from w w w. java2s . c o m*/ * * @param ex the ex * @return the runtime exception */ public static RuntimeException convertException(RuntimeException ex) { if (ex instanceof QueryTimeoutException) { // this is a oracle/hibernate bug workouround. // hibernate think this is is a query timeout, but should a DataException if (ex.getCause() instanceof org.hibernate.QueryTimeoutException) { org.hibernate.QueryTimeoutException qto = (org.hibernate.QueryTimeoutException) ex.getCause(); if (qto.getCause() instanceof SQLException) { SQLException sqlex = (SQLException) qto.getCause(); // ORA-12899 if (sqlex.getErrorCode() == 12899) { return new DataPersistenceException(ex.getMessage(), qto.getSQL(), sqlex.getSQLState(), ex); } } } } if (ex instanceof PersistenceException) { Throwable cause = ex.getCause(); if (cause instanceof ConstraintViolationException) { ConstraintViolationException cve = (ConstraintViolationException) cause; cve.getMessage(); String sql = cve.getSQL(); return new ConstraintPersistenceException(cve.getMessage(), sql, cve.getSQLState(), cve.getConstraintName(), ex); } else if (cause instanceof DataException) { DataException dex = (DataException) cause; return new DataPersistenceException(ex.getMessage(), dex.getSQL(), dex.getSQLState(), ex); } else if (cause instanceof PropertyValueException) { if (StringUtils.startsWith(cause.getMessage(), "not-null ") == true) { return new NullableConstraintPersistenceException(ex.getMessage(), ex); } } } return ex; }
From source file:edu.wustl.common.exceptionformatter.ConstraintViolationFormatter.java
License:BSD License
private String MySQLformatMessage(Exception objExcp, Object[] args) { Logger.out.debug(objExcp.getClass().getName()); if (objExcp instanceof gov.nih.nci.security.exceptions.CSTransactionException) { objExcp = (Exception) objExcp.getCause(); Logger.out.debug(objExcp); }//from w ww . jav a2 s. co m String dispTableName = null; String tableName = null; // stores Table_Name for which column name to be found String columnName = null; //stores Column_Name of table String formattedErrMsg = null; // Formatted Error Message return by this method Connection connection = null; if (args[0] != null) { tableName = (String) args[0]; } else { Logger.out.debug("Table Name not specified"); tableName = new String("Unknown Table"); } Logger.out.debug("Table Name:" + tableName); dispTableName = tableName; if (args.length > 2) { if (args[2] != null) { dispTableName = (String) args[2]; } else { Logger.out.debug("Table Name not specified"); dispTableName = tableName; } } try { //get Class name from message "could not insert [classname]" ConstraintViolationException cEX = (ConstraintViolationException) objExcp; String message = cEX.getMessage(); Logger.out.debug("message :" + message); int startIndex = message.indexOf("["); /** * Name : kalpana thakur * Reviewer Name : Vaishali * Bug ID: 4926 * Description:In case of Edit, get Class name from message "could not insert [classname #id]" */ int endIndex = message.indexOf("#"); if (endIndex == -1) { endIndex = message.indexOf("]"); } String className = message.substring((startIndex + 1), endIndex); Logger.out.debug("ClassName: " + className); Class classObj = Class.forName(className); // get table name from class tableName = HibernateMetaData.getRootTableName(classObj); /** * Name : kalpana thakur * Reviewer Name : Vaishali * Bug ID: 6034 * Description:To retrive the appropriate tablename checking the SQL" */ if (!(cEX.getSQL().contains(tableName))) { tableName = HibernateMetaData.getTableName(classObj); } } catch (Exception e) { Logger.out.error(e.getMessage(), e); } try { // Generate Error Message by appending all messages of previous cause Exceptions String sqlMessage = generateErrorMessage(objExcp); // From the MySQL error msg and extract the key ID // The unique key voilation message is "Duplicate entry %s for key %d" int key = -1; int indexofMsg = 0; indexofMsg = sqlMessage.indexOf(Constants.MYSQL_DUPL_KEY_MSG); indexofMsg += Constants.MYSQL_DUPL_KEY_MSG.length(); // Get the %d part of the string String strKey = sqlMessage.substring(indexofMsg, sqlMessage.length() - 1); key = Integer.parseInt(strKey); Logger.out.debug(String.valueOf(key)); // For the key extracted frm the string, get the column name on which the // costraint has failed boolean found = false; // get connection from arguments if (args[1] != null) { connection = (Connection) args[1]; } else { Logger.out.debug("Error Message: Connection object not given"); } // Get database metadata object for the connection DatabaseMetaData dbmd = connection.getMetaData(); // Get a description of the given table's indices and statistics ResultSet rs = dbmd.getIndexInfo(connection.getCatalog(), null, tableName, true, false); HashMap indexDetails = new HashMap(); StringBuffer columnNames = new StringBuffer(""); int indexCount = 1; String constraintVoilated = ""; while (rs.next()) { // In this loop, all the indexes are stored as key of the HashMap // and the column names are stored as value. Logger.out.debug("Key: " + indexCount); if (key == indexCount) { constraintVoilated = rs.getString("INDEX_NAME"); Logger.out.debug("Constraint: " + constraintVoilated); found = true; // column name for given key index found //break; } StringBuffer temp = (StringBuffer) indexDetails.get(rs.getString("INDEX_NAME")); if (temp != null) { temp.append(rs.getString("COLUMN_NAME")); temp.append(","); indexDetails.remove(rs.getString("INDEX_NAME")); indexDetails.put(rs.getString("INDEX_NAME"), temp); Logger.out.debug("Column :" + temp.toString()); } else { temp = new StringBuffer(rs.getString("COLUMN_NAME")); //temp.append(rs.getString("COLUMN_NAME")); temp.append(","); indexDetails.put(rs.getString("INDEX_NAME"), temp); } indexCount++; // increment record count*/ } Logger.out.debug("out of loop"); if (found) { columnNames = (StringBuffer) indexDetails.get(constraintVoilated); columnName = columnNames.toString(); Logger.out.debug("Column Name: " + columnNames.toString()); Logger.out.debug("Constraint: " + constraintVoilated); } rs.close(); // Create arrays of object containing data to insert in CONSTRAINT_VOILATION_ERROR Object[] arguments = new Object[2]; dispTableName = ExceptionFormatterFactory.getDisplayName(tableName, connection); arguments[0] = dispTableName; columnName = columnNames.toString(); columnName = columnName.substring(0, columnName.length()); arguments[1] = columnName; Logger.out.debug("Column Name: " + columnNames.toString()); // Insert Table_Name and Column_Name in CONSTRAINT_VOILATION_ERROR message formattedErrMsg = MessageFormat.format(Constants.CONSTRAINT_VOILATION_ERROR, arguments); } catch (Exception e) { Logger.out.error(e.getMessage(), e); formattedErrMsg = Constants.GENERIC_DATABASE_ERROR; } return formattedErrMsg; }
From source file:edu.wustl.common.util.Utility.java
License:BSD License
/** * Parse the exception object and find DB table name. * @param objExcp exception object./*from w w w . j a v a 2s. c om*/ * @throws Exception Exception * @return table Name. */ public static String parseException(Exception objExcp) throws Exception // NOPMD { LOGGER.debug(objExcp.getClass().getName()); String tableName = ""; if (objExcp instanceof gov.nih.nci.security.exceptions.CSTransactionException) { objExcp = (Exception) objExcp.getCause(); LOGGER.debug(objExcp); } /* if(args[0]!=null) { tableName = (String)args[0]; } * else {logger.debug("Table Name not specified"); tableName=new String("Unknown Table"); } logger.debug("Table Name:" + tableName);*/ //get Class name from message "could not insert [classname]" ConstraintViolationException cEX = (ConstraintViolationException) objExcp; String message = cEX.getMessage(); LOGGER.debug("message :" + message); int startIndex = message.indexOf("["); /** * Bug ID: 4926 * Description:In case of Edit, get Class name from message "could not insert [classname #id]" */ int endIndex = message.indexOf("#"); if (endIndex == -1) { endIndex = message.indexOf("]"); } String className = message.substring((startIndex + 1), endIndex); LOGGER.debug("ClassName: " + className); Class classObj = Class.forName(className); HibernateMetaData hibernateMetaData = HibernateMetaDataFactory .getHibernateMetaData(CommonServiceLocator.getInstance().getAppName()); tableName = hibernateMetaData.getRootTableName(classObj); // get table name from class /** * Bug ID: 6034 * Description:To retrive the appropriate tablename checking the SQL" */ if (!(cEX.getSQL().contains(tableName))) { tableName = hibernateMetaData.getTableName(classObj); Properties prop = new Properties(); prop.load( Thread.currentThread().getContextClassLoader().getResourceAsStream("tablemapping.properties")); if (prop.getProperty(tableName) != null) { tableName = prop.getProperty(tableName); // NOPMD } } return tableName; }
From source file:edu.wustl.dao.formatmessage.MysqlExceptionFormatter.java
License:BSD License
/** * @param objExcp :// w w w .j av a2 s. c om * @return : * @throws ClassNotFoundException : */ private String getTableName(Exception objExcp) throws ClassNotFoundException { String tableName; //get Class name from message "could not insert [class name]" ConstraintViolationException cEX = (ConstraintViolationException) objExcp; String message = objExcp.getMessage(); int startIndex = message.indexOf('['); int endIndex = message.indexOf('#'); if (endIndex == -1) { endIndex = message.indexOf(']'); } String className = message.substring((startIndex + 1), endIndex); Class classObj = Class.forName(className); // get table name from class tableName = HibernateMetaData.getRootTableName(classObj); if (!(cEX.getSQL().contains(tableName))) { tableName = HibernateMetaData.getTableName(classObj); } return tableName; }
From source file:jcms.integrationtier.exception.ConstraintViolationExceptionMySqlPatch.java
License:Open Source License
public ConstraintViolationExceptionMySqlPatch(ConstraintViolationException cve) { super(cve.getMessage(), cve.getSQLException(), cve.getSQL(), cve.getConstraintName()); this.constraintName = extractConstraintName(); }
From source file:motor.MOTOR.java
/** * Mtodo que elimina registros de una base de datos. Elimina un cliente * buscandolo por su identificador de coche.Utiliza operaciones elementales * * @param clienteId: el identificador del cliente a eliminar * @throws ExceptionMotor excepcion que integra el mensaje de error al * usuario, el codigo de error y el mensaje de error que nos ha devuelto la * base de datos// w w w .ja va 2s . c o m */ public void eliminarClientes(BigDecimal clienteId) throws ExceptionMotor { Transaction t = sesion.beginTransaction(); //Se crea un objeto Cliente transitorio Cliente cliente = new Cliente(clienteId, "", "", "", "", ""); try { sesion.delete(cliente); // Se confirma la transaccin t.commit(); } catch (StaleStateException ssEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setMensajeErrorUsuario("Error. El identificador de cliente no existe"); ex.setMensajeErrorAdministrador(ssEx.getMessage()); throw ex; } catch (ConstraintViolationException igEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(igEx.getErrorCode()); ex.setSentenciaSQL(igEx.getSQL()); ex.setMensajeErrorUsuario("Error. Hay coches asociados a este cliente"); ex.setMensajeErrorAdministrador(igEx.getMessage()); throw ex; } catch (Exception e) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(0); ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador"); ex.setMensajeErrorAdministrador(e.getMessage()); throw ex; } }
From source file:motor.MOTOR.java
/** * Mtodo que modifica los registros de un cliente ya existente. Utiliza * operaciones elementales/*from w w w . j av a2s . com*/ * * @param cliente los datos del coche a modificar * @throws ExceptionMotor excepcion que integra el mensaje de error al * usuario, el codigo de error y el mensaje de error que nos ha devuelto la * base de datos */ public void modificarCliente(Cliente cliente) throws ExceptionMotor { Transaction t = sesion.beginTransaction(); try { sesion.update(cliente); // Se confirma la transaccin t.commit(); } catch (ConstraintViolationException cvEx) { ExceptionMotor ex = new ExceptionMotor(); if (cvEx.getErrorCode() == 2290) { ex.setCodigoErrorAdministrador(cvEx.getErrorCode()); ex.setSentenciaSQL(cvEx.getSQL()); ex.setMensajeErrorUsuario( "Error. El campo telefono debe empezar por 6 o 9 y contener 9 caracteres numricos y el email debe acabar en .com o .es"); ex.setMensajeErrorAdministrador(cvEx.getMessage()); } else { ex.setCodigoErrorAdministrador(cvEx.getErrorCode()); ex.setSentenciaSQL(cvEx.getSQL()); ex.setMensajeErrorUsuario("Error. Los siguientes campos son unicos: dni, email y telefono"); ex.setMensajeErrorAdministrador(cvEx.getMessage()); } throw ex; } catch (PropertyValueException pvEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setMensajeErrorUsuario( "Error. Los siguientes campos son obligatorios: nombre, apellido1, email, telefono, dni"); ex.setMensajeErrorAdministrador(pvEx.getMessage()); throw ex; } catch (SQLGrammarException sqlEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(sqlEx.getErrorCode()); ex.setSentenciaSQL(sqlEx.getSQL()); ex.setMensajeErrorUsuario("Error. El telefono es un campo numerico"); ex.setMensajeErrorAdministrador(sqlEx.getMessage()); throw ex; } catch (GenericJDBCException jdbcEx) { ExceptionMotor ex = new ExceptionMotor(); if (jdbcEx.getErrorCode() == 20004) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. El taller esta cerrado"); ex.setMensajeErrorAdministrador(jdbcEx.getMessage()); } if (jdbcEx.getErrorCode() == 20005) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. El email debe acabar por .com o .es"); ex.setMensajeErrorAdministrador(jdbcEx.getMessage()); } if (jdbcEx.getErrorCode() == 20006) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. El campo telefono es un campo numerico de 9 caracteres"); ex.setMensajeErrorAdministrador(jdbcEx.getMessage()); } throw ex; } catch (StaleStateException ssEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setMensajeErrorUsuario("Error. No existe ese cliente"); throw ex; } catch (Exception e) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(0); ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador"); ex.setMensajeErrorAdministrador(e.getMessage()); throw ex; } }
From source file:motor.MOTOR.java
/** * Mtodo que inserta un registro en la tabla coche. Utiliza operaciones * elementales//w w w. j a v a 2s. c o m * * @param coche El objeto coche * @throws ExceptionMotor excepcion que integra el mensaje de error al * usuario, el codigo de error y el mensaje de error que nos ha devuelto la * base de datos */ public void insertarCoche(Coche coche) throws ExceptionMotor { // Se inicia una transaccin en la sesin creada Transaction t = sesion.beginTransaction(); try { sesion.save(coche); // Se confirma la transaccin t.commit(); } catch (PropertyValueException pvEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setMensajeErrorUsuario("Error. Todos los campos son obligatorios"); ex.setMensajeErrorAdministrador(pvEx.getMessage()); throw ex; } catch (ConstraintViolationException igEx) { ExceptionMotor ex = new ExceptionMotor(); if (igEx.getErrorCode() == 2291) { ex.setCodigoErrorAdministrador(igEx.getErrorCode()); ex.setSentenciaSQL(igEx.getSQL()); ex.setMensajeErrorUsuario("Error. No existe ese cliente"); ex.setMensajeErrorAdministrador("VIOLACION DE CHECK CONSTRAINT"); } else if (igEx.getErrorCode() == 1) { ex.setCodigoErrorAdministrador(igEx.getErrorCode()); ex.setSentenciaSQL(igEx.getSQL()); ex.setMensajeErrorUsuario("Error. Los siguientes campos son unicos: matricula"); ex.setMensajeErrorAdministrador("VIOLACION DE UNIQUE KEY"); } throw ex; } catch (GenericJDBCException gjdbcEx) { ExceptionMotor ex = new ExceptionMotor(); if (gjdbcEx.getErrorCode() == 20002) { ex.setCodigoErrorAdministrador(gjdbcEx.getErrorCode()); ex.setSentenciaSQL(gjdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. La ITV debe estar pasada"); ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER ITV_PASADA"); } if (gjdbcEx.getErrorCode() == 20004) { ex.setCodigoErrorAdministrador(gjdbcEx.getErrorCode()); ex.setSentenciaSQL(gjdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. El taller esta cerrado"); ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER TALLER_ABIERTO"); } throw ex; } catch (Exception e) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(0); ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador"); ex.setMensajeErrorAdministrador(e.getMessage()); throw ex; } }
From source file:motor.MOTOR.java
/** * Mtodo que modifica los datos de un coche ya existente. Usa HQL * parametrizado/*from w ww . j a v a 2s . c o m*/ * * @return el numero de registros afectados * @param coche el objeto coche con los datos a modificar * @throws ExceptionMotor excepcion que integra el mensaje de error al * usuario, el codigo de error y el mensaje de error que nos ha devuelto la * base de datos */ public int modificarCoche(Coche coche) throws ExceptionMotor { int registrosAfectados = -1; // Se inicia una transaccin en la sesin creada Transaction t = sesion.beginTransaction(); // Se crea la query HQL Query q = sesion.createQuery("update Coche set cliente.clienteId = :coclienteId," + "marca = :comarca, modelo = :comodelo, matricula = :comatricula , " + "itv = :coitv " + "where cocheId = :cococheId"); q.setString("comarca", coche.getMarca()); q.setString("comodelo", coche.getModelo()); q.setString("comatricula", coche.getMatricula()); q.setDate("coitv", coche.getItv()); q.setBigDecimal("cococheId", coche.getCocheId()); q.setBigDecimal("coclienteId", coche.getCliente().getClienteId()); try { // Se ejecuta la query q registrosAfectados = q.executeUpdate(); // Se confirma la transaccin t.commit(); } catch (GenericJDBCException jdbcEx) { ExceptionMotor ex = new ExceptionMotor(); if (jdbcEx.getErrorCode() == 2291) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. No existe ese ciente"); ex.setMensajeErrorAdministrador("NO SE HA INTRODUCIDO UN COCHE_ID QUE EXISTA"); } if (jdbcEx.getErrorCode() == 1407) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario( "Error. Los siguientes campos son obligastorios: marca, modelo, matricula, itv"); ex.setMensajeErrorAdministrador("VIOLACION DE NOT_NULL"); } if (jdbcEx.getErrorCode() == 20002) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. La ITV debe estar pasada"); ex.setMensajeErrorAdministrador("VILACION DE TRIGGER ITV_PASADA"); } if (jdbcEx.getErrorCode() == 20004) { ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode()); ex.setSentenciaSQL(jdbcEx.getSQL()); ex.setMensajeErrorUsuario("Error. El taller esta cerrado"); ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER TALLER ABIERTO"); } throw ex; } catch (ConstraintViolationException cvEx) { ExceptionMotor ex = new ExceptionMotor(); if (cvEx.getErrorCode() == 1) { ex.setCodigoErrorAdministrador(cvEx.getErrorCode()); ex.setSentenciaSQL(cvEx.getSQL()); ex.setMensajeErrorUsuario("Error. El campo matricula es unico"); ex.setMensajeErrorAdministrador("VIOLACION DE UNIQUE KEY"); } throw ex; } catch (StaleStateException ssEx) { ExceptionMotor ex = new ExceptionMotor(); ex.setMensajeErrorUsuario("Error. No existe ese coche"); ex.setMensajeErrorAdministrador("SE HA INTRODUCIDO UN COCHE_ID QUE NO EXISTE"); throw ex; } catch (Exception e) { ExceptionMotor ex = new ExceptionMotor(); ex.setCodigoErrorAdministrador(0); ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador"); ex.setMensajeErrorAdministrador(e.getMessage()); throw ex; } return registrosAfectados; }
From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java
License:Open Source License
/** * Refines the data integrity violation exception to determine the translation * key from which the user message will be constructed. * * @param exception/*from www . ja v a2 s.com*/ * the DataIntegrityViolationException. * @return the translation key to use. */ protected String refineIntegrityViolationTranslationKey(DataIntegrityViolationException exception) { if (exception.getCause() instanceof ConstraintViolationException) { ConstraintViolationException cve = (ConstraintViolationException) exception.getCause(); if (cve.getSQL() != null && cve.getSQL().toUpperCase().contains("DELETE")) { return "error.fk.delete"; } if (cve.getConstraintName() != null) { if (cve.getConstraintName().toUpperCase().contains("FK")) { return "error.fk.update"; } return "error.unicity"; } return "error.integrity"; } return "error.integrity"; }