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/auth/OnlineUserImpl.java,v 1.32 2005/02/05 23:18:35 gbs Exp $
 * $Author: gbs $
 * $Revision: 1.32 $
 * $Date: 2005/02/05 23:18:35 $
 *
 * ====================================================================
 *
 * 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.auth;

import java.awt.image.BufferedImage;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.util.DateUtil;
import net.myvietnam.mvncore.util.ParamUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mvnforum.*;
import com.mvnforum.common.MVNCaptchaService;
import com.mvnforum.db.*;
import com.octo.captcha.image.ImageCaptcha;

class OnlineUserImpl implements OnlineUser {

    private static long CHECK_NEW_MESSAGE_INTERVAL = 5 * DateUtil.MINUTE;// five minutes

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

    private int memberID = MVNForumConstant.MEMBER_ID_OF_GUEST;

    private String memberName = "";

    private int authenticationType = AUTHENTICATION_TYPE_UNAUTHENTICATED;

    private MVNForumPermission permission = null;

    private OnlineUserAction onlineUserAction = new OnlineUserAction();

    private int memberPostsPerPage = 10;
    private int memberMessagesPerPage = 10;

    private boolean invisible = false;

    private int newMessageCount = 0;

    private String memberCssPath = null;
    private String memberLogoPath = null;

    private int hourOffset = 0;
    /* private DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     * Igor: previous line should be: new SimpleDateFormat(..., Locale.US)
     * Otherwise won't work for users who don't have en/US as default.
     */
    private DateFormat timestampFormatter = null;
    private DateFormat dateFormatter = null;

    private Timestamp lastLogonTimestamp = null;

    private Timestamp lastCheckNewMessageTimestamp = null;

    private String lastLogonIP = null;

    private String localeName = "";

    private Locale locale = null;

    private boolean gender = true;

    private ImageCaptcha imageCaptcha = null;

    /**
     * Default access constructor, prevent outsite creation
     * NOTE: the implementation should init the following:
     * - Is Guest or not <br/>
     * - Call initRemoteAddr_UserAgent() <br/>
     * - The memberCssPath <br/>
     * - The memberLogoPath <br/>
     */
    OnlineUserImpl(HttpServletRequest request, boolean isGuest) throws DatabaseException {
        if (isGuest) {
            setMemberID(MVNForumConstant.MEMBER_ID_OF_GUEST);
            setMemberName(MVNForumConfig.getDefaultGuestName());
        }
        getOnlineUserAction().initRemoteAddr_UserAgent(request);
        String contextPath = request.getContextPath();
        memberCssPath = contextPath + MVNForumGlobal.CSS_FULLPATH;
        memberLogoPath = contextPath + MVNForumGlobal.LOGO_FULLPATH;
        if (isGuest && MVNForumConfig.getEnableCompany()) {
            try {
                int companyID = ParamUtil.getParameterInt(request, "companyid");
                CompanyBean companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);

                // Load the css Path for this user
                memberCssPath = MyUtil.getCompanyCssPath(companyBean, request.getContextPath());

                // Load the logo Path for this user
                memberLogoPath = MyUtil.getCompanyLogoPath(companyBean, request.getContextPath());
            } catch (ObjectNotFoundException ex) {
                // cannot find the Company in the database, just ignore
            } catch (BadInputException ex) {
                // cannot find the companyid in the request, just ignore
            }
        }
    }

    public int getMemberID() {
        return memberID;
    }

    public String getMemberName() {
        return memberName;
    }

    public boolean isGuest() {
        return ( (memberID==0) || (memberID==MVNForumConstant.MEMBER_ID_OF_GUEST) );
    }

    public boolean isMember() {
        return !isGuest();
    }

    public boolean isInvisibleMember() {
        // @todo: temp implementation
        return this.invisible;
    }

    public int getAuthenticationType() {
        return authenticationType;
    }

    public MVNForumPermission getPermission() {
        return permission;
    }

    public void reloadPermission() {
        try {
            if (isGuest()) {
                permission = MVNForumPermissionFactory.getAnonymousPermission();
            } else {
                permission = MVNForumPermissionFactory.getAuthenticatedPermission(memberID);
            }
        } catch (Exception ex) {
            log.error("Error when reload permission in OnlineUserImpl for memberID = " + memberID , ex);
        }
    }

    public void reloadProfile() {
        try {
            if (isGuest()) {
                // currently just do nothing, implement later
            } else {
                MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);

                int timeZone = memberBean.getMemberTimeZone();
                localeName = memberBean.getMemberLanguage();
                int postsPerPage = memberBean.getMemberPostsPerPage();

                setTimeZone(timeZone);
                setLocaleName(localeName);
                setGender(memberBean.getMemberGender() != 0);
                setPostsPerPage(postsPerPage);
                setInvisible(memberBean.isInvisible());
            }
        } catch (Exception ex) {
            log.error("Error when reload profile in OnlineUserImpl for memberID = " + memberID , ex);
        }
    }

    public boolean updateNewMessageCount(boolean forceUpdate) {

        if (isGuest()) return false;

        int currentMessageCount = newMessageCount;
        Timestamp now = DateUtil.getCurrentGMTTimestamp();
        long lastRequest = 0;
        if (lastCheckNewMessageTimestamp != null ) {
            lastRequest = lastCheckNewMessageTimestamp.getTime();
        }
        if ((lastCheckNewMessageTimestamp == null) ||
            forceUpdate ||
            ((lastRequest + CHECK_NEW_MESSAGE_INTERVAL) <= now.getTime())) {
            try {
                lastCheckNewMessageTimestamp = now;
                newMessageCount = DAOFactory.getMessageDAO().getNumberOfUnreadNonPublicMessages_inMember_inFolder(memberID, MVNForumConstant.MESSAGE_FOLDER_INBOX);
                if (currentMessageCount < newMessageCount) {
                    return true;
                }
            } catch (Exception ex) {
                log.error("Error when udpate new message count in OnlineUserImpl for memberID = " + memberID , ex);
            }
        }
        return false;
    }

    public OnlineUserAction getOnlineUserAction() {
        return onlineUserAction;
    }

    public java.util.Date convertGMTDate(java.util.Date gmtDate) {
        return DateUtil.convertGMTDate(gmtDate, hourOffset);
    }

    public Timestamp convertGMTTimestamp(Timestamp gmtTimestamp) {
        return DateUtil.convertGMTTimestamp(gmtTimestamp, hourOffset);
    }

    public String getGMTDateFormat(java.util.Date gmtDate) {
       return getGMTDateFormat(gmtDate, true);
    }

    public String getGMTDateFormat(java.util.Date gmtDate, boolean adjustTimeZone) {
        if (gmtDate == null) return "";

        java.util.Date date = gmtDate;
        if (adjustTimeZone) {
            date = DateUtil.convertGMTDate(gmtDate, hourOffset);
        }
        return dateFormatter.format(date);
    }

    public String getGMTTimestampFormat(Timestamp gmtTimestamp) {
       return getGMTTimestampFormat(gmtTimestamp, true);
    }

    public String getGMTTimestampFormat(Timestamp gmtTimestamp, boolean adjustTimeZone) {
        if (gmtTimestamp == null) return "";

        Timestamp timestamp = gmtTimestamp;
        if (adjustTimeZone) {
            timestamp = DateUtil.convertGMTTimestamp(gmtTimestamp, hourOffset);
        }
        return timestampFormatter.format(timestamp);
    }

    public String getLocaleName() {
        return localeName;
    }

    public Locale getLocale() {
        return locale;
    }

    public String getLastLogonIP() {
        if (isGuest()) {
            return "";
         }
        return lastLogonIP;
    }

    public Timestamp getLastLogonTimestamp() {
        return lastLogonTimestamp;
    }

/*
    public boolean getGender() {
        return gender;
    }
*/
    public int getPostsPerPage() {
        return memberPostsPerPage;
    }

    public int getMessagesPerPage() {
        return memberMessagesPerPage;
    }

    public int getNewMessageCount() {
        return newMessageCount;
    }

    public String getCssPath() {
        return memberCssPath;
    }

    public String getLogoPath() {
        return memberLogoPath;
    }

    /**
     * Build a new captcha, this method must be called before using some
     * action that need captcha validation.
     */
    public void buildNewCaptcha() {
        destroyCurrentCaptcha();

        // this line of code could throw Exception in case the captcha image
        // is small to hold the whole captcha
        imageCaptcha = MVNCaptchaService.getInstance().getNextImageCaptcha();
    }

    /**
     * Destroy the current captcha, this method must be called after validate
     * the captcha
     */
    public void destroyCurrentCaptcha() {
        imageCaptcha = null;
    }

    /**
     * Get the captcha image to challenge the user
     *
     * @return BufferedImage the captcha image to challenge the user
     */
    public BufferedImage getCurrentCaptchaImage() {
        if (imageCaptcha == null) {
            return null;
        }
        return (BufferedImage)(imageCaptcha.getChallenge());
    }

    /**
     * Validate the anwser of the captcha from user
     *
     * @param anwser String the captcha anwser from user
     * @return boolean true if the answer is valid, otherwise return false
     */
    public boolean validateCaptchaResponse(String anwser) {
        if (imageCaptcha == null) {
            return false;
        }
        anwser = anwser.toUpperCase();//use upper case for easier usage
        return (imageCaptcha.validateResponse(anwser)).booleanValue();
    }

    /**
     * Check to make sure that the captcha answer is correct
     *
     * @param answer String the captcha answer to check
     * @throws BadInputException in case the captcha answer is not correct
     */
    public void ensureCorrectCaptchaResponse(String answer)
        throws BadInputException {

        if (validateCaptchaResponse(answer) == false) {
            throw new BadInputException(MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_captcha"));
        }
    }

/*****************************************************************
 * Default-scope methods, only for internal package usage
 *****************************************************************/
    void setMemberID(int memberID) {
        if (memberID == 0) {
            this.memberID = MVNForumConstant.MEMBER_ID_OF_GUEST;
        } else {
            this.memberID = memberID;
        }
        onlineUserAction.setMemberID(this.memberID);
    }

    void setMemberName(String memberName) {
        this.memberName = memberName;
        onlineUserAction.setMemberName(memberName);
    }

    void setInvisible(boolean invisible) {
        this.invisible = invisible;
        onlineUserAction.setMemberInvisible(invisible);
    }

    void setAuthenticationType(int authType) {
        authenticationType = authType;
    }

    /**
     * NOTE: this method SHOULD ONLY BE CALLED from OnlineUserFactory
     */
    void setPermission(MVNForumPermission permission) {
        this.permission = permission;
    }

    void setTimeZone(int timeZone) {
        if ( (timeZone >= -12) && (timeZone <= 12) ) {
            this.hourOffset = timeZone;
        }
    }

    void setLocaleName(String localeName) {
        this.localeName = localeName;

        if (localeName.length() == 0) {
            this.localeName = MVNForumConfig.getDefaultLocaleName();
            this.locale = MVNForumConfig.getDefaultLocale();
        } else {
            locale = MyUtil.getLocale(localeName);
        }

        // now init the 2 class variables
        dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        timestampFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
    }

    void setLastLogonTimestamp(Timestamp lastLogon) {
        lastLogonTimestamp = lastLogon;
    }

    void setLastLogonIP(String lastLogonIP) {
        this.lastLogonIP = lastLogonIP;
    }

    void setGender(boolean gender) {
        this.gender = gender;
    }

    void setPostsPerPage(int postsPerPage) {
        if (postsPerPage < 5) {
            postsPerPage = 5;
        }
        this.memberPostsPerPage = postsPerPage;
    }

    public void setCssPath(String cssPath) {
        this.memberCssPath = cssPath;
    }

    public void setLogoPath(String logoPath) {
        this.memberLogoPath = logoPath;
    }

}
... 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.