@Override
  public AnonymousUser getAnonymousUser(HttpServletRequest request, long userId)
      throws PortalException, SystemException {

    long companyId = PortalUtil.getCompanyId(request);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(companyId);

    AnonymousUser anonymousUser = AnonymousUserLocalServiceUtil.fetchAnonymousUserByUserId(userId);

    if (anonymousUser == null) {
      anonymousUser = getAnonymousUserFromCookie(request);

      if ((anonymousUser == null)
          || ((anonymousUser.getUserId() != 0) && (anonymousUser.getUserId() != userId))) {

        anonymousUser =
            AnonymousUserLocalServiceUtil.addAnonymousUser(
                userId, request.getRemoteAddr(), null, serviceContext);
      } else {
        anonymousUser =
            AnonymousUserLocalServiceUtil.updateAnonymousUser(
                anonymousUser.getAnonymousUserId(),
                userId,
                request.getRemoteAddr(),
                anonymousUser.getTypeSettings(),
                serviceContext);
      }
    }

    return anonymousUser;
  }
  @Override
  public AnonymousUser getAnonymousUser(HttpServletRequest request, HttpServletResponse response)
      throws PortalException, SystemException {

    long companyId = PortalUtil.getCompanyId(request);
    long userId = PortalUtil.getUserId(request);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(companyId);

    AnonymousUser anonymousUser = null;

    if (userId > 0) {
      anonymousUser = getAnonymousUser(request, userId);

      if (!anonymousUser.getLastIp().equals(request.getRemoteAddr())) {
        AnonymousUserLocalServiceUtil.updateLastIp(
            anonymousUser.getAnonymousUserId(), request.getRemoteAddr());
      }

      return anonymousUser;
    }

    anonymousUser = getAnonymousUserFromCookie(request);

    if (anonymousUser == null) {
      anonymousUser =
          AnonymousUserLocalServiceUtil.addAnonymousUser(
              0, request.getRemoteAddr(), null, serviceContext);

      _anonymousUsersCookieManager.addCookie(request, response, anonymousUser.getAnonymousUserId());
    } else if (!anonymousUser.getLastIp().equals(request.getRemoteAddr())) {
      AnonymousUserLocalServiceUtil.updateLastIp(
          anonymousUser.getAnonymousUserId(), request.getRemoteAddr());
    }

    return anonymousUser;
  }
  protected AnonymousUser getAnonymousUserFromCookie(HttpServletRequest request)
      throws SystemException {

    AnonymousUser anonymousUser = null;

    long anonymousUserId = _anonymousUsersCookieManager.getAnonymousUserId(request);

    if (anonymousUserId > 0) {
      anonymousUser = AnonymousUserLocalServiceUtil.fetchAnonymousUser(anonymousUserId);
    }

    return anonymousUser;
  }