Example usage for java.sql SQLException getMessage

List of usage examples for java.sql SQLException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:jongo.jdbc.JDBCExecutor.java

/**
 * Executes the given stored procedure or function in the RDBMS using the given List 
 * of {@link jongo.jdbc.StoredProcedureParam}.
 * @param database database name or schema where to execute the stored procedure or function
 * @param queryName the name of the stored procedure or function. This gets converted to a {call foo()} statement.
 * @param params a List of {@link jongo.jdbc.StoredProcedureParam} used by the stored procedure or function.
 * @return a List of {@link jongo.rest.xstream.Row} with the results of the stored procedure (if out parameters are given)
 * or the results of the function.//www  . j  a v a  2s.  c  o m
 * @throws SQLException
 */
public static List<Row> executeQuery(final String database, final String queryName,
        final List<StoredProcedureParam> params) throws SQLException {
    l.debug("Executing stored procedure " + database + "." + queryName);

    DatabaseConfiguration dbconf = conf.getDatabaseConfiguration(database);
    QueryRunner run = JDBCConnectionFactory.getQueryRunner(dbconf);
    final String call = JongoUtils.getCallableStatementCallString(queryName, params.size());
    List<Row> rows = new ArrayList<Row>();

    Connection conn = null;
    CallableStatement cs = null;
    try {
        l.debug("Obtain connection from datasource");
        conn = run.getDataSource().getConnection();

        l.debug("Create callable statement for " + call);
        cs = conn.prepareCall(call);

        l.debug("Add parameters to callable statement");
        final List<StoredProcedureParam> outParams = addParameters(cs, params);

        l.debug("Execute callable statement");
        if (cs.execute()) {
            l.debug("Got a result set " + queryName);
            ResultSet rs = cs.getResultSet();
            JongoResultSetHandler handler = new JongoResultSetHandler(true);
            rows = handler.handle(rs);
        } else if (!outParams.isEmpty()) {
            l.debug("No result set, but we are expecting OUT values from " + queryName);
            Map<String, String> results = new HashMap<String, String>();
            for (StoredProcedureParam p : outParams) {
                results.put(p.getName(), cs.getString(p.getIndex())); // thank $deity we only return strings
            }
            rows.add(new Row(0, results));
        }
    } catch (SQLException ex) {
        l.debug(ex.getMessage());
        throw ex;
    } finally {
        try {
            if (cs != null && !cs.isClosed())
                cs.close();
        } catch (SQLException ex) {
            l.debug(ex.getMessage());
        }
        try {
            if (conn != null && !conn.isClosed())
                conn.close();
        } catch (SQLException ex) {
            l.debug(ex.getMessage());
        }
    }
    l.debug("Received " + rows.size() + " results.");
    return rows;
}

From source file:bizlogic.Records.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st;//from w  ww . j  a va 2 s .  c  o m
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT userconf.log_list.sensor_id, " + "userconf.log_list.smpl_interval, "
                + "userconf.log_list.running, " + "userconf.log_list.name AS log_name, "
                + "userconf.log_list.log_id, " + "userconf.sensorlist.name AS sensor_name "
                + "FROM USERCONF.LOG_LIST " + "JOIN userconf.sensorlist "
                + "ON userconf.log_list.sensor_id=userconf.sensorlist.sensor_id");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Records.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }

    try {
        FileWriter recordsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/records.json");
        //BufferedWriter recordsFile = new BufferedWriter(_file);
        //recordsFile.write("");
        //recordsFile.flush(); 

        FileReader fr = new FileReader("/var/lib/tomcat8/webapps/ROOT/Records/records.json");
        BufferedReader br = new BufferedReader(fr);

        JSONObject Records = new JSONObject();

        int _total = 0;

        JSONArray recordList = new JSONArray();

        while (rs.next()) {

            String isRunningStr;

            JSONObject sensor_Obj = new JSONObject();

            int sensor_id = rs.getInt("sensor_id");
            sensor_Obj.put("sensor_id", sensor_id);

            String smpl_interval = rs.getString("smpl_interval");
            sensor_Obj.put("smpl_interval", smpl_interval);

            Boolean running = rs.getBoolean("running");
            if (running) {
                //System.out.print("1");
                isRunningStr = "ON";
            } else {
                //System.out.print("0");
                isRunningStr = "OFF";
            }
            sensor_Obj.put("running", isRunningStr);

            String log_name = rs.getString("log_name");
            sensor_Obj.put("log_name", log_name);

            String sensor_name = rs.getString("sensor_name");
            sensor_Obj.put("sensor_name", sensor_name);

            int log_id = rs.getInt("log_id");
            sensor_Obj.put("recid", log_id);

            recordList.add(sensor_Obj);
            _total++;

        }

        rs.close();

        Records.put("total", _total);
        Records.put("records", recordList);

        recordsFile.write(Records.toJSONString());
        recordsFile.flush();

        recordsFile.close();

        System.out.print(Records.toJSONString());
        System.out.print(br.readLine());

    }

    catch (IOException ex) {
        Logger.getLogger(Records.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.trackplus.ddl.DataReader.java

private static int getClobTableData(BufferedWriter writer, Connection connection) throws DDLException {
    Statement st = MetaDataBL.createStatement(connection);
    try {//from  w  w  w.  ja va2s . co  m
        ResultSet rs = st.executeQuery("SELECT * FROM TMSPROJECTEXCHANGE");
        int idx = 0;
        String[] columns = MetaDataBL.getColumnsMsProjectExchange();
        while (rs.next()) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < columns.length; i++) {
                String value = rs.getString(columns[i]);
                if (value != null && "FILECONTENT".equals(columns[i])) {
                    value = encodeBase64FileContent(value);
                }
                line.append(value);
                if (i < columns.length - 1) {
                    line.append(",");
                }
            }
            MetaDataBL.appendLine(writer, line.toString());
            idx++;
        }
        rs.close();
        return idx;
    } catch (SQLException ex) {
        throw new DDLException(ex.getMessage(), ex);
    }
}

From source file:com.trackplus.ddl.DataReader.java

private static void logDatabaseMetaDataInfo(DatabaseInfo databaseInfo, Connection connection)
        throws DDLException {
    DatabaseMetaData databaseMetaData = null;
    try {/*from   ww  w . java 2 s.  c o  m*/
        databaseMetaData = connection.getMetaData();
        int majorVersion = databaseMetaData.getDatabaseMajorVersion();
        int minorVersion = databaseMetaData.getDatabaseMinorVersion();
        String productName = databaseMetaData.getDatabaseProductName();
        String productVersion = databaseMetaData.getDatabaseProductVersion();
        int driverMajorVersion = databaseMetaData.getDriverMajorVersion();
        int driverMinorVersion = databaseMetaData.getDriverMinorVersion();

        LOGGER.debug("DB DRIVER=" + databaseInfo.getDriver());
        LOGGER.debug("DB URL=" + databaseInfo.getUrl());
        LOGGER.debug("DB USER=" + databaseInfo.getUser());
        String password = databaseInfo.getPassword() == null ? null
                : databaseInfo.getPassword().replaceAll(".", "*");
        LOGGER.debug("DB PASSWORD=" + password + "\n");

        LOGGER.debug("DB majorVersion=" + majorVersion);
        LOGGER.debug("DB minorVersion=" + minorVersion);
        LOGGER.debug("DB productName=" + productName);
        LOGGER.debug("DB productVersion=" + productVersion);
        LOGGER.debug("DB driverMajorVersion=" + driverMajorVersion);
        LOGGER.debug("DB driverMinorVersion=" + driverMinorVersion);
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }
}

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * Mark a user as no longer active in the database.
 *
 * @param ticket the ticket of the user/*from   w  ww.  jav a  2s.c  om*/
 * @throws javax.security.auth.login.LoginException
 *          if the function failed
 */
public static void logout(UserTicket ticket) throws LoginException {
    PreparedStatement ps = null;
    String curSql;
    Connection con = null;
    FxContext inf = FxContext.get();
    try {

        // Obtain a database connection
        con = Database.getDbConnection();

        // EJBLookup user in the database, combined with a update statement to make sure
        // nothing changes between the lookup/set ISLOGGEDIN flag.
        curSql = "UPDATE " + TBL_ACCOUNT_DETAILS + " SET ISLOGGEDIN=? WHERE ID=? AND APPLICATION=?";
        ps = con.prepareStatement(curSql);
        ps.setBoolean(1, false);
        ps.setLong(2, ticket.getUserId());
        ps.setString(3, inf.getApplicationId());

        // Not more than one row should be affected, or the logout failed
        final int rowCount = ps.executeUpdate();
        if (rowCount > 1) {
            // Logout failed.
            LoginException le = new LoginException("Logout for user [" + ticket.getUserId() + "] failed");
            LOG.error(le);
            throw le;
        }

    } catch (SQLException exc) {
        LoginException le = new LoginException("Database error: " + exc.getMessage());
        LOG.error(le);
        throw le;
    } finally {
        Database.closeObjects(FxDBAuthentication.class, con, ps);
    }
}

From source file:com.flexive.core.security.FxDBAuthentication.java

/**
 * @param username the username/*from   w w w .  j  a v  a2s .  com*/
 * @param password the password
 * @param currentTicket the UserTicket requesting the password match
 * @param ds thedatasource
 * @return returns true if the login and password match
 * @throws FxDbException on db errors
 * @throws FxLoginFailedException on authentication errors
 */
public static boolean checkLogin(String username, String password, UserTicket currentTicket, DataSource ds)
        throws FxDbException, FxLoginFailedException {
    FxContext inf = FxContext.get();

    // Avoid null pointer exceptions
    if (password == null)
        password = "";
    if (username == null)
        username = "";

    String curSql;
    PreparedStatement ps = null;
    Connection con = null;
    try {
        // Obtain a database connection
        con = ds.getConnection();
        //               1      2           3
        curSql = "SELECT a.ID,a.USERNAME,a.PASSWORD " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN "
                + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM "
                + TBL_ACCOUNT_DETAILS
                + " WHERE APPLICATION=?) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)";
        ps = con.prepareStatement(curSql);
        ps.setString(1, inf.getApplicationId());
        ps.setString(2, username);
        final ResultSet rs = ps.executeQuery();

        // Anything found
        if (rs == null || !rs.next())
            throw new FxLoginFailedException("Invalid user or password",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        // check if the hashed password matches the hash stored in the database
        final long id = rs.getLong(1);
        final String dbUserName = rs.getString(2);
        final String hashedPass = rs.getString(3);

        // current user authorised to perform the check (ticket user id matches db user id?)
        if (id != currentTicket.getUserId() && !currentTicket.isGlobalSupervisor())
            throw new FxLoginFailedException("User not authorized to perform login check",
                    FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED);

        return FxSharedUtils.hashPassword(id, dbUserName, password).equals(hashedPass)
                // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name
                || ("SUPERVISOR".equals(username)
                        && FxSharedUtils.hashPassword(id, "supervisor", password).equals(hashedPass));

    } catch (SQLException exc) {
        throw new FxDbException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR);
    } finally {
        Database.closeObjects(FxDBAuthentication.class, con, ps);
    }
}

From source file:com.taobao.tddl.jdbc.group.util.ExceptionUtils.java

public static void throwSQLException(SQLException exception, String sql, List<Object> args)
        throws SQLException {
    if (sql != null) {
        log.info(("TDDL SQL EXECUTE ERROR REPORTER:"
                + getErrorContext(sql, args, SQL_EXECUTION_ERROR_CONTEXT_MESSAGE)) + "nest Exceptions is "
                + exception.getMessage(), exception);
    }/*from   ww w .ja v a  2  s .co  m*/
    throw exception;
}

From source file:com.trackplus.ddl.DataWriter.java

private static void insertBlobData(Connection con, String line) throws DDLException {
    String sql = "INSERT INTO TBLOB(OBJECTID, BLOBVALUE, TPUUID) VALUES(?,?,?)";
    StringTokenizer st = new StringTokenizer(line, ",");
    Integer objectID = Integer.valueOf(st.nextToken());
    String base64Str = st.nextToken();
    byte[] bytes = Base64.decodeBase64(base64Str);
    String tpuid = null;//from   w  w w  .  jav  a  2s .c om
    if (st.hasMoreTokens()) {
        tpuid = st.nextToken();
    }

    try {
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setInt(1, objectID);
        preparedStatement.setBinaryStream(2, new ByteArrayInputStream(bytes), bytes.length);
        preparedStatement.setString(3, tpuid);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }
}

From source file:com.trackplus.ddl.DataReader.java

private static int getBlobTableData(BufferedWriter writer, Connection connection) throws DDLException {
    try {/*w  w w . ja  v a2 s.com*/
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM TBLOB");
        int idx = 0;
        while (rs.next()) {
            StringBuilder line = new StringBuilder();

            //OBJECTID
            String value = rs.getString("OBJECTID");
            line.append(value).append(",");

            //BLOBVALUE
            Blob blobValue = rs.getBlob("BLOBVALUE");
            if (blobValue != null) {
                String str = new String(Base64.encodeBase64(blobValue.getBytes(1l, (int) blobValue.length())));
                if (str.length() == 0) {
                    str = " ";
                }
                line.append(str);
            } else {
                line.append("null");
            }
            line.append(",");

            //TPUUID
            value = rs.getString("TPUUID");
            line.append(value);
            writer.write(line.toString());
            writer.newLine();
            idx++;
        }
        rs.close();
        return idx;
    } catch (SQLException ex) {
        throw new DDLException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new DDLException(ex.getMessage(), ex);
    }
}

From source file:net.pms.database.TableMusicBrainzReleases.java

/**
 * Looks up MBID in the table based on the given {@link Tag}. Never returns
 * <code>null</code>//from   w  w w . j a  v a2s  .c  om
 *
 * @param tag the {@link Tag} for whose values should be used in the search
 *
 * @return The result of the search, never <code>null</code>
 */
public static MusicBrainzReleasesResult findMBID(final CoverArtArchiveTagInfo tagInfo) {
    boolean trace = LOGGER.isTraceEnabled();
    MusicBrainzReleasesResult result;

    try (Connection connection = database.getConnection()) {
        String query = "SELECT MBID, MODIFIED FROM " + TABLE_NAME + constructTagWhere(tagInfo, false);

        if (trace) {
            LOGGER.trace("Searching for release MBID with \"{}\"", query);
        }

        tableLock.readLock().lock();
        try (Statement statement = connection.createStatement()) {
            try (ResultSet resultSet = statement.executeQuery(query)) {
                if (resultSet.next()) {
                    result = new MusicBrainzReleasesResult(true, resultSet.getTimestamp("MODIFIED"),
                            resultSet.getString("MBID"));
                } else {
                    result = new MusicBrainzReleasesResult(false, null, null);
                }
            }
        } finally {
            tableLock.readLock().unlock();
        }
    } catch (SQLException e) {
        LOGGER.error("Database error while looking up Music Brainz ID for \"{}\": {}", tagInfo, e.getMessage());
        LOGGER.trace("", e);
        result = new MusicBrainzReleasesResult();
    }

    return result;
}