Example usage for org.hibernate Query setCacheable

List of usage examples for org.hibernate Query setCacheable

Introduction

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

Prototype

Query<R> setCacheable(boolean cacheable);

Source Link

Document

Enable/disable second level query (result) caching for this query.

Usage

From source file:org.unitedinternet.cosmo.dao.hibernate.UserDaoImpl.java

License:Apache License

private User findUserByEmail(String email) {
    Session session = getSession();//  w w  w. j av a2  s.  c  o  m
    Query hibQuery = session.getNamedQuery("user.byEmail").setParameter("email", email);
    hibQuery.setCacheable(true);
    hibQuery.setFlushMode(FlushMode.MANUAL);
    List users = hibQuery.list();
    if (users.size() > 0) {
        return (User) users.get(0);
    } else {
        return null;
    }
}

From source file:org.unitedinternet.cosmo.dao.hibernate.UserDaoImpl.java

License:Apache License

private User findUserByEmailIgnoreCase(String email) {
    Session session = getSession();// w ww .j a  v  a2  s  . c  o m
    Query hibQuery = session.getNamedQuery("user.byEmail.ignorecase").setParameter("email", email);
    hibQuery.setCacheable(true);
    hibQuery.setFlushMode(FlushMode.MANUAL);
    List users = hibQuery.list();
    if (users.size() > 0) {
        return (User) users.get(0);
    } else {
        return null;
    }
}

From source file:org.unitime.banner.model.dao.BannerResponseDAO.java

License:Apache License

public List find(Long sessionId, Date startDate, Date stopDate, String searchSubject, Set subjects,
        Long searchManager, Long searchDepartment, String searchCourseNumber, String searchCrn,
        String searchXlst, String searchMessage, int maxResults, boolean showHistory, boolean actionAudit,
        boolean actionUpdate, boolean actionDelete, boolean typeSuccess, boolean typeError, boolean typeWarning)
        throws LoggableException {

    List queueOuts = null;// ww  w  . j a v a 2 s  .  co  m
    Transaction tx = null;
    try {

        tx = getSession().beginTransaction();

        String whereHql = " where rp.termCode=:termCode ";

        org.hibernate.Session hibSession = new BannerResponseDAO().getSession();
        BannerSession bs = BannerSession.findBannerSessionForSession(sessionId, hibSession);

        String joinHql = "";
        if ((searchManager != null && searchManager > 0)
                || (searchDepartment != null && searchDepartment > 0)) {
            joinHql += " SubjectArea as sa " + " inner join sa.department as dept ";
            whereHql += " and sa.session = :sessionId " + "and sa.subjectAreaAbbreviation = rp.subjectCode ";
            if (searchDepartment != null && searchDepartment > 0) {
                whereHql += " and dept.uniqueId = :departmentId ";
            }
        }
        if (searchManager != null && searchManager > 0) {
            joinHql += " inner join dept.timetableManagers as mgr ";
            whereHql += " and mgr.uniqueId=:managerId";
        }

        if (startDate != null) {
            whereHql += " and rp.activityDate >= :startDate";
        }
        String fromHql = " from ";
        if (joinHql.length() > 0) {
            fromHql += joinHql + ",";
        }
        fromHql += " BannerResponse as rp";

        if (stopDate != null) {
            whereHql += " and rp.activityDate <= :stopDate";
        }

        if (searchSubject != null && searchSubject != "") {
            whereHql += " and upper(rp.subjectCode) = upper(:searchSubject) ";
        } else {
            int i = 1;
            for (Iterator it = subjects.iterator(); it.hasNext();) {
                SubjectArea s = (SubjectArea) it.next();
                if (i == 1) {
                    whereHql += " and ( rp.subjectCode in ( ";
                } else {
                    whereHql += " , ";
                }
                whereHql += " '" + s.getSubjectAreaAbbreviation() + "'";
                i++;
            }
            if (i > 1) {
                whereHql += "))";
            }
        }

        if (searchCourseNumber != null && searchCourseNumber != "") {
            whereHql += " and upper(rp.courseNumber) = upper(:searchCourseNumber) ";
        }

        if (searchCrn != null && searchCrn != "") {
            whereHql += " and rp.crn = upper(:searchCrn) ";
        }

        if (searchXlst != null && searchXlst != "") {
            whereHql += " and upper(rp.xlstGroup) like upper(:searchXlst) ";
        }

        if ((actionUpdate || actionAudit || actionDelete) && !(actionUpdate && actionAudit && actionDelete)) {
            whereHql += " and rp.action in (";
            if (actionUpdate) {
                whereHql += "'UPDATE'";
            }
            if (actionAudit) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'AUDIT'";
            }
            if (actionDelete) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'DELETE'";
            }
            whereHql += ") ";
        }

        if ((typeError || typeSuccess || typeWarning) && !(typeError && typeSuccess && typeWarning)) {
            whereHql += " and rp.type in (";
            if (typeError) {
                whereHql += "'ERROR'";
            }
            if (typeSuccess) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'SUCCESS'";
            }
            if (typeWarning) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'WARNING'";
            }
            whereHql += ") ";
        }

        if (searchMessage != null && searchMessage != "") {
            whereHql += " and upper(rp.message) like upper(:searchMessage) ";
        }
        if (!showHistory) {
            whereHql += " and rp.queueId = (select max(queueId) from BannerResponse rp3 where rp3.termCode = rp.termCode and rp3.crn = rp.crn and ((rp3.xlstGroup is null and rp.xlstGroup is null) or (rp3.xlstGroup = rp.xlstGroup))) ";
        }

        String hql = "select rp " + fromHql + whereHql
                + " order by rp.activityDate desc, rp.sequenceNumber desc ";

        Query query = getSession().createQuery(hql);
        query.setString("termCode", bs.getBannerTermCode());

        if (startDate != null) {
            query.setDate("startDate", startDate);
        }

        if (stopDate != null) {
            query.setDate("stopDate", stopDate);
        }

        if ((searchManager != null && searchManager > 0)
                || (searchDepartment != null && searchDepartment > 0)) {
            query.setLong("sessionId", sessionId);
            if (searchDepartment != null && searchDepartment > 0) {
                query.setLong("departmentId", searchDepartment);
            }
        }
        if (searchManager != null && searchManager > 0) {
            query.setLong("managerId", searchManager);
        }

        if (searchSubject != null && searchSubject != "") {
            query.setString("searchSubject", searchSubject);
        }

        if (searchCourseNumber != null && searchCourseNumber != "") {
            query.setString("searchCourseNumber", searchCourseNumber);
        }

        if (searchCrn != null && searchCrn != "") {
            query.setString("searchCrn", searchCrn);
        }

        if (searchXlst != null && searchXlst != "") {
            query.setString("searchXlst", searchXlst.replace("*", "%"));
        }

        if (searchMessage != null && searchMessage != "") {
            query.setString("searchMessage", searchMessage.replace('*', '%'));
        }

        if (maxResults < 0)
            maxResults = 0;

        if (maxResults > 0) {
            query.setMaxResults(maxResults);
        }

        query.setCacheable(false);

        queueOuts = query.list();
        tx.commit();

    } catch (HibernateException e) {
        tx.rollback();
        throw new LoggableException(e);
    } finally {
        getSession().close();
    }
    return queueOuts;
}

From source file:org.unitime.colleague.model.dao.ColleagueResponseDAO.java

License:Apache License

public List find(Long sessionId, Date startDate, Date stopDate, String searchSubject, Set subjects,
        Long searchManager, Long searchDepartment, String searchCourseNumber, String searchColleagueId,
        String searchMessage, int maxResults, boolean showHistory, boolean actionAudit, boolean actionUpdate,
        boolean actionDelete, boolean typeSuccess, boolean typeError, boolean typeWarning)
        throws LoggableException {

    List queueOuts = null;//w ww  .ja  v a 2s  . c  om
    Transaction tx = null;
    try {

        tx = getSession().beginTransaction();

        String whereHql = " where rp.termCode=:termCode ";

        org.hibernate.Session hibSession = new ColleagueResponseDAO().getSession();
        ColleagueSession bs = ColleagueSession.findColleagueSessionForSession(sessionId, hibSession);

        String joinHql = "";
        if ((searchManager != null && searchManager > 0)
                || (searchDepartment != null && searchDepartment > 0)) {
            joinHql += " SubjectArea as sa " + " inner join sa.department as dept ";
            whereHql += " and sa.session = :sessionId " + "and sa.subjectAreaAbbreviation = rp.subjectCode ";
            if (searchDepartment != null && searchDepartment > 0) {
                whereHql += " and dept.uniqueId = :departmentId ";
            }
        }
        if (searchManager != null && searchManager > 0) {
            joinHql += " inner join dept.timetableManagers as mgr ";
            whereHql += " and mgr.uniqueId=:managerId";
        }

        if (startDate != null) {
            whereHql += " and rp.activityDate >= :startDate";
        }
        String fromHql = " from ";
        if (joinHql.length() > 0) {
            fromHql += joinHql + ",";
        }
        fromHql += " ColleagueResponse as rp";

        if (stopDate != null) {
            whereHql += " and rp.activityDate <= :stopDate";
        }

        if (searchSubject != null && searchSubject != "") {
            whereHql += " and upper(rp.subjectCode) = upper(:searchSubject) ";
        } else {
            int i = 1;
            for (Iterator it = subjects.iterator(); it.hasNext();) {
                SubjectArea s = (SubjectArea) it.next();
                if (i == 1) {
                    whereHql += " and ( rp.subjectCode in ( ";
                } else {
                    whereHql += " , ";
                }
                whereHql += " '" + s.getSubjectAreaAbbreviation() + "'";
                i++;
            }
            if (i > 1) {
                whereHql += "))";
            }
        }

        if (searchCourseNumber != null && searchCourseNumber != "") {
            whereHql += " and upper(rp.courseNumber) = upper(:searchCourseNumber) ";
        }

        if (searchColleagueId != null && searchColleagueId != "") {
            whereHql += " and rp.colleagueId = upper(:searchColleagueId) ";
        }

        if ((actionUpdate || actionAudit || actionDelete) && !(actionUpdate && actionAudit && actionDelete)) {
            whereHql += " and rp.action in (";
            if (actionUpdate) {
                whereHql += "'UPDATE'";
            }
            if (actionAudit) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'AUDIT'";
            }
            if (actionDelete) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'DELETE'";
            }
            whereHql += ") ";
        }

        if ((typeError || typeSuccess || typeWarning) && !(typeError && typeSuccess && typeWarning)) {
            whereHql += " and rp.type in (";
            if (typeError) {
                whereHql += "'ERROR'";
            }
            if (typeSuccess) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'SUCCESS'";
            }
            if (typeWarning) {
                if (!whereHql.endsWith("("))
                    whereHql += ",";
                whereHql += "'WARNING'";
            }
            whereHql += ") ";
        }

        if (searchMessage != null && searchMessage != "") {
            whereHql += " and upper(rp.message) like upper(:searchMessage) ";
        }
        if (!showHistory) {
            whereHql += " and rp.queueId = (select max(queueId) from ColleagueResponse rp3 where rp3.termCode = rp.termCode and rp3.colleagueId = rp.colleagueId) ";
        }

        String hql = "select rp " + fromHql + whereHql
                + " order by rp.activityDate desc, rp.sequenceNumber desc ";

        Query query = getSession().createQuery(hql);
        query.setString("termCode", bs.getColleagueTermCode());

        if (startDate != null) {
            query.setDate("startDate", startDate);
        }

        if (stopDate != null) {
            query.setDate("stopDate", stopDate);
        }

        if ((searchManager != null && searchManager > 0)
                || (searchDepartment != null && searchDepartment > 0)) {
            query.setLong("sessionId", sessionId);
            if (searchDepartment != null && searchDepartment > 0) {
                query.setLong("departmentId", searchDepartment);
            }
        }
        if (searchManager != null && searchManager > 0) {
            query.setLong("managerId", searchManager);
        }

        if (searchSubject != null && searchSubject != "") {
            query.setString("searchSubject", searchSubject);
        }

        if (searchCourseNumber != null && searchCourseNumber != "") {
            query.setString("searchCourseNumber", searchCourseNumber);
        }

        if (searchColleagueId != null && searchColleagueId != "") {
            query.setString("searchColleagueId", searchColleagueId);
        }

        if (searchMessage != null && searchMessage != "") {
            query.setString("searchMessage", searchMessage.replace('*', '%'));
        }

        if (maxResults < 0)
            maxResults = 0;

        if (maxResults > 0) {
            query.setMaxResults(maxResults);
        }

        query.setCacheable(false);

        queueOuts = query.list();
        tx.commit();

    } catch (HibernateException e) {
        tx.rollback();
        throw new LoggableException(e);
    } finally {
        getSession().close();
    }
    return queueOuts;
}

From source file:org.unitime.timetable.action.ajax.CourseNumSuggestAction.java

License:Open Source License

/**
 * Retrieve Suggestion List of Course Numbers for a given Subject Area
 *//*  w ww  .  j  a v  a2  s .c o  m*/
public Collection getMultipleSuggestionList(HttpServletRequest request, Map map) {

    List result = null;

    // Read form variables -- Classes Schedule Screen
    if (map.get("session") != null && map.get("session") instanceof String && map.get("subjectArea") != null
            && map.get("subjectArea") instanceof String && map.get("courseNumber") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("       and co.subjectArea.subjectAreaAbbreviation = :subjectArea");
        query.append("       and co.courseNbr like :courseNbr ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(map.get("session").toString()));
        q.setString("subjectArea", map.get("subjectArea").toString());
        q.setString("courseNbr", map.get("courseNumber").toString() + "%");

        result = q.list();

        if (result == null)
            result = new ArrayList();

        return result;
    }

    User user = Web.getUser(request.getSession());

    // Security Checks
    if (!Web.isLoggedIn(request.getSession()) || user == null
            || user.getAttribute(Constants.SESSION_ID_ATTR_NAME) == null)
        return new ArrayList();

    // Get Academic Session
    String acadSessionId = user.getAttribute(Constants.SESSION_ID_ATTR_NAME).toString();

    // Read form variables -- Instructional Offerings Screen, Reservations Screen
    if (map.get("subjectAreaId") != null && map.get("courseNbr") != null
            && map.get("subjectAreaId").toString().length() > 0
            && !Constants.ALL_OPTION_VALUE.equals(map.get("subjectAreaId"))) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId ");
        query.append("        and co.courseNbr like :courseNbr ");
        //query.append("        and co.isControl = true ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("subjectAreaId").toString()));
        q.setString("courseNbr", map.get("courseNbr").toString() + "%");

        result = q.list();
    }

    // Read form variables -- Distribution Preferences Screen
    if (map.get("filterSubjectAreaId") != null
            && !Constants.BLANK_OPTION_VALUE.equals(map.get("filterSubjectAreaId"))
            && !Constants.ALL_OPTION_VALUE.equals(map.get("filterSubjectAreaId"))
            && map.get("filterCourseNbr") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId ");
        query.append("        and co.courseNbr like :courseNbr ");
        query.append("        and co.isControl = true ");
        query.append("        and co.instructionalOffering.notOffered = false ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("filterSubjectAreaId").toString()));
        q.setString("courseNbr", map.get("filterCourseNbr").toString() + "%");

        result = q.list();
    }

    // Read form variables -- Classes Screen
    if (map.get("subjectAreaIds") != null && map.get("subjectAreaIds") instanceof String
            && map.get("courseNbr") != null) {

        StringBuffer query = new StringBuffer();
        query.append("select distinct co.courseNbr ");
        query.append("  from CourseOffering co ");
        query.append(" where co.subjectArea.session.uniqueId = :acadSessionId ");
        query.append("        and co.subjectArea.uniqueId = :subjectAreaId");
        query.append("        and co.courseNbr like :courseNbr ");
        query.append("        and co.instructionalOffering.notOffered = false ");
        //query.append("        and co.isControl = true ");
        query.append(" order by co.courseNbr ");

        CourseOfferingDAO cdao = new CourseOfferingDAO();
        Session hibSession = cdao.getSession();

        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(5000);
        q.setCacheable(true);
        q.setFlushMode(FlushMode.MANUAL);
        q.setInteger("acadSessionId", Integer.parseInt(acadSessionId));
        q.setInteger("subjectAreaId", Integer.parseInt(map.get("subjectAreaIds").toString()));
        q.setString("courseNbr", map.get("courseNbr").toString() + "%");

        result = q.list();
    }

    if (result == null)
        result = new ArrayList();

    return result;
}

From source file:org.unitime.timetable.action.ClassSearchAction.java

License:Open Source License

public static Set getClasses(ClassListFormInterface form, ClassAssignmentProxy classAssignmentProxy) {
    org.hibernate.Session hibSession = (new InstructionalOfferingDAO()).getSession();

    boolean doFilterManager = form.getFilterManager() != null && form.getFilterManager().length() > 0;
    Long filterManager = (doFilterManager ? Long.valueOf(form.getFilterManager()) : null);

    boolean fetchStructure = true;
    boolean fetchCredits = false;//form.getCredit().booleanValue();
    boolean fetchInstructors = false;//form.getInstructor().booleanValue();
    boolean fetchPreferences = false;//form.getPreferences().booleanValue() || form.getTimePattern().booleanValue();
    boolean fetchAssignments = false;//(form.getTimetable()!=null && form.getTimetable().booleanValue());

    String[] subjectIds = form.getSubjectAreaIds();
    if (subjectIds != null && subjectIds.length > 0) {
        StringBuffer query = new StringBuffer();
        query.append("select c, co from Class_ as c ");

        if (fetchStructure) {
            query.append("left join fetch c.childClasses as cc ");
            query.append("left join fetch c.schedulingSubpart as ss ");
            query.append("left join fetch ss.childSubparts as css ");
            query.append("left join fetch ss.instrOfferingConfig as ioc ");
            query.append("left join fetch ioc.instructionalOffering as io ");
            query.append("left join fetch io.courseOfferings as cox ");
        }/*from   w ww .  j  a  v  a  2 s .c  om*/

        if (fetchCredits)
            query.append("left join fetch ss.creditConfigs as ssc ");

        if (fetchPreferences || fetchInstructors) {
            query.append("left join fetch c.classInstructors as ci ");
            query.append("left join fetch ci.instructor as di ");
        }

        if (fetchAssignments) {
            query.append("left join fetch c.assignments as ca ");
            query.append("left join fetch ca.rooms as car ");
        }

        if (fetchPreferences) {
            query.append("left join fetch c.preferences as cp ");
            query.append("left join fetch ss.preferences as ssp ");
            query.append("left join fetch di.preferences as dip ");
        }

        query.append(
                "inner join c.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as co ");
        query.append(" where co.subjectArea.uniqueId in ( ");
        boolean first = true;
        for (int i = 0; i < subjectIds.length; i++) {
            if (!first) {
                query.append(", ");
            } else {
                first = false;
            }
            query.append(subjectIds[i]);
        }
        query.append(") ");
        if (form.getCourseNbr() != null && form.getCourseNbr().length() > 0) {
            String courseNbr = form.getCourseNbr();
            query.append(" and co.courseNbr ");
            if (courseNbr.indexOf('*') >= 0) {
                query.append(" like '");
                courseNbr = courseNbr.replace('*', '%');
            } else {
                query.append(" = '");
            }
            if (ApplicationProperty.CourseOfferingNumberUpperCase.isTrue())
                courseNbr = courseNbr.toUpperCase();
            query.append(courseNbr);
            query.append("'  ");
        }

        if (doFilterManager) {
            if (filterManager.longValue() < 0) { //all departmental
                query.append(" and (c.managingDept is null or c.managingDept in co.subjectArea.department)");
            } else {
                query.append(" and c.managingDept = " + filterManager);
            }
        }

        if (!form.getShowCrossListedClasses()) {
            query.append(" and co.isControl = true ");
        }
        Query q = hibSession.createQuery(query.toString());
        q.setFetchSize(1000);
        q.setCacheable(true);
        TreeSet ts = new TreeSet(new ClassCourseComparator(form.getSortBy(), classAssignmentProxy,
                form.getSortByKeepSubparts()));
        long sTime = new java.util.Date().getTime();

        boolean doFilterInstructor = form.getFilterInstructor() != null
                && form.getFilterInstructor().length() > 0;
        String filterInstructor = (doFilterInstructor ? form.getFilterInstructor().toUpperCase() : null);

        boolean doFilterAssignedRoom = form.getFilterAssignedRoom() != null
                && form.getFilterAssignedRoom().length() > 0;
        String filterAssignedRoom = (doFilterAssignedRoom ? form.getFilterAssignedRoom().toUpperCase() : null);

        boolean doFilterIType = form.getFilterIType() != null && form.getFilterIType().length() > 0;
        Integer filterIType = (doFilterIType ? Integer.valueOf(form.getFilterIType()) : null);

        boolean doFilterAssignedTime = ((form.getFilterDayCode() >= 0 && form.getFilterStartSlot() >= 0
                && form.getFilterLength() >= 0)
                || (form.getFilterDayCode() > 0 && form.getFilterStartSlot() < 0
                        && form.getFilterLength() <= 0));
        TimeLocation filterAssignedTime = (doFilterAssignedTime
                ? new TimeLocation((form.getFilterDayCode() == 0 ? 255 : form.getFilterDayCode()),
                        (form.getFilterStartSlot() < 0 ? 0 : form.getFilterStartSlot()),
                        (form.getFilterStartSlot() < 0 ? Constants.SLOTS_PER_DAY
                                : Math.max(5, Constants.SLOT_LENGTH_MIN + form.getFilterLength() - 1)
                                        / Constants.SLOT_LENGTH_MIN),
                        0, 0, null, null, null, 0)
                : null);
        // days, start time & length selected -> create appropriate time location
        // days, start time selected -> create appropriate time location with 1 slot length
        // start time & length selected -> create time location all days with given start time and length
        // only start time selected -> create time location all days with given start time and 1 slot length
        // only days selected -> create time location of given days all day long (all location assigned in the given days overlap)

        Debug.debug(" --- Filter classes ---");
        for (Iterator i = q.list().iterator(); i.hasNext();) {
            Object[] o = (Object[]) i.next();
            Class_ c = (Class_) o[0];
            if (doFilterInstructor) {
                boolean filterLine = true;
                for (Iterator j = c.getClassInstructors().iterator(); j.hasNext();) {
                    ClassInstructor ci = (ClassInstructor) j.next();
                    StringTokenizer stk = new StringTokenizer(filterInstructor, " ,");
                    boolean containsInstructor = true;
                    while (stk.hasMoreTokens()) {
                        String token = stk.nextToken();
                        boolean containsToken = false;
                        if (ci.getInstructor().getFirstName() != null
                                && ci.getInstructor().getFirstName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken && ci.getInstructor().getMiddleName() != null
                                && ci.getInstructor().getMiddleName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken && ci.getInstructor().getLastName() != null
                                && ci.getInstructor().getLastName().toUpperCase().indexOf(token) >= 0)
                            containsToken = true;
                        if (!containsToken) {
                            containsInstructor = false;
                            break;
                        }
                    }
                    if (containsInstructor) {
                        filterLine = false;
                        break;
                    }
                }
                if (filterLine) {
                    continue;
                }
            }

            if (doFilterIType) {
                ItypeDesc itype = c.getSchedulingSubpart().getItype();
                boolean match = false;
                while (!match && itype != null) {
                    match = itype.getItype().equals(filterIType);
                    itype = itype.getParent();
                }
                if (!match) {
                    continue;
                }
            }

            if (doFilterAssignedTime) {
                try {
                    Assignment a = classAssignmentProxy.getAssignment(c);
                    if (a == null) {
                        continue;
                    }
                    Placement p = a.getPlacement();
                    if (p == null) {
                        continue;
                    }
                    TimeLocation t = p.getTimeLocation();
                    if (t == null) {
                        continue;
                    }
                    boolean overlap = t.shareDays(filterAssignedTime) && t.shareHours(filterAssignedTime);
                    if (!overlap) {
                        continue;
                    }
                } catch (Exception e) {
                    continue;
                }
            }

            if (doFilterAssignedRoom) {
                try {
                    Assignment a = classAssignmentProxy.getAssignment(c);
                    if (a == null) {
                        continue;
                    }
                    Placement p = a.getPlacement();
                    if (p == null || p.getNrRooms() <= 0) {
                        continue;
                    }
                    boolean filterLine = true;
                    if (p.isMultiRoom()) {
                        for (RoomLocation r : p.getRoomLocations()) {
                            if (r.getName().toUpperCase().indexOf(filterAssignedRoom) >= 0) {
                                filterLine = false;
                                break;
                            }
                        }
                    } else {
                        if (p.getRoomLocation().getName().toUpperCase().indexOf(filterAssignedRoom) >= 0) {
                            filterLine = false;
                        }
                    }
                    if (filterLine) {
                        continue;
                    }
                } catch (Exception e) {
                    continue;
                }
            }

            ts.add(o);
        }

        long eTime = new java.util.Date().getTime();
        Debug.debug("fetch time = " + (eTime - sTime));
        Debug.debug("rows = " + ts.size());
        return (ts);

    } else {
        return (new TreeSet());
    }

}

From source file:org.unitime.timetable.action.DistributionPrefsAction.java

License:Open Source License

/**
 * @param index//from www.  j  av a  2 s .  co  m
 */
private void setLookupLists(HttpServletRequest request, DistributionPrefsForm frm, Vector subjectAreaList,
        ActionMessages errors) {

    int ct = frm.getSubjectArea().size();
    for (int index = 0; index < ct; index++) {

        String subjectAreaId = frm.getSubjectArea(index);
        String courseNbr = frm.getCourseNbr(index);
        String subpart = frm.getItype(index);
        String classNumber = frm.getClassNumber(index);

        Vector crsNumList = null;
        Vector subpartList = null;
        Vector classNumList = null;

        // Process subject area selection
        if (subjectAreaId != null) {
            if (subjectAreaId.equals(Preference.BLANK_PREF_VALUE)) {
                crsNumList = new Vector();
                subpartList = new Vector();
                classNumList = new Vector();
            } else {

                StringBuffer query = new StringBuffer();
                query.append("select co.uniqueId, co.courseNbr, co.title ");
                query.append("  from InstructionalOffering as io , CourseOffering co ");
                query.append(" where co.subjectArea.uniqueId = :subjectAreaId ");
                query.append("       and io.uniqueId = co.instructionalOffering.uniqueId ");
                query.append("       and io.notOffered = false ");
                query.append("       and co.isControl = true ");
                query.append(" order by co.courseNbr ");

                InstructionalOfferingDAO idao = new InstructionalOfferingDAO();
                org.hibernate.Session hibSession = idao.getSession();

                Query q = hibSession.createQuery(query.toString());
                q.setFetchSize(200);
                q.setCacheable(true);
                q.setLong("subjectAreaId", Long.parseLong(subjectAreaId));

                List result = q.list();
                crsNumList = new Vector();
                if (result.size() > 0) {
                    for (int i = 0; i < result.size(); i++) {
                        Object[] a = (Object[]) result.get(i);
                        ComboBoxLookup cbl = new ComboBoxLookup(
                                (a[1].toString() + " - " + (a[2] == null ? "" : a[2].toString())),
                                a[0].toString());
                        crsNumList.addElement(cbl);
                    }

                    // Only one record - select it to save time and one more click
                    if (result.size() == 1) {
                        ComboBoxLookup cbl = (ComboBoxLookup) crsNumList.elementAt(0);
                        frm.setCourseNbr(index, cbl.getValue());
                        courseNbr = frm.getCourseNbr(index);
                    }
                }

                // Process course number selection
                if (courseNbr.equals(Preference.BLANK_PREF_VALUE)) {
                    subpartList = new Vector();
                    classNumList = new Vector();
                } else {
                    query = new StringBuffer();
                    query.append(" select distinct s ");
                    query.append("   from CourseOffering co, ");
                    query.append("        InstructionalOffering io, ");
                    query.append("        InstrOfferingConfig ioc, ");
                    query.append("        SchedulingSubpart s ");
                    query.append("  where co.uniqueId=:courseNbr ");
                    query.append("    and co.instructionalOffering.uniqueId=io.uniqueId ");
                    query.append("    and ioc.instructionalOffering.uniqueId=io.uniqueId ");
                    query.append("    and s.instrOfferingConfig.uniqueId=ioc.uniqueId ");

                    q = hibSession.createQuery(query.toString());
                    q.setFetchSize(200);
                    q.setCacheable(true);
                    q.setLong("courseNbr", Long.parseLong(courseNbr));

                    result = new Vector(q.list());
                    if (result != null && result.size() > 0) {
                        Collections.sort(result,
                                new SchedulingSubpartComparator(
                                        subjectAreaId == null || subjectAreaId.length() == 0 ? null
                                                : new Long(subjectAreaId)));
                        subpartList = new Vector();
                        for (int i = 0; i < result.size(); i++) {
                            SchedulingSubpart a = (SchedulingSubpart) result.get(i);
                            String ssid = a.getUniqueId().toString();
                            String name = a.getItype().getAbbv();
                            String sufix = a.getSchedulingSubpartSuffix();
                            while (a.getParentSubpart() != null) {
                                name = "&nbsp;&nbsp;&nbsp;&nbsp;" + name;
                                a = a.getParentSubpart();
                            }
                            if (a.getInstrOfferingConfig().getInstructionalOffering().getInstrOfferingConfigs()
                                    .size() > 1)
                                name += " [" + a.getInstrOfferingConfig().getName() + "]";
                            ComboBoxLookup cbl = new ComboBoxLookup(
                                    name + (sufix == null || sufix.length() == 0 ? "" : " (" + sufix + ")"),
                                    ssid);
                            subpartList.addElement(cbl);
                        }

                        // Only one record - select it to save time and one more click
                        if (result.size() == 1) {
                            ComboBoxLookup cbl = (ComboBoxLookup) subpartList.elementAt(0);
                            frm.setItype(index, cbl.getValue());
                            subpart = frm.getItype(index);
                        }
                    }

                    if (subpartList == null || subpartList.size() == 0) {
                        subpartList = new Vector();
                        errors.add("classes",
                                new ActionMessage("errors.generic", "No subparts exist for the given course"));
                    }

                    // Process subpart selection
                    if (subpart.equals(Preference.BLANK_PREF_VALUE)) {
                        classNumList = new Vector();
                    } else {
                        query = new StringBuffer();
                        query.append(" select distinct c ");
                        query.append("   from SchedulingSubpart s, ");
                        query.append("        Class_ c ");
                        query.append("  where s.uniqueId=:itype ");
                        query.append("    and s.uniqueId=c.schedulingSubpart.uniqueId ");

                        q = hibSession.createQuery(query.toString());
                        q.setFetchSize(200);
                        q.setCacheable(true);
                        q.setLong("itype", Long.parseLong(subpart));

                        result = q.list();
                        if (result != null && result.size() > 0) {
                            Collections.sort(result, new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));

                            if (classNumber.equals(Preference.BLANK_PREF_VALUE))
                                frm.setClassNumber(index, DistributionPrefsForm.ALL_CLASSES_SELECT);

                            classNumList = new Vector();
                            for (int i = 0; i < result.size(); i++) {
                                Class_ clazz = (Class_) result.get(i);
                                ComboBoxLookup cbl = new ComboBoxLookup(clazz.getSectionNumberString(),
                                        clazz.getUniqueId().toString());
                                classNumList.addElement(cbl);
                            }
                        } else {
                            classNumList = new Vector();
                            errors.add("classes", new ActionMessage("errors.generic",
                                    "No classes exist for the given subpart"));
                        }
                    }
                }
            }
        }

        // Set drop down lists for a row
        request.setAttribute(DistributionPrefsForm.SUBJ_AREA_ATTR_LIST + index, subjectAreaList);
        request.setAttribute(DistributionPrefsForm.CRS_NUM_ATTR_LIST + index, crsNumList);
        request.setAttribute(DistributionPrefsForm.ITYPE_ATTR_LIST + index, subpartList);
        request.setAttribute(DistributionPrefsForm.CLASS_NUM_ATTR_LIST + index, classNumList);
    }

    saveErrors(request, errors);
}

From source file:org.unitime.timetable.action.RoomListAction.java

License:Open Source License

public void lookupRooms(RoomListForm form, String op) {
    String from = "Location l" + " left join l.roomDepts rd" + " left join fetch l.examTypes xt"
            + " left join fetch l.features f" + " left join fetch l.roomGroups g"
            + " left join fetch l.roomType t";
    String where = "l.session.uniqueId = :sessionId";

    List<Long> departmentIds = null;
    Long examTypeId = null;/*ww w.  j a  v a  2  s  . com*/

    if (form.getDeptCodeX().equalsIgnoreCase("All")) {
        if (sessionContext.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent)) {
        } else {
            departmentIds = new ArrayList<Long>();
            String depts = "";
            for (Department department : Department.getUserDepartments(sessionContext.getUser())) {
                depts += (depts.isEmpty() ? "" : ",") + ":dept" + (departmentIds.size());
                departmentIds.add(department.getUniqueId());
            }
            where += " and (rd.department.uniqueId in (" + depts + ") or l.eventDepartment.uniqueId in ("
                    + depts + "))";

        }
    } else if (form.getDeptCodeX().equals("Exam")) {
        TreeSet<ExamType> types = ExamType.findAllUsed(sessionContext.getUser().getCurrentAcademicSessionId());
        if (!types.isEmpty()) {
            examTypeId = types.first().getUniqueId();
            form.setDeptCodeX("Exam" + examTypeId);
            where += " and xt.uniqueId = :examTypeId";
        }
    } else if (form.getDeptCodeX().matches("Exam[0-9]*")) {
        // from = "Location l inner join l.examTypes xt";
        examTypeId = Long.valueOf(form.getDeptCodeX().substring(4));
        where += " and xt.uniqueId = :examTypeId";
    } else {
        Department department = Department.findByDeptCode(form.getDeptCodeX(),
                sessionContext.getUser().getCurrentAcademicSessionId());
        if (department != null) {
            if ("Export PDF".equals(op)) {
                sessionContext.checkPermission(department, Right.RoomsExportPdf);
            } else if ("Export CSV".equals(op)) {
                sessionContext.checkPermission(department, Right.RoomsExportCsv);
            } else {
                sessionContext.checkPermission(department, Right.Rooms);
            }
            where += " and (rd.department.uniqueId = :dept0 or l.eventDepartment.uniqueId = :dept0)";
            departmentIds = new ArrayList<Long>();
            departmentIds.add(department.getUniqueId());
        } else
            return;
    }

    Integer minSize = null, maxSize = null;
    if (form.getMinRoomSize() != null && !form.getMinRoomSize().isEmpty()) {
        try {
            minSize = Integer.valueOf(form.getMinRoomSize());
            where += " and l.capacity >= :minSize";
        } catch (NumberFormatException e) {
        }
    }
    if (form.getMaxRoomSize() != null && !form.getMaxRoomSize().isEmpty()) {
        try {
            maxSize = Integer.valueOf(form.getMaxRoomSize());
            where += " and l.capacity <= :maxSize";
        } catch (NumberFormatException e) {
        }
    }

    List<Long> roomTypes = null;
    if (form.getRoomTypes() != null && form.getRoomTypes().length > 0) {
        String types = "";
        roomTypes = new ArrayList<Long>();
        for (int i = 0; i < form.getRoomTypes().length; i++) {
            types += (types.isEmpty() ? "" : ",") + ":type" + i;
            roomTypes.add(form.getRoomTypes()[i]);
        }
        where += " and l.roomType.uniqueId in (" + types + ")";
    }

    List<Long> roomGroups = null;
    if (form.getRoomGroups() != null && form.getRoomGroups().length > 0) {
        String groups = "";
        roomGroups = new ArrayList<Long>();
        for (int i = 0; i < form.getRoomGroups().length; i++) {
            groups += (groups.isEmpty() ? "" : ",") + ":group" + i;
            roomGroups.add(form.getRoomGroups()[i]);
        }
        where += " and g.uniqueId in (" + groups + ")";
    }

    List<Long> roomFeatures = null;
    if (form.getRoomFeatures() != null && form.getRoomFeatures().length > 0) {
        roomFeatures = new ArrayList<Long>();
        for (int i = 0; i < form.getRoomFeatures().length; i++) {
            from += " inner join l.features f" + i;
            where += " and f" + i + ".uniqueId = :feature" + i;
            roomFeatures.add(form.getRoomFeatures()[i]);
        }
    }

    String filter = null;
    if (form.getFilter() != null && !form.getFilter().isEmpty()) {
        filter = form.getFilter();
        where += " and ((l.class = Room and (lower(l.buildingAbbv || ' ' || l.roomNumber) like :filter or lower(l.displayName) like :filter)) or (l.class = NonUniversityLocation and lower(l.name) like :filter))";
    }

    Query query = LocationDAO.getInstance().getSession()
            .createQuery("select distinct l from " + from + " where " + where);

    query.setLong("sessionId", sessionContext.getUser().getCurrentAcademicSessionId());
    if (departmentIds != null)
        for (int i = 0; i < departmentIds.size(); i++)
            query.setLong("dept" + i, departmentIds.get(i));
    if (examTypeId != null)
        query.setLong("examTypeId", examTypeId);
    if (minSize != null)
        query.setInteger("minSize", minSize);
    if (maxSize != null)
        query.setInteger("maxSize", maxSize);
    if (filter != null)
        query.setString("filter", "%" + filter.toLowerCase() + "%");
    if (roomTypes != null)
        for (int i = 0; i < roomTypes.size(); i++)
            query.setLong("type" + i, roomTypes.get(i));
    if (roomGroups != null)
        for (int i = 0; i < roomGroups.size(); i++)
            query.setLong("group" + i, roomGroups.get(i));
    if (roomFeatures != null)
        for (int i = 0; i < roomFeatures.size(); i++)
            query.setLong("feature" + i, roomFeatures.get(i));

    form.setRooms((List<Location>) query.setCacheable(true).list());
}

From source file:org.unitime.timetable.export.hql.SavedHqlExportToCSV.java

License:Open Source License

public static void execute(UserContext user, Printer out, SavedHQLInterface.Query query,
        List<SavedHQLInterface.IdValue> options, int fromRow, int maxRows)
        throws SavedHQLException, PageAccessException {
    try {/*from  w  w  w. ja  va 2s .c  o m*/
        String hql = query.getQuery();
        for (SavedHQL.Option o : SavedHQL.Option.values()) {
            if (hql.indexOf("%" + o.name() + "%") >= 0) {
                String value = null;
                for (SavedHQLInterface.IdValue v : options)
                    if (o.name().equals(v.getValue())) {
                        value = v.getText();
                        break;
                    }
                if (value == null || value.isEmpty()) {
                    Map<Long, String> vals = o.values(user);
                    if (vals == null || vals.isEmpty())
                        throw new SavedHQLException(MESSAGES.errorUnableToSetParameterNoValues(o.name()));
                    value = "";
                    for (Long id : vals.keySet()) {
                        if (!value.isEmpty())
                            value += ",";
                        value += id.toString();
                    }
                }
                hql = hql.replace("%" + o.name() + "%", "(" + value + ")");
            }
        }
        org.hibernate.Session hibSession = SavedHQLDAO.getInstance().getSession();
        org.hibernate.Query q = hibSession.createQuery(hql);
        if (maxRows > 0)
            q.setMaxResults(maxRows);
        if (fromRow > 0)
            q.setFirstResult(fromRow);
        q.setCacheable(true);
        int len = -1;
        for (Object o : q.list()) {
            if (len < 0) {
                len = length(o);
                String[] line = new String[len];
                header(line, o, q.getReturnAliases());
                if (line.length > 0 && line[0].startsWith("__"))
                    out.hideColumn(0);
                out.printHeader(line);
            }
            String[] line = new String[len];
            line(line, o, (SessionImplementor) hibSession);
            out.printLine(line);
            out.flush();
        }
    } catch (PageAccessException e) {
        throw e;
    } catch (SavedHQLException e) {
        throw e;
    } catch (Exception e) {
        sLog.error(e.getMessage(), e);
        throw new SavedHQLException(MESSAGES.failedExecution(
                e.getMessage() + (e.getCause() == null ? "" : " (" + e.getCause().getMessage() + ")")));
    }
}