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/admin/GeneralAdminTasksWebHandler.java,v 1.63 2005/01/26 18:46:51 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.63 $
 * $Date: 2005/01/26 18:46:51 $
 *
 * ====================================================================
 *
 * 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
 * @author: Igor Manic   imanic@users.sourceforge.net
 */
package com.mvnforum.admin;

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

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.company.CompanyIndexer;
import com.mvnforum.search.member.MemberIndexer;
import com.mvnforum.search.post.*;
import freemarker.template.*;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.filter.HtmlNewLineFilter;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class GeneralAdminTasksWebHandler {

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

    private OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();

    GeneralAdminTasksWebHandler() {
    }

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

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

        Timestamp now = DateUtil.getCurrentGMTTimestamp();
        Timestamp startTimestamp = MVNForumContextListener.getInstance().getStartTimestamp();
        long upTime = now.getTime() - startTimestamp.getTime();

        request.setAttribute("StartTime", onlineUser.getGMTTimestampFormat(startTimestamp));
        request.setAttribute("NowTime", onlineUser.getGMTTimestampFormat(now));
        request.setAttribute("UpTime", DateUtil.formatDuration(upTime));
    }

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

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

    public void changeShowUserArea(HttpServletRequest request)
        throws DatabaseException, AuthenticationException,
        BadInputException, AssertionException {

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

        String mode = ParamUtil.getParameterSafe(request, "mode", true);

        if (mode.equals("on")) {
            MVNForumConfig.setShouldShowUserArea(true);
        } else if (mode.equals("off")) {
            MVNForumConfig.setShouldShowUserArea(false);
        } else {
            throw new AssertionException("Not support this mode " + mode);
        }
    }

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

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

        request.setAttribute("BackupFilesOnServer", ImportWebHandler.getBackupFilesOnServer());
    }

    void importXmlZip(HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, AssertionException, AuthenticationException, ImportException {

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

        ImportWebHandler.importXmlZip(request, response);
    }

    void exportXmlZip(HttpServletRequest request)
        throws DatabaseException, AssertionException, AuthenticationException, ExportException {

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

        ExportWebHandler.exportXmlZip(request);
    }

    void getExportXmlZip(HttpServletRequest request, HttpServletResponse response)
        throws BadInputException, DatabaseException, AssertionException, AuthenticationException, IOException {

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

        ExportWebHandler.getExportXmlZip(request, response);
    }

    void deleteExportXmlZip(HttpServletRequest request)
        throws BadInputException, DatabaseException, AssertionException, AuthenticationException, IOException {

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

        ExportWebHandler.deleteExportXmlZip(request);
        //now prepare all for redirection to "/importexport"
        request.setAttribute("BackupFilesOnServer", ImportWebHandler.getBackupFilesOnServer());
    }

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

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

        int postNumDocs = PostIndexer.getNumDocs();
        int memberNumDocs = MemberIndexer.getNumDocs();
        int companyNumDocs = -1;
        if (MVNForumConfig.getEnableCompany()) {
            companyNumDocs = CompanyIndexer.getNumDocs();
        }

        int postCount = DAOFactory.getPostDAO().getNumberOfPosts();
        int memberCount = DAOFactory.getMemberDAO().getNumberOfMembers();
        int companyCount = 0;
        if (MVNForumConfig.getEnableCompany()) {
            companyCount = DAOFactory.getCompanyDAO().getNumberOfCompanies();
        }

        request.setAttribute("PostNumDocs", new Integer(postNumDocs));
        request.setAttribute("PostCount", new Integer(postCount));

        request.setAttribute("MemberNumDocs", new Integer(memberNumDocs));
        request.setAttribute("MemberCount", new Integer(memberCount));

        request.setAttribute("CompanyNumDocs", new Integer(companyNumDocs));
        request.setAttribute("CompanyCount", new Integer(companyCount));
    }

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

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

        String target = ParamUtil.getParameter(request, "target");

        if (target.equalsIgnoreCase("post")) {
            if ( !RebuildPostIndexTask.isRebuilding()) {
                PostIndexer.scheduleRebuildIndexTask();
            }
        } else if (target.equalsIgnoreCase("member")) {
            MemberIndexer.scheduleRebuildIndexTask();
        } else if (target.equalsIgnoreCase("company") && MVNForumConfig.getEnableCompany()) {
            CompanyIndexer.scheduleRebuildIndexTask();
        } else if (target.length() == 0) {
            PostIndexer.scheduleRebuildIndexTask();
            MemberIndexer.scheduleRebuildIndexTask();
            if (MVNForumConfig.getEnableCompany()) {
                CompanyIndexer.scheduleRebuildIndexTask();
            }
        }
    }

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

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

        Locale locale = I18nUtil.getLocaleInRequest(request);
        boolean isPreviewing = ParamUtil.getParameterBoolean(request, "preview");

        if (isPreviewing) {
            ParamUtil.getParameterEmail(request, "From");//just call to check the validity of From
            String to = ParamUtil.getParameter(request, "To");
            String cc = ParamUtil.getParameter(request, "Cc");
            String bcc = ParamUtil.getParameter(request, "Bcc");
            String subject = ParamUtil.getParameter(request, "Subject", true);
            String message = ParamUtil.getParameter(request, "Message", true);

            int mailToSelector = ParamUtil.getParameterInt(request, "MailToSelector");

            String warningMessage = "";

            String previewMessage = message;
            String previewSubject = subject;

            if (mailToSelector == 0) { // that is, send to specific users
                if ((to.length() == 0) && (cc.length() == 0) && (bcc.length() == 0)) {
                    String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.please_enter_to_or_cc_or_bcc");
                    throw new BadInputException(localizedMessage);
                    //throw new BadInputException("Please enter at least To, CC or BCC.");
                }
            } else { // send to group of users
                // Then add members coresponding to the mailToSelector
                String kind;
                int groupID = -1;
                switch (mailToSelector) {
                    case 1:
                        kind = "all";
                        groupID = ParamUtil.getParameterInt(request, "group");
                        to = "Group: " + DAOFactory.getGroupsDAO().getGroup(groupID).getGroupName();
                        break;
                    case 2:
                        kind = "activated";
                        to = "All activated members";
                        break;
                    case 3:
                        kind = "nonactivated";
                        to = "All non-activated members";
                        break;
                    default:
                        String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_process_mailto_selector", new Object[] {new Integer(mailToSelector)});
                        throw new BadInputException(localizedMessage);
                        //throw new BadInputException("Cannot process MailToSelector = " + mailToSelector);
                }

                Collection memberBeans = null;

                if (kind.equals("all")) {
                    if (groupID == MVNForumConstant.GROUP_ID_OF_REGISTERED_MEMBERS) {
                        memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inActivationStatus("all");
                    } else if (groupID <= MVNForumConstant.LAST_RESERVED_GROUP_ID) {
                        String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_list_member_in_reserved_group");
                        throw new AssertionException(localizedMessage);
                        //throw new AssertionException("Cannot list member in a reserved (virtual) group.");
                    } else {
                        memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inGroup(groupID);
                    }
                } else {
                    memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inActivationStatus(kind);
                }

                if (memberBeans.size() > 0 ) {
                    warningMessage = String.valueOf(memberBeans.size() + " members");
                } else {
                    warningMessage = "No members";
                }
                MemberBean previewedMember = null;
                for(Iterator iterator = memberBeans.iterator();iterator.hasNext();) {
                    previewedMember = (MemberBean)iterator.next();
                    previewMessage = processMailTemplate(previewedMember, message);
                    previewSubject = processMailTemplate(previewedMember, subject);
                    request.setAttribute("PreviewEmail", previewedMember.getMemberEmail());
                    break;
                }
            }// end of send to a group of users
            request.setAttribute("PreviewTo", to);
            request.setAttribute("PreviewCc", cc);
            request.setAttribute("PreviewBcc", bcc);
            request.setAttribute("PreviewSubject", previewSubject);
            request.setAttribute("PreviewMessage", HtmlNewLineFilter.filter(previewMessage));
            request.setAttribute("WarningMessage",  warningMessage);
        }

        Collection groupBeans = DAOFactory.getGroupsDAO().getGroups();
        for(Iterator iterator = groupBeans.iterator(); iterator.hasNext();) {
            GroupsBean groupBean = (GroupsBean)iterator.next();
            if (groupBean.getGroupID() == MVNForumConstant.GROUP_ID_OF_GUEST) {
                iterator.remove();
                break;
            }
        }
        request.setAttribute("GroupBeans", groupBeans);
    }

    void sendMail(HttpServletRequest request)
        throws BadInputException, MessagingException, DatabaseException,
        AuthenticationException, AssertionException {

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

        Locale locale = I18nUtil.getLocaleInRequest(request);

        String from = ParamUtil.getParameterEmail(request, "From");
        String to = ParamUtil.getParameter(request, "To");
        String cc = ParamUtil.getParameter(request, "Cc");
        String bcc = ParamUtil.getParameter(request, "Bcc");
        String subject = ParamUtil.getParameter(request, "Subject", true);
        String message = ParamUtil.getParameter(request, "Message", true);

        int mailToSelector = ParamUtil.getParameterInt(request, "MailToSelector");

        Collection mailMessageStructs = new ArrayList();
        if (mailToSelector == 0) { // that is, send to specific users
            if ((to.length() == 0) && (cc.length() == 0) && (bcc.length() == 0)) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.please_enter_to_or_cc_or_bcc");
                throw new BadInputException(localizedMessage);
                //throw new BadInputException("Please enter at least To, CC or BCC.");
            }
            MailMessageStruct mailMessageStruct = new MailMessageStruct();
            mailMessageStruct.setFrom(from);
            mailMessageStruct.setTo(to);
            mailMessageStruct.setCc(cc);
            mailMessageStruct.setBcc(bcc);
            mailMessageStruct.setSubject(subject);
            mailMessageStruct.setMessage(message);
            mailMessageStructs.add(mailMessageStruct);
        } else { // send to group of users
            // now add emails in the To, CC, BCC. Please note that we ONLY use the method setTo
            String[] emailArray = MailUtil.getEmails(to, cc, bcc);
            for (int i = 0; i < emailArray.length; i++) {
                MailMessageStruct mailMessage = new MailMessageStruct();
                mailMessage.setFrom(from);
                mailMessage.setTo(emailArray[i]);
                mailMessage.setSubject(subject);
                mailMessage.setMessage(message);
                mailMessageStructs.add(mailMessage);
            }

            // Then add members coresponding to the mailToSelector
            String kind;
            int groupID = -1;
            switch (mailToSelector) {
                case 1:
                    kind = "all";
                    groupID = ParamUtil.getParameterInt(request, "group");
                    break;
                case 2:
                    kind = "activated";
                    break;
                case 3:
                    kind = "nonactivated";
                    break;
                default:
                    String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.cannot_process_mailto_selector", new Object[] {new Integer(mailToSelector)});
                    throw new BadInputException(localizedMessage);
                    //throw new BadInputException("Cannot process MailToSelector = " + mailToSelector);
            }

            Collection memberBeans = null;
            if (kind.equals("all")) {
                if (groupID == MVNForumConstant.GROUP_ID_OF_REGISTERED_MEMBERS) {
                    memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inActivationStatus("all");
                } else if (groupID <= MVNForumConstant.LAST_RESERVED_GROUP_ID) {
                    String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.cannot_list_member_in_reserved_group");
                    throw new AssertionException(localizedMessage);
                    //throw new AssertionException("Cannot list member in a reserved (virtual) group.");
                } else {
                    memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inGroup(groupID);
                }
            } else {
                memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inActivationStatus(kind);
            }
            for (Iterator countIterator = memberBeans.iterator(); countIterator.hasNext(); ) {
                MemberBean memberBean = (MemberBean) countIterator.next();
                MailMessageStruct mailMessage = new MailMessageStruct();

                mailMessage.setFrom(from);
                String memberEmail = memberBean.getMemberEmail();
                String processedSubject = processMailTemplate(memberBean, subject);
                String processedMessage = processMailTemplate(memberBean, message);
                mailMessage.setTo(memberEmail);
                mailMessage.setSubject(processedSubject);
                mailMessage.setMessage(processedMessage);
                mailMessageStructs.add(mailMessage);
            } //for
        }

        try {
            MailUtil.sendMail(mailMessageStructs);
        } catch (UnsupportedEncodingException e) {
            log.error("Cannot support encoding", e);
        }
        request.setAttribute("MailMessageStructs", mailMessageStructs);
    }

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

        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanSendMail();//@todo: check if this is the correct permission

        //@todo: review this constant parameter "nonactivated"
        Collection memberBeans = DAOFactory.getMemberDAO().getEnableMembers_inActivationStatus("nonactivated");
        Collection mailMessageStructs = new ArrayList();
        String serverName = ParamUtil.getServerPath();//ParamUtil.getServer2(request);
        for (Iterator countIterator = memberBeans.iterator(); countIterator.hasNext(); ) {
            MemberBean memberBean = (MemberBean) countIterator.next();
            MailMessageStruct mailMessage = SendMailUtil.getActivationCodeEmail(memberBean.getMemberID(), serverName);
            mailMessageStructs.add(mailMessage);
        }//for

        try {
            log.debug("About to send activate mail to all non activated members, total = " + mailMessageStructs.size());
            MailUtil.sendMail(mailMessageStructs);
        } catch (UnsupportedEncodingException e) {
            log.error("Cannot support encoding", e);
        }

        request.setAttribute("MailMessageStructs", mailMessageStructs);
    }

    /**
     *Process mail with a template from User
     */
    private String processMailTemplate(MemberBean memberBean, String message) {
        try {
            Map root = new HashMap();
            StringWriter messageWriter = new StringWriter(256);

            //Just assume some variables are needed to be replaced
            root.put("memberID", new Integer(memberBean.getMemberID()));
            root.put("memberName", memberBean.getMemberName());
            root.put("memberFirstname", memberBean.getMemberFirstname());
            root.put("memberLastname", memberBean.getMemberLastname());
            root.put("memberEmail", memberBean.getMemberEmail());

            StringReader stringReader = new StringReader(message);
            Configuration cfg = MVNForumConfig.getFreeMarkerConfiguration();
            Template messageTemplate = new Template("", stringReader, cfg, "");
            messageTemplate.process(root, messageWriter);
            message = messageWriter.toString();
        } catch (IOException ioe) {
            log.error("Cannot process mail template", ioe);
            //if we have problem while processing template, we will return orginal message
        } catch (TemplateException te) {
            log.error("Cannot process mail template", te);
            //if we have problem while processing template, we will return orginal message
        }
        //log.debug("processMailTemplate return = " + message);
        return message;
    }

    public void prepareViewLogSystem(HttpServletRequest request)
        throws FileNotFoundException, DatabaseException,
        BadInputException, AuthenticationException, AssertionException, IOException {

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

        // just for checking the valid value of "linecount"
        ParamUtil.getParameterUnsignedInt(request, "linecount", 25);
        String shortName = ParamUtil.getParameterSafe(request, "filename", false);
        String logDir = MVNForumConfig.getLogDir();
        String logFileName = "";

        if (shortName.length() == 0) {
            logFileName = MVNForumConfig.getLogFile();
        } else {
            File logDirFile = new File(logDir);
            if (!logDirFile.exists()) {
                throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
            }

            if (!logDirFile.isDirectory()) {
                throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
            }
            FileUtil.checkGoodFileName(shortName);
            logFileName = logDir + File.separatorChar + shortName;
        }

        File logFile = new File(logFileName);
        if (!logFile.exists()) {
            throw new FileNotFoundException("Cannot find the log file " + logFile.getAbsolutePath());
        }

        long size = logFile.length();
        String humanSize = FileUtil.getHumanSize(size);

        request.setAttribute("FileName", shortName);
        request.setAttribute("LogDir", logDir);
        request.setAttribute("LogFileName", logFileName);
        request.setAttribute("LogFileSize", String.valueOf(size));
        request.setAttribute("LogFileHumanSize", humanSize);
    }

    public void prepareLogFrame(HttpServletRequest request)
        throws DatabaseException, AuthenticationException, IOException,
        FileNotFoundException, AssertionException, BadInputException {

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

        String logFileName = ParamUtil.getParameterSafe(request, "filename", false);

        if (logFileName.length() == 0) {
            logFileName = MVNForumConfig.getLogFile();
        } else {
            String logDir = MVNForumConfig.getLogDir();
            File logDirFile = new File(logDir);
            if (!logDirFile.exists()) {
                throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
            }

            if (!logDirFile.isDirectory()) {
                throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
            }
            FileUtil.checkGoodFileName(logFileName);
            logFileName = logDir + File.separatorChar + logFileName;
        }

        File logFile = new File(logFileName);
        if (!logFile.exists()) {
            throw new FileNotFoundException("Cannot find the log file: " + logFile.getAbsolutePath());
        }
        if (!logFile.canRead()) {
            throw new IOException("Cannot read the log file: " + logFile.getAbsolutePath());
        }

        int lineCount = ParamUtil.getParameterUnsignedInt(request, "linecount", 25); // 25, 50 100 200 400 800
        if (lineCount > 5000) {
            lineCount = 5000;
        }
        int offset = 0;
        if (offset < 0) offset = 0;

        String[] contentLog = FileUtil.getLastLines(logFile, lineCount);

        request.setAttribute("Offset", new Integer(offset));
        request.setAttribute("ContentLog", contentLog);
    }

    public void backupSystemLog(HttpServletRequest request)
        throws DatabaseException, AuthenticationException,
        IOException, FileNotFoundException, AssertionException {

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

        boolean empty = ParamUtil.getParameterBoolean(request, "empty");

        String logFileName = MVNForumConfig.getLogFile();

        String logDir = MVNForumConfig.getLogDir();
        File logDirFile = new File(logDir);
        if (!logDirFile.exists()) {
            throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
        }
        if (!logDirFile.isDirectory()) {
            throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
        }

        String pattern = "yyyy-MM-dd_HH-mm-ss";
        String newFileName = logDir + File.separator + "mvnforumlog_" + DateUtil.format(new Date(), pattern) + ".log";
        File newFile = new File(newFileName);
        // We don't have to check file here, we check it in FileUtil.copyFile
        FileUtil.copyFile(logFileName, newFileName, false);

        if (empty) {
            FileUtil.emptyFile(logFileName);
        }

        long size = newFile.length();
        String humanSize = FileUtil.getHumanSize(size);

        request.setAttribute("LogFileName", newFile.getAbsolutePath());
        request.setAttribute("LogFileSize", String.valueOf(size));
        request.setAttribute("LogFileHumanSize", humanSize);
    }

    public void prepareListLogFiles(HttpServletRequest request)
        throws DatabaseException, AuthenticationException,
        IOException, FileNotFoundException, AssertionException {

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

        String logDir = MVNForumConfig.getLogDir();
        File logDirFile = new File(logDir);
        if (!logDirFile.exists()) {
            throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
        }
        if (!logDirFile.isDirectory()) {
            throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
        }

        File[] files = logDirFile.listFiles();
        File currentLogFile = new File(MVNForumConfig.getLogFile());

        request.setAttribute("LogFiles", files);
        request.setAttribute("CurrentLogFile", currentLogFile);
    }

    public void downloadLogFile(HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, AuthenticationException, AssertionException, BadInputException, IOException {

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

        Locale locale = I18nUtil.getLocaleInRequest(request);

        // This method require fileName is not empty
        String fileName = ParamUtil.getParameterSafe(request, "filename", true);// must check empty here
        FileUtil.checkGoodFileName(fileName);

        String logDir = MVNForumConfig.getLogDir();
        File logDirFile = new File(logDir);
        if (!logDirFile.exists()) {
            throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
        }
        if (!logDirFile.isDirectory()) {
            throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
        }

        File file = new File(MVNForumConfig.getLogDir() + File.separatorChar + fileName);
        if ((!file.exists()) || (!file.isFile())) {
            log.error("Can't find a file " + file + " to be downloaded (or maybe it's directory).");
            String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_exist_or_not_file_to_be_downloaded");
            throw new IOException(localizedMessage + " " + file);
            //throw new IOException("Can't find a file to be downloaded (or maybe it's directory).");
        }

        BufferedOutputStream output = null;
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Location", fileName);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            int length = (int) file.length();
            if (length > 0) {
                response.setContentLength(length);
            }

            output = new BufferedOutputStream(response.getOutputStream(), 1024 /* buffer size */);
            response.setBufferSize(1024);

            //when we start download, we cannot redirect or raise exceptions
            FileUtil.popFile(file, output);
            output.flush();
        } catch (FileNotFoundException e) {
            log.error("Can't find the such log file on server " + fileName);
        } catch (IOException e) {
            log.error("Error while trying to send backup file from server (" + fileName + ").", e);
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) { }
            }
        }
    }

    public void deleteLogFile(HttpServletRequest request)
        throws DatabaseException, AuthenticationException, AssertionException, BadInputException, IOException {

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

        String fileName = ParamUtil.getParameterSafe(request, "filename", true);
        FileUtil.checkGoodFileName(fileName);

        String logDir = MVNForumConfig.getLogDir();
        File logDirFile = new File(logDir);
        if (!logDirFile.exists()) {
            throw new FileNotFoundException("Cannot find the log dir: " + logDirFile.getAbsolutePath());
        }
        if (!logDirFile.isDirectory()) {
            throw new IOException("The log dir is not a directory: " + logDirFile.getAbsolutePath());
        }

        fileName = logDir + File.separator + fileName;
        String logFileName = MVNForumConfig.getLogFile();
        File currentLogFile = new File(logFileName);

        if (currentLogFile.equals(new File(fileName))) {
            throw new AssertionException("Cannot delete the current log file: " + fileName);
        }

        FileUtil.deleteFile(fileName);
    }

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