List of usage examples for org.hibernate Criteria createCriteria
public Criteria createCriteria(String associationPath) throws HibernateException;
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsService.java
License:Open Source License
@Override public FindFreeBookingsResponse findFreeBookings(FindFreeBookings findFreeBookings) { /* -------------------------------------------------------------------- * -- Read request parameters. -- * -------------------------------------------------------------------- */ FindBookingSlotType request = findFreeBookings.getFindBookingSlots(); String debug = "Received " + this.getClass().getSimpleName() + "#findFreeBookings with params: "; UserIDType uid = request.getUserID(); debug += " user ID=" + uid.getUserID() + ", user namespace=" + uid.getUserNamespace() + ", user name=" + uid.getUserName() + " user QName=" + uid.getUserQName(); PermissionIDType reqPermission = request.getPermissionID(); if (reqPermission != null) debug += " permission ID=" + reqPermission.getPermissionID(); ResourceIDType reqResource = request.getResourceID(); if (reqResource != null) debug += " resource type= " + reqResource.getType() + ", ID=" + request.getResourceID().getResourceID() + ", name=" + reqResource.getResourceName(); Calendar reqStart = request.getPeriod().getStartTime(); Calendar reqEnd = request.getPeriod().getEndTime(); this.dstHack(reqStart); this.dstHack(reqEnd); debug += " period start=" + reqStart.getTime() + ", period end=" + reqEnd.getTime(); this.logger.debug(debug); /* -------------------------------------------------------------------- * -- Generate valid, blank request parameters. -- * -------------------------------------------------------------------- */ FindFreeBookingsResponse response = new FindFreeBookingsResponse(); BookingSlotListType slots = new BookingSlotListType(); response.setFindFreeBookingsResponse(slots); PermissionIDType permission = new PermissionIDType(); slots.setPermissionID(permission);//from w w w .j a v a2 s . c o m ResourceIDType resource = new ResourceIDType(); resource.setType("TYPE"); slots.setResourceID(resource); Session ses = DataAccessActivator.getNewSession(); try { /* ---------------------------------------------------------------- * -- Load the user. -- * ---------------------------------------------------------------- */ User user = this.getUserFromUserID(uid, ses); if (user == null) { this.logger.info("Unable to provide free times because the user has not been found. Supplied " + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", " + "name=" + uid.getUserName() + '.'); return response; } /* ---------------------------------------------------------------- * -- Load the permission. -- * ---------------------------------------------------------------- */ ResourcePermission perm = null; if (reqPermission != null) { ResourcePermissionDao resPermissionDao = new ResourcePermissionDao(ses); perm = resPermissionDao.get(Long.valueOf(reqPermission.getPermissionID())); } else if (reqResource != null) { Criteria qu = ses.createCriteria(ResourcePermission.class); /* Add resource restrictions. */ qu.add(Restrictions.eq("type", reqResource.getType())); if (ResourcePermission.TYPE_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("rigType.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("rigType").add(Restrictions.eq("name", reqResource.getResourceName())); } } else if (ResourcePermission.RIG_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("rig.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("rig").add(Restrictions.eq("name", reqResource.getResourceName())); } } else if (ResourcePermission.CAPS_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("requestCapabilities.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("requestCapabilities") .add(Restrictions.eq("capabilities", reqResource.getResourceName())); } } else { this.logger.warn("Unable to provide free times because resource type " + reqResource.getType() + " is not understood."); return response; } List<UserClass> uc = new ArrayList<UserClass>(); for (UserAssociation assoc : user.getUserAssociations()) uc.add(assoc.getUserClass()); /* The permission user class must be active and bookable. */ qu.createCriteria("userClass").add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.eq("bookable", Boolean.TRUE)); qu.add(Restrictions.in("userClass", uc)); /* Add order in case we need to count in range, latest first. */ qu.addOrder(Order.desc("startTime")); @SuppressWarnings("unchecked") List<ResourcePermission> rpList = qu.list(); if (rpList.size() == 1) { /* One permission so good to go. */ perm = rpList.get(0); } else if (rpList.size() > 1) { Date rsd = reqStart.getTime(); Date red = reqEnd.getTime(); /* Multiple permissions so we take the permission in time range. */ for (ResourcePermission rp : rpList) { if (rp.getStartTime().before(rsd) && rp.getExpiryTime().after(rsd) || rp.getStartTime().before(red) && rp.getExpiryTime().after(red) || rp.getStartTime().after(rsd) && rp.getExpiryTime().before(red)) { perm = rp; break; } } /* Nothing in range so it doesn't matter which resource we give. */ if (perm == null) perm = rpList.get(0); } } /* If no permission is specified, either it doesn't exist or it wasn't * specified. Either way, we can't provide any information. */ if (perm == null) { this.logger .warn("Unable to provide free times because no permission or resource has been specified " + "or found to provide the free times of."); return response; } /* Make sure the permission a valid booking permission. */ if (!(perm.getUserClass().isActive() && perm.getUserClass().isBookable())) { this.logger.warn( "Unable to provide free times because the permission is not a valid booking permission."); return response; } /* There is a permission, but the user doesn't have it. */ if (!this.checkPermission(user, perm)) { this.logger.warn("Unable to provide free times to user " + user.getNamespace() + ':' + user.getName() + " because they do not have permission " + perm.getId() + "."); return response; } /* ---------------------------------------------------------------- * -- Populate the response with permission parameters. -- * ---------------------------------------------------------------- */ permission.setPermissionID(perm.getId().intValue()); resource.setType(perm.getType()); if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) { Rig rig = perm.getRig(); if (rig == null) { this.logger.warn("Unable to provide free times because the rig permission with ID=" + perm.getId() + " is not set with a rig."); return response; } resource.setResourceID(rig.getId().intValue()); resource.setResourceName(rig.getName()); } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) { RigType rigType = perm.getRigType(); if (rigType == null) { this.logger.warn("Unable to provide free times because the rig type permission with ID=" + perm.getId() + " is not set with a rig type."); return response; } resource.setResourceID(rigType.getId().intValue()); resource.setResourceName(rigType.getName()); } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) { RequestCapabilities caps = perm.getRequestCapabilities(); if (caps == null) { this.logger.warn( "Unable to provide free times because the request capabilities permission with ID=" + perm.getId() + " is not set with a request capabilities."); return response; } resource.setResourceID(caps.getId().intValue()); resource.setResourceName(caps.getCapabilities()); } else { this.logger.warn("Unable to provide free times because the permission with ID=" + perm.getId() + " has type '" + perm.getType() + "' which is not understood."); return response; } /* ---------------------------------------------------------------- * -- Check permission times to make sure the request is within -- * -- the permission start and expiry range. -- * ---------------------------------------------------------------- */ Calendar permStart = Calendar.getInstance(); permStart.setTime(perm.getStartTime()); /* The /actual/ permission start time may either be the permission * start time or the time horizon time. This is a second offset from * the current time (i.e. it atleast stops bookings being made for * the past. */ Calendar horizonTime = Calendar.getInstance(); horizonTime.add(Calendar.SECOND, perm.getUserClass().getTimeHorizon()); if (horizonTime.after(permStart)) { /* Which ever comes later. */ permStart = TimeUtil.coerceToNextSlotTime(horizonTime); } Calendar permEnd = Calendar.getInstance(); permEnd.setTime(perm.getExpiryTime()); if (reqEnd.before(permStart) || reqStart.after(permEnd) || permEnd.before(permStart)) { /* In this case the requested range is, after the end of the * permission region, before the start of the permission * region or the permission start is after the permission end * (the permission start is always sliding for horizion). */ BookingSlotType slot = new BookingSlotType(); slot.setSlot(request.getPeriod()); slot.setState(SlotState.NOPERMISSION); slots.addBookingSlot(slot); return response; } if (reqStart.before(permStart)) { /* Here the permission start time is after the requested start time * so the start partial date has no permission. */ TimePeriodType tp = new TimePeriodType(); tp.setStartTime(reqStart); tp.setEndTime(permStart); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.NOPERMISSION); slots.addBookingSlot(slot); /* The permission start time is now the search start time. */ reqStart = permStart; } Calendar searchEnd = reqEnd; if (reqEnd.after(permEnd)) { /* Here the permission end time is before the requested end time * so the end partial date has no permission. We will search the free * search end to the permission end but add the no permission period * last. */ searchEnd = permEnd; } /* ---------------------------------------------------------------- * -- Get the free times for the permission resource. -- * ---------------------------------------------------------------- */ List<TimePeriod> free = null; resource.setType(perm.getType()); if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) { free = this.engine.getFreeTimes(perm.getRig(), new TimePeriod(reqStart, searchEnd), perm.getSessionDuration() / 2, ses); } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) { free = this.engine.getFreeTimes(perm.getRigType(), new TimePeriod(reqStart, searchEnd), perm.getSessionDuration() / 2, ses); } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) { free = this.engine.getFreeTimes(perm.getRequestCapabilities(), new TimePeriod(reqStart, searchEnd), perm.getSessionDuration() / 2, ses); } /* ---------------------------------------------------------------- * -- Populate the resource with free and booked time -- * ---------------------------------------------------------------- */ Calendar c = reqStart; if (free.size() > 0) { for (TimePeriod period : free) { if (Math.abs(period.getStartTime().getTimeInMillis() - c.getTimeInMillis()) > 60000) { /* The difference with the last time and the next time is * more than a minute, then there should be a booked period. */ TimePeriodType tp = new TimePeriodType(); tp.setStartTime(c); tp.setEndTime(period.getStartTime()); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.BOOKED); slots.addBookingSlot(slot); } TimePeriodType tp = new TimePeriodType(); tp.setStartTime(period.getStartTime()); tp.setEndTime(period.getEndTime()); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.FREE); slots.addBookingSlot(slot); c = period.getEndTime(); } /* There is a booked spot at the end. */ if (Math.abs(searchEnd.getTimeInMillis() - c.getTimeInMillis()) > 60000) { /* The difference with the last time and the next time is * more than a minute, then there should be a booked period. */ TimePeriodType tp = new TimePeriodType(); tp.setStartTime(c); tp.setEndTime(searchEnd); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.BOOKED); slots.addBookingSlot(slot); } } else { /* There is no free times on the day. */ TimePeriodType tp = new TimePeriodType(); tp.setStartTime(reqStart); tp.setEndTime(reqEnd); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.BOOKED); slots.addBookingSlot(slot); } if (reqEnd.after(permEnd)) { /* Add a no permission at the end. */ TimePeriodType tp = new TimePeriodType(); tp.setStartTime(permEnd); tp.setEndTime(reqEnd); BookingSlotType slot = new BookingSlotType(); slot.setSlot(tp); slot.setState(SlotState.NOPERMISSION); slots.addBookingSlot(slot); } } finally { ses.close(); } return response; }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsService.java
License:Open Source License
@Override public GetBookingsResponse getBookings(GetBookings getBookings) { BookingsRequestType request = getBookings.getGetBookings(); String debug = "Received " + this.getClass().getSimpleName() + "#getBookings with params:"; if (request.getUserID() != null) debug += " user ID=" + request.getUserID().getUserID() + ", user name=" + request.getUserID().getUserName() + ", user namespace=" + request.getUserID().getUserNamespace() + " user QName=" + request.getUserID().getUserQName(); if (request.getPermissionID() != null) debug += " permission ID=" + request.getPermissionID().getPermissionID(); if (request.getResourceID() != null) debug += "resource type=" + request.getResourceID().getType() + ", resource ID=" + request.getResourceID().getResourceID() + ", resource name=" + request.getResourceID().getResourceName(); debug += " show cancelled=" + request.showCancelled() + " show finished=" + request.showFinished(); this.logger.debug(debug); GetBookingsResponse response = new GetBookingsResponse(); BookingListType bookings = new BookingListType(); response.setGetBookingsResponse(bookings); BookingsDao dao = new BookingsDao(); try {// ww w. j a va 2 s . c o m Session ses = dao.getSession(); Criteria cri = ses.createCriteria(Bookings.class); /* If user specificed, add that to query. */ User user = null; if (request.getUserID() != null && (user = this.getUserFromUserID(request.getUserID(), ses)) != null) { cri.add(Restrictions.eq("user", user)); } /* If permission was specified, add that to query. */ if (request.getPermissionID() != null) { cri.add(Restrictions.eq("resourcePermission.id", Long.valueOf(request.getPermissionID().getPermissionID()))); } /* If resource was specified, add that to query. */ ResourceIDType rid = request.getResourceID(); if (rid != null) { if (ResourcePermission.RIG_PERMISSION.equals(rid.getType())) { cri.add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION)); if (rid.getResourceID() > 0) cri.add(Restrictions.eq("rig.id", Long.valueOf(rid.getResourceID()))); if (rid.getResourceName() != null) { cri.createCriteria("rig").add(Restrictions.eq("name", rid.getResourceName())); } } else if (ResourcePermission.TYPE_PERMISSION.equals(rid.getType())) { cri.add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION)); if (rid.getResourceID() > 0) cri.add(Restrictions.eq("rigType.id", Long.valueOf(rid.getResourceID()))); if (rid.getResourceName() != null) { cri.createCriteria("rigType").add(Restrictions.eq("name", rid.getResourceName())); } } else if (ResourcePermission.CAPS_PERMISSION.equals(rid.getType())) { cri.add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION)); if (rid.getResourceID() > 0) { cri.add(Restrictions.eq("requestCapabilities.id", Long.valueOf(rid.getResourceID()))); } if (rid.getResourceName() != null) { cri.createCriteria("requestCapabilities") .add(Restrictions.eq("capabilities", rid.getResourceName())); } } else { this.logger.warn("Not added a resource restriction to existing booking search because the " + "resourece type '" + rid.getType() + "' is not one of '" + ResourcePermission.RIG_PERMISSION + "' '" + ResourcePermission.TYPE_PERMISSION + "' '" + ResourcePermission.CAPS_PERMISSION + "'."); } } /* Other constraints specified. */ if (!request.showCancelled() && !request.showFinished()) { cri.add(Restrictions.eq("active", Boolean.TRUE)); } else if (!request.showFinished()) { cri.add(Restrictions.or(Restrictions.isNotNull("cancelReason"), Restrictions.eq("active", Boolean.TRUE))); } else if (!request.showCancelled()) { cri.add(Restrictions.isNull("cancelReason")); } /* Order the results be booking start time. */ cri.addOrder(Order.asc("startTime")); @SuppressWarnings("unchecked") List<Bookings> list = cri.list(); for (Bookings booking : list) { bookings.addBookings(this.populateBookingType(new BookingType(), booking)); } } finally { dao.closeSession(); } return response; }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.intf.BookingsSOAPImpl.java
License:Open Source License
@Override public FindFreeBookingsResponse findFreeBookings(FindFreeBookings findFreeBookings) { /* -------------------------------------------------------------------- * -- Read request parameters. -- * -------------------------------------------------------------------- */ FindBookingSlotType request = findFreeBookings.getFindBookingSlots(); String debug = "Received " + this.getClass().getSimpleName() + "#findFreeBookings with params: "; UserIDType uid = request.getUserID(); debug += " user ID=" + uid.getUserID() + ", user namespace=" + uid.getUserNamespace() + ", user name=" + uid.getUserName() + " user QName=" + uid.getUserQName(); PermissionIDType reqPermission = request.getPermissionID(); if (reqPermission != null) debug += " permission ID=" + reqPermission.getPermissionID(); ResourceIDType reqResource = request.getResourceID(); if (reqResource != null) debug += " resource type= " + reqResource.getType() + ", ID=" + request.getResourceID().getResourceID() + ", name=" + reqResource.getResourceName(); Calendar reqStart = request.getPeriod().getStartTime(); Calendar reqEnd = request.getPeriod().getEndTime(); this.dstHack(reqStart); this.dstHack(reqEnd); debug += " period start=" + reqStart.getTime() + ", period end=" + reqEnd.getTime(); this.logger.debug(debug); /* -------------------------------------------------------------------- * -- Generate valid, blank request parameters. -- * -------------------------------------------------------------------- */ FindFreeBookingsResponse response = new FindFreeBookingsResponse(); BookingSlotListType slots = new BookingSlotListType(); response.setFindFreeBookingsResponse(slots); PermissionIDType permission = new PermissionIDType(); slots.setPermissionID(permission);//from w w w .j a v a 2 s .c o m ResourceIDType resource = new ResourceIDType(); resource.setType("TYPE"); slots.setResourceID(resource); Session db = DataAccessActivator.getNewSession(); try { /* ---------------------------------------------------------------- * -- Load the user. -- * ---------------------------------------------------------------- */ User user = this.getUserFromUserID(uid, db); if (user == null) { this.logger.info("Unable to provide free times because the user has not been found. Supplied " + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", " + "name=" + uid.getUserName() + '.'); return response; } /* ---------------------------------------------------------------- * -- Load the permission. -- * ---------------------------------------------------------------- */ ResourcePermission perm = null; if (reqPermission != null) { ResourcePermissionDao resPermissionDao = new ResourcePermissionDao(db); perm = resPermissionDao.get(Long.valueOf(reqPermission.getPermissionID())); } else if (reqResource != null) { Criteria qu = db.createCriteria(ResourcePermission.class); /* Add resource restrictions. */ qu.add(Restrictions.eq("type", reqResource.getType())); if (ResourcePermission.TYPE_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("rigType.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("rigType").add(Restrictions.eq("name", reqResource.getResourceName())); } } else if (ResourcePermission.RIG_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("rig.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("rig").add(Restrictions.eq("name", reqResource.getResourceName())); } } else if (ResourcePermission.CAPS_PERMISSION.equals(reqResource.getType())) { if (reqResource.getResourceID() > 0) { qu.add(Restrictions.eq("requestCapabilities.id", Long.valueOf(reqResource.getResourceID()))); } if (reqResource.getResourceName() != null) { qu.createCriteria("requestCapabilities") .add(Restrictions.eq("capabilities", reqResource.getResourceName())); } } else { this.logger.warn("Unable to provide free times because resource type " + reqResource.getType() + " is not understood."); return response; } List<UserClass> uc = new ArrayList<UserClass>(); for (UserAssociation assoc : user.getUserAssociations()) uc.add(assoc.getUserClass()); /* The permission user class must be active and bookable. */ qu.createCriteria("userClass").add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.eq("bookable", Boolean.TRUE)); qu.add(Restrictions.in("userClass", uc)); /* Add order in case we need to count in range, latest first. */ qu.addOrder(Order.desc("startTime")); @SuppressWarnings("unchecked") List<ResourcePermission> rpList = qu.list(); if (rpList.size() == 1) { /* One permission so good to go. */ perm = rpList.get(0); } else if (rpList.size() > 1) { Date rsd = reqStart.getTime(); Date red = reqEnd.getTime(); /* Multiple permissions so we take the permission in time range. */ for (ResourcePermission rp : rpList) { if (rp.getStartTime().before(rsd) && rp.getExpiryTime().after(rsd) || rp.getStartTime().before(red) && rp.getExpiryTime().after(red) || rp.getStartTime().after(rsd) && rp.getExpiryTime().before(red)) { perm = rp; break; } } /* Nothing in range so it doesn't matter which resource we give. */ if (perm == null) perm = rpList.get(0); } } /* If no permission is specified, either it doesn't exist or it wasn't * specified. Either way, we can't provide any information. */ if (perm == null) { this.logger .warn("Unable to provide free times because no permission or resource has been specified " + "or found to provide the free times of."); return response; } /* There is a permission, but the user doesn't have it. */ if (!this.checkPermission(user, perm)) { this.logger.warn("Unable to provide free times to user " + user.getNamespace() + ':' + user.getName() + " because they do not have permission " + perm.getId() + "."); return response; } /* ---------------------------------------------------------------- * -- Populate the response with permission parameters. -- * ---------------------------------------------------------------- */ permission.setPermissionID(perm.getId().intValue()); resource.setType(perm.getType()); if (ResourcePermission.RIG_PERMISSION.equals(perm.getType())) { Rig rig = perm.getRig(); if (rig == null) { this.logger.warn("Unable to provide free times because the rig permission with ID=" + perm.getId() + " is not set with a rig."); return response; } resource.setResourceID(rig.getId().intValue()); resource.setResourceName(rig.getName()); } else if (ResourcePermission.TYPE_PERMISSION.equals(perm.getType())) { RigType rigType = perm.getRigType(); if (rigType == null) { this.logger.warn("Unable to provide free times because the rig type permission with ID=" + perm.getId() + " is not set with a rig type."); return response; } resource.setResourceID(rigType.getId().intValue()); resource.setResourceName(rigType.getName()); } else if (ResourcePermission.CAPS_PERMISSION.equals(perm.getType())) { RequestCapabilities caps = perm.getRequestCapabilities(); if (caps == null) { this.logger.warn( "Unable to provide free times because the request capabilities permission with ID=" + perm.getId() + " is not set with a request capabilities."); return response; } resource.setResourceID(caps.getId().intValue()); resource.setResourceName(caps.getCapabilities()); } else if (ResourcePermission.CONSUMER_PERMISSION.equalsIgnoreCase(perm.getType())) { resource.setResourceID(-1); // Faking ID. resource.setResourceName("Fake"); } else { this.logger.warn("Unable to provide free times because the permission with ID=" + perm.getId() + " has type '" + perm.getType() + "' which is not understood."); return response; } BookingsPeriod period = new BookingsServiceImpl().getFreeBookings(reqStart, reqEnd, perm, db); for (BookingSlot slot : period.getSlots()) { TimePeriodType tp = new TimePeriodType(); tp.setStartTime(slot.getStart()); tp.setEndTime(slot.getEnd()); BookingSlotType bst = new BookingSlotType(); bst.setSlot(tp); bst.setState(SlotState.Factory.fromValue(slot.getState())); slots.addBookingSlot(bst); } } finally { db.close(); } return response; }
From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.KeysPage.java
License:Open Source License
/** * Returns the list of keys for a user class. If the parameter 'historical' * is part of the request parameters and has a value of 'true', non-usable * keys are returned otherwise usable keys are returned. Usable keys are * those that are 'active', have remaining uses and have not elapsed * their expiry time. //from w ww . ja v a 2s .c o m * * @param request request * @return list of permission keys * @throws JSONException */ @SuppressWarnings("unchecked") public JSONArray getList(HttpServletRequest request) throws JSONException { JSONArray arr = new JSONArray(); String className = request.getParameter("name"); if (className == null) { this.logger.warn("Unable to provide access key list because the user class name was not provided."); return arr; } Criteria qu = this.db.createCriteria(UserClassKey.class).add(Restrictions.eq("userTargeted", Boolean.FALSE)) .addOrder(Order.asc("id")); if ("true".equals(request.getAttribute("historical"))) { qu.add(Restrictions.disjunction().add(Restrictions.eq("active", Boolean.FALSE)) .add(Restrictions.eq("remaining", 0))) .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.lt("expiry", new Date()))); } else { qu.add(Restrictions.eq("active", Boolean.TRUE)).add(Restrictions.gt("remaining", 0)) .add(Restrictions.or(Restrictions.isNull("expiry"), Restrictions.gt("expiry", new Date()))); } qu = qu.createCriteria("userClass").add(Restrictions.eq("name", className)); for (UserClassKey key : (List<UserClassKey>) qu.list()) { JSONObject keyObj = new JSONObject(); keyObj.put("key", key.getRedeemKey()); keyObj.put("active", key.isActive()); keyObj.put("remaining", key.getRemaining()); arr.put(keyObj); } return arr; }
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. //from w w w .j a v a2 s . c o 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 w ww. ja va 2 s.c om 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.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java
License:Open Source License
@SuppressWarnings("unchecked") @Override// w w w . j a v a 2s.c o m public QuerySessionReportResponse querySessionReport(final QuerySessionReport querySessionReport) { /** Request parameters. **/ final QuerySessionReportType qSRReq = querySessionReport.getQuerySessionReport(); String debug = "Received " + this.getClass().getSimpleName() + "#querySessionReport with params:"; debug += "Requestor: " + qSRReq.getRequestor() + ", QuerySelect: " + qSRReq.getQuerySelect().toString(); if (qSRReq.getQueryConstraints() != null) { debug += ", QueryConstraints: " + qSRReq.getQueryConstraints().toString(); //DODGY only first displayed } debug += ", start time: " + qSRReq.getStartTime() + ", end time: " + qSRReq.getEndTime() + ", pagination: " + qSRReq.getPagination(); this.logger.debug(debug); final RequestorType uid = qSRReq.getRequestor(); /** Response parameters. */ final QuerySessionReportResponse resp = new QuerySessionReportResponse(); final QuerySessionReportResponseType respType = new QuerySessionReportResponseType(); final PaginationType page = new PaginationType(); page.setNumberOfPages(1); page.setPageLength(0); page.setPageNumber(1); respType.setPagination(page); respType.setSessionCount(0); respType.setTotalQueueDuration(0); respType.setTotalSessionDuration(0); resp.setQuerySessionReportResponse(respType); final org.hibernate.Session ses = DataAccessActivator.getNewSession(); /* Set up query from request parameters*/ try { /* ---------------------------------------------------------------- * -- 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(); final Criteria cri = ses.createCriteria(Session.class); // Order by request time cri.addOrder(Order.asc("requestTime")); /* Add restriction - removal time cannot be null - these are in session records */ cri.add(Restrictions.isNotNull("removalTime")); /* First Query Filter - this contains grouping for the query */ final QueryFilterType query0 = qSRReq.getQuerySelect(); /* ---------------------------------------------------------------- * -- Get the Query type and process accordingly -- * -- 1. Rig -- * -- 2. Rig Type -- * -- 3. User Class -- * -- 4. User -- * -- 5. Capabilities (not yet implemented) -- * ---------------------------------------------------------------- */ if (query0.getTypeForQuery() == TypeForQuery.RIG) { /* ---------------------------------------------------------------- * -- 1. Rig Information only available to ADMIN, to be mediated -- * -- by interface. No criteria on Requestor -- * ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- * -- 1a. Get Sessions that match the rig -- * ---------------------------------------------------------------- */ cri.add(Restrictions.eq("assignedRigName", query0.getQueryLike())); // Select time period if (qSRReq.getStartTime() != null) { cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime())); } if (qSRReq.getEndTime() != null) { cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime())); } Long idCount = new Long(-1); final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>( new UserComparator()); /* Contains list of users without user_id in session. Indexed with namespace:name */ final Map<String, SessionStatistics> userMap = new HashMap<String, SessionStatistics>(); final List<Session> list = cri.list(); for (final Session o : list) { /* ---------------------------------------------------------------- * -- 1b. Iterate through sessions and create user records -- * ---------------------------------------------------------------- */ /* Create check for user_id not being null - deleted user */ if (o.getUser() != null) { final User u = o.getUser(); if (recordMap.containsKey(u)) { recordMap.get(u).addRecord(o); } else { final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); } } else { final String nameIndex = o.getUserNamespace() + QNAME_DELIM + o.getUserName(); /* Does 'namespace:name' indexed list contain user */ if (userMap.containsKey(nameIndex)) { userMap.get(nameIndex).addRecord(o); } else { final User u = new User(); u.setName(o.getUserName()); u.setNamespace(o.getUserNamespace()); u.setId(idCount); idCount--; final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); userMap.put(nameIndex, userRec); } } } /* ---------------------------------------------------------------- * -- 1c. Get pagination requirements so correct records are -- * -- returned. -- * ---------------------------------------------------------------- */ int pageNumber = 1; int pageLength = recordMap.size(); int recordCount = 0; int totalSessionCount = 0; int totalSessionDuration = 0; int totalQueueDuration = 0; if (qSRReq.getPagination() != null) { final PaginationType pages = qSRReq.getPagination(); pageNumber = pages.getPageNumber(); pageLength = pages.getPageLength(); respType.setPagination(page); } /* ---------------------------------------------------------------- * -- 1d. Iterate through user records and calculate report data -- * ---------------------------------------------------------------- */ for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) { recordCount++; totalSessionCount += e.getValue().getSessionCount(); totalQueueDuration += e.getValue().getTotalQueueDuration(); totalSessionDuration += e.getValue().getTotalSessionDuration(); if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) { final SessionReportType reportType = new SessionReportType(); //Get user from session object final RequestorType user0 = new RequestorType(); final UserNSNameSequence nsSequence = new UserNSNameSequence(); nsSequence.setUserName(e.getKey().getName()); nsSequence.setUserNamespace(e.getKey().getNamespace()); user0.setRequestorNSName(nsSequence); reportType.setUser(user0); reportType.setRigName(query0.getQueryLike()); reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration()); reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration()); reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration()); reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration()); reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration()); reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration()); reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration()); reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration()); reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration()); reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration()); reportType.setSessionCount(e.getValue().getSessionCount()); respType.addSessionReport(reportType); } } respType.setSessionCount(totalSessionCount); respType.setTotalQueueDuration(totalQueueDuration); respType.setTotalSessionDuration(totalSessionDuration); resp.setQuerySessionReportResponse(respType); } else if (query0.getTypeForQuery() == TypeForQuery.RIG_TYPE) { /* ---------------------------------------------------------------- * -- 2. Rig Type Information only available to ADMIN, to be -- * -- mediated by interface. No criteria on Requestor -- * ---------------------------------------------------------------- */ final RigTypeDao rTypeDAO = new RigTypeDao(ses); final RigType rType = rTypeDAO.findByName(query0.getQueryLike()); if (rType == null) { this.logger.warn("No valid rig type found - " + query0.getTypeForQuery().toString()); return resp; } /* ---------------------------------------------------------------- * -- 2a. Get Sessions that match the rig type -- * ---------------------------------------------------------------- */ // Select Sessions where rig value is of the correct Rig Type cri.createCriteria("rig").add(Restrictions.eq("rigType", rType)); // Select time period if (qSRReq.getStartTime() != null) { cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime())); } if (qSRReq.getEndTime() != null) { cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime())); } Long idCount = new Long(-1); final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>( new UserComparator()); /* Contains list of users without user_id in session. Indexed with namespace:name */ final Map<String, SessionStatistics> userMap = new HashMap<String, SessionStatistics>(); final List<Session> list = cri.list(); for (final Session o : list) { /* ---------------------------------------------------------------- * -- 2b. Iterate through sessions and create user records -- * ---------------------------------------------------------------- */ /* Create check for user_id not being null - deleted user */ if (o.getUser() != null) { final User u = o.getUser(); if (recordMap.containsKey(u)) { recordMap.get(u).addRecord(o); } else { final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); } } else { final String nameIndex = o.getUserNamespace() + QNAME_DELIM + o.getUserName(); /* Does 'namespace:name' indexed list contain user */ if (userMap.containsKey(nameIndex)) { userMap.get(nameIndex).addRecord(o); } else { final User u = new User(); u.setName(o.getUserName()); u.setNamespace(o.getUserNamespace()); u.setId(idCount); idCount--; final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); userMap.put(nameIndex, userRec); } } } /* ---------------------------------------------------------------- * -- 2c. Get pagination requirements so correct records are -- * -- returned. -- * ---------------------------------------------------------------- */ int pageNumber = 1; int pageLength = recordMap.size(); int recordCount = 0; int totalSessionCount = 0; int totalSessionDuration = 0; int totalQueueDuration = 0; if (qSRReq.getPagination() != null) { final PaginationType pages = qSRReq.getPagination(); pageNumber = pages.getPageNumber(); pageLength = pages.getPageLength(); } /* ---------------------------------------------------------------- * -- 2d. Iterate through user records and calculate report data -- * ---------------------------------------------------------------- */ for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) { recordCount++; totalSessionCount += e.getValue().getSessionCount(); totalQueueDuration += e.getValue().getTotalQueueDuration(); totalSessionDuration += e.getValue().getTotalSessionDuration(); if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) { final SessionReportType reportType = new SessionReportType(); //Get user from session object final RequestorType user0 = new RequestorType(); final UserNSNameSequence nsSequence = new UserNSNameSequence(); nsSequence.setUserName(e.getKey().getName()); nsSequence.setUserNamespace(e.getKey().getNamespace()); user0.setRequestorNSName(nsSequence); reportType.setUser(user0); reportType.setRigType(rType.getName()); reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration()); reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration()); reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration()); reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration()); reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration()); reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration()); reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration()); reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration()); reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration()); reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration()); reportType.setSessionCount(e.getValue().getSessionCount()); respType.addSessionReport(reportType); } } respType.setSessionCount(totalSessionCount); respType.setTotalQueueDuration(totalQueueDuration); respType.setTotalSessionDuration(totalSessionDuration); resp.setQuerySessionReportResponse(respType); } else if (query0.getTypeForQuery() == TypeForQuery.USER_CLASS) { /* ---------------------------------------------------------------- * -- 3. User Class Information only available to ADMIN and -- * -- ACADEMIC users with permissions to generate reports -- * -- for this class. -- * ---------------------------------------------------------------- */ final UserClassDao uClassDAO = new UserClassDao(ses); final UserClass uClass = uClassDAO.findByName(query0.getQueryLike()); if (uClass == null) { this.logger.warn("No valid user class found - " + query0.getTypeForQuery().toString()); return resp; } /* ---------------------------------------------------------------- * 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 genrate reports * ---------------------------------------------------------------- */ if (User.ACADEMIC.equals(persona)) { /* An academic may generate reports for their own classes only. */ boolean hasPerm = false; final Iterator<AcademicPermission> apIt = user.getAcademicPermissions().iterator(); while (apIt.hasNext()) { final AcademicPermission ap = apIt.next(); if (ap.getUserClass().getId().equals(uClass.getId()) && ap.isCanGenerateReports()) { hasPerm = true; break; } } if (!hasPerm) { this.logger.info("Unable to generate report for user class " + uClass.getName() + " because the user " + user.getNamespace() + ':' + user.getName() + " does not own or have academic permission to it."); return resp; } this.logger.debug("Academic " + user.getNamespace() + ':' + user.getName() + " has permission to " + "generate report from user class" + uClass.getName() + '.'); } /* ---------------------------------------------------------------- * -- 3a. Get Sessions that match the user class -- * ---------------------------------------------------------------- */ //Select sessions where the resource permission associated is for this user class cri.createCriteria("resourcePermission").add(Restrictions.eq("userClass", uClass)); // Select time period if (qSRReq.getStartTime() != null) { cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime())); } if (qSRReq.getEndTime() != null) { cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime())); } //Query Filter to be used for multiple selections in later versions of reporting. //QueryFilterType queryFilters[] = qSAReq.getQueryConstraints(); final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>( new UserComparator()); final List<Session> list = cri.list(); for (final Session o : list) { /* ---------------------------------------------------------------- * -- 3b. Iterate through sessions and create user records -- * ---------------------------------------------------------------- */ /* Create check for user_id not being null - deleted user */ if (o.getUser() != null) { final User u = o.getUser(); if (recordMap.containsKey(u)) { recordMap.get(u).addRecord(o); } else { final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); } } } /* ---------------------------------------------------------------- * -- 3c. Get pagination requirements so correct records are -- * -- returned. -- * ---------------------------------------------------------------- */ int pageNumber = 1; int pageLength = recordMap.size(); int recordCount = 0; int totalSessionCount = 0; int totalSessionDuration = 0; int totalQueueDuration = 0; if (qSRReq.getPagination() != null) { final PaginationType pages = qSRReq.getPagination(); pageNumber = pages.getPageNumber(); pageLength = pages.getPageLength(); } /* ---------------------------------------------------------------- * -- 3d. Iterate through user records and calculate report data -- * ---------------------------------------------------------------- */ for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) { recordCount++; totalSessionCount += e.getValue().getSessionCount(); totalQueueDuration += e.getValue().getTotalQueueDuration(); totalSessionDuration += e.getValue().getTotalSessionDuration(); if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) { final SessionReportType reportType = new SessionReportType(); //Get user from session object final RequestorType user0 = new RequestorType(); final UserNSNameSequence nsSequence = new UserNSNameSequence(); nsSequence.setUserName(e.getKey().getName()); nsSequence.setUserNamespace(e.getKey().getNamespace()); user0.setRequestorNSName(nsSequence); reportType.setUser(user0); reportType.setUserClass(uClass.getName()); reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration()); reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration()); reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration()); reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration()); reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration()); reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration()); reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration()); reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration()); reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration()); reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration()); reportType.setSessionCount(e.getValue().getSessionCount()); respType.addSessionReport(reportType); } } respType.setSessionCount(totalSessionCount); respType.setTotalQueueDuration(totalQueueDuration); respType.setTotalSessionDuration(totalSessionDuration); resp.setQuerySessionReportResponse(respType); } else if (query0.getTypeForQuery() == TypeForQuery.USER) { /* ---------------------------------------------------------------- * -- 4. User Information only available to ADMIN and -- * -- ACADEMIC users with permissions to generate reports -- * -- for this classes to which this user belongs. -- * -- NOTE: User nam expected as: namespace:username -- * ---------------------------------------------------------------- */ final UserDao userDAO = new UserDao(ses); final String idParts[] = query0.getQueryLike().split(Reports.QNAME_DELIM, 2); final String ns = idParts[0]; final String name = (idParts.length > 1) ? idParts[1] : idParts[0]; final User user0 = userDAO.findByName(ns, name); if (user0 == null) { this.logger.warn("No valid user found - " + query0.getTypeForQuery().toString()); return resp; } /* ---------------------------------------------------------------- * 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 users belonging to * classes they can generate reports for * ---------------------------------------------------------------- */ if (User.ACADEMIC.equals(persona)) { /* An academic may generate reports for their own classes only. */ boolean hasPerm = false; final Iterator<AcademicPermission> apIt = user.getAcademicPermissions().iterator(); while (apIt.hasNext()) { final AcademicPermission ap = apIt.next(); final Iterator<UserAssociation> uaIt = user0.getUserAssociations().iterator(); while (uaIt.hasNext()) { final UserAssociation ua = uaIt.next(); if (ap.getUserClass().getId().equals(ua.getUserClass().getId()) && ap.isCanGenerateReports()) { hasPerm = true; break; } } if (hasPerm) { break; } } if (!hasPerm) { this.logger.info("Unable to generate report for user class " + user0.getName() + " because the user " + user.getNamespace() + ':' + user.getName() + " does not own or have academic permission to it."); return resp; } this.logger.debug("Academic " + user.getNamespace() + ':' + user.getName() + " has permission to " + "generate report from user class" + user0.getName() + '.'); } /* ---------------------------------------------------------------- * -- 4a. Get Sessions that match the user -- * ---------------------------------------------------------------- */ //Select sessions where the resource permission associated is for this user class cri.add(Restrictions.eq("user", user0)); // Select time period if (qSRReq.getStartTime() != null) { cri.add(Restrictions.ge("requestTime", qSRReq.getStartTime().getTime())); } if (qSRReq.getEndTime() != null) { cri.add(Restrictions.le("requestTime", qSRReq.getEndTime().getTime())); } //Query Filter to be used for multiple selections in later versions of reporting. //QueryFilterType queryFilters[] = qSAReq.getQueryConstraints(); final SortedMap<User, SessionStatistics> recordMap = new TreeMap<User, SessionStatistics>( new UserComparator()); final List<Session> list = cri.list(); for (final Session o : list) { /* ---------------------------------------------------------------- * -- 4b. Iterate through sessions and create user records -- * ---------------------------------------------------------------- */ final User u = o.getUser(); if (recordMap.containsKey(u)) { recordMap.get(u).addRecord(o); } else { final SessionStatistics userRec = new SessionStatistics(); userRec.addRecord(o); recordMap.put(u, userRec); } } /* ---------------------------------------------------------------- * -- 4c. Get pagination requirements so correct records are -- * -- returned. -- * ---------------------------------------------------------------- */ int pageNumber = 1; int pageLength = recordMap.size(); int recordCount = 0; int totalSessionCount = 0; int totalSessionDuration = 0; int totalQueueDuration = 0; if (qSRReq.getPagination() != null) { final PaginationType pages = qSRReq.getPagination(); pageNumber = pages.getPageNumber(); pageLength = pages.getPageLength(); } /* ---------------------------------------------------------------- * -- 4d. Iterate through user records and calculate report data -- * ---------------------------------------------------------------- */ for (final Entry<User, SessionStatistics> e : recordMap.entrySet()) { recordCount++; totalSessionCount += e.getValue().getSessionCount(); totalQueueDuration += e.getValue().getTotalQueueDuration(); totalSessionDuration += e.getValue().getTotalSessionDuration(); if ((recordCount > (pageNumber - 1) * pageLength) && (recordCount <= pageNumber * pageLength)) { final SessionReportType reportType = new SessionReportType(); //Get user from session object final RequestorType user1 = new RequestorType(); final UserNSNameSequence nsSequence = new UserNSNameSequence(); nsSequence.setUserName(e.getKey().getName()); nsSequence.setUserNamespace(e.getKey().getNamespace()); user1.setRequestorNSName(nsSequence); reportType.setUser(user1); reportType.setUser(user1); reportType.setAveQueueDuration(e.getValue().getAverageQueueDuration()); reportType.setMedQueueDuration(e.getValue().getMedianQueueDuration()); reportType.setMinQueueDuration(e.getValue().getMinimumQueueDuration()); reportType.setMaxQueueDuration(e.getValue().getMaximumQueueDuration()); reportType.setTotalQueueDuration(e.getValue().getTotalQueueDuration()); reportType.setAveSessionDuration(e.getValue().getAverageSessionDuration()); reportType.setMedSessionDuration(e.getValue().getMedianSessionDuration()); reportType.setMinSessionDuration(e.getValue().getMinimumSessionDuration()); reportType.setMaxSessionDuration(e.getValue().getMaximumSessionDuration()); reportType.setTotalSessionDuration(e.getValue().getTotalSessionDuration()); reportType.setSessionCount(e.getValue().getSessionCount()); respType.addSessionReport(reportType); } } respType.setSessionCount(totalSessionCount); respType.setTotalQueueDuration(totalQueueDuration); respType.setTotalSessionDuration(totalSessionDuration); resp.setQuerySessionReportResponse(respType); } } finally { ses.close(); } return resp; }
From source file:au.org.theark.core.dao.ArkAuthorisationDao.java
License:Open Source License
@SuppressWarnings("unchecked") public List<ArkUserRole> getArkRoleListByUser(ArkUserVO arkUserVo) { List<ArkUserRole> arkUserRoleList = new ArrayList<ArkUserRole>(0); Criteria criteria = getSession().createCriteria(ArkUserRole.class); criteria.add(Restrictions.eq("arkUser", arkUserVo.getArkUserEntity())); // Restrict by Study if NOT Super Administrator try {/*from w ww .j a v a2 s . c o m*/ if (!isUserAdminHelper(arkUserVo.getArkUserEntity().getLdapUserName(), RoleConstants.ARK_ROLE_SUPER_ADMINISTATOR)) { Criteria studycriteria = criteria.createCriteria("study"); studycriteria.addOrder(Order.asc("name")); } } catch (HibernateException e) { log.error(e.getMessage(), e); } catch (EntityNotFoundException e) { log.error(e.getMessage(), e); } criteria.addOrder(Order.asc("arkModule")); criteria.addOrder(Order.asc("arkRole")); arkUserRoleList = (List<ArkUserRole>) criteria.list(); return arkUserRoleList; }
From source file:au.org.theark.core.dao.ArkAuthorisationDao.java
License:Open Source License
@SuppressWarnings("unchecked") public List<Study> getStudyListForUser(ArkUserVO arkUserVo) { List<Study> studyList = new ArrayList<Study>(0); Study searchStudy = arkUserVo.getStudy(); try {//from w w w. ja v a 2 s. c o m if (isUserAdminHelper(arkUserVo.getArkUserEntity().getLdapUserName(), RoleConstants.ARK_ROLE_SUPER_ADMINISTATOR)) { studyList = getAllStudiesForSuperAdmin(arkUserVo.getStudy());// Get all Studies } else { /* Get only the studies the ArkUser is linked to via the ArkUserRole */ Criteria criteria = getSession().createCriteria(ArkUserRole.class); criteria.add(Restrictions.eq("arkUser", arkUserVo.getArkUserEntity())); Criteria studyCriteria = criteria.createCriteria("study"); applyStudySearchCriteria(searchStudy, studyCriteria); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.groupProperty("study"), "study"); criteria.setProjection(projectionList); studyList = criteria.list(); } } catch (EntityNotFoundException e1) { log.error("The specified Ark User does not exist " + arkUserVo.getArkUserEntity().getLdapUserName()); e1.printStackTrace(); } return studyList; }
From source file:au.org.theark.core.dao.ArkAuthorisationDao.java
License:Open Source License
@SuppressWarnings("unchecked") public List<Study> getStudyListForUserAndModule(ArkUserVO arkUserVo, ArkModule arkModule) { List<Study> studyList = new ArrayList<Study>(0); Study searchStudy = arkUserVo.getStudy(); Criteria criteria = getSession().createCriteria(ArkUserRole.class); try {//from w ww .j a v a 2 s. c o m // Restrict by user if NOT Super Administrator if (isUserAdminHelper(arkUserVo.getArkUserEntity().getLdapUserName(), RoleConstants.ARK_ROLE_SUPER_ADMINISTATOR)) { // Fix another bug where the Super Administrator will never be able to INNER JOIN between ArkUserRole and Study on studyId // (since a Super Admin should always have null in the arkUserRole's study column) studyList = getAllStudiesForSuperAdmin(arkUserVo.getStudy()); // Get all Studies return studyList; } else { // Not Super Administrator, so continue with building the query criteria.add(Restrictions.eq("arkUser", arkUserVo.getArkUserEntity())); } } catch (EntityNotFoundException e) { log.error(e.getMessage(), e); } if (arkModule != null) { criteria.add(Restrictions.eq("arkModule", arkModule)); } else { // If no arkModule supplied, return empty list log.error("No arkModule supplied, returning empty study list"); return studyList; } // Restrict on study criteria (by default, NOT 'Archive' status) Criteria studyCriteria = criteria.createCriteria("study"); if (searchStudy.getId() != null) { studyCriteria.add(Restrictions.eq(Constants.STUDY_KEY, searchStudy.getId())); } if (searchStudy.getName() != null) { studyCriteria.add(Restrictions.ilike(Constants.STUDY_NAME, searchStudy.getName(), MatchMode.ANYWHERE)); } if (searchStudy.getDateOfApplication() != null) { studyCriteria.add(Restrictions.eq(Constants.DATE_OF_APPLICATION, searchStudy.getDateOfApplication())); } if (searchStudy.getEstimatedYearOfCompletion() != null) { studyCriteria.add( Restrictions.eq(Constants.EST_YEAR_OF_COMPLETION, searchStudy.getEstimatedYearOfCompletion())); } if (searchStudy.getChiefInvestigator() != null) { studyCriteria.add(Restrictions.ilike(Constants.CHIEF_INVESTIGATOR, searchStudy.getChiefInvestigator(), MatchMode.ANYWHERE)); } if (searchStudy.getContactPerson() != null) { studyCriteria.add(Restrictions.ilike(Constants.CONTACT_PERSON, searchStudy.getContactPerson(), MatchMode.ANYWHERE)); } if (searchStudy.getStudyStatus() != null) { studyCriteria.add(Restrictions.eq("studyStatus", searchStudy.getStudyStatus())); try { StudyStatus status = getStudyStatus("Archive"); studyCriteria.add(Restrictions.ne("studyStatus", status)); } catch (StatusNotAvailableException notAvailable) { log.error("Cannot look up and filter on archive status. Reference data could be missing"); } } else { try { StudyStatus status = getStudyStatus("Archive"); studyCriteria.add(Restrictions.ne("studyStatus", status)); } catch (StatusNotAvailableException notAvailable) { log.error("Cannot look up and filter on archive status. Reference data could be missing"); } } ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.groupProperty("study"), "study"); studyCriteria.addOrder(Order.asc("parentStudy")); criteria.setProjection(projectionList); studyList = criteria.list(); return studyList; }