Example usage for org.hibernate Query setCalendar

List of usage examples for org.hibernate Query setCalendar

Introduction

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

Prototype

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

Source Link

Document

Bind a named Calendar-valued parameter using the full Timestamp.

Usage

From source file:com.square.logs.core.dao.implementations.LogDaoImplementation.java

License:Open Source License

@Override
public int getNbLogsBeforeDate(Calendar date) {
    final String requete = "SELECT count(id) FROM Log WHERE date <= :date";
    final Query query = createQuery(requete);
    query.setCalendar("date", date);
    final Object result = query.uniqueResult();
    if (result instanceof BigInteger) {
        return ((BigInteger) result).intValue();
    } else {//from   w ww .ja  va 2 s .co m
        return ((Long) result).intValue();
    }
}

From source file:jp.go.nict.langrid.dao.hibernate.HibernateOverUseStateDao.java

License:Open Source License

@Override
public OverUseStateSearchResult searchOverUseWithPeriod(int startIndex, int maxCount, String gridId,
        Calendar startDateTime, Calendar endDateTime, Order[] orders, Period period) throws DaoException {
    //## hibernate-postgresql????
    startDateTime = CalendarUtil.toDefaultTimeZone(startDateTime);
    endDateTime = CalendarUtil.toDefaultTimeZone(endDateTime);

    if (orders.length == 0) {
        orders = new Order[] { new Order("lastAccessDateTime", OrderDirection.DESCENDANT) };
    }/*from ww w  . j a  va  2 s.c  o  m*/
    for (Order o : orders) {
        if (o.getFieldName().equals("period")) {
            o.setFieldName("ol.period");
        }
    }

    Session session = getSession();
    getContext().beginTransaction();
    try {
        // AccessState
        Query qState = session.createQuery(countClouse + fromAndWhereClouseStateWithPeriod);
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);
        qState.setInteger("period", period.ordinal());
        long countState = (Long) qState.uniqueResult();
        qState = session.createQuery(selectClouseState + fromAndWhereClouseStateWithPeriod
                + QueryUtil.buildOrderByQuery(Object.class, "ac", orders));
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);
        qState.setInteger("period", period.ordinal());

        List<OverUseState> result = new ArrayList<OverUseState>();
        ScrollableResults iState = qState.scroll(ScrollMode.FORWARD_ONLY);
        for (int i = 0; i < (startIndex + maxCount); i++) {
            OverUseState currentState = getNextOverUseState(iState);
            if (currentState == null) {
                break;
            }
            if (startIndex <= i)
                result.add(currentState);
        }
        OverUseStateSearchResult r = new OverUseStateSearchResult(result.toArray(new OverUseState[] {}),
                (int) (countState), true);
        getContext().commitTransaction();
        return r;
    } catch (HibernateException e) {
        getContext().rollbackTransaction();
        logAdditionalInfo(e);
        throw new DaoException(e);
    } catch (RuntimeException e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    } catch (Error e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    }
}

From source file:jp.go.nict.langrid.dao.hibernate.HibernateOverUseStateDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public OverUseStateSearchResult searchOverUse(int startIndex, int maxCount, String gridId,
        Calendar startDateTime, Calendar endDateTime, Order[] orders) throws DaoException {
    //## hibernate-postgresql????
    startDateTime = CalendarUtil.toDefaultTimeZone(startDateTime);
    endDateTime = CalendarUtil.toDefaultTimeZone(endDateTime);

    if (orders.length == 0) {
        orders = new Order[] { new Order("lastAccessDateTime", OrderDirection.DESCENDANT) };
    }//from   ww  w.j  ava 2s.  c  o m
    for (Order o : orders) {
        if (o.getFieldName().equals("period")) {
            o.setFieldName("ol.period");
        }
    }
    Order[] ordersForLog = ArrayUtil.collect(orders, Order.class, new Transformer<Order, Order>() {
        public Order transform(Order value) throws TransformationException {
            Order o = new Order(value.getFieldName(), value.getDirection());
            if (o.getFieldName().equals("lastAccessDateTime")) {
                o.setFieldName("dateTime");
            } else if (o.getFieldName().equals("transferredSize")) {
                o.setFieldName("responseBytes");
            }
            return o;
        }
    });

    Session session = getSession();
    getContext().beginTransaction();
    try {
        // AccessState
        Query qState = session.createQuery(countClouse + fromAndWhereClouseState);
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);
        long countState = (Long) qState.uniqueResult();
        qState = session.createQuery(selectClouseState + fromAndWhereClouseState
                + QueryUtil.buildOrderByQuery(Object.class, "ac", orders));
        qState.setString("gridId", gridId);
        qState.setCalendar("startDateTime", startDateTime);
        qState.setCalendar("endDateTime", endDateTime);

        // AccessLog
        Query qLog = session.createQuery(countClouse + fromAndWhereClouseLog);
        qLog.setString("gridId", gridId);
        qLog.setCalendar("startDateTime", startDateTime);
        qLog.setCalendar("endDateTime", endDateTime);
        long countLog = (Long) qLog.uniqueResult();
        qLog = session.createQuery(selectClouseLog + fromAndWhereClouseLog
                + QueryUtil.buildOrderByQuery(Object.class, "al", ordersForLog));
        qLog.setString("gridId", gridId);
        qLog.setCalendar("startDateTime", startDateTime);
        qLog.setCalendar("endDateTime", endDateTime);

        // ???
        List<OverUseState> result = new ArrayList<OverUseState>();
        Iterator<Object> iState = qState.list().iterator();
        Iterator<Object> iLog = qLog.list().iterator();
        OverUseState currentState = null;
        OverUseState currentLog = null;
        for (int i = 0; i < (startIndex + maxCount); i++) {
            if (currentState == null) {
                currentState = getNextOverUseState(iState);
            }
            if (currentLog == null) {
                currentLog = getNextOverUseState(iLog);
            }
            if (currentState == null && currentLog == null) {
                break;
            }
            if (currentState == null && currentLog != null) {
                if (startIndex <= i)
                    result.add(currentLog);
                currentLog = null;
                continue;
            }
            if (currentState != null && currentLog == null) {
                if (startIndex <= i)
                    result.add(currentState);
                currentState = null;
                continue;
            }
            int c = compare(currentState, currentLog, orders);
            if (c <= 0) {
                if (startIndex <= i)
                    result.add(currentState);
                currentState = null;
                continue;
            }
            if (c > 0) {
                if (startIndex <= i)
                    result.add(currentLog);
                currentLog = null;
                continue;
            }
        }

        OverUseStateSearchResult r = new OverUseStateSearchResult(result.toArray(new OverUseState[] {}),
                (int) (countState + countLog), true);
        getContext().commitTransaction();
        return r;
    } catch (HibernateException e) {
        getContext().rollbackTransaction();
        logAdditionalInfo(e);
        throw new DaoException(e);
    } catch (RuntimeException e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    } catch (Error e) {
        getContext().rollbackTransaction();
        throw new DaoException(e);
    }
}

From source file:net.mlw.vlh.adapter.hibernate3.util.setter.CalendarSetter.java

License:Open Source License

/**
 * <ol>//from   w ww  . j a v  a 2s  .  com
 * <li>If is filter value instance of the Calendar, it will set it directly
 * to query. </li>
 * <li>If is filter value instance of String, it try to convert it it to long and set to Calendar instance</li>
 * <li>If is filter value instance of Long, it try to convert it it to long and set to Calendar instance</li>
 * <li>Otherwise it will set null to query for key.</li>
 * </ol>
 * 
 * @see net.mlw.vlh.adapter.hibernate3.util.Setter#set(org.hibernate.Query,
 *      java.lang.String, java.lang.Object)
 */
public void set(Query query, String key, Object value) throws HibernateException, ParseException {

    Calendar calendar = null;

    if (value instanceof String) {
        calendar = Calendar.getInstance();
        try {
            calendar.setTimeInMillis(Long.valueOf((String) value).longValue());
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("The key's='" + key + "' String value='" + value + "' was converted to Calendar.");
            }
        } catch (NumberFormatException e) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("The key's='" + key + "' String value='" + value
                        + "' was not converted to Calendar, error was:" + e.getMessage());
            }
            throw e;
        }
    } else if (value instanceof Long) {
        calendar = Calendar.getInstance();
        calendar.setTimeInMillis(((Long) value).longValue());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The key's='" + key + "' Long value='" + value + "' was converted to Calendar.");
        }
    } else if (value instanceof Calendar) {
        calendar = (Calendar) value;
    } else if (value == null) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("The key='" + key + "'s value is null.");
        }
    } else {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("The key's='" + key + "' value='" + value + "' was expected as Calendar.");
        }
        throw new IllegalArgumentException("Cannot convert value of class " + value.getClass().getName()
                + " to calendar (key=" + key + ")");
    }

    query.setCalendar(key, calendar);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("The key='" + key + "' was set to the query as Calendar='" + calendar + "'.");
    }
}

From source file:onl.netfishers.netshot.work.tasks.PurgeDatabaseTask.java

License:Open Source License

@Override
public void run() {
    logger.debug("Starting cleanup process.");

    {//from w ww  .jav  a2s .c  om
        Session session = Database.getSession();
        try {
            session.beginTransaction();
            logger.trace("Cleaning up tasks finished more than {} days ago...", days);
            this.logIt(String.format("Cleaning up tasks more than %d days ago...", days), 5);
            Calendar when = Calendar.getInstance();
            when.add(Calendar.DATE, -1 * days);
            ScrollableResults tasks = session
                    .createQuery("from Task t where (t.status = :cancelled or t.status = :failure "
                            + "or t.status = :success) and (t.executionDate < :when)")
                    .setParameter("cancelled", Task.Status.CANCELLED)
                    .setParameter("failure", Task.Status.FAILURE).setParameter("success", Task.Status.SUCCESS)
                    .setDate("when", when.getTime()).setCacheMode(CacheMode.IGNORE)
                    .scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (tasks.next()) {
                Task task = (Task) tasks.get(0);
                session.delete(task);
                if (++count % 50 == 0) {
                    session.flush();
                    session.clear();
                }
            }
            session.getTransaction().commit();
            logger.trace("Cleaning up done on tasks, {} entries affected.", count);
            this.logIt(String.format("Cleaning up done on tasks, %d entries affected.", count), 5);
        } catch (HibernateException e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Database error while purging the old tasks from the database.", e);
            this.logIt("Database error during the task purge.", 1);
            this.status = Status.FAILURE;
            return;
        } catch (Exception e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Error while purging the old tasks from the database.", e);
            this.logIt("Error during the task purge.", 1);
            this.status = Status.FAILURE;
            return;
        } finally {
            session.close();
        }
    }

    if (configDays > 0) {
        Session session = Database.getSession();
        try {
            session.beginTransaction();
            logger.trace("Cleaning up configurations taken more than {} days ago...", configDays);
            this.logIt(String.format("Cleaning up configurations older than %d days...", configDays), 5);
            Calendar when = Calendar.getInstance();
            when.add(Calendar.DATE, -1 * configDays);
            Query query;
            if (configSize > 0) {
                query = session.createQuery(
                        "select c from Config c join c.attributes a where (a.class = ConfigLongTextAttribute) group by c.id having (max(length(a.longText.text)) > :size) and (c.changeDate < :when) order by c.device asc, c.changeDate desc")
                        .setInteger("size", configSize * 1024);
            } else {
                query = session.createQuery(
                        "from Config c where (c.changeDate < :when) order by c.device asc, c.changeDate desc");
            }
            ScrollableResults configs = query.setCalendar("when", when).setCacheMode(CacheMode.IGNORE)
                    .scroll(ScrollMode.FORWARD_ONLY);
            long dontDeleteDevice = -1;
            Date dontDeleteBefore = null;
            int count = 0;
            while (configs.next()) {
                try {
                    Config config = (Config) configs.get(0);
                    if ((config.getDevice().getLastConfig() != null
                            && config.getDevice().getLastConfig().getId() == config.getId())
                            || (dontDeleteBefore != null && config.getChangeDate().before(dontDeleteBefore))
                            || (configKeepDays > 0 && dontDeleteDevice != config.getDevice().getId())) {
                        if (configKeepDays > 0) {
                            Calendar limitCalendar = Calendar.getInstance();
                            limitCalendar.setTime(config.getChangeDate());
                            limitCalendar.add(Calendar.DATE, -1 * configKeepDays);
                            dontDeleteBefore = limitCalendar.getTime();
                        }
                    } else {
                        session.delete(config);
                        if (++count % 30 == 0) {
                            session.flush();
                            session.clear();
                        }
                    }
                    dontDeleteDevice = config.getDevice().getId();
                } catch (NullPointerException e1) {
                }
            }
            session.getTransaction().commit();
            logger.trace("Cleaning up done on configurations, {} entries affected.", count);
            this.logIt(String.format("Cleaning up done on configurations, %d entries affected.", count), 5);
        } catch (HibernateException e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Database error while purging the old configurations from the database.", e);
            this.logIt("Database error during the configuration purge.", 1);
            this.status = Status.FAILURE;
            return;
        } catch (Exception e) {
            try {
                session.getTransaction().rollback();
            } catch (Exception e1) {

            }
            logger.error("Error while purging the old configurations from the database.", e);
            this.logIt("Error during the configuration purge.", 1);
            this.status = Status.FAILURE;
            return;
        } finally {
            session.close();
        }
    }

    this.status = Status.SUCCESS;
    logger.trace("Cleaning up process finished.");
}

From source file:org.infoglue.calendar.controllers.EventController.java

License:Open Source License

/**
 * Gets a list of all events available for a particular user.
 * @return List of Event/*from ww w  .  j av  a2 s .com*/
 * @throws Exception
 */

public Set getEventList(java.util.Calendar startDate, java.util.Calendar endDate, String userName, List roles,
        List groups, Integer stateId, boolean includeLinked, boolean includeEventsCreatedByUser,
        Session session) throws Exception {
    List result = new ArrayList();

    if (includeLinked == true) {
        String rolesSQL = getRoleSQL(roles);
        log.info("groups:" + groups.size());
        String groupsSQL = getGroupsSQL(groups);
        log.info("groupsSQL:" + groupsSQL);
        String sql = "select c from Calendar c, Role cr, Group g where cr.calendar = c AND g.calendar = c "
                + (rolesSQL != null ? " AND cr.name IN " + rolesSQL : "")
                + (groupsSQL != null ? " AND g.name IN " + groupsSQL : "") + " order by c.id";
        //String sql = "select distinct c from Calendar c, Role cr, Group g where cr.calendar = c AND g.calendar = c " + (rolesSQL != null ? " AND cr.name IN " + rolesSQL : "") + (groupsSQL != null ? " AND g.name IN " + groupsSQL : "") + " order by c.id";
        log.info("sql:" + sql);
        Query q = session.createQuery(sql);
        setRoleNames(0, q, roles);
        setGroupNames(roles.size(), q, groups);
        List calendars = q.list();

        Object[] calendarIdArray = new Object[calendars.size()];

        int i = 0;
        Iterator calendarsIterator = calendars.iterator();
        while (calendarsIterator.hasNext()) {
            Calendar calendar = (Calendar) calendarsIterator.next();
            log.info("calendar: " + calendar.getName());
            calendarIdArray[i] = calendar.getId();
            i++;
        }

        if (calendarIdArray.length > 0) {
            Criteria criteria = session.createCriteria(Event.class);
            criteria.add(Restrictions.eq("stateId", stateId));
            criteria.add(Expression.gt("endDateTime", startDate));
            criteria.addOrder(Order.asc("startDateTime"));

            /*
            criteria.add(Expression.gt("endDateTime", endDate));
            criteria.add(Expression.lt("startDateTime", startDate));
            */
            criteria.createCriteria("owningCalendar")
                    .add(Restrictions.not(Restrictions.in("id", calendarIdArray)));

            criteria.createCriteria("calendars").add(Restrictions.in("id", calendarIdArray));

            result = criteria.list();
        }

    } else {
        String rolesSQL = getRoleSQL(roles);
        log.info("groups:" + groups.size());
        String groupsSQL = getGroupsSQL(groups);
        log.info("groupsSQL:" + groupsSQL);
        String sql = "select event from Event event, Calendar c, Role cr, Group g where event.owningCalendar = c AND cr.calendar = c AND g.calendar = c AND event.stateId = ? AND event.endDateTime >= ? "
                + (rolesSQL != null ? " AND cr.name IN " + rolesSQL : "")
                + (groupsSQL != null ? " AND g.name IN " + groupsSQL : "") + " order by event.startDateTime";
        //String sql = "select distinct event from Event event, Calendar c, Role cr, Group g where event.owningCalendar = c AND cr.calendar = c AND g.calendar = c AND event.stateId = ? AND event.endDateTime >= ? " + (rolesSQL != null ? " AND cr.name IN " + rolesSQL : "") + (groupsSQL != null ? " AND g.name IN " + groupsSQL : "") + " order by event.startDateTime";
        log.info("sql:" + sql);
        Query q = session.createQuery(sql);
        q.setInteger(0, stateId.intValue());
        q.setCalendar(1, startDate);
        log.info("startDate:" + startDate.getTime());
        setRoleNames(2, q, roles);
        /*
        q.setCalendar(1, startDate);
        q.setCalendar(2, endDate);
        setRoleNames(3, q, roles);
        */
        setGroupNames(roles.size() + 2, q, groups);

        result = q.list();
    }

    log.info("result:" + result.size());

    Set set = new LinkedHashSet();
    set.addAll(result);

    if (includeEventsCreatedByUser) {
        Criteria criteria = session.createCriteria(Event.class);
        criteria.add(Restrictions.eq("stateId", stateId));
        criteria.add(Restrictions.eq("creator", userName));
        criteria.add(Expression.gt("endDateTime", startDate));
        criteria.addOrder(Order.asc("startDateTime"));

        /*
        criteria.add(Expression.gt("endDateTime", endDate));
        criteria.add(Expression.lt("startDateTime", startDate));
        */

        set.addAll(criteria.list());
    }
    List sortedList = new ArrayList();
    sortedList.addAll(set);

    Collections.sort(sortedList, new EventComparator());
    set.clear();

    set.addAll(sortedList);

    return set;
}

From source file:org.infoglue.calendar.controllers.EventController.java

License:Open Source License

/**
 * This method returns a list of Events based on a number of parameters within a transaction
 * @return List/*from  www  .  ja va 2s .c  o m*/
 * @throws Exception
 */

public Set getEventList(Calendar calendar, Integer stateId, java.util.Calendar startDate,
        java.util.Calendar endDate, Session session) throws Exception {
    Query q = session.createQuery(
            "from Event as event inner join fetch event.owningCalendar as calendar where event.owningCalendar = ? AND event.stateId = ? AND event.startDateTime >= ? AND event.endDateTime <= ? order by event.startDateTime");
    q.setEntity(0, calendar);
    q.setInteger(1, stateId.intValue());
    q.setCalendar(2, startDate);
    q.setCalendar(3, endDate);

    List list = q.list();

    Set set = new LinkedHashSet();
    set.addAll(list);

    return set;
}

From source file:org.infoglue.calendar.controllers.ResourceController.java

License:Open Source License

/**
 * This method returns a list of Events based on a number of parameters within a transaction
 * @return List/*w ww . j av  a2  s .c o m*/
 * @throws Exception
 */

public List getEventList(Calendar calendar, java.util.Calendar startDate, java.util.Calendar endDate,
        Session session) throws Exception {
    Query q = session.createQuery(
            "from Event as event inner join fetch event.owningCalendar as calendar where event.owningCalendar = ? AND event.startDateTime >= ? AND event.endDateTime <= ? order by event.startDateTime");
    q.setEntity(0, calendar);
    q.setCalendar(1, startDate);
    q.setCalendar(2, endDate);

    List list = q.list();

    Iterator iterator = list.iterator();
    while (iterator.hasNext()) {
        Object o = iterator.next();
        Event event = (Event) o;
    }

    return list;
}