Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

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

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:it.unibas.spicy.persistence.relational.DAORelational.java

private void getInstanceByTable(IConnectionFactory dataSourceDB, Connection connection, String schemaName,
        String tableName, INode setTable, IDataSourceProxy dataSource, boolean translated) throws DAOException {
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {//from w  w  w .  j  av  a  2s.  com
        String tablePath = tableName;
        //mysql jdbc driver
        if (connection.getMetaData().getDriverName().equalsIgnoreCase(SpicyEngineConstants.MYSQL_DRIVER_NAME)) {
            tablePath = connection.getCatalog() + "." + tableName;
        } else if (!schemaName.equals("")) {
            tablePath = schemaName + ".\"" + tableName + "\"";
        }
        statement = connection.prepareStatement("select * from " + tablePath + " order by 1");
        statement.setMaxRows(NUMBER_OF_SAMPLE);
        resultSet = statement.executeQuery();
        if (resultSet == null) {
            throw new DAOException("ResultSet is NULL!");
        }
        int sampleCounter = 0;
        while (resultSet.next() && sampleCounter < NUMBER_OF_SAMPLE) {
            sampleCounter++;
            TupleNode tupleNode = new TupleNode(getNode(tableName + TUPLE_SUFFIX).getLabel(), getOID());
            setTable.addChild(tupleNode);
            for (INode attributeNodeSchema : getNode(tableName + TUPLE_SUFFIX).getChildren()) {
                AttributeNode attributeNode = new AttributeNode(attributeNodeSchema.getLabel(), getOID());
                String columnName = attributeNodeSchema.getLabel();
                String oldName = dataSource.getChangedValue(tableName + "." + columnName);
                if (oldName != null && !translated) {
                    columnName = oldName;
                }
                Object columnValue = resultSet.getObject(columnName);
                LeafNode leafNode = createLeafNode(attributeNodeSchema, columnValue);
                attributeNode.addChild(leafNode);
                tupleNode.addChild(attributeNode);
            }
        }
    } catch (SQLException sqle) {
        throw new DAOException(sqle.getMessage());
    } finally {
        dataSourceDB.close(resultSet);
        dataSourceDB.close(statement);
    }
}

From source file:com.glaf.dts.transform.MxTransformManager.java

@SuppressWarnings("unchecked")
protected List<Map<String, Object>> prepare(QueryDefinition query, List<Map<String, Object>> paramList) {
    logger.debug("-------------------------3 start------------------------");
    List<Map<String, Object>> resultList = new java.util.ArrayList<Map<String, Object>>();
    List<Map<String, Object>> tmpResultList = new java.util.ArrayList<Map<String, Object>>();
    Connection conn = null;//  w  w w. ja va 2s.c o m
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        Database database = databaseService.getDatabaseById(query.getDatabaseId());
        if (database != null) {
            conn = DBConnectionFactory.getConnection(database.getName());
        } else {
            conn = DBConnectionFactory.getConnection();
        }
        logger.debug("-------------------------3 connection------------------------");
        for (Map<String, Object> paramMap : paramList) {
            logger.debug("sql:" + query.getSql());
            SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(query.getSql(), paramMap);
            logger.debug("sql:" + sqlExecutor.getSql());
            psmt = conn.prepareStatement(sqlExecutor.getSql());
            if (sqlExecutor.getParameter() != null) {
                List<Object> values = (List<Object>) sqlExecutor.getParameter();
                JdbcUtils.fillStatement(psmt, values);
                logger.debug("values:" + values);
            }

            logger.debug("-------------------------3 executeQuery------------------------");
            rs = psmt.executeQuery();
            rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowMap = new java.util.HashMap<String, Object>();
                for (int i = 1; i <= count; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    if (null == columnName || 0 == columnName.length()) {
                        columnName = rsmd.getColumnName(i);
                    }
                    try {
                        rowMap.put(columnName, rs.getObject(i));
                    } catch (SQLException ex) {
                        rowMap.put(columnName, rs.getString(i));
                    }
                }
                resultList.add(rowMap);
                tmpResultList.add(rowMap);
            }
            // logger.debug("resultList :" + tmpResultList);
            tmpResultList.clear();
        }

        query.setResultList(resultList);

        // logger.debug("resultList size:" + resultList.size());

        return resultList;
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
        logger.debug("-------------------------3 end------------------------");
    }
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

private <T> T bindSingle(final ResultSet resultSet, final Class<T> beanClass, final T beanInstance)
        throws SQLException, ReflectiveOperationException {

    if (resultSet != null) {
        final Set<String> resultLabels = ResultSets.getColumnLabels(resultSet);
        //            @SuppressWarnings("unchecked")
        //            final List<Field> fields
        //                = Reflections.fields(beanClass, Label.class);
        final Field[] fields = FieldUtils.getFieldsWithAnnotation(beanClass, Label.class);
        for (final Field field : fields) {
            final String label = field.getAnnotation(Label.class).value();
            final String suppression = suppression(beanClass, field);
            final String info = String.format("field=%s, label=%s, suppression=%s", field, label, suppression);
            if (suppressed(suppression)) {
                logger.log(Level.FINE, "suppressed; {0}", info);
                continue;
            }//from   w ww . j a va 2 s.  c  o m
            if (!resultLabels.remove(label)) {
                final String message = "unknown column; " + info;
                if (!suppressUnknownColumns()) {
                    throw new RuntimeException(message);
                }
                logger.warning(message);
                continue;
            }
            final Object value;
            try {
                value = resultSet.getObject(label);
            } catch (final Exception e) {
                final String message = "failed to get value; " + info;
                logger.severe(message);
                if (e instanceof SQLException) {
                    throw (SQLException) e;
                }
                throw new RuntimeException(e);
            }
            Values.set(field.getName(), beanInstance, value);
            //Reflections.fieldValue(field, beanInstance, value);
            //FieldUtils.writeField(field, beanInstance, value);
            //FieldUtils.writeField(field, beanInstance, value, true);
        }
        if (!resultLabels.isEmpty()) {
            for (final String resultLabel : resultLabels) {
                final Object resultValue = resultSet.getObject(resultLabel);
                logger.log(Level.WARNING, "unknown result; {0}({1})",
                        new Object[] { resultLabel, resultValue });
            }
        }
    }

    //        @SuppressWarnings("unchecked")
    //        final List<Field> fields
    //            = Reflections.fields(beanClass, Invocation.class);
    final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(beanClass, Invocation.class);
    for (final Field field : fields) {
        final Invocation invocation = field.getAnnotation(Invocation.class);
        final String suppression = suppression(beanClass, field);
        final String info = String.format("field=%s, invocation=%s, suppression=%s", field, invocation,
                suppression);
        if (suppressed(suppression)) {
            logger.log(Level.FINE, "suppressed; {0}", new Object[] { info });
            continue;
        }
        final String name = invocation.name();
        getMethodNames().remove(name);
        final Class<?>[] types = invocation.types();
        final Method method;
        try {
            method = DatabaseMetaData.class.getMethod(name, types);
        } catch (final NoSuchMethodException nsme) {
            final String message = "unknown methods; " + info;
            if (!suppressUnknownMethods()) {
                throw new RuntimeException(message);
            }
            logger.warning(message);
            continue;
        }
        for (final InvocationArgs invocationArgs : invocation.argsarr()) {
            final String[] names = invocationArgs.value();
            final Object[] args = Invocations.args(beanClass, beanInstance, types, names);
            final Object value;
            try {
                value = method.invoke(database, args);
            } catch (final Exception e) {
                logger.log(Level.SEVERE, "failed to invoke" + info, e);
                throw new RuntimeException(e);
            } catch (final AbstractMethodError ame) {
                logger.log(Level.SEVERE, "failed by abstract" + info, ame);
                throw ame;
            }
            setValue(field, beanInstance, value, args);
        }
    }

    if (TableDomain.class.isAssignableFrom(beanClass)) {
        getMethodNames().remove("getCrossReference");
        final List<Table> tables = ((TableDomain) beanInstance).getTables();
        final List<CrossReference> crossReferences = getCrossReferences(tables);
        ((TableDomain) beanInstance).setCrossReferences(crossReferences);
    }

    return beanInstance;
}

From source file:com.itemanalysis.jmetrik.graph.irt.IrtPlotAnalysis.java

private void summarizeResponseData() throws SQLException {
    this.firePropertyChange("progress-ind-on", null, null);

    Statement stmt = null;/*from   w  w  w. j a  v a2s  . c  o  m*/
    ResultSet rs = null;

    //IRT observed score distribution
    NormalDistributionApproximation latentDist = new NormalDistributionApproximation(min, max, points);
    irtDist = new IrtObservedScoreDistribution(itemResponseModels, latentDist);
    irtDist.compute();
    nscores = irtDist.getNumberOfScores();
    eapScore = new double[nscores];
    for (int i = 0; i < nscores; i++) {
        eapScore[i] = irtDist.getEAP(i);
    }

    //Summarize item response vectors
    try {
        int nrow = dao.getRowCount(conn, responseTableName);
        responseVector = new ItemResponseVector[nrow];

        VariableTableName variableTableName = new VariableTableName(responseTableName.toString());
        ArrayList<VariableAttributes> variableAttributes = dao.getSelectedVariables(conn, variableTableName,
                variables);

        //Query the db. Variables include the select items and the grouping variable is one is available.
        Table sqlTable = new Table(responseTableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        for (VariableAttributes v : variableAttributes) {
            select.addColumn(sqlTable, v.getName().nameForDatabase());
        }
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

        int i = 0;
        int c = 0;
        int ncol = itemResponseModels.length;
        byte[] rv = null;
        Object response = null;
        ItemResponseVector iVec = null;
        while (rs.next()) {
            c = 0;
            rv = new byte[ncol];

            for (VariableAttributes v : variableAttributes) {
                response = rs.getObject(v.getName().nameForDatabase());
                if ((response == null || response.equals("") || response.equals("NA"))) {
                    rv[c] = -1;//code for omitted responses
                } else {
                    rv[c] = (byte) v.getItemScoring().computeItemScore(response);
                }
                c++;
            }
            iVec = new ItemResponseVector(rv, 1.0);
            responseVector[i] = iVec;
            i++;
        } //end data summary

    } catch (SQLException ex) {
        throw (ex);
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public String getRecordsAsJson(String sql, JsonKeyCase jsonKeyCase, Boolean useCamelCase, Boolean escapeHtml,
        SimpleDateFormat dateFormatter, Object... params) {
    PreparedStatement st = null;//www  . ja v  a2 s.c  om
    ResultSet rs = null;
    ResultSetMetaData rsMetaData = null;
    Gson gson = new Gson();
    try {
        StringBuilder stringBuilder = null;
        stringBuilder = new StringBuilder("[");
        st = conn.prepareStatement(sql);
        setParams(st, params);
        rs = st.executeQuery();
        rsMetaData = rs.getMetaData();
        while (rs.next()) {
            stringBuilder.append("{");
            for (int i = 1; i <= rsMetaData.getColumnCount(); i++) {
                String attrName;
                switch (jsonKeyCase) {
                case UPPER:
                    attrName = rsMetaData.getColumnName(i).toUpperCase();
                    break;
                case LOWER:
                    attrName = rsMetaData.getColumnName(i).toLowerCase();
                    break;
                default:
                    attrName = rsMetaData.getColumnName(i);
                }
                String test = dbToFieldName(attrName);
                stringBuilder.append("\"").append((useCamelCase) ? dbToFieldName(attrName) : attrName)
                        .append("\":");
                Object val = rs.getObject(i);
                if (val == null) {
                    stringBuilder.append("null,");
                } else if (val instanceof Number) {
                    stringBuilder.append(val.toString()).append(",");
                } else if (val instanceof java.sql.Date) {
                    stringBuilder.append("\"")
                            .append(dateFormatter.format(new java.util.Date(((java.sql.Date) val).getTime())))
                            .append("\",");
                } else if (val instanceof java.sql.Timestamp) {
                    stringBuilder.append("\"")
                            .append(dateFormatter
                                    .format(new java.util.Date(((java.sql.Timestamp) val).getTime())))
                            .append("\",");
                } else {
                    if (escapeHtml)
                        stringBuilder.append(gson.toJson(rs.getObject(i).toString())).append(",");
                    else
                        stringBuilder.append("\"").append(rs.getObject(i).toString()).append("\",");
                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("},");
        }
        if (stringBuilder.length() > 1)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append("]");
        return stringBuilder.toString();
    } catch (Exception ex) {
        throw new DataQueryException(sql, null, ex);
    } finally {
        closeOnFinally(rs, st);
    }

}

From source file:at.alladin.rmbt.controlServer.OpenTestResource.java

/**
 * Gets the JSON-Representation of all open-data-fields for one specific
 * open-test-uuid/*from ww  w.j a va  2  s .  co m*/
 * @param openTestUUID
 * @return the json-string
 * 
 * 
 * columns in csv ("open data")
 * 1:open_uuid,
 * 2:open_test_uuid,
 * 3:time,
 * 4:cat_technology,
 * 5:network_type,
 * 6:lat,
 * 7:long,
 * 8:loc_src,
 * 9:zip_code,
 * 10:download_kbit,
 * 11:upload_kbit,
 * 12:ping_ms,
 * 13:signal_strength,
 * 14:server_name,
 * 15:test_duration,
 * 16:num_threads,
 * 17:platform,
 * 18:model,
 * 19:client_version,
 * 20:network_mcc_mnc,
 * 21:network_name,
 * 22:sim_mcc_mnc,
 * 23:connection,
 * 24:asn,
 * 25:ip_anonym,
 * 26:ndt_download_kbit,
 * 27:ndt_upload_kbit,
 * 28:implausible,
 * 29:lte_rsrp
 * 
 * 
 * Columns in test table
 *   uid (internal)
 *   uuid (private)
 *   client_id
 *   client_version
 *   client_name
 *   client_language (private)
 *   token (private, obsolete)
 *   server_id
 *   port
 *   use_ssl *
 *   time
 *   speed_upload
 *   speed_download
 *   ping_shortest
 *   encryption *
 *   client_public_ip (private)
 *   plattform 
 *   os_version (internal)
 *   api_level (internal)
 *   device
 *   model
 *   product
 *   phone_type (internal)
 *   data_state (internal)
 *   network_country (internal)
 *   network_operator
 *   network_operator_name
 *   network_sim_country (internal)
 *   network_sim_operator
 *   network_sim_operator_name
 *   wifi_ssid (private)
 *   wifi_bssid (private)
 *   wifi_network_id (private)
 *   duration
 *   num_threads
 *   status
 *   timezone (private)
 *   bytes_download
 *   bytes_upload
 *   nsec_download
 *   nsec_upload
 *   server_ip
 *   client_software_version
 *   geo_lat
 *   geo_long
 *   network_type
 *   location
 *   signal_strength
 *   software_revision
 *   client_test_counter
 *   nat_type
 *   client_previous_test_status
 *   public_ip_asn
 *   speed_upload_log
 *   speed_download_log
 *   total_bytes_download
 *   total_bytes_upload
 *   wifi_link_speed
 *   public_ip_rdns
 *   public_ip_as_name
 *   test_slot
 *   provider_id
 *   network_is_roaming (internal)
 *   ping_shortest_log
 *   run_ndt (internal)
 *   num_threads_requested
 *   client_public_ip_anonymized
 *   zip_code
 *   geo_provider
 *   geo_accuracy
 *   deleted (internal)
 *   comment (internal)
 *   open_uuid
 *   client_time (internal)
 *   zip_code_geo (internal)
 *   mobile_provider_id
 *   roaming_type
 *   open_test_uuid
 *   country_asn
 *   country_location
 *   test_if_bytes_download
 *   test_if_bytes_upload
 *   implausible
 *   testdl_if_bytes_download
 *   testdl_if_bytes_upload
 *   testul_if_bytes_download
 *   testul_if_bytes_upload
 *   country_geoip
 *   location_max_distance
 *   location_max_distance_gps
 *   network_group_name
 *   network_group_type
 *   time_dl_ns
 *   time_ul_ns
 *   num_threads_ul 
 *   lte_rsrp
 *   lte_rsrq
 *   mobile_network_id
 *   mobile_sim_id
 *   dist_prev
 *   speed_prev
 *   tag
 *   ping_median
 *   ping_median_log
 *   client_ip_local_type (private)
 *
 *   private: visible to user only (not public)
 *   internal: not visible (neither user nor public)
 * 
 */

private String getSingleOpenTest(String openTestUUID) {
    final String sql = "SELECT t.uid as test_uid, " + " ('O' || t.open_test_uuid) open_test_uuid," + //csv  open_test_uuid, UUID prefixed with 'O'
            " to_char(t.time AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') \"time\"," + " t.time full_time," + //csv: 3:time server time-stamp of start of measurement
            " t.client_time client_time," + //(internal) client time-stamp of start of measure
            " t.network_group_name cat_technology," + //csv 4:cat_technology
            " t.network_group_type network_type," + //csv 5:network_type

            " t.geo_lat lat," + //csv 6:lat
            " t.geo_long long," + // csv 7:long
            " t.geo_provider loc_src," + //csv 8:loc_src android: 'gps'/'network'; browser/iOS: '' (empty string)
            " t.geo_accuracy loc_accuracy, " + //accuracy of geo location in m

            /*
            //csv 6:lat
            " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN" +
            " t.geo_lat" +
            " WHEN (t.geo_accuracy < ?) THEN" +
            " ROUND(t.geo_lat*1111)/1111" + // approx 100m
            " ELSE null" +
            " END) lat," +
            // csv 7:long
            " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN" +
            " t.geo_long" +
            " WHEN (t.geo_accuracy < ?) THEN" +
            " ROUND(t.geo_long*741)/741 " + //approx 100m
            " ELSE null" +
            " END) long," +
            // csv 8:loc_src android: 'gps'/'network'; browser/iOS: '' (empty string)
            " (CASE WHEN ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN" +
            " 'rastered'" + //make raster transparent
            " ELSE t.geo_provider" +
            " END) loc_src," +
            // accuracy of geo location in m
            " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') " +
            " THEN t.geo_accuracy " +
            " WHEN (t.geo_accuracy < 100) AND ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN 100" + // limit accuracy to 100m
            " WHEN (t.geo_accuracy < ?) THEN t.geo_accuracy" +
            " ELSE null END) loc_accuracy, " +
            */

            //csv 9:zip-code - defined as integer in data base, only meaningful for measurements in Austria
            " (CASE WHEN (t.zip_code < 1000 OR t.zip_code > 9999) THEN null ELSE t.zip_code END) zip_code," +
            // " zip_code_geo," + //(internal) zip-code, integer derived from geo_location, Austria only
            " t.speed_download download_kbit," + //csv 10:download_kbit
            " t.speed_upload upload_kbit," + //csv 11: upload_kbit
            " t.wifi_link_speed," + // nominal speed of wifi-link in mbit/s , Android-only
            " (t.ping_median::float / 1000000) ping_ms," + //median ping-time in ms (stored in ns in data base)
            " signal_strength," + //csv 13:signal_strength RSSI, mainly GSM/UMTS and Wifi, Android only, in dBm
            " lte_rsrp," + // csv 29: signal_strength RSRP, Android only, in dBm
            " lte_rsrq," + // signal quality RSRQ, Android only, in dB
            " ts.name server_name," + //csv 14:server_name, name of the test server used for download/upload (not applicable for JStest)
            " implausible, " + //csv 28:implausible, measurement not shown in map nor used in statistics, normally not visible
            " public_ip_as_name, " + //name of AS (not number)
            " duration test_duration," + //csv 15:test_duration, nominal duration of downlink and uplink throughput tests in seconds
            " num_threads_requested," + // number of threads requested by control-server
            " num_threads," + //csv 16:num_threads, number of threads used in downlink throughput test (uplink may differ)
            " num_threads_ul," + // number of threads used in uplink test
            " (CASE WHEN publish_public_data THEN COALESCE(t.plattform, t.client_name) ELSE '' END) platform," + //csv 17:platform; currently used: 'CLI'/'Android'/Applet/iOS/[from client_name: RMBTws, RMBTjs](null); (null) is used for RMBTjs  //AKOS: IC 
            " (CASE WHEN publish_public_data THEN COALESCE(adm.fullname, t.model) ELSE '' END)  model," + //csv 18:model, translated t.model (model_native) to human readable form  //AKOS: IC
            " (CASE WHEN publish_public_data THEN t.model ELSE '' END) model_native," + //device used for test; Android API 'model'; iOS:'product'; Browser: Browser-name (zB Firefox)  //AKOS: IC
            " t.product product," + // product used for test; Android APO 'product'; iOS: '' (not used); Browser: same as for model (browser name)
            " t.client_software_version client_version," + //csv 19:client_version, SW-version of client software (not RMBT-client-version), eg. '1.3'
            " t.network_operator network_mcc_mnc," + //csv 20:network_mcc_mnc, mobile country and network code of current network (Android only), string, eg "232-12'
            " network_country," + //(internal) Android-only, country code derived by client from mobile network code
            // " network_is_roaming," + //(internal) roaming-status of mobile network, boolean or (null); Android-only (obsolete)
            " roaming_type," + //roaming-status of mobile network, integer: 0:not roaming,1:national,2:international,(null):unknown (eg. iOS)
            " t.network_operator_name network_name," + //csv 21:network_name, name of current mobile network as displayed on device (eg: '3likeHome')
            " t.network_sim_operator sim_mcc_mnc," + //csv 22:sim_mcc_mnc, home network of SIM (initial 5 digits from IMSI), eg '232-01'
            " t.network_sim_country sim_country," + //(internal) Android-only, country derived by client from SIM (country of home network)
            " COALESCE(mprov.name,msim.shortname,msim.name,prov.name) provider_name," + //pre-defined list of providers (based on provider_id) //TODO replace provider
            " t.nat_type \"connection\"," + //csv 23:connection, translation-mechanism in NAT, eg. nat_local_to_public_ipv4
            " t.public_ip_asn asn," + //csv 24:asn, AS (autonomous system) number, number of public IP network
            " (CASE WHEN publish_public_data THEN t.client_public_ip_anonymized ELSE '' END) ip_anonym," + //csv 25:ip_anonym, anonymized IP of client (IPv4: 8 bits removed, IPv6: 72 bits removed)
            " (ndt.s2cspd*1000)::int ndt_download_kbit," + //csv 26:ndt_download_kbit, result of NDT downlink throughput test kbit/s
            " (ndt.c2sspd*1000)::int ndt_upload_kbit," + //csv 27 ndt_uoload_kbit, result of NDT uplink throughput test in kbit/s
            " country_geoip," + // country-code derived from public IP-address, eg. 'AT'
            " country_location," + // country-code derived from geo_location, eg. 'DE'
            " country_asn," + // country_code derived from AS, eg. 'EU'
            " data->>'region' region," + // si - region from geo location
            " data->>'municipality' municipality," + // si - municipality from geo location
            " data->>'settlement' settlement," + // si - settlement from geo location
            " data->>'whitespace' whitespot," + // si - whitespace from geo location
            " data->>'cell_id' cell_id," + // si - cell_id
            " data->>'cell_name' cell_name," + // si - cell_name
            " data->>'cell_id_multiple' cell_id_multiple," + // si - cell_id_multiple
            " bytes_download," + // number of bytes downloaded during test (download and upload) (obsolete)
            " bytes_upload," + // number of bytes uploaded during test (download and upload) (obsolete)
            " test_if_bytes_download," + //downloaded bytes on interface during total test (inc. training, ping, without NDT) (obsolete)
            " test_if_bytes_upload," + //uploaded bytes on interface during total test (inc. training, ping, without NDT) (obsolete)
            " testdl_if_bytes_download," + //downloaded bytes on interface during download-test (without training-seq)
            " testdl_if_bytes_upload," + //uploaded bytes on interface during download-test (without training-seq)
            " testul_if_bytes_download," + //downloaded bytes on interface during upload-test (without training-seq)
            " testul_if_bytes_upload," + //downloaded bytes on interface during upload-test (without training-seq)
            " (t.nsec_download::float / 1000000) duration_download_ms," + //duration of download-test in ms
            " (t.nsec_upload::float / 1000000) duration_upload_ms," + //duration of upload-test in ms
            " (t.time_dl_ns::float / 1000000) time_dl_ms," + //relative start time of download-test in ms (ignoring training-phase)
            " (t.time_ul_ns::float / 1000000) time_ul_ms," + //relative start time of download-test in ms (ignoring training-phase)
            // " phone_type" + //(internal) radio type of phone: 0 no mobile radio, 1 GSM (incl. UMTS,LTE) 2 CDMA (obsolete)
            " t.publish_public_data, "
            + " ((EXTRACT (EPOCH FROM (t.timestamp - t.time))) * 1000) speed_test_duration " + " FROM test t"
            + " LEFT JOIN device_map adm ON adm.codename=t.model"
            + " LEFT JOIN test_server ts ON ts.uid=t.server_id" + " LEFT JOIN test_ndt ndt ON t.uid=ndt.test_id"
            + " LEFT JOIN provider prov ON t.provider_id=prov.uid"
            + " LEFT JOIN provider mprov ON t.mobile_provider_id=mprov.uid"
            + " LEFT JOIN mccmnc2name msim ON t.mobile_sim_id=msim.uid" + " WHERE " + " t.deleted = false "
            + " AND t.status = 'FINISHED' " + " AND t.open_test_uuid = ? ";

    //System.out.println(sql);

    final String[] columns;
    PreparedStatement ps = null;
    ResultSet rs = null;
    final JSONObject response = new JSONObject();
    try {
        ps = conn.prepareStatement(sql);

        //insert filter for accuracy
        /*
        double accuracy = Double.parseDouble(getSetting("rmbt_geo_accuracy_detail_limit"));
        ps.setDouble(1, accuracy);
        ps.setDouble(2, accuracy);
        ps.setDouble(3, accuracy);
        ps.setDouble(4, accuracy);
        ps.setDouble(5, accuracy);
        ps.setDouble(6, accuracy);
        */

        //openTestIDs are starting with "O"
        if (openTestUUID != null && openTestUUID.startsWith("O")) {
            openTestUUID = openTestUUID.substring(1);
        }
        ps.setObject(1, openTestUUID, Types.OTHER);

        if (!ps.execute())
            return null;
        rs = ps.getResultSet();

        if (rs.next()) {
            final boolean isPublishPublicData = rs.getBoolean("publish_public_data");
            //fetch data for every field
            for (int i = 0; i < openDataFieldsFull.length; i++) {

                //convert data to correct json response
                final Object obj = rs.getObject(openDataFieldsFull[i]);
                if (openDataBooleanFields.contains(openDataFieldsFull[i])) {
                    if (obj == null) {
                        response.put(openDataFieldsFull[i], false);
                    } else {
                        response.put(openDataFieldsFull[i], obj);
                    }
                } else if (obj == null) {
                    response.put(openDataFieldsFull[i], JSONObject.NULL);
                } else if (openDataNumberFields.contains(openDataFieldsFull[i])) {
                    final String tmp = obj.toString().trim();
                    if (tmp.isEmpty())
                        response.put(openDataFieldsFull[i], JSONObject.NULL);
                    else
                        response.put(openDataFieldsFull[i], JSONObject.stringToValue(tmp));
                } else {
                    final String tmp = obj.toString().trim();
                    if (tmp.isEmpty())
                        response.put(openDataFieldsFull[i], JSONObject.NULL);
                    else
                        response.put(openDataFieldsFull[i], tmp);
                }

            }
            /* obsolete (now in database)
            //special threatment for lat/lng: if too low accuracy -> do not send back to client
            double accuracy = rs.getDouble("loc_accuracy");
            if (accuracy > Double.parseDouble(settings.getString("RMBT_GEO_ACCURACY_DETAIL_LIMIT"))) {
               response.put("loc_accuracy", JSONObject.NULL);
               response.put("long", JSONObject.NULL);
               response.put("lat", JSONObject.NULL);
            }
                    
            try {
            // do not output invalid zip-codes, must be 4 digits 
            int zip_code = rs.getInt("zip_code");
            if (zip_code <= 999 || zip_code > 9999)
               response.put("zip_code", JSONObject.NULL);
            }
            catch (final SQLException e) {
               System.out.println("Error on zip_code: " + e.toString());
            };
            */

            //classify download, upload, ping, signal
            response.put("download_classification",
                    Classification.classify(classification.THRESHOLD_DOWNLOAD, rs.getLong("download_kbit")));
            response.put("upload_classification",
                    Classification.classify(classification.THRESHOLD_UPLOAD, rs.getLong("upload_kbit")));
            response.put("ping_classification",
                    Classification.classify(classification.THRESHOLD_PING, rs.getLong("ping_ms") * 1000000));
            //classify signal accordingly
            if ((rs.getString("signal_strength") != null || rs.getString("lte_rsrp") != null)
                    && rs.getString("network_type") != null) { // signal available
                if (rs.getString("lte_rsrp") == null) { // use RSSI
                    if (rs.getString("network_type").equals("WLAN")) { // RSSI for Wifi
                        response.put("signal_classification", Classification
                                .classify(classification.THRESHOLD_SIGNAL_WIFI, rs.getLong("signal_strength")));
                    } else { // RSSI for Mobile
                        response.put("signal_classification", Classification.classify(
                                classification.THRESHOLD_SIGNAL_MOBILE, rs.getLong("signal_strength")));
                    }
                } else // RSRP for LTE
                    response.put("signal_classification", Classification
                            .classify(classification.THRESHOLD_SIGNAL_RSRP, rs.getLong("lte_rsrp")));
            } else { // no signal available
                response.put("signal_classification", JSONObject.NULL);
            }

            //also load download/upload-speed-data, signal data and location data if possible
            JSONObject speedCurve = new JSONObject();
            JSONArray downloadSpeeds = new JSONArray();
            JSONArray uploadSpeeds = new JSONArray();
            JSONArray locArray = new JSONArray();
            JSONArray signalArray = new JSONArray();

            //Load speed data from database
            SpeedGraph speedGraph = new SpeedGraph(rs.getLong("test_uid"),
                    Math.max(rs.getInt("num_threads"), rs.getInt("num_threads_ul")), conn);
            for (SpeedGraph.SpeedGraphItem item : speedGraph.getUpload()) {
                JSONObject obj = new JSONObject();
                obj.put("time_elapsed", item.getTimeElapsed());
                obj.put("bytes_total", item.getBytesTotal());
                uploadSpeeds.put(obj);
            }
            for (SpeedGraph.SpeedGraphItem item : speedGraph.getDownload()) {
                JSONObject obj = new JSONObject();
                obj.put("time_elapsed", item.getTimeElapsed());
                obj.put("bytes_total", item.getBytesTotal());
                downloadSpeeds.put(obj);
            }

            //Load signal strength from database
            SignalGraph sigGraph = new SignalGraph(rs.getLong("test_uid"),
                    rs.getTimestamp("client_time").getTime(), conn);
            for (SignalGraph.SignalGraphItem item : sigGraph.getSignalList()) {
                JSONObject json = new JSONObject();
                json.put("time_elapsed", item.getTimeElapsed());
                json.put("network_type", item.getNetworkType());
                json.put("signal_strength", item.getSignalStrength());
                json.put("lte_rsrp", item.getLteRsrp());
                json.put("lte_rsrq", item.getLteRsrq());
                json.put("cat_technology", item.getCatTechnology());
                signalArray.put(json);
            }

            if (isPublishPublicData) {
                //Load gps coordinates from database
                LocationGraph locGraph = new LocationGraph(rs.getLong("test_uid"),
                        rs.getTimestamp("client_time").getTime(), conn);
                double totalDistance = locGraph.getTotalDistance();
                for (LocationGraph.LocationGraphItem item : locGraph.getLocations()) {
                    JSONObject json = new JSONObject();
                    json.put("time_elapsed", item.getTimeElapsed());
                    json.put("lat", item.getLatitude());
                    json.put("long", item.getLongitude());
                    json.put("loc_accuracy", (item.getAccuracy() > 0) ? item.getAccuracy() : JSONObject.NULL);
                    locArray.put(json);
                }

                //add total distance during test - but only if within bounds
                if ((totalDistance > 0)
                        && totalDistance <= Double.parseDouble(getSetting("rmbt_geo_distance_detail_limit")))
                    response.put("distance", totalDistance);
                else
                    response.put("distance", JSONObject.NULL);
            } else {
                response.put("distance", JSONObject.NULL);
            }

            final TestStatDao testStatDao = new TestStatDao(conn);
            final TestStat ts = testStatDao.getById(rs.getLong("test_uid"));
            if (ts != null) {
                response.put("extended_test_stat", ts.toJsonObject());
            }

            speedCurve.put("upload", uploadSpeeds);
            speedCurve.put("download", downloadSpeeds);
            speedCurve.put("signal", signalArray);
            speedCurve.put("location", locArray);
            response.put("speed_curve", speedCurve);

        } else {
            //invalid open_uuid
            setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            response.put("error", "invalid open-uuid");
        }
    } catch (final JSONException e) {
        Logger.getLogger(OpenTestResource.class.getName()).log(Level.SEVERE, null, e);
    } catch (SQLException ex) {
        try {
            setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            response.put("error", "invalid open-uuid");
        } catch (JSONException ex1) {
            Logger.getLogger(OpenTestResource.class.getName()).log(Level.SEVERE, null, ex1);
        }
        Logger.getLogger(OpenTestResource.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
        } catch (final SQLException e) {
            Logger.getLogger(OpenTestResource.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    return response.toString();
}

From source file:com.espertech.esper.epl.db.PollExecStrategyDBQuery.java

private synchronized List<EventBean> execute(PreparedStatement preparedStatement,
        Object[] lookupValuePerStream) {
    if (ExecutionPathDebugLog.isDebugEnabled && log.isInfoEnabled()) {
        log.info(".execute Executing prepared statement '" + preparedStatementText + "'");
    }//w  ww  . j ava  2s .  c o  m

    boolean hasJDBCLogging = enableJDBCLogging && jdbcPerfLog.isInfoEnabled();

    // set parameters
    SQLInputParameterContext inputParameterContext = null;
    if (columnTypeConversionHook != null) {
        inputParameterContext = new SQLInputParameterContext();
    }

    int count = 1;
    Object[] parameters = null;
    if (hasJDBCLogging) {
        parameters = new Object[lookupValuePerStream.length];
    }
    for (int i = 0; i < lookupValuePerStream.length; i++) {
        try {
            Object parameter = lookupValuePerStream[i];
            if (ExecutionPathDebugLog.isDebugEnabled && log.isInfoEnabled()) {
                log.info(".execute Setting parameter " + count + " to " + parameter + " typed "
                        + ((parameter == null) ? "null" : parameter.getClass()));
            }

            if (columnTypeConversionHook != null) {
                inputParameterContext.setParameterNumber(i + 1);
                inputParameterContext.setParameterValue(parameter);
                parameter = columnTypeConversionHook.getParameterValue(inputParameterContext);
            }

            setObject(preparedStatement, count, parameter);
            if (parameters != null) {
                parameters[i] = parameter;
            }
        } catch (SQLException ex) {
            throw new EPException("Error setting parameter " + count, ex);
        }

        count++;
    }

    // execute
    ResultSet resultSet;
    if (hasJDBCLogging) {
        long startTimeNS = System.nanoTime();
        long startTimeMS = System.currentTimeMillis();
        try {
            resultSet = preparedStatement.executeQuery();
        } catch (SQLException ex) {
            throw new EPException("Error executing statement '" + preparedStatementText + '\'', ex);
        }
        long endTimeNS = System.nanoTime();
        long endTimeMS = System.currentTimeMillis();
        jdbcPerfLog.info("Statement '" + preparedStatementText + "' delta nanosec " + (endTimeNS - startTimeNS)
                + " delta msec " + (endTimeMS - startTimeMS) + " parameters " + Arrays.toString(parameters));
    } else {
        try {
            resultSet = preparedStatement.executeQuery();
        } catch (SQLException ex) {
            throw new EPException("Error executing statement '" + preparedStatementText + '\'', ex);
        }
    }

    // generate events for result set
    List<EventBean> rows = new LinkedList<EventBean>();
    try {
        SQLColumnValueContext valueContext = null;
        if (columnTypeConversionHook != null) {
            valueContext = new SQLColumnValueContext();
        }

        SQLOutputRowValueContext rowContext = null;
        if (outputRowConversionHook != null) {
            rowContext = new SQLOutputRowValueContext();
        }

        int rowNum = 0;
        while (resultSet.next()) {
            int colNum = 1;
            Map<String, Object> row = new HashMap<String, Object>();
            for (Map.Entry<String, DBOutputTypeDesc> entry : outputTypes.entrySet()) {
                String columnName = entry.getKey();

                Object value;
                DatabaseTypeBinding binding = entry.getValue().getOptionalBinding();
                if (binding != null) {
                    value = binding.getValue(resultSet, columnName);
                } else {
                    value = resultSet.getObject(columnName);
                }

                if (columnTypeConversionHook != null) {
                    valueContext.setColumnName(columnName);
                    valueContext.setColumnNumber(colNum);
                    valueContext.setColumnValue(value);
                    valueContext.setResultSet(resultSet);
                    value = columnTypeConversionHook.getColumnValue(valueContext);
                }

                row.put(columnName, value);
                colNum++;
            }

            EventBean eventBeanRow = null;
            if (this.outputRowConversionHook == null) {
                eventBeanRow = eventAdapterService.adapterForTypedMap(row, eventType);
            } else {
                rowContext.setValues(row);
                rowContext.setRowNum(rowNum);
                rowContext.setResultSet(resultSet);
                Object rowData = outputRowConversionHook.getOutputRow(rowContext);
                if (rowData != null) {
                    eventBeanRow = eventAdapterService.adapterForTypedBean(rowData, (BeanEventType) eventType);
                }
            }

            if (eventBeanRow != null) {
                rows.add(eventBeanRow);
                rowNum++;
            }
        }
    } catch (SQLException ex) {
        throw new EPException("Error reading results for statement '" + preparedStatementText + '\'', ex);
    }

    if (enableJDBCLogging && jdbcPerfLog.isInfoEnabled()) {
        jdbcPerfLog.info("Statement '" + preparedStatementText + "' " + rows.size() + " rows");
    }

    try {
        resultSet.close();
    } catch (SQLException ex) {
        throw new EPException("Error closing statement '" + preparedStatementText + '\'', ex);
    }

    return rows;
}

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

@Test
public void testDecimal() throws SQLException {
    trace("test DECIMAL");
    ResultSet rs;
    Object o;/*from  www.  ja  v  a2s  .  c om*/

    stat = conn.createStatement();
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(21,-1,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(22,.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(23,1.0,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(24,12345678.89,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(25,99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(26,-99999998.99,9,'testDecimal')");
    stat.execute("INSERT INTO test (column1,column5,column2,column3) VALUES(27,-99999998.99,9,'testDecimal')");
    rs = stat.executeQuery("SELECT column1,column5 FROM test where column3='testDecimal' ORDER BY column1");
    BigDecimal bd;
    rs.next();
    assertTrue(rs.getInt(1) == 21);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == -1);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("-1.00")) == 0);
    assertTrue(!rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Double);
    assertTrue(new BigDecimal((Double) o).compareTo(new BigDecimal("-1.00")) == 0);
    rs.next();
    assertTrue(rs.getInt(1) == 22);
    assertTrue(!rs.wasNull());
    assertTrue(rs.getInt(2) == 0);
    assertTrue(!rs.wasNull());
    bd = rs.getBigDecimal(2);
    assertTrue(bd.compareTo(new BigDecimal("0.00")) == 0);
    assertTrue(!rs.wasNull());
    rs.next();
    checkColumnBigDecimal(rs, 2, 1, "1.00");
    rs.next();
    checkColumnBigDecimal(rs, 2, 12345679, "12345678.89");
    rs.next();
    checkColumnBigDecimal(rs, 2, 99999999, "99999998.99");
    rs.next();
    checkColumnBigDecimal(rs, 2, -99999999, "-99999998.99");
    // assertTrue(!rs.next());
}

From source file:com.nextep.designer.sqlclient.ui.editors.SQLFullClientGUI.java

/**
 * @see com.nextep.datadesigner.gui.model.IConnector#refreshConnector()
 *//*from w  w w.j  av a 2  s .c om*/
@Override
public void refreshConnector() {
    // Clearing current table columns
    // clearSQLView();

    final ISQLScript script = (ISQLScript) getModel();
    if (script.getSql() == null || "".equals(script.getSql())) {
        return;
    }
    try {
        // sqlText.add("select * from " + o.getName());
        // sqlText.select(sqlText.getItemCount()-1);
        // Creating result table
        final CTabItem sqlItem = new CTabItem(sqlFolder, SWT.NONE);
        Composite resultPane = new Composite(sqlFolder, SWT.NONE);
        final Table sqlView = new Table(resultPane, SWT.FULL_SELECTION | SWT.BORDER);
        final NextepTableEditor editor = NextepTableEditor.handle(sqlView);
        CoolBar statsBar = new CoolBar(resultPane, SWT.NONE);
        statsBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        final CoolItem rowsItem = new CoolItem(statsBar, SWT.NONE);
        rowsItem.setSize(rowsItem.computeSize(100, 20));
        final Label rowsCount = new Label(statsBar, SWT.NONE);
        rowsItem.setControl(rowsCount);
        final CoolItem timeItem = new CoolItem(statsBar, SWT.NONE);
        final Label timeLabel = new Label(statsBar, SWT.NONE);
        timeItem.setControl(timeLabel);
        timeItem.setSize(timeItem.computeSize(200, 20));
        sqlView.setHeaderVisible(true);
        sqlView.setLinesVisible(true);
        sqlView.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
        resultPane.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
        GridLayout grid = new GridLayout();
        grid.marginBottom = grid.marginHeight = grid.marginLeft = grid.marginRight = grid.marginTop = grid.marginWidth = 0;
        resultPane.setLayout(grid);
        sqlItem.setControl(resultPane);
        final Listener sortListener = new SortListener(sqlView);
        final String query = formatQuery(script.getSql());
        final int queryLen = query.length();
        sqlItem.setText(queryLen < 30 ? query : query.substring(0, 30) + "...");
        sqlItem.setToolTipText(query);
        sqlFolder.setSelection(sqlItem);
        final List<ICommand> bufferedCommands = new ArrayList<ICommand>();
        // Initializing lines
        Job refreshJob = new Job("Fetching SQL data...") {

            @Override
            protected IStatus run(IProgressMonitor monitor) {
                Statement s = null;
                ResultSet r = null;
                try {
                    s = connection.createStatement();
                    final Date startDate = new Date();
                    final boolean isResultSet = s.execute(query);
                    final Date afterExecDate = new Date();

                    if (!isResultSet) {
                        final int updates = s.getUpdateCount();
                        bufferedCommands.add(new ICommand() {

                            @Override
                            public String getName() {
                                return null;
                            }

                            @Override
                            public Object execute(Object... parameters) {
                                if (sqlView != null && !sqlView.isDisposed()) {
                                    TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                    c.setText(SQLClientMessages.getString("sql.result"));
                                    c.setWidth(300);
                                    c.addListener(SWT.Selection, sortListener);
                                    if (updates > 0) {
                                        final TableItem i = new TableItem(sqlView, SWT.NONE);
                                        i.setText(MessageFormat.format(
                                                SQLClientMessages.getString("sql.updatedRows"), updates));
                                    } else {
                                        final TableItem i = new TableItem(sqlView, SWT.NONE);
                                        i.setText(SQLClientMessages.getString("sql.queryOk"));
                                    }
                                }
                                return null;
                            }
                        });
                        syncProcessCommands(bufferedCommands);
                        return Status.OK_STATUS;
                    }
                    r = s.getResultSet();

                    // Initializing columns
                    final ResultSetMetaData md = r.getMetaData();
                    // Initializing sizing table
                    final int[] colMaxWidth = new int[md.getColumnCount() + 1];
                    for (int i = 1; i <= md.getColumnCount(); i++) {
                        final int index = i;
                        final String colName = md.getColumnName(index);
                        // final int colPrecision = md.getPrecision(index);
                        final int colType = md.getColumnType(index);
                        final int colIndex = i - 1;

                        bufferedCommands.add(new ICommand() {

                            @Override
                            public String getName() {
                                return null;
                            }

                            @Override
                            public Object execute(Object... parameters) {
                                if (!sqlView.isDisposed()) {
                                    TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                    c.addListener(SWT.Selection, sortListener);
                                    c.setText(colName);
                                    c.setWidth(colName.length() * 8);
                                    colMaxWidth[colIndex] = c.getWidth();
                                    c.setData(COL_TYPE, colType);
                                    TextColumnEditor.handle(editor, colIndex, ChangeEvent.CUSTOM_1,
                                            new IEventListener() {

                                                @Override
                                                public void handleEvent(ChangeEvent event, IObservable source,
                                                        Object data) {
                                                }
                                            });
                                }
                                return null;
                            }
                        });
                    }
                    final ResultSet rset = r;
                    int rows = 0;
                    final long execTime = afterExecDate.getTime() - startDate.getTime();
                    bufferedCommands.add(new ICommand() {

                        @Override
                        public String getName() {
                            return null;
                        }

                        @Override
                        public Object execute(Object... parameters) {
                            timeLabel.setText(MessageFormat
                                    .format(SQLClientMessages.getString("sql.executionTime"), execTime));
                            return null;
                        }
                    });
                    syncProcessCommands(bufferedCommands);
                    while (r.next()) {
                        rows++;
                        // Handling cancellation while fetching SQL lines
                        if (monitor.isCanceled()) {
                            return Status.CANCEL_STATUS;
                        }
                        final String[] colValues = new String[md.getColumnCount()];
                        final Collection<Integer> nullCols = new ArrayList<Integer>();
                        for (int i = 1; i <= md.getColumnCount(); i++) {
                            Object val = null;
                            try {
                                val = rset.getObject(i);
                            } catch (SQLException e) {
                                LOGGER.error("Error while fetching column value : " + e.getMessage(), e);
                                val = e.getMessage();
                            }
                            final String strVal = strVal(val);
                            colValues[i - 1] = strVal;
                            // Building list of null columns
                            if (val == null) {
                                nullCols.add(i - 1);
                            }
                            // Updating max sizes
                            final int colWidth = colMaxWidth[i - 1];
                            if (strVal.length() * 8 > colWidth) {
                                colMaxWidth[i - 1] = strVal.length() * 8;
                            }
                        }
                        // Adding the row as a command
                        bufferedCommands.add(buildAddRowCommand(colValues, sqlView, nullCols));
                        // Flushing to display every N lines
                        if (bufferedCommands.size() > MAX_ROWS_BEFORE_REFRESH) {
                            bufferedCommands.add(buildAdjustWidthCommand(sqlView, colMaxWidth));
                            syncProcessCommands(bufferedCommands);
                        }
                    }
                    // Flushing any left row
                    bufferedCommands.add(buildAdjustWidthCommand(sqlView, colMaxWidth));

                    final Date afterFetchDate = new Date();
                    final int nbRows = rows;
                    bufferedCommands.add(new ICommand() {

                        @Override
                        public String getName() {
                            // TODO Auto-generated method stub
                            return null;
                        }

                        @Override
                        public Object execute(Object... parameters) {
                            long fetchTime = afterFetchDate.getTime() - afterExecDate.getTime();
                            timeLabel.setText(
                                    MessageFormat.format(SQLClientMessages.getString("sql.executionFetchTime"),
                                            execTime, fetchTime));
                            rowsCount.setText(MessageFormat
                                    .format(SQLClientMessages.getString("sql.fetchedRows"), nbRows));
                            return null;
                        }
                    });
                    syncProcessCommands(bufferedCommands);
                } catch (final SQLException e) {
                    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {

                        @Override
                        public void run() {
                            if (!sqlView.isDisposed()) {
                                sqlView.removeAll();
                                for (TableColumn c : sqlView.getColumns()) {
                                    c.dispose();
                                }
                                TableColumn c = new TableColumn(sqlView, SWT.NONE);
                                c.setText("SQL Exception " + e.getErrorCode());
                                c.setWidth(300);
                                TableItem i = new TableItem(sqlView, SWT.NONE);
                                i.setText(e.getMessage());
                            }

                        }
                    });
                    // throw new ErrorException(e);
                } finally {
                    try {
                        if (r != null) {// && !r.isClosed()) {
                            r.close();
                        }
                        if (s != null) { // && !s.isClosed()) {
                            s.close();
                        }
                    } catch (SQLException e) {
                        throw new ErrorException(e);
                    } finally {
                        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {

                            @Override
                            public void run() {
                                // If the user has closed his SQL Query editor, we will
                                // fall here (exception) with a disposed button
                                if (runSQLButton != null && !runSQLButton.isDisposed()) {
                                    runSQLButton.setEnabled(true);
                                }
                            }
                        });
                    }
                }

                return Status.OK_STATUS;
            }
        };
        runSQLButton.setEnabled(false);
        refreshJob.schedule();

        // } catch(SQLException e) {
        // throw new ErrorException(e);
    } finally {
        // try {
        // if(stmt != null && !stmt.isClosed()) {
        // stmt.close();
        // }
        // if(rset != null && !rset.isClosed()) {
        // rset.close();
        // }
        // } catch(SQLException e) {
        // throw new ErrorException(e);
        // }
    }
}

From source file:com.apatar.http.HttpNode.java

@Override
protected void TransformTDBtoRDB(int mode) {
    DataBaseTools.completeTransfer();/*w ww  . ja v a  2s  .c o  m*/
    HttpConnection conn = (HttpConnection) ApplicationData.getProject().getProjectData(getConnectionDataID())
            .getData();
    String url = conn.getUrl();
    HttpRequestMethod httpRequestMethod = (HttpRequestMethod) conn.getMethod();

    TableInfo ti = getTiForConnection(IN_CONN_POINT_NAME);

    TableInfo tiOut = getTiForConnection(OUT_CONN_POINT_NAME);

    List<Record> selectionList = DataBaseTools.intersectionRecords(tiOut.getRecords(), ti.getRecords(), true);

    // read values from result set and put it in request
    SQLQueryString sqs = DataBaseTools.CreateSelectString(ApplicationData.getTempDataBase().getDataBaseInfo(),
            new SQLCreationData(selectionList, ti.getTableName()), null);

    if (sqs == null) {
        return;
    }

    ResultSet rs;
    try {
        rs = DataBaseTools.executeSelect(sqs, ApplicationData.getTempJDBC());

        while (rs.next()) {
            KeyInsensitiveMap rsData = DataBaseTools.GetDataFromRS(rs);

            HttpMethod hm;

            if (httpRequestMethod == HttpRequestMethod.post) {
                hm = sendPost(url, rsData);
            } else {
                hm = sendGet(url, rsData);
            }

            HttpClient client = new HttpClient();
            if (ApplicationData.httpClient.isUseProxy()) {
                HostConfiguration hostConfig = client.getHostConfiguration();
                hostConfig.setProxy(ApplicationData.httpClient.getHost(), ApplicationData.httpClient.getPort());
                String proxyUser = ApplicationData.httpClient.getUserName();
                if (proxyUser != null) {
                    client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                            proxyUser, ApplicationData.httpClient.getPassword()));
                }
            }

            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            int status = client.executeMethod(hm);

            KeyInsensitiveMap datas = new KeyInsensitiveMap();

            if (status != HttpStatus.SC_OK) {
                datas.put("Response", "Upload failed, response=" + HttpStatus.getStatusText(status));
            } else {
                datas.put("Response", hm.getResponseBodyAsString());
            }

            ti = getTiForConnection(OUT_CONN_POINT_NAME);

            List<Record> recs = getTiForConnection(AbstractDataBaseNode.OUT_CONN_POINT_NAME).getSchemaTable()
                    .getRecords();

            for (int j = 1; j < recs.size(); j++) {
                Record rec = recs.get(j);
                datas.put(rec.getFieldName(), rs.getObject(rec.getFieldName()));
            }

            DataBaseTools.insertData(new DataProcessingInfo(ApplicationData.getTempDataBase().getDataBaseInfo(),
                    ti.getTableName(), ti.getRecords(), ApplicationData.getTempJDBC()), datas);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    DataBaseTools.completeTransfer();
}