001: /*
002: * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/user/PmAttachmentWebHandler.java,v 1.69 2007/12/17 09:09:41 minhnn Exp $
003: * $Author: minhnn $
004: * $Revision: 1.69 $
005: * $Date: 2007/12/17 09:09:41 $
006: *
007: * ====================================================================
008: *
009: * Copyright (C) 2002-2007 by MyVietnam.net
010: *
011: * All copyright notices regarding mvnForum MUST remain
012: * intact in the scripts and in the outputted HTML.
013: * The "powered by" text/logo with a link back to
014: * http://www.mvnForum.com and http://www.MyVietnam.net in
015: * the footer of the pages MUST remain visible when the pages
016: * are viewed on the internet or intranet.
017: *
018: * This program is free software; you can redistribute it and/or modify
019: * it under the terms of the GNU General Public License as published by
020: * the Free Software Foundation; either version 2 of the License, or
021: * any later version.
022: *
023: * This program is distributed in the hope that it will be useful,
024: * but WITHOUT ANY WARRANTY; without even the implied warranty of
025: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
026: * GNU General Public License for more details.
027: *
028: * You should have received a copy of the GNU General Public License
029: * along with this program; if not, write to the Free Software
030: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
031: *
032: * Support can be obtained from support forums at:
033: * http://www.mvnForum.com/mvnforum/index
034: *
035: * Correspondence and Marketing Questions can be sent to:
036: * info at MyVietnam net
037: *
038: * @author: Minh Nguyen
039: * @author: Mai Nguyen
040: */
041: package com.mvnforum.user;
042:
043: import java.io.*;
044: import java.sql.Timestamp;
045: import java.util.*;
046:
047: import javax.servlet.http.HttpServletRequest;
048: import javax.servlet.http.HttpServletResponse;
049:
050: import com.mvnforum.*;
051: import com.mvnforum.auth.*;
052: import com.mvnforum.common.PrivateMessageUtil;
053: import com.mvnforum.db.*;
054: import net.myvietnam.mvncore.exception.*;
055: import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
056: import net.myvietnam.mvncore.interceptor.InterceptorService;
057: import net.myvietnam.mvncore.security.SecurityUtil;
058: import net.myvietnam.mvncore.service.*;
059: import net.myvietnam.mvncore.util.*;
060: import net.myvietnam.mvncore.web.*;
061: import net.myvietnam.mvncore.web.fileupload.FileItem;
062: import net.myvietnam.mvncore.web.fileupload.FileUploadException;
063:
064: import org.apache.commons.io.IOUtils;
065: import org.apache.commons.logging.Log;
066: import org.apache.commons.logging.LogFactory;
067:
068: public class PmAttachmentWebHandler {
069:
070: private static Log log = LogFactory
071: .getLog(PmAttachmentWebHandler.class);
072:
073: private OnlineUserManager onlineUserManager = OnlineUserManager
074: .getInstance();
075:
076: private URLResolverService urlResolverService = MvnCoreServiceFactory
077: .getMvnCoreService().getURLResolverService();
078:
079: private BinaryStorageService binaryStorageService = MvnCoreServiceFactory
080: .getMvnCoreService().getBinaryStorageService();
081:
082: private FileUploadParserService fileUploadParserService = MvnCoreServiceFactory
083: .getMvnCoreService().getFileUploadParserService();
084:
085: public PmAttachmentWebHandler() {
086: }
087:
088: public void prepareAdd(GenericRequest request)
089: throws BadInputException, DatabaseException,
090: ObjectNotFoundException, AuthenticationException {
091:
092: Locale locale = I18nUtil.getLocaleInRequest(request);
093:
094: if (MVNForumConfig.getEnableMessageAttachment() == false) {
095: String localizedMessage = MVNForumResourceBundle
096: .getString(locale,
097: "java.lang.IllegalStateException.message_attachment_is_disabled");
098: throw new IllegalStateException(localizedMessage);
099: //throw new IllegalStateException("Cannot add Attachment because Attachment in Private Message feature is disabled by administrator."); // localization
100: }
101:
102: OnlineUser onlineUser = onlineUserManager
103: .getOnlineUser(request);
104: MVNForumPermission permission = onlineUser.getPermission();
105: permission.ensureIsAuthenticated();
106: permission.ensureCanUseMessage();
107: permission.ensureCanAddMessageAttachment();
108:
109: int messageID = GenericParamUtil.getParameterInt(request,
110: "message");
111: MessageBean messageBean = null;
112: try {
113: messageBean = DAOFactory.getMessageDAO().getMessage(
114: messageID);
115: } catch (ObjectNotFoundException e) {
116: String localizedMessage = MVNForumResourceBundle
117: .getString(
118: locale,
119: "mvncore.exception.ObjectNotFoundException.messageid_not_exists",
120: new Object[] { new Integer(messageID) });
121: throw new ObjectNotFoundException(localizedMessage);
122: }
123: if (messageBean.getFolderName().equalsIgnoreCase(
124: MVNForumConstant.MESSAGE_FOLDER_DRAFT) == false) {
125: String localizedMessage = MVNForumResourceBundle
126: .getString(
127: locale,
128: "mvncore.exception.BadInputException.cannot_add_attachment.pm_does_not_in_folder_draft");
129: throw new BadInputException(localizedMessage);
130: //throw new BadInputException("Cannot add attachment because this Private Message does not in the folder Draft");
131: }
132:
133: if (messageBean.getMemberID() != onlineUser.getMemberID()) {
134: String localizedMessage = MVNForumResourceBundle
135: .getString(locale,
136: "mvncore.exception.BadInputException.pm_not_belongs_to_you");
137: throw new BadInputException(localizedMessage);
138: //throw new BadInputException("This Private Message does not belong to you");
139: }
140:
141: request.setAttribute("MessageBean", messageBean);
142: }
143:
144: public void processAdd(GenericRequest request,
145: GenericResponse response) throws BadInputException,
146: CreateException, DatabaseException, IOException,
147: ForeignKeyNotFoundException, AuthenticationException,
148: ObjectNotFoundException, InterceptorException {
149:
150: SecurityUtil.checkHttpPostMethod(request);
151:
152: Locale locale = I18nUtil.getLocaleInRequest(request);
153:
154: if (MVNForumConfig.getEnableMessageAttachment() == false) {
155: String localizedMessage = MVNForumResourceBundle
156: .getString(locale,
157: "java.lang.IllegalStateException.message_attachment_is_disabled");
158: throw new IllegalStateException(localizedMessage);
159: //throw new IllegalStateException("Cannot add Attachment because Attachment in Private Message feature is disabled by administrator."); // localization
160: }
161:
162: OnlineUser onlineUser = onlineUserManager
163: .getOnlineUser(request);
164: MVNForumPermission permission = onlineUser.getPermission();
165: permission.ensureIsAuthenticated();
166: permission.ensureCanUseMessage();
167: permission.ensureCanAddMessageAttachment();
168:
169: MyUtil.saveVNTyperMode(request, response);
170:
171: final int UNLIMITED = -1;
172: int sizeMax = permission.canAdminSystem() ? UNLIMITED
173: : MVNForumConfig.getMaxMessageAttachmentSize();
174: int sizeThreshold = 100000;
175: String tempDir = MVNForumConfig.getTempDir();
176:
177: log
178: .debug("PmAttachmentWebHandler : process upload with temp dir = "
179: + tempDir);
180:
181: List fileItems;
182: try {
183: fileItems = fileUploadParserService.parseRequest(request,
184: sizeMax, sizeThreshold, tempDir, "UTF-8");
185: } catch (FileUploadException ex) {
186: log.error("Cannot upload", ex);
187: String localizedMessage = MVNForumResourceBundle.getString(
188: locale, "java.io.IOException.cannot_upload",
189: new Object[] { ex.getMessage() });
190: throw new IOException(localizedMessage);
191: //throw new IOException("Cannot upload. Detailed reason: " + ex.getMessage());
192: }
193:
194: // values that must get from the form
195: int messageID = 0;
196: String attachFilename = null;
197: int attachFileSize = 0;
198: String attachMimeType = null;
199: String attachDesc = null;
200: boolean attachMore = false;
201: boolean markAsQuote = false;
202: boolean addToSentFolder = false;
203:
204: FileItem attachFileItem = null;
205:
206: String actionParam = urlResolverService.getActionParam();
207: for (int i = 0; i < fileItems.size(); i++) {
208: FileItem currentFileItem = (FileItem) fileItems.get(i);
209: String fieldName = currentFileItem.getFieldName();
210: if (fieldName.equals("AddToSentFolder")) {
211: String content = currentFileItem.getString("utf-8");
212: addToSentFolder = (content.length() > 0);
213: log.debug("addToSentFolder = " + addToSentFolder);
214: } else if (fieldName.equals("AttachMore")) {
215: String content = currentFileItem.getString("utf-8");
216: attachMore = (content.length() > 0);
217: log.debug("attachMore = " + attachMore);
218: } else if (fieldName.equals("MarkAsQuote")) {
219: String content = currentFileItem.getString("utf-8");
220: markAsQuote = (content.length() > 0);
221: log.debug("markAsQuote = " + markAsQuote);
222: } else if (fieldName.equals("MessageID")) {
223: String content = currentFileItem.getString("utf-8");
224: messageID = Integer.parseInt(content);
225: log.debug("messageID = " + messageID);
226: } else if (fieldName.equals("AttachDesc")) {
227: String content = currentFileItem.getString("utf-8");
228: attachDesc = DisableHtmlTagFilter.filter(content);
229: log.debug("attachDesc = " + attachDesc);
230: attachDesc = InterceptorService.getInstance()
231: .validateContent(attachDesc);
232: } else if (fieldName.equals("vnselector")) {
233: //ignore
234: } else if (fieldName.equals("AttachFilename")) {
235: if (currentFileItem.isFormField() == true) {
236: String localizedMessage = MVNForumResourceBundle
237: .getString(locale,
238: "java.lang.AssertionError.cannot_process_uploaded_attach_file_with_form_field");
239: throw new AssertionError(localizedMessage);
240: //throw new AssertionError("Cannot process uploaded attach file with a form field.");
241: }
242: attachMimeType = currentFileItem.getContentType();
243: attachMimeType = DisableHtmlTagFilter
244: .filter(attachMimeType);
245: attachFileSize = (int) currentFileItem.getSize();
246: if (attachFileSize == 0) {
247: String localizedMessage = MVNForumResourceBundle
248: .getString(
249: locale,
250: "mvncore.exception.BadInputException.cannot_process_upload_with_file_size_is_zero");
251: throw new BadInputException(localizedMessage);
252: //throw new BadInputException("Cannot process an attach file with size = 0. Please check the file size or check if your file is missing.");
253: }
254: String fullFilePath = currentFileItem.getName();
255: attachFilename = FileUtil.getFileName(fullFilePath);
256: attachFilename = DisableHtmlTagFilter
257: .filter(attachFilename);
258: log.debug("attachFilename = " + attachFilename);
259:
260: // now save to attachFileItem
261: attachFileItem = currentFileItem;
262: } else if (fieldName.equals(actionParam)) {
263: // ignore
264: } else {
265: String localizedMessage = MVNForumResourceBundle
266: .getString(
267: locale,
268: "java.lang.AssertionError.cannot_process_field_name",
269: new Object[] { fieldName });
270: throw new AssertionError(localizedMessage);
271: //throw new AssertionError("Cannot process field name = " + fieldName);
272: }
273: } // end for
274: Timestamp now = DateUtil.getCurrentGMTTimestamp();
275:
276: // check constraint
277: MessageBean messageBean = null;
278: try {
279: messageBean = DAOFactory.getMessageDAO().getMessage(
280: messageID);
281: } catch (ObjectNotFoundException e) {
282: String localizedMessage = MVNForumResourceBundle
283: .getString(
284: locale,
285: "mvncore.exception.ObjectNotFoundException.messageid_not_exists",
286: new Object[] { new Integer(messageID) });
287: throw new ObjectNotFoundException(localizedMessage);
288: }
289:
290: if (messageBean.getFolderName().equalsIgnoreCase(
291: MVNForumConstant.MESSAGE_FOLDER_DRAFT) == false) {
292: String localizedMessage = MVNForumResourceBundle
293: .getString(
294: locale,
295: "mvncore.exception.BadInputException.cannot_add_attachment.pm_does_not_in_folder_draft");
296: throw new BadInputException(localizedMessage);
297: //throw new BadInputException("Cannot add attachment because this Private Message does not in the folder Draft");
298: }
299:
300: int logonMemberID = onlineUser.getMemberID();
301:
302: // Check if the message is from this member
303: if (messageBean.getMemberID() != logonMemberID) {
304: String localizedMessage = MVNForumResourceBundle
305: .getString(locale,
306: "mvncore.exception.BadInputException.pm_not_belongs_to_you");
307: throw new BadInputException(localizedMessage);
308: //throw new BadInputException("This Private Message does not belong to you");
309: }
310:
311: // Check if the message is from this logon member
312: AssertionUtil
313: .doAssert(
314: messageBean.getMessageSenderID() == logonMemberID,
315: "Assertion: The MessageSenderID must equals the current logined user.");
316: AssertionUtil
317: .doAssert(messageBean.getMessageSenderName().equals(
318: onlineUser.getMemberName()),
319: "Assertion: The MessageSenderName must equals the current logined user.");
320: //String logonMemberName = onlineUser.getMemberName();
321:
322: // now all contraints/permission have been checked
323: // values that we can init now
324: String creationIP = request.getRemoteAddr();
325: Timestamp attachCreationDate = now;
326: Timestamp attachModifiedDate = now;
327: int attachDownloadCount = 0;
328: int attachOption = 0;// check it
329: int attachStatus = 0;// check it
330: int attachID = DAOFactory.getPmAttachmentDAO().create(
331: logonMemberID, attachFilename, attachFileSize,
332: attachMimeType, attachDesc, creationIP,
333: attachCreationDate, attachModifiedDate,
334: attachDownloadCount, attachOption, attachStatus);
335: try {
336: DAOFactory.getPmAttachMessageDAO().create(messageID,
337: attachID, 0/*type*/, 0/*option*/, 0/*status*/);
338: } catch (DuplicateKeyException ex) {
339: // this should never happen
340: AssertionUtil
341: .doAssert(false,
342: "DuplicateKeyException when create PmAttachMessage");
343: }
344:
345: try {
346: // String filename = AttachmentUtil.getPmAttachFilenameOnDisk(attachID);
347: // log.debug("Message's attachment filename to save to file system = " + filename);
348: // attachFileItem.write(new File(filename));
349: binaryStorageService.storeData(
350: BinaryStorageService.CATEGORY_PM_ATTACHMENT, String
351: .valueOf(attachID), attachFilename,
352: attachFileItem.getInputStream(), attachFileSize, 0,
353: 0, attachMimeType, creationIP);
354:
355: } catch (Exception ex) {
356: log.error("Cannot save the attachment file", ex);
357: DAOFactory.getPmAttachMessageDAO().delete(messageID,
358: attachID);
359: DAOFactory.getPmAttachmentDAO().delete(attachID);
360: String localizedMessage = MVNForumResourceBundle.getString(
361: locale,
362: "java.io.IOException.cannot_save_attach_file");
363: throw new IOException(localizedMessage);
364: //throw new IOException("Cannot save the attachment file to the file system.");
365: }
366:
367: // Update AttachCount in Message table
368: int attachCount = DAOFactory.getPmAttachMessageDAO()
369: .getNumberOfBeans_inMessage(messageID);
370:
371: try {
372: DAOFactory.getMessageDAO().updateAttachCount(messageID,
373: attachCount);
374: } catch (ObjectNotFoundException e) {
375: String localizedMessage = MVNForumResourceBundle
376: .getString(
377: locale,
378: "mvncore.exception.ObjectNotFoundException.messageid_not_exists",
379: new Object[] { new Integer(messageID) });
380: throw new ObjectNotFoundException(localizedMessage);
381: }
382: int maxPrivateMessage = MVNForumConfig.getMaxPrivateMessages();
383:
384: // We will check AttachMore parameter here to REALLY send message to receivers
385: if (attachMore == false) {
386: String[] receivedMembers = StringUtil.getStringArrays(
387: messageBean.getMessageToList(), messageBean
388: .getMessageCcList(), messageBean
389: .getMessageBccList(), ";");
390: Hashtable receivers = MyUtil.checkMembers(receivedMembers,
391: locale);
392: int messageType = messageBean.getMessageType();
393: if (markAsQuote) {
394: // that is, quote cannot be a public message
395: // Actually, if this is a public message, then quote option is disabled from the jsp file
396: messageType = MessageBean.MESSAGE_TYPE_QUOTE;
397: }
398: Collection attachBeans = DAOFactory.getPmAttachmentDAO()
399: .getPmAttachments_inMessage(
400: messageBean.getMessageID()); //messageBean is original message
401:
402: StringBuffer overQuotaReceivers = new StringBuffer(128);
403: for (Enumeration enumeration = receivers.keys(); enumeration
404: .hasMoreElements();) {
405: int receivedMemberID = ((Integer) enumeration
406: .nextElement()).intValue();
407: String receivedMemberName = (String) receivers
408: .get(new Integer(receivedMemberID));
409:
410: int receiverMessageCount = DAOFactory.getMessageDAO()
411: .getNumberOfNonPublicMessages_inMember(
412: receivedMemberID);
413: if (receiverMessageCount >= maxPrivateMessage) {
414: if (overQuotaReceivers.length() > 0) {
415: overQuotaReceivers.append(", ");
416: }
417: overQuotaReceivers.append(receivedMemberName);
418: continue;
419: }
420:
421: // Create REAL message for receivers when finish. It means we have new messageID for each new receiver
422: int eachMessageID = DAOFactory.getMessageDAO().create(
423: MVNForumConstant.MESSAGE_FOLDER_INBOX,
424: receivedMemberID, logonMemberID,
425: messageBean.getMessageSenderName(),
426: messageBean.getMessageToList(),
427: messageBean.getMessageCcList(),
428: messageBean.getMessageBccList(),
429: messageBean.getMessageTopic(),
430: messageBean.getMessageBody(), messageType,
431: messageBean.getMessageOption(),
432: messageBean.getMessageStatus(),
433: MessageBean.MESSAGE_READ_STATUS_DEFAULT,
434: messageBean.getMessageNotify(),
435: messageBean.getMessageIcon(), attachCount,
436: creationIP, now);
437:
438: // Add to statistics
439: if (logonMemberID != receivedMemberID) {
440: DAOFactory.getMessageStatisticsDAO().create(
441: logonMemberID, receivedMemberID, now,
442: messageBean.getMessageAttachCount(),
443: messageBean.getMessageType(),
444: messageBean.getMessageOption(),
445: messageBean.getMessageStatus());
446: }
447: // We must create a loop to create Attach for many receivers and many attachments
448: for (Iterator attachIter = attachBeans.iterator(); attachIter
449: .hasNext();) {
450: PmAttachmentBean pmAttachBean = (PmAttachmentBean) attachIter
451: .next();
452: try {
453: DAOFactory.getPmAttachMessageDAO().create(
454: eachMessageID,
455: pmAttachBean.getPmAttachID(),
456: 0/*type*/, 0/*option*/, 0/*status*/);
457: } catch (DuplicateKeyException ex) {
458: // this should never happen
459: AssertionUtil
460: .doAssert(false,
461: "DuplicateKeyException when create PmAttachMessage");
462: }
463: }
464: } // end of for on receivers
465: request.setAttribute("OverQuotaReceivers",
466: overQuotaReceivers.toString());
467:
468: if (addToSentFolder) {
469: int senderMessageCount = DAOFactory.getMessageDAO()
470: .getNumberOfNonPublicMessages_inMember(
471: logonMemberID);
472: if (senderMessageCount < maxPrivateMessage) {
473: messageType = MessageBean.MESSAGE_TYPE_DEFAULT;// always a default type in the Sent folder
474: int sentMessageID = DAOFactory
475: .getMessageDAO()
476: .create(
477: MVNForumConstant.MESSAGE_FOLDER_SENT,
478: logonMemberID,
479: logonMemberID,
480: messageBean.getMessageSenderName(),
481: messageBean.getMessageToList(),
482: messageBean.getMessageCcList(),
483: messageBean.getMessageBccList(),
484: messageBean.getMessageTopic(),
485: messageBean.getMessageBody(),
486: messageType,
487: messageBean.getMessageOption(),
488: messageBean.getMessageStatus(),
489: MessageBean.MESSAGE_READ_STATUS_DEFAULT,
490: messageBean.getMessageNotify(),
491: messageBean.getMessageIcon(),
492: attachCount, creationIP, now);
493:
494: for (Iterator attachIter = attachBeans.iterator(); attachIter
495: .hasNext();) {
496: PmAttachmentBean pmAttachBean = (PmAttachmentBean) attachIter
497: .next();
498: try {
499: DAOFactory
500: .getPmAttachMessageDAO()
501: .create(
502: sentMessageID,
503: pmAttachBean
504: .getPmAttachID(),
505: 0/*type*/, 0/*option*/, 0/*status*/);
506: } catch (DuplicateKeyException ex) {
507: // this should never happen
508: AssertionUtil
509: .doAssert(false,
510: "DuplicateKeyException when create PmAttachMessage");
511: }
512: }
513: } else {
514: request.setAttribute("AddSentFolderOverQuota",
515: Boolean.TRUE);
516: }
517: }// if add to sent folder
518:
519: // Now delete the message in the draft
520: PrivateMessageUtil.deleteMessageInDatabase(messageID,
521: logonMemberID);
522: }// if not attach more file
523:
524: request.setAttribute("MessageID", String.valueOf(messageID));
525: request.setAttribute("AttachMore", new Boolean(attachMore));
526: request.setAttribute("AddToSentFolder", new Boolean(
527: addToSentFolder));
528: request.setAttribute("MarkAsQuote", new Boolean(markAsQuote));
529: }
530:
531: public void downloadAttachment(HttpServletRequest request,
532: HttpServletResponse response) throws BadInputException,
533: DatabaseException, ObjectNotFoundException, IOException,
534: AuthenticationException {
535:
536: Locale locale = I18nUtil.getLocaleInRequest(request);
537:
538: if (MVNForumConfig.getEnableMessageAttachment() == false) {
539: String localizedMessage = MVNForumResourceBundle
540: .getString(locale,
541: "java.lang.IllegalStateException.message_attachment_is_disabled");
542: throw new IllegalStateException(localizedMessage);
543: //throw new IllegalStateException("Cannot add Attachment because Attachment in Private Message feature is disabled by administrator."); // localization
544: }
545:
546: OnlineUser onlineUser = onlineUserManager
547: .getOnlineUser(request);
548: MVNForumPermission permission = onlineUser.getPermission();
549: permission.ensureIsAuthenticated();
550: permission.ensureCanUseMessage();
551:
552: int attachID = ParamUtil.getParameterInt(request, "attach");
553: int messageID = ParamUtil.getParameterInt(request, "message");
554:
555: PmAttachmentBean pmAttachBean = null;
556: try {
557: pmAttachBean = DAOFactory.getPmAttachmentDAO()
558: .getPmAttachment(attachID);
559: } catch (ObjectNotFoundException e) {
560: String localizedMessage = MVNForumResourceBundle
561: .getString(
562: locale,
563: "mvncore.exception.ObjectNotFoundException.attachmentid_not_exists",
564: new Object[] { new Integer(attachID) });
565: throw new ObjectNotFoundException(localizedMessage);
566: }
567:
568: MessageBean messageBean = null;
569: try {
570: messageBean = DAOFactory.getMessageDAO().getMessage(
571: messageID);
572: } catch (ObjectNotFoundException e) {
573: String localizedMessage = MVNForumResourceBundle
574: .getString(
575: locale,
576: "mvncore.exception.ObjectNotFoundException.messageid_not_exists",
577: new Object[] { new Integer(messageID) });
578: throw new ObjectNotFoundException(localizedMessage);
579: }
580:
581: // Check if the message is from this member
582: boolean isPublicMessage = (messageBean.getMessageType() == MessageBean.MESSAGE_TYPE_PUBLIC);
583:
584: if ((messageBean.getMemberID() != onlineUser.getMemberID())
585: && !isPublicMessage) {
586: String localizedMessage = MVNForumResourceBundle
587: .getString(locale,
588: "mvncore.exception.BadInputException.pm_not_belongs_to_you");
589: throw new BadInputException(localizedMessage);
590: //throw new BadInputException("This Private Message does not belong to you");
591: }
592:
593: // check if the attachment is really in this message
594: DAOFactory.getPmAttachMessageDAO().findByPrimaryKey(messageID,
595: attachID);
596:
597: InputStream inputStream = null;
598: OutputStream outputStream = null;
599: try {
600: /*String attachFilename = AttachmentUtil.getPmAttachFilenameOnDisk(attachID);
601: File attachFile = new File(attachFilename);
602: if ((!attachFile.exists()) || (!attachFile.isFile())) {
603: log.error("Can't find a file " + attachFile + " to be downloaded (or maybe it's directory).");
604: String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_exist_or_not_file_to_be_downloaded");
605: throw new IOException(localizedMessage + " (PmAttachID=" + attachID + ")");
606: //throw new IOException("Can't find a file to be downloaded (or maybe it's directory).");
607: }*/
608:
609: // we should not call this method after done the outputStream
610: // because we dont want exception after download
611: try {
612: DAOFactory.getPmAttachmentDAO().increaseDownloadCount(
613: attachID);
614: } catch (ObjectNotFoundException e) {
615: String localizedMessage = MVNForumResourceBundle
616: .getString(
617: locale,
618: "mvncore.exception.ObjectNotFoundException.attachmentid_not_exists",
619: new Object[] { new Integer(attachID) });
620: throw new ObjectNotFoundException(localizedMessage);
621: }
622:
623: response.setContentType(pmAttachBean.getPmAttachMimeType());
624: response.setHeader("Location", pmAttachBean
625: .getPmAttachFilename());
626:
627: // now use Cache-Control if the MIME type are image
628: if (pmAttachBean.getPmAttachMimeType().startsWith("image/")) {
629: long cacheTime = DateUtil.DAY * 30 / 1000;// 30 days
630: response.setHeader("Cache-Control", "max-age="
631: + cacheTime);
632: }
633:
634: response.setHeader("Content-Disposition",
635: "attachment; filename="
636: + pmAttachBean.getPmAttachFilename());
637:
638: //outputStream.write(buffer);
639: try {
640: inputStream = binaryStorageService.getInputStream(
641: BinaryStorageService.CATEGORY_PM_ATTACHMENT,
642: String.valueOf(attachID), null);
643:
644: outputStream = response.getOutputStream();
645: //FileUtil.popFile(attachFile, outputStream);
646: IOUtils.copy(inputStream, outputStream);
647: } catch (IOException ex) {
648: // cannot throw Exception after we output to the response
649: log.error(
650: "Error while trying to send PM attachment file from server: attachID = "
651: + attachID + ".", ex);
652: }
653: outputStream.flush();
654: outputStream.close();
655: outputStream = null;// no close twice
656: } catch (IOException ex) {
657: throw ex;
658: } finally {
659: if (inputStream != null) {
660: try {
661: inputStream.close();
662: } catch (IOException ex) {
663: }
664: }
665: if (outputStream != null) {
666: try {
667: outputStream.close();
668: } catch (IOException ex) {
669: }
670: }
671: }
672: }
673:
674: public void deleteOrphanPmAttachment() throws DatabaseException {
675:
676: Collection attachBeans = DAOFactory.getPmAttachmentDAO()
677: .getOrphanPmAttachments();
678:
679: // now checking if they DO be orphan
680: for (Iterator iter = attachBeans.iterator(); iter.hasNext();) {
681: PmAttachmentBean pmAttachmentBean = (PmAttachmentBean) iter
682: .next();
683: int pmAttachID = pmAttachmentBean.getPmAttachID();
684: int messageCount = DAOFactory.getPmAttachMessageDAO()
685: .getNumberOfBeans_inPmAttach(pmAttachID);
686: AssertionUtil
687: .doAssert(
688: messageCount <= 0,
689: "This PmAttachID ["
690: + pmAttachID
691: + "] is not orphan because MessageCount = "
692: + messageCount
693: + ". Please report this to mvnForum Developers");
694: }
695:
696: // Now checking correct orphan is done, go ahead and delete the PmAttachment
697: for (Iterator iter = attachBeans.iterator(); iter.hasNext();) {
698: PmAttachmentBean pmAttachmentBean = (PmAttachmentBean) iter
699: .next();
700: int pmAttachID = pmAttachmentBean.getPmAttachID();
701: log.debug("About to delete orphan PmAttachment with ID = "
702: + pmAttachID);
703:
704: //this method already catch the exception
705: //AttachmentUtil.deletePmAttachFilenameOnDisk(pmAttachID);
706: try {
707: binaryStorageService.deleteData(
708: BinaryStorageService.CATEGORY_PM_ATTACHMENT,
709: String.valueOf(pmAttachID), null);
710: } catch (IOException e) {
711: // exception should not occur
712: log.warn(
713: "Cannot BinaryStorage.deleteData with PmAttachID = "
714: + pmAttachID, e);
715: }
716:
717: try {
718: DAOFactory.getPmAttachmentDAO().delete(pmAttachID);
719: } catch (Exception ex) {
720: log.warn(
721: "Cannot delete message attachment in database with PmAttachID = "
722: + pmAttachID, ex);
723: }
724: }
725: }
726: }
|