home | 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/WatchWebHandler.java,v 1.23 2005/01/26 18:46:53 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.23 $
 * $Date: 2005/01/26 18:46:53 $
 *
 * ====================================================================
 *
 * 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.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.*;

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

import com.mvnforum.MVNForumConfig;
import com.mvnforum.MVNForumResourceBundle;
import com.mvnforum.auth.*;
import com.mvnforum.db.*;
import freemarker.template.TemplateException;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class WatchWebHandler {

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

    private OnlineUserManager userManager = OnlineUserManager.getInstance();

    //private DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.DEFAULT, SimpleDateFormat.DEFAULT);

    WatchWebHandler() {
    }

    void sendMail()
        throws AssertionException, DatabaseException, MessagingException, BadInputException, ObjectNotFoundException, TemplateException, IOException {

        if (MVNForumConfig.getEnableWatch() == false) {
            log.warn("Ingore Watch sendMail because this feature is disabled by administrator.");
            return;
        }
        String forumBase = ParamUtil.getServerPath() + ParamUtil.getContextPath() + UserModuleConfig.getUrlPattern();
        //log.debug("Forum base = " + forumBase);

        //get the list of watch for each member, the watch is choosen based on oldest lastsent time
        Collection beans = DAOFactory.getWatchDAO().getMemberBeans();
        //log.debug("Watch: total member = " + beans.size());
        Iterator iterator = beans.iterator();
        while (iterator.hasNext()) {
            WatchBean watchBean = (WatchBean)iterator.next();
            int memberID = watchBean.getMemberID();

            // check if member is enable here
            if (DAOFactory.getMemberDAO().getActivateCode(memberID).equals(MemberBean.MEMBER_ACTIVATECODE_ACTIVATED) == false) {
                // Not activated, then we continue with the next user
                continue;
            }

            // Check the frequency of the update
            Timestamp lastSent = watchBean.getWatchLastSentDate();
            Timestamp now = DateUtil.getCurrentGMTTimestamp();

            // We will now support a single watch standard, but should be
            // bitmasked in future to support multiple watch schedule for the same
            // thread or forum
            long minimumWaitTime = 0;
            int watchOption = watchBean.getWatchOption();
            if (watchOption == WatchBean.WATCH_OPTION_DEFAULT) {
                watchOption = MVNForumConfig.getDefaultWatchOption();
            }

            switch (watchOption) {
                case WatchBean.WATCH_OPTION_LIVE:
                    minimumWaitTime = 0;
                    break;
                case WatchBean.WATCH_OPTION_HOURLY:
                    minimumWaitTime = DateUtil.HOUR;
                    break;
                case WatchBean.WATCH_OPTION_DAILY:
                    minimumWaitTime = DateUtil.DAY;
                    break;
                case WatchBean.WATCH_OPTION_WEEKLY:
                    minimumWaitTime = DateUtil.WEEK;
                    break;
                default:// currently only default is processed (WatchOption = 0)
                    // note that watch option might have any value so we have to have default fallback
                    minimumWaitTime = DateUtil.DAY;
                    break;
            }
            if ( (now.getTime() - lastSent.getTime()) > minimumWaitTime ) {
                sendMail_forMember(memberID, forumBase, lastSent);
            }
        }
    }

    void sendMail_forMember(int memberID, String forumBase, Timestamp lastSent)
        throws AssertionException, DatabaseException, MessagingException, BadInputException, ObjectNotFoundException, TemplateException, IOException {

        MVNForumPermission permission = null;
        try {
            permission = MVNForumPermissionFactory.getAuthenticatedPermission(memberID);
        } catch (AssertionException e) {
            log.error("Cannot create watch mail for Guest with id = " + memberID, e);
            return;// do nothing, just return if member is guest.
        }

        if (permission.isActivated() == false) {
            // if member is not activated, then we ignore this member
            return;
        }

        Collection watchBeans = DAOFactory.getWatchDAO().getWatches_forMember(memberID);
        //log.debug("Watch size = " + watchBeans.size() + " for memberid = " + memberID);
        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        MemberBean receiver = null;
        try {
            receiver = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
        } catch (ObjectNotFoundException e) {
            log.error("Cannot get member with id = " + memberID, e);
            return;// do nothing just return if member does not exist
        }

        //then optimize the watchBeans
        watchBeans = WatchUtil.optimize(watchBeans);

        WatchMail watchMail = new WatchMail(receiver, permission, forumBase, lastSent, now);

        for (Iterator watchIterator = watchBeans.iterator(); watchIterator.hasNext(); ) {
            WatchBean watchBean = (WatchBean)watchIterator.next();
            watchMail.appendWatch(watchBean);
        }

        if (watchMail.haveAtLeastOneNewThread()) {
            // send mail now
            String from = MVNForumConfig.getWebMasterEmail(); //use the default MailFrom value
            String to = receiver.getMemberEmail();
            String subject = watchMail.getWatchSubject();
            String content = watchMail.getMailContent();
            //log.debug("Send message from websmater to ~ " + to + "~");
            try {
                MailUtil.sendMail(from, to, "" /*cc*/, "" /*bcc*/, subject, content);
            } catch (UnsupportedEncodingException e) {
                log.error("Cannot support encoding", e);
            }

            // finally, update the lastsent
            DAOFactory.getWatchDAO().updateLastSentDate_forMember(memberID, now);
        } else {
            log.debug("No new thread for MemberID = " + memberID);
        }
    }

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

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

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

        Collection watchBeans = DAOFactory.getWatchDAO().getWatches_forMember(memberID);

        Collection globalWatchBeans = WatchUtil.getGlobalWatchs(watchBeans);
        Collection categoryWatchBeans = WatchUtil.getCategoryWatchs(watchBeans);
        Collection forumWatchBeans = WatchUtil.getForumWatchs(watchBeans);
        Collection threadWatchBeans = WatchUtil.getThreadWatchs(watchBeans);

        // @todo Improve the performance of the below code
        for (Iterator iter = threadWatchBeans.iterator(); iter.hasNext(); ) {
            WatchBean threadWatchBean = (WatchBean)iter.next();
            int threadID = threadWatchBean.getThreadID();

            ThreadBean threadBean = null;
            try {
                threadBean = DAOFactory.getThreadDAO().getThread(threadID);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.threadid_not_exists", new Object[] {new Integer(threadID)});
                throw new ObjectNotFoundException(localizedMessage);
            }
            threadWatchBean.setThreadBean(threadBean);
        }

        request.setAttribute("WatchBeans", watchBeans);
        request.setAttribute("GlobalWatchBeans", globalWatchBeans);
        request.setAttribute("CategoryWatchBeans", categoryWatchBeans);
        request.setAttribute("ForumWatchBeans", forumWatchBeans);
        request.setAttribute("ThreadWatchBeans", threadWatchBeans);
    }

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

        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (MVNForumConfig.getEnableWatch() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_add_watch.watch_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot add Watch because Watch feature is disabled by administrator.");
        }

        OnlineUser onlineUser = userManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        if (MVNForumConfig.getEnableCompany() == false) {
            permission.ensureIsActivated();
        }
    }

    void processAdd(HttpServletRequest request)
        throws BadInputException, CreateException, DatabaseException, ObjectNotFoundException,
        ForeignKeyNotFoundException, AuthenticationException, AssertionException {

        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (MVNForumConfig.getEnableWatch() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_add_watch.watch_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot add Watch because Watch feature is disabled by administrator.");
        }

        OnlineUser onlineUser = userManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        if (MVNForumConfig.getEnableCompany() == false) {
            permission.ensureIsActivated();
        }

        Timestamp now = DateUtil.getCurrentGMTTimestamp();

        int memberID = onlineUser.getMemberID();
        int categoryID              = 0;
        int forumID                 = 0;
        int threadID                = 0;
        int watchType               = 0;//ParamUtil.getParameterInt(request, "WatchType");
        int watchOption             = WatchBean.WATCH_OPTION_DEFAULT;//ParamUtil.getParameterInt(request, "WatchOption");
        int watchStatus             = 0;//ParamUtil.getParameterInt(request, "WatchStatus");
        Timestamp watchCreationDate = now;
        Timestamp watchLastSentDate = now;
        Timestamp watchEndDate      = now;// @todo: check it !!!

        int watchSelector = ParamUtil.getParameterInt(request, "WatchSelector");
        switch (watchSelector) {
            case 0:
                break;
            case 1:
                categoryID = ParamUtil.getParameterInt(request, "category");
                break;
            case 2:
                forumID = ParamUtil.getParameterInt(request, "forum");
                ForumCache.getInstance().getBean(forumID).ensureNotDisabledForum();
                break;
            case 3:
                threadID = ParamUtil.getParameterInt(request, "thread");
                DAOFactory.getThreadDAO().findByPrimaryKey(threadID);
                break;
            default:
                // please do not localize this
                throw new AssertionException("Cannot process WatchSelector = " + watchSelector);
        }

        try {
            DAOFactory.getWatchDAO().create(memberID, categoryID, forumID,
                                       threadID, watchType, watchOption,
                                       watchStatus, watchCreationDate, watchLastSentDate,
                                       watchEndDate);
        } catch (DuplicateKeyException ex) {
            // User try to create a duplicate watch, just ignore
        }
    }

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

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

        int memberID = onlineUser.getMemberID();

        Locale locale = I18nUtil.getLocaleInRequest(request);

        // primary key column(s)
        int watchID = ParamUtil.getParameterInt(request, "watch");

        WatchBean watchBean = DAOFactory.getWatchDAO().getWatch(watchID);

        // check if the watch is owned by the current member
        if (watchBean.getMemberID() != memberID) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_delete.watch_is_not_owned_by_current_member");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("Cannot delete watch: this watch is not owned by the current member.");
        }

        //now delete the watch
        DAOFactory.getWatchDAO().delete(watchID);
    }
}


my book on functional programming

 

new blog posts

 

Copyright 1998-2019 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.