Example usage for org.hibernate LockMode UPGRADE

List of usage examples for org.hibernate LockMode UPGRADE

Introduction

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

Prototype

LockMode UPGRADE

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

Click Source Link

Document

An upgrade lock.

Usage

From source file:at.ac.tuwien.ifs.tita.dao.GenericHibernateDao.java

License:Apache License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
    T entity;/*from   w  ww .  j av  a 2s  .  co  m*/
    try {
        if (lock) {
            entity = (T) getSession().load(this.persistenceClass, id, LockMode.UPGRADE);
        } else {
            entity = (T) getSession().load(this.persistenceClass, id);
        }
    } catch (Exception e) {
        throw new PersistenceException("Failure during reading entity. Class="
                + this.persistenceClass.getSimpleName() + "\n" + e.getMessage(), e);
    }

    return entity;
}

From source file:br.gov.jfrj.siga.model.dao.ModeloDao.java

License:Open Source License

@SuppressWarnings({ "unchecked", "deprecation" })
public <T> T consultar(final Serializable id, Class<T> clazz, final boolean lock) {

    if (id == null) {
        log.warn("[aConsultar] - O ID recebido para efetuar a consulta  nulo. ID: " + id);
        throw new IllegalArgumentException("O identificador do objeto  nulo ou invlido.");
    }/* w  w w .j a  va2  s . c om*/
    T entidade;
    if (lock)
        entidade = (T) getSessao().load(clazz, id, LockMode.UPGRADE);
    else
        entidade = (T) getSessao().load(clazz, id);

    return entidade;

}

From source file:com.amkaawaken.DAO.hibernate.GenericHibernateDAO.java

@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
    T entity;//w w w.  j  a  v a2s.c om
    if (lock) {
        entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
    } else {
        entity = (T) getSession().load(getPersistentClass(), id);
    }

    return entity;
}

From source file:com.cloud.bridge.service.core.s3.S3Engine.java

License:Open Source License

/**
 * If acl is set then the cannedAccessPolicy parameter should be null and is ignored.   
 * The cannedAccessPolicy parameter is for REST Put requests only where a simple set of ACLs can be
 * created with a single header value.  Note that we do not currently support "anonymous" un-authenticated 
 * access in our implementation./*from   www  .  java2  s. c o  m*/
 * 
 * @throws IOException 
 */
@SuppressWarnings("deprecation")
public OrderedPair<SObject, SObjectItem> allocObjectItem(SBucket bucket, String nameKey, S3MetaDataEntry[] meta,
        S3AccessControlList acl, String cannedAccessPolicy) {
    SObjectDao objectDao = new SObjectDao();
    SObjectItemDao objectItemDao = new SObjectItemDao();
    SMetaDao metaDao = new SMetaDao();
    SAclDao aclDao = new SAclDao();
    SObjectItem item = null;
    int versionSeq = 1;
    int versioningStatus = bucket.getVersioningStatus();

    Session session = PersistContext.getSession();

    // [A] To write into a bucket the user must have write permission to that bucket
    S3PolicyContext context = new S3PolicyContext(PolicyActions.PutObject, bucket.getName());
    context.setKeyName(nameKey);
    context.setEvalParam(ConditionKeys.Acl, cannedAccessPolicy);

    verifyAccess(context, "SBucket", bucket.getId(), SAcl.PERMISSION_WRITE); // TODO - check this validates plain POSTs

    // [B] If versioning is off them we over write a null object item
    SObject object = objectDao.getByNameKey(bucket, nameKey);
    if (object != null) {
        // -> if versioning is on create new object items
        if (SBucket.VERSIONING_ENABLED == versioningStatus) {
            session.lock(object, LockMode.UPGRADE);
            versionSeq = object.getNextSequence();
            object.setNextSequence(versionSeq + 1);
            session.save(object);

            item = new SObjectItem();
            item.setTheObject(object);
            object.getItems().add(item);
            item.setVersion(String.valueOf(versionSeq));
            Date ts = DateHelper.currentGMTTime();
            item.setCreateTime(ts);
            item.setLastAccessTime(ts);
            item.setLastModifiedTime(ts);
            session.save(item);
        } else { // -> find an object item with a null version, can be null
                 //    if bucket started out with versioning enabled and was then suspended
            item = objectItemDao.getByObjectIdNullVersion(object.getId());
            if (item == null) {
                item = new SObjectItem();
                item.setTheObject(object);
                object.getItems().add(item);
                Date ts = DateHelper.currentGMTTime();
                item.setCreateTime(ts);
                item.setLastAccessTime(ts);
                item.setLastModifiedTime(ts);
                session.save(item);
            }
        }
    } else { // -> there is no object nor an object item
        object = new SObject();
        object.setBucket(bucket);
        object.setNameKey(nameKey);
        object.setNextSequence(2);
        object.setCreateTime(DateHelper.currentGMTTime());
        object.setOwnerCanonicalId(UserContext.current().getCanonicalUserId());
        session.save(object);

        item = new SObjectItem();
        item.setTheObject(object);
        object.getItems().add(item);
        if (SBucket.VERSIONING_ENABLED == versioningStatus)
            item.setVersion(String.valueOf(versionSeq));
        Date ts = DateHelper.currentGMTTime();
        item.setCreateTime(ts);
        item.setLastAccessTime(ts);
        item.setLastModifiedTime(ts);
        session.save(item);
    }

    // [C] We will use the item DB id as the file name, MD5/contentLength will be stored later
    String suffix = null;
    int dotPos = nameKey.lastIndexOf('.');
    if (dotPos >= 0)
        suffix = nameKey.substring(dotPos);
    if (suffix != null)
        item.setStoredPath(String.valueOf(item.getId()) + suffix);
    else
        item.setStoredPath(String.valueOf(item.getId()));

    metaDao.save("SObjectItem", item.getId(), meta);

    // [D] Are we setting an ACL along with the object
    //  -> the ACL is ALWAYS set on a particular instance of the object (i.e., a version)
    if (null != cannedAccessPolicy) {
        setCannedAccessControls(cannedAccessPolicy, "SObjectItem", item.getId(), bucket);
    } else if (null == acl || 0 == acl.size()) {
        // -> this is termed the "private" or default ACL, "Owner gets FULL_CONTROL"
        setSingleAcl("SObjectItem", item.getId(), SAcl.PERMISSION_FULL);
    } else if (null != acl) {
        aclDao.save("SObjectItem", item.getId(), acl);
    }

    session.update(item);
    return new OrderedPair<SObject, SObjectItem>(object, item);
}

From source file:com.esoft.yeepay.user.service.impl.YeePayCorpAccountOperation.java

@Override
@Transactional(rollbackFor = Exception.class, noRollbackFor = TrusteeshipReturnException.class)
public void receiveOperationPostCallback(ServletRequest request) throws TrusteeshipReturnException {
    try {/*from w ww  .j  a  v  a  2  s. c  o  m*/
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    // ?? xml?
    String respXML = request.getParameter("resp");
    log.debug(respXML.toString());
    // ??
    String sign = request.getParameter("sign");
    boolean flag = CFCASignUtil.isVerifySign(respXML, sign);
    if (flag) {
        // ??
        @SuppressWarnings("unchecked")
        Map<String, String> resultMap = Dom4jUtil.xmltoMap(respXML);
        // ?? userId
        String requestNo = resultMap.get("requestNo").substring(resultMap.get("requestNo").indexOf("a") + 1);
        // ?
        String code = resultMap.get("code");
        String description = resultMap.get("description");
        TrusteeshipOperation to = trusteeshipOperationBO.get(YeePayConstants.OperationType.ENTERPRISE_REGISTER,
                requestNo, requestNo, "yeepay");
        ht.evict(to);
        to = ht.get(TrusteeshipOperation.class, to.getId(), LockMode.UPGRADE);

        to.setResponseTime(new Date());
        to.setResponseData(respXML);
        // ? ????
        User user = ht.get(User.class, requestNo);
        if ("1".equals(code)) {
            if (user != null) {
                TrusteeshipAccount ta = ht.get(TrusteeshipAccount.class, user.getId());
                if (ta == null) {
                    ta = new TrusteeshipAccount();
                    ta.setId(user.getId());
                    ta.setUser(user);
                }
                ta.setAccountId(user.getId());
                ta.setCreateTime(new Date());
                ta.setStatus(TrusteeshipConstants.Status.PASSED);
                ta.setTrusteeship("yeepay");
                ht.saveOrUpdate(ta);
                userBO.removeRole(user, new Role("WAIT_CONFIRM"));
                userBO.addRole(user, new Role("LOANER"));
                // ??
                springSecurityService.refreshLoginUserAuthorities(user.getId());
                to.setStatus(TrusteeshipConstants.Status.PASSED);
                ht.merge(to);
            }
        } else {
            to.setStatus(TrusteeshipConstants.Status.REFUSED);
            ht.merge(to);
            userBO.removeRole(user, new Role("WAIT_CONFIRM"));
            // ??
            springSecurityService.refreshLoginUserAuthorities(user.getId());
            if ("0".equals(code)) {
                throw new TrusteeshipReturnException(description);
            }
            // 
            throw new TrusteeshipReturnException(code + ":" + description);
        }
    }

}

From source file:com.esoft.yeepay.user.service.impl.YeePayCorpAccountOperation.java

@Override
@Transactional(rollbackFor = Exception.class)
public void receiveOperationS2SCallback(ServletRequest request, ServletResponse response) {

    try {//from   w  ww  . j av  a  2 s . co m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    // ?? xml?
    String notifyxml = request.getParameter("notify");
    // ??
    String sign = request.getParameter("sign");
    boolean flag = CFCASignUtil.isVerifySign(notifyxml, sign);
    if (flag) {
        // ??
        @SuppressWarnings("unchecked")
        Map<String, String> resultMap = Dom4jUtil.xmltoMap(notifyxml);
        String code = resultMap.get("code");
        String message = resultMap.get("message");
        String platformUserNo = resultMap.get("platformUserNo");
        TrusteeshipOperation to = trusteeshipOperationBO.get(YeePayConstants.OperationType.ENTERPRISE_REGISTER,
                platformUserNo, platformUserNo, "yeepay");
        ht.evict(to);
        to = ht.get(TrusteeshipOperation.class, to.getId(), LockMode.UPGRADE);
        to.setResponseTime(new Date());
        to.setResponseData(notifyxml);

        User user = ht.get(User.class, platformUserNo);
        log.info("code:" + code);
        if ("1".equals(code)) {
            if (user != null) {
                TrusteeshipAccount ta = ht.get(TrusteeshipAccount.class, user.getId());
                if (ta == null) {
                    ta = new TrusteeshipAccount();
                    ta.setId(user.getId());
                    ta.setUser(user);
                }
                ta.setAccountId(user.getId());
                ta.setCreateTime(new Date());
                ta.setStatus(TrusteeshipConstants.Status.PASSED);
                ta.setTrusteeship("yeepay");
                ht.saveOrUpdate(ta);
                userBO.removeRole(user, new Role("WAIT_CONFIRM"));
                userBO.addRole(user, new Role("LOANER"));
                // ??
                springSecurityService.refreshLoginUserAuthorities(user.getId());
                to.setStatus(TrusteeshipConstants.Status.PASSED);
                ht.merge(to);
            }
        } else if ("0".equals(code) || "104".equals(code)) {
            to.setStatus(TrusteeshipConstants.Status.REFUSED);
            ht.merge(to);
            userBO.removeRole(user, new Role("WAIT_CONFIRM"));
            // ??
            springSecurityService.refreshLoginUserAuthorities(user.getId());
        } else {
            // 
            throw new RuntimeException(new TrusteeshipReturnException(code + ":" + message));
        }
    }

    try {
        response.getWriter().write("SUCCESS");
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

}

From source file:com.farmafene.commons.hibernate.generators.WorkInOther.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w  w  .  j a  va  2s . c  o  m
 * 
 * @since 1.0.0
 */
private String getSelectQuery(Dialect dialect) {
    StringBuilder sb = new StringBuilder("SELECT ")
            .append(campos.getTarget().getAnnotation(Column.class).name());
    sb.append(" FROM ");
    sb.append(dialect.appendLockHint(LockMode.UPGRADE, db.getNombreSecuencia()));
    writeWhereParameters(null, sb, campos.getLista());
    sb.append(dialect.getForUpdateString());
    return sb.toString();
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query.//from   w ww  . ja  va  2 s . c  o m
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.huateng.ebank.entity.dao.mng.SeqctlDAO.java

/**
 * ?Hibernate ID//  w  w  w . j a v  a2s  .  co  m
 *
 * @param id
 * @return Seqctl
 * @throws CommonException
 */
public Seqctl query(long id) throws CommonException {
    try {
        return (Seqctl) this.getHibernateTemplate().load(Seqctl.class, new Long(id), LockMode.UPGRADE);
    } catch (Exception e) {
        ExceptionUtil.throwCommonException(e.getMessage(), ErrorCode.ERROR_CODE_SEQCTL_SELECT, e);
    }
    return null;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

public void lockPath(RepoFolder folder) {
    validateResourceUriLength(folder.getURI().length());
    if (!isLockFoldersOnPathChange()) {
        return;/*from   w w w. j  a  v  a 2 s .  c  om*/
    }

    HibernateTemplate template = getHibernateTemplate();
    RepoFolder parent = folder.getParent();
    if (parent != null && !parent.isNew()) {
        lockReadFolder(parent);
    }

    if (!folder.isNew()) {
        //lock the folder to indicate that its path has changed
        template.lock(folder, LockMode.UPGRADE);
    }
}