Example usage for java.sql ResultSet findColumn

List of usage examples for java.sql ResultSet findColumn

Introduction

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

Prototype

int findColumn(String columnLabel) throws SQLException;

Source Link

Document

Maps the given ResultSet column label to its ResultSet column index.

Usage

From source file:org.hyperic.hq.plugin.sybase.SybaseServerDetector.java

private void setEngineServices(List services, Statement stmt) throws SQLException {
    ResultSet rs = null;
    try {//  ww w .ja  v  a2s . c o m
        rs = stmt.executeQuery(ENGINE_QUERY);
        int engine_col = rs.findColumn("engine");
        while (rs != null && rs.next()) {
            String engineNum = rs.getString(engine_col).trim().replaceAll("\\s+", "_");
            ServiceResource service = new ServiceResource();
            service.setType(this, TYPE_SP_SYSMON + "Engine");
            service.setServiceName("engine" + engineNum);
            ConfigResponse productConfig = new ConfigResponse();
            productConfig.setValue(PROP_ENGINE, "engine" + engineNum);
            productConfig.setValue("id", engineNum);
            service.setProductConfig(productConfig);
            service.setMeasurementConfig();
            services.add(service);
        }
    } finally {
        if (rs != null)
            rs.close();
    }
}

From source file:org.hyperic.hq.plugin.sybase.SybaseServerDetector.java

private void setCacheServices(List services, Statement stmt) throws SQLException {
    ResultSet rs = null;
    try {//w w w  .  j  av a 2s .c  o m
        rs = stmt.executeQuery(CACHE_QUERY);
        int name_col = rs.findColumn("name");
        while (rs != null && rs.next()) {
            String cacheName = rs.getString(name_col).trim().replaceAll("\\s+", "_");
            ServiceResource service = new ServiceResource();
            service.setType(this, TYPE_SP_SYSMON + "Cache");
            service.setServiceName("Cachename=" + cacheName);
            ConfigResponse productConfig = new ConfigResponse();
            productConfig.setValue("cachename", cacheName);
            service.setProductConfig(productConfig);
            service.setMeasurementConfig();
            services.add(service);
        }
    } finally {
        if (rs != null)
            rs.close();
    }
}

From source file:org.kew.rmf.core.lucene.LuceneDataLoader.java

private void load(DatabaseRecordSource recordSource) throws DataLoadException {
    int i = 0;/*w  w w  .java  2s  .  co m*/
    int errors = 0;

    ResultSet resultSet;
    try {
        resultSet = recordSource.getResultSet();
    } catch (SQLException e) {
        throw new DataLoadException(configName + ": Problem reading data from database " + recordSource, e);
    }

    try {
        // check whether the necessary column names are present in the ResultSet
        for (String headerName : this.config.getPropertyAuthorityColumnNames()) {
            try {
                resultSet.findColumn(headerName);
            } catch (SQLException se) {
                throw new DataLoadException(String.format(
                        "%s: Database result doesn't contain field name %s as defined in config.",
                        this.config.getName(), headerName));
            }
        }
        // same for the id-field
        try {
            resultSet.findColumn(Configuration.ID_FIELD_NAME);
        } catch (SQLException se) {
            throw new DataLoadException(
                    String.format("%s: Database result doesn't contain field name %s as defined in config.",
                            this.config.getName(), Configuration.ID_FIELD_NAME));
        }

        Document doc = null;
        while (resultSet.next()) {
            // Index record
            try {
                doc = this.indexRecord(resultSet);
            } catch (Exception e) {
                errors++;
                String message = configName + ": Problem indexing record " + i + ", " + resultSet;
                if (errors < config.getMaximumLoadErrors()) {
                    logger.warn(message, e);
                } else {
                    throw new DataLoadException(message, e);
                }
            }

            // Log progress
            if (i++ % this.config.getLoadReportFrequency() == 0) {
                logger.info("{}: Indexed {} documents", configName, i);
                logger.debug("{}: Most recent indexed document was {}", configName, doc);
            }
        }
        recordSource.close();

        indexWriter.commit();
    } catch (Exception e) {
        throw new DataLoadException(configName + ": Error " + e.getMessage() + " loading records at row " + i,
                e);
    }
    logger.info("{}: Indexed {} records", configName, i);
}

From source file:org.nuxeo.ecm.directory.sql.SQLSession.java

private Object getFieldValue(ResultSet rs, String fieldName) throws DirectoryException {
    try {/*from w  ww  .  ja  v a2 s .  c  o  m*/
        Column column = table.getColumn(fieldName);
        if (column == null) {
            throw new DirectoryException(
                    String.format("Column '%s' does not exist in table '%s'", fieldName, table.getKey()));
        }
        int index = rs.findColumn(column.getPhysicalName());
        return column.getFromResultSet(rs, index);
    } catch (SQLException e) {
        throw new DirectoryException("getFieldValue failed", e);
    }
}

From source file:org.opencb.opencga.storage.hadoop.variant.converters.annotation.HBaseToVariantAnnotationConverter.java

public VariantAnnotation convert(ResultSet resultSet) {
    int column;//from www.j  a  va  2  s .  c om
    try {
        column = resultSet.findColumn(VariantPhoenixHelper.VariantColumn.FULL_ANNOTATION.column());
    } catch (SQLException e) {
        //Column not found
        return null;
    }
    try {
        String value = resultSet.getString(column);
        if (StringUtils.isNotEmpty(value)) {
            try {
                return objectMapper.readValue(value, VariantAnnotation.class);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    } catch (SQLException e) {
        // This should never happen!
        throw new IllegalStateException(e);
    }
    return null;

}

From source file:org.sipfoundry.sipxconfig.cdr.CdrManagerImplTest.java

public void testColumnInfo() throws Exception {
    ResultSet rs = createMock(ResultSet.class);
    for (int i = 0; i < ColumnInfo.FIELDS.length; i++) {
        rs.findColumn((String) anyObject());
        expectLastCall().andReturn(i);//from   w w w  .ja  v  a 2s.  c  o  m
    }
    replay(rs);

    ColumnInfoFactory ciFactory = new DefaultColumnInfoFactory(TimeZone.getDefault());
    ColumnInfo[] infos = ciFactory.create(rs);

    assertEquals(ColumnInfo.FIELDS.length, infos.length);
    for (int i = 0; i < infos.length; i++) {
        assertEquals(i, infos[i].getIndex());
        assertEquals(ColumnInfo.TIME_FIELDS[i], infos[i].isTimestamp());
    }
    verify(rs);
}

From source file:org.sipfoundry.sipxconfig.cdr.CdrManagerImplTest.java

public void testCdrsCsvWriter() throws Exception {
    TimeZone tz = DateUtils.UTC_TIME_ZONE;
    Calendar calendar = Calendar.getInstance(tz);

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    String dateStr = String.format("\"%s\",", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(timestamp));

    ResultSet rs = createMock(ResultSet.class);
    for (int i = 0; i < ColumnInfo.FIELDS.length; i++) {
        rs.findColumn((String) anyObject());
        expectLastCall().andReturn(i);/*  w  w  w . j a  v  a2 s.com*/
    }

    rs.getString(0);
    expectLastCall().andReturn("caller");
    rs.getString(1);
    expectLastCall().andReturn("callee");

    rs.getTimestamp(eq(2), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);
    rs.getTimestamp(eq(3), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);
    rs.getTimestamp(eq(4), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);

    rs.getString(5);
    expectLastCall().andReturn("404");

    rs.getString(6);
    expectLastCall().andReturn("I");

    rs.getString(7);
    expectLastCall().andReturn("0000-0000");

    replay(rs);

    StringWriter writer = new StringWriter();

    ColumnInfoFactory columnInforFactory = new DefaultColumnInfoFactory(tz);
    CdrsWriter handler = new CdrsCsvWriter(writer, columnInforFactory);
    handler.writeHeader();
    handler.processRow(rs);
    handler.writeFooter();

    assertEquals(
            "callee_aor,caller_aor,start_time,connect_time,end_time,failure_status,termination,call_id\n"
                    + "\"caller\",\"callee\"," + dateStr + dateStr + dateStr + "\"404\",\"I\",\"0000-0000\"\n",
            writer.toString());

    verify(rs);
}

From source file:org.sipfoundry.sipxconfig.cdr.CdrManagerImplTest.java

public void testCdrsJsonWriter() throws Exception {
    TimeZone tz = DateUtils.UTC_TIME_ZONE;
    Calendar calendar = Calendar.getInstance(tz);

    Timestamp timestamp = new Timestamp(0);

    ResultSet rs = createMock(ResultSet.class);
    for (int i = 0; i < ColumnInfo.FIELDS.length; i++) {
        rs.findColumn((String) anyObject());
        expectLastCall().andReturn(i);/*from w w  w  .  j  a va2  s  .c o  m*/
    }

    rs.getString(0);
    expectLastCall().andReturn("\"Brian Ferry\"<sip:1111@example.org>");
    rs.getString(1);
    expectLastCall().andReturn("sip:callee@example.com");

    rs.getTimestamp(eq(2), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);
    rs.getTimestamp(eq(3), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);
    rs.getTimestamp(eq(4), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);

    rs.getString(5);
    expectLastCall().andReturn("404");

    rs.getString(6);
    expectLastCall().andReturn("I");

    rs.getString(7);
    expectLastCall().andReturn("0000-0000");

    replay(rs);

    StringWriter writer = new StringWriter();

    Format testDateFormat = new Format() {
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            return toAppendTo.append("2008-05-02T06:29:08-04:00");
        }

        public Object parseObject(String source, ParsePosition pos) {
            return null;
        }
    };

    DefaultColumnInfoFactory ciFactory = new DefaultColumnInfoFactory(tz);
    ciFactory.setDateFormat(testDateFormat);
    ciFactory.setAorFormat(CdrsJsonWriter.AOR_FORMAT);
    CdrsWriter handler = new CdrsJsonWriter(writer, ciFactory);
    handler.writeHeader();
    handler.processRow(rs);
    handler.writeFooter();

    InputStream expectedJson = getClass().getResourceAsStream("cdrs.test.json");
    assertNotNull(expectedJson);

    assertEquals(IOUtils.toString(expectedJson), writer.toString());

    verify(rs);
}

From source file:org.sipfoundry.sipxconfig.cdr.CdrManagerImplTest.java

public void testCdrsCsvWriterNullConnectTime() throws Exception {
    TimeZone tz = DateUtils.UTC_TIME_ZONE;
    Calendar calendar = Calendar.getInstance(tz);

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    String dateStr = String.format("\"%s\",", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(timestamp));

    ResultSet rs = createMock(ResultSet.class);
    for (int i = 0; i < ColumnInfo.FIELDS.length; i++) {
        rs.findColumn((String) anyObject());
        expectLastCall().andReturn(i);/*from   ww w.  j  a  v a 2s .c o m*/
    }

    rs.getString(0);
    expectLastCall().andReturn("caller");
    rs.getString(1);
    expectLastCall().andReturn("callee");

    rs.getTimestamp(eq(2), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);
    rs.getTimestamp(eq(3), eqTimeZone(calendar));
    expectLastCall().andReturn(null);
    rs.getTimestamp(eq(4), eqTimeZone(calendar));
    expectLastCall().andReturn(timestamp);

    rs.getString(5);
    expectLastCall().andReturn("404");

    rs.getString(6);
    expectLastCall().andReturn("I");

    rs.getString(7);
    expectLastCall().andReturn("0000-0000");

    replay(rs);

    StringWriter writer = new StringWriter();

    ColumnInfoFactory columnInforFactory = new DefaultColumnInfoFactory(tz);
    RowCallbackHandler handler = new CdrsCsvWriter(writer, columnInforFactory);
    handler.processRow(rs);

    assertEquals("\"caller\",\"callee\"," + dateStr + "\"\"," + dateStr + "\"404\",\"I\",\"0000-0000\"\n",
            writer.toString());

    verify(rs);
}

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;/*from w w w.j  a v a  2  s  .  co  m*/
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}