Example usage for java.sql ResultSetMetaData getColumnCount

List of usage examples for java.sql ResultSetMetaData getColumnCount

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnCount.

Prototype

int getColumnCount() throws SQLException;

Source Link

Document

Returns the number of columns in this ResultSet object.

Usage

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static Document addResultSetXmlPart(Element resultsElement, ResultSet rs, Document xmlDocumentResult)
        throws SQLException {
    // resultSet = statement.getResultSet();
    // connection to an ACCESS MDB
    ResultSetMetaData rsmd = rs.getMetaData();
    Element resultSetElement = xmlDocumentResult.createElement("ResultSet");

    resultSetElement.setAttribute("fetchSize", String.valueOf(rs.getFetchSize()));
    resultsElement.appendChild(resultSetElement);

    int colCount = rsmd.getColumnCount();
    while (rs.next()) {
        Element rowElement = xmlDocumentResult.createElement("Row");
        rowElement.setAttribute("rowNumber", String.valueOf(rs.getRow()));

        resultsElement.appendChild(rowElement);
        for (int ii = 1; ii <= colCount; ii++) {
            String columnName = "";
            if (!StringUtils.isBlank(rsmd.getTableName(ii))) {
                columnName += (rsmd.getTableName(ii)).toUpperCase() + ".";
            }/*www .j  a  v  a  2  s . c o m*/
            columnName += (rsmd.getColumnName(ii)).toUpperCase();
            String value = rs.getString(ii);
            Element node = xmlDocumentResult.createElement(createXmlName(columnName));
            if (!StringUtils.isBlank(value)) {
                Text textNode = xmlDocumentResult.createTextNode(value.toString());
                node.appendChild(textNode);
            }
            rowElement.appendChild(node);
        }
        resultSetElement.appendChild(rowElement);
    }
    return xmlDocumentResult;
}

From source file:adapter.gbase.signalling.SignallingAdapter.java

@Override
public SignallingDetailEntity getSignallingDetail(String tabName, String startDate, String endDate,
        String phone, String xdrId, String rowKey) throws Exception {
    SignallingDetailEntity signallingDetail = new SignallingDetailEntity();
    Statement statement = null;//from  w w w .j  a va  2 s .c  om
    ResultSet resultSet = null;
    try {
        statement = DbKit.getConfig("gbase").getConnection().createStatement();
        String sql = "";
        if (tabName.equals("gn")) {
            sql = "SELECT `xdr_id`,`imsi`,`msisdn`,`imei`,`imei_tac`,`tac`,`eci`,`sgw_ip`,`sgw_port`,`apn`,`start_time`,`end_time`,`time_hour`,`time_day`,`protocol`,`app_type`,`app_subtype`,`app_content`,`app_status`,`user_ip`,`user_ip_type`,`user_port`,`l4_protocol`,`appserver_ip`,`appserver_ip_type`,`appserver_port`,`ulthroughput`,`dlthroughput`,`ulpackets`,`dlpackets`,`ultcp_disorder_packets`,`dltcp_disorder_packets`,`ultcp_retransfer_packets`,`dltcp_retransfer_packets`,`ultcp_response_time`,`dltcp_response_time`,`ultcp_flag_packets`,`dltcp_flag_packets`,`tcplink_response_time1`,`tcplink_response_time2`,`window_size`,`mss_size`,`tcplink_count`,`tcplink_state`,`finish`,`session_duration` FROM `dw`.`f_ms_s1u_general`";
            sql += " where 2>1";
            if (startDate != null) {
                sql += " and start_time=" + startDate;
            }
            if (endDate != null) {
                sql += " and end_time=" + endDate;
            }
            if (xdrId != "" && xdrId != null) {
                sql += " and xdr_id='" + xdrId + "'";
            }
            if (phone != "" && phone != null) {
                sql += " and msisdn=" + phone;
            }
            sql += " limit 0,1";
        } else if (tabName.equals("http")) {
            sql = "  SELECT `xdr_id`,`imsi`,`msisdn`,`imei`,`imei_tac`,`tac`,`eci`,`sgw_ip`,`sgw_port`,`apn`,`start_time`,`end_time`,`time_hour`,`time_day`,`protocol`,`app_type`,`app_subtype`,`app_content`,`app_status`,`user_ip`,`user_ip_type`,`user_port`,`l4_protocol`,`appserver_ip`,`appserver_ip_type`,`appserver_port`,`ulthroughput`,`dlthroughput`,`ulpackets`,`dlpackets`,`ultcp_disorder_packets`,`dltcp_disorder_packets`,`ultcp_retransfer_packets`,`dltcp_retransfer_packets`,`ultcp_response_time`,`dltcp_response_time`,`ultcp_flag_packets`,`dltcp_flag_packets`,`tcplink_response_time1`,`tcplink_response_time2`,`window_size`,`mss_size`,`tcplink_count`,`tcplink_state`,`finish`,`http_version`,`trans_type`,`http_status_code`,`response_time`,`lastpacket_delay`,`lastpacket_ack_delay`,`host`,`uri1`,`x_online_host`,`useragent`,`content_type`,`refer_uri`,`cookie`,`content_length`,`target_behavior`,`wtp_suspend_type`,`wtp_suspend_cause`,`title`,`keyword`,`action`,`succ_flag`,`action_delay`,`browse_tool`,`portals`,`session_duration` FROM `dw`.`f_ms_s1u_http`";
            sql += " where 2>1";
            if (startDate != null) {
                sql += " and start_time=" + startDate;
            }
            if (endDate != null) {
                sql += " and end_time=" + endDate;
            }
            if (xdrId != "" && xdrId != null) {
                sql += " and xdr_id='" + xdrId + "'";
            }
            if (phone != "" && phone != null) {
                sql += " and msisdn=" + phone;
            }
            sql += " limit 0,1";
        } else if (tabName.equals("dns")) {
            sql = "SELECT `xdr_id`,`imsi`,`msisdn`,`imei`,`imei_tac`,`tac`,`eci`,`sgw_ip`,`sgw_port`,`apn`,`start_time`,`end_time`,`time_hour`,`time_day`,`protocol`,`app_type`,`app_subtype`,`app_content`,`app_status`,`user_ip`,`user_ip_type`,`user_port`,`l4_protocol`,`appserver_ip`,`appserver_ip_type`,`appserver_port`,`ulthroughput`,`dlthroughput`,`ulpackets`,`dlpackets`,`ultcp_disorder_packets`,`dltcp_disorder_packets`,`ultcp_retransfer_packets`,`dltcp_retransfer_packets`,`ultcp_response_time`,`dltcp_response_time`,`ultcp_flag_packets`,`dltcp_flag_packets`,`tcplink_response_time1`,`tcplink_response_time2`,`window_size`,`mss_size`,`tcplink_count`,`tcplink_state`,`finish`,`domain`,`query_result_ip`,`dns_reply_code`,`dns_request_count`,`dns_response_count`,`dns_licensed_content`,`dns_add_content`,`session_duration` FROM `dw`.`f_ms_s1u_dns`";
            sql += " where 2>1";
            if (startDate != null) {
                sql += " and start_time=" + startDate;
            }
            if (endDate != null) {
                sql += " and end_time=" + endDate;
            }
            if (xdrId != "" && xdrId != null) {
                sql += " and xdr_id='" + xdrId + "'";
            }
            if (phone != "" && phone != null) {
                sql += " and msisdn=" + phone;
            }
            sql += " limit 0,1";
        } else if (tabName.equals("im")) {
            sql = "SELECT `xdr_id`,`imsi`,`msisdn`,`imei`,`imei_tac`,`tac`,`eci`,`sgw_ip`,`sgw_port`,`apn`,`start_time`,`end_time`,`time_hour`,`time_day`,`protocol`,`app_type`,`app_subtype`,`app_content`,`app_status`,`user_ip`,`user_ip_type`,`user_port`,`l4_protocol`,`appserver_ip`,`appserver_ip_type`,`appserver_port`,`ulthroughput`,`dlthroughput`,`ulpackets`,`dlpackets`,`ultcp_disorder_packets`,`dltcp_disorder_packets`,`ultcp_retransfer_packets`,`dltcp_retransfer_packets`,`ultcp_response_time`,`dltcp_response_time`,`ultcp_flag_packets`,`dltcp_flag_packets`,`tcplink_response_time1`,`tcplink_response_time2`,`window_size`,`mss_size`,`tcplink_count`,`tcplink_state`,`finish`,`username`,`version`,`client_type`,`content_type`,`session_duration` FROM `dw`.`f_ms_s1u_im`";
            sql += " where 2>1";
            if (startDate != null) {
                sql += " and start_time=" + startDate;
            }
            if (endDate != null) {
                sql += " and end_time=" + endDate;
            }
            if (xdrId != "" && xdrId != null) {
                sql += " and xdr_id='" + xdrId + "'";
            }
            if (phone != "" && phone != null) {
                sql += " and msisdn=" + phone;
            }
            sql += " limit 0,1";
        } else if (tabName.equals("mme")) {
            sql = "SELECT `xdr_id`,`imsi`,`msisdn`,`imei`,`imei_tac`,`tac`,`eci`,`other_tac`,`other_eci`,`apn`,`mme_ip`,`mme_port`,`start_time`,`end_time`,`time_hour`,`time_day`,`procedure_type`,`procedure_status`,`request_cause`,`failure_cause`,`eps_bearer_number`,`bearer_1_id`,`bearer_1_type`,`bearer_1_qci`,`bearer_1_status`,`bearer_1_request_cause`,`bearer_1_failure_cause`,`bearer_1_enb_gtp_teid`,`bearer_1_sgw_gtp_teid`,`bearer_2_id`,`bearer_2_type`,`bearer_2_qci`,`bearer_2_status`,`bearer_2_request_cause`,`bearer_2_failure_cause`,`bearer_2_enb_gtp_teid`,`bearer_2_sgw_gtp_teid`,`session_duration` FROM `dw`.`f_ms_s1mme`";
            sql += " where 2>1";
            if (startDate != null) {
                sql += " and start_time=" + startDate;
            }
            if (endDate != null) {
                sql += " and end_time=" + endDate;
            }
            if (xdrId != "" && xdrId != null) {
                sql += " and xdr_id='" + xdrId + "'";
            }
            if (phone != "" && phone != null) {
                sql += " and msisdn=" + phone;
            }
            sql += " limit 0,1";
        }

        System.out.println(sql);
        resultSet = statement.executeQuery(sql);

        String cols = "";
        JSONArray array = new JSONArray();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            String columnName = metaData.getColumnLabel(i);
            if (!cols.equals("")) {
                cols += ",";
            }
            cols += columnName;
        }
        while (resultSet.next()) {
            JSONObject jsonObj = new JSONObject();

            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                String value = resultSet.getString(columnName);
                jsonObj.put(columnName, value);
            }
            array.add(jsonObj);
        }
        signallingDetail.setSql(sql);
        signallingDetail.setCols(cols);
        signallingDetail.setJsonArray(array);
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (!resultSet.equals(null)) {
            resultSet.close();
        }
    }

    return signallingDetail;
}

From source file:edu.ku.brc.specify.conversion.MSULichensFixer.java

private void convertTaxonRecords() {
    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);

    txMapper = IdMapperMgr.getInstance().addTableMapper("taxonname", "TaxonNameID", false);
    txTypMapper = IdMapperMgr.getInstance().addTableMapper("TaxonomyType", "TaxonomyTypeID", false);
    txUnitTypMapper = IdMapperMgr.getInstance().addTableMapper("TaxonomicUnitType", "TaxonomicUnitTypeID",
            false);//  ww  w .  j a  va2  s . com
    mappers = new IdMapperIFace[] { txMapper, txMapper, txTypMapper, txMapper, txUnitTypMapper };

    newToOldColMap.put("TaxonID", "TaxonNameID");
    newToOldColMap.put("ParentID", "ParentTaxonNameID");
    newToOldColMap.put("TaxonTreeDefID", "TaxonomyTypeID");
    newToOldColMap.put("TaxonTreeDefItemID", "TaxonomicUnitTypeID");
    newToOldColMap.put("Name", "TaxonName");
    newToOldColMap.put("FullName", "FullTaxonName");
    newToOldColMap.put("IsAccepted", "Accepted");

    oldToNewColMap.put("TaxonNameID", "TaxonID");
    oldToNewColMap.put("ParentTaxonNameID", "ParentID");
    oldToNewColMap.put("TaxonomyTypeID", "TaxonTreeDefID");
    oldToNewColMap.put("TaxonomicUnitTypeID", "TaxonTreeDefItemID");
    oldToNewColMap.put("TaxonName", "Name");
    oldToNewColMap.put("FullTaxonName", "FullName");
    oldToNewColMap.put("Accepted", "IsAccepted");

    BasicSQLUtils.setDBConnection(newDBConn);

    StringBuilder newSB = new StringBuilder();
    StringBuilder vl = new StringBuilder();
    for (int i = 0; i < cols.length; i++) {
        fieldToColHash.put(cols[i], i + 1);
        colToFieldHash.put(i + 1, cols[i]);

        if (newSB.length() > 0)
            newSB.append(", ");
        newSB.append(cols[i]);

        if (vl.length() > 0)
            vl.append(',');
        vl.append('?');
    }

    StringBuilder oldSB = new StringBuilder();
    for (int i = 0; i < oldCols.length; i++) {
        oldFieldToColHash.put(oldCols[i], i + 1);
        if (oldSB.length() > 0)
            oldSB.append(", ");
        oldSB.append("ttx.");
        oldSB.append(oldCols[i]);
    }

    rankIdOldDBInx = oldFieldToColHash.get("RankID");

    String sqlStr = String.format("SELECT %s FROM taxon ", newSB.toString());
    log.debug(sqlStr);

    String fromClause = " FROM taxonname ttx LEFT JOIN msu_lichens.taxonname_TaxonNameID ON OldID = ttx.TaxonNameID LEFT JOIN msu_lichens_6.taxon AS ntx ON NewID = ntx.TaxonID WHERE ntx.TaxonID IS NULL";
    String sql = String.format("SELECT %s %s", oldSB.toString(), fromClause);
    log.debug(sql);

    String cntSQL = String.format("SELECT COUNT(*) %s", fromClause);
    log.debug(cntSQL);

    int txCnt = BasicSQLUtils.getCountAsInt(oldDBConn, cntSQL);
    if (frame != null) {
        frame.setProcess(0, txCnt);
    }

    log.debug(txCnt);

    String pStr = String.format("INSERT INTO taxon (%s) VALUES (%s)", newSB.toString(), vl.toString());
    log.debug(pStr);

    try {
        stmtTx = newDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs1 = stmtTx.executeQuery(sqlStr);
        ResultSetMetaData rsmd1 = rs1.getMetaData();
        colTypes = new int[rsmd1.getColumnCount()];
        colSizes = new int[rsmd1.getColumnCount()];
        for (int i = 0; i < colTypes.length; i++) {
            colTypes[i] = rsmd1.getColumnType(i + 1);
            colSizes[i] = rsmd1.getPrecision(i + 1);
        }
        rs1.close();
        stmtTx.close();

        missingParentTaxonCount = 0;
        lastEditedByInx = oldFieldToColHash.get("LastEditedBy");
        modifiedByAgentInx = fieldToColHash.get("ModifiedByAgentID");
        stmtTx = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        pStmtTx = newDBConn.prepareStatement(pStr);

        int cnt = 0;
        ResultSet rs = stmtTx.executeQuery(sql);
        ResultSetMetaData rsmd = rs.getMetaData();
        while (rs.next()) {
            processRow(rs, rsmd, null);

            cnt++;
            if (cnt % 1000 == 0) {
                log.debug(cnt);
                if (frame != null) {
                    frame.setProcess(cnt);
                }
            }
        }
        rs.close();

        if (frame != null) {
            frame.setProcess(txCnt, txCnt);
        }

        String msg = String.format("Stranded Taxon (no parent): %d", missingParentTaxonCount);
        tblWriter.log(msg);
        log.debug(msg);

        if (missingParentTaxonCount > 0) {
            if (frame != null)
                frame.setDesc("Renumbering the tree nodes, this may take a while...");

            HashSet<Integer> ttdHash = new HashSet<Integer>();
            for (CollectionInfo colInfo : CollectionInfo.getFilteredCollectionInfoList()) {
                if (!ttdHash.contains(colInfo.getTaxonTreeDef().getId())) {
                    DataProviderSessionIFace session = null;
                    try {
                        session = DataProviderFactory.getInstance().createSession();

                        TaxonTreeDef taxonTreeDef = colInfo.getTaxonTreeDef();
                        taxonTreeDef = (TaxonTreeDef) session
                                .getData("FROM TaxonTreeDef WHERE id = " + taxonTreeDef.getId());

                        sql = "SELECT TaxonID FROM taxon WHERE RankID = 0 AND TaxonTreeDefID = "
                                + taxonTreeDef.getId();
                        log.debug(sql);
                        Integer txRootId = BasicSQLUtils.getCount(sql);
                        Taxon txRoot = (Taxon) session.getData("FROM Taxon WHERE id = " + txRootId);

                        NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem> nodeNumberer = new NodeNumberer<Taxon, TaxonTreeDef, TaxonTreeDefItem>(
                                txRoot.getDefinition());
                        nodeNumberer.doInBackground();

                    } catch (Exception ex) {
                        //session.rollback();
                        ex.printStackTrace();

                    } finally {
                        if (session != null) {
                            session.close();
                        }
                    }
                    ttdHash.add(colInfo.getTaxonTreeDef().getId());
                }
            }
            if (frame != null)
                frame.setDesc("Renumbering done.");
        }
        missingParentTaxonCount = 0;

    } catch (SQLException ex) {
        ex.printStackTrace();

    } finally {
        try {
            stmtTx.close();
            pStmtTx.close();
        } catch (Exception ex) {
        }
    }

    System.out.println("Done.");
}

From source file:com.bitnine.tadpole.graph.core.editor.extension.browserHandler.CypherFunctionService.java

/**
 * Sigma.js ?? ?   ./*w w w . jav  a 2  s . co m*/
 * 
 * @param nodeJsonString
 * @return
 */
protected String loadDataWithSigma(final String nodeJsonString) {
    String result = "";

    JsonObject jsonNode = JsonObject.readFrom(nodeJsonString);

    ResultSet rs = null;
    java.sql.Connection javaConn = null;
    Statement statement = null;

    try {

        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

        String reqQuery = "match (n)-[r]->(p) where id(n) = '" + jsonNode.get("id").asString()
                + "' return n, r, p UNION match (n)-[r]->(p) where id(p) = '" + jsonNode.get("id").asString()
                + "' return n, r, p";
        if (logger.isDebugEnabled())
            logger.debug("Execute Math CQL : " + reqQuery);

        javaConn = client.getDataSource().getConnection();
        statement = javaConn.createStatement();

        rs = statement.executeQuery(reqQuery);
        ResultSetMetaData rsmt = rs.getMetaData();

        SigmaGraph graph = new SigmaGraph();
        Node node = null;
        GEdge edge = null;
        long row = 0;
        double parentAngle = 0;
        double angleDeg = 0;
        double nx = 0;
        double ny = 0;

        while (rs.next()) {
            row++;
            for (int columnIndex = 1; columnIndex <= rsmt.getColumnCount(); columnIndex++) {

                Object obj = rs.getObject(columnIndex);

                if (obj instanceof Vertex) {
                    node = new Node();

                    Vertex vertex = (Vertex) obj;
                    node.setLabel(vertex.getLabel());
                    angleDeg = (((360 / (rsmt.getColumnCount() * 10)) * (columnIndex * row)));
                    nx = jsonNode.get("x").asDouble()
                            + (100 * Math.cos((angleDeg * (Math.PI / 180)) - parentAngle));
                    ny = jsonNode.get("y").asDouble()
                            + (100 * Math.sin((angleDeg * (Math.PI / 180)) - parentAngle));
                    node.setX(nx);
                    node.setY(ny);

                    node.setColor(AgensUtils.getRandomRGB());
                    node.setSize(500);
                    graph.addNode(node);

                } else if (obj instanceof Edge) {

                    edge = new GEdge();
                    Edge relation = (Edge) obj;
                    edge.setId(relation.getEdgeId().getOid() + "." + relation.getEdgeId().getId());
                    edge.setLabel(relation.getLabel());
                    edge.setSource(
                            relation.getStartVertexId().getOid() + "." + relation.getStartVertexId().getId());
                    edge.setTarget(
                            relation.getEndVertexid().getOid() + "." + relation.getEndVertexid().getId());
                    edge.setType("arrow");//'line', 'curve', 'arrow', 'curvedArrow'
                    edge.setColor(AgensUtils.getRandomRGB("100"));
                    edge.setSize(0.5);

                    if (logger.isDebugEnabled())
                        logger.debug("Relation is " + relation.toString() + ", edge is " + edge.toString());

                    graph.addEdge(edge);
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Unknow Class " + obj.getClass().toString());
                }
            }
        }

        Gson gson = new Gson();
        result = gson.toJson(graph);

        if (logger.isDebugEnabled())
            logger.debug("##### Graph ####====>" + result);

    } catch (Exception e) {
        logger.error(e);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        try {
            if (javaConn != null)
                javaConn.close();
        } catch (Exception e) {
        }

    }
    return result;
}

From source file:com.yahoo.dba.perf.myperf.springmvc.UdmController.java

/**
 * /*w ww. j a  va2  s.  c om*/
 * Test UDM, use exception to send out message
 * @param req
 * @param udm
 * @param db
 * @throws SQLException
 */
private void testUDM(HttpServletRequest req, UserDefinedMetrics udm, String db) throws Exception {
    if (db == null || db.isEmpty())
        throw new Exception("please provide valid database for test");

    String[] dbs = db.split("\\|");
    if (dbs == null || dbs.length < 2)
        throw new Exception("please provide valid database for test");
    DBInstanceInfo dbinfo = this.frameworkContext.getDbInfoManager().findDB(dbs[0], dbs[1]);
    if (dbinfo == null)
        throw new Exception("please provide valid database for test");

    HashSet<String> metricsNameSet = new HashSet<String>();
    for (Metric m : udm.getMetrics()) {
        metricsNameSet.add(m.getSourceName());
    }
    DBConnectionWrapper connWrapper = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        String sql = udm.getSql();
        MetricsGroup mg = udm.getMetricsGroup();
        String udmType = udm.getUdmType();
        String nameCol = udm.getNameCol();
        String valCol = udm.getValueCol();
        String keyCol = udm.getKeyCol();
        boolean isBuiltin = false;
        if (!"SQL".equals(udm.getSource())) {
            sql = this.frameworkContext.getSqlTextForMetricsGroup(udm.getSource());
            mg = this.frameworkContext.getMetricsDef().getGroupByName(udm.getSource());
            if (mg != null) {
                if (mg.getKeyColumn() != null)
                    udmType = "key";
                else if (mg.isMultipleMetricsPerRow())
                    udmType = "column";
                else
                    udmType = "row";
                nameCol = mg.getMetricNameColumn();
                valCol = mg.getMetricValueColumn();
                keyCol = mg.getKeyColumn();
            }
            isBuiltin = true;
        }
        if (sql == null || sql.isEmpty()) {
            throw new Exception("please provide valid SQL");
        }
        connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo);
        if (connWrapper == null) {
            throw new Exception("failed to connect to target db (" + dbinfo + ")");
        }
        stmt = connWrapper.getConnection().createStatement();
        rs = stmt.executeQuery(sql);
        if (rs != null) {
            ResultSetMetaData meta = rs.getMetaData();
            //verify columns
            int cols = meta.getColumnCount();
            Map<String, Integer> colMap = new HashMap<String, Integer>(cols);
            for (int i = 1; i <= cols; i++)
                colMap.put(meta.getColumnName(i).toUpperCase(), meta.getColumnType(i));
            if ("row".equals(udmType)) {
                if (!colMap.containsKey(udm.getNameCol().toUpperCase()))
                    throw new Exception("Failed to find name column from SQL result: " + udm.getNameCol()
                            + ", returned: " + colMap);
                if (!colMap.containsKey(udm.getValueCol().toUpperCase()))
                    throw new Exception("Failed to find value column from SQL result: " + udm.getValueCol()
                            + ", returned: " + colMap);
            } else //check metrics column 
            {
                if ("key".equals(udmType)) {
                    if (!colMap.containsKey(keyCol.toUpperCase()))
                        throw new Exception("Failed to find key column from SQL result: " + udm.getKeyCol());
                }
                for (Metric m : udm.getMetrics()) {
                    if (!colMap.containsKey(m.getSourceName().toUpperCase()))
                        throw new Exception(
                                "Failed to find metric column from SQL result: " + m.getSourceName());
                }
            }
        } else {
            throw new Exception("Failed to test SQL.");
        }
        while (rs != null && rs.next()) {
            if ("row".equals(udmType)) {
                String name = rs.getString(nameCol);
                if (!metricsNameSet.contains(name))
                    continue;
                String val = rs.getString(valCol);
                try {
                    BigDecimal d = new BigDecimal(val == null ? "0" : val);
                } catch (Exception ex) {
                    throw new Exception("Expect numeric value for metric from SQL result, got " + val);
                }
            } else {
                for (Metric m : udm.getMetrics()) {
                    String val = rs.getString(m.getSourceName());
                    try {
                        BigDecimal d = new BigDecimal(val == null ? "0" : val);
                    } catch (Exception ex) {
                        throw new Exception("Expect numeric value metric value from SQL result for column "
                                + m.getShortName() + ", got " + val);
                    }
                }
            }

        }
    } finally {
        DBUtils.close(rs);
        DBUtils.close(stmt);
        WebAppUtil.closeDBConnection(req, connWrapper, true);//close it anyway
    }
}

From source file:CSVWriter.java

public String[] getColumnNames(ResultSet rs) throws SQLException {
    List<String> names = new ArrayList<String>();
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        names.add(metadata.getColumnName(i + 1));
    }//from  w  w w. j a v a 2  s .c  om

    String[] nameArray = new String[names.size()];
    return names.toArray(nameArray);
}

From source file:edu.ku.brc.specify.toycode.mexconabio.DataObjTableModel.java

/**
 * The Data members must be set to call this:
 *     numColumns/*w w w .ja v a2 s  .c  om*/
 *     itemsList
 * 
 */
protected void fillModels() {
    final String sqlStr = buildSQL();

    TimeLogger tml = new TimeLogger("Fetching Rows");
    values = new Vector<Object[]>();

    if (StringUtils.isNotEmpty(sqlStr)) {
        log.debug(sqlStr);
        try {
            PreparedStatement pStmt = conn.prepareStatement(sqlStr);
            if (searchValue != null) {
                pStmt.setObject(1, searchValue);
            }
            log.debug(sqlStr + " [" + searchValue + "]");

            tml.restart("Query");
            ResultSet rs = pStmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();

            tml.restart("Loading");
            while (rs.next()) {
                Object[] row = new Object[numColumns];
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    Object obj = rs.getObject(i + 1);
                    row[i] = obj instanceof String ? obj.toString().trim() : obj;
                }
                rowInfoList.add(new DataObjTableModelRowInfo(rs.getInt(1), false, false));
                values.add(row);
                processColumns(row);
            }
            rs.close();
            pStmt.close();
            tml.end();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    tml.restart("Step 2 - Addl Rows");
    addAdditionalRows(colDefItems, rowInfoList);

    tml.restart("Step 3");

    sameValues = new ArrayList<Boolean>(numColumns);
    hasDataList = new ArrayList<Boolean>(numColumns);
    for (int i = 0; i < numColumns; i++) {
        sameValues.add(true);
        hasDataList.add(false);
    }

    for (Object[] col : values) {
        for (int i = 0; i < numColumns; i++) {
            Object data = col[i];
            boolean hasData = data != null;

            if (hasData && !hasDataList.get(i)) {
                hasDataList.set(i, true);
                hasDataCols++;
            }
        }
    }

    tml.restart("Step  4 - adj cols");
    adjustHasDataColumns();

    tml.restart("Step  5 - Map");
    mapInx = new int[hasDataCols];
    int colInx = 0;
    //log.debug("-------------Has Data----------------------");
    for (int i = 0; i < numColumns; i++) {
        if (hasDataList.get(i)) {
            //log.debug(itemsList.get(i).getTitle());
            mapInx[colInx] = i;
            indexHash.put(i, colInx);
            //System.out.print("indexHash: "+i +" -> "+colInx);
            //log.debug("  mapInx:    "+colInx +" -> "+i);
            colInx++;
        }
    }

    tml.restart("Step  6 - same data");
    for (int i = 0; i < mapInx.length; i++) {
        colInx = mapInx[i];

        if (hasDataList.get(colInx)) {
            Object data = null;
            for (Object[] col : values) {
                Object newData = col[colInx];

                if (data == null) {
                    if (newData != null) {
                        data = newData;
                    }
                    continue;
                }

                if (newData != null && !data.equals(newData)) {
                    sameValues.set(colInx, false);
                    break;
                }
            }
        }
    }
    tml.end();
    /*
    log.debug("-----------Same------------------------");
    for (int i=0;i<mapInx.length;i++)
    {
        colInx = mapInx[i];
        if (sameValues.get(colInx))
        {
            log.debug(colInx + " " + itemsList.get(colInx).getTitle());
        }
    }*/

    items = new ArrayList<DBInfoBase>(colDefItems);
    doneFillingModels(values);
}

From source file:CSVWriter.java

public String[] getColumnValues(ResultSet rs) throws SQLException, IOException {

    List<String> values = new ArrayList<String>();
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        values.add(getColumnValue(rs, metadata.getColumnType(i + 1), i + 1));
    }//from  w w  w.  ja  va2  s.co m

    String[] valueArray = new String[values.size()];
    return values.toArray(valueArray);
}

From source file:cz.lbenda.dataman.db.DbStructureFactory.java

private void writeColumnNames(String columnsFrom, ResultSetMetaData metaData) throws SQLException {
    if (Constants.IS_IN_DEVELOP_MODE) {
        if (!columnsFromWriten.contains(columnsFrom)) {
            LOG.debug("Write column names: " + columnsFrom);
            columnsFromWriten.add(columnsFrom);
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                LOG.debug("Column: " + metaData.getColumnName(i) + " : " + metaData.getColumnLabel(i));
            }/*from   w w w.  ja  va 2s  . c  om*/
        }
    }
}

From source file:com.glaf.base.modules.todo.business.TodoJobBean.java

public void createTodoInstances(long todoId) {
    Todo todo = todoService.getTodo(todoId);
    Map<String, TodoInstance> rowsMap = new java.util.HashMap<String, TodoInstance>();
    java.sql.Connection conn = null;
    java.sql.PreparedStatement psmt = null;
    java.sql.ResultSet rs = null;
    try {/*from  w  w w.  jav  a  2 s .  co m*/
        conn = DBConnectionFactory.getConnection();
        psmt = conn.prepareStatement(todo.getSql());
        rs = psmt.executeQuery();
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        while (rs.next()) {
            TodoInstance model = new TodoInstance();
            model.setRowId(rs.getString(1));
            model.setStartDate(rs.getDate(2));
            if (rsmd.getColumnCount() == 3) {
                switch (new Long(todo.getId()).intValue()) {
                case 8005:
                case 7001:
                case 7002:
                case 7003:
                case 7004:
                case 17001:
                case 17010:
                case 18001:
                case 19001:
                case 20001:
                case 20084001:
                    model.setDeptId(rs.getLong(3));
                    break;
                default:
                    model.setActorId(rs.getString(3));
                    break;
                }
            }
            rowsMap.put(model.getRowId(), model);
        }
        rs.close();
        psmt.close();
        rs = null;
        psmt = null;
    } catch (java.sql.SQLException ex) {
        ex.printStackTrace();
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
    }

    List<TodoInstance> rows = new java.util.ArrayList<TodoInstance>();

    if (rowsMap.size() > 0) {
        Iterator<String> iter = rowsMap.keySet().iterator();
        while (iter.hasNext()) {
            String rowId = (String) iter.next();
            TodoInstance model = (TodoInstance) rowsMap.get(rowId);
            Date startDate = model.getStartDate();
            if (startDate == null) {
                startDate = new java.util.Date();
            }

            model.setProvider("sql");
            model.setLinkType(todo.getLinkType());
            model.setAppId(todo.getAppId());
            model.setModuleId(todo.getModuleId());
            model.setTodoId(todo.getId());
            model.setRoleId(todo.getRoleId());
            model.setRoleCode(todo.getRoleCode());
            model.setTitle(todo.getTitle());
            model.setCreateDate(new Date(System.currentTimeMillis()));
            model.setStartDate(startDate);
            int limitDay = todo.getLimitDay();
            int ahour = todo.getXa();
            int bhour = todo.getXb();

            Date limitWorkDate = workCalendarService.getWorkDate(startDate, limitDay);
            long time = limitWorkDate.getTime();

            Date cautionDate = new Date(time - ahour * DateUtils.HOUR);
            Date pastDueDate = new Date(time + bhour * DateUtils.HOUR);
            model.setAlarmDate(cautionDate);
            model.setPastDueDate(pastDueDate);
            model.setRowId(rowId);
            model.setVersionNo(System.currentTimeMillis());
            rows.add(model);
        }
    }

    todoService.createTodoInstances(todoId, rows);

}