Example usage for org.hibernate.criterion Restrictions lt

List of usage examples for org.hibernate.criterion Restrictions lt

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions lt.

Prototype

public static SimpleExpression lt(String propertyName, Object value) 

Source Link

Document

Apply a "less than" constraint to the named property

Usage

From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateUserAccountDao.java

License:Open Source License

/**
 * See Interface for functional description.
 *
 * @see UserAccountDaoInterface #retrieveExpiredUserLoginData(long)
 *///from   ww w  . j a va  2 s .c  o m
@Override
@SuppressWarnings("unchecked")
public List<UserLoginData> retrieveExpiredUserLoginData(final long timestamp)
        throws SqlDatabaseSystemException {

    final DetachedCriteria criteria = DetachedCriteria.forClass(UserLoginData.class);
    criteria.add(Restrictions.lt("expiryts", timestamp));
    try {
        return getHibernateTemplate().findByCriteria(criteria);
    } catch (final DataAccessException e) {
        throw new SqlDatabaseSystemException(e);
    }
}

From source file:de.escidoc.core.common.business.filter.CqlFilter.java

License:Open Source License

/**
 * Evaluate a CQL relation.//  w  w  w.ja va2 s .  c o m
 * 
 * @param relation
 *            CQL relation
 * @param propertyName
 *            left side of the statement
 * @param value
 *            right side of the statement
 * @param useLike
 *            use LIKE instead of = in case of an equality relation
 * @return Hibernate query reflecting the given CQL query
 * @throws InvalidSearchQueryException
 *             thrown if the given search query could not be translated into a SQL query
 */
protected Criterion evaluate(final CQLRelation relation, final String propertyName, final Object value,
        final boolean useLike) throws InvalidSearchQueryException {
    final Criterion result;
    final String rel = relation.getBase();

    if (value == null || value.toString().length() == 0) {
        result = Restrictions.isNull(propertyName);
    } else {
        if ("<".equals(rel)) {
            result = Restrictions.lt(propertyName, value);
        } else if ("<=".equals(rel)) {
            result = Restrictions.le(propertyName, value);
        } else if ("=".equals(rel)) {
            result = useLike ? Restrictions.like(propertyName, value) : Restrictions.eq(propertyName, value);
        } else if (">=".equals(rel)) {
            result = Restrictions.ge(propertyName, value);
        } else if (">".equals(rel)) {
            result = Restrictions.gt(propertyName, value);
        } else if ("<>".equals(rel)) {
            result = Restrictions.ne(propertyName, value);
        } else {
            throw new InvalidSearchQueryException(rel + ": relation not implemented");
        }
    }
    return result;
}

From source file:de.escidoc.core.st.business.persistence.hibernate.HibernateStagingFileDao.java

License:Open Source License

/**
 * See Interface for functional description.
 *///from  w  w w  . j  a  v a 2 s  .  c o  m
@Override
public List<StagingFile> findExpiredStagingFiles() throws SqlDatabaseSystemException {

    try {
        final DetachedCriteria criteria = DetachedCriteria.forClass(StagingFile.class);
        criteria.add(Restrictions.lt("expiryTs", System.currentTimeMillis()));
        return getHibernateTemplate().findByCriteria(criteria);
    } catch (final DataAccessException e) {
        throw new SqlDatabaseSystemException(e);
    }
}

From source file:de.forsthaus.backend.dao.impl.IpToCountryDAOImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w  w  w  .j av  a  2  s  .  c o m*/
public IpToCountry getCountry(Long ipNumber) {

    IpToCountry result = null;

    DetachedCriteria criteria = DetachedCriteria.forClass(IpToCountry.class);
    criteria.add(Restrictions.lt("ipcIpFrom", ipNumber));
    criteria.add(Restrictions.gt("ipcIpTo", ipNumber));

    result = (IpToCountry) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));

    return result;

}

From source file:de.ingrid.portal.scheduler.jobs.AnniversaryFetcherJob.java

License:EUPL

private void insertIntoDB(String lang) throws JobExecutionException {

    Session session = HibernateUtil.currentSession();
    Transaction tx = null;//from ww w  .j a  va 2s  . c om

    try {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int thisYear = cal.get(Calendar.YEAR);
        Date queryDate = cal.getTime();

        Calendar queryDateFrom = Calendar.getInstance();
        queryDateFrom.setTime(queryDate);
        queryDateFrom.set(Calendar.HOUR_OF_DAY, 0);
        queryDateFrom.set(Calendar.MINUTE, 0);
        queryDateFrom.set(Calendar.SECOND, 0);
        queryDateFrom.set(Calendar.MILLISECOND, 0);
        Calendar queryDateTo = Calendar.getInstance();
        queryDateTo.setTime(queryDate);
        queryDateTo.set(Calendar.HOUR_OF_DAY, 23);
        queryDateTo.set(Calendar.MINUTE, 59);
        queryDateTo.set(Calendar.SECOND, 59);
        queryDateTo.set(Calendar.MILLISECOND, 0);
        IngridHitDetail[] details = SNSAnniversaryInterfaceImpl.getInstance().getAnniversaries(queryDate, lang);
        if (details.length > 0) {

            for (int i = 0; i < details.length; i++) {
                if ((details[i] instanceof DetailedTopic) && details[i].size() > 0) {
                    DetailedTopic detail = (DetailedTopic) details[i];
                    if (log.isDebugEnabled()) {
                        log.debug("Anniversary gefunden! (topic:'" + detail.getTopicID() + "', lang:" + lang
                                + ")");
                    }
                    // check if theis item already exists
                    tx = session.beginTransaction();
                    List anniversaryList = session.createCriteria(IngridAnniversary.class)
                            .add(Restrictions.eq("topicId", detail.getTopicID()))
                            .add(Restrictions.eq("language", lang)).list();
                    tx.commit();
                    if (anniversaryList.isEmpty()) {
                        IngridAnniversary anni = new IngridAnniversary();
                        anni.setTopicId(detail.getTopicID());
                        anni.setTopicName(detail.getTopicName());
                        String from = detail.getFrom();
                        anni.setDateFrom(from);
                        if (from != null) {
                            // !!! trim, sns date may have white spaces !!! :-(
                            from = from.trim();
                            anni.setDateFrom(from);
                            Date fromDate = UtilsDate.parseDateString(from);
                            cal.setTime(fromDate);
                            if (thisYear == cal.get(Calendar.YEAR)) {
                                if (log.isDebugEnabled()) {
                                    log.debug("Skip Anniversary for (topic:'" + detail.getTopicID() + "', lang:"
                                            + lang
                                            + ") because the year of the event equals the current year.");
                                }
                                break;
                            }
                            anni.setDateFromYear(new Integer(cal.get(Calendar.YEAR)));
                            anni.setDateFromMonth(new Integer(cal.get(Calendar.MONTH) + 1));
                            anni.setDateFromDay(new Integer(cal.get(Calendar.DAY_OF_MONTH)));
                        }
                        String to = detail.getTo();
                        anni.setDateTo(to);
                        if (to != null) {
                            // !!! trim, sns date may have white spaces !!! :-(
                            to = to.trim();
                            anni.setDateTo(to);
                            Date toDate = UtilsDate.parseDateString(to);
                            cal.setTime(toDate);
                            anni.setDateToYear(new Integer(cal.get(Calendar.YEAR)));
                            anni.setDateToMonth(new Integer(cal.get(Calendar.MONTH) + 1));
                            anni.setDateToDay(new Integer(cal.get(Calendar.DAY_OF_MONTH)));
                        }
                        anni.setAdministrativeId(detail.getAdministrativeID());
                        anni.setFetched(new Date());
                        anni.setFetchedFor(queryDate);
                        anni.setLanguage(lang);

                        tx = session.beginTransaction();
                        session.save(anni);
                        tx.commit();
                    }
                }
            }
        } else {
            if (log.isWarnEnabled()) {
                log.warn("!!! SNS query: NO Anniversaries found for date = " + queryDate + " !!!");
            }
        }
        // remove old entries
        cal.setTime(new Date());
        cal.add(Calendar.DATE, -7);
        tx = session.beginTransaction();
        List deleteEntries = session.createCriteria(IngridAnniversary.class)
                .add(Restrictions.lt("fetchedFor", cal.getTime())).list();
        tx.commit();
        Iterator it = deleteEntries.iterator();
        tx = session.beginTransaction();
        while (it.hasNext()) {
            session.delete((IngridAnniversary) it.next());
        }
        tx.commit();

    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        log.error("Error executing quartz job AnniversaryFetcherJob.", e);
        throw new JobExecutionException("Error executing quartz job AnniversaryFetcherJob.", e, false);
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:de.ingrid.portal.scheduler.jobs.RSSFetcherJob.java

License:EUPL

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 */// w ww .j  av a  2 s.  co  m
public void execute(JobExecutionContext context) throws JobExecutionException {

    if (log.isDebugEnabled()) {
        log.debug("RSSFetcherJob is started ...");
    }

    Session session = HibernateUtil.currentSession();
    Transaction tx = null;
    JobDataMap dataMap = context.getJobDetail().getJobDataMap();

    int status = STATUS_OK;
    String statusCode = STATUS_CODE_NO_ERROR;
    try {

        SyndFeed feed = null;
        URL feedUrl = null;
        SyndFeedInput input = null;
        Date publishedDate = null;
        SyndEntry entry = null;
        int cnt = 0;
        int feedEntriesCount = 0;
        // String errorMsg = "";

        Calendar cal;

        // get rss sources from database
        tx = session.beginTransaction();
        List rssSources = session.createCriteria(IngridRSSSource.class).list();
        tx.commit();
        Iterator it = rssSources.iterator();

        // start timer
        startTimer();
        URLConnection urlCon = null;
        while (it.hasNext()) {
            IngridRSSSource rssSource = (IngridRSSSource) it.next();
            if (log.isDebugEnabled()) {
                log.debug("Working on: " + rssSource.getUrl());
            }
            try {
                feedUrl = new URL(rssSource.getUrl());
                urlCon = feedUrl.openConnection();
                urlCon.setConnectTimeout(15000);
                urlCon.setReadTimeout(15000);
                new Thread(new InterruptThread(urlCon, 30000)).start();
                input = new SyndFeedInput();
                feed = input.build(new XmlReader(urlCon));

                if (log.isDebugEnabled()) {
                    log.debug("Resource fetched.");
                }

                if (feed.getLanguage() == null) {
                    feed.setLanguage(rssSource.getLanguage());
                }
                if (rssSource.getDescription() != null && rssSource.getDescription().trim().length() > 0) {
                    feed.setAuthor(rssSource.getDescription().trim());
                }

                Iterator it2 = feed.getEntries().iterator();
                // work on all rss items of the feed
                while (it2.hasNext()) {
                    entry = (SyndEntry) it2.next();
                    if (log.isDebugEnabled()) {
                        log.debug("Working on item: " + entry.getTitle());
                    }
                    boolean includeEntry = true;
                    String categoryFilter = rssSource.getCategories();
                    if (categoryFilter != null && !categoryFilter.equalsIgnoreCase("all")) {
                        includeEntry = false;
                        List categories = entry.getCategories();
                        if (categories != null && categories.size() > 0) {
                            for (int i = 0; i < categories.size(); i++) {
                                SyndCategoryImpl category = (SyndCategoryImpl) categories.get(i);
                                String categoryStr = category.getName().toLowerCase();
                                if (categoryStr != null && categoryStr.length() > 0) {
                                    categoryStr = UtilsString.regExEscape(category.getName().toLowerCase());
                                    if (categoryFilter.toLowerCase().matches("^" + categoryStr + ".*|.*,"
                                            + categoryStr + ",.*|.*," + categoryStr + "$")) {
                                        includeEntry = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    // filter entries with no title
                    if (includeEntry && (entry.getTitle() == null || entry.getTitle().trim().length() == 0)) {
                        includeEntry = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Ignore item, because item has no title: " + entry);
                        }
                    }

                    publishedDate = entry.getPublishedDate();
                    // check for published date in the entry
                    if (publishedDate == null) {
                        includeEntry = false;
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "Ignore item, because a publishing date could not be retrieved: " + entry);
                        }
                    }

                    cal = Calendar.getInstance();

                    // filter entries with dates in future
                    if (includeEntry && publishedDate != null && publishedDate.after(cal.getTime())) {
                        includeEntry = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Ignore item, because the publishing date is in the future: "
                                    + publishedDate);
                        }
                    }
                    // filter dates before RSS entry window
                    cal.add(Calendar.DATE,
                            -1 * PortalConfig.getInstance().getInt(PortalConfig.RSS_HISTORY_DAYS));
                    if (includeEntry && publishedDate != null && publishedDate.before(cal.getTime())) {
                        includeEntry = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Ignore item, because the publishing date is too far in the past: "
                                    + publishedDate);
                        }
                    }

                    if (includeEntry) {
                        // process title here to have same value for checks !
                        // NOTICE: not empty, already checked above !
                        String title = processStringForStore(entry.getTitle(), 255);

                        // check if this entry already exists
                        tx = session.beginTransaction();
                        List rssEntries = session.createCriteria(IngridRSSStore.class)
                                .add(Restrictions.eq("link", entry.getLink()))
                                .add(Restrictions.eq("language", feed.getLanguage())).list();
                        tx.commit();

                        // NOTICE: link might be different although news IS THE SAME !!!
                        // (e.g. Bing always adds different tid parameter ! for ads ?).
                        // So we also check via title and date and language
                        if (rssEntries.isEmpty()) {
                            tx = session.beginTransaction();
                            rssEntries = session.createCriteria(IngridRSSStore.class)
                                    .add(Restrictions.eq("title", title))
                                    .add(Restrictions.eq("publishedDate", publishedDate))
                                    .add(Restrictions.eq("language", feed.getLanguage())).list();
                            tx.commit();
                        }

                        if (rssEntries.isEmpty()) {
                            List authors = new ArrayList();
                            SyndPerson author = new SyndPersonImpl();
                            authors.add(author);
                            if (feed.getAuthor() == null || feed.getAuthor().length() == 0) {
                                if (entry.getAuthor() == null || entry.getAuthor().length() == 0) {
                                    if (feed.getTitle() != null && feed.getTitle().length() > 0) {
                                        author.setName(feed.getTitle());
                                    } else {
                                        author.setName("nicht angegeben / not specified");
                                    }
                                } else {
                                    author.setName(entry.getAuthor());
                                }
                            } else {
                                author.setName(feed.getAuthor());
                            }
                            entry.setAuthors(authors);

                            IngridRSSStore rssEntry = new IngridRSSStore();
                            rssEntry.setTitle(title);
                            String description = processStringForStore(entry.getDescription().getValue(), null);
                            rssEntry.setDescription(description);
                            rssEntry.setLink(entry.getLink());
                            rssEntry.setLanguage(feed.getLanguage());
                            rssEntry.setPublishedDate(publishedDate);
                            rssEntry.setAuthor(entry.getAuthor());

                            tx = session.beginTransaction();
                            session.save(rssEntry);
                            tx.commit();
                            if (log.isDebugEnabled()) {
                                log.debug("Item saved to database.");
                            }

                            cnt++;
                            feedEntriesCount++;
                        } else {
                            for (int i = 0; i < rssEntries.size(); i++) {
                                session.evict(rssEntries.get(i));
                            }
                        }
                        rssEntries = null;
                    }
                }

                feed = null;
            } catch (SocketTimeoutException e) {
                log.error("Error building RSS feed (" + rssSource.getUrl() + ").", e);
                status = STATUS_ERROR;
                statusCode = STATUS_CODE_ERROR_TIMEOUT;
            } catch (SocketException e) {
                log.error("Error building RSS feed (" + rssSource.getUrl()
                        + "). Probable timeouted by watch dog thread.", e);
                status = STATUS_ERROR;
                statusCode = STATUS_CODE_ERROR_TIMEOUT;
            } catch (Throwable t) {
                log.error("Error building RSS feed (" + rssSource.getUrl() + ").", t);
                status = STATUS_ERROR;
                statusCode = STATUS_CODE_ERROR_UNSPECIFIC;
            } finally {
                try {
                    if (urlCon != null && urlCon instanceof HttpURLConnection) {
                        if (log.isDebugEnabled()) {
                            log.debug("Close '" + urlCon.getURL() + "' regulary.");
                        }
                        ((HttpURLConnection) urlCon).disconnect();
                    }
                } catch (Exception e) {
                    // ignore exception
                }

                // add information about the fetching of this feed into the
                // RSSSource database
                tx = session.beginTransaction();

                if (feedEntriesCount > 0) {
                    rssSource.setLastUpdate(new Date());
                    rssSource.setNumLastCount(feedEntriesCount);
                }

                // rssSource.setLastMessageUpdate(new Date());

                // rssSource.setError(errorMsg);

                session.save(rssSource);
                tx.commit();

                session.evict(rssSource);
                feedEntriesCount = 0;
                // errorMsg = "";
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Number of RSS entries added: " + cnt);
        }

        // remove old entries
        cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1 * PortalConfig.getInstance().getInt(PortalConfig.RSS_HISTORY_DAYS));

        tx = session.beginTransaction();
        List deleteEntries = session.createCriteria(IngridRSSStore.class)
                .add(Restrictions.lt("publishedDate", cal.getTime())).list();
        tx.commit();
        it = deleteEntries.iterator();
        tx = session.beginTransaction();
        while (it.hasNext()) {
            Object obj = it.next();
            session.evict(obj);
            session.delete((IngridRSSStore) obj);
        }
        tx.commit();
        deleteEntries.clear();
    } catch (Exception t) {
        if (tx != null) {
            tx.rollback();
        }
        if (log.isErrorEnabled()) {
            log.error("Error executing quartz job RSSFetcherJob.", t);
        }
        status = STATUS_ERROR;
        statusCode = STATUS_CODE_ERROR_UNSPECIFIC;
        throw new JobExecutionException("Error executing quartz job RSSFetcherJob.", t, false);
    } finally {
        computeTime(dataMap, stopTimer());
        if (log.isDebugEnabled()) {
            log.debug("Update quartz job data.");
        }
        updateJobData(context, status, statusCode);
        updateJob(context);
        HibernateUtil.closeSession();
        if (log.isDebugEnabled()) {
            log.debug("Hibernate session is closed.");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("RSSFetcherJob finished.");
    }
}

From source file:de.iteratec.iteraplan.businesslogic.reports.query.node.AbstractLeafNode.java

License:Open Source License

/**
 * Returns the {@link Criterion} for the specified {@code effectivePropertyName} and {@code comparator}.
 * //from  w w w .j av a  2 s  .co m
 * @param effectivePropertyName the property name path
 * @param comparator the comparator describing the compare operation
 * @param attrType string representation of the property's attribute type as in {@link BBAttribute#getTypeOfAttribute(String)} 
 * @return the newly created {@link Criterion} for the specified {@code comparator} or {@code null} if the 
 *    comparator is not supported
 */
protected Criterion getCriterionForComparator(String effectivePropertyName, Comparator comparator,
        String attrType) {
    Criterion criterion = null;
    switch (comparator) {
    case EQ:
        criterion = Restrictions.eq(effectivePropertyName, getProcessedPattern());
        break;
    case GEQ:
        criterion = Restrictions.ge(effectivePropertyName, getProcessedPattern());
        break;
    case LEQ:
        criterion = Restrictions.le(effectivePropertyName, getProcessedPattern());
        break;
    case GT:
        criterion = Restrictions.gt(effectivePropertyName, getProcessedPattern());
        break;
    case LT:
        criterion = Restrictions.lt(effectivePropertyName, getProcessedPattern());
        break;
    case LIKE:
        criterion = new IteraplanLikeExpression(effectivePropertyName, getProcessedPattern().toString(), true);
        break;
    case NOT_LIKE:
        criterion = Restrictions.not(
                new IteraplanLikeExpression(effectivePropertyName, getProcessedPattern().toString(), true));
        break;
    case IS:
        // see Type#getSpecialPropertyHQLStrings
        criterion = "null".equals(getPattern()) ? Restrictions.isNull(effectivePropertyName)
                : Restrictions.isNotNull(effectivePropertyName);
        break;
    case ANY_ASSIGNMENT:
        criterion = getAnyAssignmentCriterion(effectivePropertyName, attrType);
        break;
    case NO_ASSIGNMENT:
        criterion = getNoAssignmentCriterion(effectivePropertyName, attrType);
        break;
    case NEQ:
        criterion = Restrictions.ne(effectivePropertyName, getProcessedPattern());
        break;
    default:
        break;
    }

    return criterion;
}

From source file:de.iteratec.iteraplan.businesslogic.reports.query.node.DateAttributeLeafNode.java

License:Open Source License

/** {@inheritDoc} */
@Override//from w ww  .j  a v a 2  s.  c  o m
protected Criterion getCriterionForComparator() {
    Criterion criterion = null;
    switch (getComparator()) {
    case GT:
        criterion = Restrictions.gt("value", getPattern());
        break;
    case EQ:
        criterion = Restrictions.eq("value", getPattern());
        break;
    case LT:
        criterion = Restrictions.lt("value", getPattern());
        break;
    case ANY_ASSIGNMENT:
        criterion = Restrictions.naturalId();
        break;
    default:
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR);
    }

    return criterion;
}

From source file:de.iteratec.iteraplan.businesslogic.reports.query.node.NumberAttributeLeafNode.java

License:Open Source License

/** {@inheritDoc} */
@Override// ww  w  .  j a  v  a 2  s  .c o m
protected Criterion getCriterionForComparator() {
    String value = "value";

    Criterion criterion = null;
    switch (getComparator()) {
    case GT:
        criterion = Restrictions.gt(value, getPattern());
        break;
    case GEQ:
        criterion = Restrictions.ge(value, getPattern());
        break;
    case EQ:
        criterion = Restrictions.eq(value, getPattern());
        break;
    case LEQ:
        criterion = Restrictions.le(value, getPattern());
        break;
    case LT:
        criterion = Restrictions.lt(value, getPattern());
        break;
    case ANY_ASSIGNMENT:
        criterion = Restrictions.naturalId();
        break;
    default:
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR);
    }

    return criterion;
}

From source file:de.lemo.dms.connectors.moodle_2_3.ExtractAndMapMoodle.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void getLMStables(final DBConfigObject dbConf, final long readingfromtimestamp,
        final long readingtotimestamp, List<Long> courses, List<String> logins) {

    // accessing DB by creating a session and a transaction using HibernateUtil
    final Session session = HibernateUtil.getSessionFactory(dbConf).openSession();
    // Session session = HibernateUtil.getDynamicSourceDBFactoryMoodle("jdbc:mysql://localhost/moodle19",
    session.clear();/*from  w  w  w  . j  a v a  2 s  . co  m*/
    final Transaction tx = session.beginTransaction();

    // reading the LMS Database, create tables as lists of instances of the DB-table classes
    Criteria criteria;
    boolean hasCR = false;
    if (courses != null && courses.size() > 0)
        hasCR = true;

    boolean empty = false;

    if (this.userLms == null) {

        //Read Context
        criteria = session.createCriteria(ContextLMS.class, "obj");
        List<Long> contextLevels = new ArrayList<Long>();
        contextLevels.add(40L);
        contextLevels.add(50L);

        criteria.add(Restrictions.in("obj.contextlevel", contextLevels));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.contextLms = criteria.list();
        logger.info("ContextLMS tables: " + this.contextLms.size());

        if (logins != null && !logins.isEmpty()) {
            List<String> archetypes = new ArrayList<String>();
            List<Long> roleIds = new ArrayList<Long>();
            List<String> userIds = new ArrayList<String>();

            archetypes.add("manager");
            archetypes.add("coursecreator");
            archetypes.add("teacher");
            archetypes.add("editingteacher");

            criteria = session.createCriteria(RoleLMS.class, "obj");
            criteria.add(Restrictions.in("obj.archetype", archetypes));
            for (RoleLMS role : (List<RoleLMS>) criteria.list())
                roleIds.add(role.getId());

            criteria = session.createCriteria(UserLMS.class, "obj");
            criteria.add(Restrictions.in("obj.username", logins));
            for (UserLMS user : (List<UserLMS>) criteria.list())
                userIds.add(user.getId() + "");

            criteria = session.createCriteria(RoleAssignmentsLMS.class, "obj");
            criteria.add(Restrictions.in("obj.userid", userIds));
            criteria.add(Restrictions.in("obj.roleid", roleIds));
            for (ContextLMS c : this.contextLms) {
                for (RoleAssignmentsLMS ra : (List<RoleAssignmentsLMS>) criteria.list()) {
                    if (c.getContextlevel() == 50 && c.getId() == ra.getContextid()) {
                        courses.add(c.getInstanceid());
                        hasCR = true;
                    }
                }
            }

        }

        criteria = session.createCriteria(AssignLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.assignLms = criteria.list();
        logger.info("AssignLMS tables: " + this.assignLms.size());

        criteria = session.createCriteria(EnrolLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.courseid", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.enrolLms = criteria.list();
        logger.info("EnrolLMS tables: " + this.enrolLms.size());

        criteria = session.createCriteria(ModulesLMS.class, "obj");
        criteria.addOrder(Property.forName("obj.id").asc());
        this.modulesLms = criteria.list();
        logger.info("ModulesLMS tables: " + this.modulesLms.size());

        criteria = session.createCriteria(UserEnrolmentsLMS.class, "obj");
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (EnrolLMS e : this.enrolLms)
                ids.add(e.getId());
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.enrolid", ids));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        if (!(hasCR && empty))
            this.userEnrolmentsLms = criteria.list();
        else
            this.userEnrolmentsLms = new ArrayList<UserEnrolmentsLMS>();
        logger.info("UserEnrolmentsLMS tables: " + this.userEnrolmentsLms.size());

        criteria = session.createCriteria(CourseModulesLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.courseModulesLms = criteria.list();
        logger.info("CourseModulesLMS tables: " + this.courseModulesLms.size());

        criteria = session.createCriteria(ResourceLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.resourceLms = criteria.list();
        logger.info("ResourceLMS tables: " + this.resourceLms.size());

        //Read Urls
        criteria = session.createCriteria(UrlLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));

        criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.urlLms = criteria.list();
        logger.info("UrlLMS tables: " + this.urlLms.size());

        //Read Pages
        criteria = session.createCriteria(PageLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));

        criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.pageLms = criteria.list();
        logger.info("UrlLMS tables: " + this.pageLms.size());

        criteria = session.createCriteria(CourseLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.id", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.courseLms = criteria.list();
        logger.info("CourseLMS tables: " + this.courseLms.size());

        criteria = session.createCriteria(ChatLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.chatLms = criteria.list();
        logger.info("ChatLMS tables: " + this.chatLms.size());

        criteria = session.createCriteria(CourseCategoriesLMS.class, "obj");
        criteria.addOrder(Property.forName("obj.id").asc());
        this.courseCategoriesLms = criteria.list();
        logger.info("CourseCategoriesLMS tables: " + this.courseCategoriesLms.size());

        criteria = session.createCriteria(ForumLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.forumLms = criteria.list();
        logger.info("ForumLMS tables: " + this.forumLms.size());

        criteria = session.createCriteria(GroupsLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.courseid", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.groupLms = criteria.list();
        logger.info("GroupsLMS tables: " + this.groupLms.size());

        criteria = session.createCriteria(QuizLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.quizLms = criteria.list();
        logger.info("QuizLMS tables: " + this.quizLms.size());

        criteria = session.createCriteria(WikiLMS.class, "obj");
        if (hasCR)
            criteria.add(Restrictions.in("obj.course", courses));
        criteria.addOrder(Property.forName("obj.id").asc());
        this.wikiLms = criteria.list();
        logger.info("WikiLMS tables: " + this.wikiLms.size());

        criteria = session.createCriteria(QuizQuestionInstancesLMS.class, "obj");
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (QuizLMS e : this.quizLms)
                ids.add(e.getId());
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.quiz", ids));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        if (!(hasCR && empty))
            this.quizQuestionInstancesLms = criteria.list();
        else
            this.quizQuestionInstancesLms = new ArrayList<QuizQuestionInstancesLMS>();
        logger.info("QuizQuestionInstancesLMS tables: " + this.quizQuestionInstancesLms.size());

        criteria = session.createCriteria(QuestionLMS.class, "obj");
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (QuizQuestionInstancesLMS e : this.quizQuestionInstancesLms)
                ids.add(e.getQuestion());
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.id", ids));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        if (!(hasCR && empty))
            this.questionLms = criteria.list();
        else
            this.questionLms = new ArrayList<QuestionLMS>();
        logger.info("QuestionLMS tables: " + this.questionLms.size());

        criteria = session.createCriteria(RoleLMS.class, "obj");
        criteria.addOrder(Property.forName("obj.id").asc());
        this.roleLms = criteria.list();
        logger.info("RoleLMS tables: " + this.roleLms.size());

        session.clear();

        /*
        criteria = session.createCriteria(AssignmentLMS.class, "obj");
        if(hasCR)
        {
           criteria.add(Restrictions.in("obj.course", courses));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        this.assignmentLms = criteria.list();
        logger.info("AssignmentLMS tables: " + this.assignmentLms.size());
        */
        criteria = session.createCriteria(ScormLMS.class, "obj");
        if (hasCR) {
            criteria.add(Restrictions.in("obj.course", courses));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        this.scormLms = criteria.list();
        logger.info("ScormLMS tables: " + this.scormLms.size());

        criteria = session.createCriteria(GradeItemsLMS.class, "obj");
        if (hasCR) {
            criteria.add(Restrictions.in("obj.courseid", courses));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        this.gradeItemsLms = criteria.list();
        logger.info("GradeItemsLMS tables: " + this.gradeItemsLms.size());

        criteria = session.createCriteria(RoleAssignmentsLMS.class, "obj");
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (ContextLMS c : this.contextLms) {
                if (c.getContextlevel() == 50 && courses.contains(c.getInstanceid()))
                    ids.add(c.getId());
            }
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.contextid", ids));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        if (!(hasCR && empty))
            this.roleAssignmentsLms = criteria.list();
        else
            this.roleAssignmentsLms = new ArrayList<RoleAssignmentsLMS>();
        logger.info("RoleAssignmentsLMS tables: " + this.roleAssignmentsLms.size());

        criteria = session.createCriteria(UserLMS.class, "obj");
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (RoleAssignmentsLMS e : this.roleAssignmentsLms)
                ids.add(Long.valueOf(e.getUserid()));
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.id", ids));
        }
        criteria.addOrder(Property.forName("obj.id").asc());
        if (!(hasCR && empty))
            this.userLms = criteria.list();
        else
            this.userLms = new ArrayList<UserLMS>();
        logger.info("UserLMS tables: " + this.userLms.size());
    }

    criteria = session.createCriteria(QuizAttemptsLMS.class, "obj");
    if (hasCR)
        if (hasCR) {
            ArrayList<Long> ids = new ArrayList<Long>();
            for (QuizLMS e : this.quizLms)
                ids.add(e.getId());
            if (!(empty = ids.isEmpty()))
                criteria.add(Restrictions.in("obj.quiz", ids));
        }
    criteria.add(Restrictions.lt("obj.timemodified", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.quizAttemptsLms = criteria.list();
    else
        this.quizAttemptsLms = new ArrayList<QuizAttemptsLMS>();
    logger.info("QuizAttemptsLMS tables: " + this.quizAttemptsLms.size());

    criteria = session.createCriteria(LogLMS.class, "obj");
    if (hasCR)
        criteria.add(Restrictions.in("obj.course", courses));
    criteria.add(Restrictions.lt("obj.time", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.time", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    this.logLms = criteria.list();
    logger.info("LogLMS tables: " + this.logLms.size());

    criteria = session.createCriteria(ChatLogLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (ChatLMS e : this.chatLms)
            ids.add(e.getId());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.chat", ids));
    }
    criteria.add(Restrictions.lt("obj.timestamp", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timestamp", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.chatLogLms = criteria.list();
    else
        this.chatLogLms = new ArrayList<ChatLogLMS>();
    logger.info("ChatLogLMS tables: " + this.chatLogLms.size());

    final Query forumPosts;
    if (!hasCR) {
        forumPosts = session.createQuery(
                "from ForumPostsLMS x where x.created>=:readingtimestamp and x.created<=:ceiling order by x.id asc");
        forumPosts.setParameter("readingtimestamp", readingfromtimestamp);
        forumPosts.setParameter("ceiling", readingtotimestamp);
        this.forumPostsLms = forumPosts.list();
    } else {
        String courseClause = "(";
        for (int i = 0; i < courses.size(); i++) {
            courseClause += courses.get(i);
            if (i < courses.size() - 1)
                courseClause += ",";
            else
                courseClause += ")";
        }
        forumPosts = session.createSQLQuery(
                "SELECT posts.id,posts.userid,posts.created,posts.modified,posts.subject,posts.message,posts.discussion from forum_posts as posts JOIN log as logs ON posts.userid = logs.userid Where logs.course in "
                        + courseClause
                        + " and (posts.created = logs.time or posts.modified = logs.time) AND posts.created>=:readingtimestamp and posts.created<=:ceiling");
        forumPosts.setParameter("readingtimestamp", readingfromtimestamp);
        forumPosts.setParameter("ceiling", readingtotimestamp);
        List<Object[]> tmpl = forumPosts.list();
        if (this.forumPostsLms == null)
            this.forumPostsLms = new ArrayList<ForumPostsLMS>();
        for (Object[] obj : tmpl) {
            ForumPostsLMS p = new ForumPostsLMS();
            if (obj[0].getClass().equals(BigInteger.class)) {
                p.setId(((BigInteger) obj[0]).longValue());
            } else {
                p.setId(((Integer) obj[0]).longValue());
            }
            if (obj[0].getClass().equals(BigInteger.class)) {
                p.setUserid(((BigInteger) obj[1]).longValue());
            } else {
                p.setUserid(((Integer) obj[1]).longValue());
            }
            if (obj[0].getClass().equals(BigInteger.class)) {
                p.setCreated(((BigInteger) obj[2]).longValue());
            } else {
                p.setCreated(((Integer) obj[2]).longValue());
            }
            if (obj[0].getClass().equals(BigInteger.class)) {
                p.setModified(((BigInteger) obj[3]).longValue());
            } else {
                p.setModified(((Integer) obj[3]).longValue());
            }
            p.setSubject((String) obj[4]);
            p.setMessage((String) obj[5]);
            if (obj[0].getClass().equals(BigInteger.class)) {
                p.setDiscussion(((BigInteger) obj[6]).longValue());
            } else {
                p.setDiscussion(((Integer) obj[6]).longValue());
            }
            this.forumPostsLms.add(p);

        }
    }
    logger.info("ForumPostsLMS tables: " + this.forumPostsLms.size());

    final Query forumPostsModified;
    if (!hasCR) {
        forumPostsModified = session.createQuery(
                "from ForumPostsLMS x where x.modified>=:readingtimestamp and x.modified<=:ceiling order by x.id asc");
        this.forumPostsLms.addAll(forumPostsModified.list());
    } else {
        String courseClause = "(";
        for (int i = 0; i < courses.size(); i++) {
            courseClause += courses.get(i);
            if (i < courses.size() - 1)
                courseClause += ",";
            else
                courseClause += ")";
        }
        forumPostsModified = session.createSQLQuery(
                "SELECT posts.id,posts.userid,posts.created,posts.modified,posts.subject,posts.message from mdl_forum_posts as posts JOIN mdl_log as logs ON posts.userid = logs.userid Where logs.course in "
                        + courseClause
                        + " and (posts.created = logs.time or posts.modified = logs.time) AND posts.modified>=:readingtimestamp and posts.modified<=:ceiling");
        forumPostsModified.setParameter("readingtimestamp", readingfromtimestamp);
        forumPostsModified.setParameter("ceiling", readingtotimestamp);
        List<Object[]> tmpl = forumPostsModified.list();
        if (this.forumPostsLms == null)
            this.forumPostsLms = new ArrayList<ForumPostsLMS>();
        for (Object[] obj : tmpl) {
            ForumPostsLMS p = new ForumPostsLMS();
            p.setId(((Integer) obj[0]).longValue());
            p.setUserid(((Integer) obj[1]).longValue());
            p.setCreated(((Integer) obj[2]).longValue());
            p.setModified(((Integer) obj[3]).longValue());
            p.setSubject((String) obj[4]);
            p.setMessage((String) obj[5]);

            this.forumPostsLms.add(p);

        }
    }
    logger.info("ForumPostsModifiedLMS tables: " + this.forumPostsLms.size());

    session.clear();

    criteria = session.createCriteria(AssignGradesLMS.class, "obj");
    if (hasCR) {
        List<Long> tmp = new ArrayList<Long>();
        for (AssignLMS assign : assignLms) {
            tmp.add(assign.getId());
        }

        if (!(empty = tmp.isEmpty()))
            criteria.add(Restrictions.in("obj.assignment", tmp));
    }
    criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
    criteria.add(Restrictions.lt("obj.timemodified", readingtotimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.assignGradesLms = criteria.list();
    else
        this.assignGradesLms = new ArrayList<AssignGradesLMS>();
    logger.info("AssignGradesLMS tables: " + this.assignGradesLms.size());

    criteria = session.createCriteria(GroupsMembersLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (GroupsLMS e : this.groupLms)
            ids.add(e.getId());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.groupid", ids));
    }
    criteria.add(Restrictions.lt("obj.timeadded", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timeadded", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.groupMembersLms = criteria.list();
    else
        this.groupMembersLms = new ArrayList<GroupsMembersLMS>();
    logger.info("GroupsMembersLMS tables: " + this.groupMembersLms.size());

    criteria = session.createCriteria(QuestionStatesLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (QuizQuestionInstancesLMS e : this.quizQuestionInstancesLms)
            ids.add(e.getQuestion());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.question", ids));
    }
    criteria.add(Restrictions.lt("obj.timestamp", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timestamp", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.questionStatesLms = criteria.list();
    else
        this.questionStatesLms = new ArrayList<QuestionStatesLMS>();
    logger.info("QuestionStatesLMS tables: " + this.questionStatesLms.size());

    /*
    criteria = session.createCriteria(AssignmentSubmissionsLMS.class, "obj");
    if(hasCR)
    {
       ArrayList<Long> ids = new ArrayList<Long>();
        for(AssignmentLMS e : this.assignmentLms)
     ids.add(e.getId());
        if(!(empty = ids.isEmpty()))
     criteria.add(Restrictions.in("obj.id", ids));
    }
    criteria.add(Restrictions.lt("obj.timecreated", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timecreated", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if(!(hasCR && empty))
       this.assignmentSubmissionLms = criteria.list();
    else
       this.assignmentSubmissionLms = new ArrayList<AssignmentSubmissionsLMS>();
    logger.info("AssignmentSubmissionsLMS tables: " + this.userLms.size());
     */

    criteria = session.createCriteria(QuizGradesLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (QuizLMS e : this.quizLms)
            ids.add(e.getId());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.quiz", ids));
    }
    criteria.add(Restrictions.lt("obj.timemodified", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.quizGradesLms = criteria.list();
    else
        this.quizGradesLms = new ArrayList<QuizGradesLMS>();
    logger.info("QuizGradesLMS tables: " + this.quizGradesLms.size());

    criteria = session.createCriteria(ForumDiscussionsLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (ForumLMS e : this.forumLms)
            ids.add(e.getId());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.forum", ids));
    }
    criteria.add(Restrictions.lt("obj.timemodified", readingtotimestamp));
    criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.forumDiscussionsLms = criteria.list();
    else
        this.forumDiscussionsLms = new ArrayList<ForumDiscussionsLMS>();
    logger.info("ForumDiscussionsLMS tables: " + this.forumDiscussionsLms.size());

    criteria = session.createCriteria(GradeGradesLMS.class, "obj");
    if (hasCR) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (GradeItemsLMS e : this.gradeItemsLms)
            ids.add(e.getId());
        if (!(empty = ids.isEmpty()))
            criteria.add(Restrictions.in("obj.itemid", ids));
    }
    //criteria.add(Restrictions.lt("obj.timemodified", readingtotimestamp));
    //criteria.add(Restrictions.gt("obj.timemodified", readingfromtimestamp));
    criteria.addOrder(Property.forName("obj.id").asc());
    if (!(hasCR && empty))
        this.gradeGradesLms = criteria.list();
    else
        this.gradeGradesLms = new ArrayList<GradeGradesLMS>();
    logger.info("GradeGradesLMS tables: " + this.gradeGradesLms.size());

    session.clear();

    // hibernate session finish and close
    tx.commit();
    session.close();

}