Example usage for org.hibernate Session merge

List of usage examples for org.hibernate Session merge

Introduction

In this page you can find the example usage for org.hibernate Session merge.

Prototype

Object merge(Object object);

Source Link

Document

Copy the state of the given object onto the persistent object with the same identifier.

Usage

From source file:au.edu.anu.metadatastores.store.digitalcollections.DigitalCollectionsService.java

License:Open Source License

/**
 * Set the status of the record to deleted
 * //from  ww  w . ja va2 s  .  c  om
 * @param content The stub of the content to delete
 */
private void processDeleted(HarvestContent content) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();

        Query query = session
                .createQuery("FROM DigitalCollectionsItem WHERE extSystem = :extSystem AND extId = :extId");
        query.setParameter("extSystem", extSystem_);
        query.setParameter("extId", content.getIdentifier());

        DigitalCollectionsItem item = (DigitalCollectionsItem) query.uniqueResult();

        if (item != null) {
            item.setDeleted(Boolean.TRUE);
            session.merge(item);
        } else {
            LOGGER.debug("No record to be deleted: {}", content.getIdentifier());
        }
        session.getTransaction().commit();
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.digitalcollections.DigitalCollectionsService.java

License:Open Source License

/**
 * Process the record//from ww  w. j  a  v  a 2s  .  c  om
 * 
 * @param content The harvested content
 */
private void processRecord(HarvestContent content) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.enableFilter("attributes");
        LOGGER.debug("Identifier: {}", content.getIdentifier());

        Query query = session
                .createQuery("FROM DigitalCollectionsItem WHERE extSystem = :extSystem AND extId = :extId");
        query.setParameter("extSystem", extSystem_);
        query.setParameter("extId", content.getIdentifier());

        DigitalCollectionsItem item = (DigitalCollectionsItem) query.uniqueResult();
        if (item == null) {
            item = new DigitalCollectionsItem();
            item.setExtSystem(extSystem_);
            item.setExtId(content.getIdentifier());
            session.save(item);
        }

        try {
            JAXBContext context = JAXBContext.newInstance(DublinCore.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();

            DublinCore dublinCore = (DublinCore) unmarshaller.unmarshal(new StringReader(content.getContent()));
            Date lastModified = new Date();
            super.processRecord((DublinCoreItem) item, dublinCore, session, lastModified);
        } catch (JAXBException e) {
            LOGGER.error("Exception transforming document", e);
        } catch (InvocationTargetException e) {
            LOGGER.error("Error invoking method", e);
        } catch (IllegalAccessException e) {
            LOGGER.error("Error accessing method", e);
        }

        session.merge(item);

        LOGGER.info("Item Numbers: {}", item.getItemAttributes().size());

        session.getTransaction().commit();
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.grants.GrantService.java

License:Open Source License

/**
 * Save the grant information//from  w  w  w. java  2  s  . c o  m
 * 
 * @param grant The grant to save
 * @param userUpdated Indicator of whether it is user updated or system updated
 * @return The GrantItem that has been created/updated
 */
public GrantItem saveGrant(Grant grant, Boolean userUpdated) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();

    GrantItem item = null;
    try {
        session.enableFilter("attributes");
        session.beginTransaction();

        Query query = session.createQuery("from GrantItem where extId = :extId");
        query.setParameter("extId", grant.getContractCode());

        item = (GrantItem) query.uniqueResult();

        Date lastModified = new Date();
        ItemTraitParser parser = new ItemTraitParser();
        Item newItem = null;
        newItem = parser.getItem(grant, userUpdated, lastModified);

        if (item == null) {
            item = new GrantItem();
            if (newItem.getExtId() == null) {
                return null;
            }
            item.setExtId(newItem.getExtId());
            session.save(item);
        }

        updateAttributesFromItem(item, newItem, session, lastModified);

        LOGGER.debug("Number of item attributes before: {}", item.getItemAttributes().size());

        associatePeople(item, grant, session);

        LOGGER.debug("Number of Item Attributes after: {}", item.getItemAttributes().size());

        item = (GrantItem) session.merge(item);
        session.getTransaction().commit();
    } catch (IllegalAccessException e) {
        LOGGER.error("Exception accessing field when trying to get a grant item", e);
    } catch (InvocationTargetException e) {
        LOGGER.error("Exception invoking method when trying to get a grant item", e);
    } catch (Exception e) {
        if (item == null) {
            LOGGER.error("Exception querying item", e);
        } else {
            LOGGER.error("Error Merging Item {}", item.getIid(), e);
            LOGGER.info("Error with item: {}, Title: {}, System: {}, Ext Id: {}", item.getIid(),
                    item.getTitle(), item.getExtSystem(), item.getExtId());
            for (ItemAttribute attr : item.getItemAttributes()) {
                LOGGER.info("AID: {}, IID: {}, Type: {}, Value: {}", new Object[] { attr.getAid(),
                        attr.getItem().getIid(), attr.getAttrType(), attr.getAttrValue() });
            }
            for (HistItemAttribute attr : item.getHistItemAttributes()) {
                LOGGER.info("AID: {}, Date: {}, Type: {}, Value: {}", new Object[] { attr.getId().getAid(),
                        attr.getId().getHistDatetime(), attr.getAttrType(), attr.getAttrValue() });
            }
        }
    } finally {
        session.close();
    }

    return item;
}

From source file:au.edu.anu.metadatastores.store.misc.RelationService.java

License:Open Source License

/**
 * Updates the relation with a confirmation or denial of the relationship
 * /*from  w  ww.  j a va 2  s  . c  o  m*/
 * @param relation The relation to confirm or deny
 * @param isRelation Whether the relation is one or not
 */
public void confirmOrDenyRelation(Relation relation, Boolean isRelation) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();

        PotentialRelationId id = new PotentialRelationId(relation.getIid(), relation.getRelationValue(),
                relation.getRelatedIid());

        PotentialRelation potentialRelation = (PotentialRelation) session.get(PotentialRelation.class, id);

        if (potentialRelation == null) {
            potentialRelation = new PotentialRelation();
            potentialRelation.setId(id);
        }

        potentialRelation.setRequireCheck(Boolean.FALSE);
        potentialRelation.setIslink(isRelation);

        session.merge(potentialRelation);

        ItemRelationId itemRelationId = new ItemRelationId(id.getIid(), id.getRelationValue(),
                id.getRelatedIid());

        ItemRelation itemRelation = (ItemRelation) session.get(ItemRelation.class, itemRelationId);

        if (isRelation == Boolean.TRUE) {
            if (itemRelation == null) {
                itemRelation = new ItemRelation();
                itemRelation.setId(itemRelationId);
                itemRelation.setUserUpdated(Boolean.TRUE);
                session.save(itemRelation);
            } else {
                itemRelation.setUserUpdated(Boolean.TRUE);
                session.merge(itemRelation);
            }
        } else {
            if (itemRelation != null) {
                session.delete(itemRelation);
            }
        }

        session.getTransaction().commit();
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Save the person's information/*  w w  w .ja  va2  s .  c  o  m*/
 * 
 * @param person The person to save
 * @param userUpdated Indicates whether the information is user updated or not
 * @return The item information for the person
 */
public PersonItem savePerson(Person person, Boolean userUpdated) {
    if (person.getExtId() == null) {
        return null;
    }

    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.enableFilter("attributes");

        Query query = session.createQuery("from PersonItem where extId = :extId");
        query.setParameter("extId", person.getExtId());

        PersonItem item = (PersonItem) query.uniqueResult();
        String title = person.getFullName();

        Date lastModified = new Date();
        ItemTraitParser parser = new ItemTraitParser();
        Item newItem = null;

        try {
            newItem = parser.getItem(person, userUpdated, lastModified);
        } catch (Exception e) {
            LOGGER.error("Exception transforming person to an item", e);
        }

        if (item == null) {
            item = new PersonItem();
            item.setExtId(person.getExtId().toLowerCase());
            item.setTitle(title);
            item = (PersonItem) session.merge(item);
        } else {
            item.setTitle(title);
        }

        updateAttributesFromItem(item, newItem, session, lastModified);

        item = (PersonItem) session.merge(item);
        session.getTransaction().commit();
        return item;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.publication.PublicationService.java

License:Open Source License

/**
 * Save the publication//from  w ww.j  a  va  2  s .  c  om
 * 
 * @param publication The publication to save
 * @param userUpdated Indicates whether the update is user updated
 * @return The publication item
 */
public PublicationItem savePublication(Publication publication, Boolean userUpdated) {
    if (publication.getTitle() == null || publication.getTitle().trim().length() == 0) {
        return null;
    }

    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.enableFilter("attributes");

        //note this may need to be updated if we retrieve publications from other systems without an aries id
        Query query = session.createQuery(
                "SELECT pi FROM PublicationItem as pi inner join pi.itemAttributes as pia WHERE pia.attrType = :attrType and pia.attrValue = :attrValue");
        query.setParameter("attrType", StoreAttributes.ARIES_ID);
        query.setParameter("attrValue", publication.getAriesId());

        PublicationItem item = (PublicationItem) query.uniqueResult();

        Date lastModified = new Date();
        ItemTraitParser parser = new ItemTraitParser();
        Item newItem = null;
        try {
            newItem = parser.getItem(publication, userUpdated, lastModified);
        } catch (Exception e) {
            LOGGER.error("Exception transforming grant to an item", e);
        }

        if (item == null) {
            item = new PublicationItem();
            Query idQuery = session.createSQLQuery("SELECT nextval('publication_seq')");
            BigInteger id = (BigInteger) idQuery.uniqueResult();
            item.setExtId("p" + id.toString());
            item.setTitle(publication.getTitle());
            item = (PublicationItem) session.merge(item);
        } else if (publication.getTitle() != null && publication.getTitle().trim().length() > 0) {
            item.setTitle(publication.getTitle());
        }
        updateAttributesFromItem(item, newItem, session, lastModified);

        //TODO remove people who are no longer related
        Item personItem = null;
        ItemRelation itemRelation = null;
        ItemRelationId id = null;
        List<Item> peopleItems = new ArrayList<Item>();
        for (Person person : publication.getAuthors()) {
            personItem = personService_.getPersonItem(person.getUid());
            if (personItem != null) {
                peopleItems.add(personItem);
            } else {
                LOGGER.error("No person found to add relation for id: {}", person.getUid());
            }
        }
        boolean hasPerson = false;
        for (Item item2 : peopleItems) {
            for (ItemRelation relation : item.getItemRelationsForIid()) {
                if (relation.getId().getRelatedIid().equals(item2.getIid())) {
                    hasPerson = true;
                    break;
                }
            }
            if (!hasPerson) {
                itemRelation = new ItemRelation();
                id = new ItemRelationId(item.getIid(), StoreProperties.getProperty("publication.author.type"),
                        item2.getIid());
                itemRelation.setId(id);
                item.getItemRelationsForIid().add(itemRelation);
            }
            hasPerson = false;
        }

        item = (PublicationItem) session.merge(item);

        session.getTransaction().commit();

        return item;
    } finally {
        session.close();
    }
}

From source file:au.edu.uts.eng.remotelabs.schedserver.bookings.impl.slotsengine.DayBookings.java

License:Open Source License

/**
 * Finds a rig that matches the booking constraints and is viable (i.e. is
 * ready to be allocated to a session.                                   
 * /*from  w w  w.j a v  a2 s  .  co m*/
 * @param current rig assigned to booking which is assumed to be offline
 * @param mb memory booking
 * @param ses database session
 * @return viable matching rig or null if not found
 */
public Rig findViableRig(String current, MBooking mb, Session ses) {
    /* Rig bookings cannot be balanced to other rigs, so we can immediately
     * give a no success response. */
    if (mb.getType() == BType.RIG)
        return null;

    RigDao dao = new RigDao(ses);
    Rig currentRig = dao.findByName(current);
    if (currentRig == null) {
        this.logger.error("Attempt to find a viable rig for booking failed because rig " + current + " was not "
                + "found. Serious state loss.");
        return null;
    }

    RigBookings rb = this.getRigBookings(currentRig, ses), next;
    switch (mb.getType()) {
    case TYPE:
        next = rb.getTypeLoopNext();
        while (next != rb) {
            if (this.outerLoadBalance(next, mb, false)) {
                Rig viable = (Rig) ses.merge(next.getRig());
                ses.refresh(viable);
                if (viable.isActive() && viable.isOnline() && !viable.isInSession()) {
                    this.logger.debug("Viable load balancing found rig " + viable.getName() + " can satisfy "
                            + "booking for rig type " + mb.getRigType().getName() + '.');
                    this.outerLoadBalance(next, mb, true);
                    next.commitBooking(mb);
                    rb.removeBooking(mb);
                    return viable;
                }
            }
            next = next.getTypeLoopNext();
        }
        break;

    case CAPABILITY:
        next = rb.getCapsLoopNext(mb.getRequestCapabilities());
        while (next != rb) {
            if (this.outerLoadBalance(next, mb, false)) {
                Rig viable = (Rig) ses.merge(next.getRig());
                if (viable.isActive() && viable.isOnline() && !viable.isInSession()) {
                    this.logger.debug("Viable load balancing found rig " + viable.getName() + " can satisfy "
                            + "booking for request capabilities "
                            + mb.getRequestCapabilities().getCapabilities() + '.');
                    this.outerLoadBalance(next, mb, true);
                    next.commitBooking(mb);
                    rb.removeBooking(mb);
                    return viable;
                }
            }
            next = next.getCapsLoopNext(mb.getRequestCapabilities());
        }
        break;
    }

    return null;
}

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 w w . j  a  v a2  s .  c  om
 *  <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 />/*from   ww w.  j  a v  a2  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.org.theark.study.model.dao.StudyDao.java

License:Open Source License

public void updateStudy(Study study, Collection<ArkModule> selectedApplications)
        throws CannotRemoveArkModuleException {
    Session session = getSession();

    // session.update(study);
    // execute merge method instead of update to avoid org.hibernate.NonUniqueObjectException
    session.merge(study);

    Collection<LinkStudyArkModule> linkStudyArkModulesToAdd = getModulesToAddList(study, selectedApplications);
    // Determine Removal List here
    Collection<LinkStudyArkModule> linkStudyArkModulesToRemove = getModulesToRemoveList(study,
            selectedApplications);//from  w  ww. j a  va  2s. c o  m

    // Process the Removal of Linked ArkModules for this study
    for (LinkStudyArkModule linkStudyArkModule : linkStudyArkModulesToRemove) {
        session.delete(linkStudyArkModule);
    }
    // Insert the new modules for the Study
    for (LinkStudyArkModule linkStudyArkModule : linkStudyArkModulesToAdd) {
        session.save(linkStudyArkModule);
    }

    // Flush must be the last thing to call. If there is any other code/logic to be added make sure session.flush() is invoked after that.
    session.flush();
}