class UserNamespaceAuthorizationServiceImpl implements UserNamespaceAuthorizationService {

    @PublishNotificationMessages
    @NamespacePermission(fields = "#key?.namespace", permissions = NamespacePermissionEnum.GRANT)
    @Override
    public UserNamespaceAuthorization updateUserNamespaceAuthorization(UserNamespaceAuthorizationKey key, UserNamespaceAuthorizationUpdateRequest request)
    {
        // Validate and trim the key.
        validateUserNamespaceAuthorizationKey(key);

        // Validate and trim the request parameters.
        validateUserNamespaceAuthorizationUpdateRequest(request);

        // Retrieve and ensure that a user namespace authorization exists with the specified key.
        UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity = getUserNamespaceAuthorizationEntity(key);

        // Get the current user
        UserAuthorizations userAuthorizations = currentUserService.getCurrentUser();

        // If the current user id is equal to the user id in the namespace authorization key
        // and the user namespace authorization entity contains the grant permission
        if (userAuthorizations.getUserId().equalsIgnoreCase(key.getUserId()) && userNamespaceAuthorizationEntity.getGrantPermission())
        {
            // Assert that the request contains the grant namespace permission
            Assert.isTrue(request.getNamespacePermissions().contains(NamespacePermissionEnum.GRANT),
                "Users are not allowed to remove their own GRANT namespace permission." +
                    " Please include the GRANT namespace permission in this request, or have another user remove the GRANT permission.");
        }

        // Update the permissions.
        updateNamespacePermissions(userNamespaceAuthorizationEntity, request.getNamespacePermissions());
        userNamespaceAuthorizationDao.saveAndRefresh(userNamespaceAuthorizationEntity);

        // Create a user namespace authorization change notification to be sent on update user namespace authorization event.
        messageNotificationEventService.processUserNamespaceAuthorizationChangeNotificationEvent(key);

        // Create and return the user namespace authorization object from the updated entity.
        return createUserNamespaceAuthorizationFromEntity(userNamespaceAuthorizationEntity);
    }

}