KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > tigris > scarab > actions > ModifyIssue


1 package org.tigris.scarab.actions;
2
3 /* ================================================================
4  * Copyright (c) 2000-2003 CollabNet. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowlegement: "This product includes
19  * software developed by Collab.Net <http://www.Collab.Net/>."
20  * Alternately, this acknowlegement may appear in the software itself, if
21  * and wherever such third-party acknowlegements normally appear.
22  *
23  * 4. The hosted project names must not be used to endorse or promote
24  * products derived from this software without prior written
25  * permission. For written permission, please contact info@collab.net.
26  *
27  * 5. Products derived from this software may not use the "Tigris" or
28  * "Scarab" names nor may "Tigris" or "Scarab" appear in their names without
29  * prior written permission of Collab.Net.
30  *
31  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
35  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
39  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
40  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ====================================================================
44  *
45  * This software consists of voluntary contributions made by many
46  * individuals on behalf of Collab.Net.
47  */

48
49 import java.util.ArrayList JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.HashSet JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.Set JavaDoc;
56
57 import org.apache.commons.collections.map.LinkedMap;
58 import org.apache.commons.fileupload.FileItem;
59 import org.apache.fulcrum.intake.model.Field;
60 import org.apache.fulcrum.intake.model.Group;
61 import org.apache.fulcrum.parser.ParameterParser;
62 import org.apache.torque.om.NumberKey;
63 import org.apache.turbine.RunData;
64 import org.apache.turbine.TemplateContext;
65 import org.apache.turbine.Turbine;
66 import org.apache.turbine.tool.IntakeTool;
67 import org.tigris.scarab.actions.base.BaseModifyIssue;
68 import org.tigris.scarab.attribute.DateAttribute;
69 import org.tigris.scarab.attribute.OptionAttribute;
70 import org.tigris.scarab.om.ActivitySet;
71 import org.tigris.scarab.om.Attachment;
72 import org.tigris.scarab.om.AttachmentManager;
73 import org.tigris.scarab.om.Attribute;
74 import org.tigris.scarab.om.AttributeValue;
75 import org.tigris.scarab.om.Condition;
76 import org.tigris.scarab.om.Depend;
77 import org.tigris.scarab.om.DependManager;
78 import org.tigris.scarab.om.DependType;
79 import org.tigris.scarab.om.Issue;
80 import org.tigris.scarab.om.IssueManager;
81 import org.tigris.scarab.om.IssueType;
82 import org.tigris.scarab.om.Module;
83 import org.tigris.scarab.om.ScarabUser;
84 import org.tigris.scarab.services.security.ScarabSecurity;
85 import org.tigris.scarab.tools.ScarabGlobalTool;
86 import org.tigris.scarab.tools.ScarabLocalizationTool;
87 import org.tigris.scarab.tools.ScarabRequestTool;
88 import org.tigris.scarab.tools.localization.L10NKeySet;
89 import org.tigris.scarab.tools.localization.L10NMessage;
90 import org.tigris.scarab.tools.localization.LocalizationKey;
91 import org.tigris.scarab.util.ComponentLocator;
92 import org.tigris.scarab.util.Log;
93 import org.tigris.scarab.util.MutableBoolean;
94 import org.tigris.scarab.util.ScarabConstants;
95 import org.tigris.scarab.util.ScarabException;
96 import org.tigris.scarab.util.ScarabUtil;
97
98 /**
99  * This class is responsible for edit issue forms.
100  * ScarabIssueAttributeValue
101  * @author <a HREF="mailto:elicia@collab.net">Elicia David</a>
102  * @version $Id: ModifyIssue.java 9649 2005-04-26 18:39:05Z jorgeuriarte $
103  */

104 public class ModifyIssue extends BaseModifyIssue
105 {
106
107     public void doSubmitattributes(RunData data, TemplateContext context)
108         throws Exception JavaDoc
109     {
110         if (isCollision(data, context))
111         {
112             return;
113         }
114
115         ScarabRequestTool scarabR = getScarabRequestTool(context);
116         ScarabLocalizationTool l10n = getLocalizationTool(context);
117         Issue issue = scarabR.getIssue();
118         Module module = scarabR.getCurrentModule();
119
120         if (issue == null)
121         {
122             // no need to set the message here as
123
// it is done in scarabR.getIssue()
124
return;
125         }
126         ScarabUser user = (ScarabUser)data.getUser();
127         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
128                                issue.getModule()))
129         {
130             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
131             return;
132         }
133
134         IntakeTool intake = getIntakeTool(context);
135         
136         ScarabGlobalTool scarabG = this.getGlobalTool(data);
137         
138         boolean isReasonRequired = scarabG.isIssueReasonRequired(module);
139         
140         // Reason field is required to modify attributes
141
Group reasonGroup = intake.get("Attachment", "attCommentKey" + issue.getQueryKey(), false);
142         Field reasonField = null;
143         reasonField = reasonGroup.get("Data");
144
145         if(isReasonRequired)
146         {
147             reasonField.setRequired(true);
148         }
149         
150         // make sure to trim the whitespace
151
String JavaDoc reasonFieldString = reasonField.toString();
152         if (reasonFieldString != null)
153         {
154             reasonFieldString = reasonFieldString.trim();
155         }
156         if (reasonGroup == null || !reasonField.isValid() ||
157             reasonFieldString.length() == 0)
158         {
159             if (isReasonRequired)
160             {
161                 reasonField.setMessage(
162                     "ExplanatoryReasonRequiredToModifyAttributes");
163             }
164         }
165
166         // Set any other required flags
167
Set JavaDoc selectedOptions = new HashSet JavaDoc();
168         Map JavaDoc conditionallyRequiredFields = new HashMap JavaDoc();
169         IssueType issueType = issue.getIssueType();
170         List JavaDoc requiredAttributes = issueType
171             .getRequiredAttributes(issue.getModule());
172         AttributeValue aval = null;
173         Group group = null;
174         LinkedMap modMap = issue.getModuleAttributeValuesMap();
175         for (Iterator JavaDoc iter = modMap.mapIterator(); iter.hasNext(); )
176         {
177             aval = (AttributeValue)modMap.get(iter.next());
178             group = intake.get("AttributeValue", aval.getQueryKey(), false);
179
180             if (group != null)
181             {
182                 Field field = null;
183                 if (aval instanceof OptionAttribute)
184                 {
185                     field = group.get("OptionId");
186                     // Will store the selected optionId, for later query.
187
Object JavaDoc fieldValue = field.getValue();
188                     if (null != fieldValue)
189                     {
190                         selectedOptions.add(fieldValue);
191                     }
192                 }
193                 else
194                 {
195                     field = group.get("Value");
196                 }
197                 /**
198                  * If the field has any conditional constraint, will be added to the collection for later query.
199                  */

200                 List JavaDoc conditions = aval.getRModuleAttribute().getConditions();
201                 if (conditions.size() > 0)
202                 {
203                     for (Iterator JavaDoc it = conditions.iterator(); it.hasNext(); )
204                     {
205                         Condition cond = (Condition)it.next();
206                         Integer JavaDoc id = cond.getOptionId();
207                         List JavaDoc fields = (List JavaDoc)conditionallyRequiredFields.get(id);
208                         if (fields == null)
209                         {
210                             fields = new ArrayList JavaDoc();
211                         }
212                         fields.add(field);
213                         conditionallyRequiredFields.put(id, fields);
214                     }
215                 }
216                 
217                 for (int j=requiredAttributes.size()-1; j>=0; j--)
218                 {
219                     if (aval.getAttribute().getPrimaryKey().equals(
220                          ((Attribute)requiredAttributes.get(j)).getPrimaryKey()))
221                     {
222                         field.setRequired(true);
223                         break;
224                     }
225                 }
226             }
227         }
228         /**
229          * Now that we have all the info, we will force the 'required' status of any field
230          * whose requiredOptionId has been set in the issue.
231          */

232         for (Iterator JavaDoc requiredIds = conditionallyRequiredFields.keySet().iterator(); requiredIds.hasNext(); )
233         {
234             Integer JavaDoc attributeId= (Integer JavaDoc)requiredIds.next();
235             if (selectedOptions.contains(attributeId))
236             {
237                 List JavaDoc fields = (List JavaDoc)conditionallyRequiredFields.get(attributeId);
238                 for (Iterator JavaDoc iter = fields.iterator(); iter.hasNext(); )
239                 {
240                     Field field = (Field)iter.next();
241                     if (field.getValue().toString().length() == 0)
242                     {
243                         field.setRequired(true);
244                         field.setMessage("ConditionallyRequiredAttribute");
245                     }
246                 }
247             }
248         }
249
250         if (intake.isAllValid())
251         {
252             AttributeValue aval2 = null;
253             HashMap JavaDoc newAttVals = new HashMap JavaDoc();
254
255             // Set the attribute values entered
256
Iterator JavaDoc iter2 = modMap.mapIterator();
257             boolean modifiedAttribute = false;
258             while (iter2.hasNext())
259             {
260                 aval = (AttributeValue)modMap.get(iter2.next());
261                 aval2 = AttributeValue.getNewInstance(aval.getAttributeId(),
262                                                       aval.getIssue());
263                 aval2.setProperties(aval);
264  
265                 group = intake.get("AttributeValue", aval.getQueryKey(), false);
266                 String JavaDoc oldValue = "";
267                 String JavaDoc newValue = "";
268
269                 if (group != null)
270                 {
271                     if (aval instanceof OptionAttribute)
272                     {
273                         newValue = group.get("OptionId").toString();
274                         oldValue = aval.getOptionIdAsString();
275                     }
276                     else
277                     {
278                         newValue = group.get("Value").toString();
279                         oldValue = aval.getValue();
280                     }
281                     // A value has been entered for the attribute.
282
// The old value is different from the new, or is unset:
283
// Set new value.
284
if (newValue.length() > 0
285                          && ((oldValue == null) ||
286                             (oldValue != null && !oldValue.trim().equals(newValue.trim()))))
287                     {
288                         group.setProperties(aval2);
289                         newAttVals.put(aval.getAttributeId(), aval2);
290                         modifiedAttribute = true;
291                     }
292                     // The attribute is being undefined.
293
else if (oldValue != null && newValue.length() == 0 &&
294                              oldValue.length() != 0)
295                     {
296                         aval2.setValue(null);
297                         newAttVals.put(aval.getAttributeId(), aval2);
298                         modifiedAttribute = true;
299                     }
300                 }
301             }
302             if (!modifiedAttribute)
303             {
304                 scarabR.setAlertMessage(L10NKeySet.MustModifyAttribute);
305                 return;
306             }
307             Attachment attachment = AttachmentManager.getInstance();
308             reasonGroup.setProperties(attachment);
309             try
310             {
311                 DateAttribute.convertDateAttributes(newAttVals.values(), getLocalizationTool(context).get("ShortDatePattern"));
312                 ActivitySet activitySet = issue.setAttributeValues(null,
313                                                 newAttVals, attachment, user);
314                 intake.removeAll();
315                 scarabR.setConfirmMessage(L10NKeySet.ChangesSaved);
316                 sendEmail(activitySet, issue, DEFAULT_MSG, context);
317             }
318             catch (Exception JavaDoc se)
319             {
320                 scarabR.setAlertMessage(l10n.getMessage(se));
321             }
322         }
323         else
324         {
325             scarabR.setAlertMessage(ERROR_MESSAGE);
326         }
327     }
328     
329     /**
330      * Modifies attachments of type "url".
331      */

332     public void doSaveurl (RunData data, TemplateContext context)
333         throws Exception JavaDoc
334     {
335         if (isCollision(data, context))
336         {
337             return;
338         }
339         
340         ScarabRequestTool scarabR = getScarabRequestTool(context);
341         ScarabLocalizationTool l10n = getLocalizationTool(context);
342         Issue issue = scarabR.getIssue();
343         if (issue == null)
344         {
345             // no need to set the message here as
346
// it is done in scarabR.getIssue()
347
return;
348         }
349
350         IntakeTool intake = getIntakeTool(context);
351         ScarabUser user = (ScarabUser)data.getUser();
352
353         List JavaDoc urls = issue.getUrls();
354         ActivitySet activitySet = null;
355         for (int i = 0; i<urls.size(); i++)
356         {
357             Attachment attachment = (Attachment)urls.get(i);
358             if (attachment.getTypeId().equals(Attachment.URL__PK)
359                 && !attachment.getDeleted())
360             {
361                 Group group = intake.get("Attachment", attachment.getQueryKey(), false);
362
363                 Field nameField = group.get("Name");
364                 Field dataField = group.get("Data");
365                 if (dataField.isValid())
366                 {
367                     dataField.setRequired(true);
368                 }
369                 
370                 if (intake.isAllValid())
371                 {
372                     // store the new and old data
373
String JavaDoc oldDescription = attachment.getName();
374                     String JavaDoc oldURL = new String JavaDoc(attachment.getData());
375                     String JavaDoc newDescription = nameField.toString();
376                     String JavaDoc newURL = dataField.toString();
377
378                     if (!oldDescription.equals(newDescription))
379                     {
380                         group.setProperties(attachment);
381                         attachment.save();
382                         activitySet = issue
383                             .doChangeUrlDescription(activitySet, user,
384                                                     attachment, oldDescription);
385                         scarabR.setConfirmMessage(L10NKeySet.UrlSaved);
386                     }
387                     if (!oldURL.equals(newURL))
388                     {
389                         group.setProperties(attachment);
390                         attachment.save();
391                         activitySet = issue
392                             .doChangeUrlUrl(activitySet, user,
393                                             attachment, oldURL);
394                         scarabR.setConfirmMessage(L10NKeySet.UrlSaved);
395                     }
396                 }
397                 else
398                 {
399                      scarabR.setAlertMessage(ERROR_MESSAGE);
400                 }
401             }
402         }
403
404         // if there is a new URL, add it
405
Group newGroup = intake.get("Attachment", "urlKey", false);
406         if (newGroup != null)
407         {
408             Field dataField = newGroup.get("Data");
409             String JavaDoc dataFieldString = dataField.toString();
410             if (dataFieldString != null && dataFieldString.trim().length() > 0)
411             {
412                 // create the new attachment
413
Attachment attachment = AttachmentManager.getInstance();
414                 // set the form data to the attachment object
415
newGroup.setProperties(attachment);
416                 activitySet = issue.addUrl(attachment, user);
417
418                 // remove the group
419
intake.remove(newGroup);
420                 scarabR.setConfirmMessage(L10NKeySet.UrlSaved);
421                 sendEmail(activitySet, issue, L10NKeySet.UrlSaved, context);
422             }
423         }
424     }
425
426     /**
427      * Enable edition mode for the comment page.
428      */

429     public void doEditcommentpage(RunData data, TemplateContext context)
430          throws Exception JavaDoc
431     {
432         if (isCollision(data, context))
433         {
434             return;
435         }
436         ScarabUser user = (ScarabUser)data.getUser();
437         ScarabRequestTool scarabR = getScarabRequestTool(context);
438         ScarabLocalizationTool l10n = getLocalizationTool(context);
439         Issue issue = scarabR.getIssue();
440         if (issue == null)
441         {
442             // no need to set the message here as
443
// it is done in scarabR.getIssue()
444
return;
445         }
446         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
447                                issue.getModule()))
448         {
449             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
450             return;
451         }
452         data.getParameters().add("edit_comments", "true");
453         data.getParameters().add("fullcomments", data.getParameters().get("fullcomments"));
454         return;
455     }
456
457     /**
458      * Adds an attachment of type "comment".
459      */

460     public void doSubmitcomment (RunData data, TemplateContext context)
461          throws Exception JavaDoc
462     {
463         ScarabRequestTool scarabR = getScarabRequestTool(context);
464         ScarabLocalizationTool l10n = getLocalizationTool(context);
465         Issue issue = scarabR.getIssue();
466         if (issue == null)
467         {
468             // no need to set the message here as
469
// it is done in scarabR.getIssue()
470
return;
471         }
472         ScarabUser user = (ScarabUser)data.getUser();
473         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
474                                issue.getModule()))
475         {
476             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
477             return;
478         }
479
480         IntakeTool intake = getIntakeTool(context);
481         Group group = intake.get("Attachment", "commentKey", false);
482         if (group != null)
483         {
484             Attachment attachment = AttachmentManager.getInstance();
485             try
486             {
487                 group.setProperties(attachment);
488             }
489             catch (Exception JavaDoc e)
490             {
491                 scarabR.setAlertMessage(ERROR_MESSAGE);
492                 return;
493             }
494             
495             try
496             {
497                 issue.addComment(attachment, (ScarabUser)data.getUser());
498             }
499             catch(Exception JavaDoc e)
500             {
501                 String JavaDoc l10nMessage = l10n.getMessage(e);
502                 scarabR.setAlertMessage(l10nMessage);
503                 return;
504             }
505             scarabR.setConfirmMessage(L10NKeySet.CommentSaved);
506             intake.remove(group);
507         }
508         else
509         {
510             scarabR.setAlertMessage(ERROR_MESSAGE);
511         }
512     }
513
514     /**
515      * Add an attachment of type "file"
516      */

517     public void doSubmitfile (RunData data, TemplateContext context)
518         throws Exception JavaDoc
519     {
520         ScarabRequestTool scarabR = getScarabRequestTool(context);
521         ScarabLocalizationTool l10n = getLocalizationTool(context);
522         Issue issue = scarabR.getIssue();
523         if (issue == null)
524         {
525             // no need to set the message here as
526
// it is done in scarabR.getIssue()
527
return;
528         }
529         ScarabUser user = (ScarabUser)data.getUser();
530         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
531                                issue.getModule()))
532         {
533             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
534             return;
535         }
536
537         IntakeTool intake = getIntakeTool(context);
538         Group group = intake.get("Attachment", "fileKey" + issue.getQueryKey(), false);
539         Field nameField = group.get("Name");
540         // set some required fields
541
if (nameField.isValid())
542         {
543             nameField.setRequired(true);
544         }
545         // validate intake
546
if (intake.isAllValid() && group != null)
547         {
548             // adding a file is a special process
549
addFileAttachment(issue, group, (Attachment) null, scarabR, data,
550                               intake);
551             ActivitySet activitySet = issue.doSaveFileAttachments(user);
552             if (activitySet != null)
553             {
554                 scarabR.setConfirmMessage(L10NKeySet.FileSaved);
555                 sendEmail(activitySet, issue, L10NKeySet.FileSaved, context);
556             }
557             else
558             {
559                 scarabR.setAlertMessage(ERROR_MESSAGE);
560             }
561         }
562         else
563         {
564             scarabR.setAlertMessage(ERROR_MESSAGE);
565         }
566     }
567
568     /**
569      * Adds a file attachment to an issue.
570      *
571      * @param issue The issue to add an attachment to.
572      * @param group Intake group.
573      * @param attachment The attachment to add, or <code>null</code>
574      * to use a new blank one.
575      * @param scarabR Request tool.
576      * @param data Contextual data.
577      * @param intake Intake tool.
578      */

579     static void addFileAttachment(Issue issue, Group group,
580                                   Attachment attachment,
581                                   ScarabRequestTool scarabR, RunData data,
582                                   IntakeTool intake)
583         throws Exception JavaDoc
584     {
585         ScarabLocalizationTool l10n = (ScarabLocalizationTool)
586             getTemplateContext(data).get(ScarabConstants.LOCALIZATION_TOOL);
587         if (group != null)
588         {
589             Field nameField = group.get("Name");
590             Field fileField = group.get("File");
591             nameField.setRequired(true);
592             fileField.setRequired(true);
593             Field mimeAField = group.get("MimeTypeA");
594             Field mimeBField = group.get("MimeTypeB");
595             String JavaDoc mimeA = mimeAField.toString();
596             String JavaDoc mimeB = mimeBField.toString();
597             String JavaDoc mimeType = null;
598             if (mimeB != null && mimeB.trim().length() > 0)
599             {
600                 mimeType = mimeB;
601             }
602             else if ("autodetect".equals(mimeA) && fileField.isValid())
603             {
604                 try
605                 {
606                     String JavaDoc filename =
607                         ((FileItem)fileField.getValue()).getName();
608                     String JavaDoc contentType =
609                         ComponentLocator.getMimeTypeService().getContentType(filename, null);
610                     if (contentType == null)
611                     {
612                         // could not match extension.
613
mimeAField
614                             .setMessage("intake_CouldNotDetermineMimeType");
615                     }
616                     else
617                     {
618                         mimeType = contentType;
619                     }
620                 }
621                 catch (Exception JavaDoc e)
622                 {
623                     // we do not want any exception thrown here to affect
624
// the user experience, it is just considered a
625
// non-detectable file type. But still the exception is
626
// not expected, so log it.
627
mimeAField.setMessage("intake_CouldNotDetermineMimeType");
628                     Log.get().info(
629                         "Could not determine mimetype of uploaded file.", e);
630                 }
631             }
632             else
633             {
634                 mimeAField.setRequired(true);
635                 mimeType = mimeA;
636             }
637             if (group.isAllValid())
638             {
639                 if (attachment == null)
640                 {
641                     attachment = AttachmentManager.getInstance();
642                 }
643                 group.setProperties(attachment);
644                 attachment.setMimeType(mimeType);
645                 issue.addFile(attachment, (ScarabUser)data.getUser());
646                 // remove the group so that the form data doesn't show up again
647
intake.remove(group);
648             }
649             else
650             {
651                 scarabR.setAlertMessage(ERROR_MESSAGE);
652             }
653         }
654         else
655         {
656             scarabR.setAlertMessage(L10NKeySet.CouldNotLocateAttachmentGroup);
657         }
658     }
659
660     /**
661      * Eventually, this should be moved somewhere else once we can figure
662      * out how to separate email out of the request context scope.
663      */

664     private void sendEmail(ActivitySet activitySet, Issue issue, LocalizationKey msg,
665                            TemplateContext context)
666         throws Exception JavaDoc
667     {
668         try
669         {
670             activitySet.sendEmail(issue);
671         }
672         catch (Exception JavaDoc e)
673         {
674             L10NMessage l10nMessage = new L10NMessage(EMAIL_ERROR2,msg,e);
675             getScarabRequestTool(context).setConfirmMessage(l10nMessage);
676         }
677     }
678
679     /**
680      * Edits a comment.
681      */

682     public void doEditcomment (RunData data, TemplateContext context)
683         throws Exception JavaDoc
684     {
685         if (isCollision(data, context))
686         {
687             return;
688         }
689         
690         ScarabUser user = (ScarabUser)data.getUser();
691         ScarabRequestTool scarabR = getScarabRequestTool(context);
692         ScarabLocalizationTool l10n = getLocalizationTool(context);
693         Issue issue = scarabR.getIssue();
694         if (issue == null)
695         {
696             // no need to set the message here as
697
// it is done in scarabR.getIssue()
698
return;
699         }
700
701         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
702                                issue.getModule()))
703         {
704             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
705             return;
706         }
707
708         ParameterParser params = data.getParameters();
709         Object JavaDoc[] keys = params.getKeys();
710         ActivitySet activitySet = null;
711         for (int i=0; i<keys.length; i++)
712         {
713             String JavaDoc key = (String JavaDoc) keys[i];
714             if (key.startsWith("edit_comment_"))
715             {
716                 String JavaDoc attachmentId = key.substring(13);
717                 String JavaDoc newComment = params.getString(key,"");
718                 Attachment attachment = AttachmentManager
719                     .getInstance(new NumberKey(attachmentId), false);
720                 try
721                 {
722                     activitySet = issue.doEditComment(activitySet, newComment,
723                                                       attachment, user);
724                 }
725                 catch (ScarabException se)
726                 {
727                     scarabR.setAlertMessage(l10n.getMessage(se));
728                 }
729             }
730         }
731         if (activitySet != null)
732         {
733             scarabR.setConfirmMessage(DEFAULT_MSG);
734         }
735         else
736         {
737             scarabR.setInfoMessage(L10NKeySet.NoCommentsChanged);
738         }
739     }
740
741    /**
742     * Deletes a url.
743     */

744    public void doDeleteurl (RunData data, TemplateContext context)
745         throws Exception JavaDoc
746     {
747         if (isCollision(data, context))
748         {
749             return;
750         }
751         
752         ScarabRequestTool scarabR = getScarabRequestTool(context);
753         ScarabLocalizationTool l10n = getLocalizationTool(context);
754         Issue issue = scarabR.getIssue();
755         if (issue == null)
756         {
757             // no need to set the message here as
758
// it is done in scarabR.getIssue()
759
return;
760         }
761
762         ScarabUser user = (ScarabUser)data.getUser();
763         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
764                                issue.getModule()))
765         {
766             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
767             return;
768         }
769
770         ParameterParser params = data.getParameters();
771         Object JavaDoc[] keys = params.getKeys();
772         ActivitySet activitySet = null;
773         for (int i=0; i < keys.length; i++)
774         {
775             String JavaDoc key = (String JavaDoc) keys[i];
776             if (key.startsWith("url_delete_"))
777             {
778                 String JavaDoc attachmentId = key.substring(11);
779                 Attachment attachment = AttachmentManager
780                     .getInstance(new NumberKey(attachmentId), false);
781                 activitySet = issue.doDeleteUrl(activitySet, attachment, user);
782             }
783         }
784         if (activitySet != null)
785         {
786             scarabR.setConfirmMessage(DEFAULT_MSG);
787             sendEmail(activitySet, issue, L10NKeySet.UrlDeleted,
788                       context);
789         }
790         else
791         {
792             scarabR.setInfoMessage(L10NKeySet.NoUrlsChanged);
793         }
794     }
795     
796     /**
797      * Deletes a file.
798      */

799     public void doDeletefile (RunData data, TemplateContext context)
800         throws Exception JavaDoc
801     {
802         if (isCollision(data, context))
803         {
804             return;
805         }
806         
807         ScarabRequestTool scarabR = getScarabRequestTool(context);
808         ScarabLocalizationTool l10n = getLocalizationTool(context);
809         Issue issue = scarabR.getIssue();
810         if (issue == null)
811         {
812             // no need to set the message here as
813
// it is done in scarabR.getIssue()
814
return;
815         }
816
817         ScarabUser user = (ScarabUser)data.getUser();
818         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
819                                issue.getModule()))
820         {
821             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
822             return;
823         }
824
825         ParameterParser params = data.getParameters();
826         Object JavaDoc[] keys = params.getKeys();
827         ActivitySet activitySet = null;
828         String JavaDoc attachmentFullPath = new String JavaDoc();
829
830         boolean allFilesDeleted = true;
831
832         boolean deletePhysically = Turbine.getConfiguration()
833         .getBoolean("scarab.attachment.remove.permanent",false);
834
835         for (int i = 0; i < keys.length; i++)
836         {
837             String JavaDoc key = (String JavaDoc) keys[i];
838             if (key.startsWith("file_delete_"))
839             {
840                 String JavaDoc attachmentId = key.substring(12);
841                 Attachment attachment = AttachmentManager.getInstance(
842                 new NumberKey(attachmentId), false);
843                 MutableBoolean physicallyDeleted = new MutableBoolean(false);
844                 activitySet = issue.doRemoveAttachment(activitySet, physicallyDeleted, attachment, user);
845                 //set deleted to false if at least for one of the
846
//deleted attachmnents the file was not removed from
847
//disk.
848
if (deletePhysically && !physicallyDeleted.booleanValue())
849                 {
850                     allFilesDeleted = false;
851                 }
852                 attachmentFullPath = attachment.getFullPath();
853             }
854         }
855
856         if (activitySet != null)
857         {
858             if (allFilesDeleted)
859             {
860                 scarabR.setConfirmMessage(DEFAULT_MSG);
861             }
862             else
863             {
864                 scarabR.setAlertMessage(L10NKeySet.FilesPartiallyDeleted);
865             }
866             sendEmail(activitySet, issue, L10NKeySet.FileDeleted, context);
867
868         }
869         else
870         {
871             scarabR.setInfoMessage(L10NKeySet.NoFilesChanged);
872         }
873     }
874
875     /**
876      * Modifies the dependency type between the current issue
877      * And its parent or child issue.
878      */

879     public void doDeletedependencies(RunData data, TemplateContext context)
880         throws Exception JavaDoc
881     {
882         saveDependencyChanges(data, context, true);
883     }
884
885     /**
886      * Modifies the dependency type between the current issue
887      * And its parent or child issue.
888      */

889     public void doSavedependencychanges(RunData data, TemplateContext context)
890         throws Exception JavaDoc
891     {
892         saveDependencyChanges(data, context, false);
893     }
894
895     /**
896      * Modifies the dependency type between the current issue
897      * And its parent or child issue.
898      */

899     private void saveDependencyChanges(RunData data, TemplateContext context,
900                                        boolean doDelete)
901         throws Exception JavaDoc
902     {
903         if (isCollision(data, context))
904         {
905             return;
906         }
907
908         ScarabRequestTool scarabR = getScarabRequestTool(context);
909         ScarabLocalizationTool l10n = getLocalizationTool(context);
910         Issue issue = scarabR.getIssue();
911         if (issue == null)
912         {
913             // no need to set the message here as
914
// it is done in scarabR.getIssue()
915
return;
916         }
917
918         ScarabUser user = (ScarabUser)data.getUser();
919         if (!user.hasPermission(ScarabSecurity.ISSUE__EDIT,
920                                issue.getModule()))
921         {
922             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
923             return;
924         }
925
926         IntakeTool intake = getIntakeTool(context);
927         Group group = intake.get("Depend","newDep"+issue.getQueryKey(),false);
928         String JavaDoc reasonForChange = group.get("Description").toString();
929
930         boolean depAdded = doAdddependency(issue, intake, group, scarabR,
931                                            context, l10n, user);
932         boolean changesMade = doUpdatedependencies(issue, intake, scarabR,
933                                                    context, l10n, user,
934                                                    reasonForChange, doDelete);
935         if (!depAdded)
936         {
937             scarabR.setAlertMessage(ERROR_MESSAGE);
938         }
939         if (!depAdded && !changesMade)
940         {
941             scarabR.setInfoMessage(NO_CHANGES_MADE);
942         }
943         else
944         {
945             intake.remove(group);
946         }
947     }
948
949     /**
950      * Modifies the dependency type between the current issue
951      * And its parent or child issue.
952      */

953     private boolean doAdddependency(Issue issue, IntakeTool intake,
954                                  Group group, ScarabRequestTool scarabR,
955                                  TemplateContext context,
956                                  ScarabLocalizationTool l10n,
957                                  ScarabUser user)
958         throws Exception JavaDoc
959     {
960         // Check that dependency type entered is valid
961
Field type = group.get("TypeId");
962         type.setRequired(true);
963         // Check that child ID entered is valid
964
Field childId = group.get("ObserverUniqueId");
965         childId.setRequired(true);
966         if (!type.isValid() && childId.isValid())
967         {
968             type.setMessage(l10n.get(L10NKeySet.EnterValidDependencyType));
969             return false;
970         }
971         else if (type.isValid() && !childId.isValid())
972         {
973             childId.setMessage(l10n.get(L10NKeySet.EnterValidIssueId));
974             return false;
975         }
976         String JavaDoc childIdStr = childId.toString();
977         // we need to struggle here because if there is no
978
// issue id, we just want to return because the person
979
// on the page could just be updating existing deps
980
// and in this case, the issue id might be empty.
981
if (childIdStr != null)
982         {
983             childIdStr.trim();
984         }
985         if (childIdStr == null || childIdStr.length() == 0)
986         {
987             return true;
988         }
989         // Check that child ID entered corresponds to a valid issue
990
// The id might not have the prefix appended so use the current
991
// module prefix as the thing to try.
992
Issue childIssue = null;
993         Module currentModule = scarabR.getCurrentModule();
994         try
995         {
996             childIssue = IssueManager
997                 .getIssueById(childIdStr, currentModule.getCode());
998         }
999         catch(Exception JavaDoc e)
1000        {
1001            // Ignore this
1002
}
1003        if (childIssue == null || childIssue.getDeleted())
1004        {
1005            childId.setMessage(l10n.get(L10NKeySet.EnterValidIssueId));
1006            return false;
1007        }
1008        // Make sure issue is not being marked as dependant on itself.
1009
else if (childIssue.equals(issue))
1010        {
1011            childId.setMessage(l10n.get(L10NKeySet.CannotAddSelfDependency));
1012            return false;
1013        }
1014        if (intake.isAllValid())
1015        {
1016            Depend depend = DependManager.getInstance();
1017            depend.setDefaultModule(currentModule);
1018            group.setProperties(depend);
1019            ActivitySet activitySet = null;
1020            try
1021            {
1022                activitySet = issue
1023                    .doAddDependency(activitySet, depend, childIssue, user);
1024            }
1025            catch (ScarabException se)
1026            {
1027                childId.setMessage(se.getL10nMessage().getMessage(l10n));
1028                return false;
1029            }
1030            catch (Exception JavaDoc e)
1031            {
1032                log().debug("Delete error: ", e);
1033                return false;
1034            }
1035
1036            scarabR.setConfirmMessage(DEFAULT_MSG);
1037            if (activitySet != null)
1038            {
1039                // FIXME: I think that we are sending too many emails here
1040
sendEmail(activitySet, childIssue, DEFAULT_MSG,
1041                          context);
1042                sendEmail(activitySet, issue, DEFAULT_MSG,
1043                          context);
1044            }
1045            return true;
1046        }
1047        else
1048        {
1049            return false;
1050        }
1051    }
1052
1053    /**
1054     * Modifies the dependency type between the current issue
1055     * And its parent or child issue.
1056     */

1057    private boolean doUpdatedependencies(Issue issue, IntakeTool intake,
1058                                       ScarabRequestTool scarabR,
1059                                       TemplateContext context,
1060                                       ScarabLocalizationTool l10n,
1061                                       ScarabUser user,
1062                                       String JavaDoc reasonForChange,
1063                                       boolean doDelete)
1064        throws Exception JavaDoc
1065    {
1066        ActivitySet activitySet = null;
1067        List JavaDoc dependencies = issue.getAllDependencies();
1068        for (int i=0; i < dependencies.size(); i++)
1069        {
1070            Depend oldDepend = (Depend)dependencies.get(i);
1071            Depend newDepend = DependManager.getInstance();
1072            // copy oldDepend properties to newDepend
1073
newDepend.setProperties(oldDepend);
1074            Group group = intake.get("Depend", oldDepend.getQueryKey(), false);
1075            // there is nothing to doo here, so move along now kiddies.
1076
if (group == null)
1077            {
1078                continue;
1079            }
1080
1081            DependType oldDependType = oldDepend.getDependType();
1082            // set properties on the object
1083
group.setProperties(newDepend);
1084            DependType newDependType = newDepend.getDependType();
1085
1086            // set the description of the changes
1087
newDepend.setDescription(reasonForChange);
1088
1089            // make the changes
1090
if (doDelete && newDepend.getDeleted())
1091            {
1092                try
1093                {
1094                    activitySet =
1095                        issue.doDeleteDependency(activitySet, oldDepend, user);
1096                }
1097                catch (ScarabException se)
1098                {
1099                    // it will error out if they attempt to delete
1100
// a dep via a child dep.
1101
String JavaDoc l10nKey = se.getMessage();
1102                    scarabR.setAlertMessage(l10n.get(l10nKey));
1103                }
1104                catch (Exception JavaDoc e)
1105                {
1106                    scarabR.setAlertMessage(ERROR_MESSAGE);
1107                    log().debug("Delete error: ", e);
1108                }
1109            }
1110            else if (! oldDependType.equals(newDependType))
1111            {
1112                // need to do this because newDepend could have the deleted
1113
// flag set to true if someone selected it as well as
1114
// clicked the save changes button. this is why we have the
1115
// doDeleted flag as well...issue.doChange will only do the
1116
// change if the deleted flag is false...so force it...
1117
newDepend.setDeleted(false);
1118                // make the changes
1119
activitySet =
1120                    issue.doChangeDependencyType(activitySet, oldDepend,
1121                                                 newDepend, user);
1122            }
1123            intake.remove(group);
1124        }
1125
1126        // something changed...
1127
if (activitySet != null)
1128        {
1129            scarabR.setConfirmMessage(DEFAULT_MSG);
1130            
1131            // FIXME: when we add a dep, we send email to both issues,
1132
// but here we are not...should we? it almost seems like
1133
// to much email. We need someone to define this behavior
1134
// better. (JSS)
1135
sendEmail(activitySet, issue, DEFAULT_MSG, context);
1136            return true;
1137        }
1138        else // nothing changed
1139
{
1140            return false;
1141        }
1142    }
1143
1144    /**
1145     * Redirects to AssignIssue page.
1146     */

1147    public void doEditassignees(RunData data, TemplateContext context)
1148         throws Exception JavaDoc
1149    {
1150        IntakeTool intake = getIntakeTool(context);
1151        intake.removeAll();
1152        ScarabRequestTool scarabR = getScarabRequestTool(context);
1153        ScarabLocalizationTool l10n = getLocalizationTool(context);
1154        Issue issue = scarabR.getIssue();
1155        if (issue == null)
1156        {
1157            // no need to set the message here as
1158
// it is done in scarabR.getIssue()
1159
return;
1160        }
1161        ScarabUser user = (ScarabUser)data.getUser();
1162        if (user.hasPermission(ScarabSecurity.ISSUE__ASSIGN,
1163                               issue.getModule()))
1164        {
1165            data.getParameters().add("id", issue.getUniqueId());
1166            data.getParameters().add("issue_ids", issue.getUniqueId());
1167            scarabR.resetAssociatedUsers();
1168            setTarget(data, "AssignIssue.vm");
1169        }
1170        else
1171        {
1172            scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
1173        }
1174    }
1175
1176
1177
1178    /**
1179     * Redirects to MoveIssue page with move action selected.
1180     */

1181    public void doMove(RunData data, TemplateContext context)
1182         throws Exception JavaDoc
1183    {
1184        boolean collisionOccurred = isCollision(data, context);
1185        context.put("collisionDetectedOnMoveAttempt", collisionOccurred ? Boolean.TRUE : Boolean.FALSE);
1186        if (collisionOccurred)
1187        {
1188            // Report the collision to the user.
1189
return;
1190        }
1191        ScarabRequestTool scarabR = getScarabRequestTool(context);
1192        ScarabLocalizationTool l10n = getLocalizationTool(context);
1193        Module module = scarabR.getCurrentModule();
1194        List JavaDoc moveToModules =((ScarabUser)data.getUser()).getCopyToModules(module, "move");
1195        if (moveToModules.size() > 0)
1196        {
1197            ParameterParser pp = data.getParameters();
1198            pp.setString("mv_0rb", "move");
1199            ((IntakeTool)context.get("intake")).get("MoveIssue")
1200                .getDefault().get("Action").init(pp);
1201            String JavaDoc[] issueIds = pp.getStrings("issue_ids");
1202            String JavaDoc currentIssueId = getScarabRequestTool(context).getIssue().getUniqueId();
1203            if (!ScarabUtil.contains(issueIds, currentIssueId))
1204            {
1205                pp.add("issue_ids", currentIssueId);
1206            }
1207            setTarget(data, "MoveIssue.vm");
1208        }
1209        else
1210        {
1211            scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
1212            setTarget(data, "ViewIssue.vm");
1213        }
1214    }
1215
1216    /**
1217     * Redirects to MoveIssue page with copy action selected.
1218     */

1219    public void doCopy(RunData data, TemplateContext context)
1220         throws Exception JavaDoc
1221    {
1222        boolean collisionOccurred = isCollision(data, context);
1223        context.put("collisionDetectedOnMoveAttempt", collisionOccurred ? Boolean.TRUE : Boolean.FALSE);
1224        if (collisionOccurred)
1225        {
1226            // Report the collision to the user.
1227
return;
1228        }
1229        ParameterParser pp = data.getParameters();
1230        pp.setString("mv_0rb", "copy");
1231        ((IntakeTool)context.get("intake")).get("MoveIssue")
1232            .getDefault().get("Action").init(pp);
1233        String JavaDoc[] issueIds = pp.getStrings("issue_ids");
1234        String JavaDoc currentIssueId = getScarabRequestTool(context).getIssue().getUniqueId();
1235        if (!ScarabUtil.contains(issueIds, currentIssueId))
1236        {
1237            pp.add("issue_ids", currentIssueId);
1238        }
1239        setTarget(data, "MoveIssue.vm");
1240    }
1241
1242    /**
1243     * does not actually modify an issue, but sets the preferred view
1244     * of an issue for the current session
1245     */

1246    public void doSetissueview(RunData data, TemplateContext context)
1247         throws Exception JavaDoc
1248    {
1249        String JavaDoc tab = data.getParameters().getString("tab",
1250                                          ScarabConstants.ISSUE_VIEW_ALL);
1251        data.getUser().setTemp(ScarabConstants.TAB_KEY, tab);
1252    }
1253    
1254    /**
1255     * Helper method to retrieve the ScarabGlobalTool from the Context
1256     */

1257    private ScarabGlobalTool getGlobalTool(RunData data)
1258    {
1259        return (ScarabGlobalTool)org.apache.turbine.modules.Module
1260            .getTemplateContext(data).get(ScarabConstants.SCARAB_GLOBAL_TOOL);
1261    }
1262}
1263
Popular Tags