Source Code Cross Referenced for PrivateMessageManagerImpl.java in  » ERP-CRM-Financial » sakai » org » sakaiproject » component » app » messageforums » ui » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » sakai » org.sakaiproject.component.app.messageforums.ui 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /**********************************************************************************
0002:         * $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java $
0003:         * $Id: PrivateMessageManagerImpl.java 9227 2006-05-15 15:02:42Z cwen@iupui.edu $
0004:         ***********************************************************************************
0005:         *
0006:         * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
0007:         * 
0008:         * Licensed under the Educational Community License, Version 1.0 (the "License"); 
0009:         * you may not use this file except in compliance with the License. 
0010:         * You may obtain a copy of the License at
0011:         * 
0012:         *      http://www.opensource.org/licenses/ecl1.php
0013:         * 
0014:         * Unless required by applicable law or agreed to in writing, software 
0015:         * distributed under the License is distributed on an "AS IS" BASIS, 
0016:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
0017:         * See the License for the specific language governing permissions and 
0018:         * limitations under the License.
0019:         *
0020:         **********************************************************************************/package org.sakaiproject.component.app.messageforums.ui;
0021:
0022:        import java.sql.SQLException;
0023:        import java.util.ArrayList;
0024:        import java.util.Date;
0025:        import java.util.Iterator;
0026:        import java.util.List;
0027:        import java.util.ResourceBundle;
0028:        import java.util.Set;
0029:
0030:        import org.hibernate.Hibernate;
0031:        import org.hibernate.HibernateException;
0032:        import org.hibernate.LockMode;
0033:        import org.hibernate.Query;
0034:        import org.hibernate.Session;
0035:
0036:        import org.apache.commons.logging.Log;
0037:        import org.apache.commons.logging.LogFactory;
0038:        import org.sakaiproject.api.app.messageforums.Area;
0039:        import org.sakaiproject.api.app.messageforums.AreaManager;
0040:        import org.sakaiproject.api.app.messageforums.Attachment;
0041:        import org.sakaiproject.api.app.messageforums.Message;
0042:        import org.sakaiproject.api.app.messageforums.MessageForumsForumManager;
0043:        import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager;
0044:        import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager;
0045:        import org.sakaiproject.api.app.messageforums.PrivateForum;
0046:        import org.sakaiproject.api.app.messageforums.PrivateMessage;
0047:        import org.sakaiproject.api.app.messageforums.PrivateMessageRecipient;
0048:        import org.sakaiproject.api.app.messageforums.PrivateTopic;
0049:        import org.sakaiproject.api.app.messageforums.Topic;
0050:        import org.sakaiproject.api.app.messageforums.UniqueArrayList;
0051:        import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager;
0052:        import org.sakaiproject.id.api.IdManager;
0053:        import org.sakaiproject.tool.api.ToolSession;
0054:        import org.sakaiproject.site.api.ToolConfiguration;
0055:        import org.sakaiproject.tool.api.SessionManager;
0056:        import org.sakaiproject.tool.cover.ToolManager;
0057:        import org.sakaiproject.component.app.messageforums.TestUtil;
0058:        import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageImpl;
0059:        import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageRecipientImpl;
0060:        import org.sakaiproject.exception.IdUnusedException;
0061:        import org.sakaiproject.component.cover.ServerConfigurationService;
0062:        import org.sakaiproject.email.api.EmailService;
0063:        import org.sakaiproject.content.api.ContentResource;
0064:        import org.sakaiproject.content.cover.ContentHostingService;
0065:        import org.sakaiproject.authz.cover.SecurityService;
0066:        import org.sakaiproject.site.cover.SiteService;
0067:        import org.sakaiproject.user.api.User;
0068:        import org.sakaiproject.user.cover.UserDirectoryService;
0069:        import org.sakaiproject.util.ResourceLoader;
0070:        import org.springframework.orm.hibernate3.HibernateCallback;
0071:        import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
0072:
0073:        public class PrivateMessageManagerImpl extends HibernateDaoSupport
0074:                implements  PrivateMessageManager {
0075:
0076:            private static final Log LOG = LogFactory
0077:                    .getLog(PrivateMessageManagerImpl.class);
0078:
0079:            private static final String QUERY_AGGREGATE_COUNT = "findAggregatePvtMsgCntForUserInContext";
0080:            private static final String QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT = "findPrvtMsgsByUserTypeContext";
0081:            private static final String QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS = "findPrivateMessageByIdWithRecipients";
0082:
0083:            private static List aggregateList;
0084:
0085:            private AreaManager areaManager;
0086:            private MessageForumsMessageManager messageManager;
0087:            private MessageForumsForumManager forumManager;
0088:            private MessageForumsTypeManager typeManager;
0089:            private IdManager idManager;
0090:            private SessionManager sessionManager;
0091:            private EmailService emailService;
0092:
0093:            private static final String MESSAGES_TITLE = "pvt_message_nav";
0094:            private static final String PVT_RECEIVED = "pvt_received";
0095:            private static final String PVT_SENT = "pvt_sent";
0096:            private static final String PVT_DELETED = "pvt_deleted";
0097:
0098:            /** String ids for email footer messsage */
0099:            private static final String EMAIL_FOOTER1 = "pvt_email_footer1";
0100:            private static final String EMAIL_FOOTER2 = "pvt_email_footer2";
0101:            private static final String EMAIL_FOOTER3 = "pvt_email_footer3";
0102:            private static final String EMAIL_FOOTER4 = "pvt_email_footer4";
0103:
0104:            public void init() {
0105:                LOG.info("init()");
0106:                ;
0107:            }
0108:
0109:            public boolean getPrivateAreaEnabled() {
0110:
0111:                if (LOG.isDebugEnabled()) {
0112:                    LOG.debug("getPrivateAreaEnabled()");
0113:                }
0114:
0115:                return areaManager.isPrivateAreaEnabled();
0116:
0117:            }
0118:
0119:            public void setPrivateAreaEnabled(boolean value) {
0120:
0121:                if (LOG.isDebugEnabled()) {
0122:                    LOG.debug("setPrivateAreaEnabled(value: " + value + ")");
0123:                }
0124:
0125:            }
0126:
0127:            /**
0128:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#isPrivateAreaEnabled()
0129:             */
0130:            public boolean isPrivateAreaEnabled() {
0131:                return areaManager.isPrivateAreaEnabled();
0132:            }
0133:
0134:            /**
0135:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#getPrivateMessageArea()
0136:             */
0137:            public Area getPrivateMessageArea() {
0138:                return areaManager.getPrivateArea();
0139:            }
0140:
0141:            public void savePrivateMessageArea(Area area) {
0142:                areaManager.saveArea(area);
0143:            }
0144:
0145:            /**
0146:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#initializePrivateMessageArea(org.sakaiproject.api.app.messageforums.Area)
0147:             */
0148:            public PrivateForum initializePrivateMessageArea(Area area) {
0149:                String userId = getCurrentUser();
0150:
0151:                initializeMessageCounts();
0152:
0153:                getHibernateTemplate().lock(area, LockMode.NONE);
0154:
0155:                PrivateForum pf;
0156:
0157:                /** create default user forum/topics if none exist */
0158:                if ((pf = forumManager.getPrivateForumByOwnerArea(
0159:                        getCurrentUser(), area)) == null) {
0160:                    /** initialize collections */
0161:                    //getHibernateTemplate().initialize(area.getPrivateForumsSet());
0162:                    pf = forumManager
0163:                            .createPrivateForum(getResourceBundleString(MESSAGES_TITLE));
0164:
0165:                    //area.addPrivateForum(pf);
0166:                    //pf.setArea(area);
0167:                    //areaManager.saveArea(area);
0168:
0169:                    PrivateTopic receivedTopic = forumManager
0170:                            .createPrivateForumTopic(
0171:                                    getResourceBundleString(PVT_RECEIVED),
0172:                                    true, false, userId, pf.getId());
0173:
0174:                    PrivateTopic sentTopic = forumManager
0175:                            .createPrivateForumTopic(
0176:                                    getResourceBundleString(PVT_SENT), true,
0177:                                    false, userId, pf.getId());
0178:
0179:                    PrivateTopic deletedTopic = forumManager
0180:                            .createPrivateForumTopic(
0181:                                    getResourceBundleString(PVT_DELETED), true,
0182:                                    false, userId, pf.getId());
0183:
0184:                    //PrivateTopic draftTopic = forumManager.createPrivateForumTopic("Drafts", true,false,
0185:                    //    userId, pf.getId());
0186:
0187:                    /** save individual topics - required to add to forum's topic set */
0188:                    forumManager.savePrivateForumTopic(receivedTopic);
0189:                    forumManager.savePrivateForumTopic(sentTopic);
0190:                    forumManager.savePrivateForumTopic(deletedTopic);
0191:                    //forumManager.savePrivateForumTopic(draftTopic);
0192:
0193:                    pf.addTopic(receivedTopic);
0194:                    pf.addTopic(sentTopic);
0195:                    pf.addTopic(deletedTopic);
0196:                    //pf.addTopic(draftTopic);
0197:                    pf.setArea(area);
0198:
0199:                    PrivateForum oldForum;
0200:                    if ((oldForum = forumManager
0201:                            .getPrivateForumByOwnerAreaNull(getCurrentUser())) != null) {
0202:                        oldForum = initializationHelper(oldForum);
0203:                        //    		getHibernateTemplate().initialize(oldForum.getTopicsSet());
0204:                        List pvtTopics = oldForum.getTopics();
0205:
0206:                        for (int i = 0; i < pvtTopics.size(); i++) {
0207:                            PrivateTopic currentTopic = (PrivateTopic) pvtTopics
0208:                                    .get(i);
0209:                            if (currentTopic != null) {
0210:                                if (!currentTopic.getTitle().equals("Received")
0211:                                        && !currentTopic.getTitle().equals(
0212:                                                "Sent")
0213:                                        && !currentTopic.getTitle().equals(
0214:                                                "Deleted")
0215:                                        && !currentTopic.getTitle().equals(
0216:                                                "Drafts")
0217:                                        && area.getContextId().equals(
0218:                                                currentTopic.getContextId())) {
0219:                                    currentTopic.setPrivateForum(pf);
0220:                                    forumManager
0221:                                            .savePrivateForumTopic(currentTopic);
0222:                                    pf.addTopic(currentTopic);
0223:                                }
0224:                            }
0225:                        }
0226:                        if (oldForum.getAutoForward() != null) {
0227:                            pf.setAutoForward(oldForum.getAutoForward());
0228:                        }
0229:                        if (oldForum.getAutoForwardEmail() != null) {
0230:                            pf.setAutoForwardEmail(oldForum
0231:                                    .getAutoForwardEmail());
0232:                        }
0233:                    }
0234:
0235:                    forumManager.savePrivateForum(pf);
0236:
0237:                } else {
0238:                    //getHibernateTemplate().initialize(pf.getTopicsSet());   
0239:                    pf = forumManager.getPrivateForumByOwnerAreaWithAllTopics(
0240:                            getCurrentUser(), area);
0241:                }
0242:
0243:                return pf;
0244:            }
0245:
0246:            public PrivateForum initializationHelper(PrivateForum forum) {
0247:
0248:                /** reget to load topic foreign keys */
0249:                //PrivateForum pf = forumManager.getPrivateForumByOwnerAreaNull(getCurrentUser());
0250:                //getHibernateTemplate().initialize(pf.getTopicsSet());    
0251:                PrivateForum pf = forumManager
0252:                        .getPrivateForumByOwnerAreaNullWithAllTopics(getCurrentUser());
0253:                return pf;
0254:            }
0255:
0256:            public PrivateForum initializationHelper(PrivateForum forum,
0257:                    Area area) {
0258:
0259:                /** reget to load topic foreign keys */
0260:                //PrivateForum pf = forumManager.getPrivateForumByOwnerArea(getCurrentUser(), area);
0261:                //getHibernateTemplate().initialize(pf.getTopicsSet());    
0262:                PrivateForum pf = forumManager
0263:                        .getPrivateForumByOwnerAreaWithAllTopics(
0264:                                getCurrentUser(), area);
0265:                return pf;
0266:            }
0267:
0268:            /**
0269:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#savePrivateMessage(org.sakaiproject.api.app.messageforums.Message)
0270:             */
0271:            public void savePrivateMessage(Message message) {
0272:                messageManager.saveMessage(message);
0273:            }
0274:
0275:            public Message getMessageById(Long id) {
0276:                return messageManager.getMessageById(id);
0277:            }
0278:
0279:            //Attachment
0280:            public Attachment createPvtMsgAttachment(String attachId,
0281:                    String name) {
0282:                try {
0283:                    Attachment attach = messageManager.createAttachment();
0284:
0285:                    attach.setAttachmentId(attachId);
0286:
0287:                    attach.setAttachmentName(name);
0288:
0289:                    ContentResource cr = ContentHostingService
0290:                            .getResource(attachId);
0291:                    attach
0292:                            .setAttachmentSize((new Integer(cr
0293:                                    .getContentLength())).toString());
0294:                    attach.setCreatedBy(cr.getProperties().getProperty(
0295:                            cr.getProperties().getNamePropCreator()));
0296:                    attach.setModifiedBy(cr.getProperties().getProperty(
0297:                            cr.getProperties().getNamePropModifiedBy()));
0298:                    attach.setAttachmentType(cr.getContentType());
0299:                    String tempString = cr.getUrl();
0300:                    String newString = new String();
0301:                    char[] oneChar = new char[1];
0302:                    for (int i = 0; i < tempString.length(); i++) {
0303:                        if (tempString.charAt(i) != ' ') {
0304:                            oneChar[0] = tempString.charAt(i);
0305:                            String concatString = new String(oneChar);
0306:                            newString = newString.concat(concatString);
0307:                        } else {
0308:                            newString = newString.concat("%20");
0309:                        }
0310:                    }
0311:                    //tempString.replaceAll(" ", "%20");
0312:                    //attach.setAttachmentUrl(newString);
0313:                    attach.setAttachmentUrl("/url");
0314:
0315:                    return attach;
0316:                } catch (Exception e) {
0317:                    e.printStackTrace();
0318:                    return null;
0319:                }
0320:            }
0321:
0322:            // Himansu: I am not quite sure this is what you want... let me know.
0323:            // Before saving a message, we need to add all the attachmnets to a perticular message
0324:            public void addAttachToPvtMsg(PrivateMessage pvtMsgData,
0325:                    Attachment pvtMsgAttach) {
0326:                pvtMsgData.addAttachment(pvtMsgAttach);
0327:            }
0328:
0329:            // Required for editing multiple attachments to a message. 
0330:            // When you reply to a message, you do have option to edit attachments to a message
0331:            public void removePvtMsgAttachment(Attachment o) {
0332:                o.getMessage().removeAttachment(o);
0333:            }
0334:
0335:            public Attachment getPvtMsgAttachment(Long pvtMsgAttachId) {
0336:                return messageManager.getAttachmentById(pvtMsgAttachId);
0337:            }
0338:
0339:            public int getTotalNoMessages(Topic topic) {
0340:                return messageManager.findMessageCountByTopicId(topic.getId());
0341:            }
0342:
0343:            public int getUnreadNoMessages(Topic topic) {
0344:                return messageManager.findUnreadMessageCountByTopicId(topic
0345:                        .getId());
0346:            }
0347:
0348:            /**
0349:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#saveAreaAndForumSettings(org.sakaiproject.api.app.messageforums.Area, org.sakaiproject.api.app.messageforums.PrivateForum)
0350:             */
0351:            public void saveAreaAndForumSettings(Area area, PrivateForum forum) {
0352:
0353:                /** method calls placed in this function to participate in same transaction */
0354:
0355:                saveForumSettings(forum);
0356:
0357:                /** need to evict forum b/c area saves fk on forum (which places two objects w/same id in session */
0358:                //getHibernateTemplate().evict(forum);
0359:                if (isInstructor()) {
0360:                    savePrivateMessageArea(area);
0361:                }
0362:            }
0363:
0364:            public void saveForumSettings(PrivateForum forum) {
0365:                if (LOG.isDebugEnabled()) {
0366:                    LOG.debug("saveForumSettings(forum: " + forum + ")");
0367:                }
0368:
0369:                if (forum == null) {
0370:                    throw new IllegalArgumentException("Null Argument");
0371:                }
0372:
0373:                forumManager.savePrivateForum(forum);
0374:            }
0375:
0376:            /**
0377:             * Topic Folder Setting
0378:             */
0379:            public boolean isMutableTopicFolder(String parentTopicId) {
0380:                return false;
0381:            }
0382:
0383:            public void createTopicFolderInForum(PrivateForum pf,
0384:                    String folderName) {
0385:                String userId = getCurrentUser();
0386:                PrivateTopic createdTopic = forumManager
0387:                        .createPrivateForumTopic(folderName, true, true,
0388:                                userId, pf.getId());
0389:
0390:                /** set context and type to differentiate user topics within sites */
0391:                createdTopic.setContextId(getContextId());
0392:                createdTopic.setTypeUuid(typeManager
0393:                        .getUserDefinedPrivateTopicType());
0394:
0395:                forumManager.savePrivateForumTopic(createdTopic);
0396:                pf.addTopic(createdTopic);
0397:                forumManager.savePrivateForum(pf);
0398:            }
0399:
0400:            public void createTopicFolderInTopic(PrivateForum pf,
0401:                    PrivateTopic parentTopic, String folderName) {
0402:                String userId = getCurrentUser();
0403:                PrivateTopic createdTopic = forumManager
0404:                        .createPrivateForumTopic(folderName, true, true,
0405:                                userId, pf.getId());
0406:                createdTopic.setParentTopic(parentTopic);
0407:                forumManager.savePrivateForumTopic(createdTopic);
0408:                pf.addTopic(createdTopic);
0409:                forumManager.savePrivateForum(pf);
0410:            }
0411:
0412:            public void renameTopicFolder(PrivateForum pf, String topicUuid,
0413:                    String newName) {
0414:                String userId = getCurrentUser();
0415:                List pvtTopics = pf.getTopics();
0416:                for (Iterator iter = pvtTopics.iterator(); iter.hasNext();) {
0417:                    PrivateTopic element = (PrivateTopic) iter.next();
0418:                    if (element.getUuid().equals(topicUuid)) {
0419:                        element.setTitle(newName);
0420:                        element.setModifiedBy(userId);
0421:                        element.setModified(new Date());
0422:                    }
0423:                }
0424:                forumManager.savePrivateForum(pf);
0425:            }
0426:
0427:            public void deleteTopicFolder(PrivateForum pf, String topicUuid) {
0428:                List pvtTopics = pf.getTopics();
0429:                for (Iterator iter = pvtTopics.iterator(); iter.hasNext();) {
0430:                    PrivateTopic element = (PrivateTopic) iter.next();
0431:                    if (element.getUuid().equals(topicUuid)) {
0432:                        pf.removeTopic(element);
0433:                        break;
0434:                    }
0435:                }
0436:                forumManager.savePrivateForum(pf);
0437:            }
0438:
0439:            /**
0440:             * Return Topic based on uuid 
0441:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#getTopicByIdWithMessages(java.lang.Long)
0442:             */
0443:            public Topic getTopicByUuid(final String topicUuid) {
0444:                if (LOG.isDebugEnabled()) {
0445:                    LOG.debug("getTopicByIdWithMessages(final Long" + topicUuid
0446:                            + ")");
0447:                }
0448:                return forumManager.getTopicByUuid(topicUuid);
0449:            }
0450:
0451:            public static final String PVTMSG_MODE_RECEIVED = "pvt_received";
0452:            public static final String PVTMSG_MODE_SENT = "pvt_sent";
0453:            public static final String PVTMSG_MODE_DELETE = "pvt_deleted";
0454:            public static final String PVTMSG_MODE_DRAFT = "pvt_drafts";
0455:
0456:            /*  public static final String PVTMSG_MODE_RECEIVED = "Received";
0457:             public static final String PVTMSG_MODE_SENT = "Sent";
0458:             public static final String PVTMSG_MODE_DELETE = "Deleted";
0459:             public static final String PVTMSG_MODE_DRAFT = "Drafts"; */
0460:
0461:            public void movePvtMsgTopic(PrivateMessage message, Topic oldTopic,
0462:                    Topic newTopic) {
0463:                List recipients = message.getRecipients();
0464:                //get new topic type uuid
0465:                String newTopicTypeUuid = getTopicTypeUuid(newTopic.getTitle());
0466:                //get pld topic type uuid
0467:                String oldTopicTypeUuid = getTopicTypeUuid(oldTopic.getTitle());
0468:
0469:                //now set the recipiant with new topic type uuid
0470:                for (Iterator iter = recipients.iterator(); iter.hasNext();) {
0471:                    PrivateMessageRecipient element = (PrivateMessageRecipient) iter
0472:                            .next();
0473:                    if (element.getTypeUuid().equals(oldTopicTypeUuid)
0474:                            && (element.getUserId().equals(getCurrentUser()))) {
0475:                        element.setTypeUuid(newTopicTypeUuid);
0476:                    }
0477:                }
0478:                savePrivateMessage(message);
0479:
0480:            }
0481:
0482:            /**
0483:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#createPrivateMessage(java.lang.String)
0484:             */
0485:            public PrivateMessage createPrivateMessage(String typeUuid) {
0486:                PrivateMessage message = new PrivateMessageImpl();
0487:                message.setUuid(idManager.createUuid());
0488:                message.setTypeUuid(typeUuid);
0489:                message.setCreated(new Date());
0490:                message.setCreatedBy(getCurrentUser());
0491:
0492:                LOG.info("message " + message.getUuid()
0493:                        + " created successfully");
0494:                return message;
0495:            }
0496:
0497:            public boolean hasNextMessage(PrivateMessage message) {
0498:                // TODO: Needs optimized
0499:                boolean next = false;
0500:                if (message != null && message.getTopic() != null
0501:                        && message.getTopic().getMessages() != null) {
0502:                    for (Iterator iter = message.getTopic().getMessages()
0503:                            .iterator(); iter.hasNext();) {
0504:                        Message m = (Message) iter.next();
0505:                        if (next) {
0506:                            return true;
0507:                        }
0508:                        if (m.getId().equals(message.getId())) {
0509:                            next = true;
0510:                        }
0511:                    }
0512:                }
0513:
0514:                // if we get here, there is no next message
0515:                return false;
0516:            }
0517:
0518:            public boolean hasPreviousMessage(PrivateMessage message) {
0519:                // TODO: Needs optimized
0520:                PrivateMessage prev = null;
0521:                if (message != null && message.getTopic() != null
0522:                        && message.getTopic().getMessages() != null) {
0523:                    for (Iterator iter = message.getTopic().getMessages()
0524:                            .iterator(); iter.hasNext();) {
0525:                        Message m = (Message) iter.next();
0526:                        if (m.getId().equals(message.getId())) {
0527:                            // need to check null because we might be on the first message
0528:                            // which means there is no previous one
0529:                            return prev != null;
0530:                        }
0531:                        prev = (PrivateMessage) m;
0532:                    }
0533:                }
0534:
0535:                // if we get here, there is no previous message
0536:                return false;
0537:            }
0538:
0539:            public PrivateMessage getNextMessage(PrivateMessage message) {
0540:                // TODO: Needs optimized
0541:                boolean next = false;
0542:                if (message != null && message.getTopic() != null
0543:                        && message.getTopic().getMessages() != null) {
0544:                    for (Iterator iter = message.getTopic().getMessages()
0545:                            .iterator(); iter.hasNext();) {
0546:                        Message m = (Message) iter.next();
0547:                        if (next) {
0548:                            return (PrivateMessage) m;
0549:                        }
0550:                        if (m.getId().equals(message.getId())) {
0551:                            next = true;
0552:                        }
0553:                    }
0554:                }
0555:
0556:                // if we get here, there is no next message
0557:                return null;
0558:            }
0559:
0560:            public PrivateMessage getPreviousMessage(PrivateMessage message) {
0561:                // TODO: Needs optimized
0562:                PrivateMessage prev = null;
0563:                if (message != null && message.getTopic() != null
0564:                        && message.getTopic().getMessages() != null) {
0565:                    for (Iterator iter = message.getTopic().getMessages()
0566:                            .iterator(); iter.hasNext();) {
0567:                        Message m = (Message) iter.next();
0568:                        if (m.getId().equals(message.getId())) {
0569:                            return prev;
0570:                        }
0571:                        prev = (PrivateMessage) m;
0572:                    }
0573:                }
0574:
0575:                // if we get here, there is no previous message
0576:                return null;
0577:            }
0578:
0579:            public List getMessagesByTopic(String userId, Long topicId) {
0580:                // TODO Auto-generated method stub
0581:                return null;
0582:            }
0583:
0584:            public List getReceivedMessages(String orderField, String order) {
0585:                return getMessagesByType(typeManager
0586:                        .getReceivedPrivateMessageType(), orderField, order);
0587:            }
0588:
0589:            public List getSentMessages(String orderField, String order) {
0590:                return getMessagesByType(typeManager
0591:                        .getSentPrivateMessageType(), orderField, order);
0592:            }
0593:
0594:            public List getDeletedMessages(String orderField, String order) {
0595:                return getMessagesByType(typeManager
0596:                        .getDeletedPrivateMessageType(), orderField, order);
0597:            }
0598:
0599:            public List getDraftedMessages(String orderField, String order) {
0600:                return getMessagesByType(typeManager
0601:                        .getDraftPrivateMessageType(), orderField, order);
0602:            }
0603:
0604:            public PrivateMessage initMessageWithAttachmentsAndRecipients(
0605:                    PrivateMessage msg) {
0606:
0607:                PrivateMessage pmReturn = (PrivateMessage) messageManager
0608:                        .getMessageByIdWithAttachments(msg.getId());
0609:                getHibernateTemplate().initialize(pmReturn.getRecipients());
0610:                return pmReturn;
0611:            }
0612:
0613:            /**
0614:             * helper method to get messages by type
0615:             * @param typeUuid
0616:             * @return message list
0617:             */
0618:            public List getMessagesByType(final String typeUuid,
0619:                    final String orderField, final String order) {
0620:
0621:                if (LOG.isDebugEnabled()) {
0622:                    LOG.debug("getMessagesByType(typeUuid:" + typeUuid
0623:                            + ", orderField: " + orderField + ", order:"
0624:                            + order + ")");
0625:                }
0626:
0627:                //    HibernateCallback hcb = new HibernateCallback() {
0628:                //      public Object doInHibernate(Session session) throws HibernateException, SQLException {
0629:                //        Criteria messageCriteria = session.createCriteria(PrivateMessageImpl.class);
0630:                //        Criteria recipientCriteria = messageCriteria.createCriteria("recipients");
0631:                //        
0632:                //        Conjunction conjunction = Expression.conjunction();
0633:                //        conjunction.add(Expression.eq("userId", getCurrentUser()));
0634:                //        conjunction.add(Expression.eq("typeUuid", typeUuid));        
0635:                //        
0636:                //        recipientCriteria.add(conjunction);
0637:                //        
0638:                //        if ("asc".equalsIgnoreCase(order)){
0639:                //          messageCriteria.addOrder(Order.asc(orderField));
0640:                //        }
0641:                //        else if ("desc".equalsIgnoreCase(order)){
0642:                //          messageCriteria.addOrder(Order.desc(orderField));
0643:                //        }
0644:                //        else{
0645:                //          LOG.debug("getMessagesByType failed with (typeUuid:" + typeUuid + ", orderField: " + orderField +
0646:                //              ", order:" + order + ")");
0647:                //          throw new IllegalArgumentException("order must have value asc or desc");          
0648:                //        }
0649:                //        
0650:                //        //todo: parameterize fetch mode
0651:                //        messageCriteria.setFetchMode("recipients", FetchMode.EAGER);
0652:                //        messageCriteria.setFetchMode("attachments", FetchMode.EAGER);
0653:                //        
0654:                //        return messageCriteria.list();        
0655:                //      }
0656:                //    };
0657:
0658:                HibernateCallback hcb = new HibernateCallback() {
0659:                    public Object doInHibernate(Session session)
0660:                            throws HibernateException, SQLException {
0661:                        Query q = session
0662:                                .getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
0663:                        Query qOrdered = session.createQuery(q.getQueryString()
0664:                                + " order by " + orderField + " " + order);
0665:
0666:                        qOrdered.setParameter("userId", getCurrentUser(),
0667:                                Hibernate.STRING);
0668:                        qOrdered.setParameter("typeUuid", typeUuid,
0669:                                Hibernate.STRING);
0670:                        qOrdered.setParameter("contextId", getContextId(),
0671:                                Hibernate.STRING);
0672:                        return qOrdered.list();
0673:                    }
0674:                };
0675:
0676:                return (List) getHibernateTemplate().execute(hcb);
0677:            }
0678:
0679:            /**
0680:             * FOR SYNOPTIC TOOL:
0681:             * 	helper method to get messages by type
0682:             * 	needed to pass contextId since could be in MyWorkspace
0683:             * 
0684:             * @param typeUuid
0685:             * 			The type of forum it is (Private or Topic)
0686:             * @param contextId
0687:             * 			The site id whose messages are needed
0688:             * 
0689:             * @return message list
0690:             */
0691:            public List getMessagesByTypeByContext(final String typeUuid,
0692:                    final String contextId) {
0693:
0694:                if (LOG.isDebugEnabled()) {
0695:                    LOG.debug("getMessagesByTypeForASite(typeUuid:" + typeUuid
0696:                            + ")");
0697:                }
0698:
0699:                HibernateCallback hcb = new HibernateCallback() {
0700:                    public Object doInHibernate(Session session)
0701:                            throws HibernateException, SQLException {
0702:                        Query q = session
0703:                                .getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
0704:
0705:                        q.setParameter("userId", getCurrentUser(),
0706:                                Hibernate.STRING);
0707:                        q.setParameter("typeUuid", typeUuid, Hibernate.STRING);
0708:                        q
0709:                                .setParameter("contextId", contextId,
0710:                                        Hibernate.STRING);
0711:                        return q.list();
0712:                    }
0713:                };
0714:
0715:                return (List) getHibernateTemplate().execute(hcb);
0716:            }
0717:
0718:            /**
0719:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findMessageCount(java.lang.String)
0720:             */
0721:            public int findMessageCount(String typeUuid) {
0722:                if (LOG.isDebugEnabled()) {
0723:                    LOG.debug("findMessageCount executing with typeUuid: "
0724:                            + typeUuid);
0725:                }
0726:
0727:                if (typeUuid == null) {
0728:                    LOG.error("findMessageCount failed with typeUuid: "
0729:                            + typeUuid);
0730:                    throw new IllegalArgumentException("Null Argument");
0731:                }
0732:
0733:                if (aggregateList == null) {
0734:                    LOG.error("findMessageCount failed with aggregateList: "
0735:                            + aggregateList);
0736:                    throw new IllegalStateException("aggregateList is null");
0737:                }
0738:
0739:                int totalCount = 0;
0740:                for (Iterator i = aggregateList.iterator(); i.hasNext();) {
0741:                    Object[] element = (Object[]) i.next();
0742:                    /** filter on type */
0743:                    if (typeUuid.equals(element[1])) {
0744:                        /** add read/unread message types */
0745:                        totalCount += ((Integer) element[2]).intValue();
0746:                    }
0747:                }
0748:
0749:                return totalCount;
0750:            }
0751:
0752:            /**
0753:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findUnreadMessageCount(java.lang.String)
0754:             */
0755:            public int findUnreadMessageCount(String typeUuid) {
0756:                if (LOG.isDebugEnabled()) {
0757:                    LOG
0758:                            .debug("findUnreadMessageCount executing with typeUuid: "
0759:                                    + typeUuid);
0760:                }
0761:
0762:                if (typeUuid == null) {
0763:                    LOG.error("findUnreadMessageCount failed with typeUuid: "
0764:                            + typeUuid);
0765:                    throw new IllegalArgumentException("Null Argument");
0766:                }
0767:
0768:                if (aggregateList == null) {
0769:                    LOG.error("findMessageCount failed with aggregateList: "
0770:                            + aggregateList);
0771:                    throw new IllegalStateException("aggregateList is null");
0772:                }
0773:
0774:                int unreadCount = 0;
0775:                for (Iterator i = aggregateList.iterator(); i.hasNext();) {
0776:                    Object[] element = (Object[]) i.next();
0777:                    /** filter on type and read status*/
0778:                    if (!typeUuid.equals(element[1])
0779:                            || Boolean.TRUE.equals(element[0])) {
0780:                        continue;
0781:                    } else {
0782:                        unreadCount = ((Integer) element[2]).intValue();
0783:                        break;
0784:                    }
0785:                }
0786:
0787:                return unreadCount;
0788:            }
0789:
0790:            /**
0791:             * initialize message counts
0792:             * @param typeUuid
0793:             */
0794:            private void initializeMessageCounts() {
0795:                if (LOG.isDebugEnabled()) {
0796:                    LOG.debug("initializeMessageCounts executing");
0797:                }
0798:
0799:                HibernateCallback hcb = new HibernateCallback() {
0800:                    public Object doInHibernate(Session session)
0801:                            throws HibernateException, SQLException {
0802:                        Query q = session.getNamedQuery(QUERY_AGGREGATE_COUNT);
0803:                        q.setParameter("contextId", getContextId(),
0804:                                Hibernate.STRING);
0805:                        q.setParameter("userId", getCurrentUser(),
0806:                                Hibernate.STRING);
0807:                        return q.list();
0808:                    }
0809:                };
0810:
0811:                aggregateList = (List) getHibernateTemplate().execute(hcb);
0812:            }
0813:
0814:            /**
0815:             * FOR SYNOPTIC TOOL:
0816:             * 	Returns a list of all sites this user is in along with a count of his/her
0817:             * 	unread messages
0818:             * 
0819:             * @return
0820:             * 	List of site id, count of unread message pairs
0821:             */
0822:            public List getPrivateMessageCountsForAllSites() {
0823:                HibernateCallback hcb = new HibernateCallback() {
0824:                    public Object doInHibernate(Session session)
0825:                            throws HibernateException, SQLException {
0826:                        Query q = session
0827:                                .getNamedQuery("findUnreadPvtMsgCntByUserForAllSites");
0828:                        q.setParameter("userId", getCurrentUser(),
0829:                                Hibernate.STRING);
0830:                        return q.list();
0831:                    }
0832:                };
0833:
0834:                return (List) getHibernateTemplate().execute(hcb);
0835:
0836:            }
0837:
0838:            /**
0839:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#deletePrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.lang.String)
0840:             */
0841:            public void deletePrivateMessage(PrivateMessage message,
0842:                    String typeUuid) {
0843:
0844:                String userId = getCurrentUser();
0845:
0846:                if (LOG.isDebugEnabled()) {
0847:                    LOG.debug("deletePrivateMessage(message:" + message
0848:                            + ", typeUuid:" + typeUuid + ")");
0849:                }
0850:
0851:                /** fetch recipients for message */
0852:                PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
0853:
0854:                /**
0855:                 *  create PrivateMessageRecipient to search
0856:                 */
0857:                PrivateMessageRecipient pmrReadSearch = new PrivateMessageRecipientImpl(
0858:                        userId, typeUuid, getContextId(), Boolean.TRUE);
0859:
0860:                PrivateMessageRecipient pmrNonReadSearch = new PrivateMessageRecipientImpl(
0861:                        userId, typeUuid, getContextId(), Boolean.FALSE);
0862:
0863:                int indexDelete = -1;
0864:                int indexRead = pvtMessage.getRecipients().indexOf(
0865:                        pmrReadSearch);
0866:                if (indexRead != -1) {
0867:                    indexDelete = indexRead;
0868:                } else {
0869:                    int indexNonRead = pvtMessage.getRecipients().indexOf(
0870:                            pmrNonReadSearch);
0871:                    if (indexNonRead != -1) {
0872:                        indexDelete = indexNonRead;
0873:                    } else {
0874:                        LOG
0875:                                .error("deletePrivateMessage -- cannot find private message for user: "
0876:                                        + userId + ", typeUuid: " + typeUuid);
0877:                    }
0878:                }
0879:
0880:                if (indexDelete != -1) {
0881:                    PrivateMessageRecipient pmrReturned = (PrivateMessageRecipient) pvtMessage
0882:                            .getRecipients().get(indexDelete);
0883:
0884:                    if (pmrReturned != null) {
0885:
0886:                        /** check for existing deleted message from user */
0887:                        PrivateMessageRecipient pmrDeletedSearch = new PrivateMessageRecipientImpl(
0888:                                userId, typeManager
0889:                                        .getDeletedPrivateMessageType(),
0890:                                getContextId(), Boolean.TRUE);
0891:
0892:                        int indexDeleted = pvtMessage.getRecipients().indexOf(
0893:                                pmrDeletedSearch);
0894:
0895:                        if (indexDeleted == -1) {
0896:                            pmrReturned.setRead(Boolean.TRUE);
0897:                            pmrReturned.setTypeUuid(typeManager
0898:                                    .getDeletedPrivateMessageType());
0899:                        } else {
0900:                            pvtMessage.getRecipients().remove(indexDelete);
0901:                        }
0902:                    }
0903:                }
0904:            }
0905:
0906:            /**
0907:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#sendPrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.util.Set, boolean)
0908:             */
0909:            public void sendPrivateMessage(PrivateMessage message,
0910:                    Set recipients, boolean asEmail) {
0911:
0912:                if (LOG.isDebugEnabled()) {
0913:                    LOG.debug("sendPrivateMessage(message: " + message
0914:                            + ", recipients: " + recipients + ")");
0915:                }
0916:
0917:                if (message == null || recipients == null) {
0918:                    throw new IllegalArgumentException("Null Argument");
0919:                }
0920:
0921:                if (recipients.size() == 0) {
0922:                    /** for no just return out
0923:                      throw new IllegalArgumentException("Empty recipient list");
0924:                     **/
0925:                    return;
0926:                }
0927:
0928:                String currentUserAsString = getCurrentUser();
0929:                List recipientList = new UniqueArrayList();
0930:
0931:                /** test for draft message */
0932:                if (message.getDraft().booleanValue()) {
0933:                    PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
0934:                            currentUserAsString, typeManager
0935:                                    .getDraftPrivateMessageType(),
0936:                            getContextId(), Boolean.TRUE);
0937:
0938:                    recipientList.add(receiver);
0939:                    message.setRecipients(recipientList);
0940:                    savePrivateMessage(message);
0941:                    return;
0942:                }
0943:
0944:                for (Iterator i = recipients.iterator(); i.hasNext();) {
0945:                    User u = (User) i.next();
0946:                    String userId = u.getId();
0947:
0948:                    /** determine if recipient has forwarding enabled */
0949:                    Area currentArea = getAreaByContextIdAndTypeId(typeManager
0950:                            .getPrivateMessageAreaType());
0951:                    PrivateForum pf = forumManager.getPrivateForumByOwnerArea(
0952:                            userId, currentArea);
0953:                    PrivateForum oldPf = forumManager
0954:                            .getPrivateForumByOwnerAreaNull(userId);
0955:
0956:                    boolean forwardingEnabled = false;
0957:
0958:                    if (pf != null && pf.getAutoForward().booleanValue()) {
0959:                        forwardingEnabled = true;
0960:                    }
0961:                    if (pf == null && oldPf != null
0962:                            && oldPf.getAutoForward().booleanValue()) {
0963:                        forwardingEnabled = true;
0964:                    }
0965:
0966:                    List additionalHeaders = new ArrayList(1);
0967:                    additionalHeaders.add("Content-Type: text/html");
0968:
0969:                    User currentUser = UserDirectoryService.getCurrentUser();
0970:                    StringBuffer body = new StringBuffer(message.getBody());
0971:
0972:                    body.insert(0, "From: " + currentUser.getDisplayName()
0973:                            + "<p/>");
0974:
0975:                    // need to filter out hidden users if there are any and:
0976:                    //   a non-instructor (! site.upd)
0977:                    //   instructor but not the author
0978:                    String sendToString = message.getRecipientsAsText();
0979:                    if (sendToString.indexOf("(") > 0
0980:                            && (!isInstructor() || (message.getAuthor() != getAuthorString()))) {
0981:                        sendToString = sendToString.substring(0, sendToString
0982:                                .indexOf("("));
0983:                    }
0984:
0985:                    body.insert(0, "To: " + sendToString + "<p/>");
0986:
0987:                    if (message.getAttachments() != null
0988:                            && message.getAttachments().size() > 0) {
0989:
0990:                        body.append("<br/><br/>");
0991:                        for (Iterator iter = message.getAttachments()
0992:                                .iterator(); iter.hasNext();) {
0993:                            Attachment attachment = (Attachment) iter.next();
0994:                            //body.append("<a href=\"" + attachment.getAttachmentUrl() +
0995:                            //"\">" + attachment.getAttachmentName() + "</a><br/>");            
0996:                            body.append("<a href=\""
0997:                                    + messageManager
0998:                                            .getAttachmentUrl(attachment
0999:                                                    .getAttachmentId()) + "\">"
1000:                                    + attachment.getAttachmentName()
1001:                                    + "</a><br/>");
1002:                        }
1003:                    }
1004:
1005:                    String siteTitle = null;
1006:                    try {
1007:                        siteTitle = SiteService.getSite(getContextId())
1008:                                .getTitle();
1009:                    } catch (IdUnusedException e) {
1010:                        LOG.error(e.getMessage(), e);
1011:                    }
1012:
1013:                    String this PageId = "";
1014:                    ToolSession ts = sessionManager.getCurrentToolSession();
1015:                    if (ts != null) {
1016:                        ToolConfiguration tool = SiteService.findTool(ts
1017:                                .getPlacementId());
1018:                        if (tool != null) {
1019:                            this PageId = tool.getPageId();
1020:                        }
1021:                    }
1022:
1023:                    String footer = "<p>----------------------<br>"
1024:                            + getResourceBundleString(EMAIL_FOOTER1)
1025:                            + " "
1026:                            + ServerConfigurationService
1027:                                    .getString("ui.service") + " "
1028:                            + getResourceBundleString(EMAIL_FOOTER2) + " \""
1029:                            + siteTitle + "\" "
1030:                            + getResourceBundleString(EMAIL_FOOTER3) + "\n"
1031:                            + getResourceBundleString(EMAIL_FOOTER4)
1032:                            + " <a href=\""
1033:                            + ServerConfigurationService.getPortalUrl()
1034:                            + "/site/"
1035:                            + ToolManager.getCurrentPlacement().getContext()
1036:                            + "/page/" + this PageId + "\">";
1037:
1038:                    footer += siteTitle + "</a>.</p>";
1039:                    body.append(footer);
1040:
1041:                    String bodyString = body.toString();
1042:
1043:                    /** determines if default in sakai.properties is set, if not will make a reasonable default */
1044:                    String defaultEmail = "notifications@"
1045:                            + ServerConfigurationService.getServerName();
1046:                    String systemEmail = ServerConfigurationService.getString(
1047:                            "msgcntr.notification.from.address", defaultEmail);
1048:
1049:                    /** determine if current user is equal to recipient */
1050:                    Boolean isRecipientCurrentUser = (currentUserAsString
1051:                            .equals(userId) ? Boolean.TRUE : Boolean.FALSE);
1052:
1053:                    if (!asEmail && forwardingEnabled) {
1054:                        if (pf != null) {
1055:                            emailService.send(systemEmail, pf
1056:                                    .getAutoForwardEmail(), message.getTitle(),
1057:                                    bodyString, u.getEmail(), null,
1058:                                    additionalHeaders);
1059:                        } else if (oldPf != null) {
1060:                            emailService.send(systemEmail, oldPf
1061:                                    .getAutoForwardEmail(), message.getTitle(),
1062:                                    bodyString, u.getEmail(), null,
1063:                                    additionalHeaders);
1064:                        }
1065:
1066:                        // use forwarded address if set
1067:
1068:                        PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
1069:                                userId, typeManager
1070:                                        .getReceivedPrivateMessageType(),
1071:                                getContextId(), isRecipientCurrentUser);
1072:                        recipientList.add(receiver);
1073:                    } else if (asEmail) {
1074:                        emailService.send(systemEmail, u.getEmail(), message
1075:                                .getTitle(), bodyString, u.getEmail(), null,
1076:                                additionalHeaders);
1077:                    } else {
1078:                        PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
1079:                                userId, typeManager
1080:                                        .getReceivedPrivateMessageType(),
1081:                                getContextId(), isRecipientCurrentUser);
1082:                        recipientList.add(receiver);
1083:                    }
1084:                }
1085:
1086:                /** add sender as a saved recipient */
1087:                PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(
1088:                        currentUserAsString, typeManager
1089:                                .getSentPrivateMessageType(), getContextId(),
1090:                        Boolean.TRUE);
1091:
1092:                recipientList.add(sender);
1093:
1094:                message.setRecipients(recipientList);
1095:
1096:                savePrivateMessage(message);
1097:
1098:                /** enable if users are stored in message forums user table
1099:                 Iterator i = recipients.iterator();
1100:                 while (i.hasNext()){
1101:                 String userId = (String) i.next();
1102:                 
1103:                 //getForumUser will create user if forums user does not exist
1104:                 message.addRecipient(userManager.getForumUser(userId.trim()));
1105:                 }
1106:                 **/
1107:
1108:            }
1109:
1110:            /**
1111:             * @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#markMessageAsReadForUser(org.sakaiproject.api.app.messageforums.PrivateMessage)
1112:             */
1113:            public void markMessageAsReadForUser(final PrivateMessage message) {
1114:
1115:                if (LOG.isDebugEnabled()) {
1116:                    LOG.debug("markMessageAsReadForUser(message: " + message
1117:                            + ")");
1118:                }
1119:
1120:                if (message == null) {
1121:                    throw new IllegalArgumentException("Null Argument");
1122:                }
1123:
1124:                final String userId = getCurrentUser();
1125:
1126:                /** fetch recipients for message */
1127:                PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
1128:
1129:                /** create PrivateMessageRecipientImpl to search for recipient to update */
1130:                PrivateMessageRecipientImpl searchRecipient = new PrivateMessageRecipientImpl(
1131:                        userId, typeManager.getReceivedPrivateMessageType(),
1132:                        getContextId(), Boolean.FALSE);
1133:
1134:                List recipientList = pvtMessage.getRecipients();
1135:
1136:                if (recipientList == null || recipientList.size() == 0) {
1137:                    LOG.error("markMessageAsReadForUser(message: " + message
1138:                            + ") has empty recipient list");
1139:                    throw new Error("markMessageAsReadForUser(message: "
1140:                            + message + ") has empty recipient list");
1141:                }
1142:
1143:                int recordIndex = pvtMessage.getRecipients().indexOf(
1144:                        searchRecipient);
1145:
1146:                if (recordIndex != -1) {
1147:                    ((PrivateMessageRecipientImpl) recipientList
1148:                            .get(recordIndex)).setRead(Boolean.TRUE);
1149:                }
1150:            }
1151:
1152:            /**
1153:             * FOR SYNOPTIC TOOL:
1154:             * 	Need to pass in contextId also
1155:             */
1156:            public void markMessageAsReadForUser(final PrivateMessage message,
1157:                    final String contextId) {
1158:
1159:                if (LOG.isDebugEnabled()) {
1160:                    LOG.debug("markMessageAsReadForUser(message: " + message
1161:                            + ")");
1162:                }
1163:
1164:                if (message == null) {
1165:                    throw new IllegalArgumentException("Null Argument");
1166:                }
1167:
1168:                final String userId = getCurrentUser();
1169:
1170:                /** fetch recipients for message */
1171:                PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
1172:
1173:                /** create PrivateMessageRecipientImpl to search for recipient to update */
1174:                PrivateMessageRecipientImpl searchRecipient = new PrivateMessageRecipientImpl(
1175:                        userId, typeManager.getReceivedPrivateMessageType(),
1176:                        contextId, Boolean.FALSE);
1177:
1178:                List recipientList = pvtMessage.getRecipients();
1179:
1180:                if (recipientList == null || recipientList.size() == 0) {
1181:                    LOG.error("markMessageAsReadForUser(message: " + message
1182:                            + ") has empty recipient list");
1183:                    throw new Error("markMessageAsReadForUser(message: "
1184:                            + message + ") has empty recipient list");
1185:                }
1186:
1187:                int recordIndex = pvtMessage.getRecipients().indexOf(
1188:                        searchRecipient);
1189:
1190:                if (recordIndex != -1) {
1191:                    ((PrivateMessageRecipientImpl) recipientList
1192:                            .get(recordIndex)).setRead(Boolean.TRUE);
1193:                }
1194:            }
1195:
1196:            private PrivateMessage getPrivateMessageWithRecipients(
1197:                    final PrivateMessage message) {
1198:
1199:                if (LOG.isDebugEnabled()) {
1200:                    LOG.debug("getPrivateMessageWithRecipients(message: "
1201:                            + message + ")");
1202:                }
1203:
1204:                if (message == null) {
1205:                    throw new IllegalArgumentException("Null Argument");
1206:                }
1207:
1208:                HibernateCallback hcb = new HibernateCallback() {
1209:                    public Object doInHibernate(Session session)
1210:                            throws HibernateException, SQLException {
1211:                        Query q = session
1212:                                .getNamedQuery(QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS);
1213:                        q.setParameter("id", message.getId(), Hibernate.LONG);
1214:                        return q.uniqueResult();
1215:                    }
1216:                };
1217:
1218:                PrivateMessage pvtMessage = (PrivateMessage) getHibernateTemplate()
1219:                        .execute(hcb);
1220:
1221:                if (pvtMessage == null) {
1222:                    LOG.error("getPrivateMessageWithRecipients(message: "
1223:                            + message + ") could not find message");
1224:                    throw new Error("getPrivateMessageWithRecipients(message: "
1225:                            + message + ") could not find message");
1226:                }
1227:
1228:                return pvtMessage;
1229:            }
1230:
1231:            public List searchPvtMsgs(String typeUuid, String searchText,
1232:                    Date searchFromDate, Date searchToDate,
1233:                    boolean searchByText, boolean searchByAuthor,
1234:                    boolean searchByBody, boolean searchByLabel,
1235:                    boolean searchByDate) {
1236:                return messageManager.findPvtMsgsBySearchText(typeUuid,
1237:                        searchText, searchFromDate, searchToDate, searchByText,
1238:                        searchByAuthor, searchByBody, searchByLabel,
1239:                        searchByDate);
1240:            }
1241:
1242:            public String getAuthorString() {
1243:                String authorString = getCurrentUser();
1244:
1245:                try {
1246:                    authorString = UserDirectoryService.getUser(authorString)
1247:                            .getSortName();
1248:
1249:                } catch (Exception e) {
1250:                    e.printStackTrace();
1251:                }
1252:
1253:                return authorString;
1254:            }
1255:
1256:            private String getCurrentUser() {
1257:                if (TestUtil.isRunningTests()) {
1258:                    return "test-user";
1259:                }
1260:                return sessionManager.getCurrentSessionUserId();
1261:            }
1262:
1263:            public AreaManager getAreaManager() {
1264:                return areaManager;
1265:            }
1266:
1267:            public void setAreaManager(AreaManager areaManager) {
1268:                this .areaManager = areaManager;
1269:            }
1270:
1271:            public MessageForumsMessageManager getMessageManager() {
1272:                return messageManager;
1273:            }
1274:
1275:            public void setMessageManager(
1276:                    MessageForumsMessageManager messageManager) {
1277:                this .messageManager = messageManager;
1278:            }
1279:
1280:            public void setTypeManager(MessageForumsTypeManager typeManager) {
1281:                this .typeManager = typeManager;
1282:            }
1283:
1284:            public void setSessionManager(SessionManager sessionManager) {
1285:                this .sessionManager = sessionManager;
1286:            }
1287:
1288:            public void setIdManager(IdManager idManager) {
1289:                this .idManager = idManager;
1290:            }
1291:
1292:            public void setForumManager(MessageForumsForumManager forumManager) {
1293:                this .forumManager = forumManager;
1294:            }
1295:
1296:            public void setEmailService(EmailService emailService) {
1297:                this .emailService = emailService;
1298:            }
1299:
1300:            public boolean isInstructor() {
1301:                LOG.debug("isInstructor()");
1302:                return isInstructor(UserDirectoryService.getCurrentUser());
1303:            }
1304:
1305:            /**
1306:             * Check if the given user has site.upd access
1307:             * 
1308:             * @param user
1309:             * @return
1310:             */
1311:            private boolean isInstructor(User user) {
1312:                if (LOG.isDebugEnabled()) {
1313:                    LOG.debug("isInstructor(User " + user + ")");
1314:                }
1315:                if (user != null)
1316:                    return SecurityService.unlock(user, "site.upd",
1317:                            getContextSiteId());
1318:                else
1319:                    return false;
1320:            }
1321:
1322:            /**
1323:             * @return siteId
1324:             */
1325:            public String getContextSiteId() {
1326:                LOG.debug("getContextSiteId()");
1327:
1328:                return ("/site/" + ToolManager.getCurrentPlacement()
1329:                        .getContext());
1330:            }
1331:
1332:            public String getContextId() {
1333:
1334:                LOG.debug("getContextId()");
1335:
1336:                if (TestUtil.isRunningTests()) {
1337:                    return "01001010";
1338:                } else {
1339:                    return ToolManager.getCurrentPlacement().getContext();
1340:                }
1341:            }
1342:
1343:            //Helper class
1344:            public String getTopicTypeUuid(String topicTitle) {
1345:                String topicTypeUuid;
1346:
1347:                if (getResourceBundleString(PVTMSG_MODE_RECEIVED).equals(
1348:                        topicTitle)) {
1349:                    topicTypeUuid = typeManager.getReceivedPrivateMessageType();
1350:                } else if (getResourceBundleString(PVTMSG_MODE_SENT).equals(
1351:                        topicTitle)) {
1352:                    topicTypeUuid = typeManager.getSentPrivateMessageType();
1353:                } else if (getResourceBundleString(PVTMSG_MODE_DELETE).equals(
1354:                        topicTitle)) {
1355:                    topicTypeUuid = typeManager.getDeletedPrivateMessageType();
1356:                } else if (getResourceBundleString(PVTMSG_MODE_DRAFT).equals(
1357:                        topicTitle)) {
1358:                    topicTypeUuid = typeManager.getDraftPrivateMessageType();
1359:                } else {
1360:                    topicTypeUuid = typeManager.getCustomTopicType(topicTitle);
1361:                }
1362:                return topicTypeUuid;
1363:            }
1364:
1365:            public Area getAreaByContextIdAndTypeId(final String typeId) {
1366:                LOG
1367:                        .debug("getAreaByContextIdAndTypeId executing for current user: "
1368:                                + getCurrentUser());
1369:                HibernateCallback hcb = new HibernateCallback() {
1370:                    public Object doInHibernate(Session session)
1371:                            throws HibernateException, SQLException {
1372:                        Query q = session
1373:                                .getNamedQuery("findAreaByContextIdAndTypeId");
1374:                        q.setParameter("contextId", getContextId(),
1375:                                Hibernate.STRING);
1376:                        q.setParameter("typeId", typeId, Hibernate.STRING);
1377:                        return q.uniqueResult();
1378:                    }
1379:                };
1380:
1381:                return (Area) getHibernateTemplate().execute(hcb);
1382:            }
1383:
1384:            /**
1385:             * Gets Strings from Message Bundle (specifically for titles)
1386:             * TODO: pull directly from bundle instead of using areaManager
1387:             * 		as an intermediary
1388:             * 
1389:             * @param key
1390:             * 			Message bundle key for String wanted
1391:             * 
1392:             * @return
1393:             * 			String requested or "[missing key: key]" if not found
1394:             */
1395:            public String getResourceBundleString(String key) {
1396:                //	 ResourceBundle rb = ResourceBundle.getBundle(MESSAGECENTER_BUNDLE);
1397:
1398:                return areaManager.getResourceBundleString(key);
1399:            }
1400:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.