Example usage for java.sql ResultSet getBinaryStream

List of usage examples for java.sql ResultSet getBinaryStream

Introduction

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

Prototype

java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a stream of uninterpreted bytes.

Usage

From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java

private void updateLocalPatchBLOB(Connection connection) throws SQLException, IOException {
    if (log.isDebugEnabled())
        log.debug("Updating local patch ");
    PreparedStatement segmentSelect = null;
    ResultSet resultSet = null;
    try {/*from w  w  w .  ja  v a  2s. c  o m*/
        segmentSelect = connection
                .prepareStatement("select version_, packet_ from search_segments where name_ = ?");
        segmentSelect.clearParameters();
        segmentSelect.setString(1, INDEX_PATCHNAME);
        resultSet = segmentSelect.executeQuery();
        if (resultSet.next()) {
            InputStream packetStream = null;
            try {
                long version = resultSet.getLong(1);
                packetStream = resultSet.getBinaryStream(2);
                clusterStorage.unpackPatch(packetStream);
                if (log.isDebugEnabled())
                    log.debug("Updated Patch from DB " + version);
            } finally {
                try {
                    packetStream.close();
                } catch (Exception ex) {
                    log.debug(ex);
                }
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Didnt find patch in database, this is Ok ");
        }
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentSelect.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }

}

From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java

/**
 * updte a segment from the database//from   w  ww. jav  a2s .co m
 * 
 * @param connection
 * @param addsi
 */
protected void updateLocalSegmentBLOB(Connection connection, SegmentInfo addsi)
        throws SQLException, IOException {
    if (log.isDebugEnabled())
        log.debug("Updating local segment from databse " + addsi);
    PreparedStatement segmentSelect = null;
    ResultSet resultSet = null;
    try {
        segmentSelect = connection
                .prepareStatement("select version_, packet_ from search_segments where name_ = ?");
        segmentSelect.clearParameters();
        segmentSelect.setString(1, addsi.getName());
        resultSet = segmentSelect.executeQuery();
        if (resultSet.next()) {
            InputStream packetStream = null;
            try {
                long version = resultSet.getLong(1);
                packetStream = resultSet.getBinaryStream(2);
                clusterStorage.unpackSegment(addsi, packetStream, version);
                if (log.isDebugEnabled())
                    log.debug("Updated Packet from DB to versiob " + version);
            } finally {
                try {
                    packetStream.close();
                } catch (Exception ex) {
                    log.debug(ex);
                }
            }
        } else {
            log.error("Didnt find segment in database");
        }
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentSelect.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }

}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public VersionRetriever getVersionList(ResourceIDImpl resourceID, long snapshotID) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;/*from  w w  w.  j av a 2  s. c o  m*/
    VersionRetriever versionRetriever = null;
    try {
        if (resourceID.isCollection()) {
            String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT "
                    + "WHERE REG_SNAPSHOT_ID=? AND REG_PATH_ID = ? "
                    + "AND REG_RESOURCE_NAME IS NULL AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setLong(1, snapshotID);
            ps.setInt(2, resourceID.getPathID());
            ps.setInt(3, CurrentSession.getTenantId());
        } else {
            String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT "
                    + "WHERE REG_SNAPSHOT_ID=? AND REG_PATH_ID = ? "
                    + "AND REG_RESOURCE_NAME=? AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setLong(1, snapshotID);
            ps.setInt(2, resourceID.getPathID());
            ps.setString(3, resourceID.getName());
            ps.setInt(4, CurrentSession.getTenantId());
        }

        result = ps.executeQuery();

        if (result.next()) {
            InputStream resourceVIDStream = RegistryUtils
                    .getMemoryStream(result.getBinaryStream(DatabaseConstants.RESOURCE_VIDS_FIELD));
            versionRetriever = new VersionRetriever(resourceVIDStream);
        }
    } catch (Exception e) {

        String msg = "Failed to get version of resource " + resourceID.getPath() + " of snapshot " + snapshotID
                + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return versionRetriever;
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceVersionDAO.java

public VersionRetriever getVersionList(ResourceIDImpl resourceID, long snapshotID) throws RepositoryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;/* w ww  .  j av  a2  s.com*/
    VersionRetriever versionRetriever = null;

    try {
        if (resourceID.isCollection()) {
            String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT "
                    + "WHERE REG_SNAPSHOT_ID=? AND REG_PATH_ID = ? "
                    + "AND REG_RESOURCE_NAME IS NULL AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setLong(1, snapshotID);
            ps.setInt(2, resourceID.getPathID());
            ps.setInt(3, CurrentContext.getTenantId());
        } else {
            String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT "
                    + "WHERE REG_SNAPSHOT_ID=? AND REG_PATH_ID = ? "
                    + "AND REG_RESOURCE_NAME=? AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setLong(1, snapshotID);
            ps.setInt(2, resourceID.getPathID());
            ps.setString(3, resourceID.getName());
            ps.setInt(4, CurrentContext.getTenantId());
        }

        result = ps.executeQuery();

        if (result.next()) {
            InputStream resourceVIDStream = RepositoryUtils
                    .getMemoryStream(result.getBinaryStream(DatabaseConstants.RESOURCE_VIDS_FIELD));
            versionRetriever = new VersionRetriever(resourceVIDStream);
        }
    } catch (Exception e) {
        String msg = "Failed to get version of resource " + resourceID.getPath() + " of snapshot " + snapshotID
                + ". " + e.getMessage();
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return versionRetriever;
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceDAO.java

public InputStream getContentStream(int contentID) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    PreparedStatement ps = null;/*w w  w .  j  a v  a 2s  .  co m*/
    ResultSet result = null;
    try {
        String resourceContentSQL = "SELECT REG_CONTENT_DATA  FROM  REG_CONTENT WHERE "
                + "REG_CONTENT_ID = ? AND REG_TENANT_ID=?";
        ps = conn.prepareStatement(resourceContentSQL);
        ps.setLong(1, contentID);
        ps.setInt(2, CurrentSession.getTenantId());
        result = ps.executeQuery();
        if (result.next()) {
            InputStream rawInputStream = result.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD);
            if (rawInputStream != null) {
                return RegistryUtils.getMemoryStream(rawInputStream);
            }
        }

    } catch (SQLException ex) {
        String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
        log.error(msg, ex);
        throw new RegistryException(msg, ex);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return null;
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceDAO.java

public InputStream getContentStream(int contentID) throws RepositoryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    PreparedStatement ps = null;/*from  ww w .j a  v a  2 s .c  o m*/
    ResultSet result = null;

    try {
        String resourceContentSQL = "SELECT REG_CONTENT_DATA  FROM  REG_CONTENT WHERE REG_CONTENT_ID = ? AND REG_TENANT_ID=?";
        ps = conn.prepareStatement(resourceContentSQL);
        ps.setLong(1, contentID);
        ps.setInt(2, CurrentContext.getTenantId());
        result = ps.executeQuery();

        if (result.next()) {
            InputStream rawInputStream = result.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD);
            if (rawInputStream != null) {
                return RepositoryUtils.getMemoryStream(rawInputStream);
            }
        }
    } catch (SQLException ex) {
        String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
        log.error(msg, ex);
        throw new RepositoryDBException(msg, ex);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return null;
}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or api identifier.
 * Both alias and api identifier are optional
 *
 * @param tenantId      : The id of the tenant which the certificate belongs to.
 * @param alias         : Alias for the certificate. (Optional)
 * @param apiIdentifier : The API which the certificate is mapped to. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 *//*from w  ww  . j  av a 2 s .com*/
public List<ClientCertificateDTO> getClientCertificates(int tenantId, String alias, APIIdentifier apiIdentifier)
        throws CertificateManagementException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
    int apiId = 0;
    int index = 1;
    String selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT;
    if (StringUtils.isNotEmpty(alias) && apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS_APIID;
    } else if (StringUtils.isNotEmpty(alias)) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS;
    } else if (apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_APIID;
    }

    try {
        connection = APIMgtDBUtil.getConnection();
        if (apiIdentifier != null) {
            apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, connection);
        }
        preparedStatement = connection.prepareStatement(selectQuery);
        preparedStatement.setBoolean(index, false);
        index++;
        preparedStatement.setInt(index, tenantId);
        index++;
        if (alias != null) {
            preparedStatement.setString(index, alias);
            index++;
        }
        if (apiIdentifier != null) {
            preparedStatement.setInt(index, apiId);
        }
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            alias = resultSet.getString("ALIAS");
            ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
            clientCertificateDTO.setTierName(resultSet.getString("TIER_NAME"));
            clientCertificateDTO.setAlias(alias);
            clientCertificateDTO.setCertificate(
                    APIMgtDBUtil.getStringFromInputStream(resultSet.getBinaryStream("CERTIFICATE")));
            if (apiIdentifier == null) {
                apiIdentifier = new APIIdentifier(
                        APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")),
                        resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
            }
            clientCertificateDTO.setApiIdentifier(apiIdentifier);
            clientCertificateDTOS.add(clientCertificateDTO);
        }
    } catch (SQLException e) {
        handleException("Error while searching client certificate details for the tenant " + tenantId, e);
    } catch (APIManagementException e) {
        handleException("API Management Exception while searching client certificate details for the tenant "
                + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return clientCertificateDTOS;
}

From source file:pt.iflow.flows.FlowHolderBean.java

public synchronized byte[] readTemplateData(UserInfoInterface userInfo, String name) {
    Connection db = null;/*ww w.  j  a v  a  2s.  c  om*/
    PreparedStatement st = null;
    ResultSet rs = null;
    byte[] data = null;
    try {
        db = Utils.getDataSource().getConnection();

        // copy from template
        st = db.prepareStatement("select data FROM flow_template where name=?");
        st.setString(1, name);
        rs = st.executeQuery();
        if (rs.next()) {
            InputStream is = rs.getBinaryStream("data");
            data = getBytes(is);
        }

    } catch (Exception e) {
        try {
            db.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        DatabaseInterface.closeResources(db, st, rs);
    }

    return data;

}

From source file:org.wso2.carbon.ml.database.internal.MLDatabaseService.java

/**
 * Retrieve the model summary/*from w  w  w .j ava  2s . c o  m*/
 */
@Override
public ModelSummary getModelSummary(long modelId) throws DatabaseHandlerException {
    Connection connection = null;
    PreparedStatement getStatement = null;
    ResultSet result = null;
    try {
        connection = dbh.getDataSource().getConnection();
        getStatement = connection.prepareStatement(SQLQueries.GET_MODEL_SUMMARY);
        getStatement.setLong(1, modelId);
        result = getStatement.executeQuery();
        if (result.first() && result.getBinaryStream(1) != null) {
            return MLDBUtil.getModelSummaryFromInputStream(result.getBinaryStream(1));
        } else {
            throw new DatabaseHandlerException("Summary not available for model: " + modelId);
        }
    } catch (Exception e) {
        throw new DatabaseHandlerException("An error occurred while retrieving the summary " + "of model "
                + modelId + ": " + e.getMessage(), e);
    } finally {
        // Close the database resources.
        MLDatabaseUtils.closeDatabaseResources(connection, getStatement);
    }
}

From source file:org.sakaiproject.db.impl.BasicSqlService.java

/**
 * Read a single field from the db, from multiple record - concatenating the binary values into value.
 * /* w ww.ja  v  a2  s  .c  o  m*/
 * @param callerConn
 *        The optional db connection object to use.
 * @param sql
 *        The sql statement.
 * @param fields
 *        The array of fields for parameters.
 * @param value
 *        The array of bytes to fill with the value read from the db.
 */
public void dbReadBinary(Connection callerConn, String sql, Object[] fields, byte[] value) {
    // check for a transaction conncetion
    if (callerConn == null) {
        callerConn = (Connection) threadLocalManager().get(TRANSACTION_CONNECTION);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("dbReadBinary(Connection " + callerConn + ", String " + sql + ", Object[] "
                + Arrays.toString(fields) + ")");
    }

    // for DEBUG
    long start = 0;
    long connectionTime = 0;
    int lenRead = 0;

    if (LOG.isDebugEnabled()) {
        String userId = usageSessionService().getSessionId();
        LOG.debug("Sql.dbReadBinary(): " + userId + "\n" + sql);
    }

    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet result = null;
    ResultSetMetaData meta = null;

    try {
        if (m_showSql)
            start = System.currentTimeMillis();
        if (callerConn != null) {
            conn = callerConn;
        } else {
            conn = borrowConnection();
        }
        if (m_showSql)
            connectionTime = System.currentTimeMillis() - start;
        if (m_showSql)
            start = System.currentTimeMillis();

        pstmt = conn.prepareStatement(sql);

        // put in all the fields
        prepareStatement(pstmt, fields);

        result = pstmt.executeQuery();

        int index = 0;
        while (result.next() && (index < value.length)) {
            InputStream stream = result.getBinaryStream(1);
            int len = stream.read(value, index, value.length - index);
            stream.close();
            index += len;
            if (m_showSql)
                lenRead += len;
        }
    } catch (Exception e) {
        LOG.warn("Sql.dbReadBinary(): " + e);
    } finally {
        if (null != result) {
            try {
                result.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): result close fail: " + e);
            }
        }
        if (null != pstmt) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                LOG.warn("Sql.dbReadBinary(): pstmt close fail: " + e);
            }
        }
        // return the connection only if we have borrowed a new one for this call
        if (callerConn == null) {
            if (null != conn) {
                // if we commit on read
                if (m_commitAfterRead) {
                    try {
                        conn.commit();
                    } catch (SQLException e) {
                        LOG.warn("Sql.dbReadBinary(): conn commit fail: " + e);
                    }
                }
                returnConnection(conn);
            }
        }
    }

    if (m_showSql) {
        debug("sql read binary: len: " + lenRead + "  time: " + connectionTime + " / "
                + (System.currentTimeMillis() - start), sql, fields);
    }
}