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.flexive.ejb.beans.ScriptingEngineBean.java

/**
* {@inheritDoc}/*from   w  w w .  j av  a  2s  .  com*/
* @since 3.1.2
*/
@Override
public FxScriptSchedule updateScriptSchedule(FxScriptScheduleEdit scriptSchedule)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptExecution);
    FxScriptSchedule ss;
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    //check script schedule existence
    CacheAdmin.getEnvironment().getScriptSchedule(scriptSchedule.getId());
    //check script existence
    FxScriptInfo si = CacheAdmin.getEnvironment().getScript(scriptSchedule.getScriptId());
    //check for valid script event
    if (si.getEvent() != FxScriptEvent.Manual)
        throw new FxConstraintViolationException("ex.scripting.schedule.wrongScriptEvent");
    //check consistency
    checkScriptScheduleConsistency(scriptSchedule);
    try {
        ss = new FxScriptSchedule(scriptSchedule.getId(), scriptSchedule.getScriptId(),
                scriptSchedule.getName(), scriptSchedule.isActive(), scriptSchedule.getStartTime(),
                scriptSchedule.getEndTime(), scriptSchedule.getRepeatInterval(),
                scriptSchedule.getRepeatTimes(), scriptSchedule.getCronString());
        // Obtain a database connection
        con = Database.getDbConnection(); //        1        2          3            4            5                 6            7               8         9
        sql = "UPDATE " + TBL_SCRIPT_SCHEDULES
                + " SET SNAME=?, ACTIVE=?, STARTTIME=?, ENDTIME=?, REPEATINTERVAL=?, REPEATTIMES=?, CRONSTRING=? WHERE ID=? AND SCRIPT=?";
        ps = con.prepareStatement(sql);
        ps.setString(1, ss.getName());
        ps.setBoolean(2, ss.isActive());
        ps.setTimestamp(3, new Timestamp(ss.getStartTime().getTime()));
        ps.setTimestamp(4, ss.getEndTime() == null ? null : new Timestamp(ss.getEndTime().getTime()));
        ps.setLong(5, ss.getRepeatInterval());
        ps.setInt(6, ss.getRepeatTimes());
        ps.setString(7, ss.getCronString());
        ps.setLong(8, ss.getId());
        ps.setLong(9, ss.getScriptId());
        ps.executeUpdate();
        if (EJBLookup.getTimerService().isInstalled()) {
            EJBLookup.getTimerService().updateScriptSchedule(ss);
        }
        success = true;
    } catch (SQLException exc) {
        throw new FxUpdateException(LOG, exc, "ex.scripting.schedule.update.failed", scriptSchedule.getName(),
                exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
    return ss;
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

@Override
public List<String> findRefusedEventsKeys(ObmUser calendarUser, Date d) {
    List<Integer> result = new LinkedList<Integer>();
    Connection con = null;/*from  w ww  . j  a v a2  s.co  m*/
    PreparedStatement ps = null;
    ResultSet rs = null;

    String q = "SELECT eventlink_event_id FROM EventLink, UserEntity WHERE "
            + "eventlink_state='DECLINED' AND eventlink_entity_id=userentity_entity_id AND userentity_user_id=? ";
    if (d != null) {
        q += "AND eventlink_timeupdate >= ?";
    }
    try {
        con = obmHelper.getConnection();
        ps = con.prepareStatement(q);
        ps.setInt(1, calendarUser.getUid());
        if (d != null) {
            ps.setTimestamp(2, new Timestamp(d.getTime()));
        }

        rs = ps.executeQuery();
        while (rs.next()) {
            result.add(rs.getInt(1));
        }
    } catch (SQLException se) {
        logger.error(se.getMessage(), se);
    } finally {
        obmHelper.cleanup(con, ps, rs);
    }

    List<String> ret = new ArrayList<String>(result.size());
    for (Integer eid : result) {
        ret.add(eid.toString());
    }
    return ret;
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void insertConnectorMessage(ConnectorMessage connectorMessage, boolean storeMaps, boolean updateStats) {
    logger.debug(connectorMessage.getChannelId() + "/" + connectorMessage.getMessageId() + "/"
            + connectorMessage.getMetaDataId() + ": inserting connector message with" + (storeMaps ? "" : "out")
            + " maps");

    try {/*from w  w w  .  jav  a 2  s  . co  m*/
        PreparedStatement statement = prepareStatement("insertConnectorMessage",
                connectorMessage.getChannelId());
        statement.setInt(1, connectorMessage.getMetaDataId());
        statement.setLong(2, connectorMessage.getMessageId());
        statement.setString(3, connectorMessage.getServerId());
        statement.setTimestamp(4, new Timestamp(connectorMessage.getReceivedDate().getTimeInMillis()));
        statement.setString(5, Character.toString(connectorMessage.getStatus().getStatusCode()));

        if (connectorMessage.getConnectorName() == null) {
            statement.setNull(6, Types.VARCHAR);
        } else {
            statement.setString(6, connectorMessage.getConnectorName());
        }

        statement.setInt(7, connectorMessage.getSendAttempts());

        if (connectorMessage.getSendDate() == null) {
            statement.setNull(8, Types.TIMESTAMP);
        } else {
            statement.setTimestamp(8, new Timestamp(connectorMessage.getSendDate().getTimeInMillis()));
        }

        if (connectorMessage.getResponseDate() == null) {
            statement.setNull(9, Types.TIMESTAMP);
        } else {
            statement.setTimestamp(9, new Timestamp(connectorMessage.getResponseDate().getTimeInMillis()));
        }

        statement.setInt(10, connectorMessage.getErrorCode());
        statement.setInt(11, connectorMessage.getChainId());
        statement.setInt(12, connectorMessage.getOrderId());
        statement.executeUpdate();

        if (storeMaps) {
            updateSourceMap(connectorMessage);
            updateMaps(connectorMessage);
        }

        updateErrors(connectorMessage);

        if (updateStats) {
            transactionStats.update(connectorMessage.getChannelId(), connectorMessage.getMetaDataId(),
                    connectorMessage.getStatus(), null);
        }
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:com.flexive.ejb.beans.ScriptingEngineBean.java

/**
* {@inheritDoc}// ww w  .  j  av  a 2 s  . co  m
* @since 3.1.2
*/
@Override
public FxScriptSchedule createScriptSchedule(FxScriptScheduleEdit scriptSchedule)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptManagement);
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.ScriptExecution);
    FxScriptSchedule ss;
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    boolean success = false;
    //check script existence
    FxScriptInfo si = CacheAdmin.getEnvironment().getScript(scriptSchedule.getScriptId());
    //check for valid script event
    if (si.getEvent() != FxScriptEvent.Manual)
        throw new FxConstraintViolationException("ex.scripting.schedule.wrongScriptEvent");
    //check consistency
    checkScriptScheduleConsistency(scriptSchedule);
    try {
        // for groovy scripts set cached flag to true
        ss = new FxScriptSchedule(seq.getId(FxSystemSequencer.SCRIPTS), scriptSchedule.getScriptId(),
                scriptSchedule.getName(), scriptSchedule.isActive(), scriptSchedule.getStartTime(),
                scriptSchedule.getEndTime(), scriptSchedule.getRepeatInterval(),
                scriptSchedule.getRepeatTimes(), scriptSchedule.getCronString());

        // Obtain a database connection
        con = Database.getDbConnection();
        //                                                1   2      3     4       5         6        7               8          9
        sql = "INSERT INTO " + TBL_SCRIPT_SCHEDULES
                + " (ID,SCRIPT,SNAME,ACTIVE,STARTTIME,ENDTIME,REPEATINTERVAL,REPEATTIMES,CRONSTRING) VALUES (?,?,?,?,?,?,?,?,?)";
        ps = con.prepareStatement(sql);
        ps.setLong(1, ss.getId());
        ps.setLong(2, ss.getScriptId());
        ps.setString(3, ss.getName());
        ps.setBoolean(4, ss.isActive());
        ps.setTimestamp(5, new Timestamp(ss.getStartTime().getTime()));
        ps.setTimestamp(6, ss.getEndTime() == null ? null : new Timestamp(ss.getEndTime().getTime()));
        ps.setLong(7, ss.getRepeatInterval());
        ps.setInt(8, ss.getRepeatTimes());
        ps.setString(9, ss.getCronString());
        ps.executeUpdate();
        if (EJBLookup.getTimerService().isInstalled()) {
            EJBLookup.getTimerService().scheduleScript(ss);
        }
        success = true;
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.scripting.schedule.create.failed", scriptSchedule.getName(),
                exc.getMessage());
    } finally {
        Database.closeObjects(ScriptingEngineBean.class, con, ps);
        if (!success)
            EJBUtils.rollback(ctx);
        else
            StructureLoader.reloadScripting(FxContext.get().getDivisionId());
    }
    return ss;
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void update(final Verblijfsobject verblijfsobject) throws DAOException {
    try {/*w  w w  .  j  av a 2s.  co m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("update bag_verblijfsobject set"
                                + " aanduiding_record_inactief = ?," + " officieel = ?,"
                                + " verblijfsobject_geometrie = ?," + " oppervlakte_verblijfsobject = ?,"
                                + " verblijfsobject_status = ?," + " einddatum_tijdvak_geldigheid = ?,"
                                + " in_onderzoek = ?," + " bron_documentdatum = ?,"
                                + " bron_documentnummer = ?," + " bag_nummeraanduiding_id = ?"
                                + " where bag_verblijfsobject_id = ?" + " and aanduiding_record_correctie = ?"
                                + " and begindatum_tijdvak_geldigheid = ?");
                        ps.setInt(1, verblijfsobject.getAanduidingRecordInactief().ordinal());
                        ps.setInt(2, verblijfsobject.getOfficieel().ordinal());
                        ps.setString(3, verblijfsobject.getVerblijfsobjectGeometrie());
                        ps.setInt(4, verblijfsobject.getOppervlakteVerblijfsobject());
                        ps.setInt(5, verblijfsobject.getVerblijfsobjectStatus().ordinal());
                        if (verblijfsobject.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(6, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(6,
                                    new Timestamp(verblijfsobject.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(7, verblijfsobject.getInOnderzoek().ordinal());
                        ps.setDate(8, new Date(verblijfsobject.getDocumentdatum().getTime()));
                        ps.setString(9, verblijfsobject.getDocumentnummer());
                        ps.setLong(10, verblijfsobject.getHoofdAdres());
                        ps.setLong(11, verblijfsobject.getIdentificatie());
                        ps.setLong(12, verblijfsobject.getAanduidingRecordCorrectie());
                        ps.setTimestamp(13,
                                new Timestamp(verblijfsobject.getBegindatumTijdvakGeldigheid().getTime()));
                        return ps;
                    }
                });
                deleteGebruikersdoelen(verblijfsobject);
                insertGebruikersdoelen(verblijfsobject);
                deleteNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject);
                insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject);
                deleteGerelateerdePanden(verblijfsobject);
                insertGerelateerdePanden(verblijfsobject);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error updating verblijfsobject: " + verblijfsobject.getIdentificatie(), e);
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

private List<DeletedEvent> findDeletedEvents(ObmUser calendarUser, Date d, EventType eventType,
        List<DeletedEvent> declined) {

    List<DeletedEvent> result = new LinkedList<DeletedEvent>();
    result.addAll(declined);//from   www  . j  a  v a2 s .co m
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String q = "SELECT deletedevent_event_id, deletedevent_event_ext_id FROM DeletedEvent "
            + "WHERE deletedevent_user_id=? AND deletedevent_type=? ";
    if (d != null) {
        q += "AND deletedevent_timestamp >= ?";
    }
    try {
        con = obmHelper.getConnection();
        ps = con.prepareStatement(q);
        ps.setInt(1, calendarUser.getUid());
        ps.setObject(2, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, eventType.toString()));
        if (d != null) {
            ps.setTimestamp(3, new Timestamp(d.getTime()));
        }

        rs = ps.executeQuery();
        while (rs.next()) {
            result.add(DeletedEvent.builder().eventObmId(rs.getInt(1)).eventExtId(rs.getString(2)).build());
        }
    } catch (SQLException se) {
        logger.error(se.getMessage(), se);
    } finally {
        obmHelper.cleanup(con, ps, rs);
    }

    return result;
}

From source file:net.unicon.mercury.fac.rdbms.RdbmsMessageFactory.java

/**
 * Creates a message and sends it to all of the provided recipients.
 * The message is returned to the caller.
 *
 * @param conn         connection to the data source.
 * @param recipients   users that the message will be sent to. Must not
 *                     contain any null elements.
 * @param subject      message subject//  w w w .jav a 2  s .  c o  m
 * @param body         message content
 * @param attachments  attachments to the message. May be null.
 * @return             the message that is created and sent.
 * @throws MercuryException
 * @see net.unicon.mercury.IMessageFactory#sendMessage(IRecipient[],
 *                                         String, String, IAttachment[])
 */
public IMessage sendMessage(IRecipient[] recipients, String subject, String body, IAttachment[] attachments,
        Priority priority) throws MercuryException {

    // Assertions
    if (recipients == null) {
        throw new IllegalArgumentException("Argument 'recipients' cannot be null.");
    }
    if (subject == null) {
        throw new IllegalArgumentException("Argument 'subject' cannot be null.");
    }
    if (body == null) {
        throw new IllegalArgumentException("Argument 'body' cannot be null.");
    }
    // attachments can be null.

    IMessage rslt = null;
    Connection conn = null;
    PreparedStatement pstmt = null;
    ConnState connst = null;
    Set sentSet = new HashSet();

    try {
        Calendar cal = Calendar.getInstance();

        rslt = createMessage(this, String.valueOf(getMessageSequencer().next()), subject, this.owner,
                recipients, cal.getTime(), body, priority, false);

        if (attachments != null && attachments.length > 0) {
            sendAttachments(attachments, rslt.getId());
        }

        // Setup connection
        conn = dataSource.getConnection();
        connst = beginTransaction(conn);

        // Add message
        pstmt = conn.prepareStatement(qm.getQuery("SEND_MESSAGE"));

        // Set all parameters
        pstmt.setLong(1, Long.parseLong(rslt.getId()));
        pstmt.setString(2, rslt.getSender().toNativeFormat());
        pstmt.setString(3, rslt.getSubject());
        pstmt.setTimestamp(4, new Timestamp(rslt.getDate().getTime()));
        pstmt.setString(5, rslt.getBody());
        pstmt.setInt(6, priority.toInt());
        if (expiration > 0) {
            cal.add(Calendar.DATE, expiration);
            pstmt.setTimestamp(7, new Timestamp(cal.getTime().getTime()));
        } else {
            pstmt.setTimestamp(7, null);
        }

        pstmt.executeUpdate(); // Message added, not committed

        // Clear resources for reuse
        closeStatement(pstmt);
        pstmt = null;

        // For sender, and each recipient, add a "copy" of the
        // message into dispatch table

        pstmt = conn.prepareStatement(qm.getQuery("DISPATCH_MESSAGE"));

        // Set parameters for sender
        pstmt.setLong(1, Long.parseLong(rslt.getId()));
        pstmt.setString(2, rslt.getSender().toNativeFormat());
        pstmt.setInt(3, RdbmsDispatchType.SENDER.toInt());
        pstmt.setNull(4, Types.INTEGER); // Recipient type has no meaning
        pstmt.setString(5, UNREAD); // Unread to start
        pstmt.setInt(6, (int) SpecialFolder.OUTBOX_VALUE); // Place it in sender's outbox

        pstmt.executeUpdate(); // Sender added, not committed

        // Then create each recipients copy
        pstmt.setLong(1, Long.parseLong(rslt.getId()));
        pstmt.setInt(3, RdbmsDispatchType.RECEIVER.toInt());
        pstmt.setString(5, UNREAD); // Unread to start
        pstmt.setInt(6, (int) SpecialFolder.INBOX_VALUE);
        for (int i = 0; i < recipients.length; i++) {

            // Assertions
            if (recipients[i] == null) {
                String msg = "Argument 'recipients [IRecipient[]]' " + "cannot contain null elements.";
                throw new IllegalArgumentException(msg);
            }

            if (!sentSet.add(recipients[i])) {
                continue;
            }

            IRecipientType rType = recipients[i].getType();
            if (!(rType instanceof RdbmsRecipientType)) {
                rType = RdbmsRecipientType.getType(rType.getLabel());
            }
            pstmt.setString(2, recipients[i].getAddress().toNativeFormat());
            pstmt.setInt(4, ((RdbmsRecipientType) rType).toInt());
            pstmt.executeUpdate(); // Recipient added, not committed
        }

        // Finally commit transaction
        conn.commit();

    } catch (Exception t) {
        rollBack(conn); // Message not added, nor any recipients if any fail
        String msg = "RdbmsMessageFactory was not able to send message: " + t.getMessage();
        log.error(msg, t);
        throw new MercuryException(msg, t);
    } finally {
        closeStatement(pstmt);
        pstmt = null;
        cleanupTransactionConnection(conn, connst);
        conn = null;
    }

    return rslt;
}

From source file:org.ohmage.query.impl.SurveyUploadQuery.java

@Override
public List<Integer> insertSurveys(final String username, final String client, final String campaignUrn,
        final List<SurveyResponse> surveyUploadList, final Map<UUID, Image> bufferedImageMap,
        final Map<String, Video> videoContentsMap, final Map<String, Audio> audioContentsMap)
        throws DataAccessException {

    List<Integer> duplicateIndexList = new ArrayList<Integer>();
    int numberOfSurveys = surveyUploadList.size();

    // The following variables are used in logging messages when errors occur
    SurveyResponse currentSurveyResponse = null;
    PromptResponse currentPromptResponse = null;
    String currentSql = null;/*from   ww  w.  j  a  v a 2 s  .c  om*/

    List<File> fileList = new LinkedList<File>();

    // Wrap all of the inserts in a transaction 
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("survey upload");
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
    TransactionStatus status = transactionManager.getTransaction(def); // begin transaction

    // Use a savepoint to handle nested rollbacks if duplicates are found
    Object savepoint = status.createSavepoint();

    try { // handle TransactionExceptions

        for (int surveyIndex = 0; surveyIndex < numberOfSurveys; surveyIndex++) {

            try { // handle DataAccessExceptions

                final SurveyResponse surveyUpload = surveyUploadList.get(surveyIndex);
                currentSurveyResponse = surveyUpload;
                currentSql = SQL_INSERT_SURVEY_RESPONSE;

                KeyHolder idKeyHolder = new GeneratedKeyHolder();

                // First, insert the survey
                getJdbcTemplate().update(new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(SQL_INSERT_SURVEY_RESPONSE,
                                Statement.RETURN_GENERATED_KEYS);

                        String locationString = null;
                        Location location = surveyUpload.getLocation();
                        if (location != null) {
                            try {
                                locationString = location.toJson(false, LocationColumnKey.ALL_COLUMNS)
                                        .toString();
                            } catch (JSONException e) {
                                throw new SQLException(e);
                            } catch (DomainException e) {
                                throw new SQLException(e);
                            }
                        }

                        ps.setString(1, surveyUpload.getSurveyResponseId().toString());
                        ps.setString(2, username);
                        ps.setString(3, campaignUrn);
                        ps.setLong(4, surveyUpload.getTime());
                        ps.setString(5, surveyUpload.getTimezone().getID());
                        ps.setString(6, surveyUpload.getLocationStatus().toString());
                        ps.setString(7, locationString);
                        ps.setString(8, surveyUpload.getSurvey().getId());
                        try {
                            ps.setString(9,
                                    surveyUpload
                                            .toJson(false, false, false, false, true, true, true, true, true,
                                                    false, false, true, true, true, true, false, false)
                                            .toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        } catch (DomainException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        ps.setString(10, client);
                        ps.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
                        try {
                            ps.setString(12, surveyUpload.getLaunchContext().toJson(true).toString());
                        } catch (JSONException e) {
                            throw new SQLException("Couldn't create the JSON.", e);
                        }
                        try {
                            ps.setString(13, PreferenceCache.instance()
                                    .lookup(PreferenceCache.KEY_DEFAULT_SURVEY_RESPONSE_SHARING_STATE));
                        } catch (CacheMissException e) {
                            throw new SQLException("Error reading from the cache.", e);
                        }
                        return ps;
                    }
                }, idKeyHolder);

                savepoint = status.createSavepoint();

                final Number surveyResponseId = idKeyHolder.getKey(); // the primary key on the survey_response table for the 
                                                                      // just-inserted survey
                currentSql = SQL_INSERT_PROMPT_RESPONSE;

                // Now insert each prompt response from the survey
                Collection<Response> promptUploadList = surveyUpload.getResponses().values();

                createPromptResponse(username, client, surveyResponseId, fileList, promptUploadList, null,
                        bufferedImageMap, videoContentsMap, audioContentsMap, transactionManager, status);

            } catch (DataIntegrityViolationException dive) { // a unique index exists only on the survey_response table

                if (isDuplicate(dive)) {

                    LOGGER.debug("Found a duplicate survey upload message for user " + username);

                    duplicateIndexList.add(surveyIndex);
                    status.rollbackToSavepoint(savepoint);

                } else {

                    // Some other integrity violation occurred - bad!! All 
                    // of the data to be inserted must be validated before 
                    // this query runs so there is either missing validation 
                    // or somehow an auto_incremented key has been duplicated.

                    LOGGER.error("Caught DataAccessException", dive);
                    logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                            campaignUrn);
                    for (File f : fileList) {
                        f.delete();
                    }
                    rollback(transactionManager, status);
                    throw new DataAccessException(dive);
                }

            } catch (org.springframework.dao.DataAccessException dae) {

                // Some other database problem happened that prevented
                // the SQL from completing normally.

                LOGGER.error("caught DataAccessException", dae);
                logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username,
                        campaignUrn);
                for (File f : fileList) {
                    f.delete();
                }
                rollback(transactionManager, status);
                throw new DataAccessException(dae);
            }

        }

        // Finally, commit the transaction
        transactionManager.commit(status);
        LOGGER.info("Completed survey message persistence");
    }

    catch (TransactionException te) {

        LOGGER.error("failed to commit survey upload transaction, attempting to rollback", te);
        rollback(transactionManager, status);
        for (File f : fileList) {
            f.delete();
        }
        logErrorDetails(currentSurveyResponse, currentPromptResponse, currentSql, username, campaignUrn);
        throw new DataAccessException(te);
    }

    LOGGER.info(
            "Finished inserting survey responses and any associated images into the database and the filesystem.");
    return duplicateIndexList;
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

@Override
public List<Event> listEventsByIntervalDate(final AccessToken token, final ObmUser obmUser,
        final Date startDate, final Date endDate, final EventType typeFilter) {

    final String sql = "SELECT " + EVENT_SELECT_FIELDS + ", eventexception_date as recurrence_id "
            + " FROM Event e " + "INNER JOIN EventLink att ON att.eventlink_event_id=e.event_id "
            + "INNER JOIN UserEntity ue ON att.eventlink_entity_id=ue.userentity_entity_id "
            + "INNER JOIN EventEntity ON e.event_id=evententity_event_id "
            + "INNER JOIN UserObm o ON e.event_owner=o.userobm_id "
            + "INNER JOIN UserObm c ON e.event_usercreate=c.userobm_id "
            + "INNER JOIN Domain ON e.event_domain_id=domain_id "
            + "LEFT JOIN EventCategory1 ON e.event_category1_id=eventcategory1_id "
            + "LEFT JOIN EventException ON e.event_id = eventexception_child_id "
            + "WHERE e.event_type=? AND ue.userentity_user_id=? "
            + "AND ((event_repeatkind != 'none' AND event_endrepeat <= ?) OR "
            + "(event_repeatkind = 'none' AND event_date >= ? AND event_date <= ?) )";

    PreparedStatement evps = null;
    ResultSet evrs = null;/*  ww w  . j a  v  a  2 s.  c  om*/
    Connection con = null;

    final List<Event> changedEvent = new LinkedList<Event>();
    final Map<EventObmId, Event> eventById = new HashMap<EventObmId, Event>();
    final List<Event> ret = new LinkedList<Event>();
    final Calendar cal = getGMTCalendar();

    try {
        con = obmHelper.getConnection();
        evps = con.prepareStatement(sql);
        int idx = 1;
        evps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, typeFilter.toString()));
        evps.setObject(idx++, obmUser.getUid());
        evps.setTimestamp(idx++, new Timestamp(endDate.getTime()));
        evps.setTimestamp(idx++, new Timestamp(startDate.getTime()));
        evps.setTimestamp(idx++, new Timestamp(endDate.getTime()));
        evrs = evps.executeQuery();
        while (evrs.next()) {
            Event event = eventFromCursor(cal, evrs);
            Set<Date> extDate = getAllDateEventException(con, event.getObmId());
            Date recurDate = ical4jHelper.isInIntervalDate(event, startDate, endDate, extDate);
            if (recurDate != null) {
                eventById.put(event.getObmId(), event);
                changedEvent.add(event);
                ret.add(event);
            }
        }

        IntegerIndexedSQLCollectionHelper changedIds = new IntegerIndexedSQLCollectionHelper(changedEvent);
        loadAttendees(con, eventById, obmUser.getDomain().getName());
        loadAlerts(con, token, eventById, changedIds);
        loadExceptions(con, cal, eventById, changedIds);
        loadEventExceptions(con, token, eventById, changedIds);

    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
    } finally {
        obmHelper.cleanup(con, evps, evrs);
    }

    return ret;
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void update(final Verblijfsobject origineel, final Verblijfsobject mutation) throws DAOException {
    try {//ww  w .  j av  a2s .  co m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("update bag_verblijfsobject set"
                                + " aanduiding_record_inactief = ?," + " aanduiding_record_correctie = ?,"
                                + " officieel = ?," + " verblijfsobject_geometrie = ?,"
                                + " oppervlakte_verblijfsobject = ?," + " verblijfsobject_status = ?,"
                                + " einddatum_tijdvak_geldigheid = ?," + " in_onderzoek = ?,"
                                + " bron_documentdatum = ?," + " bron_documentnummer = ?,"
                                + " bag_nummeraanduiding_id = ?" + " where bag_verblijfsobject_id = ?"
                                + " and aanduiding_record_correctie = ?"
                                + " and begindatum_tijdvak_geldigheid = ?");
                        ps.setInt(1, mutation.getAanduidingRecordInactief().ordinal());
                        ps.setLong(2, mutation.getAanduidingRecordCorrectie());
                        ps.setInt(3, mutation.getOfficieel().ordinal());
                        ps.setString(4, mutation.getVerblijfsobjectGeometrie());
                        ps.setInt(5, mutation.getOppervlakteVerblijfsobject());
                        ps.setInt(6, mutation.getVerblijfsobjectStatus().ordinal());
                        if (mutation.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(7, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(7,
                                    new Timestamp(mutation.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(8, mutation.getInOnderzoek().ordinal());
                        ps.setDate(9, new Date(mutation.getDocumentdatum().getTime()));
                        ps.setString(10, mutation.getDocumentnummer());
                        ps.setLong(11, mutation.getHoofdAdres());
                        ps.setLong(12, origineel.getIdentificatie());
                        ps.setLong(13, origineel.getAanduidingRecordCorrectie());
                        ps.setTimestamp(14,
                                new Timestamp(origineel.getBegindatumTijdvakGeldigheid().getTime()));
                        return ps;
                    }
                });
                deleteGebruikersdoelen(origineel);
                insertGebruikersdoelen(mutation);
                deleteNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, origineel);
                insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, mutation);
                deleteGerelateerdePanden(origineel);
                insertGerelateerdePanden(mutation);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error updating verblijfsobject: " + origineel.getIdentificatie(), e);
    }
}