Example usage for java.sql SQLException getLocalizedMessage

List of usage examples for java.sql SQLException getLocalizedMessage

Introduction

In this page you can find the example usage for java.sql SQLException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

@Override
public void refreshRows(SortedSet<Integer> rowsIndex) throws SQLException {
    try (Resource res = resultSetHolder.getResource()) {
        Set<Integer> batchIds = new HashSet<>();
        for (int refRowId : rowsIndex) {
            batchIds.add(refRowId / fetchSize);
            cache.remove(((long) refRowId));
        }//from   w w  w .j a v a2  s .c  o m
        for (int batchId : batchIds) {
            if (batchId < rowFetchFirstPk.size() && batchId >= 0) {
                rowFetchFirstPk.set(batchId, null);
            }
            if (batchId == currentBatchId) {
                currentBatchId = -1;
                currentBatch = new ArrayList<>(fetchSize + 1);
            }
        }
    } catch (SQLException ex) {
        LOGGER.warn(ex.getLocalizedMessage(), ex);
    }
}

From source file:controllers.Collections.java

public static Result getCollection(String table, GetRows callback) {
    Logger.debug("getCollection(" + table + ")");

    ObjectNode json = Json.newObject();// ww w .  j  a  va  2 s  . c  o  m
    ArrayNode payload = json.arrayNode();

    String query = "SELECT * FROM " + table + ";";
    Connection conn = DB.getConnection();
    PreparedStatement stmt;
    ResultSet rs;

    try {
        stmt = conn.prepareStatement(query);
    } catch (SQLException e) {
        json.put("success", false);
        json.put("message", "Internal Server Error");
        json.put("error_code", 1);

        Logger.error("[GET:" + table + "] Problem preparing statement!");

        return internalServerError(json);
    }

    try {
        rs = stmt.executeQuery();

        while (rs.next()) {
            ObjectNode rec = callback.getRows(rs);

            if (rec == null) {
                json.put("success", false);
                json.put("message", "Internal Server Error");
                json.put("error_code", 1);

                Logger.error("[GET:" + table + "] Problem in getRows callback.");

                return internalServerError(json);
            } else {
                payload.add(rec);
            }
        }

        json.put("success", true);
        json.put("message", "");
        json.put("error_code", "");
        json.put("payload", payload);

    } catch (SQLException e) {
        json.put("success", false);
        json.put("message", "Internal Server Error");
        json.put("error_code", 1);

        Logger.error("[GET:" + table + "] Problem executing query... " + e.getLocalizedMessage());

        return internalServerError(json);
    }

    try {
        conn.close();
    } catch (SQLException e) {

    }

    return ok(toJson(json));
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Disables auto-commit and closes {@code con}.
 *
 * @param con connection to be closed/*from w  ww  . ja v  a2  s.  c  o m*/
 * @throws DataSourceException
 */
protected void closeConnection(Connection con) throws DataSourceException {
    if (con != null) {
        try {
            try {
                con.setAutoCommit(true);
            } catch (SQLException e) {
                throw new DataSourceException(e.getLocalizedMessage());
            } finally {
                con.close();
            }
        } catch (SQLException e) {
            throw new DataSourceException(e.getLocalizedMessage());
        }
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Returns the number of elements fulfilling constraints in given table.
 *
 * @param table/*from   www .  java2s. c o  m*/
 * @param constraints
 * @return
 * @throws DataSourceException
 */
public int getNumberOfElements(String table, List<Constraint> constraints) throws DataSourceException {
    logger.debug("get number of elements for table " + table);
    try {
        Connection connection = dataSource.getConnection();
        try {
            String query = "SELECT COUNT(*) FROM " + table + toQuery(constraints);
            logger.debug("getNumberOfReaders: " + query);

            PreparedStatement stmt = connection.prepareStatement(query);
            try {
                fillInArguments(constraints, stmt);
                ResultSet rs = stmt.executeQuery();
                try {
                    // go to first row
                    if (rs.next()) {
                        int count = rs.getInt(1);
                        return count;
                    } else {
                        logger.error("SQL result has no row");
                        return 0;
                    }
                } finally {
                    rs.close();
                }
            } finally {
                stmt.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    }
}

From source file:swp.bibjsf.persistence.Data.java

@Override
public void deleteAll(List<? extends BusinessObject> elements) throws DataSourceException {
    logger.debug("delete all given elements");

    Connection con;/* w ww .  j  a va 2  s .  co m*/
    try {
        con = dataSource.getConnection();
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    }
    try {
        con.setAutoCommit(false);
        try {
            for (BusinessObject r : elements) {
                if (r instanceof Reader) {
                    deleteReader((Reader) r);
                } else if (r instanceof Book) {
                    deleteBook((Book) r);
                } else {
                    throw new DataSourceException("unhandled business object type in Data.deleteAll(): "
                            + r.getClass().getCanonicalName());
                }
            }
            con.commit();
            logger.debug("deletion finalized");
        } catch (SQLException e) {
            con.rollback();
            logger.error("deletion rolled back");
        }
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    } finally {
        closeConnection(con);
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Retrieves the column information from <code>table</code>.
 *
 * @param table/*w  w  w  . j  a  va  2s . com*/
 *            the name of the table whose columns need to be known
 * @return descriptors for each table column
 * @throws DataSourceException
 *             thrown in case of problems with the data source
 */
private ColumnDescriptor[] getColumns(String table) throws DataSourceException {
    final String query = "SELECT * from " + table;
    try {
        Connection connection = dataSource.getConnection();
        try {
            logger.debug("getColumns " + query);
            Statement stmt = connection.createStatement();
            try {
                ResultSet set = stmt.executeQuery(query);
                try {
                    final int numberOfColumns = set.getMetaData().getColumnCount();
                    ColumnDescriptor[] result = new ColumnDescriptor[numberOfColumns];
                    { // get columns
                        ResultSetMetaData metaData = set.getMetaData();
                        for (int column = 1; column <= numberOfColumns; column++) {
                            result[column - 1] = new ColumnDescriptor();
                            result[column - 1].type = metaData.getColumnType(column);
                            result[column - 1].label = metaData.getColumnLabel(column);
                        }
                    }
                    return result;
                } finally {
                    set.close();
                }
            } finally {
                stmt.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Resets database. If createAdmin, the admin role is created.
 *
 * @throws DataSourceException// w  w  w  .  jav a2s .  com
 */
private void reset(boolean createAdmin) throws DataSourceException {
    // TODO: this operation should be atomic
    try {
        run.update("DROP TABLE " + bookTableName);
    } catch (SQLException e) {
        throw new DataSourceException("reset failed with: " + e.getLocalizedMessage());
    }
    try {
        run.update("DROP TABLE " + groupTableName);
    } catch (SQLException e) {
        throw new DataSourceException("reset failed with: " + e.getLocalizedMessage());
    }
    try {
        run.update("DROP TABLE " + readerTableName);
    } catch (SQLException e) {
        throw new DataSourceException("reset failed with: " + e.getLocalizedMessage());
    }
    try {
        checkDatabaseStructure(createAdmin);
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Exports all rows in <code>table</code> to <code>out</code> in CSV format.
 *
 * @param out//from ww  w .ja v a 2s .  c  o m
 *            the output stream
 * @param table
 *            the name of the table to be exported
 * @throws DataSourceException
 *             thrown in case of problems with the data source
 */
public void export(OutputStream out, final String table) throws DataSourceException {
    final String query = "SELECT * from " + table;
    try {
        Connection connection = dataSource.getConnection();
        try {
            logger.debug("export " + query);
            Statement stmt = connection.createStatement();
            try {
                ResultSet set = stmt.executeQuery(query);
                try {
                    final PrintStream printer = newPrintStream(out);
                    final SimpleDateFormat df = new SimpleDateFormat(DATEFORMAT);
                    final int numberOfColumns = set.getMetaData().getColumnCount();
                    { // print header row
                        ResultSetMetaData metaData = set.getMetaData();
                        for (int column = 1; column <= numberOfColumns; column++) {
                            printer.print(quote(metaData.getColumnLabel(column)));
                            if (column < numberOfColumns) {
                                printer.print(DEFAULT_SEPARATOR);
                            }
                        }
                        printer.println();
                    }
                    // print data rows
                    while (set.next()) {
                        for (int column = 1; column <= numberOfColumns; column++) {
                            Object value = set.getObject(column);
                            if (value != null) {
                                // null should appear as empty string
                                if (value instanceof Date) {
                                    printer.print(quote(df.format((Date) value)));
                                } else {
                                    printer.print(quote(value.toString()));
                                }
                            }
                            if (column < numberOfColumns) {
                                printer.print(DEFAULT_SEPARATOR);
                            }
                        }
                        printer.println();
                    }
                } finally {
                    set.close();
                }
            } finally {
                stmt.close();
            }
        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        throw new DataSourceException(e.getLocalizedMessage());
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Returns all books that are stored in the database.
 *
 * @return list of books/*w ww.jav  a  2s .  c o m*/
 * @throws DataSourceException
 *             if there is a problem with the database.
 */
@Override
public final List<Book> getAllBooks() throws DataSourceException {
    logger.debug("get all books");
    try {
        ResultSetHandler<List<Book>> resultSetHandler = new BeanListHandler<Book>(Book.class);

        List<Book> books = run.query("SELECT * FROM " + bookTableName, resultSetHandler);
        return books;
    } catch (SQLException e) {
        logger.error("list books failure");
        throw new DataSourceException(e.getLocalizedMessage());
    }
}

From source file:swp.bibjsf.persistence.Data.java

/**
 * Update the book in the database in such way that the books
 * gets all the values of the book provided as parameter. A Book with the
 * same ID as the provided book must already exist. If the parameter is
 * {@code null}, a new {@code IllegalArgumentException} is thrown.
 *
 * @param book/*from w  w  w.  ja  v a  2 s. c  om*/
 *          the book with the updated values.
 *
 * @return {@code true}, if the update was successful,
 *         {@code false} otherwise.
 *             * @throws DataSourceException
 *             if there a problems with the database.
 */
@Override
public final int updateBook(final Book book) throws DataSourceException {
    logger.debug("update book");
    try {
        if (book == null) {
            logger.error("book was null, no update possible");
            throw new IllegalArgumentException(Messages.get("nobook"));
        }
        return update(bookTableName, book, "id", book.getId(), null, null);
    } catch (SQLException e) {
        logger.error("update book failure");
        throw new DataSourceException(e.getLocalizedMessage());
    }
}