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

📄 pmattachmentwebhandler.java

📁 解觖java技术中后台无法上传数给的情况
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            // this should never happen
            throw new AssertionException("DuplicateKeyException when create PmAttachMessage");
        }

        try {
//            String filename = AttachmentUtil.getPmAttachFilenameOnDisk(attachID);
//            log.debug("Message's attachment filename to save to file system = " + filename);
//            attachFileItem.write(new File(filename));
            BinaryStorage binaryStorage = ManagerFactory.getBinaryStorage();
            binaryStorage.storeData(BinaryStorage.CATEGORY_PM_ATTACHMENT, String.valueOf(attachID), attachFilename,
                                    attachFileItem.getInputStream(), attachFileSize, 0, 0, attachMimeType, creationIP);

        } catch (Exception ex) {
            log.error("Cannot save the attachment file", ex);
            DAOFactory.getPmAttachMessageDAO().delete(messageID, attachID);
            DAOFactory.getPmAttachmentDAO().delete(attachID);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.cannot_save_attach_file");
            throw new IOException(localizedMessage);
            //throw new IOException("Cannot save the attachment file to the file system.");
        }

        // Update AttachCount in Message table
        int attachCount = DAOFactory.getPmAttachMessageDAO().getNumberOfBeans_inMessage(messageID);

        try {
            DAOFactory.getMessageDAO().updateAttachCount(messageID, attachCount);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.messageid_not_exists", new Object[] {new Integer(messageID)});
            throw new ObjectNotFoundException(localizedMessage);
        }
        int maxPrivateMessage = MVNForumConfig.getMaxPrivateMessage();

        // We will check AttachMore parameter here to REALLY send message to receivers
        if (attachMore == false) {
            String[] receivedMembers = StringUtil.getStringArrays(messageBean.getMessageToList(), messageBean.getMessageCcList(), messageBean.getMessageBccList(), ";");
            Hashtable receivers = MyUtil.checkMembers(receivedMembers, locale);
            int messageType = messageBean.getMessageType();
            if (markAsQuote) {
                // that is, quote cannot be a public message
                // Actually, if this is a public message, then quote option is disabled from the jsp file
                messageType = MessageBean.MESSAGE_TYPE_QUOTE;
            }
            Collection attachBeans = DAOFactory.getPmAttachmentDAO().getPmAttachments_inMessage(messageBean.getMessageID()); //messageBean is original message

            StringBuffer overQuotaReceivers = new StringBuffer(128);
            for (Enumeration enumeration = receivers.keys(); enumeration.hasMoreElements(); ) {
                int receivedMemberID = ((Integer)enumeration.nextElement()).intValue();
                String receivedMemberName = (String)receivers.get(new Integer(receivedMemberID));

                int receiverMessageCount = DAOFactory.getMessageDAO().getNumberOfNonPublicMessages_inMember(receivedMemberID);
                if (receiverMessageCount >= maxPrivateMessage) {
                    if (overQuotaReceivers.length() > 0) {
                        overQuotaReceivers.append(", ");
                    }
                    overQuotaReceivers.append(receivedMemberName);
                    continue;
                }

                // Create REAL message for receivers when finish. It means we have new messageID for each new receiver
                int eachMessageID = DAOFactory.getMessageDAO().create(MVNForumConstant.MESSAGE_FOLDER_INBOX, receivedMemberID, logonMemberID,
                                                    messageBean.getMessageSenderName(), messageBean.getMessageToList(), messageBean.getMessageCcList(),
                                                    messageBean.getMessageBccList(), messageBean.getMessageTopic(), messageBean.getMessageBody(),
                                                    messageType, messageBean.getMessageOption(), messageBean.getMessageStatus(),
                                                    MessageBean.MESSAGE_READ_STATUS_DEFAULT, messageBean.getMessageNotify(), messageBean.getMessageIcon(),
                                                    attachCount, creationIP, now);

                // Add to statistics
                if (logonMemberID != receivedMemberID) {
                    DAOFactory.getMessageStatisticsDAO().create(logonMemberID, receivedMemberID, now,
                            messageBean.getMessageAttachCount(), messageBean.getMessageType(),
                            messageBean.getMessageOption(), messageBean.getMessageStatus());
                }
                // We must create a loop to create Attach for many receivers and many attachments
                for (Iterator attachIter = attachBeans.iterator(); attachIter.hasNext(); ) {
                    PmAttachmentBean pmAttachBean = (PmAttachmentBean)attachIter.next();
                    try {
                        DAOFactory.getPmAttachMessageDAO().create(eachMessageID, pmAttachBean.getPmAttachID(), 0/*type*/, 0/*option*/, 0/*status*/);
                    } catch (DuplicateKeyException ex) {
                        // this should never happen
                        throw new AssertionException("DuplicateKeyException when create PmAttachMessage");
                    }
                }
            } // end of for on receivers
            request.setAttribute("OverQuotaReceivers", overQuotaReceivers.toString());

            if (addToSentFolder) {
                int senderMessageCount = DAOFactory.getMessageDAO().getNumberOfNonPublicMessages_inMember(logonMemberID);
                if (senderMessageCount < maxPrivateMessage) {
                    messageType = MessageBean.MESSAGE_TYPE_DEFAULT;// always a default type in the Sent folder
                    int sentMessageID = DAOFactory.getMessageDAO().create(MVNForumConstant.MESSAGE_FOLDER_SENT, logonMemberID, logonMemberID,
                            messageBean.getMessageSenderName(), messageBean.getMessageToList(), messageBean.getMessageCcList(),
                            messageBean.getMessageBccList(), messageBean.getMessageTopic(), messageBean.getMessageBody(),
                            messageType, messageBean.getMessageOption(), messageBean.getMessageStatus(),
                            MessageBean.MESSAGE_READ_STATUS_DEFAULT, messageBean.getMessageNotify(), messageBean.getMessageIcon(),
                            attachCount, creationIP, now);

                    for (Iterator attachIter = attachBeans.iterator(); attachIter.hasNext(); ) {
                        PmAttachmentBean pmAttachBean = (PmAttachmentBean)attachIter.next();
                        try {
                            DAOFactory.getPmAttachMessageDAO().create(sentMessageID, pmAttachBean.getPmAttachID(), 0/*type*/, 0/*option*/, 0/*status*/);
                        } catch (DuplicateKeyException ex) {
                            // this should never happen
                            throw new AssertionException("DuplicateKeyException when create PmAttachMessage");
                        }
                    }
                } else {
                    request.setAttribute("AddSentFolderOverQuota", Boolean.TRUE);
                }
            }// if add to sent folder

            // Now delete the message in the draft
            PrivateMessageUtil.deleteMessageInDatabase(messageID, logonMemberID);
        }// if not attach more file

        request.setAttribute("MessageID", String.valueOf(messageID));
        request.setAttribute("AttachMore", new Boolean(attachMore));
        request.setAttribute("AddToSentFolder", new Boolean(addToSentFolder));
        request.setAttribute("MarkAsQuote", new Boolean(markAsQuote));
    }

    public void downloadAttachment(HttpServletRequest request, HttpServletResponse response)
        throws BadInputException, DatabaseException, ObjectNotFoundException,
        IOException, AuthenticationException, AssertionException  {

        Locale locale = I18nUtil.getLocaleInRequest(request);

        if (MVNForumConfig.getEnableMessageAttachment() == false) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.AssertionException.message_attachment_is_disabled");
            throw new AssertionException(localizedMessage);
            //throw new AssertionException("Cannot add Attachment because Attachment in Private Message feature is disabled by administrator.");  // localization
        }

        OnlineUser onlineUser = userManager.getOnlineUser(request);
        MVNForumPermission permission = onlineUser.getPermission();
        permission.ensureIsAuthenticated();
        permission.ensureCanUseMessage();

        int attachID  = ParamUtil.getParameterInt(request, "attach");
        int messageID  = ParamUtil.getParameterInt(request, "message");

        PmAttachmentBean pmAttachBean = null;
        try {
            pmAttachBean = DAOFactory.getPmAttachmentDAO().getPmAttachment(attachID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.attachmentid_not_exists", new Object [] {new Integer(attachID)});
            throw new ObjectNotFoundException(localizedMessage);
        }

        MessageBean messageBean = null;
        try {
            messageBean = DAOFactory.getMessageDAO().getMessage(messageID);
        } catch (ObjectNotFoundException e) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.messageid_not_exists", new Object[] {new Integer(messageID)});
            throw new ObjectNotFoundException(localizedMessage);
        }

        // Check if the message is from this member
        boolean isPublicMessage = (messageBean.getMessageType() == MessageBean.MESSAGE_TYPE_PUBLIC);

        if ((messageBean.getMemberID() != onlineUser.getMemberID()) && !isPublicMessage) {
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.pm_not_belongs_to_you");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("This Private Message does not belong to you");
        }

        // check if the attachment is really in this message
        DAOFactory.getPmAttachMessageDAO().findByPrimaryKey(messageID, attachID);

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            /*String attachFilename = AttachmentUtil.getPmAttachFilenameOnDisk(attachID);
            File attachFile = new File(attachFilename);
            if ((!attachFile.exists()) || (!attachFile.isFile())) {
                log.error("Can't find a file " + attachFile + " to be downloaded (or maybe it's directory).");
                String localizedMessage = MVNForumResourceBundle.getString(locale, "java.io.IOException.not_exist_or_not_file_to_be_downloaded");
                throw new IOException(localizedMessage + " (PmAttachID=" + attachID + ")");
                //throw new IOException("Can't find a file to be downloaded (or maybe it's directory).");
            }*/

            // we should not call this method after done the outputStream
            // because we dont want exception after download
            try {
                DAOFactory.getPmAttachmentDAO().increaseDownloadCount(attachID);
            } catch (ObjectNotFoundException e) {
                String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.ObjectNotFoundException.attachmentid_not_exists", new Object[] {new Integer(attachID)});
                throw new ObjectNotFoundException(localizedMessage);
            }

            response.setContentType(pmAttachBean.getPmAttachMimeType());
            response.setHeader("Location", pmAttachBean.getPmAttachFilename());

            // now use Cache-Control if the MIME type are image
            if (pmAttachBean.getPmAttachMimeType().startsWith("image/")) {
                long cacheTime = DateUtil.DAY * 30 / 1000;// 30 days
                response.setHeader("Cache-Control", "max-age=" + cacheTime);
            }

            response.setHeader("Content-Disposition", "attachment; filename=" + pmAttachBean.getPmAttachFilename());

            //outputStream.write(buffer);
            try {
                BinaryStorage binaryStorage = ManagerFactory.getBinaryStorage();
                inputStream = binaryStorage.getInputStream(BinaryStorage.CATEGORY_PM_ATTACHMENT, String.valueOf(attachID), null);

                outputStream = response.getOutputStream();
                //FileUtil.popFile(attachFile, outputStream);
                IOUtils.copy(inputStream, outputStream);
            } catch (IOException ex) {
                // cannot throw Exception after we output to the response
                log.error("Error while trying to send PM attachment file from server: attachID = " + attachID + ".", ex);
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;// no close twice
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) { }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) { }
            }
        }
    }

    void deleteOrphanPmAttachment() throws DatabaseException, AssertionException {

        Collection attachBeans = DAOFactory.getPmAttachmentDAO().getOrphanPmAttachments();

        // now checking if they DO be orphan
        for (Iterator iter = attachBeans.iterator(); iter.hasNext(); ) {
            PmAttachmentBean pmAttachmentBean = (PmAttachmentBean)iter.next();
            int pmAttachID = pmAttachmentBean.getPmAttachID();
            int messageCount = DAOFactory.getPmAttachMessageDAO().getNumberOfBeans_inPmAttach(pmAttachID);
            if (messageCount > 0) {
                // do not need to be localized
                throw new AssertionException("This PmAttachID [" + pmAttachID + "] is not orphan because MessageCount = " + messageCount + ". Please report this to mvnForum Developers");
            }
        }

        BinaryStorage binaryStorage = ManagerFactory.getBinaryStorage();
        // Now checking correct orphan is done, go ahead and delete the PmAttachment
        for (Iterator iter = attachBeans.iterator(); iter.hasNext(); ) {
            PmAttachmentBean pmAttachmentBean = (PmAttachmentBean)iter.next();
            int pmAttachID = pmAttachmentBean.getPmAttachID();
            log.debug("About to delete orphan PmAttachment with ID = " + pmAttachID);

            //this method already catch the exception
            //AttachmentUtil.deletePmAttachFilenameOnDisk(pmAttachID);
            try {
                binaryStorage.deleteData(BinaryStorage.CATEGORY_PM_ATTACHMENT, String.valueOf(pmAttachID), null);
            } catch (IOException e) {
                // exception should not occur
                log.warn("Cannot BinaryStorage.deleteData with PmAttachID = " + pmAttachID, e);
            }

            try {
                DAOFactory.getPmAttachmentDAO().delete(pmAttachID);
            } catch (Exception ex) {
                log.warn("Cannot delete message attachment in database with PmAttachID = " + pmAttachID, ex);
            }
        }
    }
}

⌨️ 快捷键说明

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