Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

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

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:wikipedia.sql.Links.java

/** @param skip_titles list of titles to be skipped */
public static String[] getTitleToByIDFrom(SessionHolder session, String title_from, int pl_from,
        PageNamespace namespace,//  w ww  .j  a  v  a  2s. c  o m
        //List<String> skip_titles, 
        Map<String, Set<String>> m_out, Map<String, Set<String>> m_in) {
    if (0 == pl_from) {
        return NULL_STRING_ARRAY;
    }

    Statement s = null;
    ResultSet rs = null;
    List<String> titles = new ArrayList<String>();

    sb.setLength(0);
    sb.append("SELECT pl_title FROM pagelinks WHERE pl_from=");
    sb.append(pl_from < 0 ? -pl_from : pl_from);
    sb.append(" AND pl_namespace=");
    sb.append(namespace.toInt());

    int size, i = 0;
    //String str_sql = null;
    try {
        s = session.connect.conn.createStatement();
        //str_sql = "SELECT pl_title FROM pagelinks WHERE " + sb.toString() + " AND pl_namespace="+namespace;

        //System.out.print("GetTitleToByIDFrom 1 sql="+sb.toString());
        s.executeQuery(sb.toString());
        //GetTitleToByIDFromQuery(rs, s, sb);
        //System.out.println(" OK.");

        rs = s.getResultSet();

        while (rs.next()) {
            Encodings e = session.connect.enc;
            String db_str = Encodings.bytesTo(rs.getBytes("pl_title"), e.GetDBEnc());
            String utf8_str = e.EncodeFromDB(db_str);

            //if(!session.skipTitle(utf8_str)) {
            //if(!skip_titles.contains(utf8_str)) {
            titles.add(utf8_str);
            //titles.add(connect.enc.EncodeFromDB(rs.getString("pl_title")));
            //}
            addTitlesToMaps(title_from, utf8_str, m_out, m_in);
            //}

            /*if(max_pl_title_len < utf8_str.length()) {
            max_pl_title_len = utf8_str.length();
            System.out.println("GetTitleToByIDFrom max_pl_title_len="+max_pl_title_len);
            }*/
        }
        /*if(max_titles_len < titles.size()) {
        max_titles_len = titles.size();
        System.out.println("GetTitleToByIDFrom max_titles_len="+max_titles_len);
        }*/

    } catch (SQLException ex) {
        System.err.println("SQLException (Links.java GetTitleToByIDFrom 1): sql='" + sb.toString() + "' "
                + ex.getMessage());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
            }
            rs = null;
        }
        if (s != null) {
            try {
                s.close();
            } catch (SQLException sqlEx) {
            }
            s = null;
        }
    }
    return (String[]) titles.toArray(NULL_STRING_ARRAY);
}

From source file:org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCache.java

/**
 * Queries the database for the value. If it gets a result, the value is
 * deserialized.// www  .j ava2s.  c o  m
 * <p>
 * @see org.apache.jcs.auxiliary.disk.AbstractDiskCache#doGet(java.io.Serializable)
 */
public ICacheElement doGet(Serializable key) {
    incrementGetCount();

    if (log.isDebugEnabled()) {
        log.debug("Getting " + key + " from disk");
    }

    if (!alive) {
        return null;
    }

    ICacheElement obj = null;

    byte[] data = null;
    try {
        // region, key
        String selectString = "select ELEMENT from " + getJdbcDiskCacheAttributes().getTableName()
                + " where REGION = ? and CACHE_KEY = ?";

        Connection con = poolAccess.getConnection();
        try {
            PreparedStatement psSelect = null;
            try {
                psSelect = con.prepareStatement(selectString);
                psSelect.setString(1, this.getCacheName());
                psSelect.setString(2, key.toString());

                ResultSet rs = psSelect.executeQuery();
                try {
                    if (rs.next()) {
                        data = rs.getBytes(1);
                    }
                    if (data != null) {
                        try {
                            // USE THE SERIALIZER
                            obj = (ICacheElement) getElementSerializer().deSerialize(data);
                        } catch (IOException ioe) {
                            log.error(ioe);
                        } catch (Exception e) {
                            log.error("Problem getting item.", e);
                        }
                    }
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                    rs.close();
                }
            } finally {
                if (psSelect != null) {
                    psSelect.close();
                }
                psSelect.close();
            }
        } finally {
            if (con != null) {
                con.close();
            }
        }
    } catch (SQLException sqle) {
        log.error(sqle);
    }

    if (log.isInfoEnabled()) {
        if (getCount % LOG_INTERVAL == 0) {
            // TODO make a log stats method
            log.info("Get Count [" + getCount + "]");
        }
    }

    return obj;
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.ConfigOperationDAOImpl.java

@Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status)
        throws OperationManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ConfigOperation configOperation;//  w  w w .  java  2s  . co m
    List<Operation> operations = new ArrayList<>();

    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        Connection conn = OperationManagementDAOFactory.getConnection();
        String sql = "SELECT co.OPERATION_ID, co.OPERATION_CONFIG FROM DM_CONFIG_OPERATION co "
                + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? "
                + "AND STATUS = ?) dm ON dm.OPERATION_ID = co.OPERATION_ID";

        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, enrolmentId);
        stmt.setString(2, status.toString());
        rs = stmt.executeQuery();

        while (rs.next()) {
            byte[] operationDetails = rs.getBytes("OPERATION_CONFIG");
            bais = new ByteArrayInputStream(operationDetails);
            ois = new ObjectInputStream(bais);
            configOperation = (ConfigOperation) ois.readObject();
            configOperation.setStatus(status);
            configOperation.setId(rs.getInt("OPERATION_ID"));
            operations.add(configOperation);
        }
    } catch (IOException e) {
        throw new OperationManagementDAOException(
                "IO Error occurred while de serialize the configuration " + "operation object", e);
    } catch (ClassNotFoundException e) {
        throw new OperationManagementDAOException(
                "Class not found error occurred while de serialize the " + "configuration operation object", e);
    } catch (SQLException e) {
        throw new OperationManagementDAOException("SQL error occurred while retrieving the operation available "
                + "for the device'" + enrolmentId + "' with status '" + status.toString(), e);
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ObjectOutputStream", e);
            }
        }
        OperationManagementDAOUtil.cleanupResources(stmt, rs);
    }
    return operations;
}

From source file:org.wso2.carbon.certificate.mgt.core.dao.impl.GenericCertificateDAOImpl.java

@Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    CertificateResponse certificateResponse;
    List<CertificateResponse> certificates = new ArrayList<>();
    PaginationResult paginationResult;//  w ww .  ja  v a2 s . c  o  m
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        Connection conn = this.getConnection();
        String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM "
                + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?";
        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, tenantId);
        stmt.setInt(2, rowNum);
        stmt.setInt(3, limit);
        resultSet = stmt.executeQuery();

        int resultCount = 0;
        while (resultSet.next()) {
            certificateResponse = new CertificateResponse();
            byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
            certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
            certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
            certificateResponse.setUsername(resultSet.getString("USERNAME"));
            CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
            certificates.add(certificateResponse);
            resultCount++;
        }
        paginationResult = new PaginationResult();
        paginationResult.setData(certificates);
        paginationResult.setRecordsTotal(resultCount);
    } catch (SQLException e) {
        String errorMsg = "SQL error occurred while retrieving the certificates.";
        log.error(errorMsg, e);
        throw new CertificateManagementDAOException(errorMsg, e);
    } finally {
        CertificateManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return paginationResult;
}

From source file:com.alfaariss.oa.authentication.password.jdbc.JDBCProtocolResource.java

/**
 * @see AbstractDigestorResourceHandler#getData(java.lang.String,
 *      java.lang.String)//from  ww  w .ja  v  a2 s  . c o m
 */
protected byte[] getData(String realm, String username) throws OAException, UserException {
    Connection oConnection = null;
    PreparedStatement sPreparedStatementQuery = null;
    ResultSet oResultSet = null;
    byte[] result = null;

    try {
        oConnection = _oDataSource.getConnection();
    } catch (SQLException e) {
        _logger.warn("Could not open connection", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    try {
        sPreparedStatementQuery = oConnection.prepareStatement(_query);
        sPreparedStatementQuery.setString(1, username);
        oResultSet = sPreparedStatementQuery.executeQuery();

        if (!oResultSet.next()) {
            _logger.debug("No result after executing query for user: " + username);
            throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        }

        result = oResultSet.getBytes(1);

        String sResult = oResultSet.getString(1);

        if (_logger.isDebugEnabled()) {
            _logger.debug("Result Bytes: " + new String(result));
            _logger.debug("Result string: " + sResult);
        }

        if (result == null) {
            _logger.warn("No user password found for user: " + username);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }
    } catch (SQLException e) {
        _logger.warn("Could not execute query", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (oConnection != null) {
                oConnection.close();
            }
        } catch (Exception e) {
            _logger.error("Could not close connection", e);
        }
    }

    return result;
}

From source file:org.wso2.carbon.certificate.mgt.core.dao.impl.PostgreSQLCertificateDAOImpl.java

@Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    CertificateResponse certificateResponse;
    List<CertificateResponse> certificates = new ArrayList<>();
    PaginationResult paginationResult;/*  w ww.j av a2 s . c o  m*/
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        Connection conn = this.getConnection();
        String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM "
                + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?";
        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, tenantId);
        stmt.setInt(2, limit);
        stmt.setInt(3, rowNum);
        resultSet = stmt.executeQuery();

        int resultCount = 0;
        while (resultSet.next()) {
            certificateResponse = new CertificateResponse();
            byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
            certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
            certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
            certificateResponse.setUsername(resultSet.getString("USERNAME"));
            CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
            certificates.add(certificateResponse);
            resultCount++;
        }
        paginationResult = new PaginationResult();
        paginationResult.setData(certificates);
        paginationResult.setRecordsTotal(resultCount);
    } catch (SQLException e) {
        String errorMsg = "SQL error occurred while retrieving the certificates.";
        log.error(errorMsg, e);
        throw new CertificateManagementDAOException(errorMsg, e);
    } finally {
        CertificateManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return paginationResult;
}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

private List<DataSource> getAttachments(long messageId) throws DAOException {
    try {/*from  w  w w .j  av a 2s.  c om*/
        return simpleJdbcTemplate.query(
                "select name, content_type, content" + " from ebms_attachment" + " where ebms_message_id = ?",
                new ParameterizedRowMapper<DataSource>() {
                    @Override
                    public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),
                                rs.getString("content_type"));
                        result.setName(rs.getString("name"));
                        return result;
                    }
                }, messageId);
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:com.linkedin.databus.bootstrap.utils.BootstrapTableReader.java

public void execute() throws Exception {
    String query = getQuery();//  w  ww . j a  v a  2 s. com
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();

        LOG.info("Executing query : " + query);
        rs = stmt.executeQuery(query);

        byte[] b1 = new byte[1024 * 1024];
        ByteBuffer buffer = ByteBuffer.wrap(b1);
        DbusEventInternalReadable event = _eventFactory.createReadOnlyDbusEventFromBuffer(buffer, 0);

        int count = 0;
        _eventHandler.onStart(query);

        while (rs.next()) {
            buffer.clear();
            buffer.put(rs.getBytes("val"));
            event = event.reset(buffer, 0);
            GenericRecord record = _decoder.getGenericRecord(event);
            _eventHandler.onRecord(event, record);
            count++;
        }
        _eventHandler.onEnd(count);
    } finally {
        DBHelper.close(rs, stmt, conn);
    }
}

From source file:com.joliciel.jochre.graphics.GraphicsDaoJdbc.java

@Override
public void loadOriginalImage(JochreImageInternal jochreImage) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT image_image FROM ocr_image WHERE image_id=:image_id";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();
    paramSource.addValue("image_id", jochreImage.getId());

    LOG.debug(sql);/*from   w w w  .  ja  v a2 s .c om*/
    logParameters(paramSource);

    byte[] pixels = (byte[]) jt.query(sql, paramSource, new ResultSetExtractor() {
        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                byte[] pixels = rs.getBytes("image_image");

                return pixels;
            } else {
                return null;
            }
        }

    });

    ByteArrayInputStream is = new ByteArrayInputStream(pixels);
    BufferedImage image;
    try {
        image = ImageIO.read(is);
        is.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    jochreImage.setOriginalImageDB(image);
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.PolicyOperationDAOImpl.java

@Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status)
        throws OperationManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    PolicyOperation policyOperation;//from  ww  w . j  a  va  2 s .c o  m
    List<Operation> operations = new ArrayList<>();

    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        Connection conn = OperationManagementDAOFactory.getConnection();
        String sql = "SELECT po.OPERATION_ID, ENABLED, OPERATION_DETAILS FROM DM_POLICY_OPERATION po "
                + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? "
                + "AND STATUS = ?) dm ON dm.OPERATION_ID = po.OPERATION_ID";

        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, enrolmentId);
        stmt.setString(2, status.toString());
        rs = stmt.executeQuery();

        while (rs.next()) {
            byte[] operationDetails = rs.getBytes("OPERATION_DETAILS");
            bais = new ByteArrayInputStream(operationDetails);
            ois = new ObjectInputStream(bais);
            policyOperation = (PolicyOperation) ois.readObject();
            policyOperation.setStatus(status);
            operations.add(policyOperation);
        }
    } catch (IOException e) {
        throw new OperationManagementDAOException(
                "IO Error occurred while de serialize the profile " + "operation object", e);
    } catch (ClassNotFoundException e) {
        throw new OperationManagementDAOException(
                "Class not found error occurred while de serialize the " + "profile operation object", e);
    } catch (SQLException e) {
        throw new OperationManagementDAOException("SQL error occurred while retrieving the operation "
                + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e);
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ObjectOutputStream", e);
            }
        }
        OperationManagementDAOUtil.cleanupResources(stmt, rs);
    }
    return operations;
}