You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by ma...@apache.org on 2014/03/20 09:16:10 UTC

svn commit: r1579559 [13/23] - in /james/hupa/trunk: ./ client/ client/src/main/java/com/google/web/bindery/requestfactory/server/ client/src/main/java/org/apache/hupa/ client/src/main/java/org/apache/hupa/client/ client/src/main/java/org/apache/hupa/c...

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchFoldersServiceImpl.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchFoldersServiceImpl.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchFoldersServiceImpl.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchFoldersServiceImpl.java Thu Mar 20 08:16:02 2014
@@ -1,171 +1,171 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.mail.Folder;
-import javax.mail.MessagingException;
-
-import org.apache.hupa.shared.data.ImapFolderImpl;
-import org.apache.hupa.shared.domain.ImapFolder;
-import org.apache.hupa.shared.domain.User;
-import org.apache.hupa.shared.exception.HupaException;
-
-import com.sun.mail.imap.IMAPStore;
-
-public class FetchFoldersServiceImpl extends AbstractService implements FetchFoldersService {
-
-    @Override
-    public List<ImapFolder> fetch(ImapFolder imapFolder, Boolean recursive) throws MessagingException, HupaException {
-        if(recursive){
-            return this.pullAll();
-        }
-        try {
-            Folder folder = null;
-            IMAPStore store = cache.get(getUser());
-            if (imapFolder == null) {
-                folder = store.getDefaultFolder();
-            } else {
-                folder = store.getFolder(imapFolder.getFullName());
-            }
-            List<ImapFolder> imapFolders = new ArrayList<ImapFolder>();
-            for (Folder f : folder.list()) {
-                ImapFolder i = createImapFolder(f);
-                imapFolders.add(i);
-            }
-            return imapFolders;
-        } catch (MessagingException e) {
-            e.printStackTrace();
-            throw new MessagingException();
-        }
-    }
-    
-    public List<ImapFolder> pullAll() throws MessagingException, HupaException {
-        User user = getUser();
-        try {
-
-            // get the store for the user
-            IMAPStore store = cache.get(user);
-            com.sun.mail.imap.IMAPFolder folder = (com.sun.mail.imap.IMAPFolder) store.getDefaultFolder();
-
-            // List of mail 'root' imap folders
-            List<ImapFolder> imapFolders = new ArrayList<ImapFolder>();
-
-            // Create IMAPFolder tree list
-            for (Folder f : folder.list()) {
-                ImapFolder imapFolder = createIMAPFolder(f);
-                imapFolders.add(imapFolder);
-                walkFolders(f, imapFolder);
-            }
-
-            return imapFolders;
-        } catch (MessagingException e) {
-            e.printStackTrace();
-            logger.error("Unable to get folders for User " + user, e);
-            e.printStackTrace();
-            throw new MessagingException();
-        }
-    }
-
-    /**
-     * Walk through the folder's sub-folders and add sub-folders to current
-     * imapFolder
-     * 
-     * @param folder
-     *            Folder to walk
-     * @param imapFolder
-     *            Current IMAPFolder
-     * @throws ActionException
-     *             If an error occurs
-     * @throws MessagingException
-     *             If an error occurs
-     * @throws HupaException
-     */
-    private void walkFolders(Folder folder, ImapFolder imapFolder) throws MessagingException, HupaException {
-        for (Folder f : folder.list()) {
-            ImapFolder iFolder = createIMAPFolder(f);
-            imapFolder.getChildren().add(iFolder);
-            walkFolders(f, iFolder);
-        }
-    }
-
-    private ImapFolder createIMAPFolder(Folder folder) throws MessagingException, HupaException {
-
-        String fullName = folder.getFullName();
-        String delimiter;
-        ImapFolder iFolder = null;
-
-        try {
-            logger.debug("Creating folder: " + fullName + " for user: " + getUser());
-            delimiter = String.valueOf(folder.getSeparator());
-            iFolder = new ImapFolderImpl(fullName);
-            iFolder.setHasChildren(true);
-            iFolder.setDelimiter(delimiter);
-            if ("[Gmail]".equals(folder.getFullName()))
-                return iFolder;
-            iFolder.setMessageCount(folder.getMessageCount());
-            iFolder.setSubscribed(folder.isSubscribed());
-            iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
-        } catch (MessagingException e) {
-            logger.error("Unable to construct folder " + folder.getFullName(), e);
-        }
-
-        return iFolder;
-    }
-
-    /**
-     * Create a new IMAPFolder from the given Folder
-     * 
-     * @param folder
-     *            Current folder
-     * @return imapFolder Created IMAPFolder
-     * @throws HupaException
-     * @throws Exception
-     *             If an error occurs
-     * @throws MessagingException
-     *             If an error occurs
-     */
-    private ImapFolder createImapFolder(Folder folder) throws HupaException {
-        String fullName = folder.getFullName();
-        String delimiter;
-        ImapFolder iFolder = null;
-        try {
-            new RuntimeException().printStackTrace();
-            System.out.println("Creating folder2: " + fullName + " for user: " + this.getUser());
-            delimiter = String.valueOf(folder.getSeparator());
-            iFolder = new ImapFolderImpl(fullName);
-            iFolder.setDelimiter(delimiter);
-            if ("[Gmail]".equals(folder.getFullName()))
-                return iFolder;
-            iFolder.setMessageCount(folder.getMessageCount());
-            iFolder.setSubscribed(folder.isSubscribed());
-            iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
-            if (folder.list().length != 0) {
-                iFolder.setHasChildren(true);
-            }
-        } catch (MessagingException e) {
-            e.printStackTrace();
-        }
-        return iFolder;
-    }
-
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.mail.Folder;
+import javax.mail.MessagingException;
+
+import org.apache.hupa.shared.data.ImapFolderImpl;
+import org.apache.hupa.shared.domain.ImapFolder;
+import org.apache.hupa.shared.domain.User;
+import org.apache.hupa.shared.exception.HupaException;
+
+import com.sun.mail.imap.IMAPStore;
+
+public class FetchFoldersServiceImpl extends AbstractService implements FetchFoldersService {
+
+    @Override
+    public List<ImapFolder> fetch(ImapFolder imapFolder, Boolean recursive) throws MessagingException, HupaException {
+        if(recursive){
+            return this.pullAll();
+        }
+        try {
+            Folder folder = null;
+            IMAPStore store = cache.get(getUser());
+            if (imapFolder == null) {
+                folder = store.getDefaultFolder();
+            } else {
+                folder = store.getFolder(imapFolder.getFullName());
+            }
+            List<ImapFolder> imapFolders = new ArrayList<ImapFolder>();
+            for (Folder f : folder.list()) {
+                ImapFolder i = createImapFolder(f);
+                imapFolders.add(i);
+            }
+            return imapFolders;
+        } catch (MessagingException e) {
+            e.printStackTrace();
+            throw new MessagingException();
+        }
+    }
+
+    public List<ImapFolder> pullAll() throws MessagingException, HupaException {
+        User user = getUser();
+        try {
+
+            // get the store for the user
+            IMAPStore store = cache.get(user);
+            com.sun.mail.imap.IMAPFolder folder = (com.sun.mail.imap.IMAPFolder) store.getDefaultFolder();
+
+            // List of mail 'root' imap folders
+            List<ImapFolder> imapFolders = new ArrayList<ImapFolder>();
+
+            // Create IMAPFolder tree list
+            for (Folder f : folder.list()) {
+                ImapFolder imapFolder = createIMAPFolder(f);
+                imapFolders.add(imapFolder);
+                walkFolders(f, imapFolder);
+            }
+
+            return imapFolders;
+        } catch (MessagingException e) {
+            e.printStackTrace();
+            logger.error("Unable to get folders for User " + user, e);
+            e.printStackTrace();
+            throw new MessagingException();
+        }
+    }
+
+    /**
+     * Walk through the folder's sub-folders and add sub-folders to current
+     * imapFolder
+     *
+     * @param folder
+     *            Folder to walk
+     * @param imapFolder
+     *            Current IMAPFolder
+     * @throws ActionException
+     *             If an error occurs
+     * @throws MessagingException
+     *             If an error occurs
+     * @throws HupaException
+     */
+    private void walkFolders(Folder folder, ImapFolder imapFolder) throws MessagingException, HupaException {
+        for (Folder f : folder.list()) {
+            ImapFolder iFolder = createIMAPFolder(f);
+            imapFolder.getChildren().add(iFolder);
+            walkFolders(f, iFolder);
+        }
+    }
+
+    private ImapFolder createIMAPFolder(Folder folder) throws MessagingException, HupaException {
+
+        String fullName = folder.getFullName();
+        String delimiter;
+        ImapFolder iFolder = null;
+
+        try {
+            logger.debug("Creating folder: " + fullName + " for user: " + getUser());
+            delimiter = String.valueOf(folder.getSeparator());
+            iFolder = new ImapFolderImpl(fullName);
+            iFolder.setHasChildren(true);
+            iFolder.setDelimiter(delimiter);
+            if ("[Gmail]".equals(folder.getFullName()))
+                return iFolder;
+            iFolder.setMessageCount(folder.getMessageCount());
+            iFolder.setSubscribed(folder.isSubscribed());
+            iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
+        } catch (MessagingException e) {
+            logger.error("Unable to construct folder " + folder.getFullName(), e);
+        }
+
+        return iFolder;
+    }
+
+    /**
+     * Create a new IMAPFolder from the given Folder
+     *
+     * @param folder
+     *            Current folder
+     * @return imapFolder Created IMAPFolder
+     * @throws HupaException
+     * @throws Exception
+     *             If an error occurs
+     * @throws MessagingException
+     *             If an error occurs
+     */
+    private ImapFolder createImapFolder(Folder folder) throws HupaException {
+        String fullName = folder.getFullName();
+        String delimiter;
+        ImapFolder iFolder = null;
+        try {
+            new RuntimeException().printStackTrace();
+            System.out.println("Creating folder2: " + fullName + " for user: " + this.getUser());
+            delimiter = String.valueOf(folder.getSeparator());
+            iFolder = new ImapFolderImpl(fullName);
+            iFolder.setDelimiter(delimiter);
+            if ("[Gmail]".equals(folder.getFullName()))
+                return iFolder;
+            iFolder.setMessageCount(folder.getMessageCount());
+            iFolder.setSubscribed(folder.isSubscribed());
+            iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
+            if (folder.list().length != 0) {
+                iFolder.setHasChildren(true);
+            }
+        } catch (MessagingException e) {
+            e.printStackTrace();
+        }
+        return iFolder;
+    }
+
+}

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesBaseServiceImpl.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesBaseServiceImpl.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesBaseServiceImpl.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesBaseServiceImpl.java Thu Mar 20 08:16:02 2014
@@ -1,233 +1,233 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.mail.Address;
-import javax.mail.FetchProfile;
-import javax.mail.Message;
-import javax.mail.MessagingException;
-import javax.mail.Multipart;
-import javax.mail.Part;
-import javax.mail.UIDFolder;
-import javax.mail.internet.MimeMessage.RecipientType;
-
-import org.apache.hupa.server.handler.JavamailUtil;
-import org.apache.hupa.server.preferences.UserPreferencesStorage;
-import org.apache.hupa.server.utils.MessageUtils;
-import org.apache.hupa.shared.data.FetchMessagesResultImpl;
-import org.apache.hupa.shared.data.ImapFolderImpl;
-import org.apache.hupa.shared.data.MessageImpl.IMAPFlag;
-import org.apache.hupa.shared.data.TagImpl;
-import org.apache.hupa.shared.domain.FetchMessagesAction;
-import org.apache.hupa.shared.domain.FetchMessagesResult;
-import org.apache.hupa.shared.domain.ImapFolder;
-import org.apache.hupa.shared.domain.Tag;
-import org.apache.hupa.shared.domain.User;
-import org.apache.hupa.shared.exception.HupaException;
-
-import com.google.inject.Inject;
-import com.sun.mail.imap.IMAPStore;
-
-public abstract class FetchMessagesBaseServiceImpl extends AbstractService{
-
-    @Inject protected UserPreferencesStorage userPreferences;
-    
-    public FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException{
-        User user = getUser();
-        ImapFolder folder = action.getFolder();
-        if (folder == null) {
-            folder = new ImapFolderImpl(user.getSettings().getInboxFolderName());
-        }
-        com.sun.mail.imap.IMAPFolder f = null;
-        int start = action.getStart();
-        int offset = action.getOffset();
-        try {
-            IMAPStore store = cache.get(user);
-            
-            f =  (com.sun.mail.imap.IMAPFolder)store.getFolder(folder.getFullName());
-
-             // check if the folder is open, if not open it read only
-            if (f.isOpen() == false) {
-                f.open(com.sun.mail.imap.IMAPFolder.READ_ONLY);
-            }
-
-            // if the folder is empty we have no need to process 
-            int exists = f.getMessageCount();
-            if (exists == 0) {
-                 return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset, 0, 0);
-            }        
-            
-            MessageConvertArray convArray = getMessagesToConvert(f,action);
-            return new FetchMessagesResultImpl(convert(offset, f, convArray.getMesssages()),start, offset,convArray.getRealCount(),f.getUnreadMessageCount());
-        } catch (MessagingException e) {
-            logger.info("Error fetching messages in folder: " + folder.getFullName() + " " + e.getMessage());
-            // Folder can not contain messages
-            return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset, 0, 0);
-        } finally {
-            if (f != null && f.isOpen()) {
-                try {
-                    f.close(false);
-                } catch (MessagingException e) {
-                    // we don't care to much about an exception on close here...
-                }
-            }
-        }
-    }
-
-
-    protected abstract MessageConvertArray getMessagesToConvert(com.sun.mail.imap.IMAPFolder f, FetchMessagesAction action) throws MessagingException;
-    
-    protected List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
-        List<org.apache.hupa.shared.domain.Message> mList = new ArrayList<org.apache.hupa.shared.domain.Message>();
-        // Setup fetchprofile to limit the stuff which is fetched 
-        FetchProfile fp = new FetchProfile();
-        fp.add(FetchProfile.Item.ENVELOPE);
-        fp.add(FetchProfile.Item.FLAGS);
-        fp.add(FetchProfile.Item.CONTENT_INFO);
-        fp.add(UIDFolder.FetchProfileItem.UID);
-        folder.fetch(messages, fp);
-        
-        // loop over the fetched messages
-        for (int i = 0; i < messages.length && i < offset; i++) {
-            org.apache.hupa.shared.domain.Message msg = new org.apache.hupa.shared.data.MessageImpl();
-            Message m = messages[i];                
-            String from = null;
-            if (m.getFrom() != null && m.getFrom().length >0 ) {
-                from = MessageUtils.decodeText(m.getFrom()[0].toString());
-            }
-            msg.setFrom(from);
-
-            String replyto = null;
-            if (m.getReplyTo() != null && m.getReplyTo().length >0 ) {
-                replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
-            }
-            msg.setReplyto(replyto);
-            
-            ArrayList<String> to = new ArrayList<String>();
-            // Add to addresses
-            Address[] toArray = m.getRecipients(RecipientType.TO);
-            if (toArray != null) {
-                for (Address addr : toArray) {
-                    String mailTo = MessageUtils.decodeText(addr.toString());
-                    to.add(mailTo);
-                }
-            }
-            msg.setTo(to);
-            
-            // Check if a subject exist and if so decode it
-            String subject = m.getSubject();
-            if (subject != null) {
-                subject = MessageUtils.decodeText(subject);
-            }
-            msg.setSubject(subject);
-            
-            // Add cc addresses
-            Address[] ccArray = m.getRecipients(RecipientType.CC);
-            ArrayList<String> cc = new ArrayList<String>();
-            if (ccArray != null) {
-                for (Address addr : ccArray) {
-                    String mailCc = MessageUtils.decodeText(addr.toString());
-                    cc.add(mailCc);
-                }                
-            }
-            msg.setCc(cc);
-
-            userPreferences.addContact(from);
-            userPreferences.addContact(to);
-            userPreferences.addContact(replyto);
-            userPreferences.addContact(cc);
-
-            // Using sentDate since received date is not useful in the view when using fetchmail
-            msg.setReceivedDate(m.getSentDate());
-
-            // Add flags
-            ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());
-          
-            ArrayList<Tag> tags = new ArrayList<Tag>();
-            for (String flag : m.getFlags().getUserFlags()) {
-                if (flag.startsWith(TagImpl.PREFIX)) {
-                    tags.add(new TagImpl(flag.substring(TagImpl.PREFIX.length())));
-                }
-            }
-            
-            msg.setUid(folder.getUID(m));
-            msg.setFlags(iFlags);
-            msg.setTags(tags);
-            try {
-                msg.setHasAttachments(hasAttachment(m));
-            } catch (MessagingException e) {
-                logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:" + msg.getSubject() + " cause:" + e.getMessage());
-                logger.info("");
-            }
-            mList.add(0, msg);
-            
-        }
-        return mList;
-    }
-
-    private boolean hasAttachment(Message message) throws MessagingException {
-        if (message.getContentType().startsWith("multipart/")) {
-            try {
-                Object content;
-
-                content = message.getContent();
-
-                if (content instanceof Multipart) {
-                    Multipart mp = (Multipart) content;
-                    if (mp.getCount() > 1) {
-                        for (int i = 0; i < mp.getCount(); i++) {
-                            String disp = mp.getBodyPart(i).getDisposition();
-                            if (disp != null
-                                    && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
-                                return true;
-                            }
-                        }
-                    }
-
-                }
-            } catch (IOException e) {
-                logger.error("Error while get content of message " + message.getMessageNumber());
-            }
-            
-        }
-        return false;
-    }   
-    protected final class MessageConvertArray {
-        private Message[] messages;
-        private int realCount;
-
-        public MessageConvertArray(int realCount, Message[] messages) {
-            this.messages = messages;
-            this.realCount = realCount;
-        }
-        
-        public int getRealCount() {
-            return realCount;
-        }
-        
-        public Message[] getMesssages() {
-            return messages;
-        }
-    }
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.mail.Address;
+import javax.mail.FetchProfile;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.Part;
+import javax.mail.UIDFolder;
+import javax.mail.internet.MimeMessage.RecipientType;
+
+import org.apache.hupa.server.handler.JavamailUtil;
+import org.apache.hupa.server.preferences.UserPreferencesStorage;
+import org.apache.hupa.server.utils.MessageUtils;
+import org.apache.hupa.shared.data.FetchMessagesResultImpl;
+import org.apache.hupa.shared.data.ImapFolderImpl;
+import org.apache.hupa.shared.data.MessageImpl.IMAPFlag;
+import org.apache.hupa.shared.data.TagImpl;
+import org.apache.hupa.shared.domain.FetchMessagesAction;
+import org.apache.hupa.shared.domain.FetchMessagesResult;
+import org.apache.hupa.shared.domain.ImapFolder;
+import org.apache.hupa.shared.domain.Tag;
+import org.apache.hupa.shared.domain.User;
+import org.apache.hupa.shared.exception.HupaException;
+
+import com.google.inject.Inject;
+import com.sun.mail.imap.IMAPStore;
+
+public abstract class FetchMessagesBaseServiceImpl extends AbstractService{
+
+    @Inject protected UserPreferencesStorage userPreferences;
+
+    public FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException{
+        User user = getUser();
+        ImapFolder folder = action.getFolder();
+        if (folder == null) {
+            folder = new ImapFolderImpl(user.getSettings().getInboxFolderName());
+        }
+        com.sun.mail.imap.IMAPFolder f = null;
+        int start = action.getStart();
+        int offset = action.getOffset();
+        try {
+            IMAPStore store = cache.get(user);
+
+            f =  (com.sun.mail.imap.IMAPFolder)store.getFolder(folder.getFullName());
+
+             // check if the folder is open, if not open it read only
+            if (f.isOpen() == false) {
+                f.open(com.sun.mail.imap.IMAPFolder.READ_ONLY);
+            }
+
+            // if the folder is empty we have no need to process
+            int exists = f.getMessageCount();
+            if (exists == 0) {
+                 return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset, 0, 0);
+            }
+
+            MessageConvertArray convArray = getMessagesToConvert(f,action);
+            return new FetchMessagesResultImpl(convert(offset, f, convArray.getMesssages()),start, offset,convArray.getRealCount(),f.getUnreadMessageCount());
+        } catch (MessagingException e) {
+            logger.info("Error fetching messages in folder: " + folder.getFullName() + " " + e.getMessage());
+            // Folder can not contain messages
+            return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset, 0, 0);
+        } finally {
+            if (f != null && f.isOpen()) {
+                try {
+                    f.close(false);
+                } catch (MessagingException e) {
+                    // we don't care to much about an exception on close here...
+                }
+            }
+        }
+    }
+
+
+    protected abstract MessageConvertArray getMessagesToConvert(com.sun.mail.imap.IMAPFolder f, FetchMessagesAction action) throws MessagingException;
+
+    protected List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
+        List<org.apache.hupa.shared.domain.Message> mList = new ArrayList<org.apache.hupa.shared.domain.Message>();
+        // Setup fetchprofile to limit the stuff which is fetched
+        FetchProfile fp = new FetchProfile();
+        fp.add(FetchProfile.Item.ENVELOPE);
+        fp.add(FetchProfile.Item.FLAGS);
+        fp.add(FetchProfile.Item.CONTENT_INFO);
+        fp.add(UIDFolder.FetchProfileItem.UID);
+        folder.fetch(messages, fp);
+
+        // loop over the fetched messages
+        for (int i = 0; i < messages.length && i < offset; i++) {
+            org.apache.hupa.shared.domain.Message msg = new org.apache.hupa.shared.data.MessageImpl();
+            Message m = messages[i];
+            String from = null;
+            if (m.getFrom() != null && m.getFrom().length >0 ) {
+                from = MessageUtils.decodeText(m.getFrom()[0].toString());
+            }
+            msg.setFrom(from);
+
+            String replyto = null;
+            if (m.getReplyTo() != null && m.getReplyTo().length >0 ) {
+                replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
+            }
+            msg.setReplyto(replyto);
+
+            ArrayList<String> to = new ArrayList<String>();
+            // Add to addresses
+            Address[] toArray = m.getRecipients(RecipientType.TO);
+            if (toArray != null) {
+                for (Address addr : toArray) {
+                    String mailTo = MessageUtils.decodeText(addr.toString());
+                    to.add(mailTo);
+                }
+            }
+            msg.setTo(to);
+
+            // Check if a subject exist and if so decode it
+            String subject = m.getSubject();
+            if (subject != null) {
+                subject = MessageUtils.decodeText(subject);
+            }
+            msg.setSubject(subject);
+
+            // Add cc addresses
+            Address[] ccArray = m.getRecipients(RecipientType.CC);
+            ArrayList<String> cc = new ArrayList<String>();
+            if (ccArray != null) {
+                for (Address addr : ccArray) {
+                    String mailCc = MessageUtils.decodeText(addr.toString());
+                    cc.add(mailCc);
+                }
+            }
+            msg.setCc(cc);
+
+            userPreferences.addContact(from);
+            userPreferences.addContact(to);
+            userPreferences.addContact(replyto);
+            userPreferences.addContact(cc);
+
+            // Using sentDate since received date is not useful in the view when using fetchmail
+            msg.setReceivedDate(m.getSentDate());
+
+            // Add flags
+            ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());
+
+            ArrayList<Tag> tags = new ArrayList<Tag>();
+            for (String flag : m.getFlags().getUserFlags()) {
+                if (flag.startsWith(TagImpl.PREFIX)) {
+                    tags.add(new TagImpl(flag.substring(TagImpl.PREFIX.length())));
+                }
+            }
+
+            msg.setUid(folder.getUID(m));
+            msg.setFlags(iFlags);
+            msg.setTags(tags);
+            try {
+                msg.setHasAttachments(hasAttachment(m));
+            } catch (MessagingException e) {
+                logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:" + msg.getSubject() + " cause:" + e.getMessage());
+                logger.info("");
+            }
+            mList.add(0, msg);
+
+        }
+        return mList;
+    }
+
+    private boolean hasAttachment(Message message) throws MessagingException {
+        if (message.getContentType().startsWith("multipart/")) {
+            try {
+                Object content;
+
+                content = message.getContent();
+
+                if (content instanceof Multipart) {
+                    Multipart mp = (Multipart) content;
+                    if (mp.getCount() > 1) {
+                        for (int i = 0; i < mp.getCount(); i++) {
+                            String disp = mp.getBodyPart(i).getDisposition();
+                            if (disp != null
+                                    && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
+                                return true;
+                            }
+                        }
+                    }
+
+                }
+            } catch (IOException e) {
+                logger.error("Error while get content of message " + message.getMessageNumber());
+            }
+
+        }
+        return false;
+    }
+    protected final class MessageConvertArray {
+        private Message[] messages;
+        private int realCount;
+
+        public MessageConvertArray(int realCount, Message[] messages) {
+            this.messages = messages;
+            this.realCount = realCount;
+        }
+
+        public int getRealCount() {
+            return realCount;
+        }
+
+        public Message[] getMesssages() {
+            return messages;
+        }
+    }
+}

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesService.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesService.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesService.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesService.java Thu Mar 20 08:16:02 2014
@@ -1,34 +1,34 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import java.util.List;
-
-import javax.mail.Message;
-import javax.mail.MessagingException;
-
-import org.apache.hupa.shared.domain.FetchMessagesAction;
-import org.apache.hupa.shared.domain.FetchMessagesResult;
-import org.apache.hupa.shared.exception.HupaException;
-
-public interface FetchMessagesService {
-    FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException;
-    List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException;
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import java.util.List;
+
+import javax.mail.Message;
+import javax.mail.MessagingException;
+
+import org.apache.hupa.shared.domain.FetchMessagesAction;
+import org.apache.hupa.shared.domain.FetchMessagesResult;
+import org.apache.hupa.shared.exception.HupaException;
+
+public interface FetchMessagesService {
+    FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException;
+    List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException;
+}

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesServiceImpl.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesServiceImpl.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesServiceImpl.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/FetchMessagesServiceImpl.java Thu Mar 20 08:16:02 2014
@@ -1,306 +1,306 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.mail.Address;
-import javax.mail.FetchProfile;
-import javax.mail.Message;
-import javax.mail.MessagingException;
-import javax.mail.Multipart;
-import javax.mail.Part;
-import javax.mail.UIDFolder;
-import javax.mail.internet.MimeMessage.RecipientType;
-import javax.mail.search.BodyTerm;
-import javax.mail.search.FromStringTerm;
-import javax.mail.search.OrTerm;
-import javax.mail.search.SearchTerm;
-import javax.mail.search.SubjectTerm;
-
-import org.apache.hupa.server.handler.JavamailUtil;
-import org.apache.hupa.server.preferences.UserPreferencesStorage;
-import org.apache.hupa.server.utils.MessageUtils;
-import org.apache.hupa.shared.data.FetchMessagesResultImpl;
-import org.apache.hupa.shared.data.MessageImpl.IMAPFlag;
-import org.apache.hupa.shared.data.TagImpl;
-import org.apache.hupa.shared.domain.FetchMessagesAction;
-import org.apache.hupa.shared.domain.FetchMessagesResult;
-import org.apache.hupa.shared.domain.Tag;
-import org.apache.hupa.shared.domain.User;
-import org.apache.hupa.shared.exception.HupaException;
-
-import com.google.inject.Inject;
-import com.sun.mail.imap.IMAPFolder;
-import com.sun.mail.imap.IMAPStore;
-
-public class FetchMessagesServiceImpl extends AbstractService implements FetchMessagesService {
-
-    @Inject protected UserPreferencesStorage userPreferences;
-
-    public FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException {
-        User user = getUser();
-        // ImapFolder folder = action.getFolder();
-        if (action.getFolder() == null || action.getFolder().getFullName() == null) {
-            // folder = new
-            // ImapFolderImpl(user.getSettings().getInboxFolderName());
-            throw new IllegalArgumentException("why you want to ask us for messages in a null folder");
-        }
-        com.sun.mail.imap.IMAPFolder f = null;
-        int start = action.getStart();
-        int offset = action.getOffset();
-        try {
-            IMAPStore store = cache.get(user);
-
-            f = (com.sun.mail.imap.IMAPFolder) store.getFolder(action.getFolder().getFullName());
-
-            // check if the folder is open, if not open it read only
-            if (f.isOpen() == false) {
-                f.open(com.sun.mail.imap.IMAPFolder.READ_ONLY);
-            }
-
-            // if the folder is empty we have no need to process
-            int exists = f.getMessageCount();
-            if (exists == 0) {
-                return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start,
-                        offset, 0, 0);
-            }
-
-            MessageConvertArray convArray = getMessagesToConvert(f, action);
-            return new FetchMessagesResultImpl(convert(offset, f, convArray.getMesssages()), start, offset,
-                    convArray.getRealCount(), f.getUnreadMessageCount());
-        } catch (MessagingException e) {
-            logger.info("Error fetching messages in folder: " + action.getFolder().getFullName() + " " + e.getMessage());
-            // Folder can not contain messages
-            return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset,
-                    0, 0);
-        } finally {
-            if (f != null && f.isOpen()) {
-                try {
-                    f.close(false);
-                } catch (MessagingException e) {
-                    // we don't care to much about an exception on close here...
-                }
-            }
-        }
-    }
-
-    protected MessageConvertArray getMessagesToConvert(IMAPFolder f, FetchMessagesAction action)
-            throws MessagingException, HupaException {
-
-        String searchString = action.getSearchString();
-        int start = action.getStart();
-        int offset = action.getOffset();
-        int end = start + offset;
-        Message[] messages;
-        int exists;
-        // check if a searchString was given, and if so use it
-        if (searchString == null) {
-            exists = f.getMessageCount();
-
-            if (end > exists) {
-                end = exists;
-            }
-
-            int firstIndex = exists - end + 1;
-            if (firstIndex < 1) {
-                firstIndex = 1;
-            }
-            int lastIndex = exists - start;
-
-            messages = f.getMessages(firstIndex, lastIndex);
-        } else {
-            SearchTerm subjectTerm = new SubjectTerm(searchString);
-            SearchTerm fromTerm = new FromStringTerm(searchString);
-            SearchTerm bodyTerm = new BodyTerm(searchString);
-            SearchTerm orTerm = new OrTerm(new SearchTerm[] { subjectTerm, fromTerm, bodyTerm });
-            Message[] tmpMessages = f.search(orTerm);
-            if (end > tmpMessages.length) {
-                end = tmpMessages.length;
-            }
-            exists = tmpMessages.length;
-
-            int firstIndex = exists - end;
-
-            if (tmpMessages.length > firstIndex) {
-                List<Message> mList = new ArrayList<Message>();
-                for (int i = firstIndex; i < tmpMessages.length; i++) {
-                    if (i == end)
-                        break;
-                    mList.add(tmpMessages[i]);
-                }
-                messages = mList.toArray(new Message[mList.size()]);
-            } else {
-                messages = new Message[0];
-            }
-
-        }
-        logger.debug("Fetching messages for user: " + getUser() + " returns: " + messages.length + " messages in "
-                + f.getFullName());
-
-        return new MessageConvertArray(exists, messages);
-    }
-    
-
-    public List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder,
-            Message[] messages) throws MessagingException {
-        List<org.apache.hupa.shared.domain.Message> mList = new ArrayList<org.apache.hupa.shared.domain.Message>();
-        
-        // Setup fetchprofile to limit the stuff which is fetched
-        FetchProfile fp = getFetchProfile();
-        folder.fetch(messages, fp);
-        
-        // loop over the fetched messages
-        for (int i = 0; i < messages.length && i < offset; i++) {
-            org.apache.hupa.shared.domain.Message msg = new org.apache.hupa.shared.data.MessageImpl();
-            Message message = messages[i];
-
-            String from = null;
-            if (message.getFrom() != null && message.getFrom().length > 0) {
-                from = MessageUtils.decodeText(message.getFrom()[0].toString());
-            }
-            msg.setFrom(from);
-
-            String replyto = null;
-            if (message.getReplyTo() != null && message.getReplyTo().length > 0) {
-                replyto = MessageUtils.decodeText(message.getReplyTo()[0].toString());
-            }
-            msg.setReplyto(replyto);
-
-            ArrayList<String> to = new ArrayList<String>();
-            // Add to addresses
-            Address[] toArray = message.getRecipients(RecipientType.TO);
-            if (toArray != null) {
-                for (Address addr : toArray) {
-                    String mailTo = MessageUtils.decodeText(addr.toString());
-                    to.add(mailTo);
-                }
-            }
-            msg.setTo(to);
-
-            // Check if a subject exist and if so decode it
-            String subject = message.getSubject();
-            if (subject != null) {
-                subject = MessageUtils.decodeText(subject);
-            }
-            msg.setSubject(subject);
-
-            // Add cc addresses
-            Address[] ccArray = message.getRecipients(RecipientType.CC);
-            ArrayList<String> cc = new ArrayList<String>();
-            if (ccArray != null) {
-                for (Address addr : ccArray) {
-                    String mailCc = MessageUtils.decodeText(addr.toString());
-                    cc.add(mailCc);
-                }
-            }
-            msg.setCc(cc);
-
-            userPreferences.addContact(from);
-            userPreferences.addContact(to);
-            userPreferences.addContact(replyto);
-            userPreferences.addContact(cc);
-
-            // Using sentDate since received date is not useful in the view when
-            // using fetchmail
-            msg.setReceivedDate(message.getSentDate());
-
-            // Add flags
-            ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(message.getFlags());
-
-            ArrayList<Tag> tags = new ArrayList<Tag>();
-            for (String flag : message.getFlags().getUserFlags()) {
-                if (flag.startsWith(TagImpl.PREFIX)) {
-                    tags.add(new TagImpl(flag.substring(TagImpl.PREFIX.length())));
-                }
-            }
-
-            msg.setUid(folder.getUID(message));
-            msg.setFlags(iFlags);
-            msg.setTags(tags);
-            try {
-                msg.setHasAttachments(hasAttachment(message));
-            } catch (MessagingException e) {
-                logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
-                        + msg.getSubject() + " cause:" + e.getMessage());
-                logger.info("");
-            }
-            mList.add(0, msg);
-
-        }
-        return mList;
-    }
-
-    protected FetchProfile getFetchProfile() {
-        FetchProfile fp = new FetchProfile();
-        fp.add(FetchProfile.Item.ENVELOPE);
-        fp.add(FetchProfile.Item.FLAGS);
-        fp.add(FetchProfile.Item.CONTENT_INFO);
-        fp.add(UIDFolder.FetchProfileItem.UID);
-        return fp;
-    }
-
-    private boolean hasAttachment(Message message) throws MessagingException {
-        if (message.getContentType().startsWith("multipart/")) {
-            try {
-                Object content;
-
-                content = message.getContent();
-
-                if (content instanceof Multipart) {
-                    Multipart mp = (Multipart) content;
-                    if (mp.getCount() > 1) {
-                        for (int i = 0; i < mp.getCount(); i++) {
-                            String disp = mp.getBodyPart(i).getDisposition();
-                            if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
-                                return true;
-                            }
-                        }
-                    }
-
-                }
-            } catch (IOException e) {
-                logger.error("Error while get content of message " + message.getMessageNumber());
-            }
-
-        }
-        return false;
-    }
-
-    protected final class MessageConvertArray {
-        private Message[] messages;
-        private int realCount;
-
-        public MessageConvertArray(int realCount, Message[] messages) {
-            this.messages = messages;
-            this.realCount = realCount;
-        }
-
-        public int getRealCount() {
-            return realCount;
-        }
-
-        public Message[] getMesssages() {
-            return messages;
-        }
-    }
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.mail.Address;
+import javax.mail.FetchProfile;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.Part;
+import javax.mail.UIDFolder;
+import javax.mail.internet.MimeMessage.RecipientType;
+import javax.mail.search.BodyTerm;
+import javax.mail.search.FromStringTerm;
+import javax.mail.search.OrTerm;
+import javax.mail.search.SearchTerm;
+import javax.mail.search.SubjectTerm;
+
+import org.apache.hupa.server.handler.JavamailUtil;
+import org.apache.hupa.server.preferences.UserPreferencesStorage;
+import org.apache.hupa.server.utils.MessageUtils;
+import org.apache.hupa.shared.data.FetchMessagesResultImpl;
+import org.apache.hupa.shared.data.MessageImpl.IMAPFlag;
+import org.apache.hupa.shared.data.TagImpl;
+import org.apache.hupa.shared.domain.FetchMessagesAction;
+import org.apache.hupa.shared.domain.FetchMessagesResult;
+import org.apache.hupa.shared.domain.Tag;
+import org.apache.hupa.shared.domain.User;
+import org.apache.hupa.shared.exception.HupaException;
+
+import com.google.inject.Inject;
+import com.sun.mail.imap.IMAPFolder;
+import com.sun.mail.imap.IMAPStore;
+
+public class FetchMessagesServiceImpl extends AbstractService implements FetchMessagesService {
+
+    @Inject protected UserPreferencesStorage userPreferences;
+
+    public FetchMessagesResult fetch(FetchMessagesAction action) throws HupaException {
+        User user = getUser();
+        // ImapFolder folder = action.getFolder();
+        if (action.getFolder() == null || action.getFolder().getFullName() == null) {
+            // folder = new
+            // ImapFolderImpl(user.getSettings().getInboxFolderName());
+            throw new IllegalArgumentException("why you want to ask us for messages in a null folder");
+        }
+        com.sun.mail.imap.IMAPFolder f = null;
+        int start = action.getStart();
+        int offset = action.getOffset();
+        try {
+            IMAPStore store = cache.get(user);
+
+            f = (com.sun.mail.imap.IMAPFolder) store.getFolder(action.getFolder().getFullName());
+
+            // check if the folder is open, if not open it read only
+            if (f.isOpen() == false) {
+                f.open(com.sun.mail.imap.IMAPFolder.READ_ONLY);
+            }
+
+            // if the folder is empty we have no need to process
+            int exists = f.getMessageCount();
+            if (exists == 0) {
+                return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start,
+                        offset, 0, 0);
+            }
+
+            MessageConvertArray convArray = getMessagesToConvert(f, action);
+            return new FetchMessagesResultImpl(convert(offset, f, convArray.getMesssages()), start, offset,
+                    convArray.getRealCount(), f.getUnreadMessageCount());
+        } catch (MessagingException e) {
+            logger.info("Error fetching messages in folder: " + action.getFolder().getFullName() + " " + e.getMessage());
+            // Folder can not contain messages
+            return new FetchMessagesResultImpl(new ArrayList<org.apache.hupa.shared.domain.Message>(), start, offset,
+                    0, 0);
+        } finally {
+            if (f != null && f.isOpen()) {
+                try {
+                    f.close(false);
+                } catch (MessagingException e) {
+                    // we don't care to much about an exception on close here...
+                }
+            }
+        }
+    }
+
+    protected MessageConvertArray getMessagesToConvert(IMAPFolder f, FetchMessagesAction action)
+            throws MessagingException, HupaException {
+
+        String searchString = action.getSearchString();
+        int start = action.getStart();
+        int offset = action.getOffset();
+        int end = start + offset;
+        Message[] messages;
+        int exists;
+        // check if a searchString was given, and if so use it
+        if (searchString == null) {
+            exists = f.getMessageCount();
+
+            if (end > exists) {
+                end = exists;
+            }
+
+            int firstIndex = exists - end + 1;
+            if (firstIndex < 1) {
+                firstIndex = 1;
+            }
+            int lastIndex = exists - start;
+
+            messages = f.getMessages(firstIndex, lastIndex);
+        } else {
+            SearchTerm subjectTerm = new SubjectTerm(searchString);
+            SearchTerm fromTerm = new FromStringTerm(searchString);
+            SearchTerm bodyTerm = new BodyTerm(searchString);
+            SearchTerm orTerm = new OrTerm(new SearchTerm[] { subjectTerm, fromTerm, bodyTerm });
+            Message[] tmpMessages = f.search(orTerm);
+            if (end > tmpMessages.length) {
+                end = tmpMessages.length;
+            }
+            exists = tmpMessages.length;
+
+            int firstIndex = exists - end;
+
+            if (tmpMessages.length > firstIndex) {
+                List<Message> mList = new ArrayList<Message>();
+                for (int i = firstIndex; i < tmpMessages.length; i++) {
+                    if (i == end)
+                        break;
+                    mList.add(tmpMessages[i]);
+                }
+                messages = mList.toArray(new Message[mList.size()]);
+            } else {
+                messages = new Message[0];
+            }
+
+        }
+        logger.debug("Fetching messages for user: " + getUser() + " returns: " + messages.length + " messages in "
+                + f.getFullName());
+
+        return new MessageConvertArray(exists, messages);
+    }
+
+
+    public List<org.apache.hupa.shared.domain.Message> convert(int offset, com.sun.mail.imap.IMAPFolder folder,
+            Message[] messages) throws MessagingException {
+        List<org.apache.hupa.shared.domain.Message> mList = new ArrayList<org.apache.hupa.shared.domain.Message>();
+
+        // Setup fetchprofile to limit the stuff which is fetched
+        FetchProfile fp = getFetchProfile();
+        folder.fetch(messages, fp);
+
+        // loop over the fetched messages
+        for (int i = 0; i < messages.length && i < offset; i++) {
+            org.apache.hupa.shared.domain.Message msg = new org.apache.hupa.shared.data.MessageImpl();
+            Message message = messages[i];
+
+            String from = null;
+            if (message.getFrom() != null && message.getFrom().length > 0) {
+                from = MessageUtils.decodeText(message.getFrom()[0].toString());
+            }
+            msg.setFrom(from);
+
+            String replyto = null;
+            if (message.getReplyTo() != null && message.getReplyTo().length > 0) {
+                replyto = MessageUtils.decodeText(message.getReplyTo()[0].toString());
+            }
+            msg.setReplyto(replyto);
+
+            ArrayList<String> to = new ArrayList<String>();
+            // Add to addresses
+            Address[] toArray = message.getRecipients(RecipientType.TO);
+            if (toArray != null) {
+                for (Address addr : toArray) {
+                    String mailTo = MessageUtils.decodeText(addr.toString());
+                    to.add(mailTo);
+                }
+            }
+            msg.setTo(to);
+
+            // Check if a subject exist and if so decode it
+            String subject = message.getSubject();
+            if (subject != null) {
+                subject = MessageUtils.decodeText(subject);
+            }
+            msg.setSubject(subject);
+
+            // Add cc addresses
+            Address[] ccArray = message.getRecipients(RecipientType.CC);
+            ArrayList<String> cc = new ArrayList<String>();
+            if (ccArray != null) {
+                for (Address addr : ccArray) {
+                    String mailCc = MessageUtils.decodeText(addr.toString());
+                    cc.add(mailCc);
+                }
+            }
+            msg.setCc(cc);
+
+            userPreferences.addContact(from);
+            userPreferences.addContact(to);
+            userPreferences.addContact(replyto);
+            userPreferences.addContact(cc);
+
+            // Using sentDate since received date is not useful in the view when
+            // using fetchmail
+            msg.setReceivedDate(message.getSentDate());
+
+            // Add flags
+            ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(message.getFlags());
+
+            ArrayList<Tag> tags = new ArrayList<Tag>();
+            for (String flag : message.getFlags().getUserFlags()) {
+                if (flag.startsWith(TagImpl.PREFIX)) {
+                    tags.add(new TagImpl(flag.substring(TagImpl.PREFIX.length())));
+                }
+            }
+
+            msg.setUid(folder.getUID(message));
+            msg.setFlags(iFlags);
+            msg.setTags(tags);
+            try {
+                msg.setHasAttachments(hasAttachment(message));
+            } catch (MessagingException e) {
+                logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
+                        + msg.getSubject() + " cause:" + e.getMessage());
+                logger.info("");
+            }
+            mList.add(0, msg);
+
+        }
+        return mList;
+    }
+
+    protected FetchProfile getFetchProfile() {
+        FetchProfile fp = new FetchProfile();
+        fp.add(FetchProfile.Item.ENVELOPE);
+        fp.add(FetchProfile.Item.FLAGS);
+        fp.add(FetchProfile.Item.CONTENT_INFO);
+        fp.add(UIDFolder.FetchProfileItem.UID);
+        return fp;
+    }
+
+    private boolean hasAttachment(Message message) throws MessagingException {
+        if (message.getContentType().startsWith("multipart/")) {
+            try {
+                Object content;
+
+                content = message.getContent();
+
+                if (content instanceof Multipart) {
+                    Multipart mp = (Multipart) content;
+                    if (mp.getCount() > 1) {
+                        for (int i = 0; i < mp.getCount(); i++) {
+                            String disp = mp.getBodyPart(i).getDisposition();
+                            if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
+                                return true;
+                            }
+                        }
+                    }
+
+                }
+            } catch (IOException e) {
+                logger.error("Error while get content of message " + message.getMessageNumber());
+            }
+
+        }
+        return false;
+    }
+
+    protected final class MessageConvertArray {
+        private Message[] messages;
+        private int realCount;
+
+        public MessageConvertArray(int realCount, Message[] messages) {
+            this.messages = messages;
+            this.realCount = realCount;
+        }
+
+        public int getRealCount() {
+            return realCount;
+        }
+
+        public Message[] getMesssages() {
+            return messages;
+        }
+    }
+}

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsService.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsService.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsService.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsService.java Thu Mar 20 08:16:02 2014
@@ -1,27 +1,27 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import org.apache.hupa.shared.domain.GetMessageDetailsAction;
-import org.apache.hupa.shared.domain.GetMessageDetailsResult;
-
-public interface GetMessageDetailsService {
-    GetMessageDetailsResult get(GetMessageDetailsAction action) throws Exception;
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import org.apache.hupa.shared.domain.GetMessageDetailsAction;
+import org.apache.hupa.shared.domain.GetMessageDetailsResult;
+
+public interface GetMessageDetailsService {
+    GetMessageDetailsResult get(GetMessageDetailsAction action) throws Exception;
+}

Modified: james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsServiceImpl.java
URL: http://svn.apache.org/viewvc/james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsServiceImpl.java?rev=1579559&r1=1579558&r2=1579559&view=diff
==============================================================================
--- james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsServiceImpl.java (original)
+++ james/hupa/trunk/server/src/main/java/org/apache/hupa/server/service/GetMessageDetailsServiceImpl.java Thu Mar 20 08:16:02 2014
@@ -1,204 +1,204 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.hupa.server.service;
-
-import static org.apache.hupa.server.utils.RegexPatterns.regex_badAttrs;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_badTags;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_email;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_existingEmailLinks;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_existingHttpLinks;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_gt;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_htmllink;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_inlineImg;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_lt;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_nl;
-import static org.apache.hupa.server.utils.RegexPatterns.regex_unneededTags;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_badAttrs;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_badTags;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_email;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_existingHttpLinks;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_existngEmailLinks;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_gt;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_htmllink;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_inlineImg;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_lt;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_nl;
-import static org.apache.hupa.server.utils.RegexPatterns.repl_unneededTags;
-import static org.apache.hupa.server.utils.RegexPatterns.replaceAll;
-import static org.apache.hupa.server.utils.RegexPatterns.replaceAllRecursive;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-import javax.mail.Flags;
-import javax.mail.Flags.Flag;
-import javax.mail.Header;
-import javax.mail.Message;
-import javax.mail.MessagingException;
-import javax.mail.internet.MimeMessage;
-
-import org.apache.hupa.server.utils.MessageUtils;
-import org.apache.hupa.shared.data.GetMessageDetailsResultImpl;
-import org.apache.hupa.shared.data.MailHeaderImpl;
-import javax.mail.Multipart;
-import javax.mail.Part;
-import javax.mail.internet.MimeMessage;
-
-import org.apache.hupa.server.utils.MessageUtils;
-import org.apache.hupa.shared.data.GetMessageDetailsResultImpl;
-import org.apache.hupa.shared.data.MailHeaderImpl;
-import org.apache.hupa.shared.data.MessageDetailsImpl;
-import org.apache.hupa.shared.domain.GetMessageDetailsAction;
-import org.apache.hupa.shared.domain.GetMessageDetailsResult;
-import org.apache.hupa.shared.domain.ImapFolder;
-import org.apache.hupa.shared.domain.MessageAttachment;
-import org.apache.hupa.shared.domain.MessageDetails;
-import org.apache.hupa.shared.domain.User;
-
-import com.sun.mail.imap.IMAPStore;
-
-public class GetMessageDetailsServiceImpl extends AbstractService implements GetMessageDetailsService {
-
-    public GetMessageDetailsResult get(GetMessageDetailsAction action) throws Exception {
-        return new GetMessageDetailsResultImpl(exposeMessage(getUser(), action.getFolder(), action.getUid()));
-    }
-
-    protected MessageDetails exposeMessage(User user, ImapFolder folder, long uid) throws Exception {
-        IMAPStore store = null;
-        com.sun.mail.imap.IMAPFolder f = null;
-        try {
-            store = cache.get(user);
-
-            f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName());
-
-            if (f.isOpen() == false) {
-                f.open(com.sun.mail.imap.IMAPFolder.READ_WRITE);
-            }
-
-            MimeMessage message = (MimeMessage) f.getMessageByUID(uid);
-
-            MessageDetails mDetails = mimeToDetails(message, f.getFullName(), uid, user);
-
-            mDetails.setUid(uid);
-
-            f.setFlags(new Message[] { message }, new Flags(Flag.SEEN), true);
-
-            return mDetails;
-        } catch (Exception e) {
-            logger.error("Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid, e);
-            throw new Exception("Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid);
-
-        } finally {
-            if (f != null && f.isOpen()) {
-                try {
-                    f.close(false);
-                } catch (MessagingException e) {
-                    // ignore on close
-                }
-            }
-        }
-    }
-
-    protected MessageDetails mimeToDetails(MimeMessage message, String folderName, long uid, User user) throws IOException,
-            MessagingException, UnsupportedEncodingException {
-        MessageDetails mDetails = new MessageDetailsImpl();
-
-        Object content = message.getContent();
-
-        StringBuffer sbPlain = new StringBuffer();
-        ArrayList<MessageAttachment> attachmentList = new ArrayList<MessageAttachment>();
-
-        boolean isHTML = MessageUtils.handleParts(message, content, sbPlain, attachmentList);
-
-        if (isHTML) {
-            mDetails.setText(filterHtmlDocument(sbPlain.toString(), folderName, uid));
-        } else {
-            mDetails.setText(txtDocumentToHtml(sbPlain.toString(), folderName, uid));
-        }
-
-        mDetails.setMessageAttachments(attachmentList);
-
-        for (@SuppressWarnings("unchecked") Enumeration<Header> en = message.getAllHeaders(); en.hasMoreElements();) {
-            Header header = en.nextElement();
-            if (header.getName().toLowerCase().matches("^(x-.*|date|from|to|subject)$")) {
-                mDetails.getMailHeaders().add(new MailHeaderImpl(header.getName(), header.getValue()));
-            }
-        }
-
-        return mDetails;
-    }
-
-    protected String txtDocumentToHtml(String txt, String folderName, long uuid) {
-
-        if (txt == null || txt.length() == 0)
-            return txt;
-
-        // escape html tags symbols
-        txt = replaceAll(txt, regex_lt, repl_lt);
-        txt = replaceAll(txt, regex_gt, repl_gt);
-
-        // enclose between <a> http links and emails
-        txt = replaceAll(txt, regex_htmllink, repl_htmllink);
-        txt = replaceAll(txt, regex_email, repl_email);
-
-        // put break lines
-        txt = replaceAll(txt, regex_nl, repl_nl);
-
-        txt = filterHtmlDocument(txt, folderName, uuid);
-
-        return txt;
-    }
-
-    protected String filterHtmlDocument(String html, String folderName, long uuid) {
-
-        if (html == null || html.length() == 0)
-            return html;
-
-        // Replace in-line images links to use Hupa's download servlet
-        html = replaceAll(html, regex_inlineImg, repl_inlineImg).replaceAll("%%FOLDER%%", folderName).replaceAll(
-                "%%UID%%", String.valueOf(uuid));
-        // Remove head, script and style tags to avoid interferences with Hupa
-        html = replaceAll(html, regex_badTags, repl_badTags);
-        // Remove body and html tags
-        html = replaceAll(html, regex_unneededTags, repl_unneededTags);
-        // Remove all onClick attributes
-        html = replaceAllRecursive(html, regex_badAttrs, repl_badAttrs);
-        html = replaceAll(html, regex_existingHttpLinks, repl_existingHttpLinks);
-
-        // FIXME: These have serious performance problems (see
-        // testMessageDetails_Base64Image_Performance)
-        // Add <a> tags to links which are not already into <a>
-        // html = replaceAll(html, regex_orphandHttpLinks,
-        // repl_orphandHttpLinks);
-        // Add javascript method to <a> in order to open links in a different
-        // window
-        // Add <a> tags to emails which are not already into <a>
-        // html = replaceAll(html, regex_orphandEmailLinks,
-        // repl_orphandEmailLinks);
-        // Add a js method to mailto links in order to compose new mails inside
-        // hupa
-        html = replaceAll(html, regex_existingEmailLinks, repl_existngEmailLinks);
-
-        return html;
-    }
-
-}
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+
+package org.apache.hupa.server.service;
+
+import static org.apache.hupa.server.utils.RegexPatterns.regex_badAttrs;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_badTags;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_email;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_existingEmailLinks;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_existingHttpLinks;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_gt;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_htmllink;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_inlineImg;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_lt;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_nl;
+import static org.apache.hupa.server.utils.RegexPatterns.regex_unneededTags;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_badAttrs;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_badTags;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_email;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_existingHttpLinks;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_existngEmailLinks;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_gt;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_htmllink;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_inlineImg;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_lt;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_nl;
+import static org.apache.hupa.server.utils.RegexPatterns.repl_unneededTags;
+import static org.apache.hupa.server.utils.RegexPatterns.replaceAll;
+import static org.apache.hupa.server.utils.RegexPatterns.replaceAllRecursive;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import javax.mail.Flags;
+import javax.mail.Flags.Flag;
+import javax.mail.Header;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.hupa.server.utils.MessageUtils;
+import org.apache.hupa.shared.data.GetMessageDetailsResultImpl;
+import org.apache.hupa.shared.data.MailHeaderImpl;
+import javax.mail.Multipart;
+import javax.mail.Part;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.hupa.server.utils.MessageUtils;
+import org.apache.hupa.shared.data.GetMessageDetailsResultImpl;
+import org.apache.hupa.shared.data.MailHeaderImpl;
+import org.apache.hupa.shared.data.MessageDetailsImpl;
+import org.apache.hupa.shared.domain.GetMessageDetailsAction;
+import org.apache.hupa.shared.domain.GetMessageDetailsResult;
+import org.apache.hupa.shared.domain.ImapFolder;
+import org.apache.hupa.shared.domain.MessageAttachment;
+import org.apache.hupa.shared.domain.MessageDetails;
+import org.apache.hupa.shared.domain.User;
+
+import com.sun.mail.imap.IMAPStore;
+
+public class GetMessageDetailsServiceImpl extends AbstractService implements GetMessageDetailsService {
+
+    public GetMessageDetailsResult get(GetMessageDetailsAction action) throws Exception {
+        return new GetMessageDetailsResultImpl(exposeMessage(getUser(), action.getFolder(), action.getUid()));
+    }
+
+    protected MessageDetails exposeMessage(User user, ImapFolder folder, long uid) throws Exception {
+        IMAPStore store = null;
+        com.sun.mail.imap.IMAPFolder f = null;
+        try {
+            store = cache.get(user);
+
+            f = (com.sun.mail.imap.IMAPFolder) store.getFolder(folder.getFullName());
+
+            if (f.isOpen() == false) {
+                f.open(com.sun.mail.imap.IMAPFolder.READ_WRITE);
+            }
+
+            MimeMessage message = (MimeMessage) f.getMessageByUID(uid);
+
+            MessageDetails mDetails = mimeToDetails(message, f.getFullName(), uid, user);
+
+            mDetails.setUid(uid);
+
+            f.setFlags(new Message[] { message }, new Flags(Flag.SEEN), true);
+
+            return mDetails;
+        } catch (Exception e) {
+            logger.error("Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid, e);
+            throw new Exception("Unable to expose msg for user " + user + " in folder " + folder + " with uid " + uid);
+
+        } finally {
+            if (f != null && f.isOpen()) {
+                try {
+                    f.close(false);
+                } catch (MessagingException e) {
+                    // ignore on close
+                }
+            }
+        }
+    }
+
+    protected MessageDetails mimeToDetails(MimeMessage message, String folderName, long uid, User user) throws IOException,
+            MessagingException, UnsupportedEncodingException {
+        MessageDetails mDetails = new MessageDetailsImpl();
+
+        Object content = message.getContent();
+
+        StringBuffer sbPlain = new StringBuffer();
+        ArrayList<MessageAttachment> attachmentList = new ArrayList<MessageAttachment>();
+
+        boolean isHTML = MessageUtils.handleParts(message, content, sbPlain, attachmentList);
+
+        if (isHTML) {
+            mDetails.setText(filterHtmlDocument(sbPlain.toString(), folderName, uid));
+        } else {
+            mDetails.setText(txtDocumentToHtml(sbPlain.toString(), folderName, uid));
+        }
+
+        mDetails.setMessageAttachments(attachmentList);
+
+        for (@SuppressWarnings("unchecked") Enumeration<Header> en = message.getAllHeaders(); en.hasMoreElements();) {
+            Header header = en.nextElement();
+            if (header.getName().toLowerCase().matches("^(x-.*|date|from|to|subject)$")) {
+                mDetails.getMailHeaders().add(new MailHeaderImpl(header.getName(), header.getValue()));
+            }
+        }
+
+        return mDetails;
+    }
+
+    protected String txtDocumentToHtml(String txt, String folderName, long uuid) {
+
+        if (txt == null || txt.length() == 0)
+            return txt;
+
+        // escape html tags symbols
+        txt = replaceAll(txt, regex_lt, repl_lt);
+        txt = replaceAll(txt, regex_gt, repl_gt);
+
+        // enclose between <a> http links and emails
+        txt = replaceAll(txt, regex_htmllink, repl_htmllink);
+        txt = replaceAll(txt, regex_email, repl_email);
+
+        // put break lines
+        txt = replaceAll(txt, regex_nl, repl_nl);
+
+        txt = filterHtmlDocument(txt, folderName, uuid);
+
+        return txt;
+    }
+
+    protected String filterHtmlDocument(String html, String folderName, long uuid) {
+
+        if (html == null || html.length() == 0)
+            return html;
+
+        // Replace in-line images links to use Hupa's download servlet
+        html = replaceAll(html, regex_inlineImg, repl_inlineImg).replaceAll("%%FOLDER%%", folderName).replaceAll(
+                "%%UID%%", String.valueOf(uuid));
+        // Remove head, script and style tags to avoid interferences with Hupa
+        html = replaceAll(html, regex_badTags, repl_badTags);
+        // Remove body and html tags
+        html = replaceAll(html, regex_unneededTags, repl_unneededTags);
+        // Remove all onClick attributes
+        html = replaceAllRecursive(html, regex_badAttrs, repl_badAttrs);
+        html = replaceAll(html, regex_existingHttpLinks, repl_existingHttpLinks);
+
+        // FIXME: These have serious performance problems (see
+        // testMessageDetails_Base64Image_Performance)
+        // Add <a> tags to links which are not already into <a>
+        // html = replaceAll(html, regex_orphandHttpLinks,
+        // repl_orphandHttpLinks);
+        // Add javascript method to <a> in order to open links in a different
+        // window
+        // Add <a> tags to emails which are not already into <a>
+        // html = replaceAll(html, regex_orphandEmailLinks,
+        // repl_orphandEmailLinks);
+        // Add a js method to mailto links in order to compose new mails inside
+        // hupa
+        html = replaceAll(html, regex_existingEmailLinks, repl_existngEmailLinks);
+
+        return html;
+    }
+
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org