Example usage for java.sql PreparedStatement setBinaryStream

List of usage examples for java.sql PreparedStatement setBinaryStream

Introduction

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

Prototype

void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException;

Source Link

Document

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

Usage

From source file:org.wso2.carbon.user.core.tenant.JDBCTenantManager.java

/**
 * This method is introduced when we require to create a tenant with provided tenant Id. In some cases, we need to
 * duplicate tenant in multiple environments with same Id.
 *
 * @param tenant - tenant bean with tenantId set.
 * @return/*www.j  a  va  2  s .  c  om*/
 * @throws UserStoreException if tenant Id is already taken.
 */
public int addTenantWithGivenId(org.wso2.carbon.user.api.Tenant tenant) throws UserStoreException {
    // check if tenant id is available, if not available throw exception.
    if (getTenant(tenant.getId()) != null) {
        String errorMsg = "Tenant with tenantId:" + tenant.getId() + " is already created. Tenant creation is "
                + "aborted for tenant domain:" + tenant.getDomain();
        log.error(errorMsg);
        throw new UserStoreException(errorMsg);
    }

    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    ResultSet result = null;
    int id = 0;
    try {
        dbConnection = getDBConnection();
        String sqlStmt = TenantConstants.ADD_TENANT_WITH_ID_SQL;

        String dbProductName = dbConnection.getMetaData().getDatabaseProductName();
        prepStmt = dbConnection.prepareStatement(sqlStmt,
                new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "UM_ID") });
        prepStmt.setInt(1, tenant.getId());
        prepStmt.setString(2, tenant.getDomain().toLowerCase());
        prepStmt.setString(3, tenant.getEmail());
        Date createdTime = tenant.getCreatedDate();
        long createdTimeMs;
        if (createdTime == null) {
            createdTimeMs = System.currentTimeMillis();
        } else {
            createdTimeMs = createdTime.getTime();
        }
        prepStmt.setTimestamp(4, new Timestamp(createdTimeMs));
        String realmConfigString = RealmConfigXMLProcessor
                .serialize((RealmConfiguration) tenant.getRealmConfig()).toString();
        InputStream is = new ByteArrayInputStream(realmConfigString.getBytes());
        prepStmt.setBinaryStream(5, is, is.available());

        prepStmt.executeUpdate();

        id = tenant.getId();
        dbConnection.commit();
    } catch (Exception e) {

        DatabaseUtil.rollBack(dbConnection);

        String msg = "Error in adding tenant with " + "tenant domain: " + tenant.getDomain().toLowerCase()
                + ".";
        if (log.isDebugEnabled()) {
            log.debug(msg, e);
        }
        throw new UserStoreException(msg, e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection, result, prepStmt);
    }
    return id;
}

From source file:oscar.util.SqlUtils.java

/**
 * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information
 * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=)
 *//*from www  .  j a va  2s  . c  om*/
public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType)
        throws SQLException {
    try {
        logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")...");
        Object value = null;
        // Check for hard-coded NULL
        if (!("$null$".equals(val))) {
            value = val;
        }
        if (value != null) {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setInt(col, Integer.parseInt((String) value));
                break;
            case FieldTypes.NUMERIC:
                ps.setBigDecimal(col, createAppropriateNumeric(value));
                break;
            case FieldTypes.CHAR:
                ps.setString(col, (String) value);
                break;
            case FieldTypes.DATE:
                ps.setDate(col, createAppropriateDate(value));
                break; // #checkme
            case FieldTypes.TIMESTAMP:
                ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value));
                break;
            case FieldTypes.DOUBLE:
                ps.setDouble(col, Double.valueOf((String) value).doubleValue());
                break;
            case FieldTypes.FLOAT:
                ps.setFloat(col, Float.valueOf((String) value).floatValue());
                break;
            case FieldTypes.LONG:
                ps.setLong(col, Long.parseLong(String.valueOf(value)));
                break;
            case FieldTypes.BLOB:
                FileHolder fileHolder = (FileHolder) value;
                try {
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(byteOut);
                    out.writeObject(fileHolder);
                    out.flush();
                    byte[] buf = byteOut.toByteArray();
                    byteOut.close();
                    out.close();
                    ByteArrayInputStream bytein = new ByteArrayInputStream(buf);
                    int byteLength = buf.length;
                    ps.setBinaryStream(col, bytein, byteLength);
                    // store fileHolder as a whole (this way we don't lose file meta-info!)
                } catch (IOException ioe) {
                    MiscUtils.getLogger().error("Error", ioe);
                    logger.info(ioe.toString());
                    throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2);
                }
                break;
            case FieldTypes.DISKBLOB:
                ps.setString(col, (String) value);
                break;
            default:
                ps.setObject(col, value); // #checkme
            }
        } else {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setNull(col, java.sql.Types.INTEGER);
                break;
            case FieldTypes.NUMERIC:
                ps.setNull(col, java.sql.Types.NUMERIC);
                break;
            case FieldTypes.CHAR:
                ps.setNull(col, java.sql.Types.CHAR);
                break;
            case FieldTypes.DATE:
                ps.setNull(col, java.sql.Types.DATE);
                break;
            case FieldTypes.TIMESTAMP:
                ps.setNull(col, java.sql.Types.TIMESTAMP);
                break;
            case FieldTypes.DOUBLE:
                ps.setNull(col, java.sql.Types.DOUBLE);
                break;
            case FieldTypes.FLOAT:
                ps.setNull(col, java.sql.Types.FLOAT);
                break;
            case FieldTypes.BLOB:
                ps.setNull(col, java.sql.Types.BLOB);
            case FieldTypes.DISKBLOB:
                ps.setNull(col, java.sql.Types.CHAR);
            default:
                ps.setNull(col, java.sql.Types.OTHER);
            }
        }
    } catch (Exception e) {
        throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1);
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Put a collection of captchas with his locale
 *
 * @param captchas The captchas to add/*  w ww.  j a v  a 2  s .co  m*/
 * @param locale   The locale of the captchas
 */
public void putAllCaptcha(Collection captchas, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;

    if (captchas != null && captchas.size() > 0) {
        Iterator captIt = captchas.iterator();
        if (log.isDebugEnabled()) {
            log.debug("try to insert " + captchas.size() + " captchas");
        }

        try {
            con = datasource.getConnection();
            con.setAutoCommit(false);
            ps = con.prepareStatement("insert into " + table + "(" + timeMillisColumn + "," + hashCodeColumn
                    + "," + localeColumn + "," + captchaColumn + ") values (?,?,?,?)");

            while (captIt.hasNext()) {

                Captcha captcha = (Captcha) captIt.next();
                try {
                    long currenttime = System.currentTimeMillis();
                    long hash = captcha.hashCode();

                    ps.setLong(1, currenttime);
                    ps.setLong(2, hash);
                    ps.setString(3, locale.toString());
                    // Serialise the entry
                    final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
                    final ObjectOutputStream objstr = new ObjectOutputStream(outstr);
                    objstr.writeObject(captcha);
                    objstr.close();
                    final ByteArrayInputStream inpstream = new ByteArrayInputStream(outstr.toByteArray());

                    ps.setBinaryStream(4, inpstream, outstr.size());

                    ps.addBatch();

                    if (log.isDebugEnabled()) {
                        log.debug("insert captcha added to batch : " + currenttime + ";" + hash);
                    }

                } catch (IOException e) {
                    log.warn("error during captcha serialization, "
                            + "check your class versions. removing row from database", e);
                }
            }
            //exexute batch and commit()

            ps.executeBatch();
            log.debug("batch executed");

            con.commit();
            log.debug("batch commited");

        } catch (SQLException e) {
            log.error(DB_ERROR, e);

        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                }
            }
        }
    }

}

From source file:org.dcache.chimera.FsSqlDriver.java

/**
 *
 *  creates a new id for a tag and stores it into t_tags_inodes table.
 *
 * @param uid/*from  ww w.  j a  v  a2 s  .  c o m*/
 * @param gid
 * @param mode
 * @param value
 * @return
 */
long createTagInode(int uid, int gid, int mode, byte[] value) {
    final String CREATE_TAG_INODE_WITH_VALUE = "INSERT INTO t_tags_inodes (imode, inlink, iuid, igid, isize, "
            + "ictime, iatime, imtime, ivalue) VALUES (?,1,?,?,?,?,?,?,?)";

    Timestamp now = new Timestamp(System.currentTimeMillis());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int rc = _jdbc.update(con -> {
        PreparedStatement ps = con.prepareStatement(CREATE_TAG_INODE_WITH_VALUE,
                Statement.RETURN_GENERATED_KEYS);
        ps.setInt(1, mode | UnixPermission.S_IFREG);
        ps.setInt(2, uid);
        ps.setInt(3, gid);
        ps.setLong(4, value.length);
        ps.setTimestamp(5, now);
        ps.setTimestamp(6, now);
        ps.setTimestamp(7, now);
        ps.setBinaryStream(8, new ByteArrayInputStream(value), value.length);
        return ps;
    }, keyHolder);
    if (rc != 1) {
        throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(CREATE_TAG_INODE_WITH_VALUE, 1, rc);
    }
    return (Long) keyHolder.getKeys().get("itagid");
}

From source file:org.cloudgraph.rdb.service.JDBCSupport.java

protected void executeInsert(PlasmaType type, StringBuilder sql, Map<String, PropertyPair> values,
        Connection con) {/*  w  ww  . j  a  v  a2 s  .c  o  m*/
    PreparedStatement statement = null;
    List<InputStream> streams = null;
    try {

        if (log.isDebugEnabled()) {
            log.debug("execute: " + sql.toString());
            StringBuilder paramBuf = createParamDebug(values);
            log.debug("params: " + paramBuf.toString());
        }

        statement = con.prepareStatement(sql.toString());

        for (PropertyPair pair : values.values()) {
            PlasmaProperty valueProp = pair.getProp();
            if (pair.getValueProp() != null)
                valueProp = pair.getValueProp();
            int jdbcType = converter.toJDBCDataType(valueProp, pair.getValue());
            Object jdbcValue = converter.toJDBCDataValue(valueProp, pair.getValue());
            if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                statement.setObject(pair.getColumn(), jdbcValue, jdbcType);
            } else {
                byte[] bytes = (byte[]) jdbcValue;
                long len = bytes.length;
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                statement.setBinaryStream(pair.getColumn(), is, len);
                if (streams == null)
                    streams = new ArrayList<InputStream>();
                streams.add(is);
            }
        }

        statement.execute();
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        if (streams != null)
            try {
                for (InputStream stream : streams)
                    stream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }

    }
}

From source file:org.cloudgraph.rdb.service.JDBCSupport.java

protected void execute(PlasmaType type, StringBuilder sql, Map<String, PropertyPair> values, Connection con) {
    PreparedStatement statement = null;
    List<InputStream> streams = null;
    try {/*from www  . j av a2  s. c om*/
        if (log.isDebugEnabled()) {
            log.debug("execute: " + sql.toString());
            StringBuilder paramBuf = createParamDebug(values);
            log.debug("params: " + paramBuf.toString());
        }
        statement = con.prepareStatement(sql.toString());
        for (PropertyPair pair : values.values()) {
            PlasmaProperty valueProp = pair.getProp();
            if (pair.getValueProp() != null)
                valueProp = pair.getValueProp();

            int jdbcType = converter.toJDBCDataType(valueProp, pair.getValue());
            Object jdbcValue = converter.toJDBCDataValue(valueProp, pair.getValue());
            if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                statement.setObject(pair.getColumn(), jdbcValue, jdbcType);
            } else {
                byte[] bytes = (byte[]) jdbcValue;
                long len = bytes.length;
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                statement.setBinaryStream(pair.getColumn(), is, len);
                if (streams == null)
                    streams = new ArrayList<InputStream>();
                streams.add(is);
            }

            if (pair.getOldValue() != null) {
                Object jdbcOldValue = converter.toJDBCDataValue(valueProp, pair.getOldValue());
                if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                    statement.setObject(pair.getOldValueColumn(), jdbcOldValue, jdbcType);
                } else {
                    byte[] bytes = (byte[]) jdbcOldValue;
                    long len = bytes.length;
                    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                    statement.setBinaryStream(pair.getOldValueColumn(), is, len);
                    if (streams == null)
                        streams = new ArrayList<InputStream>();
                    streams.add(is);
                }
            }
        }
        statement.executeUpdate();
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        if (streams != null)
            try {
                for (InputStream stream : streams)
                    stream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }

    }
}

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

private void addContent(Connection conn, long messageId, ByteBuffer src) {
    if (_logger.isDebugEnabled()) {
        _logger.debug("Adding content for message " + messageId);
    }//from  w w w.jav a  2 s.  c om
    PreparedStatement stmt = null;

    try {
        src = src.slice();

        byte[] chunkData = new byte[src.limit()];
        src.duplicate().get(chunkData);

        stmt = conn.prepareStatement(INSERT_INTO_MESSAGE_CONTENT);
        stmt.setLong(1, messageId);

        ByteArrayInputStream bis = new ByteArrayInputStream(chunkData);
        stmt.setBinaryStream(2, bis, chunkData.length);
        stmt.executeUpdate();
    } catch (SQLException e) {
        closeConnection(conn);
        throw new RuntimeException("Error adding content for message " + messageId + ": " + e.getMessage(), e);
    } finally {
        closePreparedStatement(stmt);
    }

}

From source file:org.cloudgraph.rdb.service.JDBCSupport.java

protected List<PropertyPair> executeInsertWithGeneratedKeys(PlasmaType type, StringBuilder sql,
        Map<String, PropertyPair> values, Connection con) {
    List<PropertyPair> resultKeys = new ArrayList<PropertyPair>();
    PreparedStatement statement = null;
    List<InputStream> streams = null;
    ResultSet generatedKeys = null;
    try {/*from w  w  w  .  jav  a  2s .  c o  m*/

        if (log.isDebugEnabled()) {
            log.debug("execute: " + sql.toString());
            StringBuilder paramBuf = createParamDebug(values);
            log.debug("params: " + paramBuf.toString());
        }

        statement = con.prepareStatement(sql.toString(), PreparedStatement.RETURN_GENERATED_KEYS);

        for (PropertyPair pair : values.values()) {
            PlasmaProperty valueProp = pair.getProp();
            if (pair.getValueProp() != null)
                valueProp = pair.getValueProp();
            int jdbcType = converter.toJDBCDataType(valueProp, pair.getValue());
            Object jdbcValue = converter.toJDBCDataValue(valueProp, pair.getValue());
            if (jdbcType != Types.BLOB && jdbcType != Types.VARBINARY) {
                statement.setObject(pair.getColumn(), jdbcValue, jdbcType);
            } else {
                byte[] bytes = (byte[]) jdbcValue;
                long len = bytes.length;
                ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                statement.setBinaryStream(pair.getColumn(), is, len);
                if (streams == null)
                    streams = new ArrayList<InputStream>();
                streams.add(is);
            }
        }

        statement.execute();
        generatedKeys = statement.getGeneratedKeys();
        ResultSetMetaData rsMeta = generatedKeys.getMetaData();
        int numcols = rsMeta.getColumnCount();
        if (log.isDebugEnabled())
            log.debug("returned " + numcols + " keys");

        if (generatedKeys.next()) {
            // FIXME; without metadata describing which properties
            // are actually a sequence, there is guess work
            // involved in matching the values returned
            // automatically from PreparedStatment as they
            // are anonymous in terms of the column names
            // making it impossible to match them to a metadata
            // property.
            List<Property> pkPropList = type.findProperties(KeyType.primary);
            if (pkPropList == null || pkPropList.size() == 0)
                throw new DataAccessException("no pri-key properties found for type '" + type.getName() + "'");
            if (pkPropList.size() > 1)
                throw new DataAccessException("multiple pri-key properties found for type '" + type.getName()
                        + "' - cannot map to generated keys");
            PlasmaProperty prop = (PlasmaProperty) pkPropList.get(0);
            // FIXME: need to find properties per column by physical name
            // alias
            // in case where multiple generated pri-keys
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                if (log.isDebugEnabled())
                    log.debug("returned key column '" + columnName + "'");
                int columnType = rsMeta.getColumnType(i);
                Object value = converter.fromJDBCDataType(generatedKeys, i, columnType, prop);
                PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                resultKeys.add(pair);
            }
        }
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        if (streams != null)
            try {
                for (InputStream stream : streams)
                    stream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
    }

    return resultKeys;
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.lib.AbstractMailRepository#internalStore(Mail)
 *///from w  w  w.  j a v  a2 s .co  m
protected void internalStore(Mail mc) throws IOException, MessagingException {
    Connection conn = null;
    try {
        conn = datasource.getConnection();
        // Need to determine whether need to insert this record, or update
        // it.

        // Determine whether the message body has changed, and possibly
        // avoid
        // updating the database.
        boolean saveBody;

        MimeMessage messageBody = mc.getMessage();
        // if the message is a CopyOnWrite proxy we check the modified
        // wrapped object.
        if (messageBody instanceof MimeMessageCopyOnWriteProxy) {
            MimeMessageCopyOnWriteProxy messageCow = (MimeMessageCopyOnWriteProxy) messageBody;
            messageBody = messageCow.getWrappedMessage();
        }
        if (messageBody instanceof MimeMessageWrapper) {
            MimeMessageWrapper message = (MimeMessageWrapper) messageBody;
            saveBody = message.isModified();
            if (saveBody) {
                message.loadMessage();
            }
        } else {
            saveBody = true;
        }
        MessageInputStream is = new MessageInputStream(mc, sr, inMemorySizeLimit, true);

        // Begin a transaction
        conn.setAutoCommit(false);

        PreparedStatement checkMessageExists = null;
        ResultSet rsExists = null;
        boolean exists = false;
        try {
            checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
            checkMessageExists.setString(1, mc.getName());
            checkMessageExists.setString(2, repositoryName);
            rsExists = checkMessageExists.executeQuery();
            exists = rsExists.next() && rsExists.getInt(1) > 0;
        } finally {
            theJDBCUtil.closeJDBCResultSet(rsExists);
            theJDBCUtil.closeJDBCStatement(checkMessageExists);
        }

        if (exists) {
            // MessageInputStream is = new
            // MessageInputStream(mc,sr,inMemorySizeLimit, true);

            // Update the existing record
            PreparedStatement updateMessage = null;

            try {
                updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true));
                updateMessage.setString(1, mc.getState());
                updateMessage.setString(2, mc.getErrorMessage());
                if (mc.getSender() == null) {
                    updateMessage.setNull(3, java.sql.Types.VARCHAR);
                } else {
                    updateMessage.setString(3, mc.getSender().toString());
                }
                StringBuilder recipients = new StringBuilder();
                for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
                    recipients.append(i.next().toString());
                    if (i.hasNext()) {
                        recipients.append("\r\n");
                    }
                }
                updateMessage.setString(4, recipients.toString());
                updateMessage.setString(5, mc.getRemoteHost());
                updateMessage.setString(6, mc.getRemoteAddr());
                updateMessage.setTimestamp(7, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
                updateMessage.setString(8, mc.getName());
                updateMessage.setString(9, repositoryName);
                updateMessage.execute();
            } finally {
                Statement localUpdateMessage = updateMessage;
                // Clear reference to statement
                updateMessage = null;
                theJDBCUtil.closeJDBCStatement(localUpdateMessage);
            }

            // Determine whether attributes are used and available for
            // storing
            if (jdbcMailAttributesReady && mc.hasAttributes()) {
                String updateMessageAttrSql = sqlQueries.getSqlString("updateMessageAttributesSQL", false);
                PreparedStatement updateMessageAttr = null;
                try {
                    updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    try {
                        if (mc instanceof MailImpl) {
                            oos.writeObject(((MailImpl) mc).getAttributesRaw());
                        } else {
                            HashMap<String, Serializable> temp = new HashMap<String, Serializable>();
                            for (Iterator<String> i = mc.getAttributeNames(); i.hasNext();) {
                                String hashKey = i.next();
                                temp.put(hashKey, mc.getAttribute(hashKey));
                            }
                            oos.writeObject(temp);
                        }
                        oos.flush();
                        ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                        updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
                    } finally {
                        try {
                            if (oos != null) {
                                oos.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().debug(
                                    "JDBCMailRepository: Unexpected exception while closing output stream.",
                                    ioe);
                        }
                    }
                    updateMessageAttr.setString(2, mc.getName());
                    updateMessageAttr.setString(3, repositoryName);
                    updateMessageAttr.execute();
                } catch (SQLException sqle) {
                    getLogger().info("JDBCMailRepository: Trying to update mail attributes failed.", sqle);

                } finally {
                    theJDBCUtil.closeJDBCStatement(updateMessageAttr);
                }
            }

            if (saveBody) {

                PreparedStatement updateMessageBody = conn
                        .prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true));
                try {
                    updateMessageBody.setBinaryStream(1, is, (int) is.getSize());
                    updateMessageBody.setString(2, mc.getName());
                    updateMessageBody.setString(3, repositoryName);
                    updateMessageBody.execute();

                } finally {
                    theJDBCUtil.closeJDBCStatement(updateMessageBody);
                }
            }

        } else {
            // Insert the record into the database
            PreparedStatement insertMessage = null;
            try {
                String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
                int number_of_parameters = getNumberOfParameters(insertMessageSQL);
                insertMessage = conn.prepareStatement(insertMessageSQL);
                insertMessage.setString(1, mc.getName());
                insertMessage.setString(2, repositoryName);
                insertMessage.setString(3, mc.getState());
                insertMessage.setString(4, mc.getErrorMessage());
                if (mc.getSender() == null) {
                    insertMessage.setNull(5, java.sql.Types.VARCHAR);
                } else {
                    insertMessage.setString(5, mc.getSender().toString());
                }
                StringBuilder recipients = new StringBuilder();
                for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
                    recipients.append(i.next().toString());
                    if (i.hasNext()) {
                        recipients.append("\r\n");
                    }
                }
                insertMessage.setString(6, recipients.toString());
                insertMessage.setString(7, mc.getRemoteHost());
                insertMessage.setString(8, mc.getRemoteAddr());
                insertMessage.setTimestamp(9, new java.sql.Timestamp(mc.getLastUpdated().getTime()));

                insertMessage.setBinaryStream(10, is, (int) is.getSize());

                // Store attributes
                if (number_of_parameters > 10) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    try {
                        if (mc instanceof MailImpl) {
                            oos.writeObject(((MailImpl) mc).getAttributesRaw());
                        } else {
                            HashMap<String, Serializable> temp = new HashMap<String, Serializable>();
                            for (Iterator<String> i = mc.getAttributeNames(); i.hasNext();) {
                                String hashKey = i.next();
                                temp.put(hashKey, mc.getAttribute(hashKey));
                            }
                            oos.writeObject(temp);
                        }
                        oos.flush();
                        ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                        insertMessage.setBinaryStream(11, attrInputStream, baos.size());
                    } finally {
                        try {
                            if (oos != null) {
                                oos.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().debug(
                                    "JDBCMailRepository: Unexpected exception while closing output stream.",
                                    ioe);
                        }
                    }
                }

                insertMessage.execute();
            } finally {
                theJDBCUtil.closeJDBCStatement(insertMessage);
            }
        }

        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        getLogger().debug("Failed to store internal mail", e);
        throw new IOException(e.getMessage());
    } finally {
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

public int insertTrigger(Connection conn, Trigger trigger, String state, JobDetail jobDetail)
        throws SQLException, IOException {

    ByteArrayOutputStream baos = serializeJobData(trigger.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

    PreparedStatement ps = null;

    int insertResult = 0;

    try {// w  w w .  jav  a2s  .co  m
        ps = conn.prepareStatement(rtp(INSERT_TRIGGER));
        ps.setString(1, trigger.getName());
        ps.setString(2, trigger.getGroup());
        ps.setString(3, trigger.getJobName());
        ps.setString(4, trigger.getJobGroup());
        setBoolean(ps, 5, trigger.isVolatile());
        ps.setString(6, trigger.getDescription());
        ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger.getNextFireTime().getTime())));
        long prevFireTime = -1;
        if (trigger.getPreviousFireTime() != null) {
            prevFireTime = trigger.getPreviousFireTime().getTime();
        }
        ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime)));
        ps.setString(9, state);
        if (trigger instanceof SimpleTrigger && ((SimpleTrigger) trigger).hasAdditionalProperties() == false) {
            ps.setString(10, TTYPE_SIMPLE);
        } else if (trigger instanceof CronTrigger
                && ((CronTrigger) trigger).hasAdditionalProperties() == false) {
            ps.setString(10, TTYPE_CRON);
        } else {
            ps.setString(10, TTYPE_BLOB);
        }
        ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger.getStartTime().getTime())));
        long endTime = 0;
        if (trigger.getEndTime() != null) {
            endTime = trigger.getEndTime().getTime();
        }
        ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime)));
        ps.setString(13, trigger.getCalendarName());
        ps.setInt(14, trigger.getMisfireInstruction());
        ps.setBinaryStream(15, bais, len);
        ps.setInt(16, trigger.getPriority());

        insertResult = ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }

    if (insertResult > 0) {
        String[] trigListeners = trigger.getTriggerListenerNames();
        for (int i = 0; trigListeners != null && i < trigListeners.length; i++) {
            insertTriggerListener(conn, trigger, trigListeners[i]);
        }
    }

    return insertResult;
}