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.sakaiproject.util.BaseDbDualSingleStorage.java

/**
 * Get a lock on the Resource with this id, or null if a lock cannot be
 * gotten./*from   www.j  av  a  2 s.  c o m*/
 * 
 * @param id
 *        The user id.
 * @return The locked Resource with this id, or null if this records cannot
 *         be locked.
 */
public Edit editResource(String id) {
    Edit edit = null;

    if (m_locksAreInDb) {
        if ("oracle".equals(m_sql.getVendor())) {
            final List<Entity> l = new ArrayList<Entity>();
            Connection lock = null;
            if (m_user instanceof EntityReaderHandler) {
                // read the record and get a lock on it (non blocking)
                String statement = "select XML from " + m_resourceTableName + " where ( "
                        + m_resourceTableIdField + " = '" + StorageUtils.escapeSql(caseId(id)) + "' )"
                        + " for update nowait";
                lock = m_sql.dbReadLock(statement, new SqlReader() {

                    public Object readSqlResultRecord(ResultSet result) {
                        try {
                            l.add(readResource(result.getString(1), result.getBytes(2)));
                        } catch (SQLException e) {
                            M_log.warn("Failed to retrieve record ", e);
                        }
                        return null;
                    }

                });
            } else {
                // read the record and get a lock on it (non blocking)
                String statement = "select BENTRY, XML from " + m_resourceTableName + " where ( "
                        + m_resourceTableIdField + " = '" + StorageUtils.escapeSql(caseId(id)) + "' )"
                        + " for update nowait";
                lock = m_sql.dbReadLock(statement, new SqlReader() {

                    public Object readSqlResultRecord(ResultSet result) {

                        try {
                            l.add(readResource(result.getString(1), result.getBytes(2)));
                        } catch (SQLException e) {
                            M_log.warn("Failed to retrieve record ", e);
                        }
                        return null;
                    }

                });

            }

            // for missing or already locked...
            if ((lock == null) || (l.size() == 0))
                return null;

            // make first a Resource, then an Edit
            Entity entry = l.get(0);
            edit = m_user.newResourceEdit(null, entry);

            // store the lock for this object
            m_locks.put(entry.getReference(), lock);
        } else {
            throw new UnsupportedOperationException(
                    "Record locking only available when configured with Oracle database");
        }
    }

    // if the locks are in a separate table in the db
    else if (m_locksAreInTable) {
        // read the record - fail if not there
        Entity entry = getResource(id);
        if (entry == null)
            return null;

        // write a lock to the lock table - if we can do it, we get the lock
        String statement = singleStorageSql.getInsertLocks();

        // we need session id and user id
        String sessionId = UsageSessionService.getSessionId();
        if (sessionId == null) {
            sessionId = "";
        }

        // collect the fields
        Object fields[] = new Object[4];
        fields[0] = m_resourceTableName;
        fields[1] = internalRecordId(caseId(id));
        fields[2] = TimeService.newTime();
        fields[3] = sessionId;

        // add the lock - if fails, someone else has the lock
        boolean ok = m_sql.dbWriteFailQuiet(null, statement, fields);
        if (!ok) {
            return null;
        }

        // we got the lock! - make the edit from the Resource
        edit = m_user.newResourceEdit(null, entry);
    }

    // otherwise, get the lock locally
    else {
        // get the entry, and check for existence
        Entity entry = getResource(id);
        if (entry == null)
            return null;

        // we only sync this getting - someone may release a lock out of
        // sync
        synchronized (m_locks) {
            // if already locked
            if (m_locks.containsKey(entry.getReference()))
                return null;

            // make the edit from the Resource
            edit = m_user.newResourceEdit(null, entry);

            // store the edit in the locks by reference
            m_locks.put(entry.getReference(), edit);
        }
    }

    return edit;
}

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;/*from   w  w  w. j  a v a 2  s  . co m*/
    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:org.wso2.carbon.device.mgt.core.archival.dao.impl.ArchivalDAOImpl.java

@Override
public void moveOperationResponses() throws ArchivalDAOException {
    Statement stmt = null;/* www .  j av a  2  s . com*/
    PreparedStatement stmt2 = null;
    Statement stmt3 = null;
    ResultSet rs = null;
    try {
        Connection conn = ArchivalSourceDAOFactory.getConnection();
        String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN "
                + "(SELECT ID FROM DM_ARCHIVED_OPERATIONS)";
        stmt = this.createMemoryEfficientStatement(conn);
        rs = stmt.executeQuery(sql);

        Connection conn2 = ArchivalDestinationDAOFactory.getConnection();
        sql = "INSERT INTO DM_DEVICE_OPERATION_RESPONSE_ARCH VALUES(?, ?, ?, ?, ?,?,?)";
        stmt2 = conn2.prepareStatement(sql);

        int count = 0;
        while (rs.next()) {
            stmt2.setInt(1, rs.getInt("ID"));
            stmt2.setInt(2, rs.getInt("ENROLMENT_ID"));
            stmt2.setInt(3, rs.getInt("OPERATION_ID"));
            stmt2.setInt(4, rs.getInt("EN_OP_MAP_ID"));
            stmt2.setBytes(5, rs.getBytes("OPERATION_RESPONSE"));
            stmt2.setTimestamp(6, rs.getTimestamp("RECEIVED_TIMESTAMP"));
            stmt2.setTimestamp(7, this.currentTimestamp);
            stmt2.addBatch();

            if (++count % batchSize == 0) {
                stmt2.executeBatch();
                if (log.isDebugEnabled()) {
                    log.debug("Executing batch " + count);
                }
            }
        }
        stmt2.executeBatch();
        if (log.isDebugEnabled()) {
            log.debug(count + " [OPERATION_RESPONSES] Records copied to the archival table. Starting deletion");
        }
        //try the deletion now
        sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN ("
                + " SELECT ID FROM DM_ARCHIVED_OPERATIONS)";
        stmt3 = conn.createStatement();
        int affected = stmt3.executeUpdate(sql);
        if (log.isDebugEnabled()) {
            log.debug(affected + " Rows deleted");
        }
    } catch (SQLException e) {
        throw new ArchivalDAOException("Error occurred while moving operations ", e);
    } finally {
        ArchivalDAOUtil.cleanupResources(stmt, rs);
        ArchivalDAOUtil.cleanupResources(stmt2);
        ArchivalDAOUtil.cleanupResources(stmt3);
    }
}

From source file:com.chiorichan.database.DatabaseEngine.java

public static Map<String, Object> convertRow(ResultSet rs) throws SQLException {
    Map<String, Object> result = Maps.newLinkedHashMap();
    ResultSetMetaData rsmd = rs.getMetaData();

    int numColumns = rsmd.getColumnCount();

    for (int i = 1; i < numColumns + 1; i++) {
        String columnName = rsmd.getColumnName(i);

        // Loader.getLogger().info( "Column: " + columnName + " <-> " + rsmd.getColumnTypeName( i ) );

        if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
            result.put(columnName, rs.getArray(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) // Sometimes tinyints are read as bits
        {//  w  w  w  .ja v  a2  s.c o  m
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
            result.put(columnName, rs.getBoolean(columnName));
        } else if (rsmd.getColumnTypeName(i).contains("BLOB")
                || rsmd.getColumnType(i) == java.sql.Types.BINARY) {
            // BLOG = Max Length 65,535. Recommended that you use a LONGBLOG.
            byte[] bytes = rs.getBytes(columnName);
            result.put(columnName, bytes);
            /*
             * try
             * {
             * result.put( columnName, new String( bytes, "ISO-8859-1" ) );
             * }
             * catch ( UnsupportedEncodingException e )
             * {
             * e.printStackTrace();
             * }
             */
        } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
            result.put(columnName, rs.getDouble(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
            result.put(columnName, rs.getFloat(columnName));
        } else if (rsmd.getColumnTypeName(i).equals("INT")) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
            result.put(columnName, rs.getNString(columnName));
        } else if (rsmd.getColumnTypeName(i).equals("VARCHAR")) {
            result.put(columnName, rs.getString(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
            result.put(columnName, rs.getDate(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
            result.put(columnName, rs.getTimestamp(columnName));
        } else {
            result.put(columnName, rs.getObject(columnName));
        }
    }

    return result;
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.AbstractFeatureDAO.java

@Override
public List<ProfileFeature> getFeaturesForProfile(int profileId) throws FeatureManagerDAOException {
    Connection conn;//from w w  w .ja  va 2s. c  o m
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    List<ProfileFeature> featureList = new ArrayList<ProfileFeature>();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "SELECT ID, FEATURE_CODE, DEVICE_TYPE, CONTENT FROM DM_PROFILE_FEATURES "
                + "WHERE PROFILE_ID = ? AND TENANT_ID = ?";
        stmt = conn.prepareStatement(query);
        stmt.setInt(1, profileId);
        stmt.setInt(2, tenantId);
        resultSet = stmt.executeQuery();

        while (resultSet.next()) {
            ProfileFeature profileFeature = new ProfileFeature();
            profileFeature.setId(resultSet.getInt("ID"));
            profileFeature.setFeatureCode(resultSet.getString("FEATURE_CODE"));
            profileFeature.setDeviceType(resultSet.getString("DEVICE_TYPE"));

            ByteArrayInputStream bais = null;
            ObjectInputStream ois = null;
            byte[] contentBytes;
            try {
                contentBytes = resultSet.getBytes("CONTENT");
                bais = new ByteArrayInputStream(contentBytes);
                ois = new ObjectInputStream(bais);
                profileFeature.setContent(ois.readObject().toString());
            } 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);
                    }
                }
            }
            featureList.add(profileFeature);
        }
    } catch (SQLException e) {
        throw new FeatureManagerDAOException("Unable to get the list of the features from database.", e);
    } catch (IOException e) {
        throw new FeatureManagerDAOException("Unable to read the byte stream for content", e);
    } catch (ClassNotFoundException e) {
        throw new FeatureManagerDAOException("Class not found while converting the object", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return featureList;
}

From source file:net.antidot.semantic.rdf.rdb2rdf.dm.core.DirectMappingEngineWD20110324.java

private Row extractRow(DriverType driver, StdHeader header, String tableName, ResultSet valueSet,
        String timeZone, int index) throws UnsupportedEncodingException {
    TreeMap<String, byte[]> values = new TreeMap<String, byte[]>();
    for (String columnName : header.getColumnNames()) {
        try {/*from w  ww  . j  a v a2 s  .  c o m*/
            byte[] value = null;
            SQLSpecificType type = SQLSpecificType.toSQLType(header.getDatatypes().get(columnName));

            if ((driver != null) && driver.equals("com.mysql.jdbc.Driver") && type.isDateType()) {
                // Particular treatment for MySQL dates
                extractMySQLDate(columnName, valueSet, tableName, type, timeZone, values);
            } else {
                value = valueSet.getBytes(columnName);
                values.put(columnName, value);
            }
        } catch (SQLException e) {
            log.error("[TupleExtractor:extractRow] SQL Error during row extraction");
            e.printStackTrace();
        }
    }
    Row row = new Row(values, null, index);
    return row;
}

From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java

protected Object get(int type, String key) throws PropertyException {
    if (enableCache && valueMap == null && !allKeysCached) {
        //logger.info("Caching...");
        this.getKeys();
    }/*from  ww w .j  a va2s .c  om*/

    if (enableCache && valueMap != null) {
        synchronized (valueMap) {
            Object value = valueMap.get(key);
            if (value == null && !allKeysCached) {
                //if(key.indexOf("error") > -1)
                //   logger.info("Should not return... should get value");
            } else {
                if (value != null && !(value instanceof NullObject))
                    return value;
                else if (value instanceof NullObject)
                    return null;
                else if (allKeysCached)
                    return null;
            }
        }
    }

    if (logger.isInfoEnabled())
        logger.info("Getting value for key:" + key + ":" + type);

    String sql = "SELECT " + colItemType + ", " + colString + ", " + colDate + ", " + colData + ", " + colFloat
            + ", " + colNumber + " FROM " + tableName + " WHERE " + colItemKey + " = ? AND " + colGlobalKey
            + " = ?";

    Object o = null;
    Connection conn = null;

    try {
        conn = getConnection();

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, key);
        ps.setString(2, globalKey);

        int propertyType;
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            propertyType = rs.getInt(colItemType);

            if (propertyType != type) {
                throw new InvalidPropertyTypeException();
            }

            switch (type) {
            case PropertySet.BOOLEAN:

                int boolVal = rs.getInt(colNumber);
                o = new Boolean(boolVal == 1);

                break;

            case PropertySet.DATA:
                o = rs.getBytes(colData);

                break;

            case PropertySet.DATE:
                o = rs.getTimestamp(colDate);

                break;

            case PropertySet.DOUBLE:
                o = new Double(rs.getDouble(colFloat));

                break;

            case PropertySet.INT:
                o = new Integer(rs.getInt(colNumber));

                break;

            case PropertySet.LONG:
                o = new Long(rs.getLong(colNumber));

                break;

            case PropertySet.STRING:
                o = rs.getString(colString);

                break;

            default:
                throw new InvalidPropertyTypeException("JDBCPropertySet doesn't support this type yet.");
            }
        }

        rs.close();
        ps.close();
    } catch (SQLException e) {
        logger.error("Problem getting property from database:" + e.getMessage());
        throw new PropertyException(e.getMessage());
    } catch (NumberFormatException e) {
        logger.error("Problem getting property from database:" + e.getMessage());
        throw new PropertyException(e.getMessage());
    } finally {
        closeConnection(conn);
    }

    if (valueMap == null)
        valueMap = new HashMap();

    synchronized (valueMap) {
        if (o != null)
            valueMap.put(key, o);
        else
            valueMap.put(key, new NullObject());
    }

    return o;
}

From source file:org.sakaiproject.util.BaseDbDualSingleStorage.java

/**
 * Get selected Resources, filtered by a test on the id field
 * //from   w w w . j  av  a2  s. c om
 * @param filter
 *        A filter to select what gets returned.
 * @return The list of selected Resources.
 */
public List getSelectedResources(final Filter filter) {
    List all = new Vector();
    // read all users from the db
    String sql = singleStorageSql.getXmlAndFieldSql(m_resourceTableIdField, m_resourceTableName);
    // %%% + "order by " + m_resourceTableOrderField + " asc";

    List xml = m_sql.dbRead(sql, null, new SqlReader() {
        public Object readSqlResultRecord(ResultSet result) {
            try {
                // read the id m_resourceTableIdField
                String id = result.getString(1);

                // read the xml
                String xml = result.getString(2);
                byte[] blob = result.getBytes(3);

                if (!filter.accept(caseId(id)))
                    return null;

                return readResource(xml, blob);
            } catch (SQLException ignore) {
                return null;
            }
        }
    });
    // process all result xml into user objects
    if (!xml.isEmpty()) {
        for (int i = 0; i < xml.size(); i++) {
            Entity entry = (Entity) xml.get(i);
            if (entry != null)
                all.add(entry);
        }
    }

    return all;
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.AbstractFeatureDAO.java

@Override
public List<ProfileFeature> getAllProfileFeatures() throws FeatureManagerDAOException {
    Connection conn;//from w w  w . ja  v  a2 s.  c o m
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    List<ProfileFeature> featureList = new ArrayList<ProfileFeature>();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "SELECT ID, PROFILE_ID, FEATURE_CODE, DEVICE_TYPE, CONTENT FROM DM_PROFILE_FEATURES "
                + "WHERE TENANT_ID = ?";
        stmt = conn.prepareStatement(query);
        stmt.setInt(1, tenantId);
        resultSet = stmt.executeQuery();

        while (resultSet.next()) {

            ProfileFeature profileFeature = new ProfileFeature();
            profileFeature.setFeatureCode(resultSet.getString("FEATURE_CODE"));
            profileFeature.setDeviceType(resultSet.getString("DEVICE_TYPE"));
            profileFeature.setId(resultSet.getInt("ID"));
            profileFeature.setProfileId(resultSet.getInt("PROFILE_ID"));

            ByteArrayInputStream bais = null;
            ObjectInputStream ois = null;
            byte[] contentBytes;
            try {
                contentBytes = (byte[]) resultSet.getBytes("CONTENT");
                bais = new ByteArrayInputStream(contentBytes);
                ois = new ObjectInputStream(bais);
                profileFeature.setContent((Object) ois.readObject().toString());
            } 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);
                    }
                }
            }

            featureList.add(profileFeature);
        }
    } catch (SQLException e) {
        throw new FeatureManagerDAOException("Unable to get the list of the features from database.", e);
    } catch (IOException e) {
        throw new FeatureManagerDAOException("Unable to read the byte stream for content", e);
    } catch (ClassNotFoundException e) {
        throw new FeatureManagerDAOException("Class not found while converting the object", e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return featureList;
}

From source file:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java

protected static <T> T getResultSetValue(ResultSet rs, int index, Class<T> javaType) throws SQLException {
    Object value;/*ww w .j  a v  a  2s  .c o  m*/
    if (javaType == String.class) {
        value = rs.getString(index);
    } else if (javaType == NuclosPassword.class) {
        value = new NuclosPassword(ServerCryptUtil.decrypt(rs.getString(index)));
    } else if (javaType == Double.class) {
        value = rs.getDouble(index);
    } else if (javaType == Long.class) {
        value = rs.getLong(index);
    } else if (javaType == Integer.class) {
        value = rs.getInt(index);
    } else if (javaType == Boolean.class) {
        value = rs.getBoolean(index);
    } else if (javaType == BigDecimal.class) {
        value = rs.getBigDecimal(index);
    } else if (javaType == java.util.Date.class || javaType == java.sql.Date.class) {
        value = rs.getDate(index);
    } else if (javaType == InternalTimestamp.class) {
        value = InternalTimestamp.toInternalTimestamp(rs.getTimestamp(index));
    } else if (javaType == NuclosDateTime.class) {
        value = NuclosDateTime.toNuclosDateTime(rs.getTimestamp(index));
    } else if (javaType == byte[].class) {
        value = rs.getBytes(index);
    } else if (javaType == Object.class) {
        value = rs.getObject(index);
    } else if (javaType == NuclosScript.class) {
        String xml = rs.getString(index);
        if (StringUtils.isNullOrEmpty(xml)) {
            value = null;
        } else {
            final XStreamSupport xs = XStreamSupport.getInstance();
            final XStream xstream = xs.getXStream();
            try {
                value = xstream.fromXML(rs.getString(index));
            } finally {
                xs.returnXStream(xstream);
            }
        }
    } else {
        throw new IllegalArgumentException("Class " + javaType + " not supported by readField");
    }
    return rs.wasNull() ? null : javaType.cast(value);
}