List of usage examples for org.hibernate Criteria setMaxResults
public Criteria setMaxResults(int maxResults);
From source file:at.ac.tuwien.ifs.tita.dao.user.UserDAO.java
License:Apache License
/** {@inheritDoc} **/ @Override/*from www .j a v a 2s . c o m*/ @SuppressWarnings("unchecked") public List<TiTAUser> findUsersOrdered(int maxResult) throws PersistenceException { Criteria crit = getSession().createCriteria(TiTAUser.class); if (maxResult > 0) { crit.setMaxResults(maxResult); } crit.addOrder(Order.asc("userName")); crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return crit.list(); }
From source file:at.molindo.esi4j.module.hibernate.scrolling.DefaultQueryScrollingSession.java
License:Apache License
@Override public List<?> fetch(Session session, int batchSize) { Criteria criteria = session.createCriteria(_type); if (_lastId != null) { criteria.add(Restrictions.gt("id", _lastId)); }//from w ww . ja v a 2 s . c o m criteria.addOrder(Order.asc("id")); criteria.setMaxResults(batchSize); criteria.setCacheable(false); for (Map.Entry<String, FetchMode> e : _fetchModes.entrySet()) { criteria.setFetchMode(e.getKey(), e.getValue()); } List<?> list = criteria.list(); if (list.size() > 0) { ClassMetadata meta = session.getSessionFactory().getClassMetadata(_type); Object last = list.get(list.size() - 1); _lastId = meta.getIdentifier(last, (SessionImpl) session); } return list; }
From source file:au.com.optus.mcas.sdp.bizservice.ott.ordertracking.batchjob.dao.impl.AbstractDaoImpl.java
License:Open Source License
/** * {@inheritDoc}//from w w w . j av a 2s . c o m */ @SuppressWarnings("unchecked") public List<E> findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults) { Assert.notNull(criteria, "Detached criterial cannot be null in call to findByCriteria()"); if (getLogger().isDebugEnabled()) { getLogger().debug(String.format( "Finding instances of '%s' using detached criteria: %s [firstResult = %d, maxResults = %d]", getEntityClass(), criteria, firstResult, maxResults)); } final Criteria executableCriteria = criteria.getExecutableCriteria(getHibernateSession()); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (maxResults > 0) { executableCriteria.setMaxResults(maxResults); } return executableCriteria.list(); }
From source file:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.SessionDao.java
License:Open Source License
/** * Gets the users active session. If the user does not have an active * session <code>null</code> is returned. If the user has multiple * active sessions, only the lastest (ordered by request time) is * returned.// www . ja va 2 s .c o m * * @param user user to find active session of * @return active session or null */ @SuppressWarnings("unchecked") public Session findActiveSession(User user) { Criteria cri = this.session.createCriteria(Session.class); cri.add(Restrictions.eq("user", user)); cri.add(Restrictions.eq("active", Boolean.TRUE)); cri.addOrder(Order.desc("requestTime")); cri.setMaxResults(1); List<Session> sessions = cri.list(); if (sessions.size() == 0) { return null; } return sessions.get(0); }
From source file:au.edu.uts.eng.remotelabs.schedserver.dataaccess.dao.SlaveableRigsDao.java
License:Open Source License
/** * Returns info for an active session on the specified rig * /*from ww w. ja v a2s.c o m*/ * @param user user to find active session of * @return active session or null */ @SuppressWarnings("unchecked") public SlaveableRigs getInfo(Rig rig) { Criteria cri = this.session.createCriteria(SlaveableRigs.class); cri.add(Restrictions.eq("rig", rig)); cri.addOrder(Order.desc("id")); cri.setMaxResults(1); List<SlaveableRigs> sessions = cri.list(); if (sessions.size() == 0) { return null; } return sessions.get(0); }
From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.UsersPage.java
License:Open Source License
/** * Gets a list of users with a specific search term. The users may be * excluded from a specific class. /* ww w .j av a 2 s .co m*/ * * @param request * @return response * @throws Exception */ @SuppressWarnings("unchecked") public JSONArray list(HttpServletRequest request) throws JSONException { JSONArray arr = new JSONArray(); Criteria qu = this.db.createCriteria(User.class); String search = request.getParameter("search"); if (search != null) { /* Search filter. */ qu.add(Restrictions.disjunction().add(Restrictions.like("name", search, MatchMode.ANYWHERE)) .add(Restrictions.like("firstName", search, MatchMode.ANYWHERE)) .add(Restrictions.like("lastName", search, MatchMode.ANYWHERE))); } if (request.getParameter("max") != null) { /* Max results. */ qu.setMaxResults(Integer.parseInt(request.getParameter("max"))); } if (request.getParameter("in") != null) { /* Users in class. */ UserClass inClass = new UserClassDao(this.db).findByName(request.getParameter("in")); if (inClass == null) { this.logger.warn("Not going to add in class as a user list restriction because the class '" + request.getParameter("in") + "' was not found."); } else { qu.createCriteria("userAssociations").add(Restrictions.eq("userClass", inClass)); } } if (request.getParameter("notIn") != null) { /* Users not in class. */ UserClass notInClass = new UserClassDao(this.db).findByName(request.getParameter("notIn")); if (notInClass == null) { this.logger.warn("Not going to add not in class as a user list restriction because the class '" + request.getParameter("notIn") + "' was not found."); } else { DetachedCriteria subQu = DetachedCriteria.forClass(User.class) .setProjection(Property.forName("name")).createCriteria("userAssociations") .add(Restrictions.eq("userClass", notInClass)); List<String> names = subQu.getExecutableCriteria(this.db).list(); if (names.size() > 0) { qu.add(Restrictions.not(Restrictions.in("name", names))); } } } qu.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); qu.addOrder(Order.asc("lastName")); qu.addOrder(Order.asc("name")); for (User user : (List<User>) qu.list()) { JSONObject uo = new JSONObject(); uo.put("name", user.getNamespace() + "-_-" + user.getName()); if (user.getFirstName() == null || user.getLastName() == null) { uo.put("display", user.getName()); } else { uo.put("display", user.getLastName() + ", " + user.getFirstName()); } arr.put(uo); } return arr; }
From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from www .j a va2 s .com*/ public QueryInfoResponse queryInfo(final QueryInfo queryInfo) { /** Request parameters. **/ final QueryInfoType qIReq = queryInfo.getQueryInfo(); String debug = "Received " + this.getClass().getSimpleName() + "#queryInfo with params:"; debug += "Requestor: " + qIReq.getRequestor() + ", QuerySelect: " + qIReq.getQuerySelect(); if (qIReq.getQueryFilter() != null) { debug += ", QueryFilter: " + qIReq.getQueryFilter(); } debug += ", limit: " + qIReq.getLimit(); this.logger.debug(debug); final RequestorType uid = qIReq.getRequestor(); /** Response parameters. */ final QueryInfoResponse resp = new QueryInfoResponse(); final QueryInfoResponseType respType = new QueryInfoResponseType(); respType.setTypeForQuery(TypeForQuery.RIG); resp.setQueryInfoResponse(respType); final org.hibernate.Session ses = DataAccessActivator.getNewSession(); /* First Query Filter - this contains the main selection type to be selected */ final QueryFilterType query0 = qIReq.getQuerySelect(); try { Criteria cri; /* ---------------------------------------------------------------- * -- Load the requestor. -- * ---------------------------------------------------------------- */ final User user = this.getUserFromUserID(uid, ses); if (user == null) { this.logger.info("Unable to generate report because the user has not been found. Supplied " + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", " + "name=" + uid.getUserName() + '.'); return resp; } final String persona = user.getPersona(); /* Check for type of query to determine selection parameters */ if (query0.getTypeForQuery() == TypeForQuery.RIG) { /* ---------------------------------------------------------------- * -- Rig Information only available to ADMIN, to be mediated -- * -- by interface. No criteria on Requestor -- * ---------------------------------------------------------------- */ cri = ses.createCriteria(Rig.class); if (query0.getQueryLike() != null) { cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE)); } if (qIReq.getLimit() > 0) cri.setMaxResults(qIReq.getLimit()); cri.addOrder(Order.asc("name")); for (final Rig o : (List<Rig>) cri.list()) { respType.addSelectionResult(o.getName()); } } else if (query0.getTypeForQuery() == TypeForQuery.RIG_TYPE) { /* ---------------------------------------------------------------- * -- Rig Type Information only available to ADMIN, to be -- * -- mediated by interface. No criteria on Requestor -- * ---------------------------------------------------------------- */ cri = ses.createCriteria(RigType.class); if (query0.getQueryLike() != null) { cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE)); } if (qIReq.getLimit() > 0) cri.setMaxResults(qIReq.getLimit()); cri.addOrder(Order.asc("name")); for (final RigType o : (List<RigType>) cri.list()) { respType.addSelectionResult(o.getName()); } } else if (query0.getTypeForQuery() == TypeForQuery.USER_CLASS) { cri = ses.createCriteria(UserClass.class); if (query0.getQueryLike() != null) { cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE)); } if (qIReq.getLimit() > 0) cri.setMaxResults(qIReq.getLimit()); cri.addOrder(Order.asc("name")); /* ---------------------------------------------------------------- * Check that the requestor has permissions to request the report. * If persona = USER, no reports (USERs will not get here) * If persona = ADMIN, any report * If persona = ACADEMIC, only for classes they own if they can generate reports * ---------------------------------------------------------------- */ if (User.ACADEMIC.equals(persona)) { DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap") .add(Restrictions.eq("ap.canGenerateReports", true)) .setProjection(Property.forName("userClass")); cri.add(Subqueries.propertyIn("id", apList)); for (final UserClass o : (List<UserClass>) cri.list()) { respType.addSelectionResult(o.getName()); } } else if (User.ADMIN.equals(persona)) { for (final UserClass o : (List<UserClass>) cri.list()) { respType.addSelectionResult(o.getName()); } } } else if (query0.getTypeForQuery() == TypeForQuery.USER) { cri = ses.createCriteria(User.class, "u"); /* ---------------------------------------------------------------- * If persona = USER, no reports (USERs will not get here) * If persona = ADMIN, any report * If persona = ACADEMIC, only for users in classes they own if they can genrate reports * ---------------------------------------------------------------- */ if (query0.getQueryLike() != null) { cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE)); } if (qIReq.getLimit() > 0) cri.setMaxResults(qIReq.getLimit()); cri.addOrder(Order.asc("name")); if (User.ACADEMIC.equals(persona)) { DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap") .add(Restrictions.eq("ap.canGenerateReports", true)) .setProjection(Property.forName("userClass")); DetachedCriteria userList = DetachedCriteria.forClass(UserAssociation.class, "ua") .add(Subqueries.propertyIn("ua.userClass", apList)) .setProjection(Property.forName("user.id")); cri.add(Subqueries.propertyIn("id", userList)); for (final User o : (List<User>) cri.list()) { respType.addSelectionResult(o.getNamespace() + ':' + o.getName()); } } else if (User.ADMIN.equals(persona)) { for (final User o : (List<User>) cri.list()) { respType.addSelectionResult(o.getNamespace() + ':' + o.getName()); } } } else if (query0.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) { cri = ses.createCriteria(RequestCapabilities.class); if (query0.getQueryLike() != null) { cri.add(Restrictions.like("capabilities", query0.getQueryLike(), MatchMode.ANYWHERE)); } if (qIReq.getLimit() > 0) cri.setMaxResults(qIReq.getLimit()); cri.addOrder(Order.asc("capabilities")); final List<RequestCapabilities> list = cri.list(); for (final RequestCapabilities o : list) { respType.addSelectionResult(o.getCapabilities()); } } else { this.logger.error( "QueryInfo request failed because TypeForQuery does not have a valid value. Value is " + query0.getTypeForQuery().toString()); return resp; } final QueryFilterType filter[] = qIReq.getQueryFilter(); if (filter != null) { //DODGY Designed, not implemented } } finally { ses.close(); } respType.setTypeForQuery(query0.getTypeForQuery()); resp.setQueryInfoResponse(respType); return resp; }
From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java
License:Open Source License
@SuppressWarnings("unchecked") @Override//from ww w.j a v a 2 s.co m public QuerySessionAccessResponse querySessionAccess(final QuerySessionAccess querySessionAccess) { /* Request parameters. */ final QuerySessionAccessType request = querySessionAccess.getQuerySessionAccess(); final QueryFilterType filter = request.getQuerySelect(); String debug = "Received " + this.getClass().getSimpleName() + "#querySessionAccess with params: select operator=" + filter.getOperator() + ", type=" + filter.getTypeForQuery().toString() + ", like=" + filter.getQueryLike(); if (request.getStartTime() != null) debug += ", start=" + request.getStartTime().getTime(); if (request.getEndTime() != null) debug += ", end=" + request.getEndTime().getTime(); this.logger.debug(debug); /* Response parameters. */ final QuerySessionAccessResponse response = new QuerySessionAccessResponse(); final QuerySessionAccessResponseType respType = new QuerySessionAccessResponseType(); final PaginationType page = new PaginationType(); page.setNumberOfPages(1); page.setPageLength(0); page.setPageNumber(1); respType.setPagination(page); response.setQuerySessionAccessResponse(respType); final org.hibernate.Session db = DataAccessActivator.getNewSession(); try { RequestorType uid = request.getRequestor(); final User requestor = this.getUserFromUserID(uid, db); if (requestor == null) { this.logger.info("Unable to generate report because the user has not been found. Supplied " + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", " + "name=" + uid.getUserName() + '.'); return response; } /* We are only interested in sessions that are complete. */ Criteria query = db.createCriteria(Session.class).add(Restrictions.eq("active", Boolean.FALSE)) .add(Restrictions.isNotNull("removalTime")).addOrder(Order.asc("requestTime")); /* If the user has requested a time period, only add that to query. */ if (request.getStartTime() != null) query.add(Restrictions.ge("requestTime", request.getStartTime().getTime())); if (request.getEndTime() != null) query.add(Restrictions.le("requestTime", request.getEndTime().getTime())); if (request.getPagination() != null) { /* Add the requested pagination. */ final PaginationType pages = request.getPagination(); final int noPages = pages.getNumberOfPages(); final int pageNumber = pages.getPageNumber(); final int pageLength = pages.getPageLength(); if (noPages > 1) query.setMaxResults(pageLength); if (pageNumber > 1) query.setFirstResult((pageNumber - 1) * pageLength); } if (filter.getTypeForQuery() == TypeForQuery.RIG) { /* Only administrators can do rig queries. */ if (!User.ADMIN.equals(requestor.getPersona())) { this.logger.warn("Cannot provide session report for user '" + requestor.qName() + "' because their persona '" + requestor.getPersona() + "' does not allow rig reporting."); return response; } query.add(Restrictions.eq("assignedRigName", filter.getQueryLike())); } else if (filter.getTypeForQuery() == TypeForQuery.RIG_TYPE) { /* Only administrators can do rig type queries. */ if (!User.ADMIN.equals(requestor.getPersona())) { this.logger.warn("Cannot provide session report for user '" + requestor.qName() + "' because their persona '" + requestor.getPersona() + "' does not allow rig type reporting."); return response; } final RigType rigType = new RigTypeDao(db).findByName(filter.getQueryLike()); if (rigType == null) { this.logger.warn("Cannot provide session report because rig type '" + filter.getQueryLike() + "' not found."); return response; } query.createCriteria("rig").add(Restrictions.eq("rigType", rigType)); } else if (filter.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) { /* Only administrators can do request capabilities queries. */ if (!User.ADMIN.equals(requestor.getPersona())) { this.logger.warn("Cannot provide session report for user '" + requestor.qName() + "' because their persona '" + requestor.getPersona() + "' does not allow request capabilities reporting."); return response; } final RequestCapabilities reqCaps = new RequestCapabilitiesDao(db) .findCapabilites(filter.getQueryLike()); if (reqCaps == null) { this.logger.warn("Cannot provide session report because request capabilities '" + filter.getQueryLike() + "' not found."); return response; } List<Rig> capRigs = new ArrayList<Rig>(); for (MatchingCapabilities match : reqCaps.getMatchingCapabilitieses()) { capRigs.addAll(match.getRigCapabilities().getRigs()); } if (capRigs.size() == 0) { this.logger.warn( "Cannot provide session report because there are no rigs with request capabilities '" + reqCaps.getCapabilities() + "'."); return response; } query.add(Restrictions.in("rig", capRigs)); } else if (filter.getTypeForQuery() == TypeForQuery.USER_CLASS) { final UserClass userClass = new UserClassDao(db).findByName(filter.getQueryLike()); if (userClass == null) { this.logger.warn("Cannot provide session report because user class '" + filter.getQueryLike() + "' was not found."); return response; } if (User.ACADEMIC.equals(requestor.getPersona())) { /* An academic may only generate reports for the classes * they have have reporting permission in. */ boolean hasPerm = false; final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator(); while (it.hasNext()) { final AcademicPermission ap = it.next(); if (ap.getUserClass().getId().equals(userClass.getId()) && ap.isCanGenerateReports()) { hasPerm = true; break; } } if (!hasPerm) { this.logger.info("Unable to generate report for user class " + userClass.getName() + " because the user " + requestor.qName() + " does not own or have permission to report it."); return response; } this.logger.debug("Academic " + requestor.qName() + " has permission to generate report from user class " + userClass.getName() + '.'); } else if (!User.ADMIN.equals(requestor.getPersona())) { this.logger.warn("Cannot provide a user session report for user '" + requestor.qName() + "' because their persona '" + requestor.getPersona() + "' does not allow reporting."); return response; } query.createCriteria("resourcePermission").add(Restrictions.eq("userClass", userClass)); } else if (filter.getTypeForQuery() == TypeForQuery.USER) { final User user = new UserDao(db).findByQName(filter.getQueryLike()); if (user == null) { this.logger.warn("Cannot provide session report because user '" + filter.getQueryLike() + "' was not found."); return response; } if (User.ACADEMIC.equals(requestor.getPersona())) { /* The report can only contain sessions originating from the user * classes the academic has reporting permission in. */ List<ResourcePermission> perms = new ArrayList<ResourcePermission>(); final Iterator<AcademicPermission> it = requestor.getAcademicPermissions().iterator(); while (it.hasNext()) { final AcademicPermission ap = it.next(); if (!ap.isCanGenerateReports()) continue; perms.addAll(ap.getUserClass().getResourcePermissions()); } if (perms.size() == 0) { this.logger.info("Unable to generate report for user " + user.qName() + " because the user " + requestor.qName() + " does not own or have permission to report " + "on any of the users permissions."); return response; } query.add(Restrictions.in("resourcePermission", perms)); } else if (!User.ADMIN.equals(requestor.getPersona())) { this.logger.warn("Cannot provide a user session report for user '" + requestor.qName() + "' because their persona '" + requestor.getPersona() + "' does not allow reporting."); return response; } query.add(Restrictions.eq("user", user)); } else { this.logger.error("Cannot provide a session report because the query type '" + filter.getTypeForQuery().toString() + "' was not understood."); return response; } for (final Session s : (List<Session>) query.list()) { final AccessReportType report = new AccessReportType(); /* Set user who was in session. */ final RequestorType sUser = new RequestorType(); final UserNSNameSequence nsSequence = new UserNSNameSequence(); nsSequence.setUserName(s.getUserName()); nsSequence.setUserNamespace(s.getUserNamespace()); sUser.setRequestorNSName(nsSequence); sUser.setUserQName(s.getUserNamespace() + ':' + s.getUserName()); report.setUser(sUser); /* User class. */ if (s.getResourcePermission() != null) report.setUserClass(s.getResourcePermission().getUserClass().getName()); /* Rig details. */ report.setRigName(s.getAssignedRigName()); if (s.getRig() != null) report.setRigType(s.getRig().getRigType().getName()); /* Session start. */ Calendar cal = Calendar.getInstance(); cal.setTime(s.getRequestTime()); report.setQueueStartTime(cal); /* Session timings. */ if (s.getAssignmentTime() != null) { final int queueD = (int) ((s.getAssignmentTime().getTime() - s.getRequestTime().getTime()) / 1000); report.setQueueDuration(queueD); cal = Calendar.getInstance(); cal.setTime(s.getAssignmentTime()); report.setSessionStartTime(cal); final int sessionD = (int) ((s.getRemovalTime().getTime() - s.getAssignmentTime().getTime()) / 1000); report.setSessionDuration(sessionD); } else { final int queueD = (int) ((s.getRemovalTime().getTime() - s.getRequestTime().getTime()) / 1000); report.setQueueDuration(queueD); cal = Calendar.getInstance(); cal.setTime(s.getRemovalTime()); report.setSessionStartTime(cal); report.setSessionDuration(0); } /* Session end. */ cal = Calendar.getInstance(); cal.setTime(s.getRemovalTime()); report.setSessionEndTime(cal); report.setReasonForTermination(s.getRemovalReason()); respType.addAccessReportData(report); } } finally { db.close(); } return response; }
From source file:au.org.theark.admin.model.dao.AdminDao.java
License:Open Source License
public List<ArkModule> searchPageableArkModules(ArkModule arkModuleCriteria, int first, int count) { Criteria criteria = buildArkModuleCriteria(arkModuleCriteria); criteria.setFirstResult(first);//from www . j a v a 2 s. c om criteria.setMaxResults(count); List<ArkModule> list = criteria.list(); return list; }
From source file:au.org.theark.admin.model.dao.AdminDao.java
License:Open Source License
public List<ArkFunction> searchPageableArkFunctions(ArkFunction arkFunctionCriteria, int first, int count) { Criteria criteria = buildArkFunctionCriteria(arkFunctionCriteria); criteria.setFirstResult(first);//from w ww. j av a 2s . co m criteria.setMaxResults(count); List<ArkFunction> list = criteria.list(); return list; }