Example usage for java.sql ResultSet isBeforeFirst

List of usage examples for java.sql ResultSet isBeforeFirst

Introduction

In this page you can find the example usage for java.sql ResultSet isBeforeFirst.

Prototype

boolean isBeforeFirst() throws SQLException;

Source Link

Document

Retrieves whether the cursor is before the first row in this ResultSet object.

Usage

From source file:com.github.heartsemma.enderauth.Database.java

/**
 * @param uuid (Universally Unique Identifier)
 * @return The Pre-Shared Key of the user for their TOTP authentication.
 * //from  w w w. ja v a2  s  .c  o m
 * <br><br>Returns the TOTP Pre-Shared Key connected with the specified UUID.
 * <br>Returns null if unable to retrieve the key (if not found or  
 * 
 * @throws SQLException This function accesses the database via a "SELECT" query.
 * @throws DatabaseException Thrown if the returned ResultSet contains missing or what should be erroneous data.
 */
public String getTotpKey(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to retrieve TOTP PSK for user " + new String(uuid) + ".");

    String getKeyCommand = "SELECT ? FROM ? WHERE ? == ?";

    ArrayList<Object> getKeyVariables = new ArrayList<Object>();
    getKeyVariables.add(userTableTotpPSKColumn);
    getKeyVariables.add(userTableName);
    getKeyVariables.add(userTableIDColumn);
    getKeyVariables.add(uuid);

    ResultSet selection = transact(getKeyCommand, getKeyVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    //There should be one String in this resultset, but we will check it good because EnderAuth is stronk, EnderAuth is reliable.
    logger.debug("Error checking...");
    Preconditions.checkNotNull(selection);

    if (!selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement' .");

        throw new DatabaseException("getTotpKey()'s PreparedStatement returned a ResultSet that had no data.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There was no entry for this user.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error("Does " + new String(uuid) + " have an entry in the " + userTableName + " table?");

        //Returns null because we were unable to get the required data.
        throw new UUIDNotFoundException(
                "getTotpKey() was unable to find the entry in the database with the specified UUID.");

    } else if (selection.getRow() == 2) { //There was one entry for this user
        //If we get to this point, everything looks tight.   
        logger.debug("Successfully retrieved PSK from user " + new String(uuid) + ".");

        String PSK = selection.getString(userTableTotpPSKColumnIndex);
        return PSK;

    } else { //There was more than one entry for this user.
        logger.error("EnderAuth searched for " + new String(uuid)
                + "'s PSK and found multiple entries for that user in the database.");
        logger.error(
                "This should not have happened and indicates either plugin glitches or malcious database tampering.");

        throw new DatabaseException("Multiple entries matching the specified UUID were found in the database.");
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dao.users.PgUsers.java

/**
 * findOne helper method to ensure that only one result matches the search criteria.
 * /*ww w . j a v  a 2  s.c  om*/
 * @param results
 *            - from a jdbc database search
 * @return a single user that matches the search criteria or null of no matches found.
 * @throws SQLException
 *             - if a db error occurs
 * @throws SegueDatabaseException
 *             - if more than one result is returned
 */
private RegisteredUser findOneUser(final ResultSet results) throws SQLException, SegueDatabaseException {
    // are there any results
    if (!results.isBeforeFirst()) {
        return null;
    }

    List<RegisteredUser> listOfResults = Lists.newArrayList();
    while (results.next()) {
        listOfResults.add(buildRegisteredUser(results));
    }

    if (listOfResults.size() > 1) {
        throw new SegueDatabaseException(
                "Ambiguous result, expected single result and found more than one" + listOfResults);
    }

    return listOfResults.get(0);
}

From source file:ips1ap101.lib.core.db.util.Exporter.java

private static ExporterMessage export(String informe, Long rastro, Object usuario, String destino,
        EnumFormatoArchivo tipo, String select, boolean restringido, Object[] args, boolean logging) {
    Bitacora.trace(Exporter.class, "export", informe, rastro, destino, tipo);
    Bitacora.trace(trimToDefaultSelect(select));
    Utils.traceObjectArray(args);/*  w w  w.  ja va  2 s .c om*/
    UsuarioActual usuarioActual = usuario instanceof UsuarioActual ? (UsuarioActual) usuario : null;
    Long userid = usuarioActual == null ? usuario instanceof Long ? (Long) usuario : null
            : usuarioActual.getIdUsuario();
    //      String usercode = usuarioActual == null ? null : usuarioActual.getCodigoUsuario();
    //      String username = usuarioActual == null ? null : usuarioActual.getCodigoUsuario();
    String report = BaseBundle.getName(informe);
    String target = trimToNullTarget(destino);
    String format = getExportFormat(tipo);
    ResultSet resultSet = null;
    //      String archivo = logging ? getLogFileName(rastro) : null;
    String archivo = null;
    CondicionEjeFunEnumeration condicion = CondicionEjeFunEnumeration.EJECUCION_EN_PROGRESO;
    String mensaje = TLC.getBitacora().info(CBM.EXPORT_EXECUTION_BEGIN, report);
    boolean ok = Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje);
    if (ok) {
        try {
            //              if (!restringido) {
            //                  JasperReport jasperReport = Reporter.getJasperReport(report);
            //                  select = jasperReport == null ? select : Utils.replaceWhereClause(jasperReport.getQuery().getText(), select);
            //              }
            if (StringUtils.isBlank(select)) {
                String vista = BaseBundle.getNombreVistaFuncionExport(informe);
                if (StringUtils.isNotBlank(vista)) {
                    select = "select * from " + vista;
                }
            }
            if (StringUtils.isBlank(select)) {
                condicion = CondicionEjeFunEnumeration.EJECUTADO_CON_ERRORES;
                mensaje = TLC.getBitacora().error(CBM.ERROR_COMANDO_SELECT);
            } else {
                int limite = getLimiteFilasFuncionSelect(informe, usuarioActual);
                resultSet = TLC.getAgenteSql().executeQuery(select, limite, args);
                if (resultSet.isBeforeFirst()) {
                    archivo = export(resultSet, report, target, format, userid);
                    condicion = CondicionEjeFunEnumeration.EJECUTADO_SIN_ERRORES;
                    mensaje = TLC.getBitacora().warn(CBM.EXPORT_EXECUTION_END, report);
                } else {
                    condicion = CondicionEjeFunEnumeration.EJECUTADO_SIN_ERRORES;
                    mensaje = TLC.getBitacora().error(CBM.SELECT_ROW_EMPTY_SET, report);
                }
            }
        } catch (Exception ex) {
            condicion = CondicionEjeFunEnumeration.EJECUTADO_CON_ERRORES;
            mensaje = ThrowableUtils.getString(ex);
            TLC.getBitacora().fatal(ex);
            TLC.getBitacora().fatal(CBM.EXPORT_EXECUTION_ABEND, report);
        } finally {
            Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje);
            DB.close(resultSet);
        }
    } else {
        condicion = CondicionEjeFunEnumeration.EJECUCION_CANCELADA;
        mensaje = TLC.getBitacora().error(CBM.PROCESS_EXECUTION_ABEND, report);
    }
    ExporterMessage message = new ExporterMessage(report);
    message.setDestino(target);
    message.setTipo(tipo);
    message.setSelect(select);
    message.setArgs(args);
    message.setRastro(rastro);
    message.setCondicion(condicion);
    message.setArchivo(archivo);
    message.setMensaje(mensaje);
    return message;
}

From source file:ua.aits.Carpath.model.ArticleModel.java

public Boolean isHaveArticle(String id) throws SQLException {
    ResultSet result = DB.getResultSet("SELECT * FROM menu WHERE parentId=" + id + ";");
    Boolean res = result.isBeforeFirst();
    DB.closeCon();/*from  ww w  .  ja  va2s.  c o m*/
    return res;
}

From source file:org.sleuthkit.autopsy.casemodule.SingleUserCaseConverter.java

/**
 * Import the database from SQLite to PostgreSQL. Do not change any of the
 * data while loading it over. Fixing paths is done once the database is
 * completely imported.//w ww .  j a  v  a  2  s  .c  o m
 *
 * @param icd the Import Case Data for the current case
 *
 * @throws Exception
 * @throws SQLException
 * @throws ClassNotFoundException
 */
private static void importDb(ImportCaseData icd) throws SQLException, ClassNotFoundException, Exception {
    // deconflict the database name
    deconflictDatabaseName(icd);

    // Create a new database via SleuthkitCase
    SleuthkitCase newCase = SleuthkitCase.newCase(icd.getPostgreSQLDbName(), icd.getDb(),
            icd.getCaseOutputFolder().toString());
    newCase.close();

    /// Migrate from SQLite to PostgreSQL
    Class.forName("org.sqlite.JDBC"); //NON-NLS
    Connection sqliteConnection = getSQLiteConnection(icd);
    Connection postgreSQLConnection = getPostgreSQLConnection(icd);

    // blackboard_artifact_types        
    Statement inputStatement = sqliteConnection.createStatement();
    ResultSet inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifact_types"); //NON-NLS
    Statement outputStatement;
    Statement numberingPK;
    long biggestPK = 0;

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            Statement check = postgreSQLConnection.createStatement();
            ResultSet checkResult = check
                    .executeQuery("SELECT * FROM blackboard_artifact_types WHERE artifact_type_id=" + value
                            + " AND type_name LIKE '" + inputResultSet.getString(2)
                            + "' AND display_name LIKE '" + inputResultSet.getString(3) + "'"); //NON-NLS
            if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                String sql = "INSERT INTO blackboard_artifact_types (artifact_type_id, type_name, display_name) VALUES (" //NON-NLS
                        + value + ", '" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "',"
                        + " ? )"; //NON-NLS
                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 3, 1);
                pst.executeUpdate();
            }
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute(
            "ALTER SEQUENCE blackboard_artifact_types_artifact_type_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // blackboard_attribute_types
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_attribute_types"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            Statement check = postgreSQLConnection.createStatement();
            ResultSet checkResult = check
                    .executeQuery("SELECT * FROM blackboard_attribute_types WHERE attribute_type_id=" + value
                            + " AND type_name LIKE '" + inputResultSet.getString(2)
                            + "' AND display_name LIKE '" + inputResultSet.getString(3) + "'"); //NON-NLS
            if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                String sql = "INSERT INTO blackboard_attribute_types (attribute_type_id, type_name, display_name) VALUES (" //NON-NLS
                        + value + ", '" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "',"
                        + " ? )"; //NON-NLS

                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 3, 1);
                pst.executeUpdate();
            }
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute(
            "ALTER SEQUENCE blackboard_attribute_types_attribute_type_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_objects
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_objects"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement.executeUpdate("INSERT INTO tsk_objects (obj_id, par_obj_id, type) VALUES (" //NON-NLS
                    + value + "," + getNullableLong(inputResultSet, 2) + "," + inputResultSet.getInt(3) + ")"); //NON-NLS
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_objects_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_image_names, no primary key
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_image_names"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            outputStatement.executeUpdate("INSERT INTO tsk_image_names (obj_id, name, sequence) VALUES (" //NON-NLS
                    + inputResultSet.getLong(1) + ",'" + inputResultSet.getString(2) + "',"
                    + inputResultSet.getInt(3) + ")"); //NON-NLS
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }

    // tsk_image_info
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_image_info"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_image_info (obj_id, type, ssize, tzone, size, md5, display_name) VALUES (" //NON-NLS
                    + value + "," + getNullableInt(inputResultSet, 2) + "," + getNullableInt(inputResultSet, 3)
                    + "," + " ? ," + getNullableLong(inputResultSet, 5) + "," + " ? ," + " ? )"; //NON-NLS

            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 4, 1);
            populateNullableString(pst, inputResultSet, 6, 2);
            populateNullableString(pst, inputResultSet, 7, 3);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_image_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_fs_info
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_fs_info"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_fs_info (obj_id, img_offset, fs_type, block_size, block_count, root_inum, first_inum, last_inum, display_name) VALUES (" //NON-NLS
                    + value + "," + inputResultSet.getLong(2) + "," + inputResultSet.getInt(3) + ","
                    + inputResultSet.getLong(4) + "," + inputResultSet.getLong(5) + ","
                    + inputResultSet.getLong(6) + "," + inputResultSet.getLong(7) + ","
                    + inputResultSet.getLong(8) + "," + " ? )"; //NON-NLS

            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 9, 1);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_fs_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_files_path
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_path"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }

            // If the entry contains an encoding type, copy it. Otherwise use NONE.
            // The test on column count can be removed if we upgrade the database before conversion.
            int encoding = TskData.EncodingType.NONE.getType();
            ResultSetMetaData rsMetaData = inputResultSet.getMetaData();
            if (rsMetaData.getColumnCount() == 3) {
                encoding = inputResultSet.getInt(3);
            }
            outputStatement.executeUpdate("INSERT INTO tsk_files_path (obj_id, path, encoding_type) VALUES (" //NON-NLS
                    + value + ", '" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "', "
                    + encoding + ")"); //NON-NLS
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_files_path_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_files
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_files (obj_id, fs_obj_id, attr_type, attr_id, name, meta_addr, meta_seq, type, has_layout, has_path, dir_type, meta_type, dir_flags, meta_flags, size, ctime, crtime, atime, mtime, mode, uid, gid, md5, known, parent_path) VALUES (" //NON-NLS
                    + value + "," + getNullableLong(inputResultSet, 2) + "," + getNullableInt(inputResultSet, 3)
                    + "," + getNullableInt(inputResultSet, 4) + ",'"
                    + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(5)) + "',"
                    + getNullableLong(inputResultSet, 6) + "," + getNullableLong(inputResultSet, 7) + ","
                    + getNullableInt(inputResultSet, 8) + "," + getNullableInt(inputResultSet, 9) + ","
                    + getNullableInt(inputResultSet, 10) + "," + getNullableInt(inputResultSet, 11) + ","
                    + getNullableInt(inputResultSet, 12) + "," + getNullableInt(inputResultSet, 13) + ","
                    + getNullableInt(inputResultSet, 14) + "," + getNullableLong(inputResultSet, 15) + ","
                    + getNullableLong(inputResultSet, 16) + "," + getNullableLong(inputResultSet, 17) + ","
                    + getNullableLong(inputResultSet, 18) + "," + getNullableLong(inputResultSet, 19) + ","
                    + getNullableInt(inputResultSet, 20) + "," + getNullableInt(inputResultSet, 21) + ","
                    + getNullableInt(inputResultSet, 22) + "," + " ? ," + getNullableInt(inputResultSet, 24)
                    + "," + " ? )"; //NON-NLS

            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 23, 1);
            populateNullableString(pst, inputResultSet, 25, 2);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_files_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_file_layout, no primary key
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_file_layout"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            outputStatement.executeUpdate(
                    "INSERT INTO tsk_file_layout (obj_id, byte_start, byte_len, sequence) VALUES (" //NON-NLS
                            + inputResultSet.getLong(1) + "," + inputResultSet.getLong(2) + ","
                            + inputResultSet.getLong(3) + "," + inputResultSet.getInt(4) + ")"); //NON-NLS
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }

    // tsk_db_info, no primary key
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_db_info"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            Statement check = postgreSQLConnection.createStatement();
            ResultSet checkResult = check.executeQuery("SELECT * FROM tsk_db_info WHERE schema_ver="
                    + inputResultSet.getInt(1) + " AND tsk_ver=" + inputResultSet.getInt(2)); //NON-NLS
            if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                outputStatement.executeUpdate("INSERT INTO tsk_db_info (schema_ver, tsk_ver) VALUES (" //NON-NLS
                        + getNullableInt(inputResultSet, 1) + "," + getNullableInt(inputResultSet, 2) + ")"); //NON-NLS
            }
        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }

    // tag_names
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tag_names"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tag_names (tag_name_id, display_name, description, color) VALUES (" //NON-NLS
                    + value + "," + " ? ,'" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(3))
                    + "','" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(4)) + "')"; //NON-NLS

            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 2, 1);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tag_names_tag_name_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // reports
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM reports"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement.executeUpdate(
                    "INSERT INTO reports (report_id, path, crtime, src_module_name, report_name) VALUES (" //NON-NLS
                            + value + ", '" + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2))
                            + "'," + inputResultSet.getInt(3) + ",'"
                            + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(4)) + "','"
                            + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(5)) + "')"); //NON-NLS

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE reports_report_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // blackboard_artifacts
    biggestPK = Long.MIN_VALUE; // This table uses very large negative primary key values, so start at Long.MIN_VALUE
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifacts"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement.executeUpdate(
                    "INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_type_id) VALUES (" //NON-NLS
                            + value + "," + inputResultSet.getLong(2) + "," + inputResultSet.getLong(3) + ")"); //NON-NLS

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE blackboard_artifacts_artifact_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // blackboard_attributes, no primary key
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_attributes"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            String sql = "INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_byte, value_text, value_int32, value_int64, value_double) VALUES (" //NON-NLS
                    + inputResultSet.getLong(1) + "," + inputResultSet.getLong(2) + "," + " ? ," + " ? ,"
                    + inputResultSet.getLong(5) + "," + inputResultSet.getInt(6) + "," + " ? ," + " ? ,"
                    + getNullableInt(inputResultSet, 9) + "," + getNullableLong(inputResultSet, 10) + ","
                    + " ? )"; //NON-NLS
            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 3, 1);
            populateNullableString(pst, inputResultSet, 4, 2);
            populateNullableByteArray(pst, inputResultSet, 7, 3);
            populateNullableString(pst, inputResultSet, 8, 4);
            populateNullableNumeric(pst, inputResultSet, 11, 5);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }

    // tsk_vs_parts
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_vs_parts"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_vs_parts (obj_id, addr, start, length, descr, flags) VALUES (" //NON-NLS
                    + value + "," + inputResultSet.getLong(2) + "," + inputResultSet.getLong(3) + ","
                    + inputResultSet.getLong(4) + "," + " ? ," + inputResultSet.getInt(6) + ")"; //NON-NLS
            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 5, 1);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_vs_parts_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_vs_info
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_vs_info"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement
                    .executeUpdate("INSERT INTO tsk_vs_info (obj_id, vs_type, img_offset, block_size) VALUES (" //NON-NLS
                            + value + "," + inputResultSet.getInt(2) + "," + inputResultSet.getLong(3) + ","
                            + inputResultSet.getLong(4) + ")"); //NON-NLS

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_vs_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_files_derived 
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_derived"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_files_derived (obj_id, derived_id, rederive) VALUES (" //NON-NLS
                    + value + "," + inputResultSet.getLong(2) + "," + " ? )"; //NON-NLS
            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 3, 1);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE tsk_files_derived_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // tsk_files_derived_method
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_derived_method"); //NON-NLS

    while (inputResultSet.next()) {
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            String sql = "INSERT INTO tsk_files_derived_method (derived_id, tool_name, tool_version, other) VALUES (" //NON-NLS
                    + value + ", '" + inputResultSet.getString(2) + "','" + inputResultSet.getString(3) + "',"
                    + " ? )"; //NON-NLS
            PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
            populateNullableString(pst, inputResultSet, 4, 1);
            pst.executeUpdate();

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK
            .execute("ALTER SEQUENCE tsk_files_derived_method_derived_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // content_tags
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM content_tags"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement.executeUpdate(
                    "INSERT INTO content_tags (tag_id, obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset) VALUES (" //NON-NLS
                            + value + "," + inputResultSet.getLong(2) + "," + inputResultSet.getLong(3) + ",'"
                            + inputResultSet.getString(4) + "'," + inputResultSet.getLong(5) + ","
                            + inputResultSet.getLong(6) + ")"); //NON-NLS

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE content_tags_tag_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    // blackboard_artifact_tags
    biggestPK = 0;
    inputStatement = sqliteConnection.createStatement();
    inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifact_tags"); //NON-NLS

    while (inputResultSet.next()) {
        outputStatement = postgreSQLConnection.createStatement();
        try {
            long value = inputResultSet.getLong(1);
            if (value > biggestPK) {
                biggestPK = value;
            }
            outputStatement.executeUpdate(
                    "INSERT INTO blackboard_artifact_tags (tag_id, artifact_id, tag_name_id, comment) VALUES (" //NON-NLS
                            + value + "," + inputResultSet.getLong(2) + "," + inputResultSet.getLong(3) + ",'"
                            + inputResultSet.getString(4) + "')"); //NON-NLS

        } catch (SQLException ex) {
            if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                throw new SQLException(ex);
            }
        }
    }
    numberingPK = postgreSQLConnection.createStatement();
    numberingPK.execute("ALTER SEQUENCE blackboard_artifact_tags_tag_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

    sqliteConnection.close();
    postgreSQLConnection.close();
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

private void startResultSet(ResultSet resultSet) throws SQLException {
    if (resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY && !resultSet.isBeforeFirst()) {
        resultSet.beforeFirst();// w w w .j  a va2s  . co m
    }
}

From source file:ua.aits.Carpath.model.ArticleModel.java

public List<ArticleModel> getArticleByFilters(String lan, String country, String type, String menuCat)
        throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        ParseException {/*w  ww  .  ja v  a 2 s .  c  o  m*/
    String countryFilter;
    String menuFilter = "";
    if ("all".equals(country)) {
        countryFilter = "";
    } else {
        countryFilter = " AND public_country='" + country + "'";
    }
    if (!"0".equals(menuCat)) {
        menuFilter = " AND menuCat = " + menuCat;
    }
    ResultSet result = DB.getResultSet("select * from content where type IN(" + type
            + ") and publish = 1 and isDelete = 0 " + countryFilter + menuFilter + " order by id desc;");
    List<ArticleModel> newsList = new LinkedList<>();
    if (!result.isBeforeFirst()) {
        return null;
    }
    while (result.next()) {
        ArticleModel temp = new ArticleModel();
        if (result.getString("actual") != null && !"".equals(result.getString("actual"))) {
            if (Helpers.checkOldArticle(result.getString("actual"))) {
                continue;
            }
        }
        String f_title = result.getString("title" + lan.toUpperCase());
        if ("".equals(f_title) || f_title == null) {
            f_title = result.getString("titleEN");
        }
        if (f_title.length() > 55) {
            f_title = f_title.substring(0, 55);
        }
        String text = Helpers.html2text(result.getString("text" + lan.toUpperCase()));
        if (text == null || "".equals(text)) {
            text = Helpers.html2text(result.getString("textEN"));
            if ("".equals(Helpers.html2text(result.getString("textEN")))
                    && !"".equals(result.getString("textEN"))) {
                text = f_title;
            }
            if (text == null || "".equals(text) || "ua".equals(lan.toUpperCase())) {
                continue;
            }
        }
        if (text.length() > 175) {
            text = text.substring(0, 175);
        }
        temp.setTextEN(text);
        temp.setId(result.getInt("id"));
        temp.setTitle(f_title);
        temp.setCountry(translate.translateCountryByLan(lan, result.getString("country")));
        temp.setDate(result.getString("date").replace("/", "."));
        temp.setAvatar(result.getString("avatar"));
        temp.setType(result.getInt("type"));
        String[] arr = result.getString("image").split(",");
        if ("".equals(arr[0])) {
            arr[0] = "img/zak.png";
        }
        temp.setImage(arr[0]);
        newsList.add(temp);
    }
    DB.closeCon();
    return newsList;
}

From source file:org.wso2.siddhi.extension.table.rdbms.RDBMSEventTable.java

@Override
protected boolean contains(Map<String, Object> containsConditionParameterMap,
        CompiledCondition compiledCondition) {
    String containsQuery = this.resolveTableName(this.queryConfigurationEntry.getRecordExistsQuery());
    String condition = ((RDBMSCompiledCondition) compiledCondition).getCompiledQuery();
    Connection conn = this.getConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {/*  www.java 2s. c  o m*/
        stmt = RDBMSTableUtils.isEmpty(condition)
                ? conn.prepareStatement(containsQuery.replace(PLACEHOLDER_CONDITION, ""))
                : conn.prepareStatement(RDBMSTableUtils.formatQueryWithCondition(containsQuery, condition));
        RDBMSTableUtils.resolveCondition(stmt, (RDBMSCompiledCondition) compiledCondition,
                containsConditionParameterMap, 0);
        rs = stmt.executeQuery();
        return rs.next() && !rs.isBeforeFirst();
    } catch (SQLException e) {
        throw new RDBMSTableException(
                "Error performing a contains check on table '" + this.tableName + "': " + e.getMessage(), e);
    } finally {
        RDBMSTableUtils.cleanupConnection(rs, stmt, conn);
    }
}

From source file:net.certifi.audittablegen.GenericDMR.java

public Map<String, DataTypeDef> getDataTypes() {

    if (this.dataTypes != null) {
        return this.dataTypes;
    }//from ww  w  .j ava2 s.co  m

    //this is kind of ugly.  Some databases (postgres) return the VALUES of
    //metadata in lowercase, while others (hsqldb) return the VALUES of
    //metadata in uppercase.  This is why the key values are stored as
    //case insensitive - so it will work with default types for 
    Map<String, DataTypeDef> types = new CaseInsensitiveMap();

    try {
        Connection conn = dataSource.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        ResultSet rs = dmd.getTypeInfo();

        if (!rs.isBeforeFirst()) {
            throw new RuntimeException("No results for DatabaseMetaData.getTypeInfo()");
        }
        while (rs.next()) {

            DataTypeDef dtd = new DataTypeDef();

            dtd.type_name = rs.getString("TYPE_NAME");
            dtd.data_type = rs.getInt("DATA_TYPE");
            dtd.precision = rs.getInt("PRECISION");
            dtd.literal_prefix = rs.getString("LITERAL_PREFIX");
            dtd.literal_suffix = rs.getString("LITERAL_SUFFIX");
            dtd.create_params = rs.getString("CREATE_PARAMS");
            dtd.nullable = rs.getShort("NULLABLE");
            dtd.case_sensitive = rs.getBoolean("CASE_SENSITIVE");
            dtd.searchable = rs.getShort("SEARCHABLE");
            dtd.unsigned_attribute = rs.getBoolean("UNSIGNED_ATTRIBUTE");
            dtd.fixed_prec_scale = rs.getBoolean("FIXED_PREC_SCALE");
            dtd.auto_increment = rs.getBoolean("AUTO_INCREMENT");
            dtd.local_type_name = rs.getString("LOCAL_TYPE_NAME");
            dtd.minimum_scale = rs.getShort("MINIMUM_SCALE");
            dtd.maximum_scale = rs.getShort("MAXIMUM_SCALE");
            dtd.sql_data_type = rs.getInt("SQL_DATA_TYPE"); //not used
            dtd.sql_datetime_sub = rs.getInt("SQL_DATETIME_SUB"); //not used
            dtd.num_prec_radix = rs.getInt("NUM_PREC_RADIX");

            //google guava primitive types tools
            if (Ints.contains(DataTypeDef.sqlSizedTypes, dtd.data_type) && !dtd.type_name.equals("text")) {
                dtd.createWithSize = true;
            }

            types.put(dtd.type_name, dtd);

        }

    } catch (SQLException e) {
        throw Throwables.propagate(e);
    }

    this.dataTypes = types;

    Collection<String> debugValues = types.keySet();
    for (String debugValue : debugValues) {
        logger.debug("DB has type value {}", debugValue);

    }

    return types;

}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testBeforeFirstAfterLast() throws SQLException {
    // stat.executeUpdate("create table test(id int)");
    stat = conn.createStatement();//from w  w  w  . ja va 2  s  .  com
    stat.execute("insert into test (column1,column2,column3) values(1,21,'binlijin2')");
    assertTrue(stat.getUpdateCount() == 1);
    // With a result
    ResultSet rs = stat.executeQuery(
            "select column1,column2,column3 from " + TABLE_NAME + " where column1=1 and column3='binlijin2'");
    assertTrue(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());
    rs.next();
    assertFalse(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());
    rs.next();
    assertFalse(rs.isBeforeFirst());
    assertTrue(rs.isAfterLast());
    rs.close();
    rs = stat.executeQuery("select column1,column2,column3 from test where column2 = -222");
    assertFalse(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());
    rs.next();
    assertFalse(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());
    rs.close();
}