KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mvnforum > admin > ExportWebHandler


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/ExportWebHandler.java,v 1.14 2006/04/14 17:05:25 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.14 $
5  * $Date: 2006/04/14 17:05:25 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding mvnForum MUST remain
12  * intact in the scripts and in the outputted HTML.
13  * The "powered by" text/logo with a link back to
14  * http://www.mvnForum.com and http://www.MyVietnam.net in
15  * the footer of the pages MUST remain visible when the pages
16  * are viewed on the internet or intranet.
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31  *
32  * Support can be obtained from support forums at:
33  * http://www.mvnForum.com/mvnforum/index
34  *
35  * Correspondence and Marketing Questions can be sent to:
36  * info at MyVietnam net
37  *
38  * @author: Igor Manic
39  */

40 package com.mvnforum.admin;
41
42 import java.io.*;
43 import java.text.SimpleDateFormat JavaDoc;
44 import java.util.Calendar JavaDoc;
45 import java.util.Locale JavaDoc;
46
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import com.mvnforum.MVNForumConfig;
51 import com.mvnforum.MVNForumResourceBundle;
52 import com.mvnforum.auth.*;
53 import net.myvietnam.mvncore.exception.*;
54 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
55 import net.myvietnam.mvncore.util.*;
56 import net.myvietnam.mvncore.web.GenericRequest;
57 import org.apache.commons.logging.Log;
58 import org.apache.commons.logging.LogFactory;
59
60 /**
61  * @author <a HREF="mailto:">Igor Manic </a>
62  * @version $Revision: 1.14 $, $Date: 2006/04/14 17:05:25 $<br/>
63  * <code>ExportWebHandler</code> class implements methods that
64  * process HTTP requests for export. Data could be exported to MVN
65  * Forum XML file conforming <a
66  * HREF="http://www.mvnforum.com/mvn.dtd">http://www.mvnforum.com/mvn.dtd
67  * </a>, or to MVN Forum backup ZIP file.
68  *
69  */

70 public class ExportWebHandler {
71
72     /** Message log. */
73     private static Log log = LogFactory.getLog(ExportWebHandler.class);
74
75     /** Cannot instantiate. */
76     private ExportWebHandler() {
77     }
78
79     /**
80      * Processes export requests made from corresponding HTML page. <br/>
81      * Request should contain the parameter <code>ExportType</code> that tells
82      * us what type of destination backup file user wants.
83      *
84      * @param request
85      * <code>HttpServletRequest</code> of the request.
86      *
87      * @throws DatabaseException
88      * @throws AuthenticationException
89      * @throws AssertionException
90      * @throws ExportException
91      */

92     public static void exportXmlZip(HttpServletRequest JavaDoc request)
93         throws DatabaseException, AuthenticationException, AssertionException, ExportException {
94
95         OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
96         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
97         MVNForumPermission permission = onlineUser.getPermission();
98         permission.ensureCanAdminSystem();
99
100         int logonMemberID = onlineUser.getMemberID();
101         String JavaDoc logonMemberName = onlineUser.getMemberName();
102         Calendar JavaDoc exportTime = Calendar.getInstance();
103         String JavaDoc exportIP = request.getRemoteAddr();
104
105         Locale JavaDoc locale = I18nUtil.getLocaleInRequest(request);
106
107         int exportType = MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default
108
try {
109             exportType = ParamUtil.getParameterInt(request, "ExportType", MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML);
110         } catch (BadInputException e) {
111             exportType = MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default;
112
}
113
114         String JavaDoc timestamp = new SimpleDateFormat JavaDoc("yyyy-MM-dd-HH-mm-ss", Locale.US).format(exportTime.getTime());
115         String JavaDoc filename = MVNForumConfig.BACKUP_FILE_PREFIX
116                           + timestamp
117                           + ((exportType == MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP) ? ".zip"
118                              : ".xml");
119         log.debug("Will make export/backup file: " + filename);
120
121         switch (exportType) {
122         case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML:
123             ExportWebHelper.exportXml(filename, request, logonMemberID, logonMemberName, exportTime, exportIP);
124             break;
125         case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP:
126             ExportWebHelper.exportZip(filename, request, logonMemberID, logonMemberName, exportTime, exportIP);
127             break;
128
129         default:
130             log.error("exportXmlZip: invalid exportType = " + exportType);
131             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ExportException.invalid_export_type_specified");
132             throw new ExportException(localizedMessage);
133             //throw new ExportException("Invalid export type specified.");
134
}
135     }
136
137     public static void getExportXmlZip(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
138         throws BadInputException, DatabaseException, AuthenticationException, AssertionException, IOException {
139
140         OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
141         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
142         MVNForumPermission permission = onlineUser.getPermission();
143         permission.ensureCanAdminSystem();
144
145         Locale JavaDoc locale = I18nUtil.getLocaleInRequest(request);
146
147         String JavaDoc filename = ParamUtil.getParameterSafe(request, "filename", true);// must check empty
148
FileUtil.checkGoodFileName(filename);
149         filename = DisableHtmlTagFilter.filter(filename);
150
151         File f = new File(MVNForumConfig.getBackupDir() + File.separatorChar + filename);
152         if ((!f.exists()) || (!f.isFile())) {
153             log.error("Can't find a file to be downloaded (or maybe it's directory).");
154             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_exist_or_not_file_to_be_downloaded");
155             throw new IOException(localizedMessage);
156             //throw new AssertionException("Can't find a file to be downloaded (or maybe it's directory).");
157
} else {
158             try {
159                 response.setContentType("application/octet-stream");
160                 response.setHeader("Location", filename);
161                 response.setHeader("Content-Disposition", "attachment; filename=" + filename);
162                 int len = (int) f.length();
163                 if (len > 0)
164                     response.setContentLength(len);
165
166                 BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(f), 1024 /* buffer size */);
167                 BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream(), 1024 /* buffer size */);
168                 response.setBufferSize(1024);
169                 //when we start download, we cannot redirect or raise
170
// exceptions
171
sendToUser(inputStream, outputStream);
172
173                 if (inputStream != null) {
174                     try {
175                         inputStream.close();
176                     } catch (IOException e) {
177                     }
178                     inputStream = null;
179                 }
180                 if (outputStream != null) {
181                     try {
182                         outputStream.flush();
183                         outputStream.close();
184                     } catch (IOException e) {
185                     }
186                     outputStream = null;
187                 }
188             } catch (FileNotFoundException e) {
189                 log.error("Can't find a backup file on server.", e);
190                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_found_backup_file");
191                 throw new IOException(localizedMessage);
192                 //throw new IOException("Can't find a backup file on server.");
193
//rethrow - the user will be redirected to errorpage
194
} catch (IOException e) {
195                 log.error("Error while trying to send backup file from server.", e);
196                 String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.error_while_sending_backup_file");
197                 throw new IOException(localizedMessage);
198                 //throw new IOException("Error while trying to send backup file from server.");
199
//rethrow - the user will be redirected to errorpage
200
} finally {
201                 f = null;
202             }
203         }
204     }
205
206     public static void deleteExportXmlZip(GenericRequest request)
207         throws BadInputException, DatabaseException, AuthenticationException, AssertionException, IOException {
208
209         OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
210         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
211         MVNForumPermission permission = onlineUser.getPermission();
212         permission.ensureCanAdminSystem();
213
214         Locale JavaDoc locale = I18nUtil.getLocaleInRequest(request);
215
216         String JavaDoc filename = GenericParamUtil.getParameter(request, "filename", true);
217         FileUtil.checkGoodFileName(filename);
218         filename = DisableHtmlTagFilter.filter(filename);
219
220         File f = new File(MVNForumConfig.getBackupDir() + File.separatorChar + filename);
221         if ((!f.exists()) || (!f.isFile())) {
222             log.error("Can't find a file to be deleted (or maybe it's directory).");
223             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_exist_or_not_file_to_be_deleted");
224             throw new IOException(localizedMessage);
225             //throw new IOException("Can't find a file to be deleted (or maybe it's directory).");
226
} else {
227             f.delete();
228             f = null;
229         }
230     }
231
232     /**
233      * Sends (downloads) a file from server to the user.
234      *
235      * @param inputStream
236      * <code>BufferedInputStream</code> connected to the backup
237      * file that was made on server.
238      * @param outputStream
239      * <code>BufferedOutputStream</code> connected to the
240      * <code>HTTP response</code>.
241      */

242     private static void sendToUser(BufferedInputStream inputStream,
243                                    BufferedOutputStream outputStream) {
244         //this method should not throw any exception, since we are now starting
245
// commiting output
246
try {
247             //used stream objects are already buffered, so I won't do buffering
248
int b = 0;
249             while ((b = inputStream.read()) >= 0) {
250                 outputStream.write(b);
251             }
252         } catch (IOException e) {
253             try {
254                 outputStream.write("FATAL ERROR. Can't continue download.".getBytes());
255             } catch (IOException ee) {
256                 /*
257                  * Nothing we can do now. Since output was already commited, we
258                  * can't raise exception here.
259                  */

260             }
261         }
262     }
263 }
264
Popular Tags