Example usage for java.sql PreparedStatement setTimestamp

List of usage examples for java.sql PreparedStatement setTimestamp

Introduction

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

Prototype

void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Timestamp value.

Usage

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

@Override
protected String enqueueSingleJob(String queueName, PinLaterJob job, int numAutoRetries) throws Exception {
    final long currentTimeMillis = System.currentTimeMillis();
    Connection conn = null;//  w  ww  .j  a va2 s .  co  m
    PreparedStatement stmt = null;
    ResultSet rs = null;
    final ImmutableMap.Entry<String, MySQLDataSources> shard = getRandomEnqueueableShard();
    try {
        conn = shard.getValue().getGeneralDataSource().getConnection();
        String jobsTableName = MySQLBackendUtils.constructJobsTableName(queueName, shard.getKey(),
                job.getPriority());
        stmt = conn.prepareStatement(String.format(MySQLQueries.ENQUEUE_INSERT, jobsTableName),
                Statement.RETURN_GENERATED_KEYS);
        stmt.setInt(1, PinLaterJobState.PENDING.getValue());
        stmt.setInt(2, job.getNumAttemptsAllowed());
        stmt.setInt(3, job.getNumAttemptsAllowed());
        stmt.setString(4, job.getCustomStatus());
        stmt.setTimestamp(5, new Timestamp(currentTimeMillis));
        stmt.setTimestamp(6, new Timestamp(
                job.isSetRunAfterTimestampMillis() ? job.getRunAfterTimestampMillis() : currentTimeMillis));
        stmt.setBytes(7, job.getBody());
        stmt.executeUpdate();
        rs = stmt.getGeneratedKeys();
        rs.next();
        return new PinLaterJobDescriptor(queueName, shard.getKey(), job.getPriority(), rs.getLong(1))
                .toString();
    } catch (SQLException e) {
        boolean shouldRetry = checkExceptionIsRetriable(e, shard.getKey(), "enqueue");
        if (shouldRetry && numAutoRetries > 0) {
            // Retry the enqueue, potentially on a different shard.
            Stats.incr("enqueue-failures-retry");
            return enqueueSingleJob(queueName, job, numAutoRetries - 1);
        }
        // Out of retries, throw the exception. Wrap it into a PinLaterException if the exception
        // is recognized and return the appropriate error code.
        if (MySQLBackendUtils.isDatabaseDoesNotExistException(e)) {
            throw new PinLaterException(ErrorCode.QUEUE_NOT_FOUND, "Queue not found: " + queueName);
        }
        throw e;
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(stmt);
        JdbcUtils.closeConnection(conn);
    }
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public void store(String key, CacheEntry entry) {
    logger.fine("Store: " + key);

    Lock lock = lockSource.getWriteLock(key);
    lock.lock();/*from   w  w w.  j  a  v a2s .  c  o m*/
    try {
        Connection connection = connect();
        if (connection == null)
            return;

        try {
            boolean tryInsert = true;

            // Try updating this key

            String sql = "UPDATE " + cacheTableName
                    + " SET data=?, media_type=?, language=?, character_set=?, encoding=?, modification_date=?, tag=?, headers=?, expiration_date=?, document_modification_date=? WHERE key=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                statement.setBytes(1,
                        entry.getString() != null ? entry.getString().getBytes() : entry.getBytes());
                statement.setString(2, entry.getMediaType() != null ? entry.getMediaType().getName() : null);
                statement.setString(3, entry.getLanguage() != null ? entry.getLanguage().getName() : null);
                statement.setString(4,
                        entry.getCharacterSet() != null ? entry.getCharacterSet().getName() : null);
                statement.setString(5, entry.getEncoding() != null ? entry.getEncoding().getName() : null);
                statement.setTimestamp(6,
                        entry.getModificationDate() != null
                                ? new Timestamp(entry.getModificationDate().getTime())
                                : null);
                statement.setString(7, entry.getTag() != null ? entry.getTag().format() : null);
                statement.setString(8, entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders()));
                statement.setTimestamp(9,
                        entry.getExpirationDate() != null ? new Timestamp(entry.getExpirationDate().getTime())
                                : null);
                statement.setTimestamp(10,
                        entry.getDocumentModificationDate() != null
                                ? new Timestamp(entry.getDocumentModificationDate().getTime())
                                : null);
                statement.setString(11, key);
                if (!statement.execute() && statement.getUpdateCount() > 0) {
                    logger.fine("Updated " + key);

                    // Update worked, so no need to try insertion

                    tryInsert = false;
                }
            } finally {
                statement.close();
            }

            if (tryInsert) {
                // Try inserting this key

                // But first make sure we have room...

                int size = countEntries(connection);
                if (size >= maxSize) {
                    prune();

                    size = countEntries(connection);
                    if (size >= maxSize) {
                        logger.fine("No room in cache (" + size + ", " + maxSize + ")");
                        return;
                    }
                }

                // delete( connection, key );

                sql = "INSERT INTO " + cacheTableName
                        + " (key, data, media_type, language, character_set, encoding, modification_date, tag, headers, expiration_date, document_modification_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                statement = connection.prepareStatement(sql);
                try {
                    statement.setString(1, key);
                    statement.setBytes(2,
                            entry.getString() != null ? entry.getString().getBytes() : entry.getBytes());
                    statement.setString(3, getName(entry.getMediaType()));
                    statement.setString(4, getName(entry.getLanguage()));
                    statement.setString(5, getName(entry.getCharacterSet()));
                    statement.setString(6, getName(entry.getEncoding()));
                    statement.setTimestamp(7,
                            entry.getModificationDate() != null
                                    ? new Timestamp(entry.getModificationDate().getTime())
                                    : null);
                    statement.setString(8, entry.getTag() != null ? entry.getTag().format() : null);
                    statement.setString(9,
                            entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders()));
                    statement.setTimestamp(10,
                            entry.getExpirationDate() != null
                                    ? new Timestamp(entry.getExpirationDate().getTime())
                                    : null);
                    statement.setTimestamp(11,
                            entry.getDocumentModificationDate() != null
                                    ? new Timestamp(entry.getDocumentModificationDate().getTime())
                                    : null);
                    statement.execute();
                } finally {
                    statement.close();
                }
            }

            // Clean out existing tags for this key

            sql = "DELETE FROM " + cacheTagsTableName + " WHERE key=?";
            statement = connection.prepareStatement(sql);
            try {
                statement.setString(1, key);
                statement.execute();
            } finally {
                statement.close();
            }

            // Add tags for this key

            String[] tags = entry.getTags();
            if ((tags != null) && (tags.length > 0)) {
                sql = "INSERT INTO " + cacheTagsTableName + " (key, tag) VALUES (?, ?)";
                statement = connection.prepareStatement(sql);
                statement.setString(1, key);
                try {
                    for (String tag : tags) {
                        statement.setString(2, tag);
                        statement.execute();
                    }
                } finally {
                    statement.close();
                }
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not store cache entry", x);
    } finally {
        lock.unlock();
    }
}

From source file:com.sinet.gage.dao.DomainsRepository.java

/**
 * /*from   www  . j a  v a  2 s  .  c  o m*/
 * @param domains
 */
public void insertDomains(List<Domain> domains) {
    try {
        jdbcTemplate.batchUpdate(DOMAINS_INSERT_SQL, new BatchPreparedStatementSetter() {

            public int getBatchSize() {
                if (domains == null)
                    return 0;
                return domains.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Domain domain = domains.get(i);
                ps.setLong(1, domain.getDomainId());
                ps.setObject(2, domain.getGuid());
                ps.setString(3, domain.getDomainName());
                ps.setString(4, domain.getLoginPrefix());
                ps.setLong(5, domain.getFlag());
                ps.setString(6, domain.getDomainType());
                ps.setLong(7, domain.getParentDomainId());
                ps.setString(8, domain.getParentDomainName());
                ps.setLong(9, domain.getStateDomainId());
                ps.setString(10, domain.getStateDomainName());
                ps.setString(11, domain.getLicenseType());
                ps.setString(12, domain.getLicensePoolType());
                ps.setInt(13, domain.getNoOfLicense());
                ps.setBoolean(14, domain.isPilot());
                ps.setDate(15, domain.getPilotStartDate());
                ps.setDate(16, domain.getPilotEndDate());
                ps.setBoolean(17, domain.isFullSubscription());
                ps.setObject(18, domain.getSubscriptionStartDate());
                ps.setObject(19, domain.getSubscriptionEndDate());
                ps.setLong(20, domain.getCreatorUserId());
                ps.setTimestamp(21, domain.getCreationDate());
                ps.setLong(22, domain.getModifierUserId());
                ps.setTimestamp(23, domain.getModifiedDate());
            }
        });
    } catch (Exception e) {
        log.error("Error in inserting Domains", e);
    }
}

From source file:com.adanac.module.blog.dao.CommentDao.java

public Integer save(final Integer articleId, final String visitorIp, final Date commentDate,
        final String content, final String username, final String resourceUsername, final String resourceId,
        final Integer referenceCommentId) {
    return execute(new TransactionalOperation<Integer>() {
        @Override/*from w  w  w  . ja v a 2 s . co m*/
        public Integer doInConnection(Connection connection) {
            try {
                PreparedStatement statement = null;
                if (referenceCommentId == null) {
                    statement = connection.prepareStatement(
                            "insert into comments (visitor_ip,city,content,article_id,"
                                    + "create_date,username,resource_username,resource_id) values (?,?,?,?,?,?,?,?)",
                            Statement.RETURN_GENERATED_KEYS);
                } else {
                    statement = connection.prepareStatement(
                            "insert into comments (visitor_ip,city,content,article_id,"
                                    + "create_date,username,resource_username,resource_id,reference_comment_id) values (?,?,?,?,?,?,?,?,?)",
                            Statement.RETURN_GENERATED_KEYS);
                }
                statement.setString(1, visitorIp);
                statement.setString(2,
                        Configuration.isProductEnv() ? HttpApiHelper.getCity(visitorIp) : "?");
                statement.setString(3, content);
                statement.setInt(4, articleId);
                Date finalCommentDate = commentDate;
                if (commentDate == null) {
                    finalCommentDate = new Date();
                }
                statement.setTimestamp(5, new Timestamp(finalCommentDate.getTime()));
                statement.setString(6, username);
                statement.setString(7, resourceUsername);
                statement.setString(8, resourceId);
                if (referenceCommentId != null) {
                    statement.setInt(9, referenceCommentId);
                }
                int result = statement.executeUpdate();
                if (result > 0) {
                    ResultSet resultSet = statement.getGeneratedKeys();
                    if (resultSet.next()) {
                        return resultSet.getInt(1);
                    }
                }
            } catch (SQLException e) {
                error("save comments failed ...", e);
            }
            return null;
        }
    });
}

From source file:com.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java

@Override
public int saveUser(final TUserBO user) throws SQLException {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql = "insert into T_SCS_USER(" + "ID,ACCOUNT,PWD,NAME," + "DEPT_ID,ROLE_ID,EMAIL,PHONE,"
            + "MOBILE,FAX,POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID,"
            + "CREATE_DT,LASTUPDATE_DT,COMP_ID) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    try {//from   w ww  .j  a v  a  2  s.  c o m
        this.getJdbcTemplate().update(new PreparedStatementCreator() {
            int i = 1;

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setInt(i++, user.getId());
                ps.setString(i++, user.getAccount());
                ps.setString(i++, user.getPwd());
                ps.setString(i++, user.getName());
                ps.setInt(i++, user.getDeptId());
                ps.setInt(i++, user.getRoleId());
                ps.setString(i++, user.getEmail());
                ps.setString(i++, user.getPhone());
                ps.setString(i++, user.getMobile());
                ps.setString(i++, user.getFax());
                ps.setString(i++, user.getPosition());
                ps.setInt(i++, user.getState());
                ps.setString(i++, user.getComment());
                ps.setString(i++, user.getCheckCode());
                ps.setInt(i++, user.getIsAutoApprove());
                ps.setInt(i++, user.getCreatorUserId());
                ps.setTimestamp(i++, new Timestamp(user.getCreateDt().getTime()));
                //update by CQ
                ps.setTimestamp(i++, new Timestamp(user.getLastupdateDt().getTime()));
                ps.setInt(i++, user.getCompId());
                return ps;
            }
        }, keyHolder);
    } catch (Exception e) {
        throw new SQLException("??" + user.getComment() + " ID"
                + user.getCreatorUserId() + " " + user.getCreateDt() + " "
                + e.getMessage());
    }
    return keyHolder.getKey().intValue();
}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

public DepositWithdrawal createDepositOrWithdrawal(int user_id, DepositWithdrawal.OperationType type,
        long amount) throws SQLException {
    Connection connection = getConnection();
    PreparedStatement statement = null;
    PreparedStatement statementAccount = null;

    DepositWithdrawal operation = new DepositWithdrawal();
    try {/*from   w w w .  j  av a  2 s  . c  om*/
        statement = connection.prepareStatement(CREATE_ACCOUNTOPERATIONS_STATEMENT);
        connection.setAutoCommit(false);

        statement.setInt(1, user_id);
        int typeOperation = ACCOUNT_OPERATION_DEPOSIT;
        if (type == OperationType.WITHDRAWAL) {
            typeOperation = ACCOUNT_OPERATION_WITHDRAWAL;
        }
        statement.setInt(2, typeOperation);

        statement.setLong(3, amount);
        Date now = new Date();
        java.sql.Timestamp sqlDate = new java.sql.Timestamp(now.getTime());
        statement.setTimestamp(4, sqlDate);
        statement.setNull(5, Types.INTEGER);
        statement.setNull(6, Types.INTEGER);

        statement.execute();
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()) {
            operation.setId(rs.getInt(1));
            operation.setAmount(amount);
            operation.setDate(now);
            operation.setType(type);
        }
        Account account = getAccount(user_id);
        long balanceToSet = 0L;
        if (type == OperationType.DEPOSIT) {
            balanceToSet = account.getBalance() + amount;
        } else {
            balanceToSet = account.getBalance() - amount;
        }
        if (balanceToSet < 0) {
            throw new SQLException("Balance cannot become negative");
        }
        statementAccount = connection.prepareStatement(UPDATE_ACCOUNT_BY_ID_STATEMENT);
        statementAccount.setLong(1, balanceToSet);
        statementAccount.setInt(2, user_id);
        statementAccount.execute();

        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    return operation;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaDropDao.java

/**
 * Populate the rivers_droplets table/*from  w w  w.j a v  a 2s.c  om*/
 * 
 * @param drops
 */
private void insertRiverDrops(final List<Drop> drops) {

    // Get a lock on rivers_droplets
    Sequence seq = sequenceDao.findById("rivers_droplets");

    // Mapping of drop id to list index position
    final Map<Long, Integer> dropIndex = new HashMap<Long, Integer>();

    // List of rivers in a drop
    Map<Long, Set<Long>> dropRiversMap = new HashMap<Long, Set<Long>>();
    Map<Long, Set<Long>> dropChannelsMap = new HashMap<Long, Set<Long>>();

    // Registry for all channels and rivers
    Set<Long> allChannelIds = new HashSet<Long>();

    int i = 0;
    for (Drop drop : drops) {
        if (drop.getRiverIds() == null || drop.getChannelIds() == null) {
            logger.debug("No rivers or channels for drop {}", drop.getId());
            continue;
        }

        Set<Long> rivers = new HashSet<Long>();
        Set<Long> channels = new HashSet<Long>();

        rivers.addAll(drop.getRiverIds());
        channels.addAll(drop.getChannelIds());

        dropRiversMap.put(drop.getId(), rivers);
        dropChannelsMap.put(drop.getId(), channels);

        allChannelIds.addAll(channels);

        dropIndex.put(drop.getId(), i++);
    }

    // No rivers found, exit
    if (dropIndex.size() == 0)
        return;

    // Find already existing rivers_droplets
    String sql = "SELECT droplet_id, river_id FROM rivers_droplets WHERE droplet_id in (:ids)";

    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ids", dropIndex.keySet());

    List<Map<String, Object>> results = this.namedJdbcTemplate.queryForList(sql, params);

    logger.debug("Skipping {} entries from rivers_droplets", results.size());

    // Remove existing rivers_droplets entries from our Set
    for (Map<String, Object> row : results) {
        Long dropletId = ((Number) row.get("droplet_id")).longValue();
        Long riverId = ((Number) row.get("river_id")).longValue();

        Set<Long> riverSet = dropRiversMap.remove(dropletId);
        if (riverSet != null) {
            riverSet.remove(riverId);

            // Only add back the destination rivers if the set is non empty
            if (!riverSet.isEmpty()) {
                dropRiversMap.put(dropletId, riverSet);
            }
        }
    }

    // If all drops are duplicates, return early
    if (dropRiversMap.isEmpty()) {
        logger.info("No drops to add to the rivers");
        return;
    }

    // Associate the channels with active rivers
    sql = "SELECT rc.id, rc.river_id " + "FROM river_channels rc "
            + "INNER JOIN rivers r ON (rc.river_id = r.id) " + "WHERE rc.id IN (:channelIds) "
            + "AND r.river_active = 1";
    MapSqlParameterSource channelParams = new MapSqlParameterSource();
    channelParams.addValue("channelIds", allChannelIds);

    Map<Long, Long> riverChannelsMap = new HashMap<Long, Long>();
    for (Map<String, Object> row : namedJdbcTemplate.queryForList(sql, channelParams)) {

        Long channelId = ((Number) row.get("id")).longValue();
        Long riverId = ((Number) row.get("river_id")).longValue();

        riverChannelsMap.put(channelId, riverId);
    }

    // Map to hold the association between a drop, river and channel
    // During the association, we verify that the river is in the drop's
    // destination river list
    final List<Map<String, Long>> riverDropChannelList = new ArrayList<Map<String, Long>>();
    Set<RiverDropKey> riverDropKeySet = new HashSet<JpaDropDao.RiverDropKey>();
    for (Long dropletId : dropChannelsMap.keySet()) {
        for (Long channelId : dropChannelsMap.get(dropletId)) {
            if (riverChannelsMap.containsKey(channelId)) {
                Long riverId = riverChannelsMap.get(channelId);

                // Does the river drop key already exist? 
                RiverDropKey riverDropKey = new RiverDropKey(riverId, dropletId);
                if (riverDropKeySet.contains(riverDropKey))
                    continue;

                // Does not exist. Add to the in-memory registry
                riverDropKeySet.add(riverDropKey);

                if (dropRiversMap.containsKey(dropletId) && dropRiversMap.get(dropletId).contains(riverId)) {
                    Map<String, Long> entry = new HashMap<String, Long>();
                    entry.put("dropletId", dropletId);
                    entry.put("channelId", channelId);
                    entry.put("riverId", riverId);
                    riverDropChannelList.add(entry);
                }
            }
        }
    }

    logger.debug("Posting drops to rivers");

    // Insert the remaining items in the set into the DB
    sql = "INSERT INTO `rivers_droplets` (`id`, `droplet_id`, `river_id`, "
            + "`river_channel_id`, `droplet_date_pub`) " + "VALUES (?, ?, ?, ?, ?)";

    final long startKey = sequenceDao.getIds(seq, riverDropChannelList.size());

    // Map to hold to hold the no. of drops created per channel
    final Map<Long, Long> channelDropCountMap = new HashMap<Long, Long>();

    // A map to hold the new max_drop_id and drop_count per river
    final Map<Long, long[]> riverDropsMap = new HashMap<Long, long[]>();
    jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Map<String, Long> dropEntry = riverDropChannelList.get(i);
            long id = startKey + i;

            Long dropletId = dropEntry.get("dropletId");
            Long riverId = dropEntry.get("riverId");
            Long channelId = dropEntry.get("channelId");
            Drop drop = drops.get(dropIndex.get(dropletId));

            ps.setLong(1, id);
            ps.setLong(2, dropletId);
            ps.setLong(3, riverId);
            ps.setLong(4, channelId);
            ps.setTimestamp(5, new java.sql.Timestamp(drop.getDatePublished().getTime()));

            // Get updated max_drop_id and drop_count for the rivers table
            long[] update = riverDropsMap.get(riverId);
            if (update == null) {
                long[] u = { id, 1 };
                riverDropsMap.put(riverId, u);
            } else {
                update[0] = Math.max(update[0], id);
                update[1] = update[1] + 1;
            }

            // Update the drop count for the channel
            Long channelDropCount = channelDropCountMap.remove(channelId);
            channelDropCount = (channelDropCount == null) ? 1L : Long.valueOf(channelDropCount.longValue() + 1);
            channelDropCountMap.put(channelId, channelDropCount);
        }

        public int getBatchSize() {
            return riverDropChannelList.size();
        }
    });
    logger.debug("Drops successfully posted to rivers");

    // Update river max_drop_id and drop_count
    logger.debug("Updating river drop counters");
    sql = "UPDATE rivers SET max_drop_id = ?, drop_count = drop_count + ? WHERE id = ?";
    final List<Entry<Long, long[]>> riverUpdate = new ArrayList<Entry<Long, long[]>>();
    riverUpdate.addAll(riverDropsMap.entrySet());

    this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Entry<Long, long[]> entry = riverUpdate.get(i);
            ps.setLong(1, entry.getValue()[0]);
            ps.setLong(2, entry.getValue()[1]);
            ps.setLong(3, entry.getKey());
        }

        public int getBatchSize() {
            return riverUpdate.size();
        }
    });
    logger.debug("{} rivers successfully updated", riverUpdate.size());

    // Update the drop_count in TABLE `river_channels`
    logger.debug("Updating river channel statistics");
    sql = "UPDATE river_channels SET drop_count = drop_count + ? WHERE id = ?";
    final List<Entry<Long, Long>> riverChannelUpdate = new ArrayList<Entry<Long, Long>>();
    riverChannelUpdate.addAll(channelDropCountMap.entrySet());

    this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Entry<Long, Long> entry = riverChannelUpdate.get(i);
            ps.setLong(1, entry.getValue());
            ps.setLong(2, entry.getKey());
        }

        @Override
        public int getBatchSize() {
            return riverChannelUpdate.size();
        }
    });
    logger.debug("{} channels updated", riverChannelUpdate.size());

    // Insert the trend data
    logger.debug("Updating trend statistics");
    try {
        insertRiverTagTrends(drops, dropIndex, riverDropChannelList);
    } catch (Exception e) {
        logger.error("An error occurred while inserting the trend data", e);
    }

}

From source file:edu.umd.cs.marmoset.modelClasses.Project.java

private int putValues(PreparedStatement stmt, int index) throws SQLException {
    stmt.setInt(index++, Course.asPK(getCoursePK()));
    stmt.setInt(index++, getTestSetupPK());
    stmt.setInt(index++, getDiffAgainst());
    stmt.setString(index++, getProjectNumber());
    stmt.setTimestamp(index++, getOntime());
    stmt.setTimestamp(index++, getLate());
    stmt.setString(index++, getTitle());
    stmt.setString(index++, getUrl());//from w  w w  .  j a v  a2 s .  c om
    stmt.setString(index++, getDescription());
    stmt.setInt(index++, getReleaseTokens());
    stmt.setInt(index++, getRegenerationTime());
    stmt.setBoolean(index++, isTested());
    stmt.setBoolean(index++, isPair());
    stmt.setBoolean(index++, getVisibleToStudents());
    stmt.setString(index++, getPostDeadlineOutcomeVisibility());
    stmt.setString(index++, getKindOfLatePenalty());
    stmt.setDouble(index++, getLateMultiplier());
    stmt.setInt(index++, getLateConstant());
    stmt.setInt(index++, getCanonicalStudentRegistrationPK());
    stmt.setString(index++, getBestSubmissionPolicy());
    stmt.setString(index++, getReleasePolicy());
    stmt.setString(index++, getStackTracePolicy());
    // Using -1 to represent infinity in the database
    if (getNumReleaseTestsRevealed() == Integer.MAX_VALUE)
        stmt.setInt(index++, -1);
    else
        stmt.setInt(index++, getNumReleaseTestsRevealed());
    SqlUtilities.setInteger(stmt, index++, getArchivePK());
    stmt.setString(index++, browserEditing.name().toLowerCase());
    return index;
}

From source file:com.commander4j.db.JDBUserReport.java

public boolean runReport() {
    PreparedStatement prepStatement;
    boolean result = true;

    try {//www  .  j  a v a 2 s. c o m
        prepStatement = Common.hostList.getHost(getHostID()).getConnection(getSessionID())
                .prepareStatement(getSQL(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        prepStatement.setFetchSize(25);

        if (isParamDateRequired()) {
            prepStatement.setTimestamp(1, getParamFromDate());
            prepStatement.setTimestamp(2, getParamToDate());
        }

        if (getDestination().equals("SYSTEM")) {
            for (int x = 0; x < systemParams.size(); x++) {
                String type = systemParams.get(x).parameterType;

                if (type.toLowerCase().equals("string")) {
                    prepStatement.setString(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterStringValue);
                }
                if (type.toLowerCase().equals("integer")) {
                    prepStatement.setInt(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterIntegerValue);
                }
                if (type.toLowerCase().equals("long")) {
                    prepStatement.setLong(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterLongValue);
                }
                if (type.toLowerCase().equals("timestamp")) {
                    prepStatement.setTimestamp(systemParams.get(x).parameterPosition,
                            systemParams.get(x).parameterTimestampValue);
                }
            }
        }

        ResultSet tempResult = prepStatement.executeQuery();

        boolean dataReturned = true;
        if (!tempResult.next()) {
            dataReturned = false;
        }
        tempResult.beforeFirst();
        if (dataReturned) {
            if (getDestination().equals("EXCEL")) {
                generateExcel(tempResult);
            }

            if (getDestination().equals("JASPER_REPORTS")) {
                generateJasper(prepStatement);
            }
            if (getDestination().equals("PDF")) {
                generatePDF(prepStatement);
            }
            if (getDestination().equals("ACCESS")) {
                generateAccess(tempResult);
            }

            if (getDestination().equals("CSV")) {
                generateCSV(tempResult);
            }

            if (getDestination().equals("SYSTEM")) {
                generateSYSTEM(tempResult);
            }

            if (isPreviewRequired()) {
                try {
                    Desktop.getDesktop().open(new File(getExportFilename()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (isEmailEnabled()) {

                String emailaddresses = getEmailAddresses();

                if (isEmailPromptEnabled()) {
                    emailaddresses = JUtility.replaceNullStringwithBlank(
                            JOptionPane.showInputDialog(lang.get("lbl_Email_Addresses")));
                }

                StringConverter stringConverter = new StringConverter();
                ArrayConverter arrayConverter = new ArrayConverter(String[].class, stringConverter);
                arrayConverter.setDelimiter(';');
                arrayConverter.setAllowedChars(new char[] { '@', '_' });

                String[] emailList = (String[]) arrayConverter.convert(String[].class, emailaddresses);

                if (emailList.length > 0) {
                    String shortFilename = JUtility.getFilenameFromPath(getExportFilename());
                    mail.postMail(emailList,
                            "Commande4j User Report requested by "
                                    + Common.userList.getUser(Common.sessionID).getUserId() + " from ["
                                    + Common.hostList.getHost(getHostID()).getSiteDescription() + "] on "
                                    + JUtility.getClientName(),
                            "See attached report.\n", shortFilename, getExportFilename());
                    com.commander4j.util.JWait.milliSec(2000);
                }
            }

        } else {
            result = false;
            setErrorMessage("No data returned by query.");
        }

    } catch (Exception ex) {
        setErrorMessage(ex.getMessage());
        result = false;
    }

    return result;
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void save(Penalty penalty) {
    String sql;//w w w.  j  a v a  2  s  .  c om
    if (penalty.getKey() == null) {
        sql = "insert into penalty (playerid, adminid, type, reason, duration, synced, active, created, updated, expires) values (?,?,?,?,?,?,?,?,?,?)";
    } else {
        sql = "update penalty set playerid = ?," + "adminid = ?," + "type = ?," + "reason = ?,"
                + "duration = ?," + "synced = ?," + "active = ?," + "created = ?," + "updated = ?,"
                + "expires = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setLong(1, penalty.getPlayer());
        if (penalty.getAdmin() != null)
            st.setLong(2, penalty.getAdmin());
        else
            st.setNull(2, Types.INTEGER);
        st.setInt(3, penalty.getType().intValue());
        if (penalty.getReason() != null)
            st.setString(4, penalty.getReason());
        else
            st.setNull(4, Types.VARCHAR);
        if (penalty.getDuration() == null)
            penalty.setDuration(0L);
        st.setLong(5, penalty.getDuration());
        st.setBoolean(6, penalty.getSynced());
        st.setBoolean(7, penalty.getActive());
        if (penalty.getCreated() == null)
            penalty.setCreated(new Date());
        if (penalty.getUpdated() == null)
            penalty.setUpdated(new Date());
        st.setTimestamp(8, new java.sql.Timestamp(penalty.getCreated().getTime()));
        st.setTimestamp(9, new java.sql.Timestamp(penalty.getUpdated().getTime()));
        st.setTimestamp(10, new java.sql.Timestamp(
                DateUtils.addMinutes(penalty.getCreated(), penalty.getDuration().intValue()).getTime()));
        if (penalty.getKey() != null)
            st.setLong(11, penalty.getKey());
        st.executeUpdate();
        if (penalty.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                penalty.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for penalty player id {}", penalty.getPlayer());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}