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.wso2.carbon.certificate.mgt.core.dao.impl.AbstractCertificateDAOImpl.java

@Override
public List<CertificateResponse> searchCertificate(String serialNumber)
        throws CertificateManagementDAOException {
    Connection conn;/*  w  w  w.  java2s.co m*/
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    CertificateResponse certificateResponse = null;
    List<CertificateResponse> certificates = new ArrayList<>();
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        conn = this.getConnection();
        String query = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM DM_DEVICE_CERTIFICATE "
                + "WHERE SERIAL_NUMBER LIKE ? AND TENANT_ID = ? ";
        stmt = conn.prepareStatement(query);
        stmt.setString(1, "%" + serialNumber + "%");
        stmt.setInt(2, tenantId);
        resultSet = stmt.executeQuery();

        while (resultSet.next()) {
            certificateResponse = new CertificateResponse();
            byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
            certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
            certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
            certificateResponse.setUsername(resultSet.getString("USERNAME"));
            CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
            certificates.add(certificateResponse);
        }
    } catch (SQLException e) {
        String errorMsg = "Unable to get the read the certificate with serial" + serialNumber;
        log.error(errorMsg, e);
        throw new CertificateManagementDAOException(errorMsg, e);
    } finally {
        CertificateManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return certificates;
}

From source file:org.wso2.carbon.certificate.mgt.core.dao.impl.OracleCertificateDAOImpl.java

@Override
public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet resultSet = null;
    CertificateResponse certificateResponse;
    List<CertificateResponse> certificates = new ArrayList<>();
    PaginationResult paginationResult;/*  ww w  .  j a  v a  2  s .c o  m*/
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    try {
        Connection conn = this.getConnection();
        String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM "
                + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, tenantId);
        stmt.setInt(2, rowNum);
        stmt.setInt(3, limit);
        resultSet = stmt.executeQuery();

        int resultCount = 0;
        while (resultSet.next()) {
            certificateResponse = new CertificateResponse();
            byte[] certificateBytes = resultSet.getBytes("CERTIFICATE");
            certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER"));
            certificateResponse.setTenantId(resultSet.getInt("TENANT_ID"));
            certificateResponse.setUsername(resultSet.getString("USERNAME"));
            CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse);
            certificates.add(certificateResponse);
            resultCount++;
        }
        paginationResult = new PaginationResult();
        paginationResult.setData(certificates);
        paginationResult.setRecordsTotal(resultCount);
    } catch (SQLException e) {
        String errorMsg = "SQL error occurred while retrieving the certificates.";
        log.error(errorMsg, e);
        throw new CertificateManagementDAOException(errorMsg, e);
    } finally {
        CertificateManagementDAOUtil.cleanupResources(stmt, resultSet);
    }
    return paginationResult;
}

From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java

protected Object get(int type, String key) throws PropertyException {
    String sql = "SELECT " + colItemType + ", " + colString + ", " + colDate + ", " + colData + ", " + colFloat
            + ", " + colNumber + " FROM " + tableName + " WHERE " + colItemKey + " = ? AND " + colGlobalKey
            + " = ?";

    Object o = null;//from  ww  w  . ja v a  2 s.  c o  m
    Connection conn = null;

    try {
        conn = ds.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) {
        throw new PropertyException(e.getMessage());
    } catch (NumberFormatException e) {
        throw new PropertyException(e.getMessage());
    } finally {
        closeConnection(conn);
    }

    return o;
}

From source file:it.anyplace.sync.repository.repo.SqlRepository.java

private FileBlocks readFileBlocks(ResultSet resultSet) throws SQLException, InvalidProtocolBufferException {
    IndexSerializationProtos.Blocks blocks = IndexSerializationProtos.Blocks
            .parseFrom(resultSet.getBytes("blocks"));
    List<BlockInfo> blockList = Lists.transform(blocks.getBlocksList(),
            new Function<IndexSerializationProtos.BlockInfo, BlockInfo>() {
                @Override//from w w w  . j  a  v a2  s  .  c  o  m
                public BlockInfo apply(IndexSerializationProtos.BlockInfo record) {
                    return new BlockInfo(record.getOffset(), record.getSize(),
                            BaseEncoding.base16().encode(record.getHash().toByteArray()));
                }
            });
    return new FileBlocks(resultSet.getString("folder"), resultSet.getString("path"), blockList);
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.ProfileOperationDAOImpl.java

@Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status)
        throws OperationManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ProfileOperation profileOperation;//from   w w w.  j a v a 2s.  c  o m

    List<Operation> operationList = new ArrayList<Operation>();

    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;

    try {
        Connection conn = OperationManagementDAOFactory.getConnection();
        String sql = "Select po.OPERATION_ID, ENABLED, OPERATION_DETAILS from DM_PROFILE_OPERATION po "
                + "INNER JOIN  " + "(Select * From DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID=? "
                + "AND STATUS=?) dm ON dm.OPERATION_ID = po.OPERATION_ID";

        stmt = conn.prepareStatement(sql);
        stmt.setInt(1, enrolmentId);
        stmt.setString(2, status.toString());

        rs = stmt.executeQuery();

        while (rs.next()) {
            byte[] operationDetails = rs.getBytes("OPERATION_DETAILS");
            bais = new ByteArrayInputStream(operationDetails);
            ois = new ObjectInputStream(bais);
            profileOperation = (ProfileOperation) ois.readObject();
            profileOperation.setStatus(status);
            operationList.add(profileOperation);
        }

    } catch (IOException e) {
        throw new OperationManagementDAOException(
                "IO Error occurred while de serialize the profile " + "operation object", e);
    } catch (ClassNotFoundException e) {
        throw new OperationManagementDAOException(
                "Class not found error occurred while de serialize the " + "profile operation object", e);
    } catch (SQLException e) {
        throw new OperationManagementDAOException("SQL error occurred while retrieving the operation "
                + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e);
    } 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);
            }
        }
        OperationManagementDAOUtil.cleanupResources(stmt, rs);
    }
    return operationList;
}

From source file:org.sakaiproject.mailarchive.impl.conversion.ExtractXMLToColumns.java

public Object getValidateSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    byte[] rv = null;
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = blob.getBytes(1L, (int) blob.length());
        } else {//from  w  w w  . j a  va 2 s.  c o m
            System.out.println("getValidateSource(" + id + ") blob ==  null");
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length()).getBytes();
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1).getBytes();
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        rv = rs.getBytes(1);
        break;
    }
    // System.out.println("getValidateSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java

/**
 * Processor for dequeue results. Converts a row into a tuple containing fields in the
 * following order: local_id, attempts_allowed, attempts_remaining, updated_at, create_at, body.
 *///from  www. j av  a 2 s. c  o  m
private RowProcessor<Tuple6<String, Integer, Integer, Timestamp, Timestamp, ByteBuffer>> constructDequeueRowProcessor(
        final String queueName, final String shardName, final int priority) {
    return new RowProcessor<Tuple6<String, Integer, Integer, Timestamp, Timestamp, ByteBuffer>>() {
        @Override
        public Tuple6<String, Integer, Integer, Timestamp, Timestamp, ByteBuffer> process(ResultSet rs)
                throws IOException, SQLException {
            return new Tuple6<String, Integer, Integer, Timestamp, Timestamp, ByteBuffer>(
                    new PinLaterJobDescriptor(queueName, shardName, priority, rs.getLong(1)).toString(),
                    rs.getInt(2), rs.getInt(3), rs.getTimestamp(4), rs.getTimestamp(5),
                    ByteBuffer.wrap(rs.getBytes(6)));
        }
    };
}

From source file:biblivre3.administration.ReportsDAO.java

public ReservationReportDto getReservationReportData() {
    ReservationReportDto dto = new ReservationReportDto();
    Connection con = null;// w w w  .  j a v  a  2  s  .co  m
    try {
        con = getDataSource().getConnection();
        Statement st = con.createStatement();
        String sql = " select u.username, u.userid, b.record, "
                + " to_char(r.created, 'DD/MM/YYYY') as created "
                + " from reservation r, users u, cataloging_biblio b " + " where r.userid = u.userid "
                + " and r.record_serial = b.record_serial  " + " and r.record_serial is not null "
                + " order by u.username asc;  ";
        ResultSet rs = st.executeQuery(sql);
        List<String[]> biblioReservations = new ArrayList<String[]>();
        while (rs.next()) {
            String[] reservation = new String[5];
            reservation[0] = rs.getString("username");
            reservation[1] = String.valueOf(rs.getInt("userid"));
            String iso2709 = new String(rs.getBytes("record"), "UTF-8");
            Record record = MarcUtils.iso2709ToRecord(iso2709);
            reservation[2] = Indexer.listOneTitle(record);
            reservation[3] = Indexer.listPrimaryAuthor(record);
            reservation[4] = rs.getString("created");
            biblioReservations.add(reservation);
        }
        dto.setBiblioReservations(biblioReservations);

        //            String sql2 =
        //                    " select u.username, u.userid, b.record, "
        //                    + " to_char(r.created, 'DD/MM/YYYY') as created "
        //                    + " from reservation r, users u, cataloging_holdings h, cataloging_biblio b "
        //                    + " where r.userid = u.userid "
        //                    + " and r.holding_serial = h.holding_serial "
        //                    + " and h.record_serial = b.record_serial "
        //                    + " and r.holding_serial is not null "
        //                    + " and h.database = '0' order by u.username asc; ";
        //            rs = st.executeQuery(sql2);
        //            List<String[]> holdingReservations = new ArrayList<String[]>();
        //            while (rs.next()) {
        //                String[] reservation = new String[5];
        //                reservation[0] = rs.getString("username");
        //                reservation[1] = String.valueOf(rs.getInt("userid"));
        //                String iso2709 = new String(rs.getBytes("record"), "UTF-8");
        //                Record record = MarcUtils.iso2709ToRecord(iso2709);
        //                reservation[2] = Indexer.listTitle(record);
        //                reservation[3] = Indexer.listPrimaryAuthor(record);
        //                reservation[4] = rs.getString("created");
        //                holdingReservations.add(reservation);
        //            }
        //            dto.setHoldingReservations(holdingReservations);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ExceptionUser("ERROR_REPORT_DAO_EXCEPTION");
    } finally {
        closeConnection(con);
    }
    return dto;
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.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  .j  a  v  a 2  s .com
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = Byte.valueOf(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = Short.valueOf(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = Integer.valueOf(rs.getInt(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = Long.valueOf(rs.getLong(index));
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = Float.valueOf(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = Double.valueOf(rs.getDouble(index));
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = rs.getBytes(index);
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = rs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = rs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
        value = rs.getTimestamp(index);
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

From source file:org.parosproxy.paros.db.paros.ParosTableHistory.java

private RecordHistory build(ResultSet rs) throws HttpMalformedHeaderException, SQLException {
    RecordHistory history = null;//from w  w  w . j av  a  2 s .  co  m
    try {
        if (rs.next()) {
            byte[] reqBody;
            byte[] resBody;

            if (bodiesAsBytes) {
                reqBody = rs.getBytes(REQBODY);
                resBody = rs.getBytes(RESBODY);
            } else {
                reqBody = rs.getString(REQBODY).getBytes();
                resBody = rs.getString(RESBODY).getBytes();
            }

            history = new RecordHistory(rs.getInt(HISTORYID), rs.getInt(HISTTYPE), rs.getLong(SESSIONID),
                    rs.getLong(TIMESENTMILLIS), rs.getInt(TIMEELAPSEDMILLIS), rs.getString(REQHEADER), reqBody,
                    rs.getString(RESHEADER), resBody, rs.getString(TAG), rs.getString(NOTE), // ZAP: Added note
                    rs.getBoolean(RESPONSE_FROM_TARGET_HOST));
        }
    } finally {
        rs.close();
    }
    return history;

}