KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/ExportWebHelper.java,v 1.10 2006/04/14 17:36:28 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.10 $
5  * $Date: 2006/04/14 17:36:28 $
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.sql.*;
44 import java.util.*;
45 import java.util.zip.ZipEntry JavaDoc;
46 import java.util.zip.ZipOutputStream JavaDoc;
47
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49
50 import com.mvnforum.*;
51 import com.mvnforum.admin.importexport.XMLUtil;
52 import com.mvnforum.admin.importexport.XMLWriter;
53 import net.myvietnam.mvncore.db.DBUtils;
54 import net.myvietnam.mvncore.exception.*;
55 import net.myvietnam.mvncore.util.I18nUtil;
56 import org.apache.commons.logging.Log;
57 import org.apache.commons.logging.LogFactory;
58
59 /**
60  * @author Igor Manic
61  * @version $Revision: 1.10 $, $Date: 2006/04/14 17:36:28 $
62  * <br/>
63  * <code>ExportWebHelper</code> todo Igor: enter description
64  *
65  */

66 public class ExportWebHelper {
67
68     /** Message log. */
69     private static Log log = LogFactory.getLog(ExportWebHelper.class);
70
71     /** Cannot instantiate. */
72     private ExportWebHelper() {
73         super();
74     }
75
76
77 // =================================================================
78
// ===================== MAIN PUBLIC METHODS =======================
79
// =================================================================
80
public static void exportXml(String JavaDoc filename, HttpServletRequest JavaDoc request,
81             int logonMemberID, String JavaDoc logonMemberName,
82             Calendar backupTime, String JavaDoc backupIP)
83         throws ExportException {
84
85         log.debug("Making backup xml = \""+filename+"\".");
86         String JavaDoc filepath = MVNForumConfig.getBackupDir() + File.separatorChar + filename;
87         File resultFile = new File(filepath);
88         XMLWriter xmlWriter = new XMLWriter(" "/*indentString*/, resultFile);
89         try {
90             createBackupXml(xmlWriter, backupTime, backupIP);
91         } catch (ExportException e) {
92             /* xmlWriter.close() will be called again in finally section, but,
93              * nevermind, I'll ignore IOException then. Anyway, the most
94              * important is that it is called in any case, and here, in case
95              * of exception, I must first close xmlWriter, before trying
96              * to delete resultFile.
97              */

98             try {
99                 xmlWriter.close();
100             } catch (IOException ee) {
101                 log.error("I/O error while closing created XML. Ignoring...");
102                 //ignore this
103
} finally {
104                 xmlWriter=null;
105             }
106             if (resultFile!=null) { resultFile.delete(); resultFile=null; }
107             throw e; //rethrow; just wanted to ensure bad resultFile is deleted
108
} finally {
109             //see above section "catch ExportException"
110
try {
111                 xmlWriter.close();
112             } catch (IOException e) {
113                 log.error("I/O error while closing created XML. Ignoring...");
114                 //ignore this
115
} finally {
116                 xmlWriter=null;
117             }
118         }
119         /*return resultFile;*/ resultFile=null;
120     }
121
122     public static void exportZip(String JavaDoc filename, HttpServletRequest JavaDoc request,
123             int logonMemberID, String JavaDoc logonMemberName,
124             Calendar backupTime, String JavaDoc backupIP)
125         throws ExportException {
126
127         log.debug("Making backup zip = \""+filename+"\".");
128         // First, make the main XML file, in "temp" directory.
129
File mainXmlFile = null;
130
131         Locale locale = I18nUtil.getLocaleInRequest(request);
132
133         try {
134             mainXmlFile = File.createTempFile("IMPORT", ".xml", new File(MVNForumConfig.getTempDir()));
135             XMLWriter xmlWriter = new XMLWriter(" "/*indentString*/, mainXmlFile);
136             try {
137                 createBackupXml(xmlWriter, backupTime, backupIP);
138             } finally {
139                 xmlWriter.close(); xmlWriter=null;
140             }
141         } catch (IOException e) {
142             log.error("I/O error while creating XML.");
143             if (mainXmlFile!=null) { mainXmlFile.delete(); mainXmlFile=null; }
144             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ExportException.io_error.create_mail_xml_file");
145             throw new ExportException(localizedMessage);
146             //throw new ExportException("I/O error while creating main XML file.", e);
147
} catch (ExportException e) {
148             if (mainXmlFile!=null) { mainXmlFile.delete(); mainXmlFile=null; }
149             throw e; //rethrow; just wanted to ensure mainXmlFile is deleted
150
}
151
152         /* Second, create ZIP file in "backup" directory and add avatarsDir, attachsDir, mainXmlFile.
153          * I am adding XML file at the end, since it might be better for import to process
154          * XML after the other files are copied. It's not so important, but it's maybe
155          * more convenient for the admin to see those file extraction prior to
156          * importing XML, since when that XML processing starts, he will be
157          * "bombed" with dozens of messages about database items...
158          */

159         String JavaDoc zipFilePath = MVNForumConfig.getBackupDir() + File.separatorChar + filename;
160         String JavaDoc avatarsDir = request.getSession().getServletContext().getRealPath(MVNForumGlobal.UPLOADED_AVATAR_DIR);
161         String JavaDoc attachsDir = MVNForumConfig.getAttachmentDir();
162
163         ZipOutputStream JavaDoc out = null;
164         try {
165             //now create ZIP file
166
out = new ZipOutputStream JavaDoc(new FileOutputStream(zipFilePath));
167             //Select your choice of STORED (not compressed) or DEFLATED (compressed).
168
out.setMethod(ZipOutputStream.DEFLATED);
169
170             //add avatarsDir and attachsDir
171
addDirectory(out, new File(avatarsDir), MVNForumConfig.BACKUP_FILE_AvatarsDirNameInZip);
172             addDirectory(out, new File(attachsDir), MVNForumConfig.BACKUP_FILE_AttachsDirNameInZip);
173             //add mainXmlFile
174
addFile(out, mainXmlFile, MVNForumConfig.BACKUP_FILE_MainXmlFileNameInZip);
175         } catch (FileNotFoundException e) {
176             log.error("Can't find a file that has been created.");
177             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ExportException.cannot_file_created");
178             throw new ExportException(localizedMessage);
179             //throw new ExportException("Can't find a file that has been created.", e);
180
} catch (IOException e) {
181             log.error("I/O error while making ZIP file.");
182             try { out.close(); } catch (Exception JavaDoc ee) {}
183             out = null;
184             try { new File(zipFilePath).delete(); } catch (Exception JavaDoc ee) {}
185             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ExportException.io_error.make_zip_file");
186             throw new ExportException(localizedMessage);
187             //throw new ExportException("I/O error while making ZIP file.", e);
188
} finally {
189             if (out!=null) try { out.flush(); out.close(); } catch (IOException e) {}
190             out = null;
191             //delete mainXmlFile, so I don't get both XML and ZIP in the backup repository
192
if (mainXmlFile!=null) { mainXmlFile.delete(); mainXmlFile=null; }
193         }
194         /*return new File(zipFilePath);*/
195     }
196
197     private static void addFile(ZipOutputStream JavaDoc out, File file, String JavaDoc relativePath)
198     throws IOException {
199         byte[] buf = new byte[1024];
200         FileInputStream in = new FileInputStream(file);
201
202         // Add ZIP entry to output stream.
203
out.putNextEntry(new ZipEntry JavaDoc(relativePath));
204         //ZipEntry zipentry = new ZipEntry(rgstring[i]);
205
//zipentry.setSize(file.length());
206
//zipentry.setTime(file.lastModified());
207
//out.putNextEntry(zipentry);
208

209         //Transfer bytes from the file to the ZIP file
210
int len;
211         while ((len = in.read(buf)) > 0) {
212             out.write(buf, 0, len);
213         }
214
215         // Complete the entry
216
in.close(); in=null;
217         out.closeEntry();
218     }
219
220     private static void addDirectory(ZipOutputStream JavaDoc out, File dir, String JavaDoc relativePath)
221     throws IOException {
222         if (dir.isFile()) {
223             log.error("Called addDirectory on a file \""+dir.getAbsolutePath()+"\".");
224             throw new IOException("I/O error while adding directory to ZIP.");
225         }
226         if (relativePath.length()>0) { //ignore starting directory
227
if (!relativePath.endsWith("/")) relativePath+="/";
228             // Add ZIP entry to output stream.
229
out.putNextEntry(new ZipEntry JavaDoc(relativePath));
230             out.closeEntry();
231         }
232         File[] files = dir.listFiles();
233         if (files != null) {
234             for (int i = 0; i < files.length; i++) {
235                 File file = files[i];
236                 if (file.isFile()) {
237                     addFile(out, file, relativePath+file.getName());
238                 } else {
239                     addDirectory(out, file, relativePath+file.getName()+"/");
240                 }
241             }
242         }
243     }
244
245
246 // =================================================================
247
// ================= MAIN CREATING XML/ZIP METHOD ==================
248
// =================================================================
249
private static void createBackupXml(XMLWriter xmlWriter,
250                                         Calendar backupTime, String JavaDoc backupIP)
251         throws ExportException {
252
253         try {
254             xmlWriter.startDocument(MVNForumConstant.dtdschemaDecl);
255             String JavaDoc strExportDate = XMLUtil.sqlTimestampToStringDefNow(
256                    new Timestamp(backupTime.getTime().getTime()));
257             xmlWriter.startElement("mvnforum",
258                       new String JavaDoc[]{"version", "1.0",
259                                    "exportDate", strExportDate});
260
261             MemberXML.exportMemberList(xmlWriter);
262             GroupXML.exportGroupList(xmlWriter);
263             CategoryXML.exportCategoryList(xmlWriter);
264             RankXML.exportRankList(xmlWriter);
265
266             xmlWriter.endElement("mvnforum");
267             xmlWriter.endDocument();
268         } catch (IOException e) {
269             log.error("I/O error while trying to create backup XML file on server.", e);
270             throw new ExportException("", e);
271         } catch (ObjectNotFoundException e) {
272             log.error("Object not found error while trying to createBackupXml()", e);
273             throw new ExportException("Database object not found error while trying to create backup XML file on server.", e);
274         } catch (DatabaseException e) {
275             log.error("Database error while trying to createBackupXml()", e);
276             throw new ExportException("Database error while trying to create backup XML file on server.", e);
277         }
278     }
279
280
281 // =================================================================
282
// ======================= UTILITY METHODS =========================
283
// =================================================================
284
public static Collection execSqlQuery(String JavaDoc query)
285     throws DatabaseException {
286         Connection connection = null;
287         PreparedStatement statement = null;
288         ResultSet resultSet = null;
289         Collection retValue = new ArrayList();
290         try {
291             connection = DBUtils.getConnection();
292             statement = connection.prepareStatement(query);
293             resultSet = statement.executeQuery();
294             int numCols = resultSet.getMetaData().getColumnCount();
295             while (resultSet.next()) {
296                 String JavaDoc[] thisResult = new String JavaDoc[numCols];
297                 for (int i=0; i<numCols; i++) {
298                     thisResult[i]=resultSet.getString(i+1);
299                 }
300                 retValue.add(thisResult);
301             }
302             return retValue;
303         } catch (SQLException sqle) {
304             log.error("Sql Execution Error!", sqle);
305             throw new DatabaseException("Error executing SQL in ExportWebHelper.execSqlQuery.");
306         } finally {
307             DBUtils.closeResultSet(resultSet);
308             DBUtils.closeStatement(statement);
309             DBUtils.closeConnection(connection);
310         }
311     }
312
313
314 }
315
316
317
Free Books   Free Magazines  
Popular Tags