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:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java

@Override
public byte[] getNodeBytes(final VospaceId identifier) {
    return DbPoolServlet.goSql("Retrieving node " + identifier + " for user " + owner + " from meta DB",
            "SELECT node FROM nodes JOIN containers ON nodes.container_id = containers.container_id JOIN user_identities ON containers.user_id = user_identities.user_id "
                    + "WHERE `current_rev` = 1 AND `container_name` = ? AND `path` = ? AND `identity` = ?",
            new SqlWorker<byte[]>() {
                @Override/* w  w  w  .j  ava2 s  .c o m*/
                public byte[] go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setString(1, identifier.getNodePath().getContainerName());
                    stmt.setString(2, identifier.getNodePath().getNodeRelativeStoragePath());
                    stmt.setString(3, owner);
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next())
                        return rs.getBytes(1);
                    else {
                        logger.error("Node " + identifier.toString() + " not found.");
                        throw new NotFoundException("NodeNotFound");
                    }
                }
            });
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void loadObfuscationKeys(Connection con, ShareMetaData smd) throws SQLException, SignatureException {
    if (smd.obfuscationKeys == null) {
        smd.obfuscationKeys = new ObfuscationKeyDB();
    }// w w w. ja  va2 s . c  om
    PreparedStatement s = con.prepareStatement(QUERY_OBFUSCATION_KEYS);
    ResultSet rs = s.executeQuery();
    while (rs.next()) {
        PublicKey key = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_DEV_PUB_KEY));
        byte[] encKey = rs.getBytes(COL_ENC_KEY);
        smd.obfuscationKeys.add(key, encKey);
    }
    rs.close();
}

From source file:com.px100systems.data.plugin.persistence.jdbc.Storage.java

protected void load(List<String> unitNames, final LoadCallback callback) {
    final LoadData currentRecord = new LoadData();

    StringBuilder where = new StringBuilder();
    if (unitNames != null)
        for (String like : unitNames) {
            if (where.length() > 0)
                where.append(" OR ");
            where.append("(unit_name LIKE '");
            where.append(like);/*from  www  . j a  va2s  . co  m*/
            where.append("%')");
        }

    connection.getJdbc().setFetchSize(50);
    connection.getJdbc()
            .query("SELECT unit_name, generator_name, class_name, id, data_size, data FROM " + table
                    + (where.length() > 0 ? (" WHERE " + where) : "")
                    + " ORDER BY unit_name ASC, id ASC, block_number ASC", new RowCallbackHandler() {
                        @Override
                        public void processRow(ResultSet rs) throws SQLException {
                            String unitName = rs.getString("unit_name");
                            String generatorName = rs.getString("generator_name");
                            String className = rs.getString("class_name");
                            Long id = rs.getLong("id");
                            int dataSize = rs.getInt("data_size");
                            byte[] data = rs.getBytes("data");

                            if (currentRecord.id != null && (!currentRecord.id.equals(id)
                                    || !currentRecord.unitName.equals(unitName)))
                                currentRecord.insert(callback);

                            currentRecord.grow(unitName, generatorName, className, id, data, dataSize);
                        }
                    });

    currentRecord.insert(callback);
}

From source file:org.wso2.carbon.identity.workflow.mgt.dao.WorkflowRequestDAO.java

/**
 * Retrieve workflow request specified by the given uuid
 *
 * @param uuid The uuid of the request to be retrieved
 * @return// w  ww.  j  av a 2  s.  c  o m
 * @throws WorkflowException
 */
public WorkflowRequest retrieveWorkflow(String uuid) throws InternalWorkflowException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    ResultSet rs = null;

    String query = SQLConstants.GET_WORKFLOW_REQUEST_QUERY;
    try {
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, uuid);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            byte[] requestBytes = rs.getBytes(SQLConstants.REQUEST_COLUMN);
            return deserializeWorkflowRequest(requestBytes);
        }
    } catch (SQLException e) {
        throw new InternalWorkflowException("Error when executing the sql query:" + query, e);
    } catch (ClassNotFoundException | IOException e) {
        throw new InternalWorkflowException("Error when deserializing the workflow request. uuid = " + uuid, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
    return null;
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void loadShareKeys(Connection con, ShareMetaData smd) throws SQLException, SignatureException {
    if (smd.shareKeys == null) {
        smd.shareKeys = new ShareKeyDB();
    }/*  ww w. ja  v  a 2 s .  co  m*/

    PreparedStatement s = con.prepareStatement(QUERY_SHARE_KEYS);
    ResultSet rs = s.executeQuery();
    while (rs.next()) {
        PublicKey key = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_DEV_PUB_KEY));
        int keyID = rs.getInt(COL_KEY_ID);
        byte[] encKey = rs.getBytes(COL_ENC_KEY);
        ShareKeyDBEntry entry = smd.shareKeys.getEntry(keyID);
        if (entry == null) {
            logger.debug("Creating new ShareKeyEntry: " + keyID);
            entry = new ShareKeyDBEntry(smd.shareKeyAlgorithm, keyID);
            smd.shareKeys.add(keyID, entry);
        }
        logger.debug("Adding ShareKey to entry " + keyID + " for key " + DigestUtils.md2Hex(key.getEncoded()));
        entry.addEncryptedKey(encKey, key);
        logger.debug("Number of keys in entry: " + entry.size());
    }
    rs.close();
}

From source file:org.codesearch.commons.database.DBAccessImpl.java

/**
 * {@inheritDoc}//from ww  w. j a va  2 s.com
 */
@Override
public synchronized Map<String, AstNode> getFilesImportingTargetFile(String targetFileName,
        String targetRepositoryName) throws DatabaseAccessException {
    Map<String, AstNode> files = new HashMap<String, AstNode>();
    ObjectInputStream regObjectStream;
    ResultSetHandler<Map<String, byte[]>> h = new ResultSetHandler<Map<String, byte[]>>() {

        @Override
        public Map<String, byte[]> handle(ResultSet rs) throws SQLException {
            Map<String, byte[]> results = new HashMap<String, byte[]>();

            while (rs.next()) {
                results.put(rs.getString(1), rs.getBytes(2));
            }
            return results;
        }
    };

    QueryRunner run = new QueryRunner(dataSource);
    String targetPackageName = targetFileName.substring(0, targetFileName.lastIndexOf('.')) + ".*";

    try {
        Map<String, byte[]> results = run.query(STMT_GET_FILES_IMPORTING_FILE, h, targetFileName,
                targetPackageName);
        for (Map.Entry<String, byte[]> entry : results.entrySet()) {
            ByteArrayInputStream regArrayStream = new ByteArrayInputStream(entry.getValue());
            regObjectStream = new ObjectInputStream(regArrayStream);
            AstNode binaryIndex = (AstNode) regObjectStream.readObject();
            files.put(entry.getKey(), binaryIndex);
        }
    } catch (ClassNotFoundException ex) {
        throw new DatabaseAccessException(
                "The content of the blob storing the binary_index of a file could not be parsed to an Object, the database content is probably corrupt");
    } catch (IOException ex) {
        throw new DatabaseAccessException(
                "Could not create a ByteArrayInputStream from the content of the binaryIndex field in the database");
    } catch (SQLException ex) {
        throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex);
    }
    return files;
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void loadSharePaticipants(Connection con, ShareMetaData smd) throws SQLException, SignatureException {

    smd.shareParticipants = new SharePartList();

    // Load Publickeys of participants
    PreparedStatement s = con.prepareStatement(QUERY_SPL);
    ResultSet rs = s.executeQuery();
    while (rs.next()) {
        PublicKey key = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_PUB_KEY));
        smd.shareParticipants.add(key, rs.getString(COL_ALIAS));
    }/*from w  ww.j a v a 2s. c om*/
    rs.close();

    // Load and verify signature
    s = con.prepareStatement(QUERY_SIGNATURE);
    rs = s.executeQuery();
    while (rs.next()) {
        byte[] signature = rs.getBytes(COL_SIGNATURE);
        boolean verified = false;
        try {
            verified = SignatureHelper.verify(smd.shareParticipants, signature, smd.ownerPubSigKey);
            smd.shareParticipants.setSignature(signature);
        } catch (Exception e) {
        }
        if (!verified) {
            throw new SignatureException("ShareParticipantList signature could not be verified!");
        }
    }
    rs.close();
    s.close();
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Get value from given ResultSet at given index with given SQL type.
 * //from   w  w  w . j a v a  2s.  c  om
 * @param rs The ResultSet to get the value from.
 * @param index The index of the value in the ResultSet.
 * @param sqlType The SQL type of the value.
 * @return The value.
 * @throws SQLException If a database access error occurs.
 */
public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException {
    switch (sqlType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return rs.getString(index);
    case Types.DECIMAL:
    case Types.NUMERIC:
        return rs.getBigDecimal(index);
    case Types.INTEGER:
        int intVal = rs.getInt(index);
        return (rs.wasNull() ? null : new Integer(intVal));
    case Types.TIME:
        return rs.getTime(index, getCalendar());
    case Types.DATE:
        return rs.getDate(index);
    case Types.TIMESTAMP:
        return rs.getTimestamp(index, getCalendar());
    case Types.FLOAT:
    case Types.DOUBLE:
        double doubleVal = rs.getDouble(index);
        return (rs.wasNull() ? null : new Double(doubleVal));
    case Types.REAL:
        float floatVal = rs.getFloat(index);
        return (rs.wasNull() ? null : new Float(floatVal));
    case Types.SMALLINT:
        short shortVal = rs.getShort(index);
        return (rs.wasNull() ? null : new Short(shortVal));
    case Types.TINYINT:
        byte byteVal = rs.getByte(index);
        return (rs.wasNull() ? null : new Byte(byteVal));
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
    case Types.BINARY:
        return rs.getBytes(index);
    case Types.BLOB:
        Blob blob = rs.getBlob(index);
        return (blob == null ? null : blob.getBinaryStream());
    case Types.CLOB:
        return rs.getClob(index);
    case Types.BIGINT:
        long longVal = rs.getLong(index);
        return (rs.wasNull() ? null : new Long(longVal));
    case Types.BIT:
        boolean boolVal = rs.getBoolean(index);
        return (rs.wasNull() ? null : new Boolean(boolVal));
    default:
        Object value = rs.getObject(index);
        return (rs.wasNull() ? null : value);
    }
}

From source file:com.akman.excel.view.frmExportExcel.java

public void getImage() {
    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;
    try {//from  ww w.j  a  va2 s  .co  m

        String sql = "SELECT MAX(ID), Image FROM ExcelData";

        pst = conn.prepareStatement(sql);

        rs = pst.executeQuery();

        if (rs.next()) {
            byte[] imagedata = rs.getBytes("Image");
            format = new ImageIcon(imagedata);
            Rectangle rect = lblImage.getBounds();
            //Scaling the image to fit in the picLabel
            Image scaledimage = format.getImage().getScaledInstance(rect.width, rect.height,
                    Image.SCALE_DEFAULT);
            //converting the image back to image icon to make an acceptable picLabel
            format = new ImageIcon(scaledimage);

            lblImage.setIcon(format);
        }

    } catch (SQLException ex) {
        Logger.getLogger(frmSelectImage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testUUIDGeneratedKeys() throws SQLException {
    Statement stat = conn.createStatement();
    stat.execute("CREATE TABLE TEST_UUID(id UUID DEFAULT random_UUID() PRIMARY KEY)");
    stat.execute("INSERT INTO TEST_UUID() VALUES()");
    ResultSet rs = stat.getGeneratedKeys();
    rs.next();/*from   w w w . j a  va 2s .  co m*/
    byte[] data = rs.getBytes(1);
    assertEquals(16, data.length);
    stat.execute("INSERT INTO TEST_UUID VALUES(random_UUID())");
    rs = stat.getGeneratedKeys();
    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST_UUID");
}