Example usage for java.sql ResultSetMetaData getColumnLabel

List of usage examples for java.sql ResultSetMetaData getColumnLabel

Introduction

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

Prototype

String getColumnLabel(int column) throws SQLException;

Source Link

Document

Gets the designated column's suggested title for use in printouts and displays.

Usage

From source file:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java

@Override
public ResultVO executePlainQueryAsResultVO(String sql, int maxRows) throws DbException {
    return executePlainQuery(sql, maxRows, new ResultSetRunner<ResultVO>() {
        @Override/*w  ww  . j  a  v a  2  s  .c  o  m*/
        public ResultVO perform(ResultSet rs) throws SQLException {
            ResultVO result = new ResultVO();
            ResultSetMetaData metadata = rs.getMetaData();

            Class<?>[] javaTypes = new Class<?>[metadata.getColumnCount()];
            for (int i = 0; i < metadata.getColumnCount(); i++) {
                ResultColumnVO column = new ResultColumnVO();
                column.setColumnLabel(metadata.getColumnLabel(i + 1));

                DbGenericType type = getDbGenericType(metadata.getColumnType(i + 1),
                        metadata.getColumnTypeName(i + 1));
                if (type != null) {
                    Class<?> javaType = type.getPreferredJavaType();
                    // override java type here @todo this is not the right place.
                    if (type == DbGenericType.NUMERIC) {
                        if (metadata.getScale(i + 1) == 0)
                            javaType = Integer.class;
                        else
                            javaType = Double.class;
                    }
                    column.setColumnClassName(javaType.getName());
                    javaTypes[i] = javaType;
                } else {
                    column.setColumnClassName(metadata.getColumnClassName(i + 1));
                    javaTypes[i] = Object.class;
                }
                result.addColumn(column);
            }
            while (rs.next()) {
                final Object[] values = new Object[javaTypes.length];
                for (int i = 0; i < values.length; i++) {
                    values[i] = getResultSetValue(rs, i + 1, javaTypes[i]);
                }
                result.addRow(values);
            }
            return result;
        }
    });
}

From source file:org.siphon.jssql.SqlExecutor.java

/***
 * ??//  w ww.java 2s  . c  o m
 * @param connection
 * @param sql
 * @param args
 * @param travele  function(columns, row) , return true , return false 
 * @return
 * @throws SqlExecutorException 
 */
public void travel(Connection connection, String sql, NativeArray args, ScriptFunction traveler)
        throws SqlExecutorException {
    if (connection == null) {
        this.travel(sql, args, traveler);
        return;
    }

    long start = System.currentTimeMillis();

    PreparedStatement ps = null;
    ResultSet rs = null;
    boolean errorOccu = false;
    try {
        // logger.debug("execute travel " + sql + " with args: " +
        // JSON.tryStringify(args));

        ps = connection.prepareStatement(sql);
        setArgs(ps, args);
        rs = ps.executeQuery();
        ResultSetMetaData rsm = rs.getMetaData();
        ScriptObjectMirror columns = columnListToNativeArray(rsm);
        while (rs.next()) {
            ScriptObjectMirror item = jsTypeUtil.newObject();
            for (int i = 1; i <= rsm.getColumnCount(); i++) {
                String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i);
                String label = convertColumnName(cname);
                item.put(cname, fieldValueToNativeObject(rsm.getColumnType(i), rs, cname));
            }
            Object result = NativeFunction.call(traveler, traveler, item.to(ScriptObject.class), columns); // traveler.callMember("call", traveler, item, columns);
            if (JsTypeUtil.isTrue(result)) {
                break;
            }
        }
    } catch (SQLException | UnsupportedDataTypeException | ScriptException | NoSuchMethodException e) {
        errorOccu = true;
        throw new SqlExecutorException(
                "error occurs when query " + sql + " with args : " + JSON.tryStringify(args), e);
    } finally {
        long exhaust = System.currentTimeMillis() - start;
        if (exhaust > 30000) {
            logger.warn(String.format("%s with args:%s exhaust %s", sql, args, exhaust));
        }
        DbConnectionUtil.close(rs);
        DbConnectionUtil.close(ps);
    }
}

From source file:org.siphon.jssql.SqlExecutor.java

private ScriptObjectMirror columnListToNativeArray(ResultSetMetaData rsm) throws SQLException, ScriptException {
    ScriptObjectMirror arr = jsTypeUtil.newArray();
    NativeArray narr = arr.to(NativeArray.class);
    // JSON.stringify(arr)
    for (int i = 1; i <= rsm.getColumnCount(); i++) {
        ScriptObjectMirror obj = jsTypeUtil.newObject();
        String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i);
        String label = convertColumnName(cname);
        obj.put("name", label);
        obj.put("type", translateTypeName(rsm.getColumnType(i), rsm.getColumnTypeName(i)));
        // NativeArray.pushObject(narr, obj.to(ScriptObject.class));
        arr.callMember("push", obj);
    }//from   ww w.ja  v  a2s  .  co m
    return arr;
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

/**
 * Adds a property that is represented as a result set to the current element in the given xml writer.
 * /*from   www .j a v  a2s.  c  om*/
 * @param xmlWriter The XML writer to write to
 * @param name      The name of the property
 * @param result    The values of the property as a result set
 */
private void addResultSetProperty(PrettyPrintingXmlWriter xmlWriter, String name, ResultSet result) {
    String propName = name;

    if (propName.endsWith("s")) {
        propName = propName.substring(0, propName.length() - 1);
    }

    try {
        ResultSetMetaData metaData = result.getMetaData();

        xmlWriter.writeElementStart(null, propName + "s");
        try {
            while (result.next()) {
                xmlWriter.writeElementStart(null, propName);

                try {
                    for (int idx = 1; idx <= metaData.getColumnCount(); idx++) {
                        Object value = result.getObject(idx);

                        addProperty(xmlWriter, metaData.getColumnLabel(idx), value);
                    }
                } finally {
                    xmlWriter.writeElementEnd();
                }
            }
        } finally {
            xmlWriter.writeElementEnd();
        }
    } catch (SQLException ex) {
        log("Could not read the result set metadata: " + ex.getStackTrace(), Project.MSG_ERR);
    }
}

From source file:esg.node.security.UserInfoDAO.java

public void init() {

    this.idResultSetHandler = new ResultSetHandler<Integer>() {
        public Integer handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return -1;
            }// w w  w .jav  a2 s.co  m
            return rs.getInt(1);
        }
    };

    this.booleanResultSetHandler = new ResultSetHandler<Boolean>() {
        public Boolean handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return false;
            }
            return rs.getBoolean(1);
        }
    };

    this.existsResultSetHandler = new ResultSetHandler<Boolean>() {
        public Boolean handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return false;
            }
            return (rs.getInt(1) > 0);
        }
    };

    this.singleStringResultSetHandler = new ResultSetHandler<String>() {
        public String handle(ResultSet rs) throws SQLException {
            if (!rs.next()) {
                return null;
            }
            return rs.getString(1);
        }
    };

    passwordQueryHandler = new ResultSetHandler<String>() {
        public String handle(ResultSet rs) throws SQLException {
            String password = null;
            while (rs.next()) {
                password = rs.getString(1);
            }
            return password;
        }
    };

    //To handle the single record result
    userInfoResultSetHandler = new ResultSetHandler<UserInfo>() {
        public UserInfo handle(ResultSet rs) throws SQLException {
            UserInfo userInfo = null;
            while (rs.next()) {
                userInfo = new UserInfo();
                userInfo.setid(rs.getInt(1)).setOpenid(rs.getString(2)).setFirstName(rs.getString(3))
                        .setMiddleName(rs.getString(4)).setLastName(rs.getString(5))
                        .setUserName(rs.getString(6)).setEmail(rs.getString(7)).setDn(rs.getString(8))
                        .setOrganization(rs.getString(9)).setOrgType(rs.getString(10)).setCity(rs.getString(11))
                        .setState(rs.getString(12)).setCountry(rs.getString(13)).setStatusCode(rs.getInt(14));
            }
            return userInfo;
        }
    };

    userPermissionsResultSetHandler = new ResultSetHandler<Map<String, Set<String>>>() {
        Map<String, Set<String>> permissions = new HashMap<String, Set<String>>();
        Set<String> roleSet = null;

        public Map<String, Set<String>> handle(ResultSet rs) throws SQLException {
            permissions.clear();
            if (!rs.next()) {
                return permissions;
            }
            do {
                addPermission(rs.getString(1), rs.getString(2));
            } while (rs.next());
            return permissions;
        }

        public void addPermission(String groupName, String roleName) {
            //lazily instantiate the set of values for group if not
            //there
            if ((roleSet = permissions.get(groupName)) == null) {
                roleSet = new HashSet<String>();
            }

            //enter group associated with group value set
            roleSet.add(roleName);
            permissions.put(groupName, roleSet);
        }
    };

    basicResultSetHandler = new ResultSetHandler<List<String[]>>() {
        public List<String[]> handle(ResultSet rs) throws SQLException {
            ArrayList<String[]> results = new ArrayList<String[]>();
            String[] record = null;
            assert (null != results);

            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            log.trace("Number of fields: " + cols);

            log.trace("adding column data...");
            record = new String[cols];
            for (int i = 0; i < cols; i++) {
                try {
                    record[i] = meta.getColumnLabel(i + 1);
                } catch (SQLException e) {
                    log.error(e);
                }
            }
            results.add(record);

            for (int i = 0; rs.next(); i++) {
                log.trace("Looking at record " + (i + 1));
                record = new String[cols];
                for (int j = 0; j < cols; j++) {
                    record[j] = rs.getString(j + 1);
                    log.trace("gathering result record column " + (j + 1) + " -> " + record[j]);
                }
                log.trace("adding record ");
                results.add(record);
                record = null; //gc courtesy
            }
            return results;
        }
    };

    new InitAdmin();
}

From source file:org.siphon.jssql.SqlExecutor.java

private ScriptObjectMirror rsToDataTable(ResultSet rs)
        throws SQLException, SqlExecutorException, ScriptException {
    ResultSetMetaData rsm = rs.getMetaData();

    ScriptObjectMirror result = jsTypeUtil.newDataTable();
    int c = 0;/*from   w  ww. j  av  a 2s .c o m*/
    result.put("columns", columnListToNativeArray(rsm));

    ScriptObjectMirror arr = jsTypeUtil.newArray();
    NativeArray narr = arr.to(NativeArray.class);
    while (rs.next()) {
        ScriptObjectMirror item = jsTypeUtil.newObject();
        for (int i = 1; i <= rsm.getColumnCount(); i++) {
            String cname = this.useColumnLabelAsName ? rsm.getColumnLabel(i) : rsm.getColumnName(i);
            String label = convertColumnName(cname);
            item.put(label, fieldValueToNativeObject(rsm.getColumnType(i), rs, cname));
        }
        //NativeArray.pushObject(narr, item.to(ScriptObject.class));
        arr.callMember("push", item);
    }
    result.put("rows", arr);
    return result; // JSON.stringify(result)
}

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

@SuppressWarnings("unchecked")
protected List<Map<String, Object>> prepare(QueryDefinition query, Map<String, Object> paramMap) {
    logger.debug("-------------------------2 start------------------------");
    List<Map<String, Object>> resultList = new java.util.ArrayList<Map<String, Object>>();

    Connection conn = null;//from   ww  w. ja v  a 2 s  .  c om
    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("-------------------------2 connection------------------------");
        SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(query.getSql(), paramMap);
        logger.debug("--2 sql:" + sqlExecutor.getSql());
        psmt = conn.prepareStatement(sqlExecutor.getSql());
        if (sqlExecutor.getParameter() != null) {
            List<Object> values = (List<Object>) sqlExecutor.getParameter();
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        logger.debug("-------------------------2 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);
        }

        query.setResultList(resultList);

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

        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("-------------------------2 end------------------------");
    }
}

From source file:de.uniwue.info6.webapp.lists.ExerciseController.java

/**
 *
 *
 *///  ww w .j  a  va2  s.  co  m
public void compareResults() {
    boolean sameString = (this.lastUserString != null && this.userString != null
            && this.lastUserString.equals(this.userString));

    if (sameString || scenario == null || user == null) {
        return;
    }

    FacesMessage message1 = null;

    long timeSinceLastEntry = System.currentTimeMillis() - lastEntryTime;

    if (timeSinceLastEntry < timeIntervalBetweenInput) {
        Severity sev = FacesMessage.SEVERITY_INFO;
        // TODO: Text
        String msg = "Sie mssen " + Math.floor((timeIntervalBetweenInput - timeSinceLastEntry) / 1000)
                + " Sekunden bis zur nchsten Abgabe warten.";
        message1 = new FacesMessage(sev, Cfg.inst().getText("EX.SERVER_MESSAGE"), msg);
        FacesContext.getCurrentInstance().addMessage(null, message1);
        return;
    }

    this.lastUserString = this.userString;
    try {
        try {
            this.connectionPool.resetTables(scenario, user);
        } catch (Exception e) {
            LOGGER.error("COULD NOT RESET TABLES", e);
        }

        long starttime = System.currentTimeMillis();

        Connection connection = null;
        try {
            this.feedbackVisible = false;
            this.resultVisible = false;
            this.syntaxError = false;

            connection = connectionPool.getConnection(scenario);
            executer = new SqlExecuter(connection, user, scenario);

            SqlQueryComparator comparator = new SqlQueryComparator(userQuery, solutionQueries, executer);

            // get user feedback
            LinkedList<Error> errors = comparator.compare();
            usedSolutionQuery = comparator.getSolutionQuery();

            if (solutionQueries != null && !solutionQueries.isEmpty()) {
                usedSolutionIndex = solutionQueries.indexOf(usedSolutionQuery);
            }

            if (errors != null) {
                feedbackList = new ArrayList<UserFeedback>();
                for (Error er : errors) {
                    feedbackList.add(new UserFeedback(er, user));
                }
            }

            for (UserFeedback fd : feedbackList) {
                if (fd.isJavaError()) {
                    feedbackList.remove(fd);
                    break;
                }
            }

            boolean userEntrySuccess = false;

            String feedbackSummaryDB = "";

            for (UserFeedback fb : feedbackList) {
                if (fb.isSyntaxError()) {
                    syntaxError = true;
                }
                if (fb.isMainError()) {
                    userEntrySuccess = fb.isCorrect();
                } else {
                    String fd = fb.getFeedback();
                    if (!userEntrySuccess) {
                        feedbackSummaryDB += fb.getTitle() + ": " + fd + "<br/>";
                    }
                }
            }

            if (usedSolutionQuery == null || usedSolutionQuery.getResult() == null) {
                ArrayList<UserFeedback> newFeedbackList = new ArrayList<UserFeedback>();
                newFeedbackList.add(new UserFeedback(Cfg.inst().getProp(DEF_LANGUAGE, "QUE.UNEXPECTED_ERROR"),
                        Cfg.inst().getProp(DEF_LANGUAGE, "QUE.UNEXPECTED_ERROR2"), user));
                newFeedbackList.addAll(feedbackList);
                feedbackList = newFeedbackList;
                this.feedbackVisible = true;
                LOGGER.error("EMPTY SOLUTION RESULT, FAULTY SOLUTION-QUERY?\n" + feedbackSummaryDB);
            }

            if (usedSolutionQuery != null && usedSolutionQuery.getResult() != null) {
                /*
                 * **************************************************************
                 * get column-names and values from db solution-query
                 * **************************************************************
                 */

                if (solutionQueryValues == null || solutionQueryColumns == null || solutionQueryValues.isEmpty()
                        || solutionQueryColumns.isEmpty()) {
                    // setting correct solution
                    SqlResult sol_result = usedSolutionQuery.getResult();
                    String[][] data = sol_result.getData();
                    solutionQueryColumns = new ArrayList<String>();
                    solutionQueryValues = new ArrayList<TableEntry>();

                    ResultSetMetaData metaData = sol_result.getResultMetaData();
                    if (metaData != null) {
                        for (int i = 1; i <= metaData.getColumnCount(); i++) {
                            String name = metaData.getColumnLabel(i);

                            if (user != null && name != null && name.contains(user.getId() + "_")) {
                                name = name.replaceAll(user.getId() + "_", "");
                            }

                            if (name != null && !name.trim().isEmpty()) {
                                solutionQueryColumns.add(name);
                            }
                        }
                    }
                    if (data != null) {
                        for (int i = 0; i < data.length; i++) {
                            TableEntry en = new TableEntry(solutionQueryColumns);
                            for (int z = 0; z < data[i].length; z++) {
                                en.addValue(data[i][z], z);
                            }
                            solutionQueryValues.add(en);
                        }
                    }
                    filteredSolutionQueryValues = solutionQueryValues;
                    createSolutionQueryColumns();
                }

                if (showResults()) {
                    this.resultVisible = true;
                    this.feedbackVisible = true;
                }

                UserEntry entry = null;
                UserResult result = null;
                boolean userEntryAvailable = false;
                byte reachedCredits = userEntrySuccess ? exercise.getCredits() : 0;
                SolutionQuery usedQuery = null;

                int index = solutionQueries.indexOf(usedSolutionQuery);
                if (index < solutions.size()) {
                    usedQuery = solutions.get(index);
                }

                String msg = null;

                if (!userString.trim().isEmpty()
                        && (!isRated() || userRights.entriesCanBeEdited(exerciseGroup))) {

                    entry = userEntryDao.getLastEntry(exercise, user);
                    msg = Cfg.inst().getText("EX.SAVED_SUCCESSFUL");
                    if (entry != null) {
                        msg = Cfg.inst().getText("EX.OVERWRITING_SUCCESSFUL");
                    }

                    if (!showFeedback) {
                        querySaved = true;
                    }

                    if (Cfg.inst().getProp(PropertiesFile.MAIN_CONFIG, PropBool.ONLY_SAVE_LAST_USER_QUERY)) {
                        // String msg = Cfg.inst().getProp(DEF_LANGUAGE,
                        // "ASSERTION.FILTER5");
                        // TODO:
                        if (entry != null) {
                            entry.setUserQuery(userString);
                            entry.setEntryTime(new Date());
                            entry.setResultMessage(feedbackSummaryDB);
                            userEntryAvailable = userEntryDao.updateInstance(entry);
                            result = userResultDao.getLastUserResultFromEntry(entry);

                            if (result != null) {
                                result.setCredits(reachedCredits);
                                result.setLastModified(new Date());
                                result.setSolutionQuery(usedQuery);
                                result.setComment(feedbackSummaryDB);
                                userResultDao.updateInstance(result);
                            }
                        } else {
                            entry = new UserEntry(user, exercise, userString, new Date());
                            entry.setResultMessage(feedbackSummaryDB);
                            userEntryAvailable = userEntryDao.insertNewInstance(entry);
                        }
                    } else {
                        entry = new UserEntry(user, exercise, userString, new Date());
                        entry.setResultMessage(feedbackSummaryDB);
                        userEntryAvailable = userEntryDao.insertNewInstance(entry);
                    }

                    if (result == null && userEntryAvailable) {
                        result = new UserResult(entry, reachedCredits, new Date());
                        result.setSolutionQuery(usedQuery);
                        result.setComment(feedbackSummaryDB);
                        userResultDao.insertNewInstance(result);
                    }
                }

                if (isRated() && !debug) {
                    if (!userRights.entriesCanBeEdited(exerciseGroup)) {
                        msg = Cfg.inst().getText("EX.RATED_CLOSED");
                    }

                    if (msg != null) {
                        // show feedback message to user
                        Severity sev = FacesMessage.SEVERITY_INFO;
                        message1 = new FacesMessage(sev, Cfg.inst().getText("EX.SERVER_MESSAGE"), msg);
                    }
                }

                if (feedbackVisible) {
                    refLinks = comparator.getRefLinks();
                }

                if (!syntaxError) {
                    SqlResult sol_result = userQuery.getResult();
                    String[][] data = sol_result.getData();
                    userQueryColumns = new ArrayList<String>();
                    userQueryValues = new ArrayList<TableEntry>();

                    ResultSetMetaData metaData = sol_result.getResultMetaData();
                    if (metaData != null) {
                        if (!debug) {
                            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                                String name = metaData.getColumnLabel(i);

                                if (user != null && name != null && name.contains(user.getId() + "_")) {
                                    name = name.replaceAll(user.getId() + "_", "");
                                }

                                if (name != null && !name.trim().isEmpty()) {
                                    userQueryColumns.add(name);
                                }
                            }
                        }
                    }
                    if (data != null) {
                        for (int i = 0; i < data.length; i++) {
                            TableEntry en = new TableEntry(userQueryColumns);
                            for (int z = 0; z < data[i].length; z++) {
                                if (data[i][z] != null) {
                                    en.addValue(data[i][z], z);
                                } else {
                                    en.addValue("NULL", z);
                                }
                            }
                            userQueryValues.add(en);
                        }
                    }
                    filteredUserQueryValues = userQueryValues;
                    createUserQueryColumns();

                    if (showFeedback) {
                        this.userResultVisible = true;
                    }
                } else {
                    if (showFeedback) {
                        this.feedbackVisible = true;
                        this.userResultVisible = false;
                    }
                }

                // ------------------------------------------------ //
                // --
                // ------------------------------------------------ //

                if (userEntrySuccess) {
                    feedbackList.clear();
                    UserFeedback feedback = new UserFeedback(
                            Cfg.inst().getProp(DEF_LANGUAGE, "COMPARATOR.DYN_RESULT"),
                            Cfg.inst().getProp(DEF_LANGUAGE, "COMPARATOR.DYN_RESULT.SUC"), user);
                    feedback.setSuccess(true);
                    feedback.setMainError(true);
                    feedbackList.add(feedback);
                }

                this.lastEntryTime = System.currentTimeMillis();
            }

        } catch (SQLException e) {
            LOGGER.error("PARSER-SQL-ERROR", e);
        } catch (Exception e) {
            LOGGER.error("PARSER-ERROR", e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        long elapsedTime = System.currentTimeMillis() - starttime;

        String processTime = "Bearbeitungszeit: " + elapsedTime + " ms.";
        if (message1 == null) {
            Severity sev = FacesMessage.SEVERITY_INFO;
            String msg = processTime;
            message1 = new FacesMessage(sev, Cfg.inst().getText("EX.SERVER_MESSAGE"), msg);
        } else if (message1 != null) {
            String details = message1.getDetail();
            message1.setDetail(details + "   (" + processTime + ")");
            FacesContext.getCurrentInstance().addMessage(null, message1);
        }

    } catch (Exception e) {
        LOGGER.error("ERROR COMPARING RESULTS", e);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java

/**
 * Generates a <code>TableModel</code> that gets its contents filled from a <code>ResultSet</code>. The column names
 * of the <code>ResultSet</code> will form the column names of the table model.
 * <p/>/*  w  ww.  j  a  v a2 s .c  o  m*/
 * Hint: To customize the names of the columns, use the SQL column aliasing (done with <code>SELECT nativecolumnname
 * AS "JavaColumnName" FROM ....</code>
 *
 * @param rs                the result set.
 * @param columnNameMapping defines, whether to use column names or column labels to compute the column index. If
 *                          true, then we map the Name.  If false, then we map the Label
 * @return a closeable table model.
 * @throws SQLException if there is a problem with the result set.
 */
public CloseableTableModel generateDefaultTableModel(final ResultSet rs, final boolean columnNameMapping)
        throws SQLException {
    try {
        final ResultSetMetaData rsmd = rs.getMetaData();
        final int colcount = rsmd.getColumnCount();
        final Class[] colTypes = TypeMapper.mapTypes(rsmd);
        //final DefaultTableMetaData metaData = new DefaultTableMetaData( colcount );

        // In past many database drivers were returning same value for column label and column name. So it is
        // inconsistent
        // what the database driver will return for column name vs column label.
        // We have a legacy configuration for this. If set, then if column label is null or empty then return column
        // name.
        // Otherwise return column label.
        // If non-legacy mode, then we return exactly what the JDBC driver returns (label for label, name for name)
        // without
        // any interpretation or interpolation.
        final Configuration globalConfig = ClassicEngineBoot.getInstance().getGlobalConfig();
        final boolean useLegacyColumnMapping = "legacy".equalsIgnoreCase( // NON-NLS
                globalConfig.getConfigProperty(
                        "org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ColumnMappingMode",
                        "legacy")); // NON-NLS

        final String[] header = new String[colcount];
        final AttributeMap[] columnMeta = new AttributeMap[colcount];

        for (int columnIndex = 0; columnIndex < colcount; columnIndex++) {
            String columnLabel = rsmd.getColumnLabel(columnIndex + 1);
            if (useLegacyColumnMapping) {
                if ((columnLabel == null) || (columnLabel.isEmpty())) {
                    // We are in legacy mode and column label is either null or empty, we then use column name instead.
                    columnLabel = rsmd.getColumnName(columnIndex + 1);
                }
                header[columnIndex] = columnLabel;
            } else {
                if (columnNameMapping) {
                    header[columnIndex] = rsmd.getColumnName(columnIndex + 1);
                } else {
                    header[columnIndex] = columnLabel;
                }
            }

            columnMeta[columnIndex] = ResultSetTableModelFactory.collectData(rsmd, columnIndex,
                    header[columnIndex]);
        }

        final Object[][] rowMap = produceData(rs, colcount);
        ImmutableTableMetaData metaData = new ImmutableTableMetaData(ImmutableDataAttributes.EMPTY,
                map(columnMeta));
        return new CloseableDefaultTableModel(rowMap, header, colTypes, metaData);
    } finally {
        Statement statement = null;
        try {
            statement = rs.getStatement();
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close statement", sqle);
        }
        try {
            rs.close();
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close resultset", sqle);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close statement", sqle);
        }
    }
}

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;//from   w  w  w . j  av  a 2  s . com
    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------------------------");
    }
}