Example usage for java.sql ResultSetMetaData getColumnClassName

List of usage examples for java.sql ResultSetMetaData getColumnClassName

Introduction

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

Prototype

String getColumnClassName(int column) throws SQLException;

Source Link

Document

Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column.

Usage

From source file:com.glaf.core.jdbc.QueryHelper.java

public List<Map<String, Object>> getResults(ResultSet rs) {
    logger.debug("--------------use mybatis results----------------");
    try {//  w  w w .ja v a  2 s  .c o  m
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<String> columns = new ArrayList<String>();
        List<TypeHandler<?>> typeHandlers = new ArrayList<TypeHandler<?>>();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 0, n = rsmd.getColumnCount(); i < n; i++) {
            columns.add(rsmd.getColumnLabel(i + 1));
            try {
                Class<?> type = Resources.classForName(rsmd.getColumnClassName(i + 1));
                TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(type);
                if (typeHandler == null) {
                    typeHandler = typeHandlerRegistry.getTypeHandler(Object.class);
                }
                typeHandlers.add(typeHandler);
            } catch (Exception ex) {
                ex.printStackTrace();
                typeHandlers.add(typeHandlerRegistry.getTypeHandler(Object.class));
            }
        }
        while (rs.next()) {
            Map<String, Object> row = new HashMap<String, Object>();
            for (int i = 0, n = columns.size(); i < n; i++) {
                String name = columns.get(i);
                TypeHandler<?> handler = typeHandlers.get(i);
                Object value = handler.getResult(rs, name);
                row.put(name, value);
                if (value != null && value instanceof java.util.Date) {
                    java.util.Date date = (java.util.Date) value;
                    row.put(name + "_date", DateUtils.getDate(date));
                    row.put(name + "_datetime", DateUtils.getDateTime(date));
                }
            }
            list.add(row);
        }
        return list;
    } catch (SQLException ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
        } catch (SQLException e) {
        }
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not
 * having any ties to the active ResultSet: in particular, it should not be
 * a Blob or Clob object but rather a byte array respectively String
 * representation.//from  w ww.  j ava 2 s  . c om
 * <p>
 * Uses the <code>getObject(index)</code> method, but includes additional
 * "hacks" to get around Oracle 10g returning a non-standard object for its
 * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
 * leaving out the time portion: These columns will explicitly be extracted
 * as standard <code>java.sql.Timestamp</code> object.
 *
 * @param rs
 *            is the ResultSet holding the data
 * @param index
 *            is the column index
 * @param readStringsAsBytes TODO
 * @return the value object
 * @throws SQLException
 *             if thrown by the JDBC API
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 */
public static Object getResultSetValue(ResultSet rs, int index, boolean readStringsAsBytes)
        throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();
    Object obj = null;
    int jdbcType = metaData.getColumnType(index);
    if (readStringsAsBytes && TypeMap.isTextType(jdbcType)) {
        byte[] bytes = rs.getBytes(index);
        if (bytes != null) {
            obj = new String(bytes);
        }
    } else {
        obj = rs.getObject(index);
    }
    String className = null;
    if (obj != null) {
        className = obj.getClass().getName();
    }
    if (obj instanceof Blob) {
        Blob blob = (Blob) obj;
        InputStream is = blob.getBinaryStream();
        try {
            obj = IOUtils.toByteArray(is);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    } else if (obj instanceof Clob) {
        Clob clob = (Clob) obj;
        Reader reader = clob.getCharacterStream();
        try {
            obj = IOUtils.toString(reader);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className))) {
        obj = rs.getTimestamp(index);
    } else if (className != null && "oracle.sql.TIMESTAMPTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && "oracle.sql.TIMESTAMPLTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && className.startsWith("oracle.sql.DATE")) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj instanceof java.sql.Date) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        }
    } else if (obj instanceof Timestamp) {
        String typeName = metaData.getColumnTypeName(index);
        if (typeName != null && typeName.equals("timestamptz")) {
            obj = rs.getString(index);
        }
    }
    return obj;
}

From source file:com.funambol.json.coredb.dao.DBManager.java

public List<Map<String, String>> executeQuery(String query, DataFilter... filters) throws Exception {
    log.info("Executing query [" + query + "].");
    if (ds == null)
        throw new Exception("Data source is null.");

    Connection connection = null;
    Statement stmt = null;//w  ww .ja  v a2s.c om
    ResultSet rsltSet = null;
    ResultSetMetaData metadata = null;

    try {
        connection = ds.getConnection();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred retrieving connection.", ex);
    }

    if (connection == null) {
        throw new Exception("Connection is null.");
    }

    try {
        stmt = connection.createStatement();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred creating statement.", ex);
    }

    try {
        rsltSet = stmt.executeQuery(query);
        metadata = rsltSet.getMetaData();
    } catch (SQLException ex) {
        release(connection, stmt, rsltSet);
        throw new Exception("An error occurred executing query [" + query + "].", ex);
    }

    try {
        if (rsltSet != null) {

            Map<String, DataFilter> columnNamesFilters = new HashMap<String, DataFilter>();
            Map<String, DataFilter> columnClassFilters = new HashMap<String, DataFilter>();
            populateFilterMap(columnNamesFilters, columnClassFilters, filters);

            List<Map<String, String>> result = new ArrayList<Map<String, String>>();
            int numberOfColumns = metadata.getColumnCount();
            while (rsltSet.next()) {
                Map<String, String> newItem = new HashMap<String, String>();
                for (int i = 1; i <= numberOfColumns; i++) {
                    String columnName = metadata.getColumnName(i);
                    String columnValue = null;
                    String columnClass = metadata.getColumnClassName(i);
                    // Retrieving filter bound to column class or column name
                    DataFilter filter = null;
                    if (!columnNamesFilters.isEmpty() && columnNamesFilters.containsKey(columnName)) {
                        filter = columnNamesFilters.get(columnName);
                    } else if (!columnClassFilters.isEmpty() && columnClassFilters.containsKey(columnClass)) {
                        filter = columnClassFilters.get(columnClass);
                    }

                    if (filter != null) {
                        Object obj = rsltSet.getObject(i);
                        columnValue = filter.applyFilter(obj);
                    } else
                        columnValue = rsltSet.getString(i);

                    newItem.put(columnName, columnValue);
                }
                result.add(newItem);
            }
            return result;

        } else
            throw new Exception("ResultSet is null.");
    } catch (SQLException ex) {
        throw new Exception("An error occurred creating result list for query [" + query + "].", ex);
    } finally {
        release(connection, stmt, rsltSet);
    }

}

From source file:com.openddal.test.BaseTestCase.java

/**
 * Check if the result set meta data is correct.
 *
 * @param rs the result set//from  w ww  .ja  v a  2s.co  m
 * @param columnCount the expected column count
 * @param labels the expected column labels
 * @param datatypes the expected data types
 * @param precision the expected precisions
 * @param scale the expected scales
 */
protected void assertResultSetMeta(ResultSet rs, int columnCount, String[] labels, int[] datatypes,
        int[] precision, int[] scale) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int cc = meta.getColumnCount();
    if (cc != columnCount) {
        fail("result set contains " + cc + " columns not " + columnCount);
    }
    for (int i = 0; i < columnCount; i++) {
        if (labels != null) {
            String l = meta.getColumnLabel(i + 1);
            if (!labels[i].equals(l)) {
                fail("column label " + i + " is " + l + " not " + labels[i]);
            }
        }
        if (datatypes != null) {
            int t = meta.getColumnType(i + 1);
            if (datatypes[i] != t) {
                fail("column datatype " + i + " is " + t + " not " + datatypes[i] + " (prec="
                        + meta.getPrecision(i + 1) + " scale=" + meta.getScale(i + 1) + ")");
            }
            String typeName = meta.getColumnTypeName(i + 1);
            String className = meta.getColumnClassName(i + 1);
            switch (t) {
            case Types.INTEGER:
                Assert.assertEquals("INTEGER", typeName);
                Assert.assertEquals("java.lang.Integer", className);
                break;
            case Types.VARCHAR:
                Assert.assertEquals("VARCHAR", typeName);
                Assert.assertEquals("java.lang.String", className);
                break;
            case Types.SMALLINT:
                Assert.assertEquals("SMALLINT", typeName);
                Assert.assertEquals("java.lang.Short", className);
                break;
            case Types.TIMESTAMP:
                Assert.assertEquals("TIMESTAMP", typeName);
                Assert.assertEquals("java.sql.Timestamp", className);
                break;
            case Types.DECIMAL:
                Assert.assertEquals("DECIMAL", typeName);
                Assert.assertEquals("java.math.BigDecimal", className);
                break;
            default:
            }
        }
        if (precision != null) {
            int p = meta.getPrecision(i + 1);
            if (precision[i] != p) {
                fail("column precision " + i + " is " + p + " not " + precision[i]);
            }
        }
        if (scale != null) {
            int s = meta.getScale(i + 1);
            if (scale[i] != s) {
                fail("column scale " + i + " is " + s + " not " + scale[i]);
            }
        }

    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java

/**
 * Populates the {@link #_groupingRanges}-{@link ArrayList} according to the configuration specified in the
 * {@link Grouping}-attribute of the {@link DataSourceConnectionConfig}. The SQL-statements needed for this are
 * executed via a local {@link Statement}-object, just as the data is retrieved via a local {@link ResultSet}-object.
 * //w w  w .j av a2s. c  o m
 * @throws CrawlerCriticalException
 *           If any of the following conditions occur:
 *           <ul>
 *           <li>Any of the columns used for grouping has a data type which is not supported: !(Number||String)</li>
 *           <li>A SQLException is raised while retrieving the grouping data from the database</li>
 *           </ul>
 */
private void prepareGrouping() throws CrawlerCriticalException {
    final Grouping grouping = _process.getSelections().getGrouping();
    BigInteger stepping = BigInteger.ONE;
    ResultSet groupingResultSet = null;
    ResultSetMetaData groupingMetaData = null;
    if (grouping != null) {
        _groupingRanges = new ArrayList<GroupingRange>();
        final String groupingSQL = grouping.getSQL();
        stepping = grouping.getStepping();
        Statement groupingStatement = null;
        try {
            groupingStatement = _connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            _log.debug("Executing SQL for grouping preparation: [" + groupingSQL + "]");
            groupingResultSet = groupingStatement.executeQuery(groupingSQL);
            groupingMetaData = groupingResultSet.getMetaData();
            _log.debug("Retrieved groupingResultSet with [" + groupingMetaData.getColumnCount() + "] columns");
            for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                Class<?> columnClass = null;
                try {
                    columnClass = Class.forName(groupingMetaData.getColumnClassName(i));

                } catch (final ClassNotFoundException e) {
                    _log.error("This should never happen: the class[" + groupingMetaData.getColumnClassName(i)
                            + "] for the column " + i + " in the grouping result set could not be resolved");
                }
                if (Number.class.isAssignableFrom(columnClass)) {
                    _log.debug("RowNr " + i + " of the grouping result set is of type [" + columnClass.getName()
                            + "], which is derived from [Number]: fine for use in a grouping");
                    continue;
                } else if (String.class.equals(columnClass)) {
                    _log.debug("RowNr " + i
                            + " of the grouping result set is of type [String]: fine for use in a grouping");
                } else {
                    throw new CrawlerCriticalException("RowNr " + i + " of the grouping result set is of type ["
                            + columnClass.getName() + "]: NOT supported as a grouping field");
                }
            }
            int groupingRecords = 0;
            PreparedStatementTypedParameter[] startValues = null;
            PreparedStatementTypedParameter[] endValues = null;
            final PreparedStatementTypedParameter[] finalValues = new PreparedStatementTypedParameter[groupingMetaData
                    .getColumnCount()];

            while (groupingResultSet.next()) {

                if (groupingRecords == 0) {

                    startValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()];
                    for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {

                        startValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                                (i * 2) - 1, groupingMetaData.getColumnType(i));
                    }

                }
                groupingRecords++;

                if (groupingRecords == stepping.intValue()) {
                    endValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()];
                    for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                        endValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                                i * 2, groupingMetaData.getColumnType(i));
                    }
                    final GroupingRange groupingRange = new GroupingRange(startValues, endValues);
                    _groupingRanges.add(groupingRange);
                    if (_log.isTraceEnabled()) {
                        _log.trace(
                                "Added GroupingRange: [" + groupingRange.toString() + "] to _groupingRanges");
                    }
                    groupingRecords = 0;
                    continue;
                }

                for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                    finalValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                            i * 2, groupingMetaData.getColumnType(i));

                }

            }
            if (groupingRecords != 0 && stepping.intValue() != 1) {
                final GroupingRange finalgroupingRange = new GroupingRange(startValues, finalValues);
                _groupingRanges.add(finalgroupingRange);
                _log.debug(
                        "Added final GroupingRange [" + finalgroupingRange.toString() + "] to _groupingRanges");
            }
        } catch (final SQLException e1) {
            throw new CrawlerCriticalException("Encountered SQLException while preparing Groupings");
        } finally {
            try {
                if (groupingStatement != null) {
                    groupingStatement.close();
                }
            } catch (final SQLException e) {
                _log.error("Could not closeGrouping statement");
            }
            try {
                groupingResultSet.close();
                _log.debug("Closed Grouping Resultset");
            } catch (final SQLException e) {
                _log.error("Could not close Resultset for Grouping statement");
            }
        }

    }
    // set current grouping to first grouping in list (if list is not empty)
    _groupingRangesIterator = _groupingRanges.iterator();
    if (_groupingRangesIterator.hasNext()) {
        _currentGroupingRange = _groupingRangesIterator.next();
    }

    _log.debug(String.format("Prepared %d grouping ranges based on specified stepping of %d",
            _groupingRanges.size(), stepping.intValue()));
}

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

@SuppressWarnings("unchecked")
public TableDefinition toTableDefinition(QueryDefinition query, String currentSql) {

    if (query.getId() != null && query.getParentId() != null) {
        query = this.fill(query.getId(), currentSql);
    }//w ww  .  j a v a 2 s.  c om

    if (query.getParentId() != null) {
        QueryDefinition parent = this.fill(query.getParentId(), null);
        if (parent != null) {
            logger.debug("parent:" + parent.getTitle());
            logger.debug("resultList:" + parent.getResultList());
            query.setParent(parent);
        }
    }

    String sql = currentSql;
    List<Object> values = null;
    logger.debug("currentSql:" + currentSql);
    if (query.getParentId() != null) {
        if (query.getParent() != null && query.getParent().getResultList() != null
                && !query.getParent().getResultList().isEmpty()) {
            for (Map<String, Object> paramMap : query.getParent().getResultList()) {
                SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap);
                sql = sqlExecutor.getSql();
                sql = QueryUtils.replaceSQLVars(sql);
                values = (List<Object>) sqlExecutor.getParameter();
                break;
            }
        }
    } else {
        if (sql != null && sql.indexOf("${") != -1) {
            sql = QueryUtils.replaceSQLVars(sql);
            SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, new java.util.HashMap<String, Object>());
            if (sqlExecutor != null) {
                sql = sqlExecutor.getSql();
                sql = QueryUtils.replaceSQLVars(sql);
                values = (List<Object>) sqlExecutor.getParameter();
            }
        }
    }

    logger.debug("sql:" + sql);
    logger.debug("values:" + values);

    TableDefinition table = new TableDefinition();
    Connection conn = null;
    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();
        }

        sql = QueryUtils.replaceSQLVars(sql);
        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnName(rsmd.getColumnName(i));
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            table.addColumn(column);

            logger.debug("----------------------------------------");
            logger.debug("sqlType:" + sqlType);
            logger.debug("javaType:" + FieldType.getJavaType(sqlType));
            logger.debug("columnName:" + rsmd.getColumnName(i));
            logger.debug("columnTypeName:" + rsmd.getColumnTypeName(i));
            logger.debug("columnClassName:" + rsmd.getColumnClassName(i));
            logger.debug("columnLabel:" + rsmd.getColumnLabel(i));
            logger.debug("columnDisplaySize:" + rsmd.getColumnDisplaySize(i));
            logger.debug("precision:" + rsmd.getPrecision(i));
            logger.debug("scale:" + rsmd.getScale(i));
        }

    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
    }
    return table;
}

From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java

@Override
//@SuppressWarnings("null")
public synchronized void exectionDone(final SQLExecutionProcessor process, final ResultSet resultSet) {
    if (statusBar != null) {
        statusBar.incrementValue(getClass().getSimpleName());
    }/*from  w ww. j a  v a 2s.c  o  m*/

    if (resultSet == null || results == null) {
        log.error("The " + (resultSet == null ? "resultSet" : "results") + " is null.");
        if (propertyListener != null) {
            propertyListener.propertyChange(new PropertyChangeEvent(this, "rowCount", null, 0));
        }
        return;
    }

    List<ERTICaptionInfo> captions = results.getVisibleCaptionInfo();

    // This can do one of two things:
    // 1) Take multiple columns and create an object and use a DataObjectFormatter to format the object.
    // 2) Table multiple objects that were derived from the columns and roll those up into a single column's value.
    //    This happens when you get back rows of info where part of the columns are duplicated because you really
    //    want those value to be put into a single column.
    //
    // Step One - Is to figure out what type of object needs to be created and what the Columns are 
    //            that need to be set into the object so the dataObjFormatter can do its job.
    //
    // Step Two - If the objects are being aggregated then the object created from the columns are added to a List
    //            and then last formatted as an "aggregation"

    try {
        if (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();

            // Composite
            boolean hasCompositeObj = false;
            DataObjSwitchFormatter dataObjFormatter = null;
            UIFieldFormatterIFace formatter = null;
            Object compObj = null;

            // Aggregates
            ERTICaptionInfo aggCaption = null;
            ERTICaptionInfo compositeCaption = null;
            Vector<Object> aggList = null;
            DataObjectSettable aggSetter = null;
            Stack<Object> aggListRecycler = null;

            DataObjectSettable dataSetter = null; // data getter for Aggregate or the Subclass

            // Loop through the caption to figure out what columns will be displayed.
            // Watch for Captions with an Aggregator or Composite 
            numColumns = captions.size();
            for (ERTICaptionInfo caption : captions) {
                colNames.addElement(caption.getColLabel());

                int inx = caption.getPosIndex() + 1;
                //log.debug(metaData.getColumnClassName(inx));
                Class<?> cls = null;
                try {
                    cls = Class.forName(metaData.getColumnClassName(inx));
                    if (cls == Calendar.class || cls == java.sql.Date.class || cls == Date.class) {
                        cls = String.class;
                    }
                } catch (SQLException ex) {
                    cls = String.class;
                }
                classNames.addElement(cls);
                caption.setColClass(cls);

                if (caption.getAggregatorName() != null) {
                    //log.debug("The Agg is ["+caption.getAggregatorName()+"] "+caption.getColName());

                    // Alright we have an aggregator
                    aggList = new Vector<Object>();
                    aggListRecycler = new Stack<Object>();
                    aggCaption = caption;
                    aggSetter = DataObjectSettableFactory.get(aggCaption.getAggClass().getName(),
                            FormHelper.DATA_OBJ_SETTER);

                    // Now check to see if we are aggregating the this type of object or a child object of this object
                    // For example Collectors use an Agent as part of the aggregation
                    if (aggCaption.getSubClass() != null) {
                        dataSetter = DataObjectSettableFactory.get(aggCaption.getSubClass().getName(),
                                FormHelper.DATA_OBJ_SETTER);
                    } else {
                        dataSetter = aggSetter;
                    }

                } else if (caption.getColInfoList() != null) {
                    formatter = caption.getUiFieldFormatter();
                    if (formatter != null) {
                        compositeCaption = caption;
                    } else {
                        // OK, now aggregation but we will be rolling up multiple columns into a single object for formatting
                        // We need to get the formatter to see what the Class is of the object
                        hasCompositeObj = true;
                        aggCaption = caption;
                        dataObjFormatter = caption.getDataObjFormatter();
                        if (dataObjFormatter != null) {
                            if (dataObjFormatter.getDataClass() != null) {
                                aggSetter = DataObjectSettableFactory.get(
                                        dataObjFormatter.getDataClass().getName(),
                                        "edu.ku.brc.af.ui.forms.DataSetterForObj");
                            } else {
                                log.error("formatterObj.getDataClass() was null for " + caption.getColName());
                            }
                        } else {
                            log.error("DataObjFormatter was null for " + caption.getColName());
                        }
                    }

                }
                //colNames.addElement(metaData.getColumnName(i));
                //System.out.println("**************** " + caption.getColLabel()+ " "+inx+ " " + caption.getColClass().getSimpleName());
            }

            // aggCaption will be non-null for both a Aggregate AND a Composite
            if (aggCaption != null) {
                // Here we need to dynamically discover what the column indexes are that we to grab
                // in order to set them into the created data object
                for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                    for (int i = 0; i < metaData.getColumnCount(); i++) {
                        String colName = StringUtils.substringAfterLast(colInfo.getColumnName(), ".");
                        if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                            colInfo.setPosition(i);
                            break;
                        }
                    }
                }

                // Now check to see if there is an Order Column because the Aggregator 
                // might need it for sorting the Aggregation
                String ordColName = aggCaption.getOrderCol();
                if (StringUtils.isNotEmpty(ordColName)) {
                    String colName = StringUtils.substringAfterLast(ordColName, ".");
                    //log.debug("colName ["+colName+"]");
                    for (int i = 0; i < metaData.getColumnCount(); i++) {
                        //log.debug("["+colName+"]["+metaData.getColumnName(i+1)+"]");
                        if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                            aggCaption.setOrderColIndex(i);
                            break;
                        }
                    }
                    if (aggCaption.getOrderColIndex() == -1) {
                        log.error("Agg Order Column Index wasn't found [" + ordColName + "]");
                    }
                }
            }

            if (ids == null) {
                ids = new Vector<Integer>();
            } else {
                ids.clear();
            }

            // Here is the tricky part.
            // When we are doing a Composite we are just taking multiple columns and 
            // essentially replace them with a single value from the DataObjFormatter
            //
            // But when doing an Aggregation we taking several rows and rolling them up into a single value.
            // so this code knows when it is doing an aggregation, so it knows to only add a new row to the display-able
            // results when primary id changes.

            DataObjFieldFormatMgr dataObjMgr = DataObjFieldFormatMgr.getInstance();
            Vector<Object> row = null;
            boolean firstTime = true;
            int prevId = Integer.MAX_VALUE; // really can't assume any value but will choose Max

            int numCols = resultSet.getMetaData().getColumnCount();
            do {
                int id = resultSet.getInt(1);
                //log.debug("id: "+id+"  prevId: "+prevId);

                // Remember aggCaption is used by both a Aggregation and a Composite
                if (aggCaption != null && !hasCompositeObj) {
                    if (firstTime) {
                        prevId = id;
                        row = new Vector<Object>();
                        firstTime = false;
                        cache.add(row);
                        ids.add(id);

                    } else if (id != prevId) {
                        //log.debug("Agg List len: "+aggList.size());

                        if (row != null && aggList != null) {
                            int aggInx = captions.indexOf(aggCaption);
                            row.remove(aggInx);
                            row.insertElementAt(dataObjMgr.aggregate(aggList, aggCaption.getAggClass()),
                                    aggInx);

                            if (aggListRecycler != null) {
                                aggListRecycler.addAll(aggList);
                            }
                            aggList.clear();

                            row = new Vector<Object>();
                            cache.add(row);
                            ids.add(id);
                        }
                        prevId = id;

                    } else if (row == null) {
                        row = new Vector<Object>();
                        cache.add(row);
                        ids.add(id);
                    }
                } else {
                    row = new Vector<Object>();
                    cache.add(row);
                    ids.add(id);
                }

                // Now for each Caption column get a value
                for (ERTICaptionInfo caption : captions) {
                    int posIndex = caption.getPosIndex();
                    if (caption == aggCaption) // Checks to see if we need to take multiple columns and make one column
                    {
                        if (hasCompositeObj) // just doing a Composite
                        {
                            if (aggSetter != null && row != null && dataObjFormatter != null) {
                                if (compObj == null) {
                                    compObj = aggCaption.getAggClass().newInstance();
                                }

                                for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                                    setField(aggSetter, compObj, colInfo.getFieldName(),
                                            colInfo.getFieldClass(), resultSet, colInfo.getPosition());
                                }
                                row.add(DataObjFieldFormatMgr.getInstance().format(compObj,
                                        compObj.getClass()));

                            } else if (formatter != null) {
                                int len = compositeCaption.getColInfoList().size();
                                Object[] val = new Object[len];
                                int i = 0;
                                for (ERTICaptionInfo.ColInfo colInfo : compositeCaption.getColInfoList()) {
                                    int colInx = colInfo.getPosition() + posIndex + 1;
                                    if (colInx < numCols) {
                                        val[i++] = resultSet.getObject(colInx);
                                    } else {
                                        //val[i++] = resultSet.getObject(posIndex+1);
                                        val[i++] = "(Missing Data)";
                                    }
                                }
                                row.add(formatter.formatToUI(val));

                            } else {
                                log.error("Aggregator is null! [" + aggCaption.getAggregatorName()
                                        + "] or row or aggList");
                            }
                        } else if (aggSetter != null && row != null && aggList != null) // Doing an Aggregation
                        {
                            Object aggObj;
                            if (aggListRecycler.size() == 0) {
                                aggObj = aggCaption.getAggClass().newInstance();
                            } else {
                                aggObj = aggListRecycler.pop();
                            }
                            Object aggSubObj = aggCaption.getSubClass() != null
                                    ? aggCaption.getSubClass().newInstance()
                                    : null;
                            aggList.add(aggObj);

                            //@SuppressWarnings("unused")
                            //DataObjAggregator aggregator = DataObjFieldFormatMgr.getInstance().getAggregator(aggCaption.getAggregatorName());
                            //log.debug(" aggCaption.getOrderColIndex() "+ aggCaption.getOrderColIndex());

                            //aggSetter.setFieldValue(aggObj, aggregator.getOrderFieldName(), resultSet.getObject(aggCaption.getOrderColIndex() + 1));

                            Object dataObj;
                            if (aggSubObj != null) {
                                aggSetter.setFieldValue(aggObj, aggCaption.getSubClassFieldName(), aggSubObj);
                                dataObj = aggSubObj;
                            } else {
                                dataObj = aggObj;
                            }

                            for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                                setField(dataSetter, dataObj, colInfo.getFieldName(), colInfo.getFieldClass(),
                                        resultSet, colInfo.getPosition());
                            }
                            row.add("PlaceHolder");

                        } else if (aggSetter == null || aggList == null) {
                            log.error("Aggregator is null! [" + aggCaption.getAggregatorName() + "] or aggList["
                                    + aggList + "]");
                        }

                    } else if (row != null) {
                        if (caption.getColName() == null && caption.getColInfoList().size() > 0) {
                            int len = caption.getColInfoList().size();
                            Object[] val = new Object[len];
                            for (int i = 0; i < caption.getColInfoList().size(); i++) {
                                int inx = posIndex + 1 + i;
                                val[i] = caption.processValue(resultSet.getObject(inx));
                            }
                            row.add(caption.getUiFieldFormatter().formatToUI(val));
                            //col += caption.getColInfoList().size() - 1;

                        } else {
                            Object obj = caption.processValue(resultSet.getObject(posIndex + 1));
                            row.add(obj);
                        }
                    }
                }

            } while (resultSet.next());

            // We were always setting the rolled up data when the ID changed
            // but on the last row we need to do it here manually (so to speak)
            if (aggCaption != null && aggList != null && aggList.size() > 0 && row != null) {
                int aggInx = captions.indexOf(aggCaption);
                row.remove(aggInx);
                String colStr;
                if (StringUtils.isNotEmpty(aggCaption.getAggregatorName())) {
                    colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList,
                            aggCaption.getAggregatorName());

                } else {
                    colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList, aggCaption.getAggClass());
                }
                row.insertElementAt(colStr, aggInx);
                aggList.clear();
                aggListRecycler.clear();
            }

            fireTableStructureChanged();
            fireTableDataChanged();
        }

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

    if (propertyListener != null) {
        propertyListener
                .propertyChange(new PropertyChangeEvent(this, "rowCount", null, new Integer(cache.size())));
    }
}

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 w w .j  a  v a  2s  .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.apache.hive.jdbc.TestJdbcDriver2.java

@Test
public void testIntervalTypes() throws Exception {
    Statement stmt = con.createStatement();

    // Since interval types not currently supported as table columns, need to create them
    // as expressions.
    ResultSet res = stmt//  w  w  w  . ja  va  2 s  .  c om
            .executeQuery("select case when c17 is null then null else interval '1' year end as col1,"
                    + " c17 -  c17 as col2 from " + dataTypeTableName + " order by col1");
    ResultSetMetaData meta = res.getMetaData();

    assertEquals("col1", meta.getColumnLabel(1));
    assertEquals(java.sql.Types.OTHER, meta.getColumnType(1));
    assertEquals("interval_year_month", meta.getColumnTypeName(1));
    assertEquals(11, meta.getColumnDisplaySize(1));
    assertEquals(11, meta.getPrecision(1));
    assertEquals(0, meta.getScale(1));
    assertEquals(HiveIntervalYearMonth.class.getName(), meta.getColumnClassName(1));

    assertEquals("col2", meta.getColumnLabel(2));
    assertEquals(java.sql.Types.OTHER, meta.getColumnType(2));
    assertEquals("interval_day_time", meta.getColumnTypeName(2));
    assertEquals(29, meta.getColumnDisplaySize(2));
    assertEquals(29, meta.getPrecision(2));
    assertEquals(0, meta.getScale(2));
    assertEquals(HiveIntervalDayTime.class.getName(), meta.getColumnClassName(2));

    // row 1 - results should be null
    assertTrue(res.next());
    // skip the last (partitioning) column since it is always non-null
    for (int i = 1; i < meta.getColumnCount(); i++) {
        assertNull("Column " + i + " should be null", res.getObject(i));
    }

    // row 2 - results should be null
    assertTrue(res.next());
    for (int i = 1; i < meta.getColumnCount(); i++) {
        assertNull("Column " + i + " should be null", res.getObject(i));
    }

    // row 3
    assertTrue(res.next());
    assertEquals("1-0", res.getString(1));
    assertEquals(1, ((HiveIntervalYearMonth) res.getObject(1)).getYears());
    assertEquals("0 00:00:00.000000000", res.getString(2));
    assertEquals(0, ((HiveIntervalDayTime) res.getObject(2)).getDays());
}

From source file:org.sakaiproject.util.foorm.Foorm.java

/**
 * /*  w  w w.ja  v  a 2 s  .  c  om*/
 * @param table
 * @param formDefinition
 * @param vendor
 * @param md
 * @return
 */
public String[] formAdjustTable(String table, String[] formDefinition, String vendor, ResultSetMetaData md) {
    ArrayList<String> rv = new ArrayList<String>();

    for (String formField : formDefinition) {
        Properties info = parseFormString(formField);
        String field = info.getProperty("field", null);
        String type = info.getProperty("type", null);
        if ("header".equals(type))
            continue;
        String maxs = adjustMax(info.getProperty("maxlength", null));
        int maxlength = 0;
        if (maxs != null)
            maxlength = (new Integer(maxs)).intValue();
        if (maxlength < 1)
            maxlength = 80;

        String sqlType = null;
        boolean autoIncrement = false;
        int sqlLength = -1;
        boolean isNullable = false;
        try {
            for (int i = 1; i <= md.getColumnCount(); i++) {
                if (field.equalsIgnoreCase(md.getColumnLabel(i))) {
                    sqlLength = md.getColumnDisplaySize(i);
                    autoIncrement = md.isAutoIncrement(i);
                    sqlType = getSuperType(md.getColumnClassName(i));
                    isNullable = (md.isNullable(i) == ResultSetMetaData.columnNullable);
                    break;
                }
            }
        } catch (Exception e) {
            // ignore
        }

        logger.fine(field + " (" + maxlength + ") type=" + type);
        logger.fine(field + " (" + sqlLength + ") auto=" + autoIncrement + " type=" + sqlType + " null="
                + isNullable);

        //  If the field is not there...
        if (sqlType == null) {
            if ("oracle".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " ADD ( " + formSql(formField, vendor) + " )");
            } else if ("mysql".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " ADD " + formSql(formField, vendor));
            } else {
                rv.add("ALTER TABLE " + table + " ADD COLUMN " + formSql(formField, vendor));
            }
            continue;
        }

        String ff = formSql(formField, vendor);

        // BLTI-220, BLTI-238 - Required will be enforced in software - not the DB
        boolean shouldAlter = false;
        if ("key".equals(type)) {
            if (!NUMBER_TYPE.equals(sqlType))
                logger.severe(field + " must be Integer and Auto Increment");
        } else if ("autodate".equals(type)) {
        } else if ("url".equals(type) || "text".equals(type) || "textarea".equals(type)) {
            if ("oracle.sql.CLOB".equals(sqlType) || "oracle.jdbc.OracleClob".equals(sqlType))
                continue; // CLOBS large enough :)
            if (!STRING_TYPE.equals(sqlType)) {
                logger.severe(field + " must be String field");
                continue;
            }
            if (sqlLength < maxlength)
                shouldAlter = true;
            if (!isNullable)
                shouldAlter = true; // BLTI-220, BLTI-238
        } else if ("radio".equals(type) || "checkbox".equals(type) || "integer".equals(type)) {
            if (NUMBER_TYPE.equals(sqlType))
                continue;
            logger.severe(field + " must be Integer field");
        }

        if (shouldAlter) {
            if ("oracle".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " MODIFY ( " + ff + " )");
            } else if ("mysql".equals(vendor)) {
                rv.add("ALTER TABLE " + table + " MODIFY " + ff);
            } else {
                rv.add("ALTER TABLE " + table + " ALTER COLUMN " + ff);
            }
        }
    }

    return rv.toArray(new String[rv.size()]);
}