⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exportwebhandler.java

📁 java servlet著名论坛源代码
💻 JAVA
字号:
/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/ExportWebHandler.java,v 1.3 2004/06/27 01:20:38 skoehler Exp $
 * $Author: skoehler $
 * $Revision: 1.3 $
 * $Date: 2004/06/27 01:20:38 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2004 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: Igor Manic   imanic@users.sourceforge.net
 */
package com.mvnforum.admin;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mvnforum.MVNForumConfig;
import com.mvnforum.auth.*;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.filter.EnableHtmlTagFilter;
import net.myvietnam.mvncore.util.ParamUtil;

/**
 * @author <a href="mailto:imanic@users.sourceforge.net">Igor Manic</a>
 * @version $Revision: 1.3 $, $Date: 2004/06/27 01:20:38 $
 * <br/>
 * <code>ExportWebHandler</code> class implements methods that process HTTP
 * requests for export. Data could be exported to MVN Forum XML file conforming
 * <a href="http://www.mvnforum.com/mvn.dtd">http://www.mvnforum.com/mvn.dtd</a>,
 * or to MVN Forum backup ZIP file.
 *
 */
class ExportWebHandler {

    /** Message log. */
    private static Log log = LogFactory.getLog(ExportWebHandler.class);

    /** Cannot instantiate. */
    private ExportWebHandler() {
    }

    /**
     * Processes export requests made from corresponding HTML page.<br/>
     * Request should contain the parameter <code>ExportType</code> that tells
     * us what type of destination backup file user wants.
     *
     * @param request <code>HttpServletRequest</code> of the request.
     *
     * @throws DatabaseException
     * @throws AuthenticationException
     * @throws AssertionException
     * @throws ExportException
     */
    public static void exportXmlZip(HttpServletRequest request)
    throws DatabaseException, AuthenticationException, AssertionException, ExportException {
        OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        int      logonMemberID   = onlineUser.getMemberID();
        String   logonMemberName = onlineUser.getMemberName();
        Calendar exportTime      = Calendar.getInstance();
        String   exportIP        = request.getRemoteAddr();

        int exportType = MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default
        try {
            exportType = ParamUtil.getParameterInt(request, "ExportType",
                                   MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML);
        } catch (BadInputException e) {
            exportType = MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default;
        }

        String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US).format(exportTime.getTime());
        String filename = MVNForumConfig.BACKUP_FILE_PREFIX + timestamp +
                          ((exportType==MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP)?".zip":".xml");
        log.debug("Will make export/backup file: " + filename);

        switch (exportType) {
            case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML:
                ExportWebHelper.exportXml(filename, request,
                                          logonMemberID, logonMemberName,
                                          exportTime, exportIP);
                break;
            case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP:
                ExportWebHelper.exportZip(filename, request,
                                          logonMemberID, logonMemberName,
                                          exportTime, exportIP);
                break;

            default:
                log.error("exportXmlZip: invalid exportType = " + exportType);
                throw new AssertionException("Invalid export type specified.");
        }
    }

    public static void getExportXmlZip(HttpServletRequest request, HttpServletResponse response)
    throws DatabaseException, AuthenticationException, AssertionException {
        OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        String filename = EnableHtmlTagFilter.filter(request.getParameter("filename"));
        if ((filename==null) || (filename.equals(""))) {
            log.error("Missing a name of a file to be downloaded.");
            throw new AssertionException("Missing a name of a file to be downloaded.");
        } else {
            File f=new File(MVNForumConfig.getBackupDir() + File.separatorChar + filename);
            if ((!f.exists()) || (!f.isFile())) {
                log.error("Can't find a file to be downloaded (or maybe it's directory).");
                throw new AssertionException("Can't find a file to be downloaded (or maybe it's directory).");
            } else {
                try {
                    response.setContentType("application/octet-stream");
                    response.setHeader("Location", filename);
                    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                    int len=(int)f.length();
                    if (len>0) response.setContentLength(len);

                    BufferedInputStream inputStream = new BufferedInputStream(
                        new FileInputStream(f), 1024/*buffer size*/);
                    BufferedOutputStream outputStream= new BufferedOutputStream(
                        response.getOutputStream(), 1024/*buffer size*/);
                    response.setBufferSize(1024);
                    //when we start download, we cannot redirect or raise exceptions
                    sendToUser(inputStream, outputStream);

                    if (inputStream!=null) {
                        try { inputStream.close(); } catch (IOException e) {}
                        inputStream=null;
                    }
                    if (outputStream!=null) {
                        try {
                            outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {}
                        outputStream=null;
                    }
                } catch (FileNotFoundException e) {
                    log.error("Can't find a backup file on server.", e);
                    throw new AssertionException("Can't find a backup file on server.");
                    //rethrow - the user will be redirected to errorpage
                } catch (IOException e) {
                    log.error("Error while trying to send backup file from server.", e);
                    throw new AssertionException("Error while trying to send backup file from server.");
                    //rethrow - the user will be redirected to errorpage
                } finally {
                    f=null;
                }
            }
        }
    }

    public static void deleteExportXmlZip(HttpServletRequest request)
    throws DatabaseException, AuthenticationException, AssertionException {
        OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
        OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureCanAdminSystem();

        String filename = EnableHtmlTagFilter.filter(request.getParameter("filename"));
        if ((filename==null) || (filename.equals(""))) {
            log.error("Missing a name of a file to be deleted.");
            throw new AssertionException("Missing a name of a file to be deleted.");
        } else {
            File f=new File(MVNForumConfig.getBackupDir() + File.separatorChar + filename);
            if ((!f.exists()) || (!f.isFile())) {
                log.error("Can't find a file to be deleted (or maybe it's directory).");
                throw new AssertionException("Can't find a file to be deleted (or maybe it's directory).");
            } else {
                f.delete(); f=null;
            }
        }
    }

    /**
     * Sends (downloads) a file from server to the user.
     *
     * @param inputStream <code>BufferedInputStream</code> connected to the backup file that was made on server.
     * @param outputStream <code>BufferedOutputStream</code> connected to the <code>HTTP response</code>.
     */
    private static void sendToUser(BufferedInputStream inputStream, BufferedOutputStream outputStream) {
        //this method should not throw any exception, since we are now starting commiting output
        try {
            //used stream objects are already buffered, so I won't do buffering
            int b=0;
            while ((b=inputStream.read()) >=0) {
                outputStream.write(b);
            }
        } catch (IOException e) {
            try {
                outputStream.write("FATAL ERROR. Can't continue download.".getBytes());
            } catch (IOException ee) {
                /* Nothing we can do now. Since output was already commited, we
                 * can't raise exception here.
                 */
            }
        }
    }


}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -