Returns a read lock for the entity type, entity key and owner.

@return org.apereo.portal.concurrency.locking.IEntityLock
@param entityType Class
@param entityKey String
@param owner String
@exception LockingException
354128
public IEntityLock newReadLock(Class entityType, String entityKey, String owner)
            throws LockingException {
        return lockService.newLock(entityType, entityKey, IEntityLockService.READ_LOCK, owner);
    }
374864
public function acquireLock($entityId, $lockType, $expirationSeconds = null, $retryTimeoutSeconds = null)
        {
            /* Sanitize */
            
            if (is_null($expirationSeconds)) {
                $expirationSeconds = (int)config('locking.expiration_seconds', 30);
            }
            
            if (is_null($retryTimeoutSeconds)) {
                $retryTimeoutSeconds = (int)config('locking.retry_timeout_seconds', 10);
            }
            
            /* Initialize */

            $lock = null;

            if (is_null(Auth::user())) {
                throw new LockTimeoutException();
            }
            $userId = Auth::user()->id;

            /* Attempt to acquire the desired lock */

            $timestampEnd = time() + $retryTimeoutSeconds;
            while (is_null($lock) && time() <= $timestampEnd) {
                /* Determine whether a more important lock is set on the requested entity */

                $needToSleep = false;

                switch ($lockType) {
                    case $this::READ_LOCK:
                        if ($this->isWriteLocked($entityId)) {
                            $needToSleep = true;
                        }

                        break;

                    case $this::WRITE_LOCK:
                        /* We need to check all active locks for this entity */

                        $locks = $this->getLocks($entityId);
                        $activeLockCount = $this->getLocks($entityId)->filter(function ($lock, $key) use ($userId) {
                            // (new Dumper())->dump($lock);
                            return Locking::WRITE_LOCK == $lock->lock_type || $lock->user_id != $userId;
                        })->count();

                        $needToSleep = (0 != $activeLockCount);

                        break;
                }

                if ($needToSleep) {
                    usleep(500000);
                    continue;
                }

                $lock = Lock::create([
                    'user_id'    => Auth::user()->id,
                    'entity_id'  => $entityId,
                    'lock_type'  => $lockType,
                    'expires_at' => Carbon::now()->addSeconds($expirationSeconds),
                ]);
            }

            if (is_null($lock)) {
                throw new LockTimeoutException();
            }

            /* Return lock */

            return $lock->id;
        }
346296
public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
    {
        // Check identity map first
        if ($entity = $this->xem->getUnitOfWork()->tryGetById($id, $this->class->rootXmlEntityName)) {
            if ($lockMode != LockMode::NONE) {
                $this->xem->lock($entity, $lockMode, $lockVersion);
            }

            return $entity; // Hit!
        }

        if ($lockMode == LockMode::NONE) {
            return $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id);
        } else if ($lockMode == LockMode::OPTIMISTIC) {
            if (!$this->class->isVersioned) {
                throw OptimisticLockException::notVersioned($this->entityName);
            }
            $entity = $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id);

            $this->xem->getUnitOfWork()->lock($entity, $lockMode, $lockVersion);

            return $entity;
        } else {
            if (!$this->xem->getConnection()->isTransactionActive()) {
                throw TransactionRequiredException::transactionRequired();
            }

            return $this->xem->getUnitOfWork()->getXmlEntityPersister($this->entityName)->load($id, null, null, array(), $lockMode);
        }
    }
831742
public boolean acquire(final Lock lock) {
        lock.setUniqueId(this.uniqueId);
        if (this.lockTimeout > 0) {
            lock.setExpirationDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.lockTimeout));
        } else {
            lock.setExpirationDate(null);
        }
        var success = false;
        try {
            if (lock.getApplicationId() != null) {
                this.entityManager.merge(lock);
            } else {
                lock.setApplicationId(this.applicationId);
                this.entityManager.persist(lock);
            }
            success = true;
        } catch (final Exception e) {
            success = false;
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId, e);
            } else {
                LOGGER.info("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId);
            }
        }
        return success;
    }
327990
private void instanceAlreadyLoaded(
		final Tuple resultset,
		final int i,
			//TODO create an interface for this usage
		final OgmEntityPersister persister,
		final org.hibernate.engine.spi.EntityKey key,
		final Object object,
		final LockMode lockMode,
		final SharedSessionContractImplementor session)
	throws HibernateException {
		if ( !persister.isInstance( object ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + object.getClass(),
					key.getIdentifier(),
					persister.getEntityName()
				);
		}

		if ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested

			final boolean isVersionCheckNeeded = persister.isVersioned() &&
					session.getPersistenceContext().getEntry( object )
							.getLockMode().lessThan( lockMode );
			// we don't need to worry about existing version being uninitialized
			// because this block isn't called by a re-entrant load (re-entrant
			// loads _always_ have lock mode NONE)
			if ( isVersionCheckNeeded ) {
				//we only check the version when _upgrading_ lock modes
				Object oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();
				persister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );
				//we need to upgrade the lock mode to the mode requested
				session.getPersistenceContext().getEntry( object )
						.setLockMode( lockMode );
			}
		}
	}
1316745
@Override
    public void convert(IEntityLock lock, int newType, int newDuration) throws LockingException {
        if (lock.getLockType() == newType) {
            throw new LockingException(
                    "Could not convert " + lock + " : old and new lock TYPEs are the same.");
        }

        if (!isValidLockType(newType)) {
            throw new LockingException(
                    "Could not convert " + lock + " : lock TYPE " + newType + " is invalid.");
        }

        if (!isValid(lock)) {
            throw new LockingException("Could not convert " + lock + " : lock is invalid.");
        }

        if (newType == WRITE_LOCK
                && retrieveLocks(lock.getEntityType(), lock.getEntityKey(), null).length > 1) {
            throw new LockingException(
                    "Could not convert " + lock + " : another lock already exists.");
        }

        if (newType == READ_LOCK) {
            /* Can always convert to READ */
        }

        Date newExpiration = getNewExpiration(newDuration);
        getLockStore().update(lock, newExpiration, newType);
        ((EntityLockImpl) lock).setLockType(newType);
        ((EntityLockImpl) lock).setExpirationTime(newExpiration);
    }
997889
@Override
    public void lock(Object entity, LockModeType lockMode)
    {
        ivEm.lock(entity, lockMode);
    }
1034781
@Override
    public IEntity getEntity(String key, Class type) throws GroupsException {
        IEntity ent = primGetEntity(key, type);

        if (cacheInUse()) {
            try {
                IEntity cachedEnt = getEntityFromCache(ent.getEntityIdentifier().getKey());
                if (cachedEnt == null) {
                    cacheAdd(ent);
                } else {
                    ent = cachedEnt;
                }
            } catch (CachingException ce) {
                throw new GroupsException(
                        "Problem retrieving group member " + type + "(" + key + ")", ce);
            }
        }
        return ent;
    }
677556
@Override
    public ILockableEntityGroup findGroupWithLock(String key, String lockOwner)
            throws GroupsException {
        CompositeEntityIdentifier ent = newCompositeEntityIdentifier(key);
        IIndividualGroupService service = getComponentService(ent);
        return (service == null) ? null : service.findGroupWithLock(ent.getLocalKey(), lockOwner);
    }
464456
public function isEntityLocked(User $user, LockableEntityInterface $entity)
    {
        /** @var LockableEntity $lockable */
        $lockable = $this->getLockableEntity($entity);

        if ($this->lockEnabled) {
            $this->removeExpiredLocks($lockable);
            $locks = $this->getEntityVersionLocksByLockableEntity($lockable, $user);

            if ($locks === null || !count($locks)) {
                $this->createEntityVersionLock($user, $lockable);

                $lockable->setUpdated(new \DateTime());
                $this->objectManager->flush();

                return false;
            }

            return true;
        }

        return false;
    }
506504
@SuppressWarnings("unchecked")
  protected <E> E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) {
    Transaction transaction = null;
    try {
      entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity);
      Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE);
      transaction = datastore.newTransaction();
      Entity storedNativeEntity = transaction.get(nativeEntity.getKey());
      if (storedNativeEntity == null) {
        throw new OptimisticLockException(
            String.format("Entity does not exist: %s", nativeEntity.getKey()));
      }
      String versionPropertyName = versionMetadata.getMappedName();
      long version = nativeEntity.getLong(versionPropertyName) - 1;
      long storedVersion = storedNativeEntity.getLong(versionPropertyName);
      if (version != storedVersion) {
        throw new OptimisticLockException(
            String.format("Expecting version %d, but found %d", version, storedVersion));
      }
      transaction.update(nativeEntity);
      transaction.commit();
      E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass());
      entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
      return updatedEntity;
    } catch (DatastoreException exp) {
      throw DatastoreUtils.wrap(exp);
    } finally {
      rollbackIfActive(transaction);
    }
  }
555060
public function getOrCreate($id, $class)
    {
        /** @var LockableEntity $lockable */
        $lockable = $this->findOneBy(['entityId' => $id, 'entityClass' => $class]);

        if ($lockable === null) {
            $lockable = new LockableEntity();
            $lockable->setEntityClass($class);
            $lockable->setEntityId($id);
        }

        return $lockable;
    }
460222
public function lock($entity, $lockMode, $lockVersion = null)
    {
        if ($entity === null) {
            throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().');
        }

        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
            throw ORMInvalidArgumentException::entityNotManaged($entity);
        }

        $class = $this->em->getClassMetadata(get_class($entity));

        switch (true) {
            case $lockMode === LockMode::OPTIMISTIC:
                if (! $class->isVersioned()) {
                    throw OptimisticLockException::notVersioned($class->getClassName());
                }

                if ($lockVersion === null) {
                    return;
                }

                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
                    $entity->initializeProxy();
                }

                $entityVersion = $class->versionProperty->getValue($entity);

                if ($entityVersion !== $lockVersion) {
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
                }

                break;

            case $lockMode === LockMode::NONE:
            case $lockMode === LockMode::PESSIMISTIC_READ:
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
                if (! $this->em->getConnection()->isTransactionActive()) {
                    throw TransactionRequiredException::transactionRequired();
                }

                $oid = spl_object_id($entity);

                $this->getEntityPersister($class->getClassName())->lock(
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
                    $lockMode
                );
                break;

            default:
                // Do nothing
        }
    }
89772
private CmsClientLock generateClientLock(CmsResource resource) throws CmsException {

        CmsObject cms = getCmsObject();
        CmsLock lock = cms.getLock(resource);
        CmsClientLock clientLock = new CmsClientLock();
        clientLock.setLockType(CmsClientLock.LockType.valueOf(lock.getType().getMode()));
        CmsUUID ownerId = lock.getUserId();
        if (!lock.isUnlocked() && (ownerId != null)) {
            clientLock.setLockOwner(cms.readUser(ownerId).getDisplayName(cms, cms.getRequestContext().getLocale()));
            clientLock.setOwnedByUser(cms.getRequestContext().getCurrentUser().getId().equals(ownerId));
        }
        return clientLock;
    }
540772
EntityType getEntityTypeBypassingRegistry(String entityTypeId) {
    return entityTypeId != null
        ? dataService.findOneById(
            ENTITY_TYPE_META_DATA, entityTypeId, getEntityTypeFetch(), EntityType.class)
        : null;
  }
810014
private ILockableEntityGroup lockableInstanceFromResultSet(ResultSet rs)
            throws SQLException, GroupsException {
        ILockableEntityGroup eg = null;

        String key = rs.getString(1);
        String creatorID = rs.getString(2);
        Integer entityTypeID = rs.getInt(3);
        Class entityType = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(entityTypeID);
        String groupName = rs.getString(4);
        String description = rs.getString(5);

        if (key != null) {
            eg = newLockableInstance(key, entityType, creatorID, groupName, description);
        }

        return eg;
    }
65581
private <T extends IEntity> Object verifyEntityId(T entity) throws FMSException {
        Class<?> objectClass = entity.getClass();
        Object rid = null;
        Method m;

        try {
            m = objectClass.getMethod("getId");
            rid = m.invoke(entity);
        } catch (Exception e) {
            throw new FMSException("Unable to read the method getId", e);
        }

        if (rid == null) {
            throw new FMSException("Id is required.");
        }
        return rid;
    }