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:org.openscore.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

@Override
public Map<Long, Payload> findPayloadByExecutionIds(Long... ids) {
    String sqlStat = QUERY_PAYLOAD_BY_EXECUTION_IDS.replaceAll(":OO_EXECUTION_STATES", getExecStateTableName());
    String qMarks = StringUtils.repeat("?", ",", ids.length);
    sqlStat = sqlStat.replace(":IDS", qMarks);

    final Map<Long, Payload> result = new HashMap<>();
    jdbcTemplate.query(sqlStat, ids, new RowCallbackHandler() {
        @Override//www .  j  ava  2 s. c o  m
        public void processRow(ResultSet resultSet) throws SQLException {
            result.put(resultSet.getLong(1), new Payload(false, false, resultSet.getBytes("payload")));
        }
    });

    return result;
}

From source file:com.avego.oauth.migration.JdbcOauthMigrationDao.java

private List<OauthRefreshTokenRecord> getOauthRefreshTokenRecords(int limit, boolean migrated) {
    String likeClause = migrated ? "not like ('%-%') " : "like ('%-%') ";
    List<OauthRefreshTokenRecord> refreshTokens = getJdbcTemplate().query(
            "select token_id, token, authentication from " + getRefreshTokenTableName() + " where token_id "
                    + likeClause + " order by token_id limit " + limit,
            new RowMapper<OauthRefreshTokenRecord>() {

                public OauthRefreshTokenRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
                    OauthRefreshTokenRecord token = new OauthRefreshTokenRecord();
                    token.setTokenId(rs.getString(1));
                    token.setToken(rs.getBytes(2));
                    token.setAuthentication(rs.getBytes(3));
                    return token;
                }/*from  ww w  .j  a  v  a2s. co  m*/
            });
    return refreshTokens;
}

From source file:com.thinkbiganalytics.util.JdbcCommon.java

/**
 * converts a JDBC result set to an Avro stream
 *
 * @param rs        The result set of the JDBC query
 * @param outStream The output stream to for the Avro formatted records
 * @return the number of rows converted to Avro format
 * @throws SQLException if errors occur while reading data from the database
 * @throws IOException  if unable to convert to Avro format
 *//*from   ww w.  jav  a 2 s  .c om*/
public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream)
        throws SQLException, IOException {
    final Schema schema = createSchema(rs);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);
                final Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == ARRAY || javaSqlType == BLOB || javaSqlType == CLOB) {
                    // bytes requires little bit different handling
                    byte[] bytes = rs.getBytes(i);
                    ByteBuffer bb = ByteBuffer.wrap(bytes);
                    rec.put(i - 1, bb);

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());

                } else if (value instanceof BigDecimal || value instanceof BigInteger) {
                    // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    rec.put(i - 1, value.toString());

                } else if (value instanceof Number || value instanceof Boolean) {
                    rec.put(i - 1, value);

                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;
        }

        return nrOfRows;
    }
}

From source file:com.avego.oauth.migration.JdbcOauthMigrationDao.java

private List<OauthAccessTokenRecord> getOauthAccessTokenRecords(int limit, boolean migrated) {
    String likeClause = migrated ? "not like ('%-%') " : "like ('%-%') ";
    List<OauthAccessTokenRecord> accessTokens = getJdbcTemplate().query(
            "select token_id, token, authentication_id, user_name, client_id, authentication, refresh_token from "
                    + getAccessTokenTableName() + " where token_id " + likeClause + " order by token_id limit "
                    + limit,/*from   w w w  . ja v  a 2 s.c om*/
            new RowMapper<OauthAccessTokenRecord>() {

                public OauthAccessTokenRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
                    OauthAccessTokenRecord token = new OauthAccessTokenRecord();
                    token.setTokenId(rs.getString(1));
                    token.setToken(rs.getBytes(2));
                    token.setAuthenticationId(rs.getString(3));
                    token.setUserName(rs.getString(4));
                    token.setClientId(rs.getString(5));
                    token.setAuthentication(rs.getBytes(6));
                    token.setRefreshToken(rs.getString(7));
                    return token;
                }
            });
    return accessTokens;
}

From source file:gr.wavesoft.webng.io.cache.DiskCacheStorage.java

public HttpCacheEntry getEntry(String string) throws IOException {
    String key = WebNGSystem.SHA1Sum(string);
    try {/* w  ww.ja va  2 s  .c  o m*/

        // Fetch item
        Database.assignArgStatements(stmSelect, new Object[] { key });
        ResultSet r = stmSelect.executeQuery();
        if (!r.next())
            return null;

        // Build entry
        HttpCacheEntry e = (HttpCacheEntry) unserialize(r.getBytes("data"), key);

        // Return the entry
        return e;

    } catch (SQLException ex) {
        systemLogger.except(ex);
        return null;
    }
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public String getFileAsString_havahol(String h_id) throws SQLException {
    checkConnection();//from w w  w .j  av  a2 s  .c om

    PreparedStatement pst = conn.prepareStatement("SELECT * FROM havahol WHERE h_id = ?");
    pst.setString(1, h_id);
    ResultSet rs = pst.executeQuery();
    String fileAsString = "";
    while (rs.next()) {
        byte[] fileBytes = rs.getBytes("file");
        fileAsString = new String(fileBytes);
    }
    return fileAsString;
}

From source file:org.opencms.db.generic.CmsSqlManager.java

/**
 * Retrieves the value of the designated column in the current row of this ResultSet object as 
 * a byte array in the Java programming language.<p>
 * /*  www  . j a  va  2s .co m*/
 * The bytes represent the raw values returned by the driver. Overwrite this method if another 
 * database server requires a different handling of byte attributes in tables.<p>
 * 
 * @param res the result set
 * @param attributeName the name of the table attribute
 * 
 * @return byte[] the column value; if the value is SQL NULL, the value returned is null 
 * 
 * @throws SQLException if a database access error occurs
 */
public byte[] getBytes(ResultSet res, String attributeName) throws SQLException {

    return res.getBytes(attributeName);
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Retrieve all n-cubes that have a name that matches the SQL like statement, within the specified app, status,
 * version, and system date.//from ww w. j  av a  2 s . c  om
 */
public static Object[] getNCubes(Connection connection, String app, String version, String status,
        String sqlLike, Date sysDate) {
    validate(connection, app, version);
    validateStatus(status);

    if (sqlLike == null) {
        sqlLike = "%";
    }

    if (sysDate == null) {
        sysDate = new Date();
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT n_cube_id, n_cube_nm, notes_bin, version_no_cd, status_cd, app_cd, create_dt, update_dt, "
                        + "create_hid, update_hid, sys_effective_dt, sys_expiration_dt, business_effective_dt, business_expiration_dt FROM n_cube WHERE n_cube_nm LIKE ? AND app_cd = ? AND version_no_cd = ? AND status_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)");
        stmt.setString(1, sqlLike);
        stmt.setString(2, app);
        stmt.setString(3, version);
        stmt.setString(4, status);
        stmt.setDate(5, systemDate);
        stmt.setDate(6, systemDate);

        ResultSet rs = stmt.executeQuery();
        List<NCubeInfoDto> records = new ArrayList<NCubeInfoDto>();

        while (rs.next()) {
            NCubeInfoDto dto = new NCubeInfoDto();
            dto.id = Long.toString(rs.getLong("n_cube_id"));
            dto.name = rs.getString("n_cube_nm");
            byte[] notes = rs.getBytes("notes_bin");
            dto.notes = new String(notes == null ? "".getBytes() : notes, "UTF-8");
            dto.version = rs.getString("version_no_cd");
            dto.status = rs.getString("status_cd");
            dto.app = rs.getString("app_cd");
            dto.createDate = rs.getDate("create_dt");
            dto.updateDate = rs.getDate("update_dt");
            dto.createHid = rs.getString("create_hid");
            dto.updateHid = rs.getString("update_hid");
            dto.sysEffDate = rs.getDate("sys_effective_dt");
            dto.sysEndDate = rs.getDate("sys_expiration_dt");
            dto.bizEffDate = rs.getDate("business_effective_dt");
            dto.bizExpDate = rs.getDate("business_expiration_dt");
            records.add(dto);
        }
        return records.toArray();
    } catch (Exception e) {
        String s = "Unable to fetch NCubes matching '" + sqlLike + "' from database";
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

From source file:com.splicemachine.mrio.api.core.SMSQLUtil.java

public Activation getActivation(String sql, TxnView txnView) throws SQLException, StandardException {

    PreparedStatement ps = connect.prepareStatement("call syscs_util.get_activation(?)");
    ps.setString(1, sql);//from  w  ww  .j ava2  s  .  c  om
    ResultSet rs = ps.executeQuery();
    rs.next();
    byte[] activationHolderBytes = rs.getBytes(1);
    try {
        SpliceSpark.setupSpliceStaticComponents();
    } catch (IOException ioe) {
        StandardException.plainWrapException(ioe);
    }
    ActivationHolder ah = (ActivationHolder) SerializationUtils.deserialize(activationHolderBytes);
    ah.init(txnView);
    return ah.getActivation();
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGMutatiesDAO.java

@Override
public MutatiesFile getNexMutatiesFile() throws DAOException {
    try {//from   w ww .j a va2s  . co  m
        MutatiesFile file = jdbcTemplate.queryForObject(
                "select *" + " from bag_mutaties_file"
                        + " where date_from = (select (max(date_to)) from bag_mutaties_file where status = "
                        + ProcessingStatus.PROCESSED.ordinal() + ")", // + 
                //" union all" + 
                //" select *" +
                //" from bag_mutaties_file" +
                //" where date_from = (select (min(date_from)) from bag_mutaties_file where status = " + ProcessingStatus.UNPROCESSED.ordinal() + 
                //" and (select count(id) from bag_mutaties_file where status = " + ProcessingStatus.PROCESSED.ordinal() + ") = 0)",
                new RowMapper<MutatiesFile>() {
                    @Override
                    public MutatiesFile mapRow(ResultSet rs, int row) throws SQLException {
                        MutatiesFile object = new MutatiesFile();
                        object.setId(rs.getLong("id"));
                        object.setDateFrom(rs.getDate("date_from"));
                        object.setDateTo(rs.getDate("date_to"));
                        object.setContent(rs.getBytes("content"));
                        object.setStatus(ProcessingStatus.values()[rs.getInt("status")]);
                        return object;
                    }
                });
        return file;
    } catch (IncorrectResultSizeDataAccessException e) {
        return null;
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}