List of usage examples for java.sql SQLException getErrorCode
public int getErrorCode()
SQLException
object. From source file:edu.mit.isda.permitservice.dataobjects.GeneralSelection.java
/** * retrieve a set of people based on a kerberos or last name * * @param criteriaXML XML string containing criteria information * @return a set of {@link Authorization} matching the specified criteria * @throws InvalidInputException If any of the parameters is NULL * @throws ObjectNotFoundException If no authorizations is found matching the criteria * @throws AuthorizationException in case of hibernate error *//*from w ww. java 2s. c o m*/ @SuppressWarnings("unchecked") public Collection<PersonRaw> listPersonRaw(String name, String search, String sort, String filter1, String filter2, String filter3) throws InvalidInputException, ObjectNotFoundException, PermissionException, AuthorizationException { if (name == null) throw new InvalidInputException(); HibernateTemplate t = getHibernateTemplate(); List alist = new ArrayList(); String last_only = "%"; String kerb_only = "%"; String both = "%"; String mitId = name; if (search.equals("kerberos")) { kerb_only = name; } else if (search.equals("last")) { last_only = name; } else if (search.equals("both")) { both = name; } if (name.endsWith("%")) { mitId = name.substring(0, name.length() - 1).trim(); } else { mitId = name.trim(); } System.out.println("******************* LAST: " + last_only); System.out.println("******************* KERB ID: " + kerb_only); System.out.println("******************* BOTH: " + both); System.out.println("******************* MIT ID: " + mitId); Collection people = null; try { if (sort.equals("last")) people = t.findByNamedQuery("QUICK_PERSON", new String[] { last_only, kerb_only, both, both, mitId, filter1, filter2, filter3 }); else if (sort.equals("kerberos")) people = t.findByNamedQuery("QUICK_PERSON_KERBSORT", new String[] { last_only, kerb_only, both, both, mitId, filter1, filter2, filter3 }); else if (sort.equals("type")) people = t.findByNamedQuery("QUICK_PERSON_TYPESORT", new String[] { last_only, kerb_only, both, both, mitId, filter1, filter2, filter3 }); else { people = t.findByNamedQuery("QUICK_PERSON", new String[] { last_only, kerb_only, both, both, mitId, filter1, filter2, filter3 }); } t.initialize(people); } catch (DataAccessException e) { Exception re = (Exception) e.getCause(); SQLException se = null; if (re instanceof org.hibernate.exception.SQLGrammarException) { se = ((org.hibernate.exception.SQLGrammarException) re).getSQLException(); } else if (e.getCause() instanceof SQLException) { se = (SQLException) e.getCause(); } if (null != se) { int i = se.getErrorCode(); String msg = se.getMessage(); String errorMessage = se.getMessage() + " Error Code: " + se.getErrorCode(); int index = msg.indexOf("\n"); if (index > 0) msg = msg.substring(0, index); if (i == InvalidInputException.FunctionCategoryInvalidLength || i == InvalidInputException.FunctionNameInvalidLength || i == InvalidInputException.NeedKerberosName || i == InvalidInputException.NeedFunctionCategory || i == InvalidInputException.InvalidFunction || i == InvalidInputException.QualifierTypeInvalidLength) throw new InvalidInputException(errorMessage, i); else if (i == PermissionException.ProxyNotAuthorized || i == PermissionException.ServerNotAuthorized) throw new PermissionException(errorMessage, i); else throw new AuthorizationException(errorMessage); } else throw new AuthorizationException(e.getMessage()); } return people; }
From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java
/** * Shutdown the database connections and cleanup. * //www. ja v a 2s.c om * @throws Exception if there are errors */ public void shutdown() throws Exception { // 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 + DATABASE_NAME + ";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)) { // throw new Exception("Error during database shutdown:", ex); // } } } finally { try { // Close our connection if (connection != null) { connection.close(); connection = null; } } catch (SQLException ex) { throw new Exception("Error closing connection:", ex); } } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java
@Override protected void dropTable(DbEntity entity) throws DatabaseEngineException { dropReferringFks(entity);/*from w w w . j a va2s . c om*/ Statement drop = null; try { drop = conn.createStatement(); final String query = format("DROP TABLE %s", quotize(entity.getName())); logger.trace(query); drop.executeUpdate(query); } catch (SQLException ex) { if (ex.getErrorCode() == TABLE_OR_VIEW_DOES_NOT_EXIST) { logger.debug("Table '{}' does not exist", entity.getName()); handleOperation(new OperationFault(entity.getName(), OperationFault.Type.TABLE_DOES_NOT_EXIST), ex); } else { throw new DatabaseEngineException("Error dropping table", ex); } } finally { try { if (drop != null) { drop.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.MySqlEngine.java
@Override protected void dropTable(DbEntity entity) throws DatabaseEngineException { dropReferringFks(entity);//from w w w. j a v a2 s. co m Statement drop = null; try { drop = conn.createStatement(); final String query = format("DROP TABLE %s", quotize(entity.getName(), escapeCharacter())); logger.trace(query); drop.executeUpdate(query); } catch (SQLException ex) { if (ex.getErrorCode() == TABLE_DOES_NOT_EXIST) { logger.debug(dev, "Table '{}' does not exist", entity.getName()); handleOperation(new OperationFault(entity.getName(), OperationFault.Type.TABLE_DOES_NOT_EXIST), ex); } else { throw new DatabaseEngineException("Error dropping table", ex); } } finally { try { if (drop != null) { drop.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java
@Override protected void dropColumn(DbEntity entity, String... columns) throws DatabaseEngineException { Statement drop = null;/* w w w .ja v a2 s . c o m*/ List<String> removeColumns = new ArrayList<String>(); removeColumns.add("ALTER TABLE"); removeColumns.add(quotize(entity.getName())); removeColumns.add("DROP COLUMN"); List<String> cols = new ArrayList<String>(); for (String col : columns) { cols.add(quotize(col)); } removeColumns.add(join(cols, ",")); try { drop = conn.createStatement(); final String query = join(removeColumns, " "); logger.trace(query); drop.executeUpdate(query); } catch (SQLException ex) { if (ex.getErrorCode() == TABLE_OR_VIEW_DOES_NOT_EXIST) { logger.debug(dev, "Table '{}' does not exist", entity.getName()); handleOperation(new OperationFault(entity.getName(), OperationFault.Type.COLUMN_DOES_NOT_EXIST), ex); } else { throw new DatabaseEngineException("Error dropping column", ex); } } finally { try { if (drop != null) { drop.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } }
From source file:jongo.RestController.java
/** * Method in charge of handling the possible exceptions thrown by the JDBCExecutor or any other * operation. The current implementation handles SQLException, JongoBadRequestException & * IllegalArgumentException to return different errors. For any other exception * a {@link jongo.rest.xstream.JongoError} with a 500 status code is returned. * @param t the exception to handle./*from w ww . j a va 2 s .c o m*/ * @param resource the name of the resource which is throwing the exception. * @return a {@link jongo.rest.xstream.JongoError} with different error codes depending * on the exception being handled. If we can't handle the exception, a 500 error code is used. */ private JongoResponse handleException(final Throwable t, final String resource) { JongoResponse response; StringBuilder b; if (t instanceof SQLException) { SQLException ex = (SQLException) t; b = new StringBuilder("Received a SQLException "); b.append(ex.getMessage()); b.append(" state ["); b.append(ex.getSQLState()); b.append("] & code ["); b.append(ex.getErrorCode()); b.append("]"); l.debug(b.toString()); response = new JongoError(resource, ex); } else if (t instanceof JongoBadRequestException) { b = new StringBuilder("Received a JongoBadRequestException "); b.append(t.getMessage()); l.debug(b.toString()); response = new JongoError(resource, Response.Status.BAD_REQUEST, t.getMessage()); } else if (t instanceof IllegalArgumentException) { b = new StringBuilder("Received an IllegalArgumentException "); b.append(t.getMessage()); l.debug(b.toString()); response = new JongoError(resource, Response.Status.BAD_REQUEST, t.getMessage()); } else { b = new StringBuilder("Received an Unhandled Exception "); b.append(t.getMessage()); l.error(b.toString()); response = new JongoError(resource, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
From source file:net.pms.dlna.DLNAMediaDatabase.java
public synchronized void updateThumbnail(String name, long modified, int type, DLNAMediaInfo media) { Connection conn = null;//from w ww . jav a 2s .co m PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement("UPDATE FILES SET THUMB = ? WHERE FILENAME = ? AND MODIFIED = ?"); ps.setString(2, name); ps.setTimestamp(3, new Timestamp(modified)); if (media != null) { ps.setBytes(1, media.getThumb()); } else { ps.setNull(1, Types.BINARY); } ps.executeUpdate(); } catch (SQLException se) { if (se.getErrorCode() == 23001) { logger.debug("Duplicate key while inserting this entry: " + name + " into the database: " + se.getMessage()); } else { logger.error(null, se); } } finally { close(ps); close(conn); } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.MySqlEngine.java
@Override protected void dropColumn(DbEntity entity, String... columns) throws DatabaseEngineException { Statement drop = null;// w ww.j a va 2s . co m List<String> removeColumns = new ArrayList<String>(); removeColumns.add("ALTER TABLE"); removeColumns.add(quotize(entity.getName(), escapeCharacter())); List<String> cols = new ArrayList<String>(); for (String col : columns) { cols.add("DROP COLUMN " + quotize(col, escapeCharacter())); } removeColumns.add(join(cols, ",")); try { drop = conn.createStatement(); final String query = join(removeColumns, " "); logger.trace(query); drop.executeUpdate(query); } catch (SQLException ex) { if (ex.getErrorCode() == TABLE_DOES_NOT_EXIST) { logger.debug(dev, "Table '{}' does not exist", entity.getName()); handleOperation(new OperationFault(entity.getName(), OperationFault.Type.COLUMN_DOES_NOT_EXIST), ex); } else { throw new DatabaseEngineException("Error dropping column", ex); } } finally { try { if (drop != null) { drop.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java
@Override protected void addIndexes(final DbEntity entity) throws DatabaseEngineException { List<DbIndex> indexes = entity.getIndexes(); for (DbIndex index : indexes) { List<String> createIndex = new ArrayList<String>(); createIndex.add("CREATE"); if (index.isUnique()) { createIndex.add("UNIQUE"); }//from w ww. j av a 2s . com createIndex.add("INDEX"); List<String> columns = new ArrayList<String>(); List<String> columnsForName = new ArrayList<String>(); for (String column : index.getColumns()) { columns.add(quotize(column)); columnsForName.add(column); } final String idxName = md5(format("%s_%s_IDX", entity.getName(), join(columnsForName, "_")), properties.getMaxIdentifierSize()); createIndex.add(quotize(idxName)); createIndex.add("ON"); createIndex.add(quotize(entity.getName())); createIndex.add("(" + join(columns, ", ") + ")"); final String statement = join(createIndex, " "); logger.trace(statement); Statement s = null; try { s = conn.createStatement(); s.executeUpdate(statement); } catch (SQLException ex) { if (ex.getErrorCode() == INDEX_ALREADY_EXISTS) { logger.debug(dev, "'{}' is already defined", idxName); handleOperation(new OperationFault(entity.getName(), OperationFault.Type.INDEX_ALREADY_EXISTS), ex); } else { throw new DatabaseEngineException("Something went wrong handling statement", ex); } } finally { try { if (s != null) { s.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java
@Override protected void addFks(DbEntity entity) throws DatabaseEngineException { for (DbFk fk : entity.getFks()) { final List<String> quotizedLocalColumns = new ArrayList<String>(); for (String s : fk.getLocalColumns()) { quotizedLocalColumns.add(quotize(s)); }/*www . j av a 2 s . c om*/ final List<String> quotizedForeignColumns = new ArrayList<String>(); for (String s : fk.getForeignColumns()) { quotizedForeignColumns.add(quotize(s)); } final String table = quotize(entity.getName()); final String quotizedLocalColumnsSting = join(quotizedLocalColumns, ", "); final String quotizedForeignColumnsString = join(quotizedForeignColumns, ", "); final String alterTable = format("ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)", table, quotize(md5("FK_" + table + quotizedLocalColumnsSting + quotizedForeignColumnsString, properties.getMaxIdentifierSize())), quotizedLocalColumnsSting, quotize(fk.getForeignTable()), quotizedForeignColumnsString); Statement alterTableStmt = null; try { alterTableStmt = conn.createStatement(); logger.trace(alterTable); alterTableStmt.executeUpdate(alterTable); } catch (SQLException ex) { if (ex.getErrorCode() == NAME_ALREADY_EXISTS) { logger.debug(dev, "Foreign key for table '{}' already exists. Error code: {}.", entity.getName(), ex.getErrorCode()); handleOperation( new OperationFault(entity.getName(), OperationFault.Type.FOREIGN_KEY_ALREADY_EXISTS), ex); } else { throw new DatabaseEngineException( format("Could not add Foreign Key to entity %s. Error code: %d.", entity.getName(), ex.getErrorCode()), ex); } } finally { try { if (alterTableStmt != null) { alterTableStmt.close(); } } catch (Exception e) { logger.trace("Error closing statement.", e); } } } }