Example usage for org.hibernate LockOptions UPGRADE

List of usage examples for org.hibernate LockOptions UPGRADE

Introduction

In this page you can find the example usage for org.hibernate LockOptions UPGRADE.

Prototype

LockOptions UPGRADE

To view the source code for org.hibernate LockOptions UPGRADE.

Click Source Link

Document

Represents LockMode.UPGRADE (will wait forever for lock and scope of false meaning only entity is locked).

Usage

From source file:org.generationcp.middleware.dao.GenericDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public T getById(final ID id, final boolean lock) {
    if (id == null) {
        return null;
    }/*  w w w .j  a va  2  s.  co m*/
    try {
        final T entity;
        if (lock) {
            entity = (T) this.getSession().get(this.getPersistentClass(), id, LockOptions.UPGRADE);
        } else {
            entity = (T) this.getSession().get(this.getPersistentClass(), id);
        }
        return entity;
    } catch (HibernateException e) {
        throw new MiddlewareQueryException("Error in getById(id=" + id + "): " + e.getMessage(), e);
    }
}

From source file:org.jboss.dashboard.factory.InitialModulesManager.java

License:Apache License

public void start() throws Exception {
    List<InitialModule> modules = initialModuleRegistry.getInitialModulesRegistered();
    for (final InitialModule module : modules) {
        new HibernateTxFragment(true) {
            protected void txFragment(Session session) throws Exception {
                InstalledModule currentVersion = (InstalledModule) session.get(InstalledModule.class,
                        module.getName(), LockOptions.UPGRADE);

                // The module is not registered => Install it!
                if (currentVersion == null) {
                    if (module.doTheInstall()) {
                        if (log.isDebugEnabled())
                            log.debug(//  w w w. ja v  a 2  s  .c  o m
                                    "Installed module " + module.getName() + " version " + module.getVersion());
                        currentVersion = new InstalledModule(module.getName(), 1);
                        session.save(currentVersion);
                        session.flush();
                    } else {
                        log.warn("Error installing module " + module.getName() + " version "
                                + module.getVersion());
                    }
                }
                // The module's version has been increased => Upgrade it!
                else if (currentVersion.getVersion() < module.getVersion()) {
                    if (module.doTheUpgrade(currentVersion.getVersion())) {
                        if (log.isDebugEnabled())
                            log.debug("Upgraded module " + module.getName() + " to version "
                                    + module.getVersion());
                        currentVersion.setVersion(module.getVersion());
                        session.saveOrUpdate(currentVersion);
                        session.flush();
                    } else {
                        log.warn("Error upgrading module " + module.getName() + " to version "
                                + module.getVersion());
                    }
                }
                // Default => Do nothing.
                else {
                    if (log.isDebugEnabled())
                        log.debug("Module " + module.getName() + " version " + module.getVersion()
                                + "is already installed.");
                }
            }
        }.execute();
    }
}

From source file:org.jboss.dashboard.initialModule.InitialModulesManager.java

License:Apache License

public void start() throws Exception {
    if (initialModulesEnabled) {

        // BZ-1014612: First check if another node is currently installing modules. If it is, do nothing, Otherwise, install initial modules.
        boolean doTheInstall = clusterNodesManager.shouldInstallModules();
        if (!doTheInstall) {
            log.info("Skipping initial modules installation as other node is currenly installing.");
            return;
        }/*from w w  w . ja v a  2  s  .  com*/

        List<InitialModule> modules = initialModuleRegistry.getInitialModulesRegistered();
        for (final InitialModule module : modules) {
            new HibernateTxFragment(true) {
                protected void txFragment(Session session) throws Exception {
                    InstalledModule currentVersion = (InstalledModule) session.get(InstalledModule.class,
                            module.getName(), LockOptions.UPGRADE);

                    // The module is not registered => Install it!
                    if (currentVersion == null) {
                        if (module.doTheInstall()) {
                            if (log.isDebugEnabled())
                                log.debug("Installed module " + module.getName() + " version "
                                        + module.getVersion());
                            currentVersion = new InstalledModule(module.getName(), 1);
                            session.save(currentVersion);
                            session.flush();
                        } else {
                            log.warn("Error installing module " + module.getName() + " version "
                                    + module.getVersion());
                        }
                    }
                    // The module's version has been increased => Upgrade it!
                    else if (currentVersion.getVersion() < module.getVersion()) {
                        if (module.doTheUpgrade(currentVersion.getVersion())) {
                            if (log.isDebugEnabled())
                                log.debug("Upgraded module " + module.getName() + " to version "
                                        + module.getVersion());
                            currentVersion.setVersion(module.getVersion());
                            session.saveOrUpdate(currentVersion);
                            session.flush();
                        } else {
                            log.warn("Error upgrading module " + module.getName() + " to version "
                                    + module.getVersion());
                        }
                    }
                    // Default => Do nothing.
                    else {
                        if (log.isDebugEnabled())
                            log.debug("Module " + module.getName() + " version " + module.getVersion()
                                    + "is already installed.");
                    }
                }
            }.execute();
        }

        // BZ-1014612: Initial modules installation finished. Set node status to old one.
        finishInstallation();

    } else {
        log.info("Initial modules are NOT being installed.");
    }
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * @param journal the Journal/*from  w w w .jav  a2 s .c o m*/
 * @param acct the account
 * @param date checkpoint date (inclusive)
 * @param layers taken into account in this checkpoint
 * @param threshold minimum number of  GLEntries required to create a checkpoint
 * @throws GLException if user doesn't have CHECKPOINT permission on this jounral.
 */
public void createCheckpoint(Journal journal, Account acct, Date date, int threshold, short[] layers)
        throws HibernateException, GLException {
    if (date == null)
        throw new GLException("Invalid checkpoint date");
    checkPermission(GLPermission.CHECKPOINT, journal);
    // Transaction tx = session.beginTransaction();
    session.buildLockRequest(LockOptions.UPGRADE).lock(journal);
    createCheckpoint0(journal, acct, date, threshold, layers);
    // tx.commit();
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * Lock a journal./*ww  w.ja  va 2  s  .c om*/
 * @param journal the journal.
 * @throws HibernateException on database errors.
 * @throws GLException if user doesn't have POST permission on this jounral.
 */
public void lock(Journal journal) throws HibernateException, GLException {
    checkPermission(GLPermission.POST, journal);
    session.buildLockRequest(LockOptions.UPGRADE).lock(journal);
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * set a journal's lockDate/*from w  w  w . jav  a2  s .c o m*/
 * @param journal the Journal
 * @param lockDate the lock date.
 * @throws HibernateException on database errors.
 * @throws GLException if users doesn't have global READ permission.
 */
public void setLockDate(Journal journal, Date lockDate) throws GLException, HibernateException {
    checkPermission(GLPermission.WRITE, journal);
    // Transaction tx = session.beginTransaction();
    session.buildLockRequest(LockOptions.UPGRADE).lock(journal);
    journal.setLockDate(lockDate);
    // tx.commit();
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

private AccountLock getLock(Journal journal, Account acct) throws HibernateException {
    AccountLock key = new AccountLock(journal, acct);
    AccountLock lck = (AccountLock) session.get(AccountLock.class, key, LockOptions.UPGRADE);
    if (lck == null)
        session.buildLockRequest(LockOptions.UPGRADE).lock(journal); // need a journal level lock
    lck = (AccountLock) session.get(AccountLock.class, key, LockOptions.UPGRADE); // try again
    if (lck == null) {
        session.save(lck = key);//  w  w w  .j a  va  2  s.  c o m
        session.flush();
    }
    return lck;
}

From source file:org.openmrs.api.db.hibernate.HibernateOrderDAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.OrderDAO#getNextOrderNumberSeedSequenceValue()
 *///from   w  w w  .jav a  2  s. c  o m
@Override
public Long getNextOrderNumberSeedSequenceValue() {
    Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(GlobalProperty.class);
    searchCriteria.add(Restrictions.eq("property", OpenmrsConstants.GP_NEXT_ORDER_NUMBER_SEED));
    GlobalProperty globalProperty = (GlobalProperty) sessionFactory.getCurrentSession()
            .get(GlobalProperty.class, OpenmrsConstants.GP_NEXT_ORDER_NUMBER_SEED, LockOptions.UPGRADE);

    if (globalProperty == null) {
        throw new APIException("GlobalProperty.missing ",
                new Object[] { OpenmrsConstants.GP_NEXT_ORDER_NUMBER_SEED });
    }

    String gpTextValue = globalProperty.getPropertyValue();
    if (StringUtils.isBlank(gpTextValue)) {
        throw new APIException("GlobalProperty.invalid.value",
                new Object[] { OpenmrsConstants.GP_NEXT_ORDER_NUMBER_SEED });
    }

    Long gpNumericValue = null;
    try {
        gpNumericValue = Long.parseLong(gpTextValue);
    } catch (NumberFormatException ex) {
        throw new APIException("GlobalProperty.invalid.value",
                new Object[] { OpenmrsConstants.GP_NEXT_ORDER_NUMBER_SEED });
    }

    globalProperty.setPropertyValue(String.valueOf(gpNumericValue + 1));

    sessionFactory.getCurrentSession().save(globalProperty);

    return gpNumericValue;
}

From source file:org.sakaiproject.assignment.impl.persistence.AssignmentRepositoryImpl.java

License:Educational Community License

@Override
@Transactional// w  w  w.  j a  va 2  s .  c o m
public AssignmentSubmission newSubmission(String assignmentId, Optional<String> groupId,
        Optional<Set<AssignmentSubmissionSubmitter>> submitters, Optional<Set<String>> feedbackAttachments,
        Optional<Set<String>> submittedAttachments, Optional<Map<String, String>> properties) {
    Assignment assignment = findAssignment(assignmentId);
    if (assignment != null) {
        Session session = sessionFactory.getCurrentSession();
        // Since this transaction is going to add a submission to the assignment we lock the assignment
        // the lock is freed once transaction is committed or rolled back
        session.buildLockRequest(LockOptions.UPGRADE).setLockMode(LockMode.PESSIMISTIC_WRITE).lock(assignment);

        AssignmentSubmission submission = new AssignmentSubmission();
        submission.setDateCreated(Instant.now());
        submitters.ifPresent(submission::setSubmitters);
        submitters.ifPresent(s -> s.forEach(submitter -> submitter.setSubmission(submission)));
        feedbackAttachments.ifPresent(submission::setFeedbackAttachments);
        submittedAttachments.ifPresent(submission::setAttachments);
        properties.ifPresent(submission::setProperties);
        if (assignment.getIsGroup()) {
            groupId.ifPresent(submission::setGroupId);
        }

        submission.setAssignment(assignment);
        assignment.getSubmissions().add(submission);

        session.persist(assignment);
        return submission;
    }
    return null;
}

From source file:org.web4thejob.orm.DataWriterServiceImpl.java

License:Open Source License

public <E extends Entity> void delete(E entity) {
    sessionFactory.getCurrentSession().buildLockRequest(LockOptions.UPGRADE).lock(entity);
    sessionFactory.getCurrentSession().refresh(entity);
    sessionFactory.getCurrentSession().delete(entity);
}