Example usage for java.sql PreparedStatement setBytes

List of usage examples for java.sql PreparedStatement setBytes

Introduction

In this page you can find the example usage for java.sql PreparedStatement setBytes.

Prototype

void setBytes(int parameterIndex, byte x[]) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java array of bytes.

Usage

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void removeXid(ConnectionWrapper connWrapper, long format, byte[] globalId, byte[] branchId)
        throws AMQStoreException {
    Connection conn = connWrapper.getConnection();

    try {//from  w  w  w.ja v  a 2 s . c  om
        PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_XIDS);
        try {
            stmt.setLong(1, format);
            stmt.setBytes(2, globalId);
            stmt.setBytes(3, branchId);
            int results = stmt.executeUpdate();

            if (results != 1) {
                throw new AMQStoreException("Unable to find message with xid");
            }
        } finally {
            stmt.close();
        }

        stmt = conn.prepareStatement(DELETE_FROM_XID_ACTIONS);
        try {
            stmt.setLong(1, format);
            stmt.setBytes(2, globalId);
            stmt.setBytes(3, branchId);
            int results = stmt.executeUpdate();

        } finally {
            stmt.close();
        }

    } catch (SQLException e) {
        _logger.error("Failed to dequeue: " + e.getMessage(), e);
        throw new AMQStoreException("Error deleting enqueued message with xid", e);
    }

}

From source file:com.predic8.membrane.core.interceptor.statistics.util.JDBCUtil.java

public static void setData(AbstractExchange exc, PreparedStatement prepSt, boolean idGenerated, int flag,
        String tId, String[] gatewayHCIDs) throws SQLException {
    int startIndex = 0;
    if (!idGenerated) {
        UUID id = UUID.randomUUID();
        prepSt.setLong(++startIndex, id.getLeastSignificantBits());
    }/*from  w w w  .ja  v  a 2 s.  co m*/
    boolean isReq = (exc.getResponse() == null);

    log.info("Handling interceptor id is: " + tId);
    log.info((isReq) ? "logging for request" : "logging for response");

    prepSt.setInt(++startIndex, (isReq) ? 200 : exc.getResponse().getStatusCode());
    prepSt.setString(++startIndex, (flag == 0) ? "REQUEST" : "RESPONSE");
    prepSt.setTimestamp(++startIndex, new Timestamp(ExchangesUtil.getDate(exc).getTime()));//skb
    prepSt.setString(++startIndex, exc.getRule().toString());
    prepSt.setString(++startIndex, exc.getRequest().getMethod());
    prepSt.setString(++startIndex, exc.getRequest().getUri());
    prepSt.setString(++startIndex,
            (gatewayHCIDs != null && !"".equals(gatewayHCIDs[2])) ? gatewayHCIDs[2] : exc.getSourceHostname());
    prepSt.setString(++startIndex,
            (gatewayHCIDs != null && !"".equals(gatewayHCIDs[3])) ? gatewayHCIDs[3] : exc.getServer());

    if (gatewayHCIDs != null) {
        prepSt.setString(++startIndex, gatewayHCIDs[0]);
        prepSt.setString(++startIndex, gatewayHCIDs[1]);
    } else {
        prepSt.setString(++startIndex, exc.getSourceHostname());
        prepSt.setString(++startIndex, exc.getServer());
    }

    prepSt.setString(++startIndex, (isReq) ? exc.getRequestContentType() : exc.getResponseContentType());
    prepSt.setInt(++startIndex, (isReq) ? exc.getRequestContentLength() : exc.getResponseContentLength());
    /*
    prepSt.setString(++ startIndex, (isReq)?null:exc.getResponseContentType());
    prepSt.setInt(++ startIndex, (isReq)?null:exc.getResponseContentLength());
    */
    prepSt.setLong(++startIndex, (isReq) ? 0 : (exc.getTimeResReceived() - exc.getTimeReqSent()));

    prepSt.setString(++startIndex, (String) getExProperty(exc, FileExchangeStore.MESSAGE_FILE_PATH));

    /* skb */
    String[] colList = { JDBCUtil.MSG_HEADER, JDBCUtil.MSG };

    if (isReq) {
        for (String col : colList) {
            log.info("processing col:" + col);

            ++startIndex;
            try {
                byte[] os = (byte[]) getExProperty(exc, col);
                if (os != null) {
                    prepSt.setBytes(startIndex, os);
                } else
                    prepSt.setBytes(startIndex, null);

            } catch (Exception ex) {
                prepSt.setBytes(startIndex, null);
            }
        }
    } else {

        for (String col : colList) {
            log.info("processing col:" + col);

            ++startIndex;
            try {
                byte[] os = null;
                if (col.equals(JDBCUtil.MSG)) {
                    try {
                        os = IOUtils.toByteArray((exc.getResponse().getBodyAsStream()));
                    } catch (Exception ex) {
                        log.info(ex.toString());
                    }
                } else if (col.equals(JDBCUtil.MSG_HEADER)) {
                    Message msg2 = exc.getResponse();

                    ByteArrayOutputStream header2 = new ByteArrayOutputStream();

                    msg2.writeStartLine(header2);
                    msg2.getHeader().write(header2);
                    header2.write((Constants.CRLF).getBytes());

                    os = header2.toByteArray();
                }
                if (os != null) {
                    prepSt.setBytes(startIndex, os);
                } else
                    prepSt.setBytes(startIndex, null);

            } catch (Exception ex) {
                prepSt.setBytes(startIndex, null);
            }
        }

    }

}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void recordXid(ConnectionWrapper connWrapper, long format, byte[] globalId, byte[] branchId,
        Transaction.Record[] enqueues, Transaction.Record[] dequeues) throws AMQStoreException {
    Connection conn = connWrapper.getConnection();

    try {/*from w ww .  j a  va 2  s  .c  o m*/

        PreparedStatement stmt = conn.prepareStatement(INSERT_INTO_XIDS);
        try {
            stmt.setLong(1, format);
            stmt.setBytes(2, globalId);
            stmt.setBytes(3, branchId);
            stmt.executeUpdate();
        } finally {
            stmt.close();
        }

        stmt = conn.prepareStatement(INSERT_INTO_XID_ACTIONS);

        try {
            stmt.setLong(1, format);
            stmt.setBytes(2, globalId);
            stmt.setBytes(3, branchId);

            if (enqueues != null) {
                stmt.setString(4, "E");
                for (Transaction.Record record : enqueues) {
                    stmt.setString(5, record.getQueue().getId().toString());
                    stmt.setLong(6, record.getMessage().getMessageNumber());
                    stmt.executeUpdate();
                }
            }

            if (dequeues != null) {
                stmt.setString(4, "D");
                for (Transaction.Record record : dequeues) {
                    stmt.setString(5, record.getQueue().getId().toString());
                    stmt.setLong(6, record.getMessage().getMessageNumber());
                    stmt.executeUpdate();
                }
            }

        } finally {
            stmt.close();
        }

    } catch (SQLException e) {
        _logger.error("Failed to enqueue: " + e.getMessage(), e);
        throw new AMQStoreException("Error writing xid ", e);
    }

}

From source file:com.runwaysdk.dataaccess.database.general.MySQL.java

/**
 * Truncates a blob by the specified length.
 * //from   w  ww  . j  a v  a 2s .c  om
 * @param table
 * @param columnName
 * @param id
 * @param length
 */
public void truncateBlob(String table, String columnName, String id, long length, Connection conn) {
    Statement statement = null;
    ResultSet resultSet = null;
    try {
        // get the blob
        statement = conn.createStatement();
        String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "'";
        String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN
                + " = '" + id + "'";
        resultSet = statement.executeQuery(select);
        resultSet.next();
        byte[] resultBytes = resultSet.getBytes(columnName);

        // truncate the bytes
        byte[] temp = new byte[(int) length];
        for (int i = 0; i < length; i++) {
            temp[i] = resultBytes[i];
        }

        // save the truncated blob
        PreparedStatement prepared = conn.prepareStatement(update);
        prepared.setBytes(1, temp);
        prepared.executeUpdate();
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
}

From source file:org.jbpm.bpel.persistence.db.type.ElementType.java

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    // easy way out: null value
    if (value == null) {
        st.setNull(index, SQL_TYPES[0]);
        if (log.isTraceEnabled())
            log.trace("binding null to parameter: " + index);
    } else {/*from   www.j a v  a  2s  .  co  m*/
        Element element = (Element) value;
        try {
            // create identity transformer
            Transformer idTransformer = XmlUtil.getTransformerFactory().newTransformer();

            // allocate memory result stream
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

            // deflate if requested
            Integer deflateLevel = getXmlDeflateLevel();
            if (deflateLevel != null) {
                // introduce deflater stream
                Deflater deflater = new Deflater(deflateLevel.intValue());
                OutputStream deflaterStream = new DeflaterOutputStream(byteStream, deflater);
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(deflaterStream));
                // release resources
                try {
                    deflaterStream.close();
                } catch (IOException e) {
                    // should not happen
                    throw new AssertionError(e);
                }
                deflater.end();
            } else {
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(byteStream));
                // noop
                // byteStream.close();
            }

            // extract contents of result stream
            st.setBytes(index, byteStream.toByteArray());
            if (log.isTraceEnabled())
                log.trace("binding '" + byteStream + "' to parameter: " + index);
        } catch (TransformerException e) {
            throw new HibernateException("could not transform to xml stream: " + element, e);
        }
    }
}

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

public void updateIaAddr(final IaAddress iaAddr) {
    getJdbcTemplate().update("update dhcplease" + " set state = ?,"
            + ((iaAddr instanceof IaPrefix) ? " prefixlen = ?," : "") + " starttime = ?,"
            + " preferredendtime = ?," + " validendtime = ?" + " where ipaddress = ?",
            new PreparedStatementSetter() {
                @Override//ww w.j  a  v  a 2  s.c om
                public void setValues(PreparedStatement ps) throws SQLException {
                    int i = 1;
                    ps.setByte(i++, iaAddr.getState());
                    if (iaAddr instanceof IaPrefix) {
                        ps.setShort(i++, ((IaPrefix) iaAddr).getPrefixLength());
                    }
                    Date start = iaAddr.getStartTime();
                    if (start != null) {
                        java.sql.Timestamp sts = new java.sql.Timestamp(start.getTime());
                        ps.setTimestamp(i++, sts, Util.GMT_CALENDAR);
                    } else {
                        ps.setNull(i++, java.sql.Types.TIMESTAMP);
                    }
                    Date preferred = iaAddr.getPreferredEndTime();
                    if (preferred != null) {
                        java.sql.Timestamp pts = new java.sql.Timestamp(preferred.getTime());
                        ps.setTimestamp(i++, pts, Util.GMT_CALENDAR);
                    } else {
                        ps.setNull(i++, java.sql.Types.TIMESTAMP);
                    }
                    Date valid = iaAddr.getValidEndTime();
                    if (valid != null) {
                        java.sql.Timestamp vts = new java.sql.Timestamp(valid.getTime());
                        ps.setTimestamp(i++, vts, Util.GMT_CALENDAR);
                    } else {
                        ps.setNull(i++, java.sql.Types.TIMESTAMP);
                    }
                    ps.setBytes(i++, iaAddr.getIpAddress().getAddress());
                }
            });
}

From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java

private void recoverXids(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler dtxrh) throws SQLException {
    Connection conn = newAutoCommitConnection();
    try {//from ww w. jav  a2  s  . c  o m
        List<Xid> xids = new ArrayList<Xid>();

        Statement stmt = conn.createStatement();
        try {
            ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_XIDS);
            try {
                while (rs.next()) {

                    long format = rs.getLong(1);
                    byte[] globalId = rs.getBytes(2);
                    byte[] branchId = rs.getBytes(3);
                    xids.add(new Xid(format, globalId, branchId));
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }

        for (Xid xid : xids) {
            List<RecordImpl> enqueues = new ArrayList<RecordImpl>();
            List<RecordImpl> dequeues = new ArrayList<RecordImpl>();

            PreparedStatement pstmt = conn.prepareStatement(SELECT_ALL_FROM_XID_ACTIONS);

            try {
                pstmt.setLong(1, xid.getFormat());
                pstmt.setBytes(2, xid.getGlobalId());
                pstmt.setBytes(3, xid.getBranchId());

                ResultSet rs = pstmt.executeQuery();
                try {
                    while (rs.next()) {

                        String actionType = rs.getString(1);
                        UUID queueId = UUID.fromString(rs.getString(2));
                        long messageId = rs.getLong(3);

                        RecordImpl record = new RecordImpl(queueId, messageId);
                        List<RecordImpl> records = "E".equals(actionType) ? enqueues : dequeues;
                        records.add(record);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                pstmt.close();
            }

            dtxrh.dtxRecord(xid.getFormat(), xid.getGlobalId(), xid.getBranchId(),
                    enqueues.toArray(new RecordImpl[enqueues.size()]),
                    dequeues.toArray(new RecordImpl[dequeues.size()]));
        }

        dtxrh.completeDtxRecordRecovery();
    } finally {
        conn.close();
    }

}

From source file:cz.lbenda.dataman.db.RowDesc.java

@SuppressWarnings("ConstantConditions")
private <T> void putToPS(ColumnDesc columnDesc, T value, PreparedStatement ps, int position)
        throws SQLException {
    if (value == null) {
        ps.setObject(position, null);/*from  w w  w.j a v a 2 s . c o  m*/
        return;
    }
    BinaryData bd = value instanceof BinaryData ? (BinaryData) value : null;
    switch (columnDesc.getDataType()) {
    case STRING:
        ps.setString(position, (String) value);
        break;
    case BOOLEAN:
        ps.setBoolean(position, (Boolean) value);
        break;
    case TIMESTAMP:
        ps.setTimestamp(position, (Timestamp) value);
        break;
    case DATE:
        ps.setDate(position, (Date) value);
        break;
    case TIME:
        ps.setTime(position, (Time) value);
        break;
    case BYTE:
        ps.setByte(position, (Byte) value);
        break;
    case SHORT:
        ps.setShort(position, (Short) value);
        break;
    case INTEGER:
        ps.setInt(position, (Integer) value);
        break;
    case LONG:
        ps.setLong(position, (Long) value);
        break;
    case FLOAT:
        ps.setFloat(position, (Float) value);
        break;
    case DOUBLE:
        ps.setDouble(position, (Double) value);
        break;
    case DECIMAL:
        ps.setBigDecimal(position, (BigDecimal) value);
        break;
    case UUID:
        ps.setBytes(position, AbstractHelper.uuidToByteArray((UUID) value));
        break;
    case ARRAY:
        throw new UnsupportedOperationException("The saving changes in ARRAY isn't supported.");
        // ps.setArray(position, (Array) value); break; // FIXME the value isn't in type java.sql.Array
    case BYTE_ARRAY:
        if (bd == null || bd.isNull()) {
            ps.setBytes(position, null);
        } else {
            try {
                ps.setBytes(position, IOUtils.toByteArray(bd.getInputStream()));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
        break;
    case CLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.CLOB);
        } else {
            ps.setClob(position, bd.getReader());
        }
        break;
    case BLOB:
        if (bd == null || bd.isNull()) {
            ps.setNull(position, Types.BLOB);
        } else {
            ps.setBlob(position, bd.getInputStream());
        }
        break;
    case OBJECT:
        ps.setObject(position, value);
    }
}

From source file:org.apache.ode.scheduler.simple.JdbcDelegate.java

public boolean insertJob(Job job, String nodeId, boolean loaded) throws DatabaseException {
    if (__log.isDebugEnabled())
        __log.debug("insertJob " + job.jobId + " on node " + nodeId + " loaded=" + loaded);

    Connection con = null;/*from  ww  w. java 2  s .  com*/
    PreparedStatement ps = null;
    try {
        int i = 1;
        con = getConnection();
        ps = con.prepareStatement(SAVE_JOB);
        ps.setString(i++, job.jobId);
        ps.setString(i++, nodeId);
        ps.setLong(i++, job.schedDate);
        ps.setInt(i++, asInteger(loaded));
        ps.setInt(i++, asInteger(job.transacted));

        JobDetails details = job.detail;
        ps.setObject(i++, details.instanceId, Types.BIGINT);
        ps.setObject(i++, details.mexId, Types.VARCHAR);
        ps.setObject(i++, details.processId, Types.VARCHAR);
        ps.setObject(i++, details.type, Types.VARCHAR);
        ps.setObject(i++, details.channel, Types.VARCHAR);
        ps.setObject(i++, details.correlatorId, Types.VARCHAR);
        ps.setObject(i++, details.correlationKeySet, Types.VARCHAR);
        ps.setObject(i++, details.retryCount, Types.INTEGER);
        ps.setObject(i++, details.inMem, Types.INTEGER);

        if (details.detailsExt == null || details.detailsExt.size() == 0) {
            ps.setObject(i++, null, Types.BLOB);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                StreamUtils.write(bos, (Serializable) details.detailsExt);
            } catch (Exception ex) {
                __log.error("Error serializing job detail: " + job.detail);
                throw new DatabaseException(ex);
            }
            ps.setBytes(i++, bos.toByteArray());
        }

        return ps.executeUpdate() == 1;
    } catch (SQLException se) {
        throw new DatabaseException(se);
    } finally {
        close(ps);
        close(con);
    }
}

From source file:lcn.module.batch.core.item.database.support.MethodMapItemPreparedStatementSetter.java

/**
 * params ? ? sqlType PreparedStatement? ??
 */// www .j a  v  a2 s  .  c  o m
public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes,
        Map<String, Method> methodMap) throws SQLException {

    ReflectionSupport<T> reflector = new ReflectionSupport<T>();

    for (int i = 0; i < params.length; i++) {
        try {

            if (sqlTypes[i].equals("String")) {
                ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("int")) {
                ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("double")) {
                ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Date")) {
                ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte")) {
                ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("short")) {
                ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("boolean")) {
                ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("long")) {
                ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("Float")) {
                ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("BigDecimal")) {
                ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else if (sqlTypes[i].equals("byte[]")) {
                ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap));
            } else {
                throw new SQLException();
            }
        } catch (IllegalArgumentException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
}