List of usage examples for org.hibernate Session flush
void flush() throws HibernateException;
From source file:au.com.nicta.ct.solution.tracking.CtTrackingModel.java
License:Open Source License
public CtResult deleteDetections(Collection<CtDetections> cd, boolean fireEvent) { // even if they are in tracks. if (!valid()) return CtResult.unchanged("Solution not valid."); if (cd.isEmpty()) return CtResult.unchanged("No detections to delete."); // CtImages i = _ism.current(); Session s = CtSession.Current(); s.beginTransaction();//from w w w. jav a2 s . c o m for (CtDetections d : cd) { CtImages i = d.getCtImages(); // in case not current image! i.getCtDetectionses().remove(d); _s.getCtDetectionses().remove(d); _orphans.remove(d); _detectionsStates.remove(d); _detectionsBoundaries.remove(d); // detection may be in many tracks HashSet<CtTracks> defunctTracks = new HashSet<CtTracks>(); HashSet<CtTracks> modifiedTracks = new HashSet<CtTracks>(); HashSet<CtTracksDetections> defunctTrackDetections = new HashSet<CtTracksDetections>(); Set<CtTracksDetections> tds = d.getCtTracksDetectionses(); // add tracks-detections of this detection must be removed for (CtTracksDetections td : tds) { // CtTracks t = td.getCtTracks(); defunctTrackDetections.add(td); } // if this leaves an empty track, remove the track too: for (CtTracksDetections td : defunctTrackDetections) { CtTracks t = td.getCtTracks(); Set<CtTracksDetections> tds2 = t.getCtTracksDetectionses(); tds.remove(td); tds2.remove(td); s.delete(td); // maybe track should be deleted too.. if (tds2.isEmpty()) { defunctTracks.add(t); } modifiedTracks.add(t); } for (CtTracks t : defunctTracks) { deleteTrackReferences(s, t); } for (CtTracks t : modifiedTracks) { if (defunctTracks.contains(t)) { continue; } updateTracksSequencedDetections(t); } s.delete(d); } s.flush(); CtSession.Current().getTransaction().commit(); fireModelChanged(); return CtResult.success("Detections deleted."); }
From source file:au.com.nicta.ct.solution.tracking.jipda.CtTkDBTracker.java
License:Open Source License
static void saveTracks(TkTracks tracks, int startTimeIdxInclusive, int endTimeIdxInclusive) { Session session = CtSession.Current(); session.beginTransaction();//from w ww . j a v a 2 s .c o m dropAllExistingTracks(session); // dropExistingTracks( session, tracks, startTimeIdxInclusive, endTimeIdxInclusive ); // session.flush(); CtSolutions solution = (CtSolutions) CtObjectDirectory.get("solution"); for (int tIdx = 0; tIdx < tracks.size(); ++tIdx) { TkTrack t = tracks.get(tIdx); // can we merge with existing track at the start CtTracks tt = findExistingTrackAtStart(session, t, startTimeIdxInclusive); // session.flush(); boolean firstDetectionHasTrack = (tt != null); // create a new track if ones does not already exist if (tt == null) { tt = new CtTracks(); tt.setCtSolutions(solution); solution.getCtTrackses().add(tt); session.save(tt); } // session.flush(); // re-associate tracks that joins at the end boolean mergedAtEnd = mergeTracksAtEnd(session, t, endTimeIdxInclusive, tt); // session.flush(); System.out.println("tt.getPkTrack(): " + (tt.getPkTrack())); // link up with parent tracks if (!t.isRoot()) { // find parent track's last detection TkTrack parent = (TkTrack) t.getParent(); TkDetection d = parent.getLast().det; if (d == null) { // no detection for this time step throw new Error("Parent track's last element can't be null detection"); } int detectionPK = d.find(DETECTION_PK); CtDetections dd = (CtDetections) CtSession.getObject(CtDetections.class, detectionPK); // associate detection with track CtTracksDetections ttdd = new CtTracksDetections(); ttdd.setCtTracks(tt); ttdd.setCtDetections(dd); tt.getCtTracksDetectionses().add(ttdd); dd.getCtTracksDetectionses().add(ttdd); session.save(ttdd); } // save detections for (int dIdx = 0; dIdx < t.elements.size(); ++dIdx) { // skip persistence of first detection if it is associated // with an existing track if (firstDetectionHasTrack && dIdx == 0) { continue; } // skip persistence of last detection if it has been merged with // existing track if (mergedAtEnd && dIdx == t.elements.size() - 1) { continue; } TkDetection d = t.elements.get(dIdx).det; if (d == null) { // no detection for this time step continue; } int detectionPK = d.find(DETECTION_PK); System.out.println("detectionPK: " + (detectionPK)); CtDetections dd = (CtDetections) CtSession.getObject(CtDetections.class, detectionPK); // associate detection with track CtTracksDetections ttdd = new CtTracksDetections(); ttdd.setCtTracks(tt); ttdd.setCtDetections(dd); tt.getCtTracksDetectionses().add(ttdd); dd.getCtTracksDetectionses().add(ttdd); session.save(ttdd); } // session.flush(); } //TODO why can we delete empty tracks? // session.flush(); // session.getTransaction().commit(); // removeEmptyTracks( session ); session.flush(); session.getTransaction().commit(); }
From source file:au.edu.anu.metadatastores.harvester.Harvest.java
License:Open Source License
/** * Save the list of harvested content//from ww w .j a v a 2 s . c o m * * @param harvestContents The list of harvested content to save */ private void saveList(List<HarvestContent> harvestContents) { Session session = HarvesterHibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); HarvestContent content = null; for (int i = 0; i < harvestContents.size(); i++) { content = harvestContents.get(i); session.save(content); if (i % 20 == 0) { session.flush(); session.clear(); } } session.getTransaction().commit(); } finally { session.close(); } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * Loads all the bookings for the day into memory. * //from w w w .j a v a2 s.c o m * @return ses database session */ @SuppressWarnings("unchecked") public void fullLoad(Session ses) { if (this.hasFullLoad) return; int num = 0; /* Load all the rigs that have bookings today. */ for (Rig rig : (List<Rig>) ses.createCriteria(Rig.class).list()) { if (this.rigBookings.containsKey(rig.getName())) continue; if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE)) .add(this.addDayRange()).add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION)) .add(Restrictions.eq("rig", rig)).setProjection(Projections.rowCount()).uniqueResult()) == 0) continue; this.logger.debug( "Rig " + rig.getName() + " has " + num + " bookings, so loading it up for full day load."); this.getRigBookings(rig, ses); } /* Load all the rig types that have bookings today. */ Criteria qu = ses.createCriteria(RigType.class); if (this.typeTargets.size() > 0) qu.add(Restrictions.not(Restrictions.in("name", this.typeTargets.keySet()))); for (RigType type : (List<RigType>) qu.list()) { if (this.typeTargets.containsKey(type.getName())) continue; if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE)) .add(this.addDayRange()) .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION)) .add(Restrictions.eq("rigType", type)).setProjection(Projections.rowCount()) .uniqueResult()) == 0) continue; this.logger.debug("Rig type " + type.getName() + " has " + num + " bookings, so loading it up for" + " full day load."); Set<Rig> rigs = type.getRigs(); if (rigs.size() == 0) { this.logger.warn("Rig type " + type.getName() + " has " + num + " bookings but not rigs so they all" + " will be cancelled."); for (Bookings bk : (List<Bookings>) ses.createCriteria(Bookings.class) .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange()) .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION)) .add(Restrictions.eq("rigType", type)).list()) { this.logger.warn("Cancelling booking for " + bk.getUser().qName() + " because booking rig type " + type.getName() + " has no rigs."); bk.setActive(false); bk.setCancelReason("Booked rig type has no rigs."); new BookingNotification(bk).notifyCancel(); } ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); continue; } this.getRigBookings(rigs.iterator().next(), ses); } /* Load all the request capabilities that have bookings today. */ qu = ses.createCriteria(RequestCapabilities.class); if (this.capsTargets.size() > 0) qu.add(Restrictions.not(Restrictions.in("capabilities", this.capsTargets.keySet()))); for (RequestCapabilities caps : (List<RequestCapabilities>) qu.list()) { if (this.capsTargets.containsKey(caps.getCapabilities())) continue; if ((num = (Integer) ses.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE)) .add(this.addDayRange()) .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION)) .add(Restrictions.eq("requestCapabilities", caps)).setProjection(Projections.rowCount()) .uniqueResult()) == 0) continue; this.logger.debug("Request capabilities " + caps.getCapabilities() + " has " + num + " bookings, so " + "loading it up for full day load."); List<RequestCapabilities> capsList = new ArrayList<RequestCapabilities>(); capsList.add(caps); this.loadRequestCapabilities(capsList, ses, true); if (!this.capsTargets.containsKey(caps.getCapabilities())) { this.logger.warn("Request capabilities " + caps.getCapabilities() + " has " + num + " bookings but " + "not any matching rigs so they all will be cancelled."); for (Bookings bk : (List<Bookings>) ses.createCriteria(Bookings.class) .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange()) .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION)) .add(Restrictions.eq("requestCapabilities", caps)).list()) { this.logger.warn("Cancelling booking for " + bk.getUser().qName() + " because booking request " + "capabilities " + caps.getCapabilities() + " has no matching rigs."); bk.setActive(false); bk.setCancelReason("Booked request capabilities has no rigs."); new BookingNotification(bk).notifyCancel(); } ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * A rig has been registered. A registered rig may: * <ul>//w ww . ja v a2s.c o m * <li>Be newly registered.</li> * <li>Have a changed type or rig capabilities from a previous registration.</li> * <li>Be the same as a previous registration.</li> * <ul> * * @param rig rig that was registered * @param ses database session */ public void rigRegistered(Rig rig, Session ses) { String rigName = rig.getName(); String rigType = rig.getRigType().getName(); List<RequestCapabilities> rigCaps = new ArrayList<RequestCapabilities>(); for (MatchingCapabilities match : rig.getRigCapabilities().getMatchingCapabilitieses()) { rigCaps.add(match.getRequestCapabilities()); } if (this.rigBookings.containsKey(rigName)) { RigBookings rb = this.rigBookings.get(rigName); /* Check the type loop to see whether we are member of the correct type * loop. */ if (!rb.getRigType().equals(rigType)) { /* The rig changed type so we must remove the rig from it current type * resource loop and it add it to the new rig resource loop. */ this.logger.debug("Registered rig " + rigName + " has a different type then when it was last " + "registered so changing type mapping."); if (rb.getTypeLoopNext() == rb) { /* The type just contains the rig so remove the type loop all together. */ this.typeTargets.remove(rb.getRigType()); /* All type bookings assigned to the rig need to be cancelled * because the type no longer exists. */ List<MBooking> typeb = rb.getTypeBookings(); for (MBooking mb : typeb) { /* In session type bookings have already been allocated * to the rig so cannot be moved. */ if (mb.getSession() != null) continue; this.logger.warn("Cancelling type booking (" + mb.getBooking().getId() + ") because the " + "previous assigned rig " + rigName + " has changed type."); rb.removeBooking(mb); Bookings b = (Bookings) ses.merge(mb.getBooking()); b.setActive(false); b.setCancelReason("Rig no longer in rig type."); new BookingNotification(b).notifyCancel(); } if (typeb.size() > 0) { ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } } else { RigBookings prev = rb.getTypeLoopNext(), next = prev.getTypeLoopNext(); while (next != rb) { prev = next; next = next.getTypeLoopNext(); } prev.setTypeLoopNext(rb.getTypeLoopNext()); if (this.typeTargets.get(prev.getRigType()) == rb) this.typeTargets.put(prev.getRigType(), prev); /* For all the type bookings, try to put the booking on * a different rig. */ List<MBooking> typeb = rb.getTypeBookings(); boolean requiresFlush = false; for (MBooking mb : typeb) { /* In session type bookings have already been allocated * to the rig so cannot be moved. */ if (mb.getSession() != null) continue; rb.removeBooking(mb); Bookings b = (Bookings) ses.merge(mb.getBooking()); mb.setBooking(b); if (!this.createBooking(mb, ses)) { requiresFlush = true; b.setActive(false); b.setCancelReason("Type over booked because rig no longer in rig type."); new BookingNotification(b).notifyCancel(); } } if (requiresFlush) { ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } } /* Add the rig to the type resource loop. */ rb.setRigType(rigType); if (this.typeTargets.containsKey(rigType)) { /* The rig type loop already exists so add the registered * rig to it. */ RigBookings tt = this.typeTargets.get(rigType); rb.setTypeLoopNext(tt.getTypeLoopNext()); tt.setTypeLoopNext(rb); } else { this.loadRigType(rig, ses, new ArrayList<RequestCapabilities>()); } } /* Make sure all the capability resource loops are correct for the * registered rig. */ List<String> currentCaps = rb.getCapabilities(); Iterator<RequestCapabilities> it = rigCaps.iterator(); while (it.hasNext()) { RequestCapabilities reqCaps = it.next(); if (currentCaps.contains(reqCaps.getCapabilities())) { it.remove(); currentCaps.remove(reqCaps.getCapabilities()); } } /* Remove the capabilities the rig is no longer a member of. */ if (currentCaps.size() > 0) { for (String cc : currentCaps) { this.logger.debug("Rig " + rigName + " no longer has capability " + cc + " so removing it from " + "the " + cc + " resource loop."); List<MBooking> capsb = rb.getCapabilitiesBookings(cc); if (rb.getCapsLoopNext(cc) == rb) { this.capsTargets.remove(cc); /* Need to cancel all of the capabilities bookings because * the request capabilities has no more rigs. */ for (MBooking mb : capsb) { if (mb.getSession() != null) continue; rb.removeBooking(mb); Bookings b = (Bookings) ses.merge(mb.getBooking()); b.setActive(false); b.setCancelReason("Capabilities over booked because rig no longer matches capability."); new BookingNotification(b).notifyCancel(); } if (capsb.size() > 0) { ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } } else { /* Remove the rig for the capabilities loop. */ RigBookings prev = rb.getCapsLoopNext(cc), next = prev.getCapsLoopNext(cc); while (next != rb) { prev = next; next = next.getCapsLoopNext(cc); } prev.setCapsLoopNext(cc, rb.getCapsLoopNext(cc)); /* First attempt to put the booking onto another rig. */ boolean requiresFlush = false; for (MBooking mb : capsb) { if (mb.getSession() != null) continue; rb.removeBooking(mb); Bookings b = (Bookings) ses.merge(mb.getBooking()); mb.setBooking(b); if (!this.createBooking(mb, ses)) { b.setActive(false); b.setCancelReason( "Capabilities over booked because rig no longer matches capability."); new BookingNotification(b).notifyCancel(); requiresFlush = true; } } if (requiresFlush) { ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } } rb.removeCapsLoopNext(cc); } } /* Make sure all the remaining capabilities are loaded. For loaded * capabilities loops, insert the rig into them. */ it = rigCaps.iterator(); while (it.hasNext()) { RequestCapabilities reqCaps = it.next(); /* Caps loop is not loaded, so no need to load it. */ if (!this.capsTargets.containsKey(reqCaps.getCapabilities())) continue; RigBookings capsb = this.capsTargets.get(reqCaps.getCapabilities()); rb.setCapsLoopNext(reqCaps, capsb.getCapsLoopNext(reqCaps)); capsb.setCapsLoopNext(reqCaps, rb); it.remove(); } if (rigCaps.size() > 0) { this.loadRequestCapabilities(rigCaps, ses, true); } } else { RigBookings rb = new RigBookings(rig, this.day); /* The rig isn't registered so may either be new *OR* the resource * loops it is a member of aren't loaded. */ if (this.typeTargets.containsKey(rigType)) { /* The type is loaded so the rig is a new rig. This means we can * safely insert the rig into its matching resource loop because * there can be no incorrect mappings. */ this.rigBookings.put(rigName, rb); this.logger .debug("Registered rig " + rig.getName() + " is new and has its type resource loop loaded " + "so inserting it into the type resource loop for day " + this.day + "."); /* Insert the rig into the type resource loop. */ RigBookings typerb = this.typeTargets.get(rigType); rb.setTypeLoopNext(typerb.getTypeLoopNext()); typerb.setTypeLoopNext(rb); /* If any of the request capabilities are loaded, add to rig * to them. */ for (RequestCapabilities caps : rigCaps) { if (this.capsTargets.containsKey(caps.getCapabilities())) { this.logger.debug("Registered rig " + rigName + " is new and has its matching capability '" + caps.getCapabilities() + "' resource loop loaded so inserting the rig in the " + "capability resource loop for day " + this.day + "."); RigBookings capsrb = this.capsTargets.get(caps.getCapabilities()); rb.setCapsLoopNext(caps, capsrb.getCapsLoopNext(caps)); capsrb.setCapsLoopNext(caps, rb); } } } else { /* The rig can be either new or existing but unloaded in this day. * Either way, we check the capabilities loops and if the rig matches * at least one, we add the rig to it and do a load of the type. */ boolean hasMatch = false; Iterator<RequestCapabilities> it = rigCaps.iterator(); while (it.hasNext()) { RequestCapabilities caps = it.next(); if (this.capsTargets.containsKey(caps.getCapabilities())) { this.logger.debug("Registered rig " + rigName + " is new and has its matching capability '" + caps.getCapabilities() + "' resource loop loaded so inserting the rig in the " + "capability resource loop."); hasMatch = true; RigBookings capsrb = this.capsTargets.get(caps.getCapabilities()); rb.setCapsLoopNext(caps, capsrb.getCapsLoopNext(caps)); capsrb.setCapsLoopNext(caps, rb); it.remove(); } } if (hasMatch) { this.rigBookings.put(rigName, rb); this.loadRigType(rig, ses, rigCaps); this.loadRequestCapabilities(rigCaps, ses, true); } } } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * Makes the rig unavailable for the scheduled offline period. If there * are already assigned bookings for the rigs, these will be either moved * to a different rig or cancelled if no matching rig is found. * <br />/* w ww . ja va 2 s . c o m*/ * This works <em>lazily</em> so if the rig isn't loaded, it will not be * loaded and marked offline. * * @param off offline period * @param ses database session */ public void putRigOffline(RigOfflineSchedule off, Session ses) { if (!(this.rigBookings.containsKey(off.getRig().getName()))) { this.logger.debug("Not committing offline period for rig " + off.getRig().getName() + " because the rig " + "isn't loaded."); return; } RigBookings rb = this.getRigBookings(off.getRig(), ses); MBooking mb = new MBooking(off, this.day); if (mb.getEndSlot() < 0) return; /* Get the the bookings on the rig that already exist. These will need * to be moved or will be canceled. */ int ss = mb.getStartSlot(); List<MBooking> oldBookings = new ArrayList<MBooking>(); while (ss <= mb.getDuration()) { MBooking ex = rb.getNextBooking(ss); if (ex == null) break; rb.removeBooking(ex); oldBookings.add(ex); ss = ex.getEndSlot() + 1; } /* Commit the maintenance holding booking. */ rb.commitBooking(mb); /* Move or cancel the old bookings. */ boolean hasCanceled = false; for (MBooking ex : oldBookings) { if (ex.getBooking() == null) continue; if (!this.createBooking(ex, ses)) { Bookings booking = (Bookings) ses.merge(ex.getBooking()); this.logger.warn("Canceling booking (ID " + booking.getId() + ") for user " + booking.getUser().qName() + " because the assigned rig " + off.getRig().getName() + " will be offline and there are no " + "other rigs which can take the booking."); booking.setActive(false); booking.setCancelReason("Rig will be offline for reservation."); hasCanceled = true; new BookingNotification(booking).notifyCancel(); } } if (hasCanceled) { /* Commit the cancellations. */ ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * Loads the request capabilities./*from w w w .j ava 2s . co m*/ * * @param capsList capabilities list * @param ses database session */ private void loadRequestCapabilities(List<RequestCapabilities> capsList, Session ses, boolean ignoreNoBookings) { while (capsList.size() > 0) { RequestCapabilities reqCaps = capsList.get(0); this.logger.debug( "Attempting to load bookings for request capabilities " + reqCaps.getCapabilities() + '.'); Criteria qu = ses.createCriteria(Bookings.class) .add(Restrictions.eq("resourceType", ResourcePermission.CAPS_PERMISSION)) .add(Restrictions.eq("requestCapabilities", reqCaps)) .add(Restrictions.eq("active", Boolean.TRUE)).add(this.addDayRange()) .addOrder(Order.desc("duration")); @SuppressWarnings("unchecked") List<Bookings> bookings = qu.list(); /* There are no bookings for this class so no need to load it * yet. */ if (ignoreNoBookings && bookings.size() == 0) { this.logger.debug("Not going to load request capabilities " + reqCaps.getCapabilities() + " because " + "it has no bookings."); capsList.remove(0); continue; } /* Find all the matching rigs. */ List<Rig> matchingRigs = new ArrayList<Rig>(); for (MatchingCapabilities match : reqCaps.getMatchingCapabilitieses()) { matchingRigs.addAll(match.getRigCapabilities().getRigs()); } /* If the request capabilities has no matching rigs, we cannot load * the request capabilities loop. */ if (matchingRigs.size() == 0) { this.logger.debug("Cannot load up request capbilities resource loop for '" + reqCaps.getCapabilities() + "' because it has no matching rigs."); capsList.remove(0); continue; } /* Make sure all the rigs are loaded. */ for (Rig r : matchingRigs) { if (!this.rigBookings.containsKey(r.getName())) { RigBookings b = new RigBookings(r, this.day); this.loadRig(b, r, ses); this.rigBookings.put(r.getName(), b); /* By definition, since a rig wasn't loaded, it's type wasn't * loaded either. */ this.loadRigType(r, ses, capsList); } } /* Complete the request capabilities resource loop. */ RigBookings first = this.rigBookings.get(matchingRigs.get(0).getName()); RigBookings prev = first; for (int i = 1; i < matchingRigs.size(); i++) { RigBookings next = this.rigBookings.get(matchingRigs.get(i).getName()); prev.setCapsLoopNext(reqCaps, next); prev = next; } prev.setCapsLoopNext(reqCaps, first); /* Load the request capabilities bookings. */ for (Bookings booking : bookings) { MBooking membooking = new MBooking(booking, this.day); RigBookings next = first; do { if (next.areSlotsFree(membooking)) { if (next.commitBooking(membooking)) { /* If there is a next booking, try load it to the next rig. */ first = next.getCapsLoopNext(reqCaps); break; } else { this.logger.error( "Failed to commit a booking to a slots that should have been empty. This " + "is a probable race condition. Ominous, but the loading search will continue regardless."); } } next = next.getCapsLoopNext(reqCaps); } while (next != first); /* The assignment loop was completed and no position was found to put * the booking, so run load balance to try to free a resource. */ if (!next.hasBooking(membooking)) { do { if (this.innerLoadBalance(next, membooking, true)) { if (next.commitBooking(membooking)) { /* If there is a next booking, try load it to the next rig. */ first = next.getCapsLoopNext(reqCaps); break; } else { this.logger .error("Failed to commit a booking to a slots that should have been empty. " + "This is a probable race condition. Ominous, but the loading search will " + "continue regardless."); } } next = next.getCapsLoopNext(reqCaps); } while (next != first); } /* The balancing loop was completed and no position was found to put * the booking, so the booking will need to be canceled. */ if (!next.hasBooking(membooking)) { this.logger.error("Request capabilities '" + reqCaps.getCapabilities() + "' is over commited " + "and has over lapping bookings. The booking for '" + booking.getUserNamespace() + ':' + booking.getUserName() + "' starting at " + booking.getStartTime() + " is being cancelled."); booking.setActive(false); booking.setCancelReason("Request capabilities was overbooked."); ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); new BookingNotification(booking).notifyCancel(); } } this.capsTargets.put(capsList.remove(0).getCapabilities(), prev); } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * Loads a rig type by creating the rig bookings type loop, then loading * the rig type bookings to rigs./* ww w . j a v a2 s. c om*/ * * @param rig rig in type * @param ses database session * @param capsToLoad list of request capabilities that may need to be loaded from * the rigs in type */ @SuppressWarnings("unchecked") private void loadRigType(Rig rig, Session ses, List<RequestCapabilities> capsToLoad) { RigBookings first = this.rigBookings.get(rig.getName()); RigBookings prev = first; /* Set up the rig type navigation loop. */ RigType rigType = rig.getRigType(); this.logger.debug("Loading rig type " + rigType.getName() + " for day " + this.day + '.'); Set<Rig> rigs = rigType.getRigs(); for (Rig r : rigs) { for (MatchingCapabilities match : r.getRigCapabilities().getMatchingCapabilitieses()) { RequestCapabilities reqCaps = match.getRequestCapabilities(); if (!capsToLoad.contains(reqCaps)) { capsToLoad.add(reqCaps); } } /* Don't duplicate the initial rig. */ if (r.equals(rig)) continue; RigBookings next = new RigBookings(r, this.day); this.loadRig(next, r, ses); this.rigBookings.put(r.getName(), next); prev.setTypeLoopNext(next); prev = next; } /* Complete the type loop. */ prev.setTypeLoopNext(first); /* Load up the type bookings. */ Criteria qu = ses.createCriteria(Bookings.class) .add(Restrictions.eq("resourceType", ResourcePermission.TYPE_PERMISSION)) .add(Restrictions.eq("rigType", rigType)).add(Restrictions.eq("active", Boolean.TRUE)) .add(this.addDayRange()).addOrder(Order.desc("duration")); for (Bookings booking : (List<Bookings>) qu.list()) { MBooking membooking = new MBooking(booking, this.day); RigBookings next = first; do { if (next.areSlotsFree(membooking)) { if (next.commitBooking(membooking)) { /* If there is a next booking, try load it to the next rig. */ first = next.getTypeLoopNext(); break; } else { this.logger.error("Failed to commit a booking to a slots that should have been empty. This " + "is a probable race condition. Ominous, but the loading search will continue regardless."); } } next = next.getTypeLoopNext(); } while (next != first); /* The assignment loop was completed and no position was found to put * the booking, so run load balance to try to free a resource. */ if (!next.hasBooking(membooking)) { do { if (this.innerLoadBalance(next, membooking, true)) { if (next.commitBooking(membooking)) { /* If there is a next booking, try load it to the next rig. */ first = next.getTypeLoopNext(); break; } else { this.logger.error("Failed to commit a booking to a slots that should have been empty. " + "This is a probable race condition. Ominous, but the loading search will " + "continue regardless."); } } next = next.getTypeLoopNext(); } while (next != first); } /* The balancing loop was completed and no position was found to put * the booking, so the type was over-booked. The booking will need to be canceled. */ if (!next.hasBooking(membooking)) { this.logger.error( "Rig type '" + rigType.getName() + "' is over commited and has over lapping bookings. " + "The booking for '" + booking.getUserNamespace() + ':' + booking.getUserName() + "' starting at " + booking.getStartTime() + " is being cancelled."); booking.setActive(false); booking.setCancelReason("Rig type was overbooked."); ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); new BookingNotification(booking).notifyCancel(); } } this.typeTargets.put(rigType.getName(), first); }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java
License:Open Source License
/** * Loads the rig booking times for the rig. If the rig is over committed * (overlapping rig bookings), one of the bookings is canceled. * // w w w.j a va2s .com * @param bookings rig bookings container * @param rig rig to load bookings from * @param ses database session */ @SuppressWarnings("unchecked") private void loadRig(RigBookings bookings, Rig rig, Session ses) { /* Load the rig offline periods. */ Criteria qu = ses.createCriteria(RigOfflineSchedule.class).add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.eq("rig", rig)).add(this.addDayRange()); for (RigOfflineSchedule off : (List<RigOfflineSchedule>) qu.list()) { bookings.commitBooking(new MBooking(off, this.day)); } /* Load the rigs bookings. */ qu = ses.createCriteria(Bookings.class) .add(Restrictions.eq("resourceType", ResourcePermission.RIG_PERMISSION)) .add(Restrictions.eq("rig", rig)).add(Restrictions.eq("active", Boolean.TRUE)) .add(this.addDayRange()); for (Bookings booking : (List<Bookings>) qu.list()) { if (!bookings.commitBooking(new MBooking(booking, this.day))) { /* The rig has been over booked so this booking will * need to be canceled. */ this.logger.error("Rig '" + rig.getName() + "' is over commited and has over lapping bookings. " + "The booking for '" + booking.getUserNamespace() + ':' + booking.getUserName() + "' starting at " + booking.getStartTime() + " is being cancelled."); booking.setActive(false); booking.setCancelReason("Rig will be offline or was overbooked."); ses.beginTransaction(); ses.flush(); ses.getTransaction().commit(); new BookingNotification(booking).notifyCancel(); } } }
From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.SlotBookingEngine.java
License:Open Source License
@Override public synchronized BookingInit init() { this.logger.debug("Initalising the slot booking engine..."); Calendar today = Calendar.getInstance(); /* Cancel all bookings in the past. */ Session db = DataAccessActivator.getNewSession(); @SuppressWarnings("unchecked") List<Bookings> bookings = db.createCriteria(Bookings.class).add(Restrictions.eq("active", Boolean.TRUE)) .add(Restrictions.lt("endTime", today.getTime())).list(); for (Bookings bk : bookings) { this.logger.warn("Cancelling booking (" + bk.getId() + ") which expired when the Scheduling Server " + "was not running for user " + bk.getUser().qName() + " which expired on " + bk.getEndTime() + '.'); bk.setActive(false);/* www. j av a2s. com*/ bk.setCancelReason("Expired when Scheduling Server was not running."); new BookingNotification(bk).notifyCancel(); } if (bookings.size() > 0) { db.beginTransaction(); db.flush(); db.getTransaction().commit(); } /* Load up the current day bookings. */ DayBookings day = this.getDayBookings(TimeUtil.getDayKey(today)); day.fullLoad(db); /* Initalise the management tasks. */ BookingInit init = new BookingInit(); this.redeemer = new Redeemer(this, day); init.addTask(this.redeemer); init.addListener(this.redeemer); init.addListener(new RigRegisteredListener()); init.addTask(new DayCleaner()); return init; }