KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > za > org > coefficient > modules > mailforum > MailForum


1 /*
2  * Coefficient - facilitates project based collaboration
3  * Copyright (C) 2003, Dylan Etkin, CSIR icomtek
4  * PO Box 395
5  * Pretoria 0001, RSA
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19 package za.org.coefficient.modules.mailforum;
20
21
22
23 import net.sf.hibernate.HibernateException;
24 import net.sf.hibernate.util.HibernateUtil;
25
26 import org.dithaka.messaging.AliasUser;
27 import org.dithaka.messaging.Conversation;
28 import org.dithaka.messaging.Forum;
29 import org.dithaka.messaging.ForumChampion;
30 import org.dithaka.messaging.ForumExpert;
31 import org.dithaka.messaging.MailForumSettings;
32 import org.dithaka.messaging.MailGenerator;
33 import org.dithaka.messaging.Message;
34 import org.dithaka.messaging.UserMailPreferences;
35
36 import org.dithaka.metadata.Resource;
37 import org.dithaka.metadata.ResourceFactory;
38 import org.dithaka.metadata.Statement;
39 import org.dithaka.persistence.PersistenceException;
40 import org.dithaka.persistence.PersistenceService;
41
42 import com.sun.corba.se.internal.core.Constant;
43
44 import za.org.coefficient.authentication.CoefficientUser;
45 import za.org.coefficient.authentication.Role;
46 import za.org.coefficient.core.Constants;
47 import za.org.coefficient.core.Project;
48 import za.org.coefficient.events.CoefficientEvent;
49 import za.org.coefficient.events.CoefficientEventHandler;
50 import za.org.coefficient.events.CoefficientEvents;
51 import za.org.coefficient.events.RoleChangedEvent;
52 import za.org.coefficient.interfaces.CoefficientContext;
53 import za.org.coefficient.interfaces.StatisticsMessageSender;
54 import za.org.coefficient.modules.BaseNavProjectModule;
55 import za.org.coefficient.modules.mailforum.util.DBUpdateUtil;
56 import za.org.coefficient.modules.project.Projects;
57 import za.org.coefficient.util.common.ConfigKeyUtil;
58 import za.org.coefficient.util.common.HibernatePager;
59 import za.org.coefficient.util.ejb.SecurityUtil;
60 import za.org.coefficient.util.ejb.VelocityScreenUtil;
61 import za.org.coefficient.util.stats.common.StatisticsMessageSenderFactory;
62
63 import java.io.Serializable JavaDoc;
64 import java.util.Collection JavaDoc;
65 import java.util.Date JavaDoc;
66 import java.util.HashMap JavaDoc;
67 import java.util.HashSet JavaDoc;
68 import java.util.Iterator JavaDoc;
69 import java.util.List JavaDoc;
70 import java.util.Map JavaDoc;
71 import java.util.Set JavaDoc;
72 import java.util.TreeMap JavaDoc;
73
74
75
76 /**
77  * @pojo2ejb.class name="MailForum"
78  * jndi-prefix="za/org/coefficient/nav-project/"
79  * interface-extends="za.org.coefficient.interfaces.Module"
80  * interface-local-extends="za.org.coefficient.interfaces.ModuleLocal"
81  *
82  * @web.resource-env-ref name="za/org/coefficient/nav-project/MailForum"
83  * type="za.org.coefficient.modules.mailforum.MailForum"
84  * @web.resource-env-ref name="MailForum"
85  * type="za.org.coefficient.modules.mailforum.MailForum"
86  */

87 public class MailForum extends BaseNavProjectModule {
88
89     public static final String JavaDoc PARAM_RESOURCE_URI = "resourceuri";
90
91     public static final String JavaDoc PARAM_RESOURCE_ID = "resourceid";
92
93     public static final String JavaDoc PARAM_FORUM_ID = "forumid";
94
95     public static final String JavaDoc PARAM_CONVERSATION_ID = "conversationid";
96
97     private static final String JavaDoc CONVERSATION_PAGER = "__conversation_pager_";
98
99     private static boolean roleChanged = false;
100
101     /**
102      * @author pieter20 Apr 25, 2005 This class is used to handle the events
103      * that MailForum Module has registerd for. In this class we are
104      * handle project champion (role changes) change events
105      */

106     private static class ProjectMemberRoleChangeEventHandler implements
107             CoefficientEventHandler, Serializable JavaDoc {
108
109         public void handleEvent(CoefficientEvent event) {
110             System.out.println("EVENT :: " + event.getDescription());
111
112             if (event.getDescription() == "ROLE_CHANGED") {
113                 roleChanged = true;
114
115             }
116
117             if (event instanceof RoleChangedEvent) {
118                 RoleChangedEvent roleChangedEvent = (RoleChangedEvent) event;
119                 Project currentProject = roleChangedEvent.getProject();
120
121                 if (currentProject != null) {// project is not null
122
Collection JavaDoc forums = null;
123
124                     System.out
125                             .println("ProjectMemberRoleChangeEventHandler.handleEvent() -> project to update:: "
126                                     + currentProject.getName());
127
128                     try {
129                         forums = getForumList(roleChangedEvent.getProject());// if
130
// this
131
// is a
132
// static
133
// class
134
// this
135
// method
136
// must
137
// be
138
// static
139
} catch (Exception JavaDoc e) {
140                         e.printStackTrace();
141                     }
142
143                     Iterator JavaDoc forumsIterator = forums.iterator();
144                     while (forumsIterator.hasNext()) {// for each forum:
145

146                         Forum forum = (Forum) forumsIterator.next();
147                         System.out
148                                 .println("ProjectMemberRoleChangeEventHandler.handleEvent() -> Updating Notification list of forum:: "
149                                         + forum.getFullName());
150                         // TODO: PVZ One can do this with set and intersections but for
151
// now:
152
// delete the old values first of this forum
153
Iterator JavaDoc notificationList = forum.getNotificationSet()
154                                 .iterator();
155                         while (notificationList.hasNext()) {
156                             ForumChampion champion = (ForumChampion) notificationList
157                                     .next();
158                             try {
159                                 champion.delete();
160                             } catch (Exception JavaDoc e) {
161                                 System.err.println("The forumChampion of this forum could not be deleted!");
162                                 e.printStackTrace();
163                             }
164
165                         }
166                         forum.setNotificationSet(null);
167
168                         Set JavaDoc emailsToNotify = addNotificationLists(
169                                 currentProject.getChampionsAsUsers(), forum);// if
170
// this
171
// is a
172
// static
173
// class
174
// this method must be
175
// static
176

177                         // add the new values
178
forum.setNotificationSet(emailsToNotify);
179                         try {
180                             forum.save();
181                             // if an error occurs here then we will have saved
182
// ForumChampions that is not associated to any
183
// forum in addNotificationLists
184
// TODO: pvz: Please fix this problem. Test by throwing an exception here.
185
} catch (Exception JavaDoc e) {
186                             e.printStackTrace();
187                         }
188
189                     }
190
191                 } else {// project is null!
192
System.out.println("The project is null. We could not use this Event!");
193
194                 }
195
196             }
197
198         }
199
200     }
201
202     static {
203         try {
204             HibernateUtil.configureHibernateForClasses(new Class JavaDoc[] {
205                     Resource.class, Statement.class, Message.class,
206                     Conversation.class, Forum.class, ForumChampion.class,
207                     UserMailPreferences.class,AliasUser.class,
208                     MailForumSettings.class });
209             ResourceFactory.registerClassExpert(new ProjectExpert(),
210                     Project.class);
211             ResourceFactory.registerClassExpert(new CoefficientUserExpert(),
212                     CoefficientUser.class);
213             ResourceFactory.registerClassExpert(new ForumExpert(), Forum.class);
214             // CoefficientEvents.registerEventHandler(CoefficientEvent.class,
215
// new MailForum.ProjectMemberRoleChangeEventHandler());
216
CoefficientEvents.registerEventHandler(CoefficientEvent.class,
217                     new MailForum.ProjectMemberRoleChangeEventHandler());
218             
219             DBUpdateUtil.updateToNewVersion();
220             
221
222         } catch (HibernateException he) {
223             he.printStackTrace();
224         }
225     }
226
227     public String JavaDoc getModuleDisplayName() {
228         return "Discussions";
229     }
230
231     public String JavaDoc getModuleDescription() {
232         return "This module combines web and mail discussions";
233     }
234
235     public String JavaDoc getMainMethod() {
236         return "forumList";
237     }
238
239     public String JavaDoc canExecuteForRole(CoefficientContext ctx, String JavaDoc methodName,
240             Role usersHighestRole) {
241         if (usersHighestRole.getRoleValue() > SecurityUtil.PROJECT_CHAMPION_ROLE_VAL
242                 && (methodName.equals("forumEdit")
243                         || methodName.equals("forumSaveAction") || methodName
244                         .equals("forumDelete"))) {
245
246             return "You must be at least a project champion to perform this operation";
247         } else {
248             return null;
249         }
250     }
251
252     /*
253      * Shows a list of fora that are linked to a particular project
254      */

255     public CoefficientContext forumList(CoefficientContext ctx)
256             throws Exception JavaDoc {
257         HashMap JavaDoc map = createMap(ctx);
258         Long JavaDoc resourceId = getResourceId(ctx, map);
259         // get the forums about the resource
260
Collection JavaDoc forums = Forum.getForumsForResourceId(resourceId);
261         map.put("forums", forums);
262         CoefficientUser user = ctx.getCurrentUser();
263         if (user != null) {
264             map.put("loggedin", "true");
265             // TODO complete
266
// if (.getRoleValue() >= SecurityUtil.PROJECT_CHAMPION_ROLE_VAL)
267
// map.put("canCreateLists", "true");
268
Project project = ctx.getProject();
269             //pvz: add project name to display with the Forum
270
if( project !=null){
271                 map.put("projectName",project.getName());
272             } else {
273                 map.put("projectName","null");
274             }
275         }
276         generatePage("forumList.vm", ctx, map);
277         return ctx;
278     }
279
280     /**
281      * @param project
282      * @return
283      * @throws Exception
284      * Apr 25, 2005 pieter20
285      *
286      * Returns a collection of forums that are linked to this project
287      */

288     public static Collection JavaDoc getForumList(Project project) throws Exception JavaDoc {
289
290         Resource resource = ResourceFactory.ensureResourceExistsFor(project);
291
292         Long JavaDoc resourceId = resource.getResourceId();
293
294         // get the forums about the resource
295
Collection JavaDoc forums = Forum.getForumsForResourceId(resourceId);
296         return forums;
297     }
298
299     public CoefficientContext forumEdit(CoefficientContext ctx)
300             throws Exception JavaDoc {
301         HashMap JavaDoc map = createMap(ctx);
302         Long JavaDoc resourceId = getResourceId(ctx, map);
303         String JavaDoc host = Constants.MAIL_SMTP_HOST;
304         map.put("mailServer", host);
305         // if there is a project, add it to the map
306
Project project = ctx.getProject();
307         //check the number of forums that can be created per project
308
boolean canCreate =true;
309             
310         if (project != null) {
311             canCreate = canCreateForum(project);
312             map.put("project", project);
313         }
314         //check if this is a create or an edit. edit have a forum id set
315
//this limit check can be moved to the forumSaveAction method
316
if ((canCreate == false) && (ctx.getParameterAsLong(PARAM_FORUM_ID) == null)) {
317             //you are trying to creat a new list and the limit has been reached.
318
ctx.setError("Limit reached! The administrator only allows "+Constants.MAX_NUM_OF_FORUMS+" to be created.");
319             return ctx;
320         }
321         // if there is a forumid, get the forum
322
Forum forum = getForum(ctx, map);
323         String JavaDoc maxMessageSize = "1024k";
324         String JavaDoc maxAttachmentSize = "1024k";
325         if (forum != null) {
326             maxMessageSize = forum.getMailForumSettings().getMaxMessageSize();
327             maxAttachmentSize = forum.getMailForumSettings().getMaxAttachmentSize();
328         }
329         map.put("maxMessageSize", maxMessageSize);
330         map.put("maxAttachmentSize", maxAttachmentSize);
331         generatePage("forumEdit.vm", ctx, map);
332         return ctx;
333     }
334
335     public CoefficientContext forumSaveAction(CoefficientContext ctx)
336             throws Exception JavaDoc {
337         HashMap JavaDoc map = createMap(ctx);
338         Long JavaDoc resourceId = getResourceId(ctx, map);
339
340         CoefficientUser user = ctx.getCurrentUser();
341         Resource rUser = ResourceFactory.ensureResourceExistsFor(user);
342
343         Long JavaDoc forumId = ctx.getParameterAsLong(PARAM_FORUM_ID);
344         Forum forum;
345
346         if (forumId == null) {
347             forum = new Forum();
348             forum.setResource(ResourceFactory.getResource(resourceId));
349             forum.setOwner(rUser);
350         } else
351             forum = Forum.getForum(forumId);
352
353         /* set the mail addresses */
354         Project project = ctx.getProject();
355         String JavaDoc forumSnippet = ctx.getParameter("mailAddressSnippet");
356         forum.setMailAddressSnippet(forumSnippet);
357         String JavaDoc address = forumSnippet + "@" + Constants.MAIL_SMTP_HOST;
358         if (project != null)
359             address = project.getShortName() + "." + address;
360         forum.setFullMailAddress(address);
361
362         // set the rest of the data
363
forum.setFullName(ctx.getParameter("fullName"));
364         forum.setMailSubjectPrefix(ctx.getParameter("mailSubjectPrefix"));
365         forum.setDescription(ctx.getParameter("description"));
366         forum.setRequireMembershipToView(ctx
367                 .getParameterAsBoolean("requireMembershipToView"));
368         forum.setRequireMembershipToPost(ctx
369                 .getParameterAsBoolean("requireMembershipToPost"));
370         forum.setModerated(ctx.getParameterAsBoolean("moderated"));
371         boolean openSubscription = ctx
372                 .getParameterAsBoolean("openSubscription");
373         forum.setRequirePermissionToSubscribe(!openSubscription);
374
375         // TODO:pvz this moved into mail_settings!!! :( I have to remove thisand the forumEdit.vm page!
376
forum.setFooterText(ctx.getParameter("footer"));
377         forum.setMaxMessageSize(ctx.getParameterAsInt("maxMessageSize", 1000));
378         forum.setMaxAttachmentSize(ctx
379                 .getParameterAsInt("maxAttachmentSize", 0));
380
381         // TODO: Document my changes: pvz
382

383     
384         MailForumSettings settings = new MailForumSettings();
385
386         settings.setListName(forum.getFullName());
387         settings.setSubjectPrefix(forum.getMailAddressSnippet());
388
389         String JavaDoc footer = settings.getFooterText();
390         // TODO: pvz This has to become dynamic and not hardcoded: if droups:
391
// footer +="\n $user, you are currently subscribed to
392
// "+project.getName()+" as: $emailAddress \n";
393
if (project != null) {
394             footer += "\nYou are currently subscribed to " + project.getName()
395             + "\n";
396         } else {
397             //global_discussion list
398
footer += "\nYou are currently subscribed to global_discussion list\n";
399         }
400         
401         settings.setFooterText(footer);
402
403         settings.save();
404         
405
406         forum.setMailForumSettings(settings);
407
408         forum.save();
409         //this order is important becuase we are saving a forum into the champ and the forum have
410
//to be saved first. Forum is managing the state of this link. If we set inverse true in champ then the
411
//champ will have to be saved first.
412
if (project != null) {
413         Set JavaDoc emailsToNotify = MailForum.addNotificationLists(project
414                     .getChampionsAsUsers(), forum);
415
416             forum.setNotificationSet(emailsToNotify);
417         }//else //global_discussion list
418

419         // fire off a statistic message
420
if (project != null) {
421             String JavaDoc action = StatisticsMessageSender.UPDATE;
422             if (forumId == null) {
423                 action = StatisticsMessageSender.CREATE;
424             }
425             StatisticsMessageSenderFactory.getStatisticsMessageSender()
426                     .reportStatistic(project.getId(), getModuleName(), action);
427         }
428
429         // the owner is the first subscriber
430
if (forumId == null)
431             forum.subscribe(user);
432
433         addForum(forum, map);
434         ctx.setForward(getModuleName(), "forumView", map);
435         return ctx;
436     }
437
438     /**
439      * @param projectChampionUserList
440      * @param forum
441      * @return Apr 25, 2005 pieter20
442      *
443      * we need to set the ForumChampion's parent ForumId and for this we need
444      * the forum. If this is not set we will have forumChamp's that do not have any reference
445      * back to the forum. But are saved in the db. Please consult the Hibernate Reference Manual Ch 16: Parent/Child
446      * and one-to-many relationships
447      */

448     private static Set JavaDoc addNotificationLists(List JavaDoc projectChampionUserList,
449             Forum forum) {
450         Iterator JavaDoc projectChampionList = projectChampionUserList.iterator();
451         Set JavaDoc emailsToNotify = new HashSet JavaDoc();
452
453         while (projectChampionList.hasNext()) {
454             CoefficientUser championUser = (CoefficientUser) projectChampionList
455                     .next();
456             String JavaDoc emailAddress = championUser.getAliasEmail();
457             ForumChampion forumChamp = new ForumChampion();
458             forumChamp.setEMailAdrress(emailAddress);
459             forumChamp.setForum(forum);
460
461             try {
462                 forumChamp.save();
463             } catch (Exception JavaDoc e) {
464                 e.printStackTrace();
465             }
466
467             emailsToNotify.add(forumChamp);
468         }
469         return emailsToNotify;
470     }
471
472     // TODO change owner of forum
473
public CoefficientContext forumView(CoefficientContext ctx)
474             throws Exception JavaDoc {
475         HashMap JavaDoc map = createMap(ctx);
476         CoefficientUser user = ctx.getCurrentUser();
477         Forum forum = getForum(ctx, map);
478         if (user != null) {
479             map.put("loggedin", "true");
480             // check user is subscribed
481
if (forum.isUserSubscribed(user)){
482                 map.put("subscribed", "true");
483                 Project project = ctx.getProject();
484                 //pvz: add project name to display with the Forum
485
if( project !=null){
486                     map.put("projectName",project.getName());
487                 } else {
488                     map.put("projectName","null");
489                 }
490             
491             }else {
492                 // check if the user is allowed to subscribe, which
493
// depends on whether we're in a project or not, and whether
494
// the forum is open or not
495
Project project = ctx.getProject();
496                 //pvz: add project name to display with the Forum
497
if( project !=null){
498                     map.put("projectName",project.getName());
499                 } else {
500                     map.put("projectName","null");
501                 }
502                 
503                 if (project == null) {
504                     if (forum.getRequirePermissionToSubscribe()) {
505                         // Is the user is a project member?
506
if (project.containsUser(user))
507                             map.put("allowSubscribe", "true");
508                     }
509                     // forum doesn't care
510
else
511                         map.put("allowSubscribe", "true");
512                 }
513                 // no project, so only depends on forum
514
else {
515                     if (forum.getRequirePermissionToSubscribe()) {
516                         // is the user an admin user?
517
if (user.getSystemRole().getRoleValue() == SecurityUtil.SITE_ADMIN_ROLE_VAL)
518                             map.put("allowSubscribe", "true");
519                     }
520                     // forum doesn't care
521
else
522                         map.put("allowSubscribe", "true");
523                 }
524             }
525             
526             String JavaDoc maxMessageSize = "";
527             String JavaDoc maxAttachmentSize = "";
528             if (forum != null) {
529                 maxMessageSize = forum.getMailForumSettings().getMaxMessageSize();
530                 maxAttachmentSize = forum.getMailForumSettings().getMaxAttachmentSize();
531             }
532             map.put("maxMessageSize", maxMessageSize);
533             map.put("maxAttachmentSize", maxAttachmentSize);
534             
535             // check if user may post
536
if (forum.mayUserViewMessages(user))
537                 map.put("allowMessageView", "true");
538             // check if user is owner (may change info)
539
Resource rUser = ResourceFactory.ensureResourceExistsFor(user);
540             if (forum.getOwner().equals(rUser))
541                 map.put("userIsOwner", "true");
542             
543         }
544         generatePage("forumView.vm", ctx, map);
545         return ctx;
546     }
547
548     public CoefficientContext userForumSubscribeToggleAction(
549             CoefficientContext ctx) throws Exception JavaDoc {
550         HashMap JavaDoc map = createMap(ctx);
551         CoefficientUser user = ctx.getCurrentUser();
552         Forum forum = getForum(ctx, map);
553         if (forum.isUserSubscribed(user)) {
554             forum.unsubscribe(user);
555         } else {
556             forum.subscribe(user);
557             //add the user to as an alias
558
Collection JavaDoc aliasUsers = AliasUser.getAliasEmailForUserName(user.getUserName());
559             // TODO: PVZ
560
if (aliasUsers == null || aliasUsers.size() == 0) {
561                 System.out
562                         .println("MailForum.messageSaveAction() -> adding user to alias user table");
563                 System.out
564                 .println("MailForum.messageSaveAction() -> adding user to alias user table: "+user.getAliasEmail());
565                 AliasUser aliasUser = new AliasUser();
566                 aliasUser.setUserName(user.getUserName());
567                 aliasUser.setAliasEmailAddress(user.getAliasEmail());
568                 aliasUser.setRealEmailAddress(user.getEmail());
569                 aliasUser.save();
570
571             }//end if alias does not exist
572
}
573         // fire off a statistic message
574
if (ctx.getProject() != null) {
575             StatisticsMessageSenderFactory.getStatisticsMessageSender()
576                     .reportStatistic(ctx.getProject().getId(), getModuleName(),
577                             StatisticsMessageSender.UPDATE);
578         }
579         ctx.setForward(getModuleName(), "forumView", map);
580         return ctx;
581     }
582
583     public CoefficientContext forumDelete(CoefficientContext ctx)
584             throws Exception JavaDoc {
585         HashMap JavaDoc map = createMap(ctx);
586         Forum forum = getForum(ctx, null);
587         PersistenceService.delete(forum);
588         ctx.setForward(getModuleName(), "forumList", map);
589         return ctx;
590     }
591
592     public CoefficientContext conversationList(CoefficientContext ctx)
593             throws Exception JavaDoc {
594         HashMap JavaDoc map = createMap(ctx);
595         Forum forum = getForum(ctx, map);
596         CoefficientUser user = ctx.getCurrentUser();
597
598         HibernatePager conversationPager = (HibernatePager) ctx
599                 .getSessionAttribute(CONVERSATION_PAGER);
600         if (ctx.getParameter("next") != null) {
601             if (conversationPager == null) {
602                 ctx
603                         .setError("There must be a list of conversations before you can view the next page.");
604             } else {
605                 conversationPager.next();
606             }
607         } else if (ctx.getParameter("prev") != null) {
608             if (conversationPager == null) {
609                 ctx
610                         .setError("There must be a list of conversations before you can view the previous page.");
611             } else {
612                 conversationPager.previous();
613             }
614         } else if (ctx.getParameter("page") != null) {
615             if (conversationPager == null || ctx.getParameter("page") == null) {
616                 ctx
617                         .setError("There must be a list of conversations and you must select a page to view.");
618             } else {
619                 conversationPager.goToPage(ctx.getParameterAsInteger("page")
620                         .intValue());
621             }
622         } else {
623             String JavaDoc strQuery = "SELECT conversation "
624                     + " FROM Conversation AS conversation, Resource AS resource "
625                     + " WHERE (resource=conversation.resource) "
626                     + " AND resource.resourceId= ? order by conversation.conversationId desc";
627             Object JavaDoc[] values = new Object JavaDoc[] { ResourceFactory
628                     .ensureResourceExistsFor(forum).getResourceId() };
629             conversationPager = new HibernatePager(strQuery, values,
630                     Constants.MAX_ELEMENTS_PER_PAGE);
631             ctx.setSessionAttribute(CONVERSATION_PAGER, conversationPager);
632         }
633         map.put("pager", conversationPager);
634         Project project = ctx.getProject();
635         //pvz: add project name to display with the Forum
636
if( project !=null){
637             map.put("projectName",project.getName());
638         } else {
639             map.put("projectName","null");
640         }
641         checkAllowPost(user, forum, map);
642         generatePage("conversationList.vm", ctx, map);
643         return ctx;
644     }
645
646     public CoefficientContext messageEdit(CoefficientContext ctx)
647             throws Exception JavaDoc {
648         HashMap JavaDoc map = createMap(ctx);
649         // when adding a message, might get a conversation, a resource, a forum
650
// or
651
// a previous message as an anchor to link the new message to
652
// sometimes have to add the subject
653
String JavaDoc anchor;
654         // look for previousmessageid
655
Long JavaDoc previousMessageId = ctx.getParameterAsLong("previousmessageid");
656         if (previousMessageId != null) {
657             anchor = "&previousmessageid=" + previousMessageId;
658             Message previousMessage = Message.getMessage(previousMessageId);
659             map.put("previousMessage", previousMessage);
660             map.put("subject", Message.getReplySubject(previousMessage
661                     .getSubject()));
662         } else {
663             // try conversationid
664
Long JavaDoc conversationId = ctx.getParameterAsLong("conversationid");
665             if (conversationId != null) {
666                 anchor = "&conversationid=" + conversationId;
667                 Conversation conversation = Conversation
668                         .getConversation(conversationId);
669                 map.put("subject", Message.getReplySubject(conversation
670                         .getSubject()));
671             } else {
672                 // try forumid
673
Long JavaDoc forumId = ctx.getParameterAsLong(PARAM_FORUM_ID);
674                 if (forumId != null) {
675                     anchor = "&forumid=" + forumId;
676                 } else {
677                     // otherwise use resourceid
678
Long JavaDoc resourceId = ctx.getParameterAsLong(PARAM_RESOURCE_ID);
679                     anchor = "&resourceid=" + resourceId;
680                 }
681             }
682         }
683         map.put("anchorInfo", anchor);
684         Project project = ctx.getProject();
685         //pvz: add project name to display with the Forum
686
if( project !=null){
687             map.put("projectName",project.getName());
688         } else {
689             map.put("projectName","null");
690         }
691         Forum forum = getForum(ctx, map);
692         generatePage("messageEdit.vm", ctx, map);
693         return ctx;
694     }
695
696     public Message createMessage(CoefficientContext ctx) throws Exception JavaDoc {
697         Message message = new Message();
698         message.setSubject(ctx.getParameter("subject"));
699         message.setBody(ctx.getParameter("body"));
700         message.setDateCreated(new Date JavaDoc(System.currentTimeMillis()));
701
702         CoefficientUser user = ctx.getCurrentUser();
703         if (user != null) {
704             message.setAuthor(user);
705         } else {
706             // get text email address
707
}
708         return message;
709     }
710
711     public CoefficientContext messageSaveAction(CoefficientContext ctx)
712             throws Exception JavaDoc {
713         HashMap JavaDoc map = createMap(ctx);
714         Forum forum = null;
715         Message message = createMessage(ctx);
716         // message might be added to a conversation, resource, forum, previous
717
// message
718
Long JavaDoc previousMessageId = ctx.getParameterAsLong("previousmessageid");
719         if (previousMessageId != null) {
720             Message previousMessage = Message.getMessage(previousMessageId);
721             message.setInReplyTo(previousMessage);
722             forum = (Forum) previousMessage.getConversation().getResource()
723                     .getObject();
724         } else {
725             Conversation conversation = null;
726             // try conversationid
727
Long JavaDoc conversationId = ctx.getParameterAsLong("conversationid");
728             if (conversationId != null) {
729                 conversation = Conversation.getConversation(conversationId);
730                 message.setConversation(conversation);
731                 forum = (Forum) conversation.getResource().getObject();
732             } else {
733                 // will need to create a conversation & link it to the anchor
734
// which could be a forum, or some other resource
735
conversation = new Conversation(message.getSubject());
736                 Resource rAnchor;
737                 // try forumid
738
Long JavaDoc forumId = ctx.getParameterAsLong(PARAM_FORUM_ID);
739                 if (forumId != null) {
740                     forum = Forum.getForum(forumId);
741                     rAnchor = ResourceFactory.ensureResourceExistsFor(forum);
742                 } else {
743                     // otherwise use resourceid
744
Long JavaDoc resourceId = ctx.getParameterAsLong(PARAM_RESOURCE_ID);
745                     if (resourceId != null) {
746                         rAnchor = ResourceFactory.getResource(resourceId);
747                     } else {
748                         throw new Exception JavaDoc(
749                                 "Nothing to attach the message to, cannot create message");
750                     }
751                 }
752                 conversation.setResource(rAnchor);
753                 conversation.save();
754                 message.setConversation(conversation);
755             }
756         }
757
758         // fire off a statistic message
759
if (ctx.getProject() != null) {
760             String JavaDoc action = StatisticsMessageSender.UPDATE;
761             if (message.getMessageid() == null) {
762                 action = StatisticsMessageSender.CREATE;
763             }
764             StatisticsMessageSenderFactory.getStatisticsMessageSender()
765                     .reportStatistic(ctx.getProject().getId(), getModuleName(),
766                             action);
767         }
768
769         message.save();
770
771
772         
773         //pvz: we need to do this check here as well as the user can post messages without being subscribed:
774
Collection JavaDoc aliasUsers = AliasUser.getAliasEmailForUserName(ctx.getCurrentUser().getUserName());
775         // TODO: PVZ
776
if (aliasUsers == null || aliasUsers.size() == 0) {
777             System.out
778                     .println("MailForum.messageSaveAction() -> adding user to alias user table");
779             System.out
780             .println("MailForum.messageSaveAction() -> adding user to alias user table: "+ctx.getCurrentUser().getAliasEmail());
781             AliasUser aliasUser = new AliasUser();
782             aliasUser.setUserName(ctx.getCurrentUser().getUserName());
783             aliasUser.setAliasEmailAddress(ctx.getCurrentUser().getAliasEmail());
784             aliasUser.setRealEmailAddress(ctx.getCurrentUser().getEmail());
785             aliasUser.save();
786
787         }
788
789         // generate a mail
790
MailGenerator.setMailServer(Constants.MAIL_SMTP_HOST);
791         //pvz: old way:
792
//String sender = ctx.getCurrentUser().getEmail();
793
//pvz: the alias way:
794
String JavaDoc sender = ctx.getCurrentUser().getAliasEmail();
795         
796         String JavaDoc forumAddress = forum.getFullMailAddress(); // TODO handle
797
// non-forum
798
// resources
799
MailGenerator.createMail(sender, message, forumAddress);
800         // send to the view conversation page
801
map
802                 .put("conversationid", message.getConversation()
803                         .getConversationId());
804         ctx.setForward(getModuleName(), "conversationView", map);
805         return ctx;
806     }
807
808     public CoefficientContext messageView(CoefficientContext ctx)
809             throws Exception JavaDoc {
810         HashMap JavaDoc map = createMap(ctx);
811         Long JavaDoc messageid = ctx.getParameterAsLong("messageid");
812         Message message = Message.getMessage(messageid);
813         map.put("message", message);
814         map.put("messageInfo", "&previousmessageid=" + message.getMessageid());
815         map.put("messageCreateDate", message.getDateCreated());
816
817         Forum forum = (Forum) message.getConversation().getResource()
818                 .getObject();
819         checkAllowPost(ctx.getCurrentUser(), forum, map);
820         
821         MailForumSettings settings = forum.getMailForumSettings();
822         //add isSubjectPrefix and subjectPrefix
823

824         map.put("addSubjectPrefix",new Boolean JavaDoc(settings.isAddSubjectPrefix()));
825     
826         
827         if (settings.isAddSubjectPrefix()) {
828             
829             map.put("subjectPrefix",settings.getSubjectPrefix());
830         }
831         Project project = ctx.getProject();
832         //pvz: add project name to display with the Forum
833
if( project !=null){
834             map.put("projectName",project.getName());
835         } else {
836             map.put("projectName","null");
837         }
838         generatePage("messageView.vm", ctx, map);
839         return ctx;
840     }
841
842     public CoefficientContext conversationView(CoefficientContext ctx)
843             throws Exception JavaDoc {
844         HashMap JavaDoc map = createMap(ctx);
845         Long JavaDoc conversationId = ctx.getParameterAsLong("conversationid");
846         Conversation conversation = Conversation
847                 .getConversation(conversationId);
848         map.put("conversation", conversation);
849         map.put("conversationInfo", "&conversationid="
850                 + conversation.getConversationId());
851         Forum forum = (Forum) conversation.getResource().getObject();
852         map.put("forum", forum);
853         Project project = ctx.getProject();
854         //pvz: add project name to display with the Forum
855
if( project !=null){
856             map.put("projectName",project.getName());
857         } else {
858             map.put("projectName","null");
859         }
860         checkAllowPost(ctx.getCurrentUser(), forum, map);
861         generatePage("conversationView.vm", ctx, map);
862         return ctx;
863     }
864
865     public CoefficientContext userMailPreferencesEdit(CoefficientContext ctx)
866             throws Exception JavaDoc {
867         HashMap JavaDoc map = createMap(ctx);
868         CoefficientUser user = ctx.getCurrentUser();
869         Resource rUser = ResourceFactory.ensureResourceExistsFor(user);
870         UserMailPreferences preferences = UserMailPreferences
871                 .ensureUserMailPreferencesExistsFor(rUser);
872         if (preferences != null)
873             map.put("preferences", preferences);
874         generatePage("userMailPreferencesEdit.vm", ctx, map);
875         return ctx;
876     }
877
878     public CoefficientContext userMailPreferencesSaveAction(
879             CoefficientContext ctx) throws Exception JavaDoc {
880         HashMap JavaDoc map = createMap(ctx);
881         CoefficientUser user = ctx.getCurrentUser();
882         Resource rUser = ResourceFactory.ensureResourceExistsFor(user);
883         UserMailPreferences preferences = UserMailPreferences
884                 .ensureUserMailPreferencesExistsFor(rUser);
885         if (preferences == null) {
886             preferences = new UserMailPreferences();
887             preferences.setUser(rUser);
888         }
889         preferences.setMailDelivery(ctx.getParameterAsInteger("mailDelivery")
890                 .intValue());
891         preferences.setMailReceipt(ctx.getParameterAsInteger("mailReceipt")
892                 .intValue());
893         preferences.setReceiveAttachments(ctx
894                 .getParameterAsBoolean("receiveAttachments"));
895         preferences.save();
896         ctx.setForward(getModuleName(), "forumList", map);
897         return ctx;
898     }
899
900     public CoefficientContext deleteAllForProject(CoefficientContext ctx)
901             throws Exception JavaDoc {
902         // TODO Auto-generated method stub
903
return ctx;
904     }
905
906     private Long JavaDoc getResourceId(CoefficientContext ctx, HashMap JavaDoc map)
907             throws Exception JavaDoc {
908         Long JavaDoc resourceId = ctx.getParameterAsLong(PARAM_RESOURCE_ID);
909         if (resourceId != null)
910             return resourceId;
911
912         Resource resource;
913         // look for a resourceuri
914
String JavaDoc strResourceURI = ctx.getParameter(PARAM_RESOURCE_URI);
915         if (strResourceURI != null)
916             resource = ResourceFactory.ensureResourceExists("forumDiscussion",
917                     strResourceURI);
918         // otherwise, get the resource for the project
919
else {
920             Project project = ctx.getProject();
921             if (project != null)
922                 resource = ResourceFactory.ensureResourceExistsFor(project);
923             // if there is no project, get the global discussion resource
924
else
925                 resource = ResourceFactory.ensureResourceExists(
926                         "General discussion", "forum:global_discussion");
927         }
928         return resource.getResourceId();
929     }
930
931     private HashMap JavaDoc createMap(CoefficientContext ctx) throws Exception JavaDoc {
932         HashMap JavaDoc map = new HashMap JavaDoc();
933         // eases the creation of url's, reduces errors, makes changing easier
934
map.put("thisModule", "index.html?module=MailForum");
935         return map;
936     }
937
938     private void generatePage(String JavaDoc page, CoefficientContext ctx, HashMap JavaDoc map) {
939         StringBuffer JavaDoc html = VelocityScreenUtil.getProcessedScreen(page, map);
940         ctx.setModuleContent(html.toString(), getModuleDisplayName());
941     }
942
943     private void checkAllowPost(CoefficientUser user, Forum forum, HashMap JavaDoc map)
944             throws Exception JavaDoc {
945         if (forum.mayUserPostMessages(user))
946             map.put("allowMessagePost", "true");
947     }
948
949     private void addForum(Forum forum, HashMap JavaDoc map) {
950         map.put("forum", forum);
951         map.put("forumInfo", "&" + PARAM_FORUM_ID + "=" + forum.getForumId());
952     }
953
954     private Forum getForum(CoefficientContext ctx, HashMap JavaDoc map)
955             throws Exception JavaDoc {
956         Forum forum = null;
957         Long JavaDoc forumId = ctx.getParameterAsLong(PARAM_FORUM_ID);
958         if (forumId != null) {
959             // get the forum from the id given
960
forum = Forum.getForum(forumId);
961             if (map != null)
962                 addForum(forum, map);
963         }
964         return forum;
965     }
966
967     /**
968      * @param ctx
969      * @return
970      * @throws Exception
971      * Apr 19, 2005 pieter20
972      *
973      */

974     public CoefficientContext forumSettingsEdit(CoefficientContext ctx)
975             throws Exception JavaDoc {
976
977         System.out.println("forumSettingsEdit");
978
979         HashMap JavaDoc map = createMap(ctx);
980         Project project = ctx.getProject();
981
982         Forum forum = getForum(ctx, map);
983
984         MailForumSettings settings = forum.getMailForumSettings();
985
986         
987         // wrap the keys in the ConfigKey object for display:
988
Map JavaDoc settingsDisplayMap = prepareSettingsForDisplay(settings
989                 .getAllSettings().keySet());
990
991         if (project != null) {
992             map.put("projectName", project.getName());
993
994         } else {
995             // this could happen in the top level discussion-module, as it also
996
// uses the MailForum module and is not associated with a project
997
// but the whole site
998
map.put("projectName", "Discussion");
999
1000        }
1001
1002        map.put("configKeys", settingsDisplayMap.values());// the configKeys
1003
// map.put("settingValues",settings.getAllSettings().values());
1004

1005        map.put("settings", settings.getAllSettings());
1006        map.put("sendOptions", "");
1007
1008        generatePage("forumSettingsEdit.vm", ctx, map);
1009        return ctx;
1010    }
1011    
1012    /**
1013     * @param settingsMap
1014     * @return
1015     * Apr 29, 2005
1016     * pieter20
1017     *
1018     * pvz: I am preparing the forum settings for display by wraping their names (to display)
1019     * and their type of display widget in the ConfigKeyUtil class
1020     * The MailForumSettings does not do this as I feel it should have no knowledge of display issues.
1021     * The MailForum is responsible for display
1022     */

1023    private Map JavaDoc prepareSettingsForDisplay(Set JavaDoc settingsKeySet) {
1024        
1025        Map JavaDoc settingsDisplayMap = new TreeMap JavaDoc();
1026        
1027        for (Iterator JavaDoc iter = settingsKeySet.iterator(); iter.hasNext();) {
1028            String JavaDoc key = (String JavaDoc) iter.next();
1029            ConfigKeyUtil configKey = new ConfigKeyUtil();
1030            
1031            if (key == MailForumSettings.FOOTER_TEXT) {
1032                configKey.setFieldName(key);
1033                configKey.setType(ConfigKeyUtil.TYPE_TEXTAREA);
1034            }else if (key == MailForumSettings.FROM_ALIAS_BCC_RECIPIENTS) {
1035                configKey.setFieldName(key);
1036                configKey.setType(ConfigKeyUtil.RADIO_BUTTON);
1037            }else if (key == MailForumSettings.FROM_ALIAS_TO_EACH_RECIPIENT) {
1038                configKey.setFieldName(key);
1039                configKey.setType(ConfigKeyUtil.RADIO_BUTTON);
1040            }else if (key == MailForumSettings.FROM_LIST_BCC_RECIPIENTS) {
1041                configKey.setFieldName(key);
1042                configKey.setType(ConfigKeyUtil.RADIO_BUTTON);
1043            }else {
1044                
1045                configKey.setFieldName(key);
1046                configKey.setType(ConfigKeyUtil.TYPE_TEXTFIELD);
1047            }
1048            settingsDisplayMap.put(key,configKey);
1049            
1050        }
1051        
1052        return settingsDisplayMap;
1053    }
1054
1055    /**
1056     * @param ctx
1057     * @return
1058     * @throws Exception
1059     * Apr 19, 2005 pieter20
1060     */

1061    public CoefficientContext forumSettingsSaveAction(CoefficientContext ctx)
1062            throws Exception JavaDoc {
1063
1064        System.out.println("forumSettingsSaveAction");
1065
1066        Set JavaDoc newSettings = new HashSet JavaDoc();
1067
1068        HashMap JavaDoc map = createMap(ctx);
1069        Forum forum = getForum(ctx, map);
1070
1071        MailForumSettings settings = forum.getMailForumSettings();
1072
1073        newSettings.addAll(settings.getAllSettings().keySet());
1074
1075        Iterator JavaDoc settingNames = newSettings.iterator();
1076
1077        for (; settingNames.hasNext();) {
1078            String JavaDoc propertyName = (String JavaDoc) settingNames.next();
1079            String JavaDoc propertyValue = ctx.getParameter(propertyName);
1080            System.out.println("propertyName: " + propertyName
1081                    + " propertyValue; " + propertyValue);
1082            settings.setSetting(propertyName, propertyValue);
1083
1084        }
1085        //this is to handle the radio buttons:
1086
String JavaDoc propertyValue = ctx.getParameter("sendOptions");
1087        System.out.println("propertyName: " + "sendOptions"
1088                + " propertyValue; " + propertyValue);
1089        System.out.println("MailForum.forumSettingsSaveAction() -> saving the sending properties.................");
1090        if (propertyValue.compareTo(MailForumSettings.FROM_ALIAS_BCC_RECIPIENTS) ==0) {
1091            System.out.println("MailForum.forumSettingsSaveAction() -> .........FROM_ALIAS_BCC_RECIPIENTS");
1092            settings.setSetting( MailForumSettings.FROM_ALIAS_BCC_RECIPIENTS, "true");
1093            settings.setSetting( MailForumSettings.FROM_ALIAS_TO_EACH_RECIPIENT, "false");
1094            settings.setSetting( MailForumSettings.FROM_LIST_BCC_RECIPIENTS, "false");
1095
1096        } else if (propertyValue.compareTo(MailForumSettings.FROM_ALIAS_TO_EACH_RECIPIENT)==0) {
1097            System.out.println("MailForum.forumSettingsSaveAction() -> .........FROM_ALIAS_TO_EACH_RECIPIENT");
1098            settings.setSetting( MailForumSettings.FROM_ALIAS_BCC_RECIPIENTS, "false");
1099            settings.setSetting( MailForumSettings.FROM_ALIAS_TO_EACH_RECIPIENT, "true");
1100            settings.setSetting( MailForumSettings.FROM_LIST_BCC_RECIPIENTS, "false");
1101
1102        } else if (propertyValue.compareTo(MailForumSettings.FROM_LIST_BCC_RECIPIENTS)==0) {
1103            System.out.println("MailForum.forumSettingsSaveAction() -> .........FROM_LIST_BCC_RECIPIENTS");
1104            settings.setSetting( MailForumSettings.FROM_ALIAS_BCC_RECIPIENTS, "false");
1105            settings.setSetting( MailForumSettings.FROM_ALIAS_TO_EACH_RECIPIENT, "false");
1106            settings.setSetting( MailForumSettings.FROM_LIST_BCC_RECIPIENTS, "true");
1107
1108        }
1109        
1110
1111        settings.save();
1112
1113        return forumView(ctx);
1114
1115    }
1116    
1117    /**
1118     * This method is used to check the number of forums that
1119     * can be created per project
1120     *
1121     * @return
1122     * May 30, 2005
1123     * pieter20
1124     */

1125    private boolean canCreateForum(Project currentProject) {
1126        
1127        try {
1128            Collection JavaDoc forumList = MailForum.getForumList(currentProject);
1129            
1130            if (forumList.size() < Constants.MAX_NUM_OF_FORUMS) {
1131                return true;
1132            } else {
1133                return false;
1134            }
1135            
1136        } catch (Exception JavaDoc e) {
1137            e.printStackTrace();
1138        }
1139        
1140        
1141        
1142        
1143        return true;
1144        
1145    }
1146
1147    
1148
1149}
1150
Popular Tags