Java Code Examples for javax.persistence.TypedQuery#setLockMode()

The following examples show how to use javax.persistence.TypedQuery#setLockMode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityGroupManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Transactional
private List<SecurityGroupFailureHostVO> takeFailureHosts() {
    String sql = "select sgf from SecurityGroupFailureHostVO sgf, HostVO host where host.uuid = sgf.hostUuid and host.status = :hostConnectionState and sgf.managementNodeId is NULL group by sgf.hostUuid order by sgf.lastOpDate ASC";
    TypedQuery<SecurityGroupFailureHostVO> q = dbf.getEntityManager().createQuery(sql, SecurityGroupFailureHostVO.class);
    q.setLockMode(LockModeType.PESSIMISTIC_READ);
    q.setParameter("hostConnectionState", HostStatus.Connected);
    q.setMaxResults(failureHostEachTimeTake);
    List<SecurityGroupFailureHostVO> lst = q.getResultList();
    if (lst.isEmpty()) {
        return lst;
    }

    List<Long> ids = CollectionUtils.transformToList(lst, new Function<Long, SecurityGroupFailureHostVO>() {
        @Override
        public Long call(SecurityGroupFailureHostVO arg) {
            return arg.getId();
        }
    });

    sql = "update SecurityGroupFailureHostVO f set f.managementNodeId = :mgmtId where f.id in (:ids)";
    Query uq = dbf.getEntityManager().createQuery(sql);
    uq.setParameter("mgmtId", Platform.getManagementServerId());
    uq.setParameter("ids", ids);
    uq.executeUpdate();
    return lst;
}
 
Example 2
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private UserConsentEntity getGrantedConsentEntity(String userId, String clientId, LockModeType lockMode) {
    StorageId clientStorageId = new StorageId(clientId);
    String queryName = clientStorageId.isLocal() ?  "userConsentByUserAndClient" : "userConsentByUserAndExternalClient";
    TypedQuery<UserConsentEntity> query = em.createNamedQuery(queryName, UserConsentEntity.class);
    query.setParameter("userId", userId);
    if (clientStorageId.isLocal()) {
        query.setParameter("clientId", clientId);
    } else {
        query.setParameter("clientStorageProvider", clientStorageId.getProviderId());
        query.setParameter("externalClientId", clientStorageId.getExternalId());
    }
    query.setLockMode(lockMode);
    List<UserConsentEntity> results = query.getResultList();
    if (results.size() > 1) {
        throw new ModelException("More results found for user [" + userId + "] and client [" + clientId + "]");
    } else if (results.size() == 1) {
        return results.get(0);
    } else {
        return null;
    }

}
 
Example 3
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private FederatedUserConsentEntity getGrantedConsentEntity(String userId, String clientId, LockModeType lockMode) {
    StorageId clientStorageId = new StorageId(clientId);
    String queryName = clientStorageId.isLocal() ?  "userFederatedConsentByUserAndClient" : "userFederatedConsentByUserAndExternalClient";
    TypedQuery<FederatedUserConsentEntity> query = em.createNamedQuery(queryName, FederatedUserConsentEntity.class);
    query.setLockMode(lockMode);
    query.setParameter("userId", userId);
    if (clientStorageId.isLocal()) {
        query.setParameter("clientId", clientId);
    } else {
        query.setParameter("clientStorageProvider", clientStorageId.getProviderId());
        query.setParameter("externalClientId", clientStorageId.getExternalId());
    }
    List<FederatedUserConsentEntity> results = query.getResultList();
    if (results.size() > 1) {
        throw new ModelException("More results found for user [" + userId + "] and client [" + clientId + "]");
    } else if (results.size() == 1) {
        return results.get(0);
    } else {
        return null;
    }
}
 
Example 4
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void leaveGroup(RealmModel realm, String userId, GroupModel group) {
    if (userId == null || group == null) return;

    TypedQuery<FederatedUserGroupMembershipEntity> query1 = em.createNamedQuery("feduserMemberOf", FederatedUserGroupMembershipEntity.class);
    query1.setParameter("userId", userId);
    query1.setParameter("groupId", group.getId());
    TypedQuery<FederatedUserGroupMembershipEntity> query = query1;
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<FederatedUserGroupMembershipEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (FederatedUserGroupMembershipEntity entity : results) {
        em.remove(entity);
    }
    em.flush();

}
 
Example 5
Source File: LocalStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional
protected void returnStorageCapacityToHost(String hostUuid, long size) {
    String sql = "select ref from LocalStorageHostRefVO ref where ref.hostUuid = :huuid and ref.primaryStorageUuid = :primaryStorageUuid";
    TypedQuery<LocalStorageHostRefVO> q = dbf.getEntityManager().createQuery(sql, LocalStorageHostRefVO.class);
    q.setParameter("huuid", hostUuid);
    q.setParameter("primaryStorageUuid", self.getUuid());
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<LocalStorageHostRefVO> refs = q.getResultList();

    if (refs.isEmpty()) {
        throw new CloudRuntimeException(String.format("cannot find host[uuid: %s] of local primary storage[uuid: %s]",
                hostUuid, self.getUuid()));
    }

    LocalStorageHostRefVO ref = refs.get(0);

    LocalStorageHostCapacityStruct s = new LocalStorageHostCapacityStruct();
    s.setSizeBeforeOverProvisioning(size);
    s.setHostUuid(hostUuid);
    s.setLocalStorage(getSelfInventory());
    s.setSize(size);

    for (LocalStorageReturnHostCapacityExtensionPoint ext : pluginRgty.getExtensionList(
            LocalStorageReturnHostCapacityExtensionPoint.class)) {
        ext.beforeReturnLocalStorageCapacityOnHost(s);
    }

    ref.setAvailableCapacity(ref.getAvailableCapacity() + s.getSize());
    dbf.getEntityManager().merge(ref);
}
 
Example 6
Source File: ImageCacheGarbageCollector.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional
private List<ImageCacheVO> getImageCacheToDelete() {
    String sql = "select i from ImageCacheVO i where i.imageUuid = NULL and i.state = :state";
    TypedQuery<ImageCacheVO> q = dbf.getEntityManager().createQuery(sql, ImageCacheVO.class);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    q.setParameter("state", ImageCacheState.ready);
    List<ImageCacheVO> ret = q.getResultList();
    
    // if ImageCacheVO in deleting state and it has been stayed for 1 day
    // that means zstack that issued garbage collection exited before removing this entry from database
    // we garbage this entry again here
    sql = "select i from ImageCacheVO i where i.imageUuid = NULL and i.state = :state and CURRENT_TIMESTAMP > DATE_ADD(i.lastOpDate, INTERVAL 1 DAY)";
    Query q1 = dbf.getEntityManager().createNativeQuery(sql, ImageCacheVO.class);
    q1.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    q1.setParameter("state", ImageCacheState.deleting);
    ret.addAll(q1.getResultList());
    if (ret.isEmpty()) {
        return ret;
    }
    
    List<Long> ids = new ArrayList<Long>(ret.size());
    for (ImageCacheVO i : ret) {
        ids.add(i.getId());
    }
    sql = "update ImageCacheVO i set i.state = :state where i.id in (:ids)";
    TypedQuery<ImageCacheVO> q2 = dbf.getEntityManager().createQuery(sql, ImageCacheVO.class);
    q2.setParameter("state", ImageCacheState.deleting);
    q2.setParameter("ids", ids);
    q2.executeUpdate();
    return ret;
}
 
Example 7
Source File: GroupAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteRoleMapping(RoleModel role) {
    if (group == null || role == null) return;

    TypedQuery<GroupRoleMappingEntity> query = getGroupRoleMappingEntityTypedQuery(role);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<GroupRoleMappingEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (GroupRoleMappingEntity entity : results) {
        em.remove(entity);
    }
    em.flush();
}
 
Example 8
Source File: ClientScopeAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteScopeMapping(RoleModel role) {
    TypedQuery<ClientScopeRoleMappingEntity> query = getRealmScopeMappingQuery(role);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<ClientScopeRoleMappingEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (ClientScopeRoleMappingEntity entity : results) {
        em.remove(entity);
    }
}
 
Example 9
Source File: UserAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void leaveGroup(GroupModel group) {
    if (user == null || group == null) return;

    TypedQuery<UserGroupMembershipEntity> query = getUserGroupMappingQuery(group);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<UserGroupMembershipEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (UserGroupMembershipEntity entity : results) {
        em.remove(entity);
    }
    em.flush();

}
 
Example 10
Source File: UserAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteRoleMapping(RoleModel role) {
    if (user == null || role == null) return;

    TypedQuery<UserRoleMappingEntity> query = getUserRoleMappingEntityTypedQuery(role);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<UserRoleMappingEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (UserRoleMappingEntity entity : results) {
        em.remove(entity);
    }
    em.flush();
}
 
Example 11
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private FederatedIdentityEntity findFederatedIdentity(UserModel user, String identityProvider, LockModeType lockMode) {
    TypedQuery<FederatedIdentityEntity> query = em.createNamedQuery("findFederatedIdentityByUserAndProvider", FederatedIdentityEntity.class);
    UserEntity userEntity = em.getReference(UserEntity.class, user.getId());
    query.setParameter("user", userEntity);
    query.setParameter("identityProvider", identityProvider);
    query.setLockMode(lockMode);
    List<FederatedIdentityEntity> results = query.getResultList();
    return results.size() > 0 ? results.get(0) : null;
}
 
Example 12
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<FederatedUserRequiredActionEntity> getRequiredActionEntities(RealmModel realm, String userId, LockModeType lockMode) {
    TypedQuery<FederatedUserRequiredActionEntity> query = em.createNamedQuery("getFederatedUserRequiredActionsByUser", FederatedUserRequiredActionEntity.class)
            .setParameter("userId", userId)
            .setParameter("realmId", realm.getId());
    query.setLockMode(lockMode);
    return query.getResultList();
}
 
Example 13
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteRoleMapping(RealmModel realm, String userId, RoleModel role) {
    TypedQuery<FederatedUserRoleMappingEntity> query = em.createNamedQuery("feduserRoleMappings", FederatedUserRoleMappingEntity.class);
    query.setParameter("userId", userId);
    List<FederatedUserRoleMappingEntity> results = query.getResultList();
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    for (FederatedUserRoleMappingEntity entity : results) {
        if (entity.getRoleId().equals(role.getId())) em.remove(entity);

    }
    em.flush();
}
 
Example 14
Source File: LocalStorageBase.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional
protected void reserveCapacityOnHost(String hostUuid, long size, String psUuid, boolean ignoreError) {
    String sql = "select ref" +
            " from LocalStorageHostRefVO ref" +
            " where ref.hostUuid = :huuid" +
            " and ref.primaryStorageUuid = :psUuid";
    TypedQuery<LocalStorageHostRefVO> q = dbf.getEntityManager().createQuery(sql, LocalStorageHostRefVO.class);
    q.setParameter("huuid", hostUuid);
    q.setParameter("psUuid", psUuid);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<LocalStorageHostRefVO> refs = q.getResultList();

    if (refs.isEmpty()) {
        String errInfo = String.format("cannot find host[uuid: %s] of local primary storage[uuid: %s]",
                hostUuid, self.getUuid());
        if (ignoreError) {
            logger.error(errInfo);
            return;
        } else {
            throw new CloudRuntimeException(errInfo);
        }
    }

    LocalStorageHostRefVO ref = refs.get(0);

    if (!ignoreError && !physicalCapacityMgr.checkCapacityByRatio(
            self.getUuid(),
            ref.getTotalPhysicalCapacity(),
            ref.getAvailablePhysicalCapacity())) {
        throw new OperationFailureException(operr("cannot reserve enough space for primary storage[uuid: %s] on host[uuid: %s], not enough physical capacity", self.getUuid(), hostUuid));
    }

    LocalStorageHostCapacityStruct s = new LocalStorageHostCapacityStruct();
    s.setLocalStorage(getSelfInventory());
    s.setHostUuid(ref.getHostUuid());
    s.setSizeBeforeOverProvisioning(size);
    s.setSize(size);

    for (LocalStorageReserveHostCapacityExtensionPoint ext : pluginRgty.getExtensionList(
            LocalStorageReserveHostCapacityExtensionPoint.class)) {
        ext.beforeReserveLocalStorageCapacityOnHost(s);
    }

    long avail = ref.getAvailableCapacity() - s.getSize();
    if (avail < 0) {
        if (ignoreError) {
            avail = 0;
        } else {
            throw new OperationFailureException(operr("host[uuid: %s] of local primary storage[uuid: %s] doesn't have enough capacity" +
                    "[current: %s bytes, needed: %s]", hostUuid, self.getUuid(), ref.getAvailableCapacity(), size));
        }

    }

    ref.setAvailableCapacity(avail);
    dbf.getEntityManager().merge(ref);
}
 
Example 15
Source File: LocalStorageBase.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional
protected void returnStorageCapacityToHostByResourceUuid(String resUuid) {
    String sql = "select href, rref" +
            " from LocalStorageHostRefVO href, LocalStorageResourceRefVO rref" +
            " where href.hostUuid = rref.hostUuid" +
            " and href.primaryStorageUuid = rref.primaryStorageUuid" +
            " and rref.resourceUuid = :resUuid" +
            " and rref.primaryStorageUuid = :puuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    q.setParameter("resUuid", resUuid);
    q.setParameter("puuid", self.getUuid());
    List<Tuple> tupleList = q.getResultList();
    if (tupleList == null || tupleList.isEmpty()) {
        return;
    }

    DebugUtils.Assert(tupleList.size() == 1,
            "should not get more than one LocalStorageHostRefVO/LocalStorageResourceRefVO");
    Tuple twoRefs = tupleList.get(0);
    LocalStorageHostRefVO href = twoRefs.get(0, LocalStorageHostRefVO.class);
    LocalStorageResourceRefVO rref = twoRefs.get(1, LocalStorageResourceRefVO.class);

    long requiredSize = rref.getSize();
    if (VolumeVO.class.getSimpleName().equals(rref.getResourceType())) {
        requiredSize = ratioMgr.calculateByRatio(self.getUuid(), requiredSize);
    }

    LocalStorageHostCapacityStruct s = new LocalStorageHostCapacityStruct();
    s.setSizeBeforeOverProvisioning(rref.getSize());
    s.setHostUuid(href.getHostUuid());
    s.setLocalStorage(getSelfInventory());
    s.setSize(requiredSize);
    for (LocalStorageReturnHostCapacityExtensionPoint ext : pluginRgty.getExtensionList(
            LocalStorageReturnHostCapacityExtensionPoint.class)) {
        ext.beforeReturnLocalStorageCapacityOnHost(s);
    }

    href.setAvailableCapacity(href.getAvailableCapacity() + s.getSize());
    dbf.getEntityManager().merge(href);
}
 
Example 16
Source File: SimpleBaseRepository.java    From es with Apache License 2.0 4 votes vote down vote up
private TypedQuery<M> applyLockMode(TypedQuery<M> query) {
    LockModeType type = lockMetadataProvider == null ? null : lockMetadataProvider.getLockModeType();
    return type == null ? query : query.setLockMode(type);
}