Example usage for org.hibernate Query setTimestamp

List of usage examples for org.hibernate Query setTimestamp

Introduction

In this page you can find the example usage for org.hibernate Query setTimestamp.

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setTimestamp(String name, Date value) 

Source Link

Document

Bind the value and the time of a given Date object to a named query parameter.

Usage

From source file:org.transitime.db.structs.AvlReport.java

License:Open Source License

/**
 * Gets list of AvlReports from database for the time span specified.
 * /* ww w  .  ja  v a2 s. co  m*/
 * @param beginTime
 * @param endTime
 * @param vehicleId
 *            Optional. If not null then will only return results for that
 *            vehicle
 * @param clause
 *             Optional. If not null then the clause, such as "ORDER BY time"
 * will be added to the hql statement.
 * @return List of AvlReports or null if an exception is thrown
 */
public static List<AvlReport> getAvlReportsFromDb(Date beginTime, Date endTime, String vehicleId,
        String clause) {
    // Sessions are not threadsafe so need to create a new one each time.
    // They are supposed to be lightweight so this should be OK.
    Session session = HibernateUtils.getSession();

    // Create the query. Table name is case sensitive!
    String hql = "FROM AvlReport " + "    WHERE time >= :beginDate " + "      AND time < :endDate";
    if (vehicleId != null)
        hql += " AND vehicleId=:vehicleId";
    if (clause != null)
        hql += " " + clause;
    Query query = session.createQuery(hql);

    // Set the parameters
    if (vehicleId != null)
        query.setString("vehicleId", vehicleId);
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    try {
        @SuppressWarnings("unchecked")
        List<AvlReport> avlReports = query.list();
        return avlReports;
    } catch (HibernateException e) {
        // Log error to the Core logger
        Core.getLogger().error(e.getMessage(), e);
        return null;
    } finally {
        // Clean things up. Not sure if this absolutely needed nor if
        // it might actually be detrimental and slow things down.
        session.close();
    }
}

From source file:org.transitime.db.structs.Match.java

License:Open Source License

/**
 * Allows batch retrieval of Match data from database. This is likely the
 * best way to read in large amounts of data.
 * /*from ww w.j ava2 s . com*/
 * @param projectId
 * @param beginTime
 * @param endTime
 * @param sqlClause
 *            The clause is added to the SQL for retrieving the
 *            arrival/departures. Useful for ordering the results. Can be
 *            null.
 * @param firstResult
 * @param maxResults
 * @return
 */
public static List<Match> getMatchesFromDb(String projectId, Date beginTime, Date endTime, String sqlClause,
        final int firstResult, final int maxResults) {
    IntervalTimer timer = new IntervalTimer();

    // Get the database session. This is supposed to be pretty light weight
    Session session = HibernateUtils.getSession(projectId);

    // Create the query. Table name is case sensitive and needs to be the
    // class name instead of the name of the db table.
    String hql = "FROM Match " + "    WHERE avlTime >= :beginDate " + "      AND avlTime < :endDate";
    if (sqlClause != null)
        hql += " " + sqlClause;
    Query query = session.createQuery(hql);

    // Set the parameters for the query
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    // Only get a batch of data at a time
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);

    try {
        @SuppressWarnings("unchecked")
        List<Match> matches = query.list();
        logger.debug("Getting matches from database took {} msec", timer.elapsedMsec());
        return matches;
    } catch (HibernateException e) {
        // Log error to the Core logger
        Core.getLogger().error(e.getMessage(), e);
        return null;
    } finally {
        // Clean things up. Not sure if this absolutely needed nor if
        // it might actually be detrimental and slow things down.
        session.close();
    }
}

From source file:org.transitime.db.structs.MonitoringEvent.java

License:Open Source License

/**
 * Reads in all MonitoringEvents from the database that were between the
 * beginTime and endTime.//from  w ww  .  j  a v a 2  s  .c o m
 * 
 * @param agencyId
 *            Which project getting data for
 * @param beginTime
 *            Specifies time range for query
 * @param endTime
 *            Specifies time range for query
 * @param sqlClause
 *            Optional. Can specify an SQL clause to winnow down the data,
 *            such as "AND routeId='71'".
 * @return
 */
public static List<MonitoringEvent> getMonitoringEvents(String agencyId, Date beginTime, Date endTime,
        String sqlClause) {
    IntervalTimer timer = new IntervalTimer();

    // Get the database session. This is supposed to be pretty light weight
    Session session = HibernateUtils.getSession(agencyId);

    // Create the query. Table name is case sensitive and needs to be the
    // class name instead of the name of the db table.
    String hql = "FROM MonitorEvent " + "    WHERE time >= :beginDate " + "      AND time < :endDate";
    if (sqlClause != null)
        hql += " " + sqlClause;
    Query query = session.createQuery(hql);

    // Set the parameters
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    try {
        @SuppressWarnings("unchecked")
        List<MonitoringEvent> monitorEvents = query.list();
        logger.debug("Getting MonitoringEvent from database " + "took {} msec", timer.elapsedMsec());
        return monitorEvents;
    } catch (HibernateException e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        // Clean things up. Not sure if this absolutely needed nor if
        // it might actually be detrimental and slow things down.
        session.close();
    }

}

From source file:org.transitime.db.structs.VehicleEvent.java

License:Open Source License

/**
 * Reads in all VehicleEvents from the database that were between the
 * beginTime and endTime.//  ww  w  . j av a 2  s. c om
 * 
 * @param agencyId
 *            Which project getting data for
 * @param beginTime
 *            Specifies time range for query
 * @param endTime
 *            Specifies time range for query
 * @param sqlClause
 *            Optional. Can specify an SQL clause to winnow down the data,
 *            such as "AND routeId='71'".
 * @return
 */
public static List<VehicleEvent> getVehicleEvents(String agencyId, Date beginTime, Date endTime,
        String sqlClause) {
    IntervalTimer timer = new IntervalTimer();

    // Get the database session. This is supposed to be pretty light weight
    Session session = HibernateUtils.getSession(agencyId);

    // Create the query. Table name is case sensitive and needs to be the
    // class name instead of the name of the db table.
    String hql = "FROM VehicleEvent " + "    WHERE time >= :beginDate " + "      AND time < :endDate";
    if (sqlClause != null)
        hql += " " + sqlClause;
    Query query = session.createQuery(hql);

    // Set the parameters
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    try {
        @SuppressWarnings("unchecked")
        List<VehicleEvent> vehicleEvents = query.list();
        logger.debug("Getting VehicleEvents from database took {} msec", timer.elapsedMsec());
        return vehicleEvents;
    } catch (HibernateException e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        // Clean things up. Not sure if this absolutely needed nor if
        // it might actually be detrimental and slow things down.
        session.close();
    }
}

From source file:org.webcurator.domain.HarvestCoordinatorDAOImpl.java

License:Apache License

/** @see org.webcurator.domain.HarvestCoordinatorDAO#getBandwidthRestriction(String, Date). */
public BandwidthRestriction getBandwidthRestriction(final String aDay, final Date aTime) {
    Object obj = getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session aSession) throws HibernateException, SQLException {
            Query q = aSession.getNamedQuery(BandwidthRestriction.QUERY_DAY_TIME).setReadOnly(true);
            q.setString(BandwidthRestriction.PARAM_DOW, aDay);
            q.setTimestamp(BandwidthRestriction.PARAM_START, aTime);
            q.setTimestamp(BandwidthRestriction.PARAM_END, aTime);

            return q.uniqueResult();
        }/*  w  w  w  .  j a v a2s.  c  o  m*/
    });

    if (obj instanceof BandwidthRestriction) {
        return (BandwidthRestriction) obj;
    }

    return null;
}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public List<TargetInstance> findPurgeableTargetInstances(final Date aPurgeDate) {
    return (List<TargetInstance>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            Query query = session.getNamedQuery(TargetInstance.QRY_GET_PURGEABLE_TIS);
            query.setTimestamp(TargetInstance.QRY_PARAM_PURGE_TIME, aPurgeDate);
            query.setString(TargetInstance.QRY_PARAM_ARCHIVED_STATE, TargetInstance.STATE_ARCHIVED);
            query.setString(TargetInstance.QRY_PARAM_REJECTED_STATE, TargetInstance.STATE_REJECTED);

            return query.list();
        }//  w w w  . j a  v a 2  s  .c om
    });
}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public List<TargetInstance> findPurgeableAbortedTargetInstances(final Date aPurgeDate) {
    return (List<TargetInstance>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            Query query = session.getNamedQuery(TargetInstance.QRY_GET_PURGEABLE_ABORTED_TIS);
            query.setTimestamp(TargetInstance.QRY_PARAM_PURGE_TIME, aPurgeDate);
            query.setString(TargetInstance.QRY_PARAM_ABORTED_STATE, TargetInstance.STATE_ABORTED);

            return query.list();
        }//  www .j a  v a  2 s  .c o m
    });
}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public List<QueuedTargetInstanceDTO> getQueue() {
    final TargetInstanceCriteria criteria = new TargetInstanceCriteria();
    Set<String> states = new HashSet<String>();
    states.add(TargetInstance.STATE_SCHEDULED);
    states.add(TargetInstance.STATE_QUEUED);
    criteria.setStates(states);//from  w ww.j a v  a2s  .com
    criteria.setTo(new Date());

    return (List) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {

            StringBuffer q = new StringBuffer();
            q.append(
                    "select new org.webcurator.domain.model.dto.QueuedTargetInstanceDTO(ti.oid, ti.scheduledTime, ti.priority, ti.state, ti.bandwidthPercent, ti.owner.agency.name) ");
            q.append("from TargetInstance ti where ti.scheduledTime <= :ed ");
            q.append("and ti.state in ('Scheduled', 'Queued') ");
            q.append("order by ti.priority asc, ti.scheduledTime asc, ti.oid asc ");

            Query query = session.createQuery(q.toString());

            query.setTimestamp("ed", new Date());

            return query.list();
        }
    });
}

From source file:org.webcurator.domain.TargetInstanceDAOImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public List<QueuedTargetInstanceDTO> getUpcomingJobs(final long futureMs) {
    return (List) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {

            StringBuffer q = new StringBuffer();
            q.append(// w  w  w . j  a  v a2  s .  c  om
                    "select new org.webcurator.domain.model.dto.QueuedTargetInstanceDTO(ti.oid, ti.scheduledTime, ti.priority, ti.state, ti.bandwidthPercent, ti.owner.agency.name) ");
            q.append("from TargetInstance ti where ti.scheduledTime <= :ed ");
            q.append("and ti.state in ('Scheduled', 'Queued') ");
            q.append("order by ti.priority asc, ti.scheduledTime asc, ti.oid asc ");

            Query query = session.createQuery(q.toString());

            query.setTimestamp("ed", new Date(System.currentTimeMillis() + futureMs));

            return query.list();
        }
    });
}

From source file:org.xerela.provider.scheduler.internal.SchedulerActivator.java

License:Mozilla Public License

/**
 * Set the status of any jobs that are marked as "still running" to canceled.  Of we're just
 * starting up, these jobs are NOT running anymore.  Of course, I don't know what this means
 * in a bundle restart scenario ... not sure what to do about that, as it's theoretically 
 * possible for a schedule to be running at the time we restart this bundle.  Ah well, an
 * obscure bug for another day./*  w  w w.  j ava 2 s. co m*/
 */
private void cleanupAbandonedJobs() {
    if (!isRAMStore()) {
        TransactionElf.beginOrJoinTransaction();

        try {
            Session session = getSessionFactory().getCurrentSession();
            Query query = session.createQuery(
                    "UPDATE ExecutionData e SET e.endTime=:et, e.canceled=true WHERE e.endTime=null");
            query.setTimestamp("et", Calendar.getInstance().getTime());
            int updated = query.executeUpdate();
            TransactionElf.commit();

            if (updated > 0) {
                USER_LOG.info(String.format("Set status of %d abandonded jobs to cancelled.", updated));
            }
        } catch (Exception e) {
            USER_LOG.warn("Exception resetting status of abandoned jobs.", e);
        }
    }
}