Example usage for java.sql ResultSet getBlob

List of usage examples for java.sql ResultSet getBlob

Introduction

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

Prototype

Blob getBlob(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a Blob object in the Java programming language.

Usage

From source file:org.wso2.intcloud.core.dao.ApplicationDAO.java

/**
 * Method for getting application from database using application hash id.
 *
 * @param dbConnection database connection
 * @param applicationHashId application hash id
 * @return/*from w w  w . j  a  v  a 2 s.co  m*/
 * @throws IntCloudException
 */
public Application getApplicationByHashId(Connection dbConnection, String applicationHashId)
        throws IntCloudException {

    PreparedStatement preparedStatement = null;
    Application application = new Application();
    ResultSet resultSet = null;

    try {

        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.GET_APPLICATION_BY_HASH_ID);

        preparedStatement.setString(1, applicationHashId);

        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {

            application.setApplicationName(resultSet.getString(SQLQueryConstants.NAME));
            application.setHashId(applicationHashId);
            application.setDescription(resultSet.getString(SQLQueryConstants.DESCRIPTION));
            application.setDefaultVersion(resultSet.getString(SQLQueryConstants.DEFAULT_VERSION));
            application.setApplicationType(resultSet.getString(SQLQueryConstants.APPLICATION_TYPE_NAME));
            application.setIcon(resultSet.getBlob(SQLQueryConstants.ICON));
            application
                    .setCarbonApplicationName(resultSet.getString(SQLQueryConstants.CARBON_APPLICATION_NAME));
            application.setParamConfiguration(resultSet.getString(SQLQueryConstants.PARAM_CONFIGURATION));
            application.setTaskConfiguration(resultSet.getString(SQLQueryConstants.TASK_CONFIGURATION));
            application.setVersions(getAllVersionsOfApplication(dbConnection, applicationHashId));

        }

    } catch (SQLException e) {
        String msg = "Error while retrieving application detail for application with hash id : "
                + applicationHashId;
        log.error(msg, e);
        throw new IntCloudException(msg, e);
    } finally {
        DBUtil.closeResultSet(resultSet);
        DBUtil.closePreparedStatement(preparedStatement);
    }
    return application;
}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void recoverMessages(MessageStoreRecoveryHandler recoveryHandler) throws SQLException {
    Connection conn = newAutoCommitConnection();
    try {/*from  w  w  w .j av a2  s.  c o  m*/
        MessageStoreRecoveryHandler.StoredMessageRecoveryHandler messageHandler = recoveryHandler.begin();

        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_META_DATA);
            try {

                long maxId = 0;

                while (rs.next()) {

                    long messageId = rs.getLong(1);
                    Blob dataAsBlob = rs.getBlob(2);

                    if (messageId > maxId) {
                        maxId = messageId;
                    }

                    byte[] dataAsBytes = dataAsBlob.getBytes(1, (int) dataAsBlob.length());
                    java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes);
                    buf.position(1);
                    buf = buf.slice();
                    MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]];
                    StorableMessageMetaData metaData = type.getFactory().createMetaData(buf);
                    StoredDerbyMessage message = new StoredDerbyMessage(messageId, metaData, true);
                    messageHandler.message(message);
                }

                _messageId.set(maxId);

                messageHandler.completeMessageRecovery();
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } finally {
        conn.close();
    }
}

From source file:ubic.gemma.core.externalDb.GoldenPathSequenceAnalysis.java

private Collection<Gene> queryAndExtract(final String chromosome, String query, Object[] params) {
    return this.getJdbcTemplate().query(query, params, new ResultSetExtractor<Collection<Gene>>() {

        @Override/*www . j a  va 2s  .  c  om*/
        public Collection<Gene> extractData(ResultSet rs) throws SQLException, DataAccessException {

            Collection<Gene> r = new HashSet<>();
            while (rs.next()) {

                Gene gene = Gene.Factory.newInstance();

                gene.setNcbiGeneId(Integer.parseInt(rs.getString(1)));
                gene.setOfficialSymbol(rs.getString(2));
                gene.setName(gene.getOfficialSymbol());

                PhysicalLocation pl = PhysicalLocation.Factory.newInstance();
                pl.setNucleotide(rs.getLong(3));
                pl.setNucleotideLength(rs.getInt(4) - rs.getInt(3));
                pl.setStrand(rs.getString(5));
                pl.setBin(SequenceBinUtils.binFromRange((int) rs.getLong(3), rs.getInt(4)));

                Chromosome c = new Chromosome(SequenceManipulation.deBlatFormatChromosomeName(chromosome),
                        GoldenPathSequenceAnalysis.this.getTaxon());
                pl.setChromosome(c);

                // note that we aren't setting the chromosome here; we already know that.
                gene.setPhysicalLocation(pl);
                r.add(gene);

                Blob blockSizes = rs.getBlob(6);
                Blob blockStarts = rs.getBlob(7);

                GoldenPathSequenceAnalysis.this.setBlocks(gene, blockSizes, blockStarts);

            }
            return r;
        }
    });
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * {@inheritDoc}/*w ww.j  av a 2 s.c  o  m*/
 */
public void checkConsistency(String[] uuids, boolean recursive, boolean fix) {
    log.info("{}: checking workspace consistency...", name);

    int count = 0;
    int total = 0;
    Collection modifications = new ArrayList();

    if (uuids == null) {
        // get all node bundles in the database with a single sql statement,
        // which is (probably) faster than loading each bundle and traversing the tree
        ResultSet rs = null;
        try {
            String sql = "select count(*) from " + schemaObjectPrefix + "BUNDLE";
            Statement stmt = connectionManager.executeStmt(sql, new Object[0]);
            try {
                rs = stmt.getResultSet();
                if (!rs.next()) {
                    log.error("Could not retrieve total number of bundles. empty result set.");
                    return;
                }
                total = rs.getInt(1);
            } finally {
                closeResultSet(rs);
            }
            if (getStorageModel() == SM_BINARY_KEYS) {
                sql = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE";
            } else {
                sql = "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix + "BUNDLE";
            }
            stmt = connectionManager.executeStmt(sql, new Object[0]);
            rs = stmt.getResultSet();

            // iterate over all node bundles in the db
            while (rs.next()) {
                NodeId id;
                if (getStorageModel() == SM_BINARY_KEYS) {
                    id = new NodeId(new UUID(rs.getBytes(1)));
                } else {
                    id = new NodeId(new UUID(rs.getLong(1), rs.getLong(2)));
                }

                // issuing 2nd statement to circumvent issue JCR-1474
                ResultSet bRs = null;
                byte[] data = null;
                try {
                    Statement bSmt = connectionManager.executeStmt(bundleSelectSQL, getKey(id.getUUID()));
                    bRs = bSmt.getResultSet();
                    if (!bRs.next()) {
                        throw new SQLException("bundle cannot be retrieved?");
                    }
                    Blob blob = bRs.getBlob(1);
                    data = getBytes(blob);
                } finally {
                    closeResultSet(bRs);
                }

                try {
                    // parse and check bundle
                    // checkBundle will log any problems itself
                    DataInputStream din = new DataInputStream(new ByteArrayInputStream(data));
                    if (binding.checkBundle(din)) {
                        // reset stream for readBundle()
                        din = new DataInputStream(new ByteArrayInputStream(data));
                        NodePropBundle bundle = binding.readBundle(din, id);
                        checkBundleConsistency(id, bundle, fix, modifications);
                    } else {
                        log.error("invalid bundle '" + id + "', see previous BundleBinding error log entry");
                    }
                } catch (Exception e) {
                    log.error("Error in bundle " + id + ": " + e);
                }
                count++;
                if (count % 1000 == 0) {
                    log.info(name + ": checked " + count + "/" + total + " bundles...");
                }
            }
        } catch (Exception e) {
            log.error("Error loading bundle", e);
        } finally {
            closeResultSet(rs);
            total = count;
        }
    } else {
        // check only given uuids, handle recursive flag

        // 1) convert uuid array to modifiable list
        // 2) for each uuid do
        //     a) load node bundle
        //     b) check bundle, store any bundle-to-be-modified in collection
        //     c) if recursive, add child uuids to list of uuids

        List uuidList = new ArrayList(uuids.length);
        // convert uuid string array to list of UUID objects
        for (int i = 0; i < uuids.length; i++) {
            try {
                uuidList.add(new UUID(uuids[i]));
            } catch (IllegalArgumentException e) {
                log.error("Invalid uuid for consistency check, skipping: '" + uuids[i] + "': " + e);
            }
        }

        // iterate over UUIDs (including ones that are newly added inside the loop!)
        for (int i = 0; i < uuidList.size(); i++) {
            final UUID uuid = (UUID) uuidList.get(i);
            try {
                // load the node from the database
                NodeId id = new NodeId(uuid);
                NodePropBundle bundle = loadBundle(id, true);

                if (bundle == null) {
                    log.error("No bundle found for uuid '" + uuid + "'");
                    continue;
                }

                checkBundleConsistency(id, bundle, fix, modifications);

                if (recursive) {
                    Iterator iter = bundle.getChildNodeEntries().iterator();
                    while (iter.hasNext()) {
                        NodePropBundle.ChildNodeEntry entry = (NodePropBundle.ChildNodeEntry) iter.next();
                        uuidList.add(entry.getId().getUUID());
                    }
                }

                count++;
                if (count % 1000 == 0) {
                    log.info(name + ": checked " + count + "/" + uuidList.size() + " bundles...");
                }
            } catch (ItemStateException e) {
                // problem already logged (loadBundle called with logDetailedErrors=true)
            }
        }

        total = uuidList.size();
    }

    // repair collected broken bundles
    if (fix && !modifications.isEmpty()) {
        log.info(name + ": Fixing " + modifications.size() + " inconsistent bundle(s)...");
        Iterator iterator = modifications.iterator();
        while (iterator.hasNext()) {
            NodePropBundle bundle = (NodePropBundle) iterator.next();
            try {
                log.info(name + ": Fixing bundle '" + bundle.getId() + "'");
                bundle.markOld(); // use UPDATE instead of INSERT
                storeBundle(bundle);
                evictBundle(bundle.getId());
            } catch (ItemStateException e) {
                log.error(name + ": Error storing fixed bundle: " + e);
            }
        }
    }

    log.info(name + ": checked " + count + "/" + total + " bundles.");
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * Performs a consistency check.//from   w  w  w. j a v  a 2  s  . co m
 */
private void checkConsistency() {
    int count = 0;
    int total = 0;
    log.info("{}: checking workspace consistency...", name);

    Collection modifications = new ArrayList();
    ResultSet rs = null;
    DataInputStream din = null;
    try {
        String sql;
        if (getStorageModel() == SM_BINARY_KEYS) {
            sql = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE";
        } else {
            sql = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE";
        }
        Statement stmt = connectionManager.executeStmt(sql, new Object[0]);
        rs = stmt.getResultSet();
        while (rs.next()) {
            NodeId id;
            Blob blob;
            if (getStorageModel() == SM_BINARY_KEYS) {
                id = new NodeId(new UUID(rs.getBytes(1)));
                blob = rs.getBlob(2);
            } else {
                id = new NodeId(new UUID(rs.getLong(1), rs.getLong(2)));
                blob = rs.getBlob(3);
            }
            din = new DataInputStream(blob.getBinaryStream());
            try {
                NodePropBundle bundle = binding.readBundle(din, id);
                Collection missingChildren = new ArrayList();
                Iterator iter = bundle.getChildNodeEntries().iterator();
                while (iter.hasNext()) {
                    NodePropBundle.ChildNodeEntry entry = (NodePropBundle.ChildNodeEntry) iter.next();
                    if (entry.getId().toString().endsWith("babecafebabe")) {
                        continue;
                    }
                    if (id.toString().endsWith("babecafebabe")) {
                        continue;
                    }
                    try {
                        NodePropBundle child = loadBundle(entry.getId());
                        if (child == null) {
                            log.error("NodeState " + id.getUUID() + " references inexistent child "
                                    + entry.getName() + " with id " + entry.getId().getUUID());
                            missingChildren.add(entry);
                        } else {
                            NodeId cp = child.getParentId();
                            if (cp == null) {
                                log.error("ChildNode has invalid parent uuid: null");
                            } else if (!cp.equals(id)) {
                                log.error("ChildNode has invalid parent uuid: " + cp + " (instead of "
                                        + id.getUUID() + ")");
                            }
                        }
                    } catch (ItemStateException e) {
                        log.error("Error while loading child node: " + e);
                    }
                }
                if (consistencyFix && !missingChildren.isEmpty()) {
                    Iterator iterator = missingChildren.iterator();
                    while (iterator.hasNext()) {
                        bundle.getChildNodeEntries().remove(iterator.next());
                    }
                    modifications.add(bundle);
                }

                NodeId parentId = bundle.getParentId();
                if (parentId != null) {
                    if (!exists(parentId)) {
                        log.error("NodeState " + id + " references inexistent parent id " + parentId);
                    }
                }
            } catch (IOException e) {
                log.error("Error in bundle " + id + ": " + e);
                din = new DataInputStream(blob.getBinaryStream());
                binding.checkBundle(din);
            }
            count++;
            if (count % 1000 == 0) {
                log.info(name + ": checked " + count + "/" + total + " bundles...");
            }
        }
    } catch (Exception e) {
        log.error("Error in bundle", e);
    } finally {
        IOUtils.closeQuietly(din);
        closeResultSet(rs);
    }

    if (consistencyFix && !modifications.isEmpty()) {
        log.info(name + ": Fixing " + modifications.size() + " inconsistent bundle(s)...");
        Iterator iterator = modifications.iterator();
        while (iterator.hasNext()) {
            NodePropBundle bundle = (NodePropBundle) iterator.next();
            try {
                log.info(name + ": Fixing bundle " + bundle.getId());
                bundle.markOld(); // use UPDATE instead of INSERT
                storeBundle(bundle);
            } catch (ItemStateException e) {
                log.error(name + ": Error storing fixed bundle: " + e);
            }
        }
    }

    log.info(name + ": checked " + count + "/" + total + " bundles.");
}

From source file:ubic.gemma.externalDb.GoldenPathSequenceAnalysis.java

/**
 * Check to see if there are ESTs that overlap with this region. We provisionally promote the ESTs to the status of
 * genes for this purpose./*from w  ww.  j  a  v a 2 s. co m*/
 * 
 * @param chromosome
 * @param regionStart the region to be checked
 * @param regionEnd
 * @return The ESTs which overlap the query region. (using the all_est table)
 */
public Collection<Gene> findESTs(final String chromosome, Long regionStart, Long regionEnd, String strand) {

    String searchChrom = SequenceManipulation.blatFormatChromosomeName(chromosome);
    String query = "SELECT est.qName, est.qName, est.tStart, est.tEnd, est.strand, est.blockSizes, est.tStarts  "
            + " FROM all_est as est  WHERE "
            + "((est.tStart > ? AND est.tEnd < ?) OR (est.tStart < ? AND est.tEnd > ?) OR "
            + "(est.tStart > ?  AND est.tStart < ?) OR  (est.tEnd > ? AND  est.tEnd < ? )) and est.tName = ? ";

    query = query + " and " + SequenceBinUtils.addBinToQuery("est", regionStart, regionEnd);

    if (strand != null) {
        query = query + " and est.strand = ?";
    }

    Object[] params = null;

    if (strand == null)
        params = new Object[] { regionStart, regionEnd, regionStart, regionEnd, regionStart, regionEnd,
                regionStart, regionEnd, searchChrom };
    else
        params = new Object[] { regionStart, regionEnd, regionStart, regionEnd, regionStart, regionEnd,
                regionStart, regionEnd, searchChrom, strand };

    return this.getJdbcTemplate().query(query, params, new ResultSetExtractor<Collection<Gene>>() {

        @Override
        public Collection<Gene> extractData(ResultSet rs) throws SQLException, DataAccessException {

            Collection<Gene> r = new HashSet<Gene>();
            while (rs.next()) {

                Gene gene = Gene.Factory.newInstance();

                gene.setNcbiGeneId(Integer.parseInt(rs.getString(1))); // STRING
                gene.setOfficialSymbol(rs.getString(2));
                gene.setName(gene.getOfficialSymbol());

                PhysicalLocation pl = PhysicalLocation.Factory.newInstance();
                pl.setNucleotide(rs.getLong(3));
                pl.setNucleotideLength(rs.getInt(4) - rs.getInt(3));
                pl.setStrand(rs.getString(5));
                pl.setBin(SequenceBinUtils.binFromRange((int) rs.getLong(3), rs.getInt(4)));

                Chromosome c = Chromosome.Factory.newInstance();
                c.setName(SequenceManipulation.deBlatFormatChromosomeName(chromosome));
                c.setTaxon(getTaxon());
                pl.setChromosome(c);

                // note that we aren't setting the chromosome here; we already know that.
                gene.setPhysicalLocation(pl);
                r.add(gene);

                Blob blockSizes = rs.getBlob(6);
                Blob blockStarts = rs.getBlob(7);

                setBlocks(gene, blockSizes, blockStarts);

            }
            return r;
        }
    });

}

From source file:org.rhq.enterprise.server.content.ContentManagerBean.java

/** For Testing only<br><br>
 * //from w w w.  j  a  v a 2s  .c  o  m
 * Writes the contents of a the Blob out to the stream passed in.
 *
 * @param stream non null stream where contents to be written to.
 */
public void writeBlobOutToStream(OutputStream stream, PackageBits bits, boolean closeStreams) {

    if (stream == null) {
        return; // no locate to write to
    }
    if ((bits == null) || (bits.getId() <= 0)) {
        //then PackageBits instance passed in is insufficiently initialized.
        log.warn("PackageBits insufficiently initialized. No data to write out.");
        return;
    }
    try {
        //open connection
        Connection conn = dataSource.getConnection();

        //prepared statement for retrieval of Blob.bits
        PreparedStatement ps = conn
                .prepareStatement("SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ?");
        try {
            ps.setInt(1, bits.getId());
            ResultSet results = ps.executeQuery();
            try {
                if (results.next()) {
                    //retrieve the Blob
                    Blob blob = results.getBlob(1);
                    //now copy the contents to the stream passed in
                    StreamUtil.copy(blob.getBinaryStream(), stream, closeStreams);
                }
            } finally {
                results.close();
            }
        } finally {
            ps.close();
        }
    } catch (Exception ex) {
        log.error("An error occurred while writing Blob contents out to stream :" + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:ubic.gemma.externalDb.GoldenPathSequenceAnalysis.java

/**
 * Check to see if there are mRNAs that overlap with this region. We promote the mRNAs to the status of genes for
 * this purpose./*  ww w  . j av  a 2 s  .  c o m*/
 * 
 * @param chromosome
 * @param regionStart the region to be checked
 * @param regionEnd
 * @return The mRNAs which overlap the query region.
 */
public Collection<Gene> findRNAs(final String chromosome, Long regionStart, Long regionEnd, String strand) {

    String searchChrom = SequenceManipulation.blatFormatChromosomeName(chromosome);
    String query = "SELECT mrna.qName, mrna.qName, mrna.tStart, mrna.tEnd, mrna.strand, mrna.blockSizes, mrna.tStarts  "
            + " FROM all_mrna as mrna  WHERE "
            + "((mrna.tStart > ? AND mrna.tEnd < ?) OR (mrna.tStart < ? AND mrna.tEnd > ?) OR "
            + "(mrna.tStart > ?  AND mrna.tStart < ?) OR  (mrna.tEnd > ? AND  mrna.tEnd < ? )) and mrna.tName = ? ";

    query = query + " and " + SequenceBinUtils.addBinToQuery("mrna", regionStart, regionEnd);

    if (strand != null) {
        query = query + " and mrna.strand = ?";
    }

    Object[] params = null;

    if (strand == null)
        params = new Object[] { regionStart, regionEnd, regionStart, regionEnd, regionStart, regionEnd,
                regionStart, regionEnd, searchChrom };
    else
        params = new Object[] { regionStart, regionEnd, regionStart, regionEnd, regionStart, regionEnd,
                regionStart, regionEnd, searchChrom, strand };

    return this.getJdbcTemplate().query(query, params, new ResultSetExtractor<Collection<Gene>>() {

        @Override
        public Collection<Gene> extractData(ResultSet rs) throws SQLException, DataAccessException {

            Collection<Gene> r = new HashSet<Gene>();
            while (rs.next()) {

                Gene gene = Gene.Factory.newInstance();

                gene.setNcbiGeneId(Integer.parseInt(rs.getString(1)));
                gene.setOfficialSymbol(rs.getString(2));
                gene.setName(gene.getOfficialSymbol());

                PhysicalLocation pl = PhysicalLocation.Factory.newInstance();
                pl.setNucleotide(rs.getLong(3));
                pl.setNucleotideLength(rs.getInt(4) - rs.getInt(3));
                pl.setStrand(rs.getString(5));
                pl.setBin(SequenceBinUtils.binFromRange((int) rs.getLong(3), rs.getInt(4)));

                Chromosome c = Chromosome.Factory.newInstance();
                c.setName(SequenceManipulation.deBlatFormatChromosomeName(chromosome));
                Taxon taxon = getTaxon();

                assert taxon != null;

                c.setTaxon(taxon);
                pl.setChromosome(c);

                // note that we aren't setting the chromosome here; we already know that.
                gene.setPhysicalLocation(pl);
                r.add(gene);

                Blob blockSizes = rs.getBlob(6);
                Blob blockStarts = rs.getBlob(7);

                setBlocks(gene, blockSizes, blockStarts);

            }
            return r;
        }
    });

}

From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java

/**
 * @param rs/*from  w  w w  . ja  v a2  s. com*/
 * @param interpretLiteralBytes
 * @param payloadLength
 * @return
 * @throws HttpMalformedHeaderException
 * @throws SQLException
 * @throws DatabaseException
 */
private List<WebSocketMessageDTO> buildMessageDTOs(ResultSet rs, boolean interpretLiteralBytes,
        int payloadLength) throws SQLException, DatabaseException {
    ArrayList<WebSocketMessageDTO> messages = new ArrayList<>();
    try {
        while (rs.next()) {
            WebSocketMessageDTO message;

            int channelId = rs.getInt("channel_id");
            WebSocketChannelDTO channel = getChannel(channelId);

            if (rs.getInt("fuzz_id") != 0) {
                WebSocketFuzzMessageDTO fuzzMessage = new WebSocketFuzzMessageDTO(channel);
                fuzzMessage.fuzzId = rs.getInt("fuzz_id");
                fuzzMessage.state = WebSocketFuzzMessageDTO.State.valueOf(rs.getString("state"));
                fuzzMessage.fuzz = rs.getString("fuzz");

                message = fuzzMessage;
            } else {
                message = new WebSocketMessageDTO(channel);
            }

            message.id = rs.getInt("message_id");
            message.setTime(rs.getTimestamp("timestamp"));
            message.opcode = rs.getInt("opcode");
            message.readableOpcode = WebSocketMessage.opcode2string(message.opcode);

            // read payload
            if (message.opcode == WebSocketMessage.OPCODE_BINARY) {
                if (payloadLength == -1) {
                    // load all bytes
                    message.payload = rs.getBytes("payload_bytes");
                } else {
                    Blob blob = rs.getBlob("payload_bytes");
                    int length = Math.min(payloadLength, (int) blob.length());
                    message.payload = blob.getBytes(1, length);
                    blob.free();
                }

                if (message.payload == null) {
                    message.payload = new byte[0];
                }
            } else {
                if (payloadLength == -1) {
                    // load all characters
                    message.payload = rs.getString("payload_utf8");
                } else {
                    Clob clob = rs.getClob("payload_utf8");
                    int length = Math.min(payloadLength, (int) clob.length());
                    message.payload = clob.getSubString(1, length);
                    clob.free();
                }

                if (message.payload == null) {
                    message.payload = "";
                }
            }

            message.isOutgoing = rs.getBoolean("is_outgoing");
            message.payloadLength = rs.getInt("payload_length");

            messages.add(message);
        }
    } finally {
        rs.close();
    }

    messages.trimToSize();

    return messages;
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value
 * type./*  w  ww .j a v  a2s .  co m*/
 * <p>
 * Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>
 * Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * 
 * @param rs is the ResultSet holding the data
 * @param index is the column index
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
private static String getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = new Byte(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = new Short(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = new Long(rs.getLong(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = new Float(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = new Double(rs.getDouble(index));
        wasNullCheck = true;
    } else if (java.sql.Time.class.equals(requiredType)) {
        // try {
        // value = rs.getTime(index);
        // } catch (SQLException e) {
        value = rs.getString(index);// ?string0000Time
        // if (value == null && !rs.wasNull()) {
        // value = "00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.sql.Date.class.equals(requiredType)) {
        // try {
        // value = convertTimestamp(rs.getTimestamp(index));
        // } catch (SQLException e) {
        // ?string0000-00-00 00:00:00Timestamp 
        value = rs.getString(index);
        // if (value == null && !rs.wasNull()) {
        // value = "0000:00:00 00:00:00"; //
        // mysqlzeroDateTimeBehavior=convertToNull0null
        // }
        // }
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (BigInteger.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else if (byte[].class.equals(requiredType)) {
        try {
            byte[] bytes = rs.getBytes(index);
            if (bytes == null) {
                value = null;
            } else {
                value = new String(bytes, "ISO-8859-1");// binaryiso-8859-1
            }
        } catch (UnsupportedEncodingException e) {
            throw new SQLException(e);
        }
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && (value != null) && rs.wasNull()) {
        value = null;
    }

    return (value == null) ? null : convertUtilsBean.convert(value);
}