@Override
 public Long getValue(final Pair<String, String> current_friend) {
   return DB.getHumanCrudWallLocal(false)
       .readWallId(
           new HumanId(current_friend.getValue()),
           new Obj<String>(current_friend.getKey()))
       .returnValueBadly();
 }
  public static boolean isCorrectPassword(final HumanId humanId, final String password) {

    final boolean isCorrect;
    if (humanId.validate() == 0) {
      final HumansAuthentication humansAuthentications =
          DB.getHumanCRUDHumanLocal(true).doDirtyRHumansAuthentication(humanId).returnValue();
      isCorrect =
          humansAuthentications
              .getHumanAuthenticationHash()
              .equals(
                  DB.getSingletonHashingFaceLocal(false)
                      .getHash(password, humansAuthentications.getHumanAuthenticationSalt()));
    } else {
      throw new ConstraintsViolatedException(humanId.getViolations());
    }
    return isCorrect;
  }
 @Override
 public Msg getValue(final String whosWall, final String visitor) {
   final List<Msg> msgs =
       DB.getHumanCrudWallLocal(false)
           .readWallLastEntries(
               new HumanId(whosWall), new Obj<String>(visitor), 1, new RefreshSpec())
           .returnValue();
   return msgs.size() != 0
       ? msgs.get(0)
       : null; // Well the comment that was here before was false!!! We all make
               // mistakes!
 }
  // -------------------------- OTHER METHODS --------------------------
  public static Return<Boolean> changePassword(final HumanId humanId, final Password newPass) {

    Return<Boolean> returnVal;
    if (humanId.validate() != 0) {
      throw new ConstraintsViolatedException(humanId.getViolations());
    } else if (newPass.validate() != 0) {
      throw new ConstraintsViolatedException(newPass.getViolations());
    } else {
      returnVal = DB.getHumanCRUDHumanLocal(true).doUHumanPassword(humanId, newPass);
      if (returnVal.returnStatus() == 0 && returnVal.returnValue()) {
        Loggers.USER.info("Password changed for user " + humanId.getObj());
      }
    }
    return returnVal;
  }
  public static Return<Boolean> changePassword(
      final HttpSession httpSession,
      final HumanId humanId,
      final Password currentPass,
      final Password newPass) {

    Return<Boolean> returnVal;
    if (humanId.validate() != 0) {
      throw new ConstraintsViolatedException(humanId.getViolations());
    } else if (currentPass.validate() != 0) {
      throw new ConstraintsViolatedException(currentPass.getViolations());
    } else if (newPass.validate() != 0) {
      throw new ConstraintsViolatedException(newPass.getViolations());
    } else {
      returnVal = DB.getHumanCRUDHumanLocal(true).doUHumanPassword(humanId, currentPass, newPass);
      if (returnVal.returnStatus() == 0 && returnVal.returnValue()) {
        Loggers.USER.info("Password changed for user " + humanId.getObj());
        {
          Loggers.USER.info(
              "Attempting to invalidating session due to password change for user "
                  + humanId.getObj());
          if (httpSession != null) {
            try {
              httpSession.invalidate();
              Loggers.USER.info(
                  "Successfully to invalidated session due to password change for user "
                      + humanId.getObj());
            } catch (final Exception e) {
              Loggers.USER.info(
                  "FAILED to invalidated session due to password change for user "
                      + humanId.getObj());
              Loggers.EXCEPTION.error("", e);
            }
          }
        }
      }
    }
    return returnVal;
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request__
   * @param response__
   * @throws javax.servlet.ServletException if a servlet-specific error occurs
   * @throws java.io.IOException if an I/O error occurs
   */
  protected void processRequest(
      final HttpServletRequest request__, final HttpServletResponse response__)
      throws ServletException, IOException {

    response__.setContentType("text/html;charset=UTF-8");

    final HttpSession userSession_;
    handleHttpSession:
    {
      /** Remove any redundant session */
      if (request__.getSession(false) != null) {
        request__.getSession(false).invalidate();
      }

      /** Make user session anyway as he came to log in */
      userSession_ = request__.getSession();

      /** Set a timeout compatible with the stateful session bean handling user */
      userSession_.setMaxInactiveInterval(
          Integer.parseInt(RBGet.globalConfig.getString("UserSessionIdleInterval")));
    }

    final Enumeration enumerated = request__.getParameterNames();
    logger.info(RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0006"));
    while (enumerated.hasMoreElements()) {
      final String param = (String) enumerated.nextElement();
      logger.info(RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0007"), param);
      logger.info(
          RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0008"),
          request__.getParameter(param).length());
    }
    doActivate:
    {
      if (!isSignOnPermitted()) {
        response__.sendRedirect(request__.getRequestURI());
        break doActivate;
      }
      if (userSession_.getAttribute(HumanUser) == null) {
        /*Ok the session does not have the bean, initialize it with the user with email id and password*/
        if (request__.getParameter(Username) != null && request__.getParameter(Password) != null) {
            /*We need both these to sign in a user*/
          try {
            Human existingUser =
                DB.getHumanCRUDHumanLocal(true).doDirtyRHuman(request__.getParameter(Username));
            @WARNING(
                "THIS CHECK IS VERY IMPORTANT. IF DB IS HASHES ARE COMPROMISED, ONLY NON-ACTIVE PROFILES CAN BE HACKED.")
            final Boolean humanAlive = existingUser.getHumanAlive();
            if (existingUser != null && !humanAlive) {
                /*Ok user name valid but now we check for password*/
              final HumansAuthentication humansAuthentications =
                  DB.getHumanCRUDHumanLocal(true)
                      .doDirtyRHumansAuthentication(new HumanId(request__.getParameter(Username)))
                      .returnValue();

              if (humansAuthentications
                  .getHumanAuthenticationHash()
                  .equals(request__.getParameter(Password))) {
                DB.getHumanCRUDHumanLocal(true)
                    .doUActivateHuman(new HumanId(existingUser.getHumanId()).getSelfAsValid());

                final HumanUserLocal humanUserLocal =
                    ai.ilikeplaces.logic.role.HumanUser.getHumanUserLocal(true);
                humanUserLocal.setHumanUserId(request__.getParameter(Username));
                userSession_.setAttribute(
                    HumanUser,
                    (new SessionBoundBadRefWrapper<HumanUserLocal>(humanUserLocal, userSession_)));
                SendMail.getSendMailLocal()
                    .sendAsHTMLAsynchronously(
                        humanUserLocal.getHumanUserId(),
                        "Access Activated!",
                        "You have activated access to I LIKE PLACES - DOWN TOWN. "
                            + "In case you need to recover your password, "
                            + "please visit: <a href='http://www.ilikeplaces.com/page/_profile'>  http://www.ilikeplaces.com/page/_profile</a>. "
                            + "Adios!");

                final String _encodedNext = request__.getParameter(NEXT);
                if (_encodedNext != null) {
                  @_tests({
                    @_test(scene = "Check for relative urls such as /page/_org", date = "20111130"),
                    @_test(scene = "Full url with parameters", status = true, date = "20111130")
                  })
                  final String next = URLDecoder.decode(_encodedNext, "UTF-8");

                  if (organize.getURL().equals(next)) {
                    response__.sendRedirect(organize.getURL());
                  } else if (tribes.getURL().equals(next)) {
                    response__.sendRedirect(tribes.getURL());
                  } else if (next != null && !"".equals(next)) {
                    response__.sendRedirect(next);
                  } else { // This condition eventually became useless, but a good fallback in case
                           // of an unseen scenario
                    response__.sendRedirect(HOME);
                  }
                } else { // This condition eventually became useless, but a good fallback in case of
                         // an unseen scenario
                  response__.sendRedirect(HOME);
                }

                break
                    doActivate; /*This is unnecessary but lets not leave chance for introducing bugs*/
              } else {
                  /*Ok password wrong. What do we do with this guy? First lets make his session object null*/
                userSession_.invalidate();
                logger.info(RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0002"));
                Loggers.USER.info(existingUser.getHumanId() + " comes with wrong activation hash.");
                redirectToProfilePage(request__, response__);
                break doActivate;
              }
            } else {
                /*There is no such user. Ask if he forgot username or whether to create a new account :)*/
              logger.info(RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0003"));
              redirectToProfilePage(request__, response__);
              break doActivate;
            }
          } catch (final Exception ex) {
            logger.error(RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0004"), ex);
            redirectToProfilePage(request__, response__);
            break doActivate;
          }
        } else {
            /*Why was the user sent here without either username or password or both(by the page)? Send him back!*/
          logger.warn(
              RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0009")
                  + request__.getRequestURL().toString());
          redirectToProfilePage(request__, response__);
          break doActivate;
        }
      } else {
          /*Why did the user come to this page if he was already logged on? Send him back!*/
        logger.info(
            RBGet.logMsgs.getString("ai.ilikeplaces.servlets.ServletLogin.0005")
                + ((SessionBoundBadRefWrapper<HumanUserLocal>) userSession_.getAttribute(HumanUser))
                    .getBoundInstance()
                    .getHumanUserId());
        redirectToProfilePage(request__, response__);
      }
    }
  }
  @Override
  protected void init(final Object... initArgs) {
    this.requestedProfile = ((HumanId) initArgs[0]).getSelfAsValid();
    this.currUserAsVisitor = ((HumanId) initArgs[1]).getSelfAsValid();

    final HumansIdentity currUserAsVisitorHI =
        UserProperty.HUMANS_IDENTITY_CACHE.get((currUserAsVisitor.getHumanId()), "");
    final HumansIdentity requestedProfileHI =
        UserProperty.HUMANS_IDENTITY_CACHE.get((requestedProfile.getHumanId()), "");

    super.setWallProfileName(currUserAsVisitorHI.getHuman().getDisplayName());
    super.setWallProfilePhoto(
        UserProperty.formatProfilePhotoUrl(currUserAsVisitorHI.getHumansIdentityProfilePhoto()));
    super.setWallTitle(
        MessageFormat.format(
            RBGet.gui().getString(TALK_AT_DOWN_TOWN_ER_0_S),
            requestedProfileHI.getHuman().getDisplayName()));

    final int friendCount =
        ((List<HumansNetPeople>)
                $$getHumanUserFromRequest(request)
                    .cache(requestedProfile.getHumanId(), DownTownFlow.FRIENDS))
            .size();

    UCAddFriends:
    if (requestedProfile.equals(currUserAsVisitor)) { // Accessing own profile
      UCInviteFriendsIfNoFriends:
      {
        if (friendCount < 2) {

          $$displayNone(WallWidgetIds.wallWidget);

          String title = "Without followers your updates will be useless";

          // https://upload.wikimedia.org/wikipedia/commons/8/8d/Ambox_padlock_red.svg
          new Info(
              request,
              new InfoCriteria().setImage("/images/What_is_exciting_lately.png"),
              $$(WallWidgetIds.wallGame));

          new Info(
              request,
              new InfoCriteria().setImage("/images/What_is_exciting_lately_Talk.png"),
              $$(WallWidgetIds.wallGame));

          new Info(request, new InfoCriteria(), $$(WallWidgetIds.wallGame)) {
            /**
             * Use this only in conjunction with GENERIC constructor.
             *
             * @param infoCriteria
             */
            @Override
            protected void init(InfoCriteria infoCriteria) {
              UCSetFriendAddWidget:
              {
                String addFollowerTitle = "";

                if (friendCount == 0) {
                  addFollowerTitle = "Add 2 Follower emails To Start Posting!";
                } else if (friendCount == 1) {
                  addFollowerTitle = "Almost there! Add 1 More Follower To Posting!";
                }

                new AdaptableSignup(
                    request,
                    new AdaptableSignupCriteria()
                        .setHumanId(requestedProfile)
                        .setWidgetTitle(addFollowerTitle)
                        .setAdaptableSignupCallback(
                            new AdaptableSignupCallback() {
                              @Override
                              public String afterInvite(final HumanId invitee) {
                                return ai.ilikeplaces.logic.Listeners.widgets
                                        .UserProperty
                                        .HUMANS_IDENTITY_CACHE
                                        .get(invitee.getHumanId(), invitee.getHumanId())
                                        .getHuman()
                                        .getDisplayName()
                                    + " is now following you!";
                              }

                              @Override
                              public String jsToSend(HumanId invitee) {
                                return JSCodeToSend.refreshPageIn(5);
                              }
                            }),
                    $$(InfoIds.InfoAppend));
              }
            }
          };

        } else {

          String addFollowerTitle = "Add more followers!";

          new AdaptableSignup(
              request,
              new AdaptableSignupCriteria()
                  .setHumanId(requestedProfile)
                  .setWidgetTitle(addFollowerTitle)
                  .setAdaptableSignupCallback(
                      new AdaptableSignupCallback() {
                        @Override
                        public String afterInvite(final HumanId invitee) {
                          return ai.ilikeplaces.logic.Listeners.widgets
                                  .UserProperty
                                  .HUMANS_IDENTITY_CACHE
                                  .get(invitee.getHumanId(), invitee.getHumanId())
                                  .getHuman()
                                  .getDisplayName()
                              + " is now following you!";
                        }

                        @Override
                        public String jsToSend(HumanId invitee) {
                          return JSCodeToSend.refreshPageIn(5);
                        }
                      }),
              $$(WallWidgetIds.wallFollowers));
        }
      }
    }

    fetchToEmail();

    final Wall wall =
        DB.getHumanCrudWallLocal(true)
            .readWall(requestedProfile, new Obj<HumanId>(currUserAsVisitor), REFRESH_SPEC)
            .returnValueBadly();
    final List<Msg> wallEntries =
        DB.getHumanCrudWallLocal(true)
            .readWallLastEntries(
                requestedProfile, new Obj<HumanId>(currUserAsVisitor), 25, REFRESH_SPEC_EMPTY)
            .returnValueBadly();

    for (final Msg msg : wallEntries) {
      new UserProperty(request, $$(WallWidgetIds.wallContent), new HumanId(msg.getMsgMetadata())) {
        protected void init(final Object... initArgs) {
          $$(Controller.Page.user_property_content).setTextContent(msg.getMsgContent());
        }
      };
    }

    DB.getHumanCRUDHumansUnseenLocal(false)
        .removeEntry(currUserAsVisitor.getObjectAsValid(), wall.getWallId());

    $$displayWallAsMuted(
        $$(WallWidgetIds.wallMute), wall.getWallMutes().contains(currUserAsVisitor));

    UCFiltering:
    {
      final List<HumansNetPeople> beFriends =
          (List<HumansNetPeople>)
              $$getHumanUserFromRequest(request)
                  .cache(requestedProfile.getHumanId(), DownTownFlow.FRIENDS);

      @_see(
          seeClasses = {
            WallWidgetHumansWall.class,
            PrivateEventDelete.class,
            PrivateEventView.class,
            Tribe.class
          })
      final String peopleFetchToEmail1 =
          new People(
                  request,
                  new PeopleCriteria().setPeople((List<HumanIdFace>) (List<?>) beFriends),
                  $(Controller.Page.Skeleton_left_column))
              .fetchToEmail;

      Loggers.debug("PEOPLE FETCH TO EMAIL CONTENT:" + peopleFetchToEmail1);

      fetchToEmailSetLeftSidebar(peopleFetchToEmail1);
      fetchToEmailSetRightSidebar("&nbsp;");
    }
  }
  @Override
  public Return<File> run(
      File file,
      final Map parameterMap,
      final String userFileExtension,
      final HttpSession session) {
    final SmartLogger sl =
        SmartLogger.start(Loggers.LEVEL.SERVER_STATUS, "Uploading Album Photo", 60000, null, true);
    Return<File> r;
    /** Renaming the file to contain extension for image manipulation flexibility */
    try {
      File newFile = new File(file.getCanonicalPath() + "." + userFileExtension);
      final boolean rename = file.renameTo(newFile);

      if (!rename) {
        sl.complete("Rename Error!");
        return new ReturnImpl<File>(new RuntimeException("Rename Error"), "Rename Error!", true);
      }

      final SessionBoundBadRefWrapper<HumanUserLocal> s =
          (SessionBoundBadRefWrapper<HumanUserLocal>) session.getAttribute(ServletLogin.HumanUser);

      if (!s.isAlive()) {
        sl.complete("No Login!");
        r = new ReturnImpl<File>(ExceptionCache.NO_LOGIN, "Please login!", true);
      } else {
        final HumanId humanId = new HumanId(s.getBoundInstance().getHumanUserId()).getSelfAsValid();

        try {
          try {

            // Uploading Original
            final String cdnFileName = newFile.getName();
            sl.appendToLogMSG(UPLOADING_ORIGINAL_IMAGE);
            final boolean uploadedOriginal =
                client.storeObjectAs(
                    CONTAINER,
                    newFile,
                    FilesConstants.getMimetype(userFileExtension),
                    ORIGINAL + cdnFileName);

            BufferedImage bi = null;

            // Uploading Standard Size
            sl.appendToLogMSG(LOADING_IMAGE_AS_BUFFERED_IMAGE);
            bi = loadImage(newFile);

            sl.appendToLogMSG(SCALING_IMAGE);
            bi = scaleImage(bi, 600); // Reducing size of image to standard view

            sl.appendToLogMSG(SAVING_SCALED_IMAGE);
            saveImage(bi, newFile);

            final String cdnfileName = newFile.getName();
            sl.appendToLogMSG(UPLOADING_STANDARD_IMAGE);
            final boolean uploadedStandard =
                client.storeObjectAs(
                    CONTAINER, newFile, FilesConstants.getMimetype(userFileExtension), cdnfileName);

            // Uploading Thumb
            sl.appendToLogMSG(LOADING_IMAGE_AS_BUFFERED_IMAGE);
            bi = loadImage(newFile);

            sl.appendToLogMSG(SCALING_IMAGE);
            bi =
                scaleImage(
                    bi,
                    190); // Reducing size of image to blueprintcss span-5 just to save bandwidth
            // for the user.

            sl.appendToLogMSG(SAVING_SCALED_IMAGE);
            saveImage(bi, newFile);

            final String cdnThumbFileName = THUMBNAIL + newFile.getName();
            sl.appendToLogMSG(UPLOADING_IMAGE_THUMB);
            final boolean uploadedThumb =
                client.storeObjectAs(
                    CONTAINER,
                    newFile,
                    FilesConstants.getMimetype(userFileExtension),
                    cdnThumbFileName);

            if (uploadedStandard && uploadedThumb && uploadedOriginal) {
              final boolean deleted = newFile.delete();
              if (deleted) {
                final Return<Album> dbr =
                    DB.getHumanCrudPrivateEventLocal(true)
                        .uPrivateEventAddEntryToAlbum(
                            humanId,
                            Long.parseLong((String) parameterMap.get(ALBUM_PIVATE_EVENT_ID)),
                            new Obj<String>(cdnFileName).getSelfAsValid());
                if (dbr.returnStatus() == 0) {
                  sl.complete(Loggers.DONE);
                  r = new ReturnImpl<File>(newFile, ALBUM_PHOTO_UPLOAD_SUCCESSFUL);
                } else {
                  r =
                      new ReturnImpl<File>(
                          new DBOperationException(dbr.returnError()),
                          ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_I_O_ISSUES,
                          true);
                }
              } else {
                r =
                    new ReturnImpl<File>(
                        ExceptionCache.FILE_DELETE_FAILED,
                        ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_CACHING_ISSUES,
                        true);
              }
            } else {
              r =
                  new ReturnImpl<File>(
                      ExceptionCache.CDN_FILE_UPLOAD_FAILED,
                      ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_I_O_ISSUES,
                      true);
            }
          } catch (final IOException e) {
            r = new ReturnImpl<File>(e, ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_I_O_ISSUES, true);
          }
        } catch (
            final RuntimeException e) { // This is for the deleteObject's returnBadly from DB return
          r = new ReturnImpl<File>(e, ALBUM_PHOTO_UPLOAD_FAILED, true);
        } catch (final Exception e) {
          r =
              new ReturnImpl<File>(
                  e, ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_IMAGE_MANIPULATION_ISSUES, true);
        }
      }
    } catch (final IOException e) {
      r = new ReturnImpl<File>(e, ALBUM_PHOTO_UPLOAD_FAILED_DUE_TO_RENAMING_ISSUES, true);
    }
    return r;
  }