KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/admin/ImportWebHandler.java,v 1.13 2006/04/14 17:36:29 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.13 $
5  * $Date: 2006/04/14 17:36:29 $
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.util.*;
44
45 import javax.servlet.http.HttpServletRequest JavaDoc;
46 import javax.servlet.http.HttpServletResponse JavaDoc;
47
48 import com.mvnforum.MVNForumConfig;
49 import com.mvnforum.MVNForumResourceBundle;
50 import com.mvnforum.admin.importexport.jive.ImportJive;
51 import com.mvnforum.admin.importexport.mvnforum.ImportMvnForum;
52 import com.mvnforum.auth.*;
53 import com.mvnforum.user.UserModuleConfig;
54 import net.myvietnam.mvncore.exception.*;
55 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
56 import net.myvietnam.mvncore.filter.EnableHtmlTagFilter;
57 import net.myvietnam.mvncore.util.*;
58 import net.myvietnam.mvncore.web.*;
59 import net.myvietnam.mvncore.web.fileupload.FileItem;
60 import net.myvietnam.mvncore.web.fileupload.FileUploadException;
61 import net.myvietnam.mvncore.web.impl.GenericRequestServletImpl;
62 import org.apache.commons.logging.Log;
63 import org.apache.commons.logging.LogFactory;
64
65 /**
66  * @author Igor Manic
67  * @version $Revision: 1.13 $, $Date: 2006/04/14 17:36:29 $
68  * <br/>
69  * <code>ImportWebHandler</code> class implements methods that process HTTP
70  * requests for import. Data could be imported from MVN Forum XML file conforming
71  * <a HREF="http://www.mvnforum.com/mvn.dtd">http://www.mvnforum.com/mvn.dtd</a>,
72  * or from MVN Forum backup ZIP file. Data can also be migrated from other sources
73  * (for now, it's only available for <code>Jive Forums</code>).
74  *
75  */

76 public class ImportWebHandler {
77
78     /** Message log. */
79     private static Log log = LogFactory.getLog(ImportWebHandler.class);
80
81     private static PrintWriter outputHtml=null;
82     /**
83      * All output messages (status, informational and error) will be written
84      * to <code>outHtml</code>.
85      *
86      * @param outHtml <code>PrintWriter</code> to write all output to. If it is
87      * <code>null</code>, there will be no output messages.
88      */

89     public static void setOutputHtmlWriter(PrintWriter outHtml) {
90         ImportWebHandler.outputHtml = outHtml;
91     }
92
93     /** Cannot instantiate. */
94     private ImportWebHandler() {
95     }
96
97     public static Vector getBackupFilesOnServer() {
98         Vector result = new Vector();
99         File dir = new File(MVNForumConfig.getBackupDir());
100         File[] files = dir.listFiles();
101         if (files != null) {
102             for (int i = 0; i < files.length; i++) {
103                 File file = files[i];
104                 if (file.isFile()) {
105                     result.add(DisableHtmlTagFilter.filter(file.getName()));
106                 } //else ignore subdirs
107
}
108         }
109         return result;
110     }
111
112     /**
113      * This is the main import request dispatcher. It parses request
114      * parameters, and decides what is the type of file used and what procedure
115      * to call (restore from mvnForum XML, or mvnForum ZIP, or migrate from Jive XML, ...).
116      * It also extracts additional request parameters, if they exist. Then it calls
117      * the desired procedure and gives it all parameters it extracted from the request.<br/>
118      * //todo Igor: add @see tags for all importXml/Zip methods
119      *
120      * @param request <code>HttpServletRequest</code> object of the request.
121      * @param response <code>HttpServletResponse</code> object of the request.
122      *
123      * @throws ImportException
124      * @throws AuthenticationException
125      * @throws DatabaseException
126      * @throws AssertionException
127      *
128      */

129     public static void importXmlZip(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
130         throws ImportException, AuthenticationException, DatabaseException, AssertionException {
131
132         OnlineUserManager onlineUserManager = OnlineUserManager.getInstance();
133         OnlineUser onlineUser = onlineUserManager.getOnlineUser(request);
134         MVNForumPermission permission = onlineUser.getPermission();
135         permission.ensureCanAdminSystem();
136
137         Locale locale = I18nUtil.getLocaleInRequest(request);
138
139         int sizeMax = MVNForumConfig.getMaxImportSize();
140         int sizeThreshold = 100000;// max memory used = 100K
141
String JavaDoc tempDir = MVNForumConfig.getTempDir();
142         List fileItems;
143         try {
144             GenericRequest genericRequest = new GenericRequestServletImpl(request);
145             FileUploadParser uploadParser = FileUploadParserFactory.getFileUploadParser();
146             fileItems = uploadParser.parseRequest(genericRequest, sizeMax, sizeThreshold, tempDir, "UTF-8");
147         } catch (FileUploadException ex) {
148             log.error("Cannot upload", ex);
149             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.cannot_upload", new Object JavaDoc[] {ex.getMessage()});
150             throw new ImportException(localizedMessage);
151             //throw new ImportException("Cannot upload file. Detailed reason: " + ex.getMessage());
152
}
153
154         // values that must get from the form
155
String JavaDoc serverImportFilename = null; //if importing from the server backup directory
156
String JavaDoc clientImportFilename = null; //if uploading import file
157
int clientImportFileSize = 0; //if uploading import file
158
FileItem clientImportFileItem = null; //if uploading import file
159

160         int importType = MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default is MVN Forum XML
161
boolean clearIfError = true; //default is to reset database in case of error
162
int messageLevel = MVNForumConfig.MESSAGE_LEVEL_ALL_MESSAGES;
163         Vector otherFieldValues=new Vector();
164
165         int logonMemberID = onlineUser.getMemberID();
166         String JavaDoc logonMemberName = onlineUser.getMemberName();
167         Calendar importTime = Calendar.getInstance();
168         String JavaDoc importIP = request.getRemoteAddr();
169         File importFile = null;
170         boolean deleteAfterImport = false;
171
172         try {
173             for (int i = 0; i < fileItems.size(); i++ ) {
174                 FileItem currentFileItem = (FileItem)fileItems.get(i);
175                 //content-type: currentFileItem.getContentType();
176
String JavaDoc fieldName = currentFileItem.getFieldName();
177                 boolean isFormField = currentFileItem.isFormField();
178
179                 if ( (fieldName.equals("ServerImportFile")) && (isFormField) ) {
180                     serverImportFilename=EnableHtmlTagFilter.filter(currentFileItem.getString());
181                     log.debug("serverImportFilename = " + serverImportFilename);
182                     currentFileItem.delete(); currentFileItem=null;
183
184                 } else if (fieldName.equals("ClientImportFile")) {
185                     if (isFormField) {
186                         String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.cannot_process_uploaded_import_file_with_a_form_field");
187                         throw new ImportException(localizedMessage);
188                         //throw new AssertionException("Cannot process uploaded import file with a form field.");
189
}
190                     clientImportFileSize = (int)currentFileItem.getSize();
191                     String JavaDoc fullFilePath = currentFileItem.getName();
192                     clientImportFilename = FileUtil.getFileName(fullFilePath);
193                     log.debug("clientImportFilename = " + clientImportFilename);
194                     // now save to clientImportFileItem
195
clientImportFileItem = currentFileItem;
196
197                 } else if ( (fieldName.equals("ImportType")) && (isFormField) ) {
198                     try {
199                         importType=Integer.parseInt(currentFileItem.getString());
200                     } catch (NumberFormatException JavaDoc e) {
201                         importType=MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML; //default
202
}
203                     currentFileItem.delete(); currentFileItem=null;
204                 } else if ( (fieldName.equals("ClearIfError")) && (isFormField) ) {
205                     int clearInt=1;
206                     try {
207                         clearInt=Integer.parseInt(currentFileItem.getString());
208                     } catch (NumberFormatException JavaDoc e) {
209                         clearInt=1; //default
210
}
211                     if (clearInt==0) clearIfError=false;
212                     else clearIfError=true;
213                     currentFileItem.delete(); currentFileItem=null;
214                 } else if ( (fieldName.equals("MessageLevel")) && (isFormField) ) {
215                     try {
216                         messageLevel=Integer.parseInt(currentFileItem.getString());
217                     } catch (NumberFormatException JavaDoc e) {
218                         messageLevel=MVNForumConfig.MESSAGE_LEVEL_ALL_MESSAGES; //default
219
}
220                     currentFileItem.delete(); currentFileItem=null;
221
222                 } else { //other field values
223
if (isFormField) {
224                         otherFieldValues.add(new String JavaDoc(fieldName));
225                         otherFieldValues.add(currentFileItem.getString());
226                     }
227                     currentFileItem.delete(); currentFileItem=null;
228                 }
229             } //for (int i = 0; i < fileItems.size(); i++ )
230

231             if ((serverImportFilename!=null) && (!serverImportFilename.equals(""))) {
232                 //import from server backup repository
233
String JavaDoc filepath = MVNForumConfig.getBackupDir() + File.separatorChar + serverImportFilename;
234                 importFile=new File(filepath);
235                 deleteAfterImport=false;
236
237             } else {
238                 //upload client import file
239
deleteAfterImport=true; //delete uploaded file
240
if ((clientImportFilename==null) || (clientImportFilename.equals(""))) {
241                     log.error("Cannot import. Please choose either a file on server, or upload a file.");
242                     String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.cannot_import.choose_a_file_on_server_or_upload_a_file");
243                     throw new ImportException(localizedMessage);
244                     //throw new ImportException("Cannot import. Please choose either a file on server, or upload a file.");
245
} else {
246                     log.debug("ImportWebHandler : process upload with temp dir = " + MVNForumConfig.getTempDir());
247                     if (clientImportFileSize == 0) {
248                         String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.cannot_process_import.file_size_is_zero");
249                         throw new ImportException(localizedMessage);
250                         //throw new ImportException("Cannot process an import file with size = 0. Please check the file size or check if your file is missing.");
251
}
252                 }
253
254                 try {
255                     String JavaDoc filepath = MVNForumConfig.getTempDir() + File.separatorChar +
256                                "import-" +
257                                ((importType==MVNForumConfig.IMPORTEXPORT_TYPE_JIVE_XML)?"jive-":"") +
258                                importTime.get(Calendar.YEAR) + "-" +
259                                importTime.get(Calendar.MONTH) + "-" +
260                                importTime.get(Calendar.DAY_OF_MONTH) + "-" +
261                                importTime.get(Calendar.HOUR_OF_DAY) + "-" +
262                                importTime.get(Calendar.MINUTE) + "-" +
263                                importTime.get(Calendar.SECOND) +
264                                ((importType==MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP)?".zip":".xml");
265                     log.debug("Client import file to save to file system = " + filepath);
266                     clientImportFileItem.write(new File(filepath));
267                     importFile=new File(filepath);
268                     clientImportFileItem.delete();
269                     clientImportFileItem=null;
270                 } catch (Exception JavaDoc ex) {
271                     log.error("Cannot save the import file.", ex);
272                     String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.cannot_import.cannot_save_import_file");
273                     throw new ImportException(localizedMessage);
274                     //throw new ImportException("Cannot save the import file to the file system.", ex);
275
}
276             }
277
278         } finally {
279             for (int i = 0; i < fileItems.size(); i++ ) {
280                 try { ((FileItem)fileItems.get(i)).delete();
281                 } catch (Exception JavaDoc e) {}
282             }
283             fileItems.clear(); fileItems=null;
284         }
285
286         if (!importFile.exists()) {
287             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.cannot_find_import_file");
288             throw new ImportException(localizedMessage);
289             //throw new ImportException("Can't find import file.");
290
}
291         else if (!importFile.isFile()) {
292             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.import_file_is_not_a_file");
293             throw new ImportException(localizedMessage);
294             //throw new ImportException("Import \"file\" is actually not a file (probably a directory).");
295
}
296         else if (!importFile.canRead()) {
297             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.dont_have_read_permission");
298             throw new ImportException(localizedMessage);
299             //throw new ImportException("Don't have a permission to read an import file from server.");
300
}
301
302         try {
303             switch (importType) {
304                 case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_XML:
305                     ImportMvnForum.importXml(importFile,
306                                             request, response,
307                                             logonMemberID, logonMemberName,
308                                             importTime, importIP,
309                                             clearIfError, messageLevel);
310                     break;
311                 case MVNForumConfig.IMPORTEXPORT_TYPE_MVN_ZIP:
312                     ImportMvnForum.importZip(importFile,
313                                             request, response,
314                                             logonMemberID, logonMemberName,
315                                             importTime, importIP,
316                                             clearIfError, messageLevel);
317                     break;
318                 case MVNForumConfig.IMPORTEXPORT_TYPE_JIVE_XML:
319                     ImportJive.importXml(importFile,
320                                      request, response,
321                                      logonMemberID, logonMemberName,
322                                      importTime, importIP,
323                                      clearIfError, otherFieldValues, messageLevel);
324                     break;
325
326                 default:
327                     log.error("importXmlZip: invalid importType = " + importType);
328                     String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ImportException.invalid_import_type_specified");
329                     throw new ImportException(localizedMessage);
330                     //throw new AssertionException("Invalid import type specified.");
331
}
332         } catch (ImportException e) {
333            /* In case of this exception, I already printed error message.
334             * Now I should NOT allow this exception to propagate higher, since
335             * it will then initiate errorpage, which I don't want, and can't
336             * allow because already commited output.
337             * So, I don't do anything here, just catch it.
338             */

339         } finally {
340             /* Logout current user, even if the import raised an exception,
341                because database data are probably changed anyway. */

342             onlineUserManager.logout(request, response);
343             //this didn't work: ManagerFactory.getOnlineUserFactory().logout(request, response);
344

345             //delete uploaded file, but only if it's not already deleted !
346
if (deleteAfterImport && (importFile.exists())) {
347                 importFile.delete();
348             }
349             importFile=null;
350         }
351     }
352
353
354 // =================================================================
355
// ===== PRINTING STATUS AND ERROR MESSAGES TO THE OUTPUT HTML =====
356
// =================================================================
357
private static boolean oddLine=true;
358     private static boolean outputHtmlNotEnded=false;
359     private static boolean outputNonImportantMessages=true;
360     private static boolean outputImportantMessages=true;
361     //outputErrors is always true
362

363     public static void setMessageOutputLevel(int messageLevel) {
364         switch (messageLevel) {
365             case MVNForumConfig.MESSAGE_LEVEL_ONLY_ERRORS:
366                 outputImportantMessages=false;
367                 outputNonImportantMessages=false;
368                 break;
369             case MVNForumConfig.MESSAGE_LEVEL_IMPORTANT_MESSAGES:
370                 outputImportantMessages=true;
371                 outputNonImportantMessages=false;
372                 break;
373             default: //MVNForumConfig.MESSAGE_LEVEL_ALL_MESSAGES
374
outputNonImportantMessages=true;
375                 outputImportantMessages=true;
376         }
377     }
378
379
380     public static void startHtml(HttpServletRequest JavaDoc request) {
381         if (outputHtml!=null) {
382             outputHtmlNotEnded=true;
383             outputHtml.println("<html>");
384             outputHtml.println("<head>");
385             outputHtml.println(" <title>mvnForum - Import/Restore Process</title>");
386             outputHtml.println(" <meta name=\"copyright\" content=\"This software is copyrighted by MyVietnam.net and released under the terms of the GNU General Public License GPL license. All rights reserved.\">");
387             outputHtml.println(" <meta name=\"Keywords\" content=\"mvnForum, server side java, online meetings, collaboration, bulletin board, board, forum, discussion board, jsp, servlet, java, j2se, j2ee, database, jdbc, connection pool, mysql, MyVietnam, mvnForum, framework, web app, web application, servlet container, tomcat, jboss, weblogic, websphere\">");
388             outputHtml.println(" <meta name=\"Description\" content=\"mvnForum is a powerful Jsp/Servlet forum (discussion board) - based on Java technology.\">");
389             outputHtml.println(" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
390             outputHtml.println(" <meta http-equiv=\"Expires\" content=\"-1\">");
391             outputHtml.println(" <link HREF=\""+request.getContextPath()+"/mvnplugin/mvnforum/css/style.css\" rel=\"stylesheet\" type=\"text/css\">");
392             outputHtml.println("</head>");
393             outputHtml.println("<body leftmargin=\"0\" topmargin=\"0\">");
394             outputHtml.println("<br/>");
395             outputHtml.println("");
396             outputHtml.println("<table class=\"tborder\" width=\"95%\" cellpadding=\"3\" align=\"center\">");
397             outputHtml.println("<tr class=\"theader\">");
398             outputHtml.println(" <td align=\"center\">Messages during the process</td>");
399             outputHtml.println("</tr>");
400             outputHtml.flush();
401             oddLine=true;
402         }
403     }
404
405     public static void endHtml() {
406         if (outputHtml!=null) {
407             outputHtml.println("</table>");
408             outputHtml.println("");
409             outputHtml.println("<br/>");
410             outputHtml.println("</body>");
411             outputHtml.println("</html>");
412             outputHtml.flush();
413             outputHtmlNotEnded=false;
414         }
415     }
416
417     public static void addMessage(String JavaDoc message) {
418         if (outputNonImportantMessages) {
419             outputHtmlTableRow(message, "messageText");
420         }
421     }
422
423     public static void addErrorMessage(String JavaDoc message) {
424         outputHtmlTableRow(message, "messageTextBoldRed");
425     }
426
427     /**
428      * Adds warning that the process contained some errors, and the database
429      * might be inconsistent now. It also tries to clear the database and
430      * create default entries, including "admin" member.
431      */

432     public static void addFinalErrorHandling(HttpServletRequest JavaDoc request, boolean resetAllData) {
433         outputHtmlTableRow("&nbsp;", "messageTextBoldRed"); //add one empty row in output message table
434
String JavaDoc message = "There was an error during the import. DATA ARE NOW PROBABLY DAMAGED.<br/>";
435         if (resetAllData) message+="Trying to clear the database and create \"admin\" member (password will be \"admin\")...<br/>";
436         outputHtmlTableRow(message, "messageTextBoldRed");
437
438         String JavaDoc indexUrl = ParamUtil.getContextPath()+
439                           UserModuleConfig.getUrlPattern()+
440                           "/index";
441         String JavaDoc finalMessage = "If you still want to import these data that produced an error, " +
442                "please correct above errors first.<br/>" +
443                "Then proceed to: &nbsp;&nbsp;&nbsp;"+
444                "<a HREF=\"login\" class=\"menuLink\">Login</a>&nbsp;|&nbsp;" +
445                "<a HREF=\"index\" class=\"menuLink\">Admin Index</a>&nbsp;|&nbsp;" +
446                "<a HREF=\""+indexUrl+"\" class=\"menuLink\">Forum Index</a><br/>" +
447                "<span class=\"messageTextBoldRed\">" +
448                "Notice you should enter new username and password!" +
449                "</span>";
450         try {
451             if (resetAllData) {
452                 ImportWebHelper.clearDatabase();
453                 ImportWebHelper.clearFiles(request.getSession().getServletContext());
454                 ImportWebHelper.createDefaultContents();
455             }
456         } catch (IOException e) {
457             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
458         } catch (DatabaseException e) {
459             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
460         } catch (CreateException e) {
461             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
462         } catch (DuplicateKeyException e) {
463             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
464         } catch (ObjectNotFoundException e) {
465             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
466         } catch (ForeignKeyNotFoundException e) {
467             addErrorMessage("Still got an error. We strongly suggest you to create new empty database.<br/>");
468         } finally {
469             outputHtmlTableRow(finalMessage, "messageTextBoldRed");
470         }
471     }
472
473     public static void addSuccessMessage() {
474         String JavaDoc indexUrl = ParamUtil.getContextPath()+
475                           UserModuleConfig.getUrlPattern()+
476                           "/index";
477         String JavaDoc message = "Successful. Proceed to: &nbsp;&nbsp;&nbsp;"+
478                          "<a HREF=\"login\" class=\"menuLink\">Login</a>&nbsp;|&nbsp;" +
479                          "<a HREF=\"index\" class=\"menuLink\">Admin Index</a>&nbsp;|&nbsp;" +
480                          "<a HREF=\""+indexUrl+"\" class=\"menuLink\">Forum Index</a><br/>" +
481                          "<span class=\"messageTextBoldRed\">" +
482                          "Notice you should enter new username and password!" +
483                          "</span>";
484         outputHtmlTableRow(message, "messageTextBold");
485     }
486
487     public static void addImportantMessage(String JavaDoc message) {
488         if (outputImportantMessages) {
489             outputHtmlTableRow(message, "messageTextBoldRed");
490         }
491     }
492
493     private static void outputHtmlTableRow(String JavaDoc message, String JavaDoc cssClass) {
494         if (outputHtml!=null) {
495             if (oddLine) {
496                 outputHtml.println("<tr class=\"trow1\">");
497             } else {
498                 outputHtml.println("<tr class=\"trow2\">");
499             }
500             outputHtml.println(" <td class=\""+cssClass+"\">"+message+"</td>");
501             outputHtml.println("</tr>");
502             outputHtml.flush();
503             oddLine=!oddLine;
504         }
505     }
506
507 }
508
Popular Tags