Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

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

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

From source file:nl.strohalm.cyclos.setup.migrations.version3_6.ClosedAccountBalancesMigration.java

@Override
public int execute(final JDBCWrapper jdbc) throws SQLException {

    // First, ensure the account status still exists, ie, not already migrated
    ResultSet accountStatusExists = null;
    try {//from  ww w .  ja va 2  s  .co m
        accountStatusExists = jdbc.query("select 1 from account_status limit 1");
    } catch (final SQLException e) {
        // The already does not exists. Exit.
        return 0;
    } finally {
        JDBCWrapper.closeQuietly(accountStatusExists);
    }

    // Populate the account limit logs from both the account status and the pending account status tables
    jdbc.execute(
            "insert into account_limit_logs " + " (account_id, date, by_id, credit_limit, upper_credit_limit) "
                    + " select account_id, date, credit_limit_by_id, credit_limit, upper_credit_limit"
                    + " from account_status" + " where credit_limit_by_id is not null");

    jdbc.execute(
            "insert into account_limit_logs " + " (account_id, date, by_id, credit_limit, upper_credit_limit) "
                    + " select account_id, date, by_id, lower_limit, upper_limit"
                    + " from pending_account_status" + " where type = 'lim'");

    // Populate the amount_reservations table from pending transfers, scheduled payments which reserves the total amount and their installments
    jdbc.execute("insert into amount_reservations" + " (subclass, account_id, date, amount, transfer_id)"
            + " select 'P', from_account_id, date, amount, id " + " from transfers t " + " where t.status = ? ",
            Payment.Status.PENDING.getValue());
    jdbc.execute(
            "insert into amount_reservations" + " (subclass, account_id, date, amount, scheduled_payment_id)"
                    + " select 'S', from_account_id, date, amount, id " + " from scheduled_payments "
                    + " where reserve_amount = true ");
    jdbc.execute(
            "insert into amount_reservations" + " (subclass, account_id, date, amount, transfer_id)"
                    + " select 'I', t.from_account_id, ifnull(t.process_date, t.date), -t.amount, t.id "
                    + " from transfers t inner join scheduled_payments sp on t.scheduled_payment_id = sp.id"
                    + " where sp.reserve_amount = true and t.status <> ? ",
            Payment.Status.SCHEDULED.getValue());

    // Iterate each account
    int results = 0;
    final ResultSet accounts = jdbc.query("select id, creation_date from accounts");
    try {
        while (accounts.next()) {
            final long accountId = accounts.getLong("id");
            final Date creationDate = new Date(DateUtils
                    .truncate(accounts.getTimestamp("creation_date"), Calendar.DAY_OF_MONTH).getTime());
            // Get, by day, each diff, either for balance or reserved amount
            ResultSet diffs = jdbc.query(" select * from ( "
                    + "     select 'B' as type, b.date, b.balance as diff" + "     from ( "
                    + "         select date(date) as date, sum(amount) as balance " + "         from ( "
                    + "             select t.process_date as date, "
                    + "             case when t.chargeback_of_id is null then "
                    + "                 case when t.from_account_id = ? then -t.amount else t.amount end "
                    + "             else "
                    + "                 case when t.to_account_id = ? then t.amount else -t.amount end "
                    + "             end as amount " + "             from transfers t "
                    + "             where (t.from_account_id = ? or t.to_account_id = ?) "
                    + "               and t.process_date is not null " + "         ) t "
                    + "         group by date(date) " + "     ) b " + "     union "
                    + "     select 'R', date(r.date), sum(r.amount) " + "     from amount_reservations r "
                    + "     where r.account_id = ? " + "     group by date(r.date) " + " ) t "
                    + " where date < current_date() " + " order by date", accountId, accountId, accountId,
                    accountId, accountId);
            Date lastDate = creationDate;
            double balance = 0;
            double reserved = 0;
            try {
                boolean hasData = false;
                while (diffs.next()) {
                    hasData = true;
                    boolean isBalance = "B".equals(diffs.getString("type"));
                    Date date = diffs.getDate("date");
                    double diff = diffs.getDouble("diff");
                    if (!lastDate.equals(date)) {
                        // Insert a closed balance when the date changes
                        results += jdbc.execute(
                                "insert into closed_account_balances (date, account_id, balance, reserved) values (?, ?, ?, ?)",
                                nextDay(lastDate), accountId, balance, reserved);
                    }
                    if (isBalance) {
                        balance += diff;
                    } else {
                        reserved += diff;
                    }
                    lastDate = date;
                }
                if (hasData) {
                    // There is a last closed balance to insert
                    results += jdbc.execute(
                            "insert into closed_account_balances (date, account_id, balance, reserved) values (?, ?, ?, ?)",
                            nextDay(lastDate), accountId, balance, reserved);
                }
            } finally {
                JDBCWrapper.closeQuietly(diffs);
            }
            // Set the last closing date
            jdbc.execute("update accounts set last_closing_date = ? where id = ?", lastDate, accountId);
        }
    } finally {
        JDBCWrapper.closeQuietly(accounts);
    }

    // Now it is safe to drop the account_status table
    jdbc.execute("drop table account_status");
    jdbc.execute("drop table pending_account_status");

    return results;
}

From source file:com.opencsv.ResultSetHelperService.java

private String getColumnValue(ResultSet rs, int colType, int colIndex, boolean trim, String dateFormatString,
        String timestampFormatString) throws SQLException, IOException {

    String value = "";

    switch (colType) {
    case Types.BIT:
    case Types.JAVA_OBJECT:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getObject(colIndex), "");
        value = ObjectUtils.toString(rs.getObject(colIndex), "");
        break;//from www .j a  v a  2s  . c  o  m
    case Types.BOOLEAN:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getBoolean(colIndex));
        value = ObjectUtils.toString(rs.getBoolean(colIndex));
        break;
    case Types.NCLOB: // todo : use rs.getNClob
    case Types.CLOB:
        Clob c = rs.getClob(colIndex);
        if (c != null) {
            StrBuilder sb = new StrBuilder();
            sb.readFrom(c.getCharacterStream());
            value = sb.toString();
        }
        break;
    case Types.BIGINT:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getLong(colIndex));
        value = ObjectUtils.toString(rs.getLong(colIndex));
        break;
    case Types.DECIMAL:
    case Types.REAL:
    case Types.NUMERIC:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getBigDecimal(colIndex), "");
        value = ObjectUtils.toString(rs.getBigDecimal(colIndex), "");
        break;
    case Types.DOUBLE:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getDouble(colIndex));
        value = ObjectUtils.toString(rs.getDouble(colIndex));
        break;
    case Types.FLOAT:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getFloat(colIndex));
        value = ObjectUtils.toString(rs.getFloat(colIndex));
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getInt(colIndex));
        value = ObjectUtils.toString(rs.getInt(colIndex));
        break;
    case Types.DATE:
        java.sql.Date date = rs.getDate(colIndex);
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(dateFormatString);
            value = df.format(date);
        }
        break;
    case Types.TIME:
        // Once Java 7 is the minimum supported version.
        //            value = Objects.toString(rs.getTime(colIndex), "");
        value = ObjectUtils.toString(rs.getTime(colIndex), "");
        break;
    case Types.TIMESTAMP:
        value = handleTimestamp(rs.getTimestamp(colIndex), timestampFormatString);
        break;
    case Types.NVARCHAR: // todo : use rs.getNString
    case Types.NCHAR: // todo : use rs.getNString
    case Types.LONGNVARCHAR: // todo : use rs.getNString
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        String columnValue = rs.getString(colIndex);
        if (trim && columnValue != null) {
            value = columnValue.trim();
        } else {
            value = columnValue;
        }
        break;
    default:
        value = "";
    }

    if (rs.wasNull() || value == null) {
        value = "";
    }

    return value;
}

From source file:com.itemanalysis.jmetrik.graph.density.DensityAnalysis.java

public XYSeriesCollection summarize() throws SQLException, IllegalArgumentException {
    Statement stmt = null;//from w  w  w  .j a v a 2 s.  co  m
    ResultSet rs = null;
    TreeMap<String, ResizableDoubleArray> data = new TreeMap<String, ResizableDoubleArray>();

    //set progress bar information
    int nrow = 0;
    JmetrikPreferencesManager pref = new JmetrikPreferencesManager();
    String dbType = pref.getDatabaseType();
    if (DatabaseType.APACHE_DERBY.toString().equals(dbType)) {
        JmetrikDatabaseFactory dbFactory = new JmetrikDatabaseFactory(DatabaseType.APACHE_DERBY);
        nrow = dao.getRowCount(conn, tableName);
    } else {
        //add other databases here when functionality is added
    }
    maxProgress = (double) nrow;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    select.addColumn(sqlTable, variable.getName().nameForDatabase());
    if (hasGroupingVariable)
        select.addColumn(sqlTable, groupVar.getName().nameForDatabase());
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    String conditionalName = "";
    ResizableDoubleArray cData = null;
    double value = Double.NaN;

    while (rs.next()) {
        if (groupVar != null) {
            String groupName = rs.getString(groupVar.getName().nameForDatabase());
            if (rs.wasNull()) {
                groupName = "";
            }
            conditionalName = groupName;
        } else {
            conditionalName = "Series 1";
        }

        cData = data.get(conditionalName);
        if (cData == null) {
            cData = new ResizableDoubleArray((int) maxProgress);
            data.put(conditionalName, cData);
        }
        value = rs.getDouble(variable.getName().nameForDatabase());
        if (!rs.wasNull()) {
            cData.addElement(value);
        }
        updateProgress();
    }
    rs.close();
    stmt.close();

    String kType = command.getSelectOneOption("kernel").getSelectedArgument();
    double adjustment = command.getFreeOption("adjust").getDouble();
    KernelFactory kernelFactory = new KernelFactory(kType);

    KernelFunction kernelFunction = kernelFactory.getKernelFunction();
    Bandwidth bandwidth = null;
    KernelDensity density = null;
    UniformDistributionApproximation uniform = null;
    Min min = new Min();
    Max max = new Max();
    double[] x = null;

    this.firePropertyChange("progress-ind-on", null, null);

    XYSeriesCollection seriesCollection = new XYSeriesCollection();
    XYSeries series = null;
    for (String s : data.keySet()) {
        series = new XYSeries(s);
        x = data.get(s).getElements();
        bandwidth = new ScottsBandwidth(x, adjustment);
        uniform = new UniformDistributionApproximation(min.evaluate(x), max.evaluate(x), KERNEL_POINTS);
        density = new KernelDensity(kernelFunction, bandwidth, uniform);

        double[] dens = density.evaluate(x);
        double[] points = density.getPoints();
        for (int i = 0; i < dens.length; i++) {
            series.add(points[i], dens[i]);
        }
        seriesCollection.addSeries(series);
    }
    return seriesCollection;

}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.ConsumersByQueueOrTopic.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/*  w w w  .ja v a  2 s  .  co  m*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(
                "This represents the average number of consumers for all channels (topics/queues/etc) on a specific message broker.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Average Consumer Count</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            try {
                data.append("<tr><td>").append(Utility.encodeHTML(urls.get(i))).append("</td>");
                double average = 0;
                try {
                    cmd = con.prepareStatement(
                            "select avg(activeconsumercount), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();

                    if (rs.next()) {
                        average = rs.getDouble(1);

                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append("<td>").append(average + "").append("</td>");

                try {
                    //ok now get the raw data....
                    cmd = con.prepareStatement(
                            "select utcdatetime,activeconsumercount, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ?;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class);
                    while (rs.next()) {

                        //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname"));
                        GregorianCalendar gcal = new GregorianCalendar();
                        gcal.setTimeInMillis(rs.getLong(1));
                        Millisecond m = new Millisecond(gcal.getTime());

                        ts.addOrUpdate(m, rs.getLong(2));

                    }
                    col.addSeries(ts);
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col,
                true, false, false);

        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:de.ingrid.importer.udk.strategy.v32.IDCStrategy3_2_0.java

private void updateDQAbsPosGenauigkeit() throws Exception {
    log.info("\nUpdating object_data_quality 'Absolute Positionsgenauigkeit'...");

    log.info("Transfer 'Absolute Positionsgenauigkeit' values from DQ table (object_data_quality) to moved "
            + "fields 'Hhengenauigkeit' (T011_obj_geo.pos_accuracy_vertical) and 'Lagegenauigkeit (m)' (T011_obj_geo.rec_exact) "
            + "if fields are empty ...");

    // NOTICE: We do NOT update search index due to same values.

    // select all relevant entries in DQ Table
    String sqlSelectDQTable = "select obj_id, name_of_measure_key, result_value from object_data_quality where dq_element_id = 117";

    // select according values in DQ Field
    PreparedStatement psSelectDQFields = jdbc
            .prepareStatement("SELECT pos_accuracy_vertical, rec_exact FROM t011_obj_geo WHERE obj_id = ?");

    // update according value in DQ Field
    PreparedStatement psUpdateDQFieldLage = jdbc
            .prepareStatement("UPDATE t011_obj_geo SET " + "rec_exact = ? " + "WHERE obj_id = ?");
    PreparedStatement psUpdateDQFieldHoehe = jdbc
            .prepareStatement("UPDATE t011_obj_geo SET " + "pos_accuracy_vertical = ? " + "WHERE obj_id = ?");

    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sqlSelectDQTable, st);
    int numProcessed = 0;
    while (rs.next()) {
        long objId = rs.getLong("obj_id");
        int dqTableMeasureKey = rs.getInt("name_of_measure_key");
        String dqTableValue = rs.getString("result_value");

        if (dqTableValue != null) {
            // read according value from field
            psSelectDQFields.setLong(1, objId);
            ResultSet rs2 = psSelectDQFields.executeQuery();
            if (rs2.next()) {
                // read field value where to migrate to and check whether was null 
                double lageFieldValue = rs2.getDouble("rec_exact");
                boolean lageFieldValueWasNull = rs2.wasNull();
                double hoeheFieldValue = rs2.getDouble("pos_accuracy_vertical");
                boolean hoeheFieldValueWasNull = rs2.wasNull();

                log.debug("Object id=" + objId + " -> read DQ table value: measureKey=" + dqTableMeasureKey
                        + ", value=" + dqTableValue + " / values in fields: Lagegenauigkeit="
                        + (lageFieldValueWasNull ? null : lageFieldValue) + ", Hhengenauigkeit="
                        + (hoeheFieldValueWasNull ? null : hoeheFieldValue));

                // transfer Lagegenauigkeit from table to field if field is null
                if (dqTableMeasureKey == syslist7117EntryKeyLagegenauigkeit && lageFieldValueWasNull) {
                    try {
                        psUpdateDQFieldLage.setDouble(1, new Double(dqTableValue));
                        psUpdateDQFieldLage.setLong(2, objId);
                        psUpdateDQFieldLage.executeUpdate();
                        numProcessed++;/*w ww  .  j a v  a 2  s.c  om*/
                        log.debug("Transferred 'Lagegenauigkeit' value '" + dqTableValue
                                + "' from DQ table to field (was empty), obj_id:" + objId);
                    } catch (Exception ex) {
                        String msg = "Problems transferring 'Lagegenauigkeit' value '" + dqTableValue
                                + "' from DQ table as DOUBLE to field, value is lost ! obj_id:" + objId;
                        log.error(msg, ex);
                        System.out.println(msg);
                    }
                }

                // transfer Hhengenauigkeit  from table to field if field is null
                if (dqTableMeasureKey == syslist7117EntryKeyHoehegenauigkeit && hoeheFieldValueWasNull) {
                    try {
                        psUpdateDQFieldHoehe.setDouble(1, new Double(dqTableValue));
                        psUpdateDQFieldHoehe.setLong(2, objId);
                        psUpdateDQFieldHoehe.executeUpdate();
                        numProcessed++;
                        log.debug("Transferred 'Hhengenauigkeit' value '" + dqTableValue
                                + "' from DQ table to field (was empty), obj_id:" + objId);
                    } catch (Exception ex) {
                        String msg = "Problems transferring 'Hhengenauigkeit' value '" + dqTableValue
                                + "' from DQ table as DOUBLE to field, value is lost ! obj_id:" + objId;
                        log.error(msg, ex);
                        System.out.println(msg);
                    }
                }
            }
            rs2.close();
        }
    }
    rs.close();
    st.close();
    psSelectDQFields.close();
    psUpdateDQFieldLage.close();
    psUpdateDQFieldHoehe.close();

    log.info("Transferred " + numProcessed + " entries... done");

    log.info("Delete 'Absoulte Positionsgenauigkeit' values from DQ table (object_data_quality) ...");
    sqlStr = "DELETE FROM object_data_quality where dq_element_id = 117";
    int numDeleted = jdbc.executeUpdate(sqlStr);
    log.debug("Deleted " + numDeleted + " entries.");

    log.info("Updating object_data_quality 'Absolute Positionsgenauigkeit' ... done\n");
}

From source file:gsn.wrappers.TetraedreFluoWrapper.java

public void run() {
    DataEnumerator data;/*from   w  w w .  j  a va 2s . c  o m*/

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }

    Connection conn = null;
    ResultSet resultSet = null;

    while (isActive()) {
        try {
            conn = sm.getConnection();
            StringBuilder query = new StringBuilder("select * from ").append(table_name)
                    .append(" where physical_input=").append(physical_input).append(" AND timestamp*1000 > "
                            + latest_timed + "  order by timestamp limit 0," + buffer_size);

            resultSet = sm.executeQueryWithResultSet(query, conn);

            //logger.debug(query);

            while (resultSet.next()) {
                Serializable[] output = new Serializable[this.getOutputFormat().length];

                //long pk = resultSet.getLong(1);
                long timed = resultSet.getLong(3) * 1000;

                //logger.warn("pk => "+ pk);
                //logger.warn("timed => "+ timed);

                for (int i = 0; i < dataFieldsLength; i++) {

                    switch (dataFieldTypes[i]) {
                    case DataTypes.VARCHAR:
                    case DataTypes.CHAR:
                        output[i] = resultSet.getString(i + 1);
                        break;
                    case DataTypes.INTEGER:
                        output[i] = resultSet.getInt(i + 1);
                        break;
                    case DataTypes.TINYINT:
                        output[i] = resultSet.getByte(i + 1);
                        break;
                    case DataTypes.SMALLINT:
                        output[i] = resultSet.getShort(i + 1);
                        break;
                    case DataTypes.DOUBLE:
                        output[i] = resultSet.getDouble(i + 1);
                        break;
                    case DataTypes.FLOAT:
                        output[i] = resultSet.getFloat(i + 1);
                        break;
                    case DataTypes.BIGINT:
                        output[i] = resultSet.getLong(i + 1);
                        break;
                    case DataTypes.BINARY:
                        output[i] = resultSet.getBytes(i + 1);
                        break;
                    }
                    //logger.warn(i+" (type: "+dataFieldTypes[i]+" ) => "+output[i]);
                }

                StreamElement se = new StreamElement(dataFieldNames, dataFieldTypes, output, timed);
                latest_timed = se.getTimeStamp();

                //logger.warn(" Latest => " + latest_timed);

                this.postStreamElement(se);

                updateCheckPointFile(latest_timed);

                //logger.warn(se);
            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            sm.close(resultSet);
            sm.close(conn);
        }

        try {
            Thread.sleep(rate);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.liferay.portal.upgrade.util.Table.java

public Object getValue(ResultSet rs, String name, Integer type) throws Exception {

    Object value = null;/*from  w  w  w.  j av a 2  s .c  om*/

    int t = type.intValue();

    if (t == Types.BIGINT) {
        try {
            value = GetterUtil.getLong(rs.getLong(name));
        } catch (SQLException e) {
            value = GetterUtil.getLong(rs.getString(name));
        }
    } else if (t == Types.BOOLEAN) {
        value = GetterUtil.getBoolean(rs.getBoolean(name));
    } else if (t == Types.CLOB) {
        try {
            Clob clob = rs.getClob(name);

            if (clob == null) {
                value = StringPool.BLANK;
            } else {
                UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(clob.getCharacterStream());

                StringBundler sb = new StringBundler();

                String line = null;

                while ((line = unsyncBufferedReader.readLine()) != null) {
                    if (sb.length() != 0) {
                        sb.append(SAFE_NEWLINE_CHARACTER);
                    }

                    sb.append(line);
                }

                value = sb.toString();
            }
        } catch (Exception e) {

            // If the database doesn't allow CLOB types for the column
            // value, then try retrieving it as a String

            value = GetterUtil.getString(rs.getString(name));
        }
    } else if (t == Types.DOUBLE) {
        value = GetterUtil.getDouble(rs.getDouble(name));
    } else if (t == Types.FLOAT) {
        value = GetterUtil.getFloat(rs.getFloat(name));
    } else if (t == Types.INTEGER) {
        value = GetterUtil.getInteger(rs.getInt(name));
    } else if (t == Types.SMALLINT) {
        value = GetterUtil.getShort(rs.getShort(name));
    } else if (t == Types.TIMESTAMP) {
        try {
            value = rs.getTimestamp(name);
        } catch (Exception e) {
        }

        if (value == null) {
            value = StringPool.NULL;
        }
    } else if (t == Types.VARCHAR) {
        value = GetterUtil.getString(rs.getString(name));
    } else {
        throw new UpgradeException("Upgrade code using unsupported class type " + type);
    }

    return value;
}

From source file:data.services.ParseBaseService.java

private void updatePropertyNames() throws SQLException, ClassNotFoundException, Exception {
    List<Car> carList = carDao.getAllAsc();
    HashMap<Long, Car> ourOldIdCarMap = new HashMap();
    for (Car car : carList) {
        ourOldIdCarMap.put(car.getCmqId(), car);
    }// ww  w  . j  ava  2  s .com

    List<CarProperty> fullCPList = carPropertyDao.getAllAsc();
    HashMap<Long, CarProperty> ourOldIdCpMap = new HashMap();
    for (CarProperty cp : fullCPList) {
        ourOldIdCpMap.put(cp.getOldId(), cp);
    }

    HashMap<Long, HashMap<Long, PropertyName>> newInfoCarMap = new HashMap();

    List<PropertyName> pnListForSave = new ArrayList();
    List<PropertyName> pnListForUpdate = new ArrayList();
    List<PropertyName> pnListForDelete = new ArrayList();

    ResultSet resSet = getFromQutoBase(
            "SELECT link.*,cpv.* FROM car_modification_property_value_link link LEFT JOIN car_property_value cpv ON link.car_property_value_id=cpv.id LEFT JOIN car_modification cm ON link.car_modification_id=cm.id WHERE cm.usage='ad_archive_catalog'");

    //HashMap<Long,ArrayList<Feature>> newFeatureInfo = new HashMap();
    while (resSet.next()) {

        Long carOldId = resSet.getLong("car_modification_id");

        HashMap<Long, PropertyName> newInfoPNMap = newInfoCarMap.get(carOldId);
        if (newInfoPNMap == null) {
            newInfoPNMap = new HashMap();
        }

        PropertyName newPn = new PropertyName();
        Long oldcpId = resSet.getLong("car_property_id");
        String strVal = StringAdapter.getString(resSet.getString("value_string")).trim();
        Double numVal = resSet.getDouble("value_number");
        Long oldPnId = resSet.getLong("id");
        String pnVal = strVal;
        if (pnVal.equals("")) {
            pnVal = StringAdapter.getString(numVal).replace(".", ",");
        }

        newPn.setOldValueId(oldPnId);
        newPn.setPropertyNameValue(pnVal);
        newPn.setParamValue(numVal);

        newInfoPNMap.put(oldcpId, newPn);

        newInfoCarMap.put(carOldId, newInfoPNMap);
    }

    for (Long carOldId : ourOldIdCarMap.keySet()) {
        try {
            Car car = ourOldIdCarMap.get(carOldId);
            List<PropertyName> oldPnList = car.getPropertyNames();
            HashMap<Long, PropertyName> oldPnMap = new HashMap();
            if (oldPnList == null) {
                oldPnList = new ArrayList();
            }

            HashMap<Long, PropertyName> newInfoPNMap = newInfoCarMap.get(carOldId);

            //int existingPnSize = 0;
            for (PropertyName pn : oldPnList) {
                Long oldcpId = pn.getCarProperty().getOldId();
                oldPnMap.put(oldcpId, pn);
                /*PropertyName newPn = newInfoPNMap.get(oldcpId);
                 if(newPn!=null){
                 pn.setOldValueId(newPn.getOldValueId());
                 pn.setParamValue(newPn.getParamValue());
                 pn.setPropertyNameValue(newPn.getPropertyNameValue());
                 propertyNameDao.update(pn);
                 existingPnSize++;
                 }else{
                 propertyNameDao.delete(pn);
                 }*/
            }
            if (oldPnMap.size() != oldPnList.size()) {
                //throw new Exception("? :"+car.getCarId()+"  ?   ?!");
                addError("? :" + car.getCarId()
                        + "  ?   ?!");
            }

            for (Long oldcpId : newInfoPNMap.keySet()) {
                PropertyName newPn = newInfoPNMap.get(oldcpId);
                PropertyName oldPn = oldPnMap.get(oldcpId);
                if (oldPn == null) {
                    oldPn = newPn;
                    oldPn.setCar(car);
                    oldPn.setAudial((long) 0);
                    oldPn.setVisual((long) 0);
                    oldPn.setKinestet((long) 0);
                    oldPn.setCarProperty(ourOldIdCpMap.get(oldcpId));
                    oldPn.setPercentValue((long) 0);
                    if (validate(oldPn,
                            "  ? ?  ?: auto_quto_id="
                                    + car.getCmqId() + ", pnv_quto_id=" + newPn.getOldValueId()
                                    + ", cp_quto_id=" + oldcpId + "; ")) {
                        pnListForSave.add(oldPn);
                    }
                } else {
                    oldPn.setParamValue(newPn.getParamValue());
                    oldPn.setPropertyNameValue(newPn.getPropertyNameValue());
                    oldPn.setOldValueId(newPn.getOldValueId());
                    if (validate(oldPn,
                            "  ? ?  : auto_quto_id="
                                    + car.getCmqId() + ", pnv_quto_id=" + newPn.getOldValueId()
                                    + ", cp_quto_id=" + oldcpId + "; ")) {
                        pnListForUpdate.add(oldPn);
                    }
                }
            }
            for (Long oldcpId : oldPnMap.keySet()) {
                if (newInfoPNMap.get(oldcpId) == null) {
                    pnListForDelete.add(oldPnMap.get(oldcpId));
                }
            }
        } catch (Exception e) {
            throw new Exception(
                    " ? ?   quto_car_id:"
                            + carOldId + "; " + e);
        }

    }
    int s = 0;
    int u = 0;
    int d = 0;
    for (PropertyName pn : pnListForSave) {
        propertyNameDao.save(pn);
        s++;
    }
    for (PropertyName pn : pnListForUpdate) {
        propertyNameDao.update(pn);
        u++;
    }
    for (PropertyName pn : pnListForDelete) {
        propertyNameDao.delete(pn);
        d++;
    }

    addError("? : " + s + " ?, " + u
            + " , " + d + " .");
}

From source file:com.sfs.whichdoctor.dao.ReceiptDAOImpl.java

/**
 * Load receipt./*from w  w w.j  a  v a2s  . c  om*/
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the receipt bean
 *
 * @throws SQLException the SQL exception
 */
private ReceiptBean loadReceipt(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    ReceiptBean receipt = new ReceiptBean();

    receipt.setId(rs.getInt("ReceiptId"));
    receipt.setGUID(rs.getInt("GUID"));

    receipt.setAbbreviation(rs.getString("Abbreviation"));
    receipt.setNumber(rs.getString("ReceiptNo"));
    receipt.setDescription(rs.getString("Description"));
    receipt.setProcessType(rs.getString("ProcessType"));
    receipt.setProcessAbbreviation(rs.getString("ProcessAbbreviation"));
    receipt.setBatchReference(rs.getInt("BatchReference"));
    receipt.setBank(rs.getString("Bank"));
    receipt.setBranch(rs.getString("Branch"));
    try {
        receipt.setIssued(rs.getDate("Issued"));
    } catch (SQLException e) {
        receipt.setIssued(null);
    }
    receipt.setCancelled(rs.getBoolean("Cancelled"));

    int organisationGUID = rs.getInt("OrganisationId");
    int personGUID = rs.getInt("PersonId");

    if (personGUID > 0) {
        receipt.setPerson(loadPerson(rs, personGUID, loadDetails));
    }
    if (organisationGUID > 0) {
        receipt.setOrganisation(loadOrganisation(rs, organisationGUID, loadDetails));
    }

    receipt.setTypeName(rs.getString("Type"));
    receipt.setClassName(rs.getString("ReceiptType"));
    receipt.setTotalValue(rs.getDouble("TotalValue"));
    receipt.setSecurity(rs.getString("Security"));

    receipt.setActive(rs.getBoolean("Active"));
    if (loadDetails.getBoolean("HISTORY")) {
        try {
            receipt.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        receipt.setCreatedBy(rs.getString("CreatedBy"));
        try {
            receipt.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        receipt.setModifiedBy(rs.getString("ModifiedBy"));
        try {
            receipt.setExportedDate(rs.getTimestamp("ExportedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage());
        }
        receipt.setExportedBy(rs.getString("ExportedBy"));
    }

    if (loadDetails.getBoolean("TAGS")) {
        try {
            receipt.setTags(this.getTagDAO().load(receipt.getGUID(), loadDetails.getString("USERDN"), true));
        } catch (Exception e) {
            dataLogger.error("Error loading tags for receipt: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("MEMO")) {
        try {
            receipt.setMemo(this.getMemoDAO().load(receipt.getGUID(), loadDetails.getBoolean("MEMO_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading memos: " + e.getMessage());
        }
    }
    if (loadDetails.getBoolean("PAYMENT")) {
        try {
            receipt.setPayments(
                    this.paymentDAO.load(receipt.getGUID(), loadDetails.getBoolean("PAYMENT_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading payment details: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("GROUPS")) {
        receipt.setGroups(loadGroups(receipt.getGUID()));
    }

    if (loadDetails.getBoolean("CREATED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        receipt.setCreatedUser(user);
    }
    if (loadDetails.getBoolean("MODIFIED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ModifiedBy"));
        user.setPreferredName(rs.getString("ModifiedFirstName"));
        user.setLastName(rs.getString("ModifiedLastName"));
        receipt.setModifiedUser(user);
    }
    if (loadDetails.getBoolean("EXPORTED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ExportedBy"));
        user.setPreferredName(rs.getString("ExportedFirstName"));
        user.setLastName(rs.getString("ExportedLastName"));
        receipt.setExportedUser(user);
    }
    return receipt;
}

From source file:org.traccar.database.QueryBuilder.java

private <T> void addProcessors(List<ResultSetProcessor<T>> processors, final Class<?> parameterType,
        final Method method, final String name) {

    if (parameterType.equals(boolean.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override/*from   w  w  w .  jav a 2  s . c  o  m*/
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getBoolean(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(int.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getInt(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(long.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getLong(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(double.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getDouble(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(String.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getString(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(Date.class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    Timestamp timestamp = resultSet.getTimestamp(name);
                    if (timestamp != null) {
                        method.invoke(object, new Date(timestamp.getTime()));
                    }
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else if (parameterType.equals(byte[].class)) {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                try {
                    method.invoke(object, resultSet.getBytes(name));
                } catch (IllegalAccessException | InvocationTargetException error) {
                    Log.warning(error);
                }
            }
        });
    } else {
        processors.add(new ResultSetProcessor<T>() {
            @Override
            public void process(T object, ResultSet resultSet) throws SQLException {
                String value = resultSet.getString(name);
                if (value != null && !value.isEmpty()) {
                    try {
                        method.invoke(object, Context.getObjectMapper().readValue(value, parameterType));
                    } catch (InvocationTargetException | IllegalAccessException | IOException error) {
                        Log.warning(error);
                    }
                }
            }
        });
    }
}