Example usage for java.sql ResultSet getBlob

List of usage examples for java.sql ResultSet getBlob

Introduction

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

Prototype

Blob getBlob(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:org.apache.gora.sql.store.SqlStore.java

protected Object readField(ResultSet resultSet, int columnIndex, Object field, Schema schema, Column column)
        throws SQLException, IOException {

    InputStream is = null;/* w w  w  .ja  v  a  2s . c om*/
    byte[] bytes = null;

    JdbcType type = JdbcType.get(resultSet.getMetaData().getColumnType(columnIndex));

    switch (type) {
    case BLOB:
        Blob blob = resultSet.getBlob(columnIndex);
        if (blob != null)
            is = blob.getBinaryStream();
        break;
    case BINARY:
    case VARBINARY:
        bytes = resultSet.getBytes(columnIndex);
        break;
    case LONGVARBINARY:
        is = resultSet.getBinaryStream(columnIndex);
        break;
    }

    if (bytes != null)
        return IOUtils.deserialize(bytes, datumReader, schema, field);
    else if (is != null)
        return IOUtils.deserialize(is, datumReader, schema, field);
    return field; // field is empty
}

From source file:com.cloudera.sqoop.testutil.ManagerCompatTestCase.java

protected void verifyBlob(String insertVal, byte[] returnVal, String seqFileVal) {
    String[] types = { "INTEGER NOT NULL", getBlobType() };
    String[] vals = { "1", insertVal };
    String[] checkCols = { "DATA_COL0", "DATA_COL1" };

    createTableWithColTypes(types, vals);

    // Verify readback of the data.
    ResultSet results = null;
    try {//  w  ww .  j ava2  s.c o  m
        results = getManager().readTable(getTableName(), getColNames());
        assertNotNull("Null results from readTable()!", results);
        assertTrue("Expected at least one row returned", results.next());
        Blob blob = results.getBlob(2);
        byte[] databaseBytes = blob.getBytes(1, (int) blob.length());
        log.info("Verifying readback of bytes from " + getTableName());

        assertEquals("byte arrays differ in size", returnVal.length, databaseBytes.length);
        for (int i = 0; i < returnVal.length; i++) {
            assertEquals("bytes differ at position " + i + ". Expected " + returnVal[i] + "; got "
                    + databaseBytes[i], returnVal[i], databaseBytes[i]);
        }

        assertFalse("Expected at most one row returned", results.next());
    } catch (SQLException sqlE) {
        fail("Got SQLException: " + sqlE.toString());
    } finally {
        if (null != results) {
            try {
                results.close();
            } catch (SQLException sqlE) {
                fail("Got SQLException in resultset.close(): " + sqlE.toString());
            }
        }

        // Free internal resources after the readTable.
        getManager().release();
    }

    // Now verify that we can use the Sqoop import mechanism on this data.
    verifyImport("1," + seqFileVal, checkCols);
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private Object getColumnValue(ResultSet rs, ResultSetMetaData meta, int index, Class clazz) throws Exception {
    Object value = null;//from  w  w  w. ja  v  a 2  s.  c o  m

    int type = meta.getColumnType(index);
    if (clazz == String.class) {
        value = rs.getString(index);
    } else if (clazz == Integer.class) {
        value = rs.getInt(index);
    } else if (clazz == Boolean.class) {
        value = rs.getBoolean(index);
    } else if (clazz == byte[].class) {
        if (type == Types.BLOB)
            value = rs.getBlob(index);
        else
            value = rs.getBytes(index);
    } else if (clazz == Long.class) {
        value = rs.getLong(index);
    } else if (clazz == BigInteger.class) {
        value = rs.getBigDecimal(index);
    } else if (clazz == Float.class) {
        value = rs.getFloat(index);
    } else if (clazz == Double.class) {
        value = rs.getDouble(index);
    } else if (clazz == java.util.Date.class) {
        Timestamp time = rs.getTimestamp(index);
        if (time == null)
            value = null;
        else {
            value = new java.util.Date(time.getTime());
        }
    } else if (clazz == java.sql.Date.class) {
        value = rs.getDate(index);
    } else if (clazz == java.sql.Time.class) {
        value = rs.getTime(index);
    } else if (clazz == java.sql.Timestamp.class) {
        value = rs.getTimestamp(index);
    } else {
        throw new Exception("Cannote determin this column type:" + meta.getColumnName(index));
    }
    return value;
}

From source file:com.sf.ddao.orm.RSMapperFactoryRegistry.java

public static RowMapperFactory getScalarMapper(final Type itemType, final int idx, boolean req) {
    if (itemType == String.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getString(idx);
            }/*from ww  w. j  a va  2  s.  c o m*/
        };
    }
    if (itemType == Integer.class || itemType == Integer.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getInt(idx);
            }
        };
    }
    if (itemType == URL.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getURL(idx);
            }
        };
    }
    if (itemType == BigInteger.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                final BigDecimal res = rs.getBigDecimal(idx);
                return res == null ? null : res.toBigInteger();
            }
        };
    }
    if (itemType == BigDecimal.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBigDecimal(idx);
            }
        };
    }
    if (itemType == InputStream.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBinaryStream(idx);
            }
        };
    }
    if (itemType == Boolean.class || itemType == Boolean.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBoolean(idx);
            }
        };
    }
    if (itemType == Blob.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBlob(idx);
            }
        };
    }
    if (itemType == java.sql.Date.class || itemType == java.util.Date.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getTimestamp(idx);
            }
        };
    }
    if (itemType instanceof Class) {
        final Class itemClass = (Class) itemType;
        final ColumnMapper columnMapper = ColumnMapperRegistry.lookup(itemClass);
        if (columnMapper != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    return columnMapper.map(rs, idx);
                }
            };
        }
        final Converter converter = ConvertUtils.lookup(itemClass);
        if (converter != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(idx);
                    if (s == null) {
                        return null;
                    }
                    return converter.convert(itemClass, s);
                }
            };
        }
        if (Enum.class.isAssignableFrom((Class<?>) itemType)) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(idx);
                    if (s == null) {
                        return null;
                    }
                    //noinspection unchecked
                    return Enum.valueOf((Class<Enum>) itemType, s);
                }
            };
        }
    }
    if (req) {
        throw new IllegalArgumentException("no mapping defined for " + itemType);
    }
    return null;
}

From source file:com.sf.ddao.orm.RSMapperFactoryRegistry.java

public static RowMapperFactory getScalarRowMapperFactory(final Type itemType, final String name, boolean req) {
    if (itemType == String.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getString(name);
            }/*from   w w  w. j  a va2s.  c o m*/
        };
    }
    if (itemType == Integer.class || itemType == Integer.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getInt(name);
            }
        };
    }
    if (itemType == URL.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getURL(name);
            }
        };
    }
    if (itemType == BigInteger.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                final BigDecimal res = rs.getBigDecimal(name);
                return res == null ? null : res.toBigInteger();
            }
        };
    }
    if (itemType == BigDecimal.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBigDecimal(name);
            }
        };
    }
    if (itemType == InputStream.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBinaryStream(name);
            }
        };
    }
    if (itemType == Boolean.class || itemType == Boolean.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBoolean(name);
            }
        };
    }
    if (itemType == Blob.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBlob(name);
            }
        };
    }
    if (itemType == java.sql.Date.class || itemType == java.util.Date.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getTimestamp(name);
            }
        };
    }
    if (itemType instanceof Class) {
        final Class itemClass = (Class) itemType;
        final ColumnMapper columnMapper = ColumnMapperRegistry.lookup(itemClass);
        if (columnMapper != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    return columnMapper.map(rs, name);
                }
            };
        }
        final Converter converter = ConvertUtils.lookup(itemClass);
        if (converter != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(name);
                    if (s == null) {
                        return null;
                    }
                    return converter.convert(itemClass, s);
                }
            };
        }
        if (Enum.class.isAssignableFrom((Class<?>) itemType)) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(name);
                    if (s == null) {
                        return null;
                    }
                    //noinspection unchecked
                    return Enum.valueOf((Class<Enum>) itemType, s);
                }
            };
        }
    }
    if (req) {
        throw new IllegalArgumentException("no mapping defined for " + itemType);
    }
    return null;
}

From source file:org.springframework.jdbc.support.JdbcUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index//from w ww .ja  v a  2s . co m
 * @param requiredType the required value type (may be {@code null})
 * @return the value object (possibly not of the specified required type,
 * with further conversion steps necessary)
 * @throws SQLException if thrown by the JDBC API
 * @see #getResultSetValue(ResultSet, int)
 */
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType)
        throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value;

    // Explicitly extract typed value, as far as possible.
    if (String.class == requiredType) {
        return rs.getString(index);
    } else if (boolean.class == requiredType || Boolean.class == requiredType) {
        value = rs.getBoolean(index);
    } else if (byte.class == requiredType || Byte.class == requiredType) {
        value = rs.getByte(index);
    } else if (short.class == requiredType || Short.class == requiredType) {
        value = rs.getShort(index);
    } else if (int.class == requiredType || Integer.class == requiredType) {
        value = rs.getInt(index);
    } else if (long.class == requiredType || Long.class == requiredType) {
        value = rs.getLong(index);
    } else if (float.class == requiredType || Float.class == requiredType) {
        value = rs.getFloat(index);
    } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) {
        value = rs.getDouble(index);
    } else if (BigDecimal.class == requiredType) {
        return rs.getBigDecimal(index);
    } else if (java.sql.Date.class == requiredType) {
        return rs.getDate(index);
    } else if (java.sql.Time.class == requiredType) {
        return rs.getTime(index);
    } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) {
        return rs.getTimestamp(index);
    } else if (byte[].class == requiredType) {
        return rs.getBytes(index);
    } else if (Blob.class == requiredType) {
        return rs.getBlob(index);
    } else if (Clob.class == requiredType) {
        return rs.getClob(index);
    } else if (requiredType.isEnum()) {
        // Enums can either be represented through a String or an enum index value:
        // leave enum type conversion up to the caller (e.g. a ConversionService)
        // but make sure that we return nothing other than a String or an Integer.
        Object obj = rs.getObject(index);
        if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Number) {
            // Defensively convert any Number to an Integer (as needed by our
            // ConversionService's IntegerToEnumConverterFactory) for use as index
            return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class);
        } else {
            // e.g. on Postgres: getObject returns a PGObject but we need a String
            return rs.getString(index);
        }
    }

    else {
        // Some unknown type desired -> rely on getObject.
        try {
            return rs.getObject(index, requiredType);
        } catch (AbstractMethodError err) {
            logger.debug("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err);
        } catch (SQLFeatureNotSupportedException ex) {
            logger.debug("JDBC driver does not support JDBC 4.1 'getObject(int, Class)' method", ex);
        } catch (SQLException ex) {
            logger.debug("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex);
        }

        // Corresponding SQL types for JSR-310 / Joda-Time types, left up
        // to the caller to convert them (e.g. through a ConversionService).
        String typeName = requiredType.getSimpleName();
        if ("LocalDate".equals(typeName)) {
            return rs.getDate(index);
        } else if ("LocalTime".equals(typeName)) {
            return rs.getTime(index);
        } else if ("LocalDateTime".equals(typeName)) {
            return rs.getTimestamp(index);
        }

        // Fall back to getObject without type specification, again
        // left up to the caller to convert the value if necessary.
        return getResultSetValue(rs, index);
    }

    // Perform was-null check if necessary (for results that the JDBC driver returns as primitives).
    return (rs.wasNull() ? null : value);
}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CsrDAO.java

/**
 * constructs and returns a Csr array from a resultSet
 *
 * @param resultSet result set/*from w w  w.  j a  va  2  s .c o m*/
 * @return array of CsrFiles
 */
private Csr[] getCsrArray(ResultSet resultSet) throws CaException, SQLException, IOException {
    ArrayList<Csr> csrList = new ArrayList<Csr>();
    int count = 0;
    while (resultSet.next()) {
        String serialNo = resultSet.getString(Constants.SERIAL_NO_LABEL);
        String status = resultSet.getString(Constants.CSR_STATUS_LABEL);
        String commonName = resultSet.getString(Constants.CSR_COMMON_NAME_LABEL);
        String organization = resultSet.getString(Constants.CSR_ORGANIZATION_LABEL);
        Csr csrFile;
        String country = null;
        String department = null;
        String city = null;
        String state = null;
        Blob csrBlob = resultSet.getBlob(Constants.CSR_CONTENT_LABEL);
        Date requestedDate = resultSet.getTimestamp(Constants.CSR_REQUESTED_DATE);
        String username = resultSet.getString(Constants.CSR_REQUESTER_USERNAME_LABEL);
        int tenantID = resultSet.getInt(Constants.TENANT_ID_LABEL);
        String userStoreDomain = resultSet.getString(Constants.USER_STORE_DOMAIN_LABEL);
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                csrBlob.getBytes(1, (int) csrBlob.length()));
        HashMap decodedContent = CsrUtils.getSubjectInfo(csr);
        if (decodedContent.containsKey("C")) {
            country = decodedContent.get("C").toString();
        }
        if (decodedContent.containsKey("L")) {
            city = decodedContent.get("L").toString();
        }
        if (decodedContent.containsKey("OU")) {
            department = decodedContent.get("OU").toString();
        }
        if (decodedContent.containsKey("ST")) {
            state = decodedContent.get("ST").toString();
        }
        csrFile = new Csr(commonName, department, organization, city, state, country, csr, serialNo, status,
                username, tenantID, userStoreDomain, requestedDate);
        csrList.add(csrFile);
    }
    Csr[] csrs = new Csr[csrList.size()];
    csrs = csrList.toArray(csrs);
    return csrs;
}

From source file:gobblin.source.extractor.extract.jdbc.JdbcExtractor.java

private String parseColumnAsString(final ResultSet resultset, final ResultSetMetaData resultsetMetadata, int i)
        throws SQLException {

    if (isBlob(resultsetMetadata.getColumnType(i))) {
        return readBlobAsString(resultset.getBlob(i));
    }/*from   ww w.  java2s  .c  om*/
    if ((resultsetMetadata.getColumnType(i) == Types.BIT || resultsetMetadata.getColumnType(i) == Types.BOOLEAN)
            && convertBitToBoolean()) {
        return Boolean.toString(resultset.getBoolean(i));
    }
    return resultset.getString(i);
}

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Get one value into DbValue from ResultSet
 * // w  w w. java2s. c om
 * @param rs
 * @param value
 * @throws WaarpDatabaseSqlException
 */
static public void getTrueValue(ResultSet rs, DbValue value) throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.LONGVARCHAR:
            value.value = rs.getString(value.column);
            break;
        case Types.BIT:
            value.value = rs.getBoolean(value.column);
            break;
        case Types.TINYINT:
            value.value = rs.getByte(value.column);
            break;
        case Types.SMALLINT:
            value.value = rs.getShort(value.column);
            break;
        case Types.INTEGER:
            value.value = rs.getInt(value.column);
            break;
        case Types.BIGINT:
            value.value = rs.getLong(value.column);
            break;
        case Types.REAL:
            value.value = rs.getFloat(value.column);
            break;
        case Types.DOUBLE:
            value.value = rs.getDouble(value.column);
            break;
        case Types.VARBINARY:
            value.value = rs.getBytes(value.column);
            break;
        case Types.DATE:
            value.value = rs.getDate(value.column);
            break;
        case Types.TIMESTAMP:
            value.value = rs.getTimestamp(value.column);
            break;
        case Types.CLOB:
            value.value = rs.getClob(value.column).getCharacterStream();
            break;
        case Types.BLOB:
            value.value = rs.getBlob(value.column).getBinaryStream();
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " for " + value.column);
        }
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Getting values in error: " + value.type + " for " + value.column,
                e);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.ocbrowser.struts.actions.ObjectClassAction.java

/**
 *
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 *
 * @return//from  w w w .j  a  v  a2 s .  co  m
 *
 * @throws IOException
 * @throws ServletException
 */
public ActionForward viewReferenceDocAttchment(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    OutputStream out = null;

    InputStream is = null;
    out = response.getOutputStream();
    String attachmentName = request.getParameter(CaDSRConstants.REFERENCE_DOC_ATTACHMENT_NAME);
    response.addHeader("Content-Disposition", "inline;filename=" + attachmentName);
    response.addHeader("Pragma", "cache");
    response.addHeader("Cache-Control", "private");
    response.addHeader("Expires", "0");

    // first find out if the attachment is new and saved in the session

    Map attMap = (Map) getSessionObject(request, CaDSRConstants.REFDOC_ATTACHMENT_MAP);
    Attachment attachment = getAttachmentFromSession(attMap, attachmentName);

    if (attachment != null) {
        FormFile attFile = (FormFile) attMap.get(attachment);

        is = attFile.getInputStream();
        response.setContentType(attachment.getMimeType());
    } else {
        Blob theBlob = null;

        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            DBUtil dbUtil = new DBUtil();

            //String dsName = CDEBrowserParams.getInstance("cdebrowser").getSbrDSN();
            dbUtil.getOracleConnectionFromContainer();

            String sqlStmt = "SELECT blob_content, mime_type, doc_size from reference_blobs where name = ?";
            log.info(sqlStmt);
            conn = dbUtil.getConnection();
            ps = conn.prepareStatement(sqlStmt);
            ps.setString(1, attachmentName);
            rs = ps.executeQuery();
            boolean exists = false;

            if (rs.next()) {
                exists = true;

                String mimeType = rs.getString(2);
                //    (mimeType);

                response.setContentType(mimeType);
                //theBlob = ((OracleResultSet)rs).getBLOB(1);
                theBlob = rs.getBlob(1);
                is = theBlob.getBinaryStream();
                response.setContentLength(rs.getInt(3));
                response.setBufferSize(4 * 1024);

                //Writing to the OutputStream
                if (is != null) {
                    byte[] buf = new byte[4 * 1024]; // 4K buffer

                    int bytesRead;

                    while ((bytesRead = is.read(buf)) != -1) {
                        out.write(buf, 0, bytesRead);
                    }
                }
                response.setStatus(HttpServletResponse.SC_OK);
            }
        } catch (Exception ex) {
            log.error("Exception Caught in ObjectClassAction.viewReferenceDocAttchment:", ex);
        } finally {
            try {
                if (is != null)
                    is.close();

                if (out != null)
                    out.close();

                try {
                    if (ps != null)
                        ps.close();
                } catch (Exception e) {
                }
                try {
                    if (rs != null)
                        rs.close();
                } catch (Exception e) {
                }
                try {
                    if (conn != null)
                        conn.close();
                } catch (Exception e) {
                }
                //if (db != null) db.closeDB();
            } catch (Exception ex) {
                log.error("Exception Caught in ObjectClassAction during cleaning up :", ex);
            }
        }
    }
    return null;
}