Example usage for org.hibernate Query setDate

List of usage examples for org.hibernate Query setDate

Introduction

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

Prototype

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

Source Link

Document

Bind the val (time is truncated) of a given Date object to a named query parameter.

Usage

From source file:org.projectforge.framework.persistence.api.BaseDao.java

License:Open Source License

/**
 * Only generic check access will be done. The matching entries will not be checked!
 *
 * @param property Property of the data base entity.
 * @param searchString String the user has typed in.
 * @return All matching entries (like search) for the given property modified or updated in the last 2 years.
 *//*from   w  ww.  j  a va2s  .  c  om*/
@Override
@SuppressWarnings("unchecked")
public List<String> getAutocompletion(final String property, final String searchString) {
    checkLoggedInUserSelectAccess();
    if (StringUtils.isBlank(searchString) == true) {
        return null;
    }
    final String hql = "select distinct " + property + " from " + clazz.getSimpleName()
            + " t where deleted=false and lastUpdate > ? and lower(t." + property + ") like ?) order by t."
            + property;
    final Query query = getSession().createQuery(hql);
    final DateHolder dh = new DateHolder();
    dh.add(Calendar.YEAR, -2); // Search only for entries of the last 2 years.
    query.setDate(0, dh.getDate());
    query.setString(1, "%" + StringUtils.lowerCase(searchString) + "%");
    final List<String> list = query.list();
    return list;
}

From source file:org.projectforge.timesheet.TimesheetDao.java

License:Open Source License

/**
 * Get all locations of the user's time sheet (not deleted ones) with modification date within last year.
 * @param searchString//from  w w  w.j av  a 2  s.  co  m
 */
@SuppressWarnings("unchecked")
public List<String> getLocationAutocompletion(final String searchString) {
    checkLoggedInUserSelectAccess();
    if (StringUtils.isBlank(searchString) == true) {
        return null;
    }
    final String s = "select distinct location from " + clazz.getSimpleName()
            + " t where deleted=false and t.user.id = ? and lastUpdate > ? and lower(t.location) like ?) order by t.location";
    final Query query = getSession().createQuery(s);
    query.setInteger(0, PFUserContext.getUser().getId());
    final DateHolder dh = new DateHolder();
    dh.add(Calendar.YEAR, -1);
    query.setDate(1, dh.getDate());
    query.setString(2, "%" + StringUtils.lowerCase(searchString) + "%");
    final List<String> list = query.list();
    return list;
}

From source file:org.projectforge.timesheet.TimesheetDao.java

License:Open Source License

/**
 * Get all locations of the user's time sheet (not deleted ones) with modification date within last year.
 * @param maxResults Limit the result to the recent locations.
 * @return result as Json object./* ww  w . ja v  a  2 s.  co m*/
 */
@SuppressWarnings("unchecked")
public Collection<String> getRecentLocation(final int maxResults) {
    checkLoggedInUserSelectAccess();
    log.info("Get recent locations from the database.");
    final String s = "select location from " + (clazz.getSimpleName()
            + " t where deleted=false and t.user.id = ? and lastUpdate > ? and t.location != null and t.location != '' order by t.lastUpdate desc");
    final Query query = getSession().createQuery(s);
    query.setInteger(0, PFUserContext.getUser().getId());
    final DateHolder dh = new DateHolder();
    dh.add(Calendar.YEAR, -1);
    query.setDate(1, dh.getDate());
    final List<Object> list = query.list();
    int counter = 0;
    final List<String> res = new ArrayList<String>();
    for (final Object loc : list) {
        if (res.contains(loc) == true) {
            continue;
        }
        res.add((String) loc);
        if (++counter >= maxResults) {
            break;
        }
    }
    return res;
}

From source file:org.sakaiproject.evaluation.dao.EvaluationDaoImpl.java

License:Educational Community License

/**
 * /*from  w w w . j av a  2s  . com*/
 * @param session
 * @param sendingAvailableEmails
 * @param templateId
 * @param userIdList
 */
protected void markRecordsAsSent(Session session, boolean sendingAvailableEmails, Long templateId,
        List<String> userIdList) {

    StringBuilder hqlBuffer = new StringBuilder();

    hqlBuffer.append("update EvalAssignUser ");
    if (sendingAvailableEmails) {
        hqlBuffer.append("set availableEmailSent = :dateSent ");
    } else {
        hqlBuffer.append("set reminderEmailSent = :dateSent ");
    }
    hqlBuffer.append(
            "where id in (select eauId from EvalEmailProcessingData where emailTemplateId = :emailTemplateId and userId = :userId)");

    Query updateQuery = session.createQuery(hqlBuffer.toString());

    updateQuery.setDate("dateSent", new Date());
    updateQuery.setLong("emailTemplateId", templateId);

    for (String userId : userIdList) {
        try {

            updateQuery.setString("userId", userId);
            updateQuery.executeUpdate();

        } catch (HibernateException e) {
            LOG.warn("Error trying to update evalAssignUser. " + userId, e);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("         --> marked entries for users: " + userIdList);
    }
    session.flush();
    userIdList.clear();
}

From source file:org.sakaiproject.evaluation.dao.EvaluationDaoImpl.java

License:Educational Community License

public int selectConsolidatedEmailRecipients(boolean useAvailableEmailSent, Date availableEmailSent,
        boolean useReminderEmailSent, Date reminderEmailSent, String emailTemplateType) {
    int count = 0;
    try {//  www.j  a va2s  .c o m
        StringBuilder queryBuf = new StringBuilder();
        Map<String, Object> params = new HashMap<>();

        queryBuf.append(
                "insert into EvalEmailProcessingData (eauId,userId,groupId,emailTemplateId,evalId,evalDueDate) ");
        queryBuf.append("select user.id as eauId,user.userId as userId,user.evalGroupId as groupId, ");
        if (EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE.equalsIgnoreCase(emailTemplateType)) {
            queryBuf.append("eval.availableEmailTemplate.id as emailTemplateId");
        } else if (EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER.equalsIgnoreCase(emailTemplateType)) {
            queryBuf.append("eval.reminderEmailTemplate.id as emailTemplateId");
        } else {
            queryBuf.append("'' as emailTemplateId");
        }
        queryBuf.append(",eval.id as evalId, eval.dueDate as evalDueDate ");
        queryBuf.append("from EvalAssignUser as user ");
        queryBuf.append("inner join user.evaluation as eval ");
        queryBuf.append(
                "where user.type = :userType and eval.startDate <= current_timestamp() and user.completedDate is null ");
        params.put("userType", EvalAssignUser.TYPE_EVALUATOR);
        if (EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE.equalsIgnoreCase(emailTemplateType)) {
            queryBuf.append("and eval.availableEmailTemplate.type = :emailTemplateType ");
            params.put("emailTemplateType", emailTemplateType);

        } else if (EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER.equalsIgnoreCase(emailTemplateType)) {
            queryBuf.append("and eval.reminderEmailTemplate.type = :emailTemplateType ");
            params.put("emailTemplateType", emailTemplateType);
        }

        if (useAvailableEmailSent) {
            if (availableEmailSent == null) {
                queryBuf.append("and user.availableEmailSent is null ");
            } else {
                queryBuf.append(
                        "and (user.availableEmailSent is null or user.availableEmailSent < :availableEmailSent) ");
                params.put("availableEmailSent", availableEmailSent);
            }
        }

        if (useReminderEmailSent) {
            if (reminderEmailSent == null) {
                queryBuf.append("and user.reminderEmailSent is null ");
            } else {
                queryBuf.append(
                        "and (user.reminderEmailSent is null or user.reminderEmailSent < :reminderEmailSent) ");
                params.put("reminderEmailSent", reminderEmailSent);
            }
        }

        Query query = currentSession().createQuery(queryBuf.toString());

        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() instanceof Date) {
                query.setDate(entry.getKey(), (Date) entry.getValue());
            } else if (entry.getValue() instanceof String) {
                query.setString(entry.getKey(), (String) entry.getValue());
            }
        }

        count = query.executeUpdate();
        LOG.debug("Rows inserted into EVAL_EMAIL_PROCESSING_QUEUE: " + count);
    } catch (DataAccessResourceFailureException | IllegalStateException | HibernateException e) {
        LOG.warn("error processing consolidated-email query: " + e);
    }

    return count;
}

From source file:org.sakaiproject.sitestats.impl.StatsManagerImpl.java

License:Educational Community License

public List<Stat> getEventStats(final String siteId, final List<String> events, final Date iDate,
        final Date fDate, final List<String> userIds, final boolean inverseUserSelection,
        final PagingPosition page, final List<String> totalsBy, final String sortBy, boolean sortAscending,
        final int maxResults) {

    final Set<String> anonymousEvents = M_ers.getAnonymousEventIds();
    StatsSqlBuilder sqlBuilder = new StatsSqlBuilder(getDbVendor(), Q_TYPE_EVENT, totalsBy, siteId, events,
            anonymousEvents, showAnonymousAccessEvents, null, null, iDate, fDate, userIds, inverseUserSelection,
            sortBy, sortAscending);/*from  www  . j a v  a  2s  .c o m*/
    final String hql = sqlBuilder.getHQL();
    final Map<Integer, Integer> columnMap = sqlBuilder.getHQLColumnMap();

    // DO IT!
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(hql);
            if (siteId != null) {
                q.setString("siteid", siteId);
            }
            if (events != null) {
                if (events.isEmpty()) {
                    events.add("");
                }
                q.setParameterList("events", events);
            }
            if (userIds != null && !userIds.isEmpty()) {
                if (userIds.size() <= 1000) {
                    q.setParameterList("users", userIds);
                } else {
                    int nUsers = userIds.size();
                    int blockId = 0, startIndex = 0;
                    int blocks = (int) (nUsers / 1000);
                    blocks = (blocks * 1000 == nUsers) ? blocks : blocks + 1;
                    for (int i = 0; i < blocks - 1; i++) {
                        q.setParameterList("users" + blockId, userIds.subList(startIndex, startIndex + 1000));
                        blockId++;
                        startIndex += 1000;
                    }
                    q.setParameterList("users" + blockId, userIds.subList(startIndex, nUsers));
                }
            }
            if (iDate != null)
                q.setDate("idate", iDate);
            if (fDate != null) {
                // adjust final date
                Calendar c = Calendar.getInstance();
                c.setTime(fDate);
                c.add(Calendar.DAY_OF_YEAR, 1);
                Date fDate2 = c.getTime();
                q.setDate("fdate", fDate2);
            }
            if (columnMap.containsKey(StatsSqlBuilder.C_USER) && anonymousEvents != null
                    && anonymousEvents.size() > 0) {
                q.setParameterList("anonymousEvents", anonymousEvents);
            }
            if (page != null) {
                q.setFirstResult(page.getFirst() - 1);
                q.setMaxResults(page.getLast() - page.getFirst() + 1);
            }
            if (maxResults > 0) {
                q.setMaxResults(maxResults);
            }
            LOG.debug("getEventStats(): " + q.getQueryString());
            List<Object[]> records = q.list();
            List<Stat> results = new ArrayList<Stat>();
            Set<String> siteUserIds = null;
            if (inverseUserSelection)
                siteUserIds = getSiteUsers(siteId);
            if (records.size() > 0) {
                Calendar cal = Calendar.getInstance();
                Map<String, ToolInfo> eventIdToolMap = M_ers.getEventIdToolMap();
                boolean groupByTool = columnMap.containsKey(StatsSqlBuilder.C_TOOL)
                        && !columnMap.containsKey(StatsSqlBuilder.C_EVENT);
                boolean hasVisitsData = columnMap.containsKey(StatsSqlBuilder.C_VISITS);
                for (Iterator<Object[]> iter = records.iterator(); iter.hasNext();) {
                    if (!inverseUserSelection) {
                        Object[] s = iter.next();
                        Stat c = null;
                        String toolId = null;
                        if (!hasVisitsData) {
                            c = new EventStatImpl();
                        } else {
                            c = new SiteVisitsImpl();
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_SITE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_SITE);
                            c.setSiteId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_USER)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_USER);
                            c.setUserId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_EVENT) && !hasVisitsData) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_EVENT);
                            ((EventStat) c).setEventId((String) s[ix]);
                            ToolInfo ti = eventIdToolMap.get((String) s[ix]);
                            toolId = ti != null ? ti.getToolId() : (String) s[ix];
                            ((EventStat) c).setToolId(toolId);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_TOOL) && !hasVisitsData) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_TOOL);
                            ToolInfo ti = eventIdToolMap.get((String) s[ix]);
                            toolId = ti != null ? ti.getToolId() : (String) s[ix];
                            //
                            ((EventStat) c).setToolId(toolId);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATE);
                            c.setDate((Date) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATEMONTH)
                                && columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ixY = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int ixM = (Integer) columnMap.get(StatsSqlBuilder.C_DATEMONTH);
                            int yr = 0, mo = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ixY]);
                                mo = Integer.parseInt((String) s[ixM]) - 1;
                            } else {
                                yr = ((Integer) s[ixY]).intValue();
                                mo = ((Integer) s[ixM]).intValue() - 1;
                            }
                            cal.set(Calendar.YEAR, yr);
                            cal.set(Calendar.MONTH, mo);
                            c.setDate(cal.getTime());
                        } else if (columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int yr = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ix]);
                            } else {
                                yr = ((Integer) s[ix]).intValue();
                            }
                            cal.set(Calendar.YEAR, yr);
                            c.setDate(cal.getTime());
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_TOTAL)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_TOTAL);
                            c.setCount(c.getCount() + ((Long) s[ix]).longValue());
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_VISITS)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_VISITS);
                            try {
                                ((SiteVisits) c).setTotalVisits(((Long) s[ix]).longValue());
                            } catch (ClassCastException cce) {
                                ((SiteVisits) c).setTotalVisits(((Integer) s[ix]).intValue());
                            }
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_UNIQUEVISITS)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_UNIQUEVISITS);
                            try {
                                ((SiteVisits) c).setTotalUnique(((Long) s[ix]).longValue());
                            } catch (ClassCastException cce) {
                                ((SiteVisits) c).setTotalUnique(((Integer) s[ix]).intValue());
                            }
                        }
                        if (!groupByTool) {
                            results.add(c);
                        } else {
                            // Special case:
                            //   - group by tool (& event not part of grouping)
                            boolean toolAggregated = false;
                            for (Stat s_ : results) {
                                EventStat es_ = (EventStat) s_;
                                if (es_.equalExceptForCount(c)) {
                                    es_.setCount(es_.getCount() + c.getCount());
                                    toolAggregated = true;
                                    break;
                                }
                            }
                            if (!toolAggregated) {
                                results.add(c);
                            }
                        }
                    } else {
                        if (siteUserIds != null) {
                            siteUserIds.remove((Object) iter.next());
                        }
                    }
                }
            }
            if (inverseUserSelection) {
                long id = 0;
                Iterator<String> iU = siteUserIds.iterator();
                while (iU.hasNext()) {
                    String userId = iU.next();
                    EventStat c = new EventStatImpl();
                    c.setId(id++);
                    c.setUserId(userId);
                    c.setSiteId(siteId);
                    c.setCount(0);
                    results.add(c);
                }
            }
            // hack for hibernate-oracle bug producing duplicate lines
            else if (getDbVendor().equals("oracle") && totalsBy.contains(T_USER) && anonymousEvents != null
                    && anonymousEvents.size() > 0) {
                List<Stat> consolidated = new ArrayList<Stat>();
                for (Stat s : results) {
                    EventStat es = (EventStat) s;
                    boolean found = false;
                    for (Stat c : consolidated) {
                        EventStat esc = (EventStat) c;
                        if (esc.equalExceptForCount((Object) es)) {
                            esc.setCount(esc.getCount() + es.getCount());
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        consolidated.add(es);
                    }
                }
                results = consolidated;
            }
            return results;
        }
    };
    return (List<Stat>) getHibernateTemplate().execute(hcb);
}

From source file:org.sakaiproject.sitestats.impl.StatsManagerImpl.java

License:Educational Community License

public int getEventStatsRowCount(final String siteId, final List<String> events, final Date iDate,
        final Date fDate, final List<String> userIds, final boolean inverseUserSelection,
        final List<String> totalsBy) {

    final Set<String> anonymousEvents = M_ers.getAnonymousEventIds();
    StatsSqlBuilder sqlBuilder = new StatsSqlBuilder(getDbVendor(), Q_TYPE_EVENT, totalsBy, siteId, events,
            anonymousEvents, showAnonymousAccessEvents, null, null, iDate, fDate, userIds, inverseUserSelection,
            null, true);/*from  w  w w  . jav  a2  s.c om*/
    final String hql = sqlBuilder.getHQL();
    final Map<Integer, Integer> columnMap = sqlBuilder.getHQLColumnMap();

    // DO IT!
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(hql);
            if (siteId != null) {
                q.setString("siteid", siteId);
            }
            if (events != null && !events.isEmpty()) {
                q.setParameterList("events", events);
            }
            if (userIds != null && !userIds.isEmpty()) {
                if (userIds.size() <= 1000) {
                    q.setParameterList("users", userIds);
                } else {
                    int nUsers = userIds.size();
                    int blockId = 0, startIndex = 0;
                    int blocks = (int) (nUsers / 1000);
                    blocks = (blocks * 1000 == nUsers) ? blocks : blocks + 1;
                    for (int i = 0; i < blocks - 1; i++) {
                        q.setParameterList("users" + blockId, userIds.subList(startIndex, startIndex + 1000));
                        blockId++;
                        startIndex += 1000;
                    }
                    q.setParameterList("users" + blockId, userIds.subList(startIndex, nUsers));
                }
            }
            if (iDate != null)
                q.setDate("idate", iDate);
            if (fDate != null) {
                // adjust final date
                Calendar c = Calendar.getInstance();
                c.setTime(fDate);
                c.add(Calendar.DAY_OF_YEAR, 1);
                Date fDate2 = c.getTime();
                q.setDate("fdate", fDate2);
            }
            if (columnMap.containsKey(StatsSqlBuilder.C_USER) && anonymousEvents != null
                    && anonymousEvents.size() > 0) {
                q.setParameterList("anonymousEvents", anonymousEvents);
            }
            LOG.debug("getEventStatsRowCount(): " + q.getQueryString());
            Integer rowCount = q.list().size();
            if (!inverseUserSelection) {
                return rowCount;
            } else {
                return getSiteUsers(siteId).size() - rowCount;
            }
        }
    };
    return (Integer) getHibernateTemplate().execute(hcb);
}

From source file:org.sakaiproject.sitestats.impl.StatsManagerImpl.java

License:Educational Community License

public List<Stat> getPresenceStats(final String siteId, final Date iDate, final Date fDate,
        final List<String> userIds, final boolean inverseUserSelection, final PagingPosition page,
        final List<String> totalsBy, final String sortBy, boolean sortAscending, final int maxResults) {

    StatsSqlBuilder sqlBuilder = new StatsSqlBuilder(getDbVendor(), Q_TYPE_PRESENCE, totalsBy, siteId,
            (Set<String>) null, null, showAnonymousAccessEvents, null, null, iDate, fDate, userIds,
            inverseUserSelection, sortBy, sortAscending);
    final String hql = sqlBuilder.getHQL();
    final Map<Integer, Integer> columnMap = sqlBuilder.getHQLColumnMap();

    // DO IT!/*from   w w w .  j a v a  2  s .com*/
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(hql);
            if (siteId != null) {
                q.setString("siteid", siteId);
            }
            if (userIds != null && !userIds.isEmpty()) {
                if (userIds.size() <= 1000) {
                    q.setParameterList("users", userIds);
                } else {
                    int nUsers = userIds.size();
                    int blockId = 0, startIndex = 0;
                    int blocks = (int) (nUsers / 1000);
                    blocks = (blocks * 1000 == nUsers) ? blocks : blocks + 1;
                    for (int i = 0; i < blocks - 1; i++) {
                        q.setParameterList("users" + blockId, userIds.subList(startIndex, startIndex + 1000));
                        blockId++;
                        startIndex += 1000;
                    }
                    q.setParameterList("users" + blockId, userIds.subList(startIndex, nUsers));
                }
            }
            if (iDate != null)
                q.setDate("idate", iDate);
            if (fDate != null) {
                // adjust final date
                Calendar c = Calendar.getInstance();
                c.setTime(fDate);
                c.add(Calendar.DAY_OF_YEAR, 1);
                Date fDate2 = c.getTime();
                q.setDate("fdate", fDate2);
            }
            if (page != null) {
                q.setFirstResult(page.getFirst() - 1);
                q.setMaxResults(page.getLast() - page.getFirst() + 1);
            }
            if (maxResults > 0) {
                q.setMaxResults(maxResults);
            }
            LOG.debug("getPresenceStats(): " + q.getQueryString());
            List<Object[]> records = q.list();
            List<Stat> results = new ArrayList<Stat>();
            Set<String> siteUserIds = null;
            if (inverseUserSelection)
                siteUserIds = getSiteUsers(siteId);
            if (records.size() > 0) {
                Calendar cal = Calendar.getInstance();
                for (Iterator<Object[]> iter = records.iterator(); iter.hasNext();) {
                    if (!inverseUserSelection) {
                        Object[] s = iter.next();
                        SitePresence c = new SitePresenceImpl();
                        if (columnMap.containsKey(StatsSqlBuilder.C_SITE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_SITE);
                            c.setSiteId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_USER)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_USER);
                            c.setUserId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATE);
                            c.setDate((Date) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATEMONTH)
                                && columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ixY = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int ixM = (Integer) columnMap.get(StatsSqlBuilder.C_DATEMONTH);
                            int yr = 0, mo = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ixY]);
                                mo = Integer.parseInt((String) s[ixM]) - 1;
                            } else {
                                yr = ((Integer) s[ixY]).intValue();
                                mo = ((Integer) s[ixM]).intValue() - 1;
                            }
                            cal.set(Calendar.YEAR, yr);
                            cal.set(Calendar.MONTH, mo);
                            c.setDate(cal.getTime());
                        } else if (columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int yr = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ix]);
                            } else {
                                yr = ((Integer) s[ix]).intValue();
                            }
                            cal.set(Calendar.YEAR, yr);
                            c.setDate(cal.getTime());
                        }
                        {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DURATION);
                            c.setDuration(c.getDuration() + ((Long) s[ix]).longValue());
                        }
                        results.add(c);
                    } else {
                        if (siteUserIds != null) {
                            siteUserIds.remove((Object) iter.next());
                        }
                    }
                }
            }
            if (inverseUserSelection) {
                long id = 0;
                Iterator<String> iU = siteUserIds.iterator();
                while (iU.hasNext()) {
                    String userId = iU.next();
                    SitePresence c = new SitePresenceImpl();
                    c.setId(id++);
                    c.setUserId(userId);
                    c.setSiteId(siteId);
                    c.setDuration(0);
                    c.setCount(0);
                    results.add(c);
                }
            }
            return results;
        }
    };
    return (List<Stat>) getHibernateTemplate().execute(hcb);
}

From source file:org.sakaiproject.sitestats.impl.StatsManagerImpl.java

License:Educational Community License

public int getPresenceStatsRowCount(final String siteId, final Date iDate, final Date fDate,
        final List<String> userIds, final boolean inverseUserSelection, final List<String> totalsBy) {

    StatsSqlBuilder sqlBuilder = new StatsSqlBuilder(getDbVendor(), Q_TYPE_PRESENCE, totalsBy, null,
            (Set<String>) null, null, showAnonymousAccessEvents, null, null, iDate, fDate, userIds,
            inverseUserSelection, null, true);
    final String hql = sqlBuilder.getHQL();

    // DO IT!//  w w w.  j  a  v  a  2  s  .  c  o m
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(hql);
            if (siteId != null) {
                q.setString("siteid", siteId);
            }
            if (userIds != null && !userIds.isEmpty()) {
                if (userIds.size() <= 1000) {
                    q.setParameterList("users", userIds);
                } else {
                    int nUsers = userIds.size();
                    int blockId = 0, startIndex = 0;
                    int blocks = (int) (nUsers / 1000);
                    blocks = (blocks * 1000 == nUsers) ? blocks : blocks + 1;
                    for (int i = 0; i < blocks - 1; i++) {
                        q.setParameterList("users" + blockId, userIds.subList(startIndex, startIndex + 1000));
                        blockId++;
                        startIndex += 1000;
                    }
                    q.setParameterList("users" + blockId, userIds.subList(startIndex, nUsers));
                }
            }
            if (iDate != null)
                q.setDate("idate", iDate);
            if (fDate != null) {
                // adjust final date
                Calendar c = Calendar.getInstance();
                c.setTime(fDate);
                c.add(Calendar.DAY_OF_YEAR, 1);
                Date fDate2 = c.getTime();
                q.setDate("fdate", fDate2);
            }
            LOG.debug("getPresenceStatsRowCount(): " + q.getQueryString());
            Integer rowCount = q.list().size();
            if (!inverseUserSelection) {
                return rowCount;
            } else {
                return getSiteUsers(siteId).size() - rowCount;
            }
        }
    };
    return (Integer) getHibernateTemplate().execute(hcb);
}

From source file:org.sakaiproject.sitestats.impl.StatsManagerImpl.java

License:Educational Community License

public List<Stat> getResourceStats(final String siteId, final String resourceAction,
        final List<String> resourceIds, final Date iDate, final Date fDate, final List<String> userIds,
        final boolean inverseUserSelection, final PagingPosition page, final List<String> totalsBy,
        final String sortBy, final boolean sortAscending, final int maxResults) {

    StatsSqlBuilder sqlBuilder = new StatsSqlBuilder(getDbVendor(), Q_TYPE_RESOURCE, totalsBy, siteId,
            (Set<String>) null, null, showAnonymousAccessEvents, resourceAction, resourceIds, iDate, fDate,
            userIds, inverseUserSelection, sortBy, sortAscending);
    final String hql = sqlBuilder.getHQL();
    final Map<Integer, Integer> columnMap = sqlBuilder.getHQLColumnMap();

    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(hql);
            if (siteId != null) {
                q.setString("siteid", siteId);
            }//from w w w . j av a  2  s .c  om
            if (userIds != null && !userIds.isEmpty()) {
                if (userIds.size() <= 1000) {
                    q.setParameterList("users", userIds);
                } else {
                    int nUsers = userIds.size();
                    int blockId = 0, startIndex = 0;
                    int blocks = (int) (nUsers / 1000);
                    blocks = (blocks * 1000 == nUsers) ? blocks : blocks + 1;
                    for (int i = 0; i < blocks - 1; i++) {
                        q.setParameterList("users" + blockId, userIds.subList(startIndex, startIndex + 1000));
                        blockId++;
                        startIndex += 1000;
                    }
                    q.setParameterList("users" + blockId, userIds.subList(startIndex, nUsers));
                }
            }
            if (resourceAction != null)
                q.setString("action", resourceAction);
            if (resourceIds != null && !resourceIds.isEmpty()) {
                List<String> simpleResourceIds = new ArrayList<String>();
                List<String> wildcardResourceIds = new ArrayList<String>();
                for (String rId : resourceIds) {
                    if (rId.endsWith("/")) {
                        wildcardResourceIds.add(rId + "%");
                    } else {
                        simpleResourceIds.add(rId);
                    }
                }
                if (simpleResourceIds.size() > 0) {
                    q.setParameterList("resources", resourceIds);
                }
                for (int i = 0; i < wildcardResourceIds.size(); i++) {
                    q.setString("resource" + i, wildcardResourceIds.get(i));
                }
            }
            if (iDate != null)
                q.setDate("idate", iDate);
            if (fDate != null) {
                // adjust final date
                Calendar c = Calendar.getInstance();
                c.setTime(fDate);
                c.add(Calendar.DAY_OF_YEAR, 1);
                Date fDate2 = c.getTime();
                q.setDate("fdate", fDate2);
            }
            if (page != null) {
                q.setFirstResult(page.getFirst() - 1);
                q.setMaxResults(page.getLast() - page.getFirst() + 1);
            }
            if (maxResults > 0) {
                q.setMaxResults(maxResults);
            }
            LOG.debug("getResourceStats(): " + q.getQueryString());
            List<Object[]> records = q.list();
            List<ResourceStat> results = new ArrayList<ResourceStat>();
            Set<String> siteUserIds = null;
            if (inverseUserSelection) {
                siteUserIds = getSiteUsers(siteId);
            }
            if (records.size() > 0) {
                Calendar cal = Calendar.getInstance();
                for (Iterator<Object[]> iter = records.iterator(); iter.hasNext();) {
                    if (!inverseUserSelection) {
                        Object[] s = iter.next();
                        ResourceStat c = new ResourceStatImpl();
                        if (columnMap.containsKey(StatsSqlBuilder.C_SITE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_SITE);
                            c.setSiteId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_USER)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_USER);
                            c.setUserId((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_RESOURCE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_RESOURCE);
                            c.setResourceRef((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_RESOURCE_ACTION)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_RESOURCE_ACTION);
                            c.setResourceAction((String) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATE)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATE);
                            c.setDate((Date) s[ix]);
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_DATEMONTH)
                                && columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ixY = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int ixM = (Integer) columnMap.get(StatsSqlBuilder.C_DATEMONTH);
                            int yr = 0, mo = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ixY]);
                                mo = Integer.parseInt((String) s[ixM]) - 1;
                            } else {
                                yr = ((Integer) s[ixY]).intValue();
                                mo = ((Integer) s[ixM]).intValue() - 1;
                            }
                            cal.set(Calendar.YEAR, yr);
                            cal.set(Calendar.MONTH, mo);
                            c.setDate(cal.getTime());
                        } else if (columnMap.containsKey(StatsSqlBuilder.C_DATEYEAR)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_DATEYEAR);
                            int yr = 0;
                            if (getDbVendor().equals("oracle")) {
                                yr = Integer.parseInt((String) s[ix]);
                            } else {
                                yr = ((Integer) s[ix]).intValue();
                            }
                            cal.set(Calendar.YEAR, yr);
                            c.setDate(cal.getTime());
                        }
                        if (columnMap.containsKey(StatsSqlBuilder.C_TOTAL)) {
                            int ix = (Integer) columnMap.get(StatsSqlBuilder.C_TOTAL);
                            c.setCount(((Long) s[ix]).longValue());
                        }
                        results.add(c);
                    } else {
                        if (siteUserIds != null) {
                            siteUserIds.remove((Object) iter.next());
                        }
                    }
                }
            }
            if (inverseUserSelection) {
                long id = 0;
                Iterator<String> iU = siteUserIds.iterator();
                while (iU.hasNext()) {
                    String userId = iU.next();
                    ResourceStat c = new ResourceStatImpl();
                    c.setId(id++);
                    c.setUserId(userId);
                    c.setSiteId(siteId);
                    c.setCount(0);
                    results.add(c);
                }
            }
            return results;
        }
    };
    return (List<Stat>) getHibernateTemplate().execute(hcb);
}