alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/user/MemberWebHandler.java,v 1.71 2005/01/28 19:40:52 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.71 $
 * $Date: 2005/01/28 19:40:52 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum.user;

import java.io.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvnforum.*;
import com.mvnforum.auth.*;
import com.mvnforum.common.SendMailUtil;
import com.mvnforum.db.*;
import com.mvnforum.search.member.MemberIndexer;
import freemarker.template.*;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.fileupload.*;
import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
import net.myvietnam.mvncore.interceptor.InterceptorService;
import net.myvietnam.mvncore.security.*;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class MemberWebHandler {

    private static Log log = LogFactory.getLog(MemberWebHandler.class);

    private OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();

    MemberWebHandler() {
    }

    void prepareAdd(HttpServletRequest request)
        throws AssertionException, DatabaseException, AuthenticationException {

        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (MVNForumConfig.getEnableNewMember() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_register.new_member_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot register new member because NEW_MEMBER feature is disabled by administrator.");
        }

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        if (MVNForumConfig.getEnableCaptcha()) {
            onlineUser.buildNewCaptcha();
        }
    }

    void processAdd(HttpServletRequest request, HttpServletResponse response)
        throws BadInputException, ObjectNotFoundException, CreateException, DatabaseException, InterceptorException,
        DuplicateKeyException, ForeignKeyNotFoundException, AssertionException, FloodException, AssertionException,
        DatabaseException, AuthenticationException {

        Locale locale = I18nUtil.getLocaleInRequest(request);
        if (MVNForumConfig.getEnableNewMember() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_register.new_member_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot register new member because NEW_MEMBER feature is disabled by administrator.");
        }

        // use for the captcha feature
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);

        MyUtil.saveVNTyperMode(request, response);

        String currentIP = request.getRemoteAddr();
        try {
            FloodControl.ensureNotReachMaximum(MVNForumGlobal.FLOOD_ID_NEW_MEMBER, currentIP);
        } catch (FloodException fe) {
            //throw new FloodException("You have reached the maximum number of the registering actions for this page. Please try this page later. This is to prevent forum from being flooded.");
            Integer maxRegisters = new Integer(FloodControl.getActionsPerHour(MVNForumGlobal.FLOOD_ID_NEW_MEMBER));
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.FloodException.register_too_many_times", new Object[] { maxRegisters });
            throw new FloodException(localizedMessage);
        }
        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        String memberName = ParamUtil.getParameterSafe(request, "MemberName", true);// check good name
        /** @todo move to a name filter */
        if ( memberName.equalsIgnoreCase(MVNForumConfig.getDefaultGuestName()) ||
             memberName.equalsIgnoreCase("Guest") ||
             memberName.equalsIgnoreCase("Administrator") ||
             memberName.equalsIgnoreCase("Moderator") ) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_register_with_reserved_name", new Object[] {memberName});
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Cannot register member with a reserved name : " + memberName);
        }
        StringUtil.checkGoodName(memberName);
        InterceptorService.getInstance().validateLoginID(memberName);
        if (memberName.length() > MVNForumGlobal.MAX_MEMBER_LOGIN_LENGTH) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.member_name_too_long");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("MemberName cannot be longer than 30 characters.");
        }

        String memberPassword1      = ParamUtil.getParameterPassword(request, "MemberMatkhau", 3, 0);
        String memberPassword2      = ParamUtil.getParameterPassword(request, "MemberMatkhauConfirm", 3, 0);
        if (!memberPassword1.equals(memberPassword2)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.confirmed_password_is_not_match");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Password and confirmed password are not the same, please try again.");
        }
        String memberPassword       = Encoder.getMD5_Base64(memberPassword1);

        String memberEmail          = ParamUtil.getParameterEmail(request, "MemberEmail");
        String memberEmailConfirm   = ParamUtil.getParameterEmail(request, "MemberEmailConfirm");
        if (!memberEmail.equals(memberEmailConfirm)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.confirmed_email_is_not_match");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Email and confirmed email are not the same, please try again.");
        }
        String memberFirstEmail     = memberEmail;
        if (memberEmail.length() > MVNForumGlobal.MAX_MEMBER_EMAIL_LENGTH) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.member_email_too_long");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("MemberEmail cannot be longer than 60 characters.");
        }
        InterceptorService.getInstance().validateMail(memberFirstEmail);

        int memberEmailVisible      = ParamUtil.getParameterBoolean(request, "MemberEmailVisible")? MemberBean.MEMBER_EMAIL_VISIBLE : MemberBean.MEMBER_EMAIL_INVISIBLE;
        int memberNameVisible       = ParamUtil.getParameterBoolean(request, "MemberNameVisible") ? MemberBean.MEMBER_NAME_VISIBLE : MemberBean.MEMBER_NAME_INVISIBLE;
        String memberFirstIP        = currentIP;
        String memberLastIP         = currentIP;
        Timestamp memberCreationDate= now;
        Timestamp memberModifiedDate= now;
        Timestamp memberLastLogon   = now;// @todo review and support it later
        int memberOption            = 0;//@todo review and support it later
        int memberStatus            = 0;// @todo review and support it later, ex: should it be active or not?
        String memberActivateCode   = "";// not activated
        int memberMessageOption     = 0;// @todo review and support it later
        int memberPostsPerPage      = ParamUtil.getParameterInt(request, "MemberPostsPerPage", 10);
        if (memberPostsPerPage < 5) {
            memberPostsPerPage = 5;
        }
        String memberTitle          = "";
        int memberTimeZone          = ParamUtil.getParameterTimeZone(request, "MemberTimeZone");
        String memberSkin           = "";
        String memberLanguage       = ParamUtil.getParameterSafe(request, "MemberLanguage", false);
        String memberFirstname      = ParamUtil.getParameterSafe(request, "MemberFirstname", true);
        String memberLastname       = ParamUtil.getParameterSafe(request, "MemberLastname", true);
        int memberGender            = ParamUtil.getParameterBoolean(request, "MemberGender") ? 1 : 0;

        //Date memberBirthday         = ParamUtil.getParameterDate(request, "MemberBirthday");
        Date memberBirthday         = ParamUtil.getParameterDate(request, "day", "month", "year");
        /** @todo : rewrite this code */
        /*
        long nowtime = System.currentTimeMillis();
        long oldest = nowtime - 100*DateUtil.YEAR;
        long youngest = nowtime - 10*DateUtil.YEAR;
        long age = (nowtime - memberBirthday.getTime())/DateUtil.YEAR;
        if (memberBirthday.getTime() > youngest || memberBirthday.getTime() < oldest) {
            log.debug("age = " + age + " date = " + memberBirthday + " gettime = " + memberBirthday.getTime());
            throw new BadInputException("Your age is not allow: " + age);
        }*/

        String memberAddress        = ParamUtil.getParameterSafe(request, "MemberAddress", false);
        String memberCity           = ParamUtil.getParameterSafe(request, "MemberCity", false);
        String memberState          = ParamUtil.getParameterSafe(request, "MemberState", false);
        String memberCountry        = ParamUtil.getParameterSafe(request, "MemberCountry", false);
        String memberPhone          = ParamUtil.getParameterSafe(request, "MemberPhone", false);
        String memberMobile         = ParamUtil.getParameterSafe(request, "MemberMobile", false);
        String memberFax            = ParamUtil.getParameterSafe(request, "MemberFax", false);
        String memberCareer         = ParamUtil.getParameterSafe(request, "MemberCareer", false);
        String memberHomepage       = ParamUtil.getParameterUrl(request, "MemberHomepage");
        String memberYahoo          = ParamUtil.getParameterSafe(request, "MemberYahoo", false);
        String memberAol            = ParamUtil.getParameterSafe(request, "MemberAol", false);
        String memberIcq            = ParamUtil.getParameterSafe(request, "MemberIcq", false);
        String memberMsn            = ParamUtil.getParameterSafe(request, "MemberMsn", false);
        String memberCoolLink1      = ParamUtil.getParameterUrl(request, "MemberCoolLink1");
        String memberCoolLink2      = ParamUtil.getParameterUrl(request, "MemberCoolLink2");

        // Now check the captcha
        if (MVNForumConfig.getEnableCaptcha()) {
            String captchaResponse = ParamUtil.getParameterSafe(request, "CaptchaResponse", false);
            onlineUser.ensureCorrectCaptchaResponse(captchaResponse);
        }
        Timestamp memberExpireDate = memberCreationDate;// equal Creation Date mean no expiration
        if (MVNForumConfig.getEnableCompany()) {
            memberExpireDate = DateUtil.getCurrentGMTTimestampExpiredDay(MVNForumConfig.getExpireDateTutor());
        }

        DAOFactory.getMemberDAO().create(memberName, memberPassword, memberFirstEmail,
                                   memberEmail, memberEmailVisible, memberNameVisible,
                                   memberFirstIP, memberLastIP, 0/*memberViewCount*/,
                                   0/*memberPostCount*/, memberCreationDate, memberModifiedDate, memberExpireDate,
                                   memberLastLogon, memberOption, memberStatus,
                                   memberActivateCode, ""/*memberTempPassword*/, 0/*memberMessageCount*/,
                                   memberMessageOption, memberPostsPerPage, 0/*memberWarnCount*/,
                                   0/*memberVoteCount*/, 0/*memberVoteTotalStars*/, 0/*memberRewardPoints*/,
                                   memberTitle, memberTimeZone, ""/*memberSignature*/,
                                   ""/*memberAvatar*/, memberSkin, memberLanguage,
                                   memberFirstname, memberLastname, memberGender,
                                   memberBirthday, memberAddress, memberCity,
                                   memberState, memberCountry, memberPhone,
                                   memberMobile, memberFax, memberCareer,
                                   memberHomepage, memberYahoo, memberAol,
                                   memberIcq, memberMsn, memberCoolLink1,
                                   memberCoolLink2);

        // Now, create 4 default folders for each member
        int memberID = 0;
        try {
            memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
            throw new ObjectNotFoundException(localizedMessage);
        }

        int folderStatus = 0;
        int folderOption = 0;
        int folderType = 0;
        DAOFactory.getMessageFolderDAO().create(MVNForumConstant.MESSAGE_FOLDER_INBOX, memberID, 0/*order*/, folderStatus, folderOption, folderType, now, now);
        DAOFactory.getMessageFolderDAO().create(MVNForumConstant.MESSAGE_FOLDER_DRAFT, memberID, 1/*order*/, folderStatus, folderOption, folderType, now, now);
        DAOFactory.getMessageFolderDAO().create(MVNForumConstant.MESSAGE_FOLDER_SENT, memberID, 2/*order*/, folderStatus, folderOption, folderType, now, now);
        DAOFactory.getMessageFolderDAO().create(MVNForumConstant.MESSAGE_FOLDER_TRASH, memberID, 3/*order*/, folderStatus, folderOption, folderType, now, now);

        FloodControl.increaseCount(MVNForumGlobal.FLOOD_ID_NEW_MEMBER, currentIP);

        if (MVNForumConfig.getEnableCaptcha()) {
            onlineUser.destroyCurrentCaptcha();
        }

        // Add member to the lucene index
        MemberBean memberBean = null;
        try {
            memberBean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
        } catch(ObjectNotFoundException ex) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.memberid_not_exists", new Object[] {new Integer(memberID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        MemberIndexer.scheduleAddMemberTask(memberBean);

        request.setAttribute("MemberBean", memberBean);

        // now, if require activation, then we will send mail
        if (MVNForumConfig.getRequireActivation()) {
            String serverName = ParamUtil.getServerPath();//ParamUtil.getServer2(request);
            try {
                SendMailUtil.sendActivationCodeEmail(memberID, serverName);
            } catch (Exception ex) {
                log.error("Cannot send mail after registration!", ex);
                request.setAttribute("mvnforum.mail.failed", "Cannot send activation email after registration!");
                //@todo: save the error message to displayed later
            }
        }

        // Begin for Company
        String companySpaceName = ParamUtil.getParameterSafe(request, "CompanySpaceName", false);
        if (companySpaceName.length() > 0) {
            try {
                int companyID = DAOFactory.getCompanyDAO().getCompanyIDFromCompanySpaceName(companySpaceName);
                CompanyBean companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);

                int privilege      = 0;
                DAOFactory.getMemberGroupDAO().create(companyBean.getGroupID(), memberName, privilege,
                                            now/*creationDate*/, now/*modifiedDate*/);

                int isActive       = 0;
                int relationType   = 0;
                int relationOption = 0;
                int relationStatus = 0;
                Timestamp expireDate = new Timestamp(now.getTime() + DateUtil.DAY * 90);
                DAOFactory.getMemberCompanyDAO().create(memberID, memberName, companyID,
                                      now/*creationDate*/, expireDate, isActive,
                                      relationType, relationOption, relationStatus);
            } catch (ObjectNotFoundException ex) {
                // Cannot find company with the space name, just ignore
            }
        }
        // End for Company
    }

    void processUpdate(HttpServletRequest request, HttpServletResponse response)
        throws BadInputException, ObjectNotFoundException, DatabaseException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        MyUtil.saveVNTyperMode(request, response);

        int memberID = onlineUser.getMemberID();

        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        // column(s) to update
        int memberEmailVisible      = ParamUtil.getParameterBoolean(request, "MemberEmailVisible")? MemberBean.MEMBER_EMAIL_VISIBLE : MemberBean.MEMBER_EMAIL_INVISIBLE;
        int memberNameVisible       = ParamUtil.getParameterBoolean(request, "MemberNameVisible") ? MemberBean.MEMBER_NAME_VISIBLE : MemberBean.MEMBER_NAME_INVISIBLE;
        int memberOption            = 0;//ParamUtil.getParameterInt(request, "MemberOption");
        int memberStatus            = 0;//@todo review and support it later
        int memberMessageOption     = 0;//ParamUtil.getParameterInt(request, "MemberMessageOption");
        int memberPostsPerPage      = ParamUtil.getParameterInt(request, "MemberPostsPerPage");
        if (memberPostsPerPage < 5) {
            memberPostsPerPage = 5;
        }
        int memberTimeZone          = ParamUtil.getParameterTimeZone(request, "MemberTimeZone");
        String memberSkin           = ParamUtil.getParameterSafe(request, "MemberSkin", false);
        String memberLanguage       = ParamUtil.getParameterSafe(request, "MemberLanguage", false);
        String memberFirstname      = ParamUtil.getParameterSafe(request, "MemberFirstname", true);
        String memberLastname       = ParamUtil.getParameterSafe(request, "MemberLastname", true);
        int memberGender            = ParamUtil.getParameterBoolean(request, "MemberGender")? 1 : 0;
        Date memberBirthday         = ParamUtil.getParameterDate(request, "MemberBirthday");
        String memberAddress        = ParamUtil.getParameterSafe(request, "MemberAddress", false);
        String memberCity           = ParamUtil.getParameterSafe(request, "MemberCity", false);
        String memberState          = ParamUtil.getParameterSafe(request, "MemberState", false);
        String memberCountry        = ParamUtil.getParameterSafe(request, "MemberCountry", false);
        String memberPhone          = ParamUtil.getParameterSafe(request, "MemberPhone", false);
        String memberMobile         = ParamUtil.getParameterSafe(request, "MemberMobile", false);
        String memberFax            = ParamUtil.getParameterSafe(request, "MemberFax", false);
        String memberCareer         = ParamUtil.getParameterSafe(request, "MemberCareer", false);
        String memberHomepage       = ParamUtil.getParameterUrl(request, "MemberHomepage");
        String memberYahoo          = ParamUtil.getParameterSafe(request, "MemberYahoo", false);
        String memberAol            = ParamUtil.getParameterSafe(request, "MemberAol", false);
        String memberIcq            = ParamUtil.getParameterSafe(request, "MemberIcq", false);
        String memberMsn            = ParamUtil.getParameterSafe(request, "MemberMsn", false);
        String memberCoolLink1      = ParamUtil.getParameterUrl(request, "MemberCoolLink1");
        String memberCoolLink2      = ParamUtil.getParameterUrl(request, "MemberCoolLink2");

        DAOFactory.getMemberDAO().update(memberID, // primary key
                               memberEmailVisible, memberNameVisible, now/*memberModifiedDate*/,
                               memberOption, memberStatus, memberMessageOption,
                               memberPostsPerPage, memberTimeZone, memberSkin,
                               memberLanguage, memberFirstname, memberLastname,
                               memberGender, memberBirthday, memberAddress,
                               memberCity, memberState, memberCountry,
                               memberPhone, memberMobile, memberFax,
                               memberCareer, memberHomepage, memberYahoo,
                               memberAol, memberIcq, memberMsn,
                               memberCoolLink1, memberCoolLink2);

        // now, update the new displayed language option
        onlineUser.reloadProfile();
        MemberBean justAddedMemberBean = null;
        try {
            justAddedMemberBean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
        } catch(ObjectNotFoundException ex) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.memberid_not_exists", new Object[] {new Integer(memberID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        MemberIndexer.scheduleUpdateMemberTask(justAddedMemberBean);

    }

    /*
     * @todo: use new method of WebHelper
     */
    void prepareEditEmail(HttpServletRequest request)
        throws DatabaseException, ObjectNotFoundException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        int memberID = onlineUser.getMemberID();
        MemberBean memberBean   = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
        request.setAttribute("MemberEmail", memberBean.getMemberEmail());
    }

    void processUpdateEmail(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException, InterceptorException,
        DuplicateKeyException, AuthenticationException, AssertionException, MessagingException,IOException, TemplateException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        Locale locale = I18nUtil.getLocaleInRequest(request);

        int memberID = onlineUser.getMemberID();

        // column(s) to update
        String memberEmail          = ParamUtil.getParameterEmail(request, "MemberEmail");
        String memberEmailConfirm   = ParamUtil.getParameterEmail(request, "MemberEmailConfirm");
        if (memberEmail.length() > MVNForumGlobal.MAX_MEMBER_EMAIL_LENGTH) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.member_email_too_long");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("MemberEmail cannot be longer than 60 characters.");
        }
        InterceptorService.getInstance().validateMail(memberEmail);

        // now check the password
        MyUtil.ensureCorrectCurrentPassword(request);

        if (!memberEmail.equals(memberEmailConfirm)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.confirmed_email_is_not_match");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Email and confirmed email are not the same, please try again.");
        }

        // invalidate the activate status
        DAOFactory.getMemberDAO().updateActivateCode(memberID, "");

        DAOFactory.getMemberDAO().updateEmail(memberID, memberEmail);

        // now reload the permission if this online user change email (not activated now)
        onlineUser.reloadPermission();

        // now, if require activation, then we will send mail
        if (MVNForumConfig.getRequireActivation()) {
            String serverName = ParamUtil.getServerPath();//ParamUtil.getServer2(request);
            SendMailUtil.sendActivationCodeEmail(memberID, serverName);
        }
    }

    void processUpdatePassword(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException,
        AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        int memberID = onlineUser.getMemberID();
        Locale locale = I18nUtil.getLocaleInRequest(request);

        // now check the password
        MyUtil.ensureCorrectCurrentPassword(request);
        /*
        // NOTE: that we dont use getParameterPassword here since it will not forward-compatible
        String memberOldPassword    = ParamUtil.getParameter(request, "MemberOldMatkhau", true);
        String oldEncodedPassword   = Encoder.getMD5_Base64(memberOldPassword);
        String currentPassword      = DAOFactory.getMemberDAO().getPassword(memberID);
        if (!currentPassword.equals(oldEncodedPassword)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_password");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("You have typed the wrong current password, please try again.");
        }*/

        // column(s) to update
        String memberPassword1      = ParamUtil.getParameterPassword(request, "MemberMatkhau", 3, 0);
        String memberPassword2      = ParamUtil.getParameterPassword(request, "MemberMatkhauConfirm", 3, 0);
        if (!memberPassword1.equals(memberPassword2)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.confirmed_password_is_not_match");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Password and confirmed password are not the same, please try again.");
        }
        String memberPassword       = Encoder.getMD5_Base64(memberPassword1);

        String currentPassword      = DAOFactory.getMemberDAO().getPassword(memberID);
        if (currentPassword.equals(memberPassword)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.old_password_and_new_password_cannot_equal");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Old password and new password cannot equal, please try again.");
        }

        DAOFactory.getMemberDAO().updatePassword(memberID, // primary key
                               memberPassword);
    }

    void prepareView_forCurrentMember(HttpServletRequest request)
        throws DatabaseException, ObjectNotFoundException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        // always update the number of new private message count in this case
        onlineUser.updateNewMessageCount(true);

        int memberID = onlineUser.getMemberID();
        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
        request.setAttribute("MemberBean", memberBean);
    }

    void prepareEdit_forCurrentMember(HttpServletRequest request)
        throws DatabaseException, ObjectNotFoundException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        int memberID = onlineUser.getMemberID();
        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forEditCurrentMember(memberID);
        request.setAttribute("MemberBean", memberBean);
    }

    /*
     * @todo: use new method of WebHelper
     */
    void prepareEditSignature(HttpServletRequest request)
        throws DatabaseException, ObjectNotFoundException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        boolean isPreviewing = ParamUtil.getParameterBoolean(request, "preview");
        if (isPreviewing) {
            String signature = ParamUtil.getParameter(request, "MemberSignature");
            if (signature.length() > 250) {
                signature = signature.substring(0, 250);// ensure no more than 250 char (should check in javascript ??)
            }
            request.setAttribute("MemberSignature", signature);
        } else {
            int memberID = onlineUser.getMemberID();
            MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
            request.setAttribute("MemberSignature", memberBean.getMemberSignature());
        }
    }

    void processUpdateSignature(HttpServletRequest request, HttpServletResponse response)
        throws ObjectNotFoundException, DatabaseException, AuthenticationException, AssertionException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();

        MyUtil.saveVNTyperMode(request, response);

        int memberID = onlineUser.getMemberID();

        // column(s) to update
        String memberSignature = ParamUtil.getParameter(request, "MemberSignature");
        memberSignature = DisableHtmlTagFilter.filter(memberSignature);

        DAOFactory.getMemberDAO().updateSignature(memberID, // primary key
                                                  memberSignature);
    }

    /*
     * @todo: use new method of WebHelper
     */
    void prepareEditAvatar(HttpServletRequest request)
        throws DatabaseException, ObjectNotFoundException, AuthenticationException, AssertionException {

        Locale locale = I18nUtil.getLocaleInRequest(request);
        if (MVNForumConfig.getEnableAvatar() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.avatar_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot use avatar because AVATAR feature is disabled by administrator.");
        }

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        permission.ensureCanUseAvatar();

        int memberID = onlineUser.getMemberID();
        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
        request.setAttribute("MemberBean", memberBean);
    }

    /**
     * Change picture from our predefined picture
     * NOTE: this method will delete uploaded image (if any) of the member
     */
    void updateMemberAvatar(HttpServletRequest request)
        throws ObjectNotFoundException, DatabaseException, AuthenticationException, AssertionException {

        if (MVNForumConfig.getEnableAvatar() == false) {
            throw new AssertionException("Cannot use avatar because AVATAR feature is disabled by administrator.");
        }

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        permission.ensureCanUseAvatar();

        int memberID      = onlineUser.getMemberID();
        String memberName = onlineUser.getMemberName();

        // first, we delete uploaded image if there is one
        StringBuffer bufferPicFile = new StringBuffer(128);
        bufferPicFile.append(MVNForumConfig.getAvatarDir());
        bufferPicFile.append(File.separatorChar).append(memberName).append(".jpg");
        String picFile =  bufferPicFile.toString();

        log.trace("Delete avatar = " + picFile);
        log.trace("String length = " + picFile.length());
        File file = new File(picFile);
        file.delete();// we dont need to check the returned value

        // then we update the database with new one
        String memberPicture = ParamUtil.getParameter(request, "MemberAvatar");
        DAOFactory.getMemberDAO().updateAvatar(memberID, memberPicture);
    }

    /**
     * upload user own avatar
     */
    void uploadAvatar(javax.servlet.ServletConfig config, HttpServletRequest request)
        throws BadInputException, AuthenticationException, IOException,
        AssertionException, ObjectNotFoundException, DatabaseException {
        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (MVNForumConfig.getEnableAvatar() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.avatar_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot use avatar because AVATAR feature is disabled by administrator.");
        }

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        permission.ensureCanUseAvatar();

        int memberID      = onlineUser.getMemberID();
        String memberName = onlineUser.getMemberName();

        FileUpload fileUpload = new FileUpload();
        fileUpload.setSizeMax(60000);//60K
        fileUpload.setSizeThreshold(100000);// max memory used = 100K (more than needed)

        List fileItems;
        try {
            fileItems = fileUpload.parseRequest(request);
        } catch (FileUploadException ex) {
            log.error("Cannot upload", ex);
            //@todo : localize me
            throw new IOException("Cannot upload. Detailed reason: " + ex.getMessage());
        }

        // make sure only one file upload
        if (fileItems.size() != 1) {
            throw new AssertionException("Assertion: Cannot upload more than 1 file while processing upload avatar for Member.");
        }

        //get the first and only file
        FileItem myFile = (FileItem)fileItems.get(0);
        if (myFile.isFormField() == true) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_process_upload_avatar_with_form_field");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot process uploaded avatar with a form field.");
        }

        // now everything all right, go ahead and create thumbnail
        InputStream inputStream = myFile.getInputStream();

        StringBuffer bufferPicFile = new StringBuffer(128);
        //bufferPicFile.append(config.getServletContext().getRealPath(MVNForumGlobal.UPLOADED_AVATAR_DIR));
        //bufferPicFile.append(File.separatorChar).append(memberName).append(".jpg");
        bufferPicFile.append(MVNForumConfig.getAvatarDir());
        bufferPicFile.append(File.separatorChar).append(memberName).append(".jpg");
        String thumbnailFile =  bufferPicFile.toString();

        //log.trace("uploaded file = " + thumbnailFile);
        //log.trace("String length = " + thumbnailFile.length());

        //The below method closes the inputStream after it have done its work.
        ImageUtil.createThumbnail(inputStream, thumbnailFile, 150/*maxWidth*/, 150/*maxHeight*/);// can throw BadInputException

        // now the image has been save, go ahead and update database
        //StringBuffer bufferVirtualFile = new StringBuffer(128);
        //bufferVirtualFile.append(MVNForumGlobal.UPLOADED_AVATAR_DIR);
        //bufferVirtualFile.append("/").append(memberName).append(".jpg");
        //String virtualFile =  bufferVirtualFile.toString();
        //String virtualFile =  memberName + ".jpg";
        try {
            DAOFactory.getMemberDAO().updateAvatar(memberID, MemberBean.MEMBER_AVATAR_USING_UPLOAD);
        } catch (DatabaseException ex) {// we dont need to catch ObjectNotFoundException since the memberID is already exits
            log.fatal("Assertion in MemberWebHandler.uploadPicture");// we dont want it to be here
            // need to delete the file if the above database task failed
            FileUtil.deleteFile(thumbnailFile);
            throw ex;
        }
    }

    void prepareForgotPassword(HttpServletRequest request)
        throws AssertionException, DatabaseException, AuthenticationException {

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        if (MVNForumConfig.getEnableCaptcha()) {
            onlineUser.buildNewCaptcha();
        }
    }

    void forgotPassword(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException, MessagingException,
        AssertionException, AssertionException, DatabaseException, AuthenticationException, IOException,TemplateException {

        // use for the captcha feature
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        Locale locale = I18nUtil.getLocaleInRequest(request);

        int memberID = 0;
        String memberName = ParamUtil.getParameter(request, "MemberName");
        StringUtil.checkGoodName(memberName);
        String memberEmail = ParamUtil.getParameter(request, "MemberEmail");
        if (memberEmail.length() > 0) {
            memberEmail = ParamUtil.getParameterEmail(request, "MemberEmail");
        }

        if (memberName.length() > 0) {// user enter his MemberName
            // we find the email of this memberID, not the provided email
            try {
                    memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
                throw new ObjectNotFoundException(localizedMessage);
            }
            MemberBean bean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
            memberEmail     = bean.getMemberEmail();
        } else if (memberEmail.length() > 0) {// user enter his email
            // we find the MemberID of this mail, now we sure that user didnt enter his MemberID
            memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberEmail(memberEmail);
            MemberBean bean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
            memberName      = bean.getMemberName();
        } else {// user didnt enter any thing
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.your_member_name_or_email_is_not_entered");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("You must enter at least your MemberName or email");
        }

        // now we have the correct pair of MemberID and MemberEmail

        // Check the  assumption above
        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
        if (!memberEmail.equalsIgnoreCase(memberBean.getMemberEmail())) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.serious_bug");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Assertion when process forgot password. This is a serious bug. Please contact the Web site administrator to report the bug.");
        }
        // end check

        // Now check the captcha
        if (MVNForumConfig.getEnableCaptcha()) {
            String captchaResponse = ParamUtil.getParameterSafe(request, "CaptchaResponse", false);
            onlineUser.ensureCorrectCaptchaResponse(captchaResponse);
        }

        String currentTempPassword = DAOFactory.getMemberDAO().getTempPassword(memberID);

        // if the current value length is less then 5, we assume that it is not set
        // and we generate the new value only in this case. This will prevent the
        // different values are sent out and confuse user.
        if (currentTempPassword.length() < 5) {
            //generate a temp password
            currentTempPassword = RandomGenerator.getRandomMD5_Base64();
            DAOFactory.getMemberDAO().updateTempPassword(memberID, currentTempPassword);
        }

        // next, encode to make sure it could be put on a link
        String urlEncodedTempPassword = Encoder.encodeURL(currentTempPassword);

        // we have pass the assertion check, go ahead
        String serverName = ParamUtil.getServerPath();//ParamUtil.getServer2(request);

        StringBuffer passwordResetUrl = new StringBuffer(256);
        passwordResetUrl.append(serverName);
        passwordResetUrl.append(ParamUtil.getContextPath());
        passwordResetUrl.append(UserModuleConfig.getUrlPattern());
        passwordResetUrl.append("/resetpassword?temppassword=");
        passwordResetUrl.append(urlEncodedTempPassword);
        passwordResetUrl.append("&member=");
        passwordResetUrl.append(memberName);

        // Prepare the FreeMarker configuration;
        Configuration cfg = MVNForumConfig.getFreeMarkerConfiguration();

        //Below is a code to map content of email to template
        Map root = new HashMap();
        root.put("serverName", serverName);
        root.put("MVNForumInfo", MVNForumInfo.getProductDesc());
        root.put("passwordResetUrl", passwordResetUrl.toString());
        root.put("memberName", memberName);
        root.put("currentTempPassword", currentTempPassword);

        StringWriter subjectWriter = new StringWriter(256);
        Template subjectTemplate = cfg.getTemplate(MVNForumGlobal.TEMPLATE_FORGOTPASSWORD_SUBJECT, "UTF-8");
        subjectTemplate.process(root, subjectWriter);
        String subject = subjectWriter.toString();

        StringWriter bodyWriter = new StringWriter(1024);
        Template bodyTemplate = cfg.getTemplate(MVNForumGlobal.TEMPLATE_FORGOTPASSWORD_BODY, "UTF-8");
        bodyTemplate.process(root, bodyWriter);
        String body = bodyWriter.toString();

//        String subject= "Your MEMBER password of website " + serverName;
/*        String body =   "This email is sent to you because you (or someone) have requested PASSWORD RESET from web site " + serverName + ".\n" +
                        "If you did not request this password reset feature, just ignore and DELETE this email IMMEDIATELY.\n" +
                        "If you do want to reset your password, please use this url to reset your password:\n" +
                        passwordResetUrl.toString() + "\n" +
                        "Thank you for using " + MVNForumInfo.getProductDesc() + " and we hope that you enjoy our forum.\n" +
                        serverName + " webmaster\n\n" +
                        "NOTE: you could use the information below in case the above link does not work:\n" +
                        "Your Member Name = " + memberName + "\n" +
                        "Your temporary password = " + currentTempPassword + "\n";
*/
        log.debug("subject = " + subject);
        log.debug("body = " + body);
        try {
            MailUtil.sendMail(MVNForumConfig.getWebMasterEmail() /*use the default MailFrom value*/,
                              memberEmail /*to*/, "" /*cc*/, "" /*bcc*/, subject, body);
        } catch (UnsupportedEncodingException e) {
            log.error("Cannot support encoding", e);
        }

        // Only destroy captcha when send mail successfully
        if (MVNForumConfig.getEnableCaptcha()) {
            onlineUser.destroyCurrentCaptcha();
        }
    }

    void resetPassword(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException {

        Locale locale = I18nUtil.getLocaleInRequest(request);

        String memberName = ParamUtil.getParameter(request, "member", true);
        StringUtil.checkGoodName(memberName);
        // IMPORTANT: MUST check that temp password is not empty, because temppassword = empty
        // means cannot reset password
        String memberTempPassword   = ParamUtil.getParameter(request, "temppassword", true);

        int memberID = 0;
        try {
            memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
            throw new ObjectNotFoundException(localizedMessage);
        }

        String currentTempPassword = DAOFactory.getMemberDAO().getTempPassword(memberID);
        if (memberTempPassword.equals(currentTempPassword) == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_temporary_password");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Your temporary password is not correct, please try the forgot password feature.");
        }

        String memberPassword1      = ParamUtil.getParameterPassword(request, "MemberMatkhau", 3, 0);
        String memberPassword2      = ParamUtil.getParameterPassword(request, "MemberMatkhauConfirm", 3, 0);
        if (!memberPassword1.equals(memberPassword2)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.confirmed_password_is_not_match");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Password and confirmed password are not the same, please try again.");
        }
        String memberPassword       = Encoder.getMD5_Base64(memberPassword1);

        DAOFactory.getMemberDAO().updatePassword(memberID, memberPassword);
        DAOFactory.getMemberDAO().updateTempPassword(memberID, "");// reset the temp password
    }

    void sendActivateCode(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException,
        MessagingException, IOException, TemplateException {

        Locale locale = I18nUtil.getLocaleInRequest(request);
        int memberID = 0;
        String memberName       = ParamUtil.getParameter(request, "MemberName", true);
        StringUtil.checkGoodName(memberName);
        String memberEmail = ParamUtil.getParameterEmail(request, "MemberEmail");

        // we find the email of this memberID, not the provided email
        try {
            memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
            throw new ObjectNotFoundException(localizedMessage);
        }

        // Check if the email is correct
        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
        if (!memberEmail.equalsIgnoreCase(memberBean.getMemberEmail())) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.provided_email_not_equals_member_email");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Your provided email does not equals to the member's email in our database. Please try again.");
        }

        // end check, send mail now
        String serverName = ParamUtil.getServerPath();//ParamUtil.getServer2(request);
        SendMailUtil.sendActivationCodeEmail(memberID, serverName);
    }

    void activateMember(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException,
        AuthenticationException, AssertionException {

        String memberName = ParamUtil.getParameter(request, "member", true);
        StringUtil.checkGoodName(memberName);
        Locale locale = I18nUtil.getLocaleInRequest(request);

        // IMPORTANT: MUST check that ActivateCode is not empty, because ActivateCode = empty
        // means invalid
        String memberActivateCode = ParamUtil.getParameter(request, "activatecode", true);
        if (memberActivateCode.equals(MemberBean.MEMBER_ACTIVATECODE_ACTIVATED)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_activate.invalid_activation_code");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Cannot activate member with invalid activation code.");
        }
        int memberID = 0;
        try {
            memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
            throw new ObjectNotFoundException(localizedMessage);
        }

        // Now, check that this member is not activated, to prevent the
        // situation that other people try to annoy this member
        if (DAOFactory.getMemberDAO().getActivateCode(memberID).equals(MemberBean.MEMBER_ACTIVATECODE_ACTIVATED)) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_activate.is_activated_member");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Cannot activate an activated member.");
        }

        String currentActivateCode = DAOFactory.getMemberDAO().getActivateCode(memberID);
        if (memberActivateCode.equals(currentActivateCode) == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_activate.wrong_activation_code");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Your activation code is not correct, please try the Member Account Activation feature.");
        }

        DAOFactory.getMemberDAO().updateActivateCode(memberID, MemberBean.MEMBER_ACTIVATECODE_ACTIVATED);// activate member

        // now reload the permission if this online user is the activated user
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        if (memberID == onlineUser.getMemberID()) {
            onlineUser.reloadPermission();
        }
    }

/*************************************************
 * For public view
 *************************************************/
    void prepareView_forPublic(HttpServletRequest request)
        throws BadInputException, ObjectNotFoundException, DatabaseException {

        String memberName = ParamUtil.getParameter(request, "member", false);
        Locale locale = I18nUtil.getLocaleInRequest(request);
        // primary key column(s)
        int memberID = -1;
        if (memberName.length() == 0) {
            memberID = ParamUtil.getParameterInt(request, "memberid");
        } else {// has MemberName
            /**@todo: improve this for better performance(dont use this method,
             * and write 2 new methods)*/
            StringUtil.checkGoodName(memberName);// check for better security
            try {
                memberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.membername_not_exists", new Object[] {memberName});
                throw new ObjectNotFoundException(localizedMessage);
            }
        }

        try {
            DAOFactory.getMemberDAO().increaseViewCount(memberID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.memberid_not_exists", new Object[] {new Integer(memberID)});
            throw new ObjectNotFoundException(localizedMessage);
        }

        MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forPublic(memberID);

        request.setAttribute("MemberBean", memberBean);
    }

    /**
     * This method supports sorting base on many criteria
     */
    void prepareListMembers_forPublic(HttpServletRequest request)
        throws DatabaseException, AssertionException, BadInputException, AuthenticationException {

        Locale locale = I18nUtil.getLocaleInRequest(request);
        if (MVNForumConfig.getEnableListMembers() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.list_members_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot list members because LIST_MEMBERS feature is disabled by administrator.");
        }

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        //MVNForumPermission permission = onlineUser.getPermission();
        //@todo: some permission checking is needed ???

        // for sort and order stuff
        String sort  = ParamUtil.getParameter(request, "sort");
        String order = ParamUtil.getParameter(request, "order");
        if (sort.length() == 0) sort = "MemberCreationDate";
        if (order.length()== 0) order = "DESC";

        // we continue
        int postsPerPage = onlineUser.getPostsPerPage();
        int offset = 0;
        try {
            offset = ParamUtil.getParameterInt(request, "offset");
        } catch (BadInputException e) {
            // do nothing
        }

        int totalMembers = DAOFactory.getMemberDAO().getNumberOfMembers();
        if (offset > totalMembers) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.offset_greater_than_total_rows");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("The offset is not allowed to be greater than total rows.");
        }

        Collection memberBeans = DAOFactory.getMemberDAO().getMembers_withSortSupport_limit(offset, postsPerPage, sort, order);

        request.setAttribute("MemberBeans", memberBeans);
        request.setAttribute("TotalMembers", new Integer(totalMembers));
    }

    // just for showing member's avatar
    public void getAvatar(HttpServletRequest request, HttpServletResponse response)
        throws BadInputException, DatabaseException, IOException {

        if (MVNForumConfig.getEnableAvatar() == false) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        int memberID = ParamUtil.getParameterInt(request, "memberid");

        MemberBean member = null;
        try {
            member = DAOFactory.getMemberDAO().getMember_forPublic(memberID);
        } catch (ObjectNotFoundException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String memberAvatar = member.getMemberAvatar();
        if (memberAvatar.equals(MemberBean.MEMBER_AVATAR_USING_UPLOAD) ||
            memberAvatar.startsWith(MVNForumGlobal.UPLOADED_AVATAR_DIR)) {
            memberAvatar = member.getMemberName() + ".jpg";
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String imageMimeType = "image/jpeg";

        File avatarFile = new File(MVNForumConfig.getAvatarDir() + File.separator + memberAvatar);
        if (!avatarFile.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (!avatarFile.isFile()) {
            response.sendError(HttpServletResponse.SC_NO_CONTENT);
            return;
        }

        long lastModified = avatarFile.lastModified();
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        //log.debug("\n ** Last Modified : " + lastModified + " If Modified Since : " + ifModifiedSince + " **");
        if (ifModifiedSince != -1) {
            if (/*(request.getHeader("If-None-Match") == null)
                && */(lastModified <= ifModifiedSince )) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }

        OutputStream outputStream = null;
        try {
            String httpModified = DateUtil.getHTTPHeaderTime(new Date(lastModified));
            response.setContentType(imageMimeType);
            response.setHeader("Location", memberAvatar);
            response.setHeader("Last-Modified", httpModified);
            //response.setHeader("Content-Disposition", "attachment; filename=" + memberAvatar);//always download
            //response.setHeader("Content-Length", String.valueOf(avatarFile.length()));//problem with compression

            // now, the header inited, just write the file content on the output
            try {
                outputStream = response.getOutputStream();
                FileUtil.popFile(avatarFile, outputStream);
            } catch (IOException ex) {
                // cannot throw Exception after we output to the response
                log.error("Error while trying to send avatar from server", ex);
            }

            outputStream.flush();
            outputStream.close();
            outputStream = null;// no close twice
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) { }
            }
        }
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.