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.sentinel.instrumentationserver.metadata.MetadataDAO.java

/**
 * Retrieve the logo from the database.// w w w  .j ava  2s  . co m
 */
public byte[] retrieveLogoFromDatabase(String apkHash) {
    connectToDatabase();

    try {
        String sqlStatementGetLogoFromHash = QueryBuilder.getQueryToRetrieveLogoFile();
        PreparedStatement preparedStatement = databaseConnection.prepareStatement(sqlStatementGetLogoFromHash);
        preparedStatement.setString(1, apkHash);

        ResultSet resultSet = preparedStatement.executeQuery();
        byte[] logo = resultSet.getBytes(1);

        resultSet.close();
        preparedStatement.close();
        disconnectFromDatabase();
        return logo;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.ode.daohib.bpel.hobj.GZipDataType.java

/** Retrieve an instance of the mapped class from a JDBC resultset. */
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
    if (names.length != 1)
        throw new IllegalStateException("Expected a single column name instead of " + names.length);
    byte[] buf = rs.getBytes(names[0]);
    if (buf == null) {
        return null;
    }//from  ww w. jav a  2s .  c  o  m
    if (buf.length >= GZIP_PREFIX.length) {
        boolean gzip = true;
        for (int i = 0; i < GZIP_PREFIX.length; i++) {
            if (buf[i] != GZIP_PREFIX[i]) {
                gzip = false;
                break;
            }
        }
        if (gzip) {
            buf = gunzip(new ByteArrayInputStream(buf, GZIP_PREFIX.length, buf.length - GZIP_PREFIX.length));
        }
    }
    return buf;
}

From source file:org.ojbc.intermediaries.sn.dao.RapbackDAOImplTest.java

@Test
@DirtiesContext/*  ww w.  j  a v a  2s  .  co m*/
public void testSaveSubsequentResults() throws Exception {

    SubsequentResults subsequentResults = new SubsequentResults();
    subsequentResults.setUcn("9222201");
    subsequentResults.setRapSheet("rapsheet".getBytes());
    subsequentResults.setResultsSender(ResultSender.FBI);

    Integer pkId = rapbackDao.saveSubsequentResults(subsequentResults);
    assertNotNull(pkId);
    assertEquals(3, pkId.intValue());

    Connection conn = dataSource.getConnection();
    ResultSet rs = conn.createStatement()
            .executeQuery("select * from SUBSEQUENT_RESULTS where SUBSEQUENT_RESULT_ID = 3");
    assertTrue(rs.next());
    assertEquals("9222201", rs.getString("ucn"));

    String rapsheetContent = new String(ZipUtils.unzip(rs.getBytes("RAP_SHEET")));
    log.info("Rap sheet content: " + rapsheetContent);
    assertEquals("rapsheet", rapsheetContent);
}

From source file:org.zenoss.zep.dao.impl.IndexMetadataDaoImpl.java

@Override
@TransactionalReadOnly// ww  w .j  a v a 2s .  c om
public IndexMetadata findIndexMetadata(String indexName) throws ZepException {
    final String sql = "SELECT * FROM index_metadata WHERE zep_instance=:zep_instance AND index_name=:index_name";
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put(COLUMN_ZEP_INSTANCE, uuidConverter.toDatabaseType(zepInstanceId));
    fields.put(COLUMN_INDEX_NAME, indexName);
    final List<IndexMetadata> l = this.template.query(sql, new RowMapper<IndexMetadata>() {
        @Override
        public IndexMetadata mapRow(ResultSet rs, int rowNum) throws SQLException {
            IndexMetadata md = new IndexMetadata();
            md.setZepInstance(uuidConverter.fromDatabaseType(rs, COLUMN_ZEP_INSTANCE));
            md.setIndexName(rs.getString(COLUMN_INDEX_NAME));
            md.setIndexVersion(rs.getInt(COLUMN_INDEX_VERSION));
            md.setIndexVersionHash(rs.getBytes(COLUMN_INDEX_VERSION_HASH));
            return md;
        }
    }, fields);
    return (l.isEmpty()) ? null : l.get(0);
}

From source file:mitm.common.hibernate.CertificateArrayUserType.java

@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    Certificate[] certificates = null;

    byte[] bytes = rs.getBytes(names[CERTIFICATE_ARRAY_COLUMN]);

    if (!rs.wasNull() && bytes != null) {
        Object deserialized = SerializationUtils.deserialize(bytes);

        if (!(deserialized instanceof LinkedList)) {
            throw new IllegalArgumentException("Object is not a LinkedList.");
        }// ww  w. jav  a 2s  . co  m

        try {
            @SuppressWarnings("unchecked")
            List<EncodedCertificate> encodedCertificates = (LinkedList<EncodedCertificate>) deserialized;

            certificates = new Certificate[encodedCertificates.size()];

            for (int i = 0; i < certificates.length; i++) {
                certificates[i] = encodedCertificates.get(i).getCertificate();
            }
        } catch (CertificateException e) {
            throw new HibernateException(e);
        } catch (NoSuchProviderException e) {
            throw new HibernateException(e);
        }
    }

    return certificates;
}

From source file:wikipedia.sql.Links.java

/** Gets array of ArticleIdAndTitle of pages which point to page with the 
 * title 'title_to', number of return array is limited by 'n_limit'.
 *
 * @param increment// ww  w  .  jav  a 2  s . c  om
 */
public static ArticleIdAndTitle[] getFromByTitleTo(SessionHolder session, String title_to,
        PageNamespace namespace, int n_limit) {
    // SELECT page_id, page_title, page_is_redirect FROM page,pagelinks 
    // WHERE page_id=pl_from AND pl_title='' AND pl_namespace = 0 LIMIT 4;
    sb.setLength(0);
    sb.append(
            "SELECT page_id, page_title, page_is_redirect FROM page,pagelinks WHERE page_id=pl_from AND pl_title='");
    sb.append(session.connect.enc.EncodeToDB(StringUtil.spaceToUnderscore(StringUtil.escapeChars(title_to))));
    sb.append("' AND pl_namespace=");
    sb.append(namespace.toInt());

    if (-1 != n_limit) {
        sb.append(" LIMIT ");
        sb.append(n_limit);
    }

    List<ArticleIdAndTitle> aid = new ArrayList<ArticleIdAndTitle>();
    //return getLinksSQL_AsID(session, sb_sql_count_size.toString(), sb_sql.toString(), n_limit);
    try {
        Statement s = session.connect.conn.createStatement();
        s.executeQuery(sb.toString());
        ResultSet rs = s.getResultSet();
        //if (rs.next()) {

        Encodings e = session.connect.enc;
        // gets all id, make permutation, takes first 'min' elements
        while (rs.next()) {
            int page_id = rs.getInt("page_id");
            if (1 == rs.getInt("page_is_redirect")) {
                page_id = -page_id;
            }

            String db_str = Encodings.bytesTo(rs.getBytes("page_title"), e.GetDBEnc());
            String page_title = e.EncodeFromDB(db_str);

            aid.add(new ArticleIdAndTitle(page_id, page_title));
        }
        //}
        rs.close();
        s.close();
    } catch (SQLException ex) {
        System.err.println("SQLException (Links.getFromByTitleTo() ArticleIdAndTitle[]): sql='" + sb.toString()
                + "' " + ex.getMessage());
    }

    return aid.toArray(ArticleIdAndTitle.NULL_ARTICLEIDANDTITLE_ARRAY);
}

From source file:com.uit.anonymousidentity.Repository.Nonces.NonceJDBCTemplate.java

public Set<Nonce> getNoncesBySID(String sid) throws SQLException {
    String sql = "select * from " + TABLE_NAME + " where " + SID + " = " + "'" + sid + "'";
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    ResultSet rs = pst.executeQuery(sql);
    if (rs.next()) {
        //data valid
        Integer nonceID;//from  w  ww  . ja  v  a2 s . c om
        String nonceSID;
        byte[] nonceBytes;
        Set<Nonce> set = new HashSet<>();
        do {
            nonceID = rs.getInt(ID);
            nonceSID = rs.getString(SID);
            nonceBytes = rs.getBytes(VALUE);
            Nonce nonce = new Nonce();
            nonce.setId(nonceID);
            nonce.setIssuerSid(nonceSID);
            nonce.setByteArray(nonceBytes);
            set.add(nonce);
        } while (rs.next());
        return set;
    } else {
        return null;
    }
}

From source file:com.jagornet.dhcp.db.JdbcIaAddressDAO.java

public List<InetAddress> findExistingIPs(final InetAddress startAddr, final InetAddress endAddr) {
    return getJdbcTemplate().query("select ipaddress from iaaddress"
            + " where ipaddress >= ? and ipaddress <= ?" + " order by ipaddress",
            new PreparedStatementSetter() {
                @Override//from ww  w.j a  va2s  .com
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, startAddr.getAddress());
                    ps.setBytes(2, endAddr.getAddress());
                }
            }, new RowMapper<InetAddress>() {
                @Override
                public InetAddress mapRow(ResultSet rs, int rowNum) throws SQLException {
                    InetAddress inetAddr = null;
                    try {
                        inetAddr = InetAddress.getByAddress(rs.getBytes("ipaddress"));
                    } catch (UnknownHostException e) {
                        // re-throw as SQLException
                        throw new SQLException("Unable to map ipaddress", e);
                    }
                    return inetAddr;
                }
            });
}

From source file:com.jagornet.dhcp.db.JdbcIaPrefixDAO.java

public List<InetAddress> findExistingIPs(final InetAddress startAddr, final InetAddress endAddr) {
    return getJdbcTemplate().query("select prefixaddress from iaprefix"
            + " where prefixaddress >= ? and prefixaddress <= ?" + " order by prefixaddress",
            new PreparedStatementSetter() {
                @Override//  w w w.  ja  v  a2  s . c  o m
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setBytes(1, startAddr.getAddress());
                    ps.setBytes(2, endAddr.getAddress());
                }
            }, new RowMapper<InetAddress>() {
                @Override
                public InetAddress mapRow(ResultSet rs, int rowNum) throws SQLException {
                    InetAddress inetAddr = null;
                    try {
                        inetAddr = InetAddress.getByAddress(rs.getBytes("prefixaddress"));
                    } catch (UnknownHostException e) {
                        // re-throw as SQLException
                        throw new SQLException("Unable to map prefixaddress", e);
                    }
                    return inetAddr;
                }
            });
}

From source file:io.cloudslang.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

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

    final Map<Long, Payload> result = new HashMap<>();
    findPayloadByExecutionIdsJDBCTemplate.query(sqlStat, ids, new RowCallbackHandler() {
        @Override//  ww  w .  j a  v  a2  s  . c om
        public void processRow(ResultSet resultSet) throws SQLException {
            result.put(resultSet.getLong(1), new Payload(resultSet.getBytes("payload")));
        }
    });

    return result;
}