KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > tigris > scarab > tools > ScarabRequestTool


1 package org.tigris.scarab.tools;
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.text.DateFormat JavaDoc;
50 import java.util.ArrayList JavaDoc;
51 import java.util.Arrays JavaDoc;
52 import java.util.Calendar JavaDoc;
53 import java.util.Collections JavaDoc;
54 import java.util.Comparator JavaDoc;
55 import java.util.HashMap JavaDoc;
56 import java.util.Hashtable JavaDoc;
57 import java.util.Iterator JavaDoc;
58 import java.util.List JavaDoc;
59 import java.util.Locale JavaDoc;
60 import java.util.Map JavaDoc;
61 import java.util.TimeZone JavaDoc;
62
63 import org.apache.commons.collections.map.LinkedMap;
64 import org.apache.commons.lang.StringUtils;
65 import org.apache.fulcrum.intake.Intake;
66 import org.apache.fulcrum.intake.model.Field;
67 import org.apache.fulcrum.intake.model.Group;
68 import org.apache.fulcrum.localization.Localization;
69 import org.apache.fulcrum.parser.ParameterParser;
70 import org.apache.fulcrum.parser.StringValueParser;
71 import org.apache.fulcrum.pool.Recyclable;
72 import org.apache.torque.TorqueException;
73 import org.apache.torque.om.ComboKey;
74 import org.apache.torque.om.NumberKey;
75 import org.apache.torque.om.SimpleKey;
76 import org.apache.torque.util.Criteria;
77 import org.apache.turbine.RunData;
78 import org.apache.turbine.TemplateContext;
79 import org.apache.turbine.Turbine;
80 import org.apache.turbine.services.pull.ApplicationTool;
81 import org.apache.turbine.tool.IntakeTool;
82 import org.tigris.scarab.attribute.DateAttribute;
83 import org.tigris.scarab.om.Activity;
84 import org.tigris.scarab.om.ActivitySet;
85 import org.tigris.scarab.om.Attachment;
86 import org.tigris.scarab.om.AttachmentManager;
87 import org.tigris.scarab.om.Attribute;
88 import org.tigris.scarab.om.AttributeGroup;
89 import org.tigris.scarab.om.AttributeGroupManager;
90 import org.tigris.scarab.om.AttributeManager;
91 import org.tigris.scarab.om.AttributeOption;
92 import org.tigris.scarab.om.AttributeOptionManager;
93 import org.tigris.scarab.om.AttributeOptionPeer;
94 import org.tigris.scarab.om.AttributePeer;
95 import org.tigris.scarab.om.AttributeValue;
96 import org.tigris.scarab.om.Depend;
97 import org.tigris.scarab.om.DependManager;
98 import org.tigris.scarab.om.FrequencyPeer;
99 import org.tigris.scarab.om.Issue;
100 import org.tigris.scarab.om.IssueManager;
101 import org.tigris.scarab.om.IssueTemplateInfo;
102 import org.tigris.scarab.om.IssueTemplateInfoManager;
103 import org.tigris.scarab.om.IssueTemplateInfoPeer;
104 import org.tigris.scarab.om.IssueType;
105 import org.tigris.scarab.om.IssueTypeManager;
106 import org.tigris.scarab.om.MITList;
107 import org.tigris.scarab.om.MITListManager;
108 import org.tigris.scarab.om.Module;
109 import org.tigris.scarab.om.ModuleManager;
110 import org.tigris.scarab.om.ParentChildAttributeOption;
111 import org.tigris.scarab.om.Query;
112 import org.tigris.scarab.om.QueryManager;
113 import org.tigris.scarab.om.QueryPeer;
114 import org.tigris.scarab.om.RModuleAttribute;
115 import org.tigris.scarab.om.RModuleAttributeManager;
116 import org.tigris.scarab.om.RModuleIssueType;
117 import org.tigris.scarab.om.RModuleIssueTypePeer;
118 import org.tigris.scarab.om.ROptionOption;
119 import org.tigris.scarab.om.ReportManager;
120 import org.tigris.scarab.om.ScarabUser;
121 import org.tigris.scarab.om.ScarabUserImplPeer;
122 import org.tigris.scarab.om.ScarabUserManager;
123 import org.tigris.scarab.om.ScopePeer;
124 import org.tigris.scarab.om.Transition;
125 import org.tigris.scarab.om.TransitionPeer;
126 import org.tigris.scarab.reports.ReportBridge;
127 import org.tigris.scarab.services.cache.ScarabCache;
128 import org.tigris.scarab.tools.localization.L10NKeySet;
129 import org.tigris.scarab.tools.localization.L10NMessage;
130 import org.tigris.scarab.tools.localization.Localizable;
131 import org.tigris.scarab.util.AnonymousUserUtil;
132 import org.tigris.scarab.util.IteratorWithSize;
133 import org.tigris.scarab.util.Log;
134 import org.tigris.scarab.util.ScarabConstants;
135 import org.tigris.scarab.util.ScarabException;
136 import org.tigris.scarab.util.ScarabLink;
137 import org.tigris.scarab.util.ScarabPaginatedList;
138 import org.tigris.scarab.util.SimpleSkipFiltering;
139 import org.tigris.scarab.util.SnippetRenderer;
140 import org.tigris.scarab.util.SubsetIteratorWithSize;
141 import org.tigris.scarab.util.WindowIterator;
142 import org.tigris.scarab.util.word.ComplexQueryException;
143 import org.tigris.scarab.util.word.IssueSearch;
144 import org.tigris.scarab.util.word.IssueSearchFactory;
145 import org.tigris.scarab.util.word.MaxConcurrentSearchException;
146 import org.tigris.scarab.util.word.QueryResult;
147 import org.tigris.scarab.util.word.SearchIndex;
148
149 /**
150  * This class is used by the Scarab API
151  */

152 public class ScarabRequestTool
153     implements ApplicationTool,Recyclable
154 {
155     private static final String JavaDoc TIME_ZONE =
156         Turbine.getConfiguration().getString("scarab.timezone", "");
157
158     /**
159      * The disposed flag.
160      */

161     private boolean disposed;
162     
163     /** the object containing request specific data */
164     private RunData data;
165
166     /**
167      * A User object for use within the Scarab API.
168      */

169     private ScarabUser user = null;
170
171     /**
172      * A Issue object for use within the Scarab API.
173      */

174     private Issue issue = null;
175
176     /**
177      * The <code>Alert!</code> message for this request.
178      */

179     private Object JavaDoc alert = null;
180
181     /**
182      * A Attribute object for use within the Scarab API.
183      */

184     private Attribute attribute = null;
185
186     /**
187      * A Attachment object for use within the Scarab API.
188      */

189     private Attachment attachment = null;
190
191     /**
192      * A Depend object for use within the Scarab API.
193      */

194     private Depend depend = null;
195
196     /**
197      * A Query object for use within the Scarab API.
198      */

199     private Query query = null;
200
201     /**
202      * An IssueTemplateInfo object for use within the Scarab API.
203      */

204     private IssueTemplateInfo templateInfo = null;
205
206     /**
207      * An IssueType object for use within the Scarab API.
208      */

209     private IssueType issueType = null;
210
211     /**
212      * An AttributeGroup object
213      */

214     private AttributeGroup group = null;
215
216     /**
217      * The issue that is currently being entered.
218      */

219     private Issue reportingIssue = null;
220
221     /**
222      * A Module object
223      */

224     private Module module = null;
225
226     /**
227      * A AttributeOption object for use within the Scarab API.
228      */

229     private AttributeOption attributeOption = null;
230
231     /**
232      * A ROptionOption
233      */

234     private ROptionOption roo = null;
235
236     /**
237      * A ParentChildAttributeOption
238      */

239     private ParentChildAttributeOption pcao = null;
240
241     /**
242      * IssueSearch object for performing queries
243      */

244     private IssueSearch issueSearch = null;
245     
246     /**
247      * A list of Issues
248      */

249     private List JavaDoc issueList;
250
251     /**
252      * keep track if the columns were reduced to avoid db limits
253      */

254     int initialIssueListColumnsSize = 0;
255     
256     /**
257      * cache list so that we always return the same object for
258      * all invocations within a single request
259      */

260     List JavaDoc issueListColumns = null;
261
262     /**
263      * A ReportGenerator
264      */

265     private ReportBridge reportGenerator = null;
266     
267     private int nbrPages = 0;
268     private int prevPage = 0;
269     private int nextPage = 0;
270     private String JavaDoc cachedNextIssueId;
271     private String JavaDoc cachedPrevIssueId;
272
273     /* messages usually set in actions */
274     private Object JavaDoc confirmMessage;
275     private Object JavaDoc infoMessage;
276     private Object JavaDoc alertMessage;
277
278     /** The time zone that will be used when formatting dates */
279     private final TimeZone JavaDoc timezone;
280     
281     Map JavaDoc attributeTypes = new HashMap JavaDoc();
282     
283     /**
284      * Constructor does initialization stuff
285      */

286     public ScarabRequestTool()
287     {
288         recycle();
289         timezone = TIME_ZONE == null ? null : TimeZone.getTimeZone(TIME_ZONE);
290     }
291
292     /**
293      * This method expects to get a RunData object
294      */

295     public void init(Object JavaDoc data)
296     {
297         this.data = (RunData)data;
298
299     }
300
301     /**
302      * nulls out the issue and user objects
303      */

304     public void refresh()
305     {
306         user = null;
307         issue = null;
308         attribute = null;
309         attachment = null;
310         depend = null;
311         query = null;
312         templateInfo = null;
313         issueType = null;
314         group = null;
315         reportingIssue = null;
316         module = null;
317         attributeOption = null;
318         roo = null;
319         pcao = null;
320         attributeTypes = new HashMap JavaDoc();
321         if (issueSearch != null)
322         {
323             // This must _always_ be called by dispose()
324
Log.get().debug("IssueSearch object is disposed of properly.");
325             issueSearch.close();
326             IssueSearchFactory.INSTANCE.notifyDone();
327             issueSearch = null;
328         }
329         issueList = null;
330         issueListColumns = null;
331         initialIssueListColumnsSize = 0;
332         reportGenerator = null;
333         nbrPages = 0;
334         prevPage = 0;
335         nextPage = 0;
336         confirmMessage = null;
337         infoMessage = null;
338         alertMessage = null;
339         cachedPrevIssueId = null;
340         cachedNextIssueId = null;
341     }
342
343     /**
344      * Sets the <code>Alert!</code> message for this request.
345      *
346      * @param message The alert message to set.
347      */

348     public void setAlert(Object JavaDoc message)
349     {
350         this.alert = message;
351     }
352
353     /**
354      * Retrieves any <code>Alert!</code> message which has been set.
355      *
356      * @return The alert message.
357      */

358     public Object JavaDoc getAlert()
359     {
360         return alert;
361     }
362
363     /**
364      * A Attachment object for use within the Scarab API
365      */

366     public void setAttachment(Attachment attachment)
367     {
368         this.attachment = attachment;
369     }
370
371     /**
372      * A Attribute object for use within the Scarab API.
373      */

374     public void setAttribute (Attribute attribute)
375     {
376         this.attribute = attribute;
377     }
378
379     /**
380      * A Depend object for use within the Scarab API.
381      */

382     public void setDepend (Depend depend)
383     {
384         this.depend = depend;
385     }
386
387     /**
388      * A Query object for use within the Scarab API.
389      */

390     public void setQuery (Query query)
391     {
392         this.query = query;
393     }
394
395     /**
396      * Get the intake tool.
397      */

398     private IntakeTool getIntakeTool()
399     {
400         return (IntakeTool)org.apache.turbine.modules.Module.getTemplateContext(data)
401             .get(ScarabConstants.INTAKE_TOOL);
402     }
403
404     /**
405      * Gets an instance of a ROptionOption from this tool.
406      * if it is null it will return a new instance of an
407      * empty ROptionOption and set it within this tool.
408      */

409     public ROptionOption getROptionOption()
410     {
411         if (roo == null)
412         {
413             roo = ROptionOption.getInstance();
414         }
415         return roo;
416     }
417
418     /**
419      * Sets an instance of a ROptionOption
420      */

421     public void setROptionOption(ROptionOption roo)
422     {
423         this.roo = roo;
424     }
425
426
427     /**
428      * A IssueTemplateInfo object for use within the Scarab API.
429      */

430     public void setIssueTemplateInfo (IssueTemplateInfo templateInfo)
431     {
432         this.templateInfo = templateInfo;
433     }
434
435     /**
436      * A IssueType object for use within the Scarab API.
437      */

438     public void setIssueType (IssueType issuetype)
439     {
440         this.issueType = issuetype;
441     }
442
443
444     /**
445      * Gets an instance of a ParentChildAttributeOption from this tool.
446      * if it is null it will return a new instance of an
447      * empty ParentChildAttributeOption and set it within this tool.
448      */

449     public ParentChildAttributeOption getParentChildAttributeOption()
450     {
451         if (pcao == null)
452         {
453             pcao = ParentChildAttributeOption.getInstance();
454         }
455         return pcao;
456     }
457
458     /**
459      * Sets an instance of a ParentChildAttributeOption
460      */

461     public void setParentChildAttributeOption(ParentChildAttributeOption roo)
462     {
463         this.pcao = roo;
464     }
465
466     /**
467      * A Attribute object for use within the Scarab API.
468      */

469     public void setAttributeOption (AttributeOption option)
470     {
471         this.attributeOption = option;
472     }
473
474     /**
475      * A Attribute object for use within the Scarab API.
476      */

477     public AttributeOption getAttributeOption()
478         throws Exception JavaDoc
479     {
480         if (attributeOption == null)
481         {
482             String JavaDoc optId = getIntakeTool()
483                 .get("AttributeOption", IntakeTool.DEFAULT_KEY)
484                 .get("OptionId").toString();
485             if (optId == null || optId.length() == 0)
486             {
487                 attributeOption = AttributeOption.getInstance();
488             }
489             else
490             {
491                 attributeOption = AttributeOptionManager
492                     .getInstance(new Integer JavaDoc(optId));
493             }
494         }
495         return attributeOption;
496     }
497
498     /**
499      * A <code>User</code> object for use within the Scarab API,
500      * generally <i>not</i> the user who is logged in.
501      */

502     public void setUser(ScarabUser user)
503     {
504         this.user = user;
505     }
506
507     /**
508      * A <code>User</code> object for use within the Scarab API. This
509      * is the result of whatever was set with <code>setUser()</code>
510      * (generally <i>not</i> the user who is logged in). It can
511      * return <code>null</code> if <code>setUser()</code> has not been
512      * previously called. If you would like to get the currently
513      * logged in <code>User</code>, retrieve that from the
514      * data.getUser() method.
515      *
516      * @return A user used during this request.
517      */

518     public ScarabUser getUser()
519     {
520         return this.user;
521     }
522
523     /**
524      * Return a specific User by ID from within the system.
525      * You can pass in either a Integer or something that
526      * will resolve to a String object as id.toString() is
527      * called on everything that isn't a Integer.
528      */

529     public ScarabUser getUser(Object JavaDoc id)
530      throws Exception JavaDoc
531     {
532         if (id == null)
533         {
534             return null;
535         }
536         ScarabUser su = null;
537         try
538         {
539             Integer JavaDoc pk = null;
540             if (id instanceof Integer JavaDoc)
541             {
542                 pk = (Integer JavaDoc) id;
543             }
544             else
545             {
546                 pk = new Integer JavaDoc(id.toString());
547             }
548             su = ScarabUserManager.getInstance(pk);
549         }
550         catch (Exception JavaDoc e)
551         {
552             // Logged at debug level, as a null user is interpreted
553
// as an invalid user id
554
Log.get().debug("User with user id "+ id +" could not be found,", e);
555         }
556         return su;
557     }
558
559     /**
560      * Return a specific User by username.
561      */

562     public ScarabUser getUserByUserName(String JavaDoc username)
563      throws Exception JavaDoc
564     {
565         ScarabUser su = null;
566         try
567         {
568             su = ScarabUserManager
569                 .getInstance(username, getCurrentModule().getScarabInstanceId());
570         }
571         catch (Exception JavaDoc e)
572         {
573             // Logged at debug level, as a null user is interpreted
574
// as an invalid username
575
Log.get().debug("User, "+username+" could not be found,", e);
576         }
577         return su;
578     }
579
580     /**
581      * @return An {@link org.tigris.scarab.om.Attribute} object
582      * (possibly "blank", but never <code>null</code>).
583      */

584     public Attribute getAttribute()
585         throws Exception JavaDoc
586     {
587         try
588         {
589             if (attribute == null)
590             {
591                 String JavaDoc attId = getIntakeTool()
592                     .get("Attribute", IntakeTool.DEFAULT_KEY)
593                     .get("Id").toString();
594                 if (attId == null || attId.length() == 0)
595                 {
596                     attId = data.getParameters().getString("attId");
597                     if (attId == null || attId.length() == 0)
598                     {
599                         attribute = AttributeManager.getInstance();
600                     }
601                     else
602                     {
603                         attribute = AttributeManager.getInstance(new Integer JavaDoc(attId));
604                     }
605                 }
606                 else
607                 {
608                     attribute = AttributeManager.getInstance(new Integer JavaDoc(attId));
609                 }
610             }
611         }
612         catch (Exception JavaDoc e)
613         {
614             e.printStackTrace();
615         }
616         return attribute;
617     }
618
619     /**
620      * A Attribute object for use within the Scarab API.
621      */

622     public Attribute getAttribute(Integer JavaDoc pk)
623      throws Exception JavaDoc
624     {
625         Attribute attr = null;
626         try
627         {
628            attr = AttributeManager.getInstance(pk);
629         }
630         catch (Exception JavaDoc e)
631         {
632             e.printStackTrace();
633         }
634         this.attribute = attr;
635         return attr;
636     }
637
638     /**
639      * A Attribute object for use within the Scarab API.
640      */

641     public AttributeOption getAttributeOption(Integer JavaDoc pk)
642      throws Exception JavaDoc
643     {
644         try
645         {
646            attributeOption = AttributeOptionManager.getInstance(pk);
647         }
648         catch(Exception JavaDoc e)
649         {
650             e.printStackTrace();
651         }
652         return attributeOption;
653     }
654
655     public AttributeOption getAttributeOption(String JavaDoc key)
656          throws Exception JavaDoc
657     {
658         return getAttributeOption(new Integer JavaDoc(key));
659     }
660
661     /**
662      * First attempts to get the RModuleUserAttributes from the user.
663      * If it is empty, then it will try to get the defaults from the module.
664      * If anything fails, it will return an empty list.
665      */

666     public List JavaDoc getRModuleUserAttributes()
667     {
668         ScarabUser user = (ScarabUser)data.getUser();
669         
670         if(issueListColumns == null){
671             ScarabLocalizationTool l10n = getLocalizationTool();
672             ScarabToolManager toolManager = new ScarabToolManager(l10n);
673             issueListColumns= toolManager.getRModuleUserAttributes(user, module, issueType);
674             if (issueListColumns != null)
675                 initialIssueListColumnsSize = issueListColumns.size();
676         }
677         
678         // DEP: Not sure about this initial list stuff, or if we need it..
679
if (initialIssueListColumnsSize > issueListColumns.size())
680         {
681             TemplateContext context =
682                 (TemplateContext) data.getTemp(Turbine.CONTEXT);
683             context.put("columnLimitExceeded", Boolean.TRUE);
684         }
685         return issueListColumns;
686     }
687     
688
689     public List JavaDoc getValidIssueListAttributes()
690     {
691         ScarabUser user = (ScarabUser)data.getUser();
692         List JavaDoc result = null;
693         try
694         {
695             MITList currentList = user.getCurrentMITList();
696             if (currentList != null)
697             {
698                 result = currentList.getCommonAttributes(false);
699             }
700         }
701         catch (Exception JavaDoc e)
702         {
703             Log.get().error("Could not get list attributes", e);
704         }
705         if (result == null)
706         {
707             result = Collections.EMPTY_LIST;
708         }
709         return result;
710     }
711
712     /**
713      * A Query object for use within the Scarab API.
714      */

715     public Query getQuery()
716         throws Exception JavaDoc
717     {
718         try
719         {
720             if (query == null)
721             {
722                 String JavaDoc queryId = data.getParameters()
723                     .getString("queryId");
724                 if (queryId == null || queryId.length() == 0)
725                 {
726                     query = Query.getInstance();
727                 }
728                 else
729                 {
730                     query = QueryManager
731                         .getInstance(new NumberKey(queryId), false);
732                 }
733             }
734         }
735         catch (Exception JavaDoc e)
736         {
737             e.printStackTrace();
738         }
739         return query;
740     }
741
742     /**
743      * A IssueTemplateInfo object for use within the Scarab API.
744      */

745     public IssueTemplateInfo getIssueTemplateInfo()
746         throws Exception JavaDoc
747     {
748         try
749         {
750             if (templateInfo == null)
751             {
752                 String JavaDoc templateId = data.getParameters()
753                     .getString("templateId");
754
755                 if (templateId == null || templateId.length() == 0)
756                 {
757                     templateInfo = IssueTemplateInfo.getInstance();
758                 }
759                 else
760                 {
761                     templateInfo = IssueTemplateInfoManager
762                         .getInstance(new NumberKey(templateId), false);
763                 }
764             }
765         }
766         catch (Exception JavaDoc e)
767         {
768             e.printStackTrace();
769         }
770         return templateInfo;
771     }
772
773     /**
774      * An Enter issue template.
775      */

776     public Issue getIssueTemplate()
777      throws Exception JavaDoc
778     {
779         Issue template = null;
780         String JavaDoc templateId = data.getParameters()
781             .getString("templateId");
782         try
783         {
784             if (templateId == null || templateId.length() == 0)
785             {
786                 template = getCurrentModule().getNewIssue(getIssueType(
787                                    getCurrentIssueType().getTemplateId().toString()));
788             }
789             else
790             {
791                 template = IssueManager
792                     .getInstance(new NumberKey(templateId), false);
793             }
794         }
795         catch (Exception JavaDoc e)
796         {
797             e.printStackTrace();
798         }
799         return template;
800     }
801
802     /**
803      * An Enter issue template.
804      */

805     public Issue getIssueTemplate(String JavaDoc templateId)
806         throws Exception JavaDoc
807     {
808         Issue template = null;
809         try
810         {
811             if (templateId == null || templateId.length() == 0)
812             {
813                 setAlertMessage(L10NKeySet.NoTemplateId);
814             }
815             else
816             {
817                 template = IssueManager
818                     .getInstance(new NumberKey(templateId), false);
819             }
820         }
821         catch (Exception JavaDoc e)
822         {
823             e.printStackTrace();
824         }
825         return template;
826     }
827
828     /**
829      * A Depend object for use within the Scarab API.
830      */

831     public Depend getDepend()
832      throws Exception JavaDoc
833     {
834         try
835         {
836             if (depend == null)
837             {
838                 String JavaDoc dependId = getIntakeTool()
839                     .get("Depend", IntakeTool.DEFAULT_KEY).get("Id").toString();
840                 if (dependId == null || dependId.length() == 0)
841                 {
842                     depend = DependManager.getInstance();
843                 }
844                 else
845                 {
846                     depend = DependManager
847                         .getInstance(new NumberKey(dependId), false);
848                 }
849             }
850         }
851         catch (Exception JavaDoc e)
852         {
853             e.printStackTrace();
854         }
855         return depend;
856     }
857
858     /**
859      * Get reason for modification.
860      */

861     public String JavaDoc getActivityReason(ActivitySet activitySet, Activity activity)
862      throws Exception JavaDoc
863     {
864         ScarabLocalizationTool l10n = getLocalizationTool();
865         ScarabToolManager toolManager = new ScarabToolManager(l10n);
866         return toolManager.getActivityReason(activitySet,activity);
867         
868     }
869             
870         
871     /**
872      * A Attachment object for use within the Scarab API.
873      */

874     public Attachment getAttachment()
875         throws Exception JavaDoc
876     {
877         try
878         {
879             if (attachment == null)
880             {
881                 Group att = getIntakeTool()
882                     .get("Attachment", IntakeTool.DEFAULT_KEY, false);
883                 if (att != null)
884                 {
885                     String JavaDoc attId = att.get("Id").toString();
886                     if (attId == null || attId.length() == 0)
887                     {
888                         attachment = new Attachment();
889                     }
890                     else
891                     {
892                         attachment = AttachmentManager
893                             .getInstance(new NumberKey(attId), false);
894                     }
895                 }
896                 else
897                 {
898                     attachment = new Attachment();
899                 }
900             }
901         }
902         catch(Exception JavaDoc e)
903         {
904         e.printStackTrace(); throw e; //EXCEPTION
905
}
906         return attachment;
907     }
908
909     /**
910      * A AttributeGroup object for use within the Scarab API.
911      */

912     public AttributeGroup getAttributeGroup()
913         throws Exception JavaDoc
914     {
915            AttributeGroup group = null;
916 try
917 {
918             String JavaDoc attGroupId = getIntakeTool()
919                 .get("AttributeGroup", IntakeTool.DEFAULT_KEY)
920                 .get("AttributeGroupId").toString();
921             if (attGroupId == null || attGroupId.length() == 0)
922             {
923                 group = new AttributeGroup();
924             }
925             else
926             {
927                 group = AttributeGroupManager
928                     .getInstance(new NumberKey(attGroupId), false);
929             }
930 }
931 catch(Exception JavaDoc e)
932 {
933 e.printStackTrace();
934 }
935         return group;
936  
937    }
938     /**
939      * Get a AttributeGroup object.
940      */

941     public AttributeGroup getAttributeGroup(String JavaDoc key)
942     {
943         AttributeGroup group = null;
944         try
945         {
946             group = AttributeGroupManager
947                 .getInstance(new NumberKey(key), false);
948         }
949         catch (Exception JavaDoc e)
950         {
951             e.printStackTrace();
952         }
953         return group;
954     }
955
956     /**
957      * Get a specific issue type by key value. Returns null if
958      * the Issue Type could not be found
959      *
960      * @param key a <code>String</code> value
961      * @return a <code>IssueType</code> value
962      */

963     public IssueType getIssueType(String JavaDoc key)
964     {
965         IssueType issueType = null;
966         try
967         {
968             issueType = IssueTypeManager
969                 .getInstance(new NumberKey(key), false);
970         }
971         catch (Exception JavaDoc e)
972         {
973             // Swallow me!
974
}
975         return issueType;
976     }
977
978     /**
979      * Get an issue type object.
980      */

981     public IssueType getIssueType()
982         throws Exception JavaDoc
983     {
984         if (issueType == null)
985         {
986             String JavaDoc key = data.getParameters()
987                 .getString("issuetypeid");
988             if (key == null)
989             {
990                 // get new issue type
991
issueType = new IssueType();
992             }
993             else
994             {
995                 try
996                 {
997                     issueType = IssueTypeManager
998                         .getInstance(new NumberKey(key), false);
999                 }
1000                catch (Exception JavaDoc e)
1001                {
1002                    issueType = new IssueType();
1003                }
1004            }
1005        }
1006        return issueType;
1007    }
1008
1009
1010    /**
1011     * Gets a new instance of AttributeValue
1012     */

1013    public AttributeValue getNewAttributeValue(Attribute attribute, Issue issue)
1014        throws Exception JavaDoc
1015    {
1016        
1017        return AttributeValue.getNewInstance(attribute.getAttributeId(),issue);
1018    }
1019
1020    /**
1021     * Get an RModuleAttribute object.
1022     *
1023     * @return a <code>Module</code> value
1024     */

1025    public RModuleAttribute getRModuleAttribute()
1026        throws Exception JavaDoc
1027    {
1028        RModuleAttribute rma = null;
1029try
1030{
1031            ComboKey rModAttId = (ComboKey)getIntakeTool()
1032                .get("RModuleAttribute", IntakeTool.DEFAULT_KEY)
1033                .get("Id").getValue();
1034            if (rModAttId == null)
1035            {
1036                Integer JavaDoc attId = (Integer JavaDoc)getIntakeTool()
1037                    .get("Attribute", IntakeTool.DEFAULT_KEY)
1038                    .get("Id").getValue();
1039                Module currentModule = getCurrentModule();
1040                if (attId != null && currentModule != null)
1041                {
1042                    SimpleKey[] nka = {
1043                        SimpleKey.keyFor(attId),
1044                        SimpleKey.keyFor(currentModule.getModuleId())
1045                    };
1046                    rma = RModuleAttributeManager
1047                        .getInstance(new ComboKey(nka), false);
1048                }
1049                else
1050                {
1051                    rma = new RModuleAttribute();
1052                }
1053            }
1054            else
1055            {
1056                rma = RModuleAttributeManager.getInstance(rModAttId, false);
1057            }
1058}
1059catch(Exception JavaDoc e)
1060{
1061e.printStackTrace();
1062}
1063        return rma;
1064    }
1065
1066    /**
1067     * A AttributeGroup object for use within the Scarab API.
1068     */

1069    public void setAttributeGroup(AttributeGroup group)
1070    {
1071        this.group = group;
1072    }
1073
1074    /**
1075     * A Module object for use within the Scarab API.
1076     */

1077    public void setModule(Module module)
1078    {
1079        this.module = module;
1080    }
1081
1082    /**
1083     * Get an Module object.
1084     *
1085     * @return a <code>Module</code> value
1086     */

1087    public Module getModule()
1088        throws Exception JavaDoc
1089    {
1090try
1091{
1092        String JavaDoc modId = getIntakeTool()
1093            .get("Module", IntakeTool.DEFAULT_KEY).get("Id").toString();
1094        if (modId == null || modId.length() == 0)
1095        {
1096            module = ModuleManager.getInstance();
1097        }
1098        else
1099        {
1100            module = ModuleManager.getInstance(new Integer JavaDoc(modId));
1101        }
1102}
1103catch(Exception JavaDoc e)
1104{
1105e.printStackTrace();
1106}
1107       return module;
1108    }
1109
1110    /**
1111     * Get a specific module by key value. Returns null if
1112     * the Module could not be found
1113     *
1114     * @param key a <code>String</code> value
1115     * @return a <code>Module</code> value
1116     */

1117    public Module getModule(String JavaDoc key)
1118    {
1119        Module me = null;
1120        if (key != null && key.length() > 0)
1121        {
1122            try
1123            {
1124                me = ModuleManager.getInstance(new Integer JavaDoc(key));
1125            }
1126            catch (Exception JavaDoc e)
1127            {
1128                Log.get().info("[ScarabRequestTool] Unable to retrieve Module: " +
1129                         key, e);
1130            }
1131        }
1132        return me;
1133    }
1134
1135    /**
1136     * Gets the Module associated with the information
1137     * passed around in the query string. Returns null if
1138     * the Module could not be found.
1139     */

1140    public Module getCurrentModule()
1141    {
1142        ScarabUser user = (ScarabUser)data.getUser();
1143        Module currentModule = null;
1144        if (user != null)
1145        {
1146            currentModule = user.getCurrentModule();
1147        }
1148
1149        return currentModule;
1150    }
1151
1152    /**
1153     * Gets the IssueType associated with the information
1154     * passed around in the query string.
1155     */

1156    public IssueType getCurrentIssueType() throws Exception JavaDoc
1157    {
1158        ScarabUser user = (ScarabUser)data.getUser();
1159        IssueType curit = user.getCurrentIssueType();
1160        if (curit == null)
1161        {
1162            curit = IssueTypeManager.getInstance(data.getParameters().
1163                    getInteger(ScarabConstants.CURRENT_ISSUE_TYPE));
1164        }
1165        return curit;
1166    }
1167
1168    public void setCurrentIssueType(IssueType type)
1169    {
1170        ScarabUser user = (ScarabUser)data.getUser();
1171        if (user != null)
1172        {
1173            user.setCurrentIssueType(type);
1174        }
1175    }
1176
1177    /**
1178     * Looks at the current RModuleIssueType and if it is null,
1179     * returns the users homepage. If it is not null, and is
1180     * dedupe, returns Wizard1...else Wizard3.
1181     */

1182    public String JavaDoc getNextEntryTemplate(IssueType issueType)
1183    {
1184        RModuleIssueType rmit = null;
1185        String JavaDoc nextTemplate = null;
1186        try
1187        {
1188            Module module = getCurrentModule();
1189            if (module == null)
1190            {
1191                nextTemplate = ((ScarabUser)data.getUser()).getHomePage();
1192                setAlertMessage(L10NKeySet.ModuleIssueTypeRequiredToEnterIssue);
1193            }
1194            else
1195            {
1196                rmit = module.getRModuleIssueType(issueType);
1197                if (rmit == null)
1198                {
1199                    nextTemplate = ((ScarabUser)data.getUser()).getHomePage();
1200                    setAlertMessage(L10NKeySet.ModuleIssueTypeRequiredToEnterIssue);
1201                }
1202                else if (rmit.getDedupe() && !module
1203                         .getDedupeGroupsWithAttributes(issueType).isEmpty())
1204                {
1205                    nextTemplate = "entry,Wizard1.vm";
1206                }
1207                else
1208                {
1209                    nextTemplate = "entry,Wizard3.vm";
1210                }
1211            }
1212        }
1213        catch (Exception JavaDoc e)
1214        {
1215            // system would be messed up, if we are here. Punt
1216
nextTemplate = "Index.vm";
1217            setAlertMessage(L10NKeySet.CannotDetermineIssueEntryTemplate);
1218            Log.get().error("CannotDetermineIssueEntryTemplate", e);
1219        }
1220        return nextTemplate;
1221    }
1222
1223    /**
1224     * Returns name of current template
1225     */

1226    public String JavaDoc getCurrentTemplate()
1227    {
1228        return data.getTarget().replace('/',',');
1229    }
1230
1231    /**
1232     * The issue that is currently being entered.
1233     *
1234     * @return an <code>Issue</code> value
1235     */

1236    public Issue getReportingIssue()
1237        throws Exception JavaDoc
1238    {
1239        if (reportingIssue == null)
1240        {
1241            String JavaDoc key = data.getParameters()
1242                .getString(ScarabConstants.REPORTING_ISSUE);
1243
1244            if (key == null)
1245            {
1246                getNewReportingIssue();
1247            }
1248            else
1249            {
1250                reportingIssue = ((ScarabUser)data.getUser())
1251                    .getReportingIssue(key);
1252
1253                // if reportingIssue is still null, the parameter must have
1254
// been stale, just get a new issue
1255
if (reportingIssue == null)
1256                {
1257                    getNewReportingIssue();
1258                }
1259            }
1260        }
1261        return reportingIssue;
1262    }
1263
1264    private void getNewReportingIssue()
1265        throws Exception JavaDoc
1266    {
1267        reportingIssue = getCurrentModule().getNewIssue(getCurrentIssueType());
1268        String JavaDoc key = ((ScarabUser)data.getUser())
1269            .setReportingIssue(reportingIssue);
1270        data.getParameters().add(ScarabConstants.REPORTING_ISSUE, key);
1271    }
1272
1273    public void setReportingIssue(Issue issue)
1274    {
1275        reportingIssue = issue;
1276    }
1277
1278    /**
1279     * Sets the current Module
1280     */

1281    public void setCurrentModule(Module me)
1282    {
1283        ScarabUser user = (ScarabUser)data.getUser();
1284        if (user != null)
1285        {
1286            user.setCurrentModule(me);
1287        }
1288    }
1289
1290    /**
1291     * A Issue object for use within the Scarab API.
1292     */

1293    public void setIssue(Issue issue)
1294    {
1295        this.issue = issue;
1296    }
1297
1298    /**
1299     * Get an Issue object from unique id given either as an intake
1300     * field or a request parameter keyed with "id".
1301     *
1302     * @return a <code>Issue</code> value
1303     */

1304    public Issue getIssue()
1305        throws Exception JavaDoc
1306    {
1307        if (issue == null)
1308        {
1309            String JavaDoc issueId = null;
1310            Group issueGroup = getIntakeTool()
1311                .get("Issue", IntakeTool.DEFAULT_KEY, false);
1312            if (issueGroup != null)
1313            {
1314                issueId = issueGroup.get("Id").toString();
1315            }
1316            else
1317            {
1318                issueId = data.getParameters().getString("id");
1319            }
1320            if (issueId != null && issueId.length() > 0)
1321            {
1322                issue = getIssue(issueId);
1323            }
1324        }
1325        return issue;
1326    }
1327
1328    /**
1329     * Takes unique id, and returns issue.
1330     * if the issue is not valid, then it returns null.
1331     */

1332    public Issue getIssue(String JavaDoc id)
1333    {
1334        Issue issue = null;
1335        if (id == null || id.length() == 0)
1336        {
1337            setInfoMessage(L10NKeySet.EnterId);
1338        }
1339        else
1340        {
1341            try
1342            {
1343                issue = IssueManager
1344                    .getIssueById(id, getCurrentModule().getCode());
1345                if (issue == null)
1346                {
1347                    setAlertMessage(L10NKeySet.InvalidId);
1348                }
1349                else if (issue.getDeleted())
1350                {
1351                    setAlertMessage(L10NKeySet.ViewIssueIssueMoved);
1352                    issue = null;
1353                }
1354            }
1355            catch (Exception JavaDoc e)
1356            {
1357                setAlertMessage(L10NKeySet.InvalidId);
1358            }
1359        }
1360        return issue;
1361    }
1362
1363    /**
1364     * The id may only be the issue's primary key.
1365     *
1366     * @param key a <code>String</code> value
1367     * @return a <code>Issue</code> value
1368     */

1369    public Issue getIssueByPk(String JavaDoc key)
1370    {
1371        Issue issue = null;
1372        try
1373        {
1374            issue = IssueManager.getInstance(new Long JavaDoc(key));
1375        }
1376        catch (Exception JavaDoc e)
1377        {
1378            setAlertMessage(L10NKeySet.InvalidIssueId);
1379        }
1380        return issue;
1381    }
1382
1383    /**
1384     * Get a list of Issue objects.
1385     *
1386     * @return a <code>Issue</code> value
1387     */

1388    public List JavaDoc getIssues()
1389        throws Exception JavaDoc
1390    {
1391        List JavaDoc issues = null;
1392
1393        Group issueGroup = getIntakeTool()
1394            .get("Issue", IntakeTool.DEFAULT_KEY, false);
1395        if (issueGroup != null)
1396        {
1397            Long JavaDoc[] issueIds = (Long JavaDoc []) issueGroup.get("Ids").getValue();
1398            if (issueIds != null)
1399            {
1400                issues = getIssues(Arrays.asList(issueIds));
1401            }
1402        }
1403        else
1404        {
1405            String JavaDoc[] paramIssueIds = data.getParameters().getStrings("issue_ids");
1406            if (paramIssueIds != null)
1407            {
1408                issues = getIssues(Arrays.asList(paramIssueIds));
1409            }
1410        }
1411        if (issues == null)
1412        {
1413            issues = Collections.EMPTY_LIST;
1414        }
1415        return issues;
1416    }
1417
1418    /**
1419     * Get a list of Issue objects from a list of issue ids. The list
1420     * can contain Strings or Integers, but all ids must be of the same type
1421     * (String or Integer).
1422     *
1423     * @param issueIds a <code>List</code> value
1424     * @return a <code>List</code> value
1425     * @exception Exception if an error occurs
1426     */

1427    public List JavaDoc getIssues(List JavaDoc issueIds)
1428        throws Exception JavaDoc
1429    {
1430        List JavaDoc issues = null;
1431        StringBuffer JavaDoc invalidIds = null;
1432        if (issueIds == null || issueIds.isEmpty())
1433        {
1434            issues = Collections.EMPTY_LIST;
1435        }
1436        else
1437        {
1438            if (issueIds.get(0) instanceof String JavaDoc)
1439            {
1440                issues = new ArrayList JavaDoc(issueIds.size());
1441                Iterator JavaDoc i = issueIds.iterator();
1442                while (i.hasNext())
1443                {
1444                    String JavaDoc id = (String JavaDoc)i.next();
1445                    Issue issue = getIssue(id);
1446                    if (issue == null)
1447                    {
1448                        if (invalidIds == null)
1449                        {
1450                            invalidIds = new StringBuffer JavaDoc(id);
1451                        }
1452                        else
1453                        {
1454                            invalidIds.append(' ').append(id);
1455                        }
1456                    }
1457                    else
1458                    {
1459                        issues.add(issue);
1460                    }
1461                }
1462                if (invalidIds != null)
1463                {
1464                    setAlertMessage(getLocalizationTool()
1465                        .format("SomeIssueIdsNotValid", invalidIds.toString()));
1466                }
1467            }
1468            else if (issueIds.get(0) instanceof Long JavaDoc)
1469            {
1470                issues = new ArrayList JavaDoc(issueIds.size());
1471                Iterator JavaDoc i = issueIds.iterator();
1472                while (i.hasNext())
1473                {
1474                    Issue issue = IssueManager.getInstance((Long JavaDoc)i.next());
1475                    if (issue == null)
1476                    {
1477                        setAlertMessage(L10NKeySet.SomeIssuePKsNotValid);
1478                    }
1479                    else
1480                    {
1481                        issues.add(issue);
1482                    }
1483                }
1484            }
1485            else
1486            {
1487                throw new IllegalArgumentException JavaDoc(
1488                    "issue ids must be Strings or Longs, not " +
1489                    issueIds.get(0).getClass().getName()); //EXCEPTION
1490
}
1491        }
1492        return issues;
1493    }
1494        
1495
1496    /**
1497     * Get all scopes.
1498     */

1499    public List JavaDoc getScopes()
1500        throws Exception JavaDoc
1501    {
1502        return ScopePeer.getAllScopes();
1503    }
1504
1505    /**
1506     * Get all frequencies.
1507     */

1508    public List JavaDoc getFrequencies()
1509        throws Exception JavaDoc
1510    {
1511        return FrequencyPeer.getFrequencies();
1512    }
1513
1514    /**
1515     * Generates link to Issue List page, re-running stored query.
1516     */

1517    public String JavaDoc getExecuteLink(String JavaDoc link, Query query)
1518    {
1519        // query.getValue() begins with a &
1520
link = link
1521            + "?action=Search&eventSubmit_doSearch=Search"
1522            + "&pagenum=1" + query.getValue();
1523
1524        Long JavaDoc listId = query.getListId();
1525        if (listId != null)
1526        {
1527            link += '&' + ScarabConstants.CURRENT_MITLIST_ID + '=' + listId;
1528        }
1529        else
1530        {
1531            link += '&' + ScarabConstants.REMOVE_CURRENT_MITLIST_QKEY + "=true";
1532        }
1533        return link;
1534     }
1535
1536    /**
1537     * Generates link to the Query Detail page.
1538     */

1539    public String JavaDoc getEditLink(String JavaDoc link, Query query)
1540    {
1541        // query.getValue() begins with a &
1542
link = link + "?queryId=" + query.getQueryId()
1543            + "&refine=true"
1544            + "&action=Search&eventSubmit_doPreparequery=foo"
1545            + query.getValue();
1546
1547        Long JavaDoc listId = query.getListId();
1548        if (listId != null)
1549        {
1550            link += '&' + ScarabConstants.CURRENT_MITLIST_ID + '=' + listId;
1551        }
1552        else
1553        {
1554            link += '&' + ScarabConstants.REMOVE_CURRENT_MITLIST_QKEY + "=true";
1555        }
1556        return link;
1557    }
1558
1559    public Intake getConditionalIntake(String JavaDoc parameter)
1560        throws Exception JavaDoc
1561    {
1562        Intake intake = null;
1563        String JavaDoc param = data.getParameters().getString(parameter);
1564        if (param == null)
1565        {
1566            intake = getIntakeTool();
1567        }
1568        else
1569        {
1570            intake = new Intake();
1571            StringValueParser parser = new StringValueParser();
1572            parser.parse(param, '&', '=', true);
1573            intake.init(parser);
1574        }
1575
1576        return intake;
1577    }
1578
1579    /**
1580     * Get a new IssueSearch object.
1581     *
1582     * @return a <code>Issue</code> value
1583     */

1584    public IssueSearch getNewSearch()
1585        throws Exception JavaDoc, MaxConcurrentSearchException
1586    {
1587        if (issueSearch == null)
1588        {
1589            ScarabUser user = (ScarabUser)data.getUser();
1590            MITList mitList = user.getCurrentMITList();
1591            if (mitList == null)
1592            {
1593                setAlertMessage(L10NKeySet.NoIssueTypeList);
1594                Log.get().warn("Attempted to create a new IssueSearch and " +
1595                               " issue types had not been selected.");
1596            }
1597            else
1598            {
1599                issueSearch =
1600                    IssueSearchFactory.INSTANCE.getInstance(mitList, user);
1601                issueSearch.setLocale(getLocalizationTool().getPrimaryLocale());
1602            }
1603        }
1604        return issueSearch;
1605    }
1606
1607    /**
1608     * Get an IssueSearch object based on a query string.
1609     *
1610     * @return a <code>Issue</code> value
1611     */

1612    public IssueSearch getPopulatedSearch(String JavaDoc query)
1613        throws Exception JavaDoc
1614    {
1615        IssueSearch search = getNewSearch();
1616        if (null == search)
1617            return null;
1618        
1619        ScarabLocalizationTool l10n = getLocalizationTool();
1620        search.setIssueListAttributeColumns(getRModuleUserAttributes());
1621        search.setLocalizationTool(getLocalizationTool());
1622        search.setQuery(query);
1623
1624        Intake intake = null;
1625
1626        if (query == null)
1627        {
1628            setInfoMessage(L10NKeySet.EnterQuery);
1629            return null;
1630        }
1631        else
1632        {
1633           intake = parseQuery(query);
1634           
1635           if (!intake.isAllValid())
1636           {
1637               return null;
1638           }
1639        }
1640
1641        // If they have entered users to search on, add them to the search
1642
StringValueParser parser = new StringValueParser();
1643        parser.parse(query, '&', '=', true);
1644        String JavaDoc[] userList = parser.getStrings("user_list");
1645        if (userList != null && userList.length > 0)
1646        {
1647            for (int i = 0; i < userList.length; i++)
1648            {
1649                String JavaDoc userId = userList[i];
1650                String JavaDoc[] attrIds = parser.getStrings("user_attr_" + userId);
1651                if (attrIds != null)
1652                {
1653                    for (int j = 0; j < attrIds.length; j++)
1654                    {
1655                        search.addUserCriteria(userId, attrIds[j]);
1656                    }
1657                }
1658            }
1659        }
1660
1661        // Set intake properties
1662
boolean searchSuccess = true;
1663        Group searchGroup = intake.get("SearchIssue",
1664                                       search.getQueryKey());
1665        
1666        Field minDate = searchGroup.get("MinDate");
1667        if (minDate != null && minDate.toString().length() > 0)
1668        {
1669           searchSuccess = checkDate(search, minDate.toString());
1670        }
1671        
1672        Field maxDate = searchGroup.get("MaxDate");
1673        if (maxDate != null && maxDate.toString().length() > 0)
1674        {
1675            searchSuccess = checkDate(search, maxDate.toString());
1676        }
1677        
1678        Field stateChangeFromDate = searchGroup.get("StateChangeFromDate");
1679        if (stateChangeFromDate != null
1680            && stateChangeFromDate.toString().length() > 0)
1681        {
1682            searchSuccess = checkDate(search, stateChangeFromDate.toString());
1683        }
1684        
1685        Field stateChangeToDate = searchGroup.get("StateChangeToDate");
1686        if (stateChangeToDate != null
1687            && stateChangeToDate.toString().length() > 0)
1688        {
1689            searchSuccess = checkDate(search, stateChangeToDate.toString());
1690        }
1691        
1692        if (!searchSuccess)
1693        {
1694            setAlertMessage(l10n.format("DateFormatPrompt",
1695                    L10NKeySet.ShortDateDisplay));
1696            return null;
1697        }
1698        
1699        try
1700        {
1701            searchGroup.setProperties(search);
1702        }
1703        catch (Exception JavaDoc e)
1704        {
1705            setAlertMessage(l10n.getMessage(e));
1706            return null;
1707        }
1708        
1709        Integer JavaDoc oldOptionId = search.getStateChangeFromOptionId();
1710        if (oldOptionId != null && oldOptionId.intValue() != 0
1711             && oldOptionId.equals(search.getStateChangeToOptionId()))
1712        {
1713            setAlertMessage(L10NKeySet.StateChangeOldEqualNew);
1714            return null;
1715        }
1716        
1717        // Set attribute values to search on
1718
LinkedMap avMap = search.getCommonAttributeValuesMap();
1719        Iterator JavaDoc i = avMap.mapIterator();
1720        while (i.hasNext())
1721        {
1722            AttributeValue aval = (AttributeValue)avMap.get(i.next());
1723            Group group = intake.get("AttributeValue", aval.getQueryKey());
1724            if (group != null)
1725            {
1726                group.setProperties(aval);
1727            }
1728        }
1729        
1730        // If user is sorting on an attribute, set sort criteria
1731
// Do not use intake, since intake parsed from query is not the same
1732
// As intake passed from the form
1733
String JavaDoc sortColumn = data.getParameters().getString("sortColumn");
1734        if (sortColumn != null && sortColumn.length() > 0
1735            && StringUtils.isNumeric(sortColumn))
1736        {
1737            search.setSortAttributeId(new Integer JavaDoc(sortColumn));
1738        }
1739        
1740        String JavaDoc sortPolarity = data.getParameters().getString("sortPolarity");
1741        if (sortPolarity != null && sortPolarity.length() > 0)
1742        {
1743            search.setSortPolarity(sortPolarity);
1744        }
1745        
1746        return search;
1747    }
1748
1749    /**
1750     * Get an IssueSearch object based on current query string.
1751     *
1752     * @return a <code>Issue</code> value
1753     */

1754    public IssueSearch getPopulatedSearch()
1755        throws Exception JavaDoc
1756    {
1757        String JavaDoc currentQueryString = ((ScarabUser)data.getUser()).getMostRecentQuery();
1758        return getPopulatedSearch(currentQueryString);
1759    }
1760
1761    /**
1762     * Parses query into intake values.
1763    */

1764    public Intake parseQuery(String JavaDoc query)
1765        throws Exception JavaDoc
1766    {
1767        Intake intake = new Intake();
1768        StringValueParser parser = new StringValueParser();
1769        parser.parse(query, '&', '=', true);
1770        
1771        intake.init(parser);
1772        return intake;
1773    }
1774
1775    /**
1776     * Performs search on current query (which is stored in user session).
1777    */

1778    public IteratorWithSize getCurrentSearchResults()
1779    {
1780        return getCurrentSearchResults(false);
1781    }
1782
1783    /**
1784     * Performs search on current query (which is stored in user session).
1785    */

1786    public IteratorWithSize getCurrentSearchResults(boolean mergePartialQueryResults)
1787    {
1788        IteratorWithSize matchingIssueIds = null;
1789        try
1790        {
1791            matchingIssueIds = getUnprotectedCurrentSearchResults(mergePartialQueryResults);
1792        }
1793        catch (MaxConcurrentSearchException e)
1794        {
1795            setAlertMessage(L10NKeySet.ResourceLimitationsPreventedSearch);
1796        }
1797        catch (ComplexQueryException e)
1798        {
1799            matchingIssueIds = IteratorWithSize.EMPTY;
1800            setAlertMessage(new SimpleSkipFiltering(getLocalizationTool()
1801                .format("SearchAbortedDueToComplexity",
1802                        new SnippetRenderer(data, "ComplexQueryHelpLink.vm"))));
1803        }
1804        catch (Exception JavaDoc e)
1805        {
1806            matchingIssueIds = IteratorWithSize.EMPTY;
1807            L10NMessage l10nMessage = new L10NMessage(L10NKeySet.ErrorProcessingQuery,e);
1808            setAlertMessage(l10nMessage);
1809            Log.get().info("Error processing a query", e);
1810        }
1811        
1812        return matchingIssueIds;
1813    }
1814
1815    /**
1816     * Caches the result of getUncachedCurrentSearchResults for the remainder
1817     * of the request.
1818     */

1819    private IteratorWithSize getUnprotectedCurrentSearchResults(boolean mergePartialQueryResults)
1820        throws Exception JavaDoc
1821    {
1822        // normally we would use "this" as the first arg to ScarabCache.get,
1823
// but SRT is not serializable. The result is a mix of a query string
1824
// and an MITList and the two should not vary over the course of one
1825
// request so use the query string as the key. We were using the
1826
// IssueSearch returned by getNewSearch as the key, but we have to
1827
// call user.getMostRecentQuery prior to getNewSearch, so using
1828
// that instead.
1829
String JavaDoc queryString = ((ScarabUser)data.getUser()).getMostRecentQuery();
1830        IteratorWithSize results = null;
1831        Object JavaDoc obj =
1832            ScarabCache.get(queryString, "getUnprotectedCurrentSearchResults");
1833        if (obj == null)
1834        {
1835            results = getUncachedCurrentSearchResults(mergePartialQueryResults);
1836            ScarabCache.put(results, queryString,
1837                            "getUnprotectedCurrentSearchResults");
1838        }
1839        else
1840        {
1841            results = (IteratorWithSize)obj;
1842        }
1843        return results;
1844    }
1845
1846    /**
1847     * Performs search on current query (which is stored in user session).
1848     */

1849    private IteratorWithSize getUncachedCurrentSearchResults(boolean mergePartialQueryResults)
1850        throws Exception JavaDoc
1851    {
1852        ScarabLocalizationTool l10n = getLocalizationTool();
1853        ScarabUser user = (ScarabUser)data.getUser();
1854        String JavaDoc currentQueryString = user.getMostRecentQuery();
1855        IssueSearch search = getPopulatedSearch(currentQueryString);
1856        IteratorWithSize queryResults = null;
1857
1858        // Do search
1859
try
1860        {
1861            if (search == null)
1862            {
1863                // an alert message should have been set while attempting
1864
// to populate the search.
1865
queryResults = IteratorWithSize.EMPTY;
1866            }
1867            else
1868            {
1869                queryResults = search.getQueryResults(mergePartialQueryResults);
1870                if (!queryResults.hasNext())
1871                {
1872                    setInfoMessage(L10NKeySet.NoMatchingIssues);
1873                }
1874            }
1875        }
1876        catch (ScarabException e)
1877        {
1878            String JavaDoc queryError = e.getMessage();
1879            if (queryError.startsWith(SearchIndex.PARSE_ERROR))
1880            {
1881                Log.get().info(queryError);
1882                setAlertMessage(new SimpleSkipFiltering(
1883                    l10n.format("QueryParserError",
1884                        new SnippetRenderer(data, "TextQueryHelp.vm"))));
1885            }
1886            else
1887            {
1888                throw e; //EXCEPTION
1889
}
1890        }
1891        return queryResults;
1892    }
1893
1894    /**
1895     * Gets the number of results for the current query. Looks first
1896     * at the URL, then requeries if size information is missing.
1897     */

1898    public int getCurrentSearchResultsSize()
1899    {
1900        String JavaDoc[] prevNextList = data.getParameters().getStrings("issueList");
1901        int result = 0;
1902        if (prevNextList == null)
1903        {
1904            result = getCurrentSearchResults().size();
1905        }
1906        else
1907        {
1908            result = Integer.parseInt(prevNextList[1]);
1909        }
1910        return result;
1911    }
1912
1913    /**
1914     * Returns the issue's position (1-based) in current issue list.
1915     */

1916    public int getIssuePosInList()
1917        throws Exception JavaDoc, ScarabException
1918    {
1919        int issuePos = -1;
1920        String JavaDoc id = getIssue().getUniqueId();
1921        String JavaDoc[] prevNextList = data.getParameters().getStrings("issueList");
1922        if (prevNextList != null)
1923        {
1924            int listOffset = Math.max(0, Integer.parseInt(prevNextList[0]));
1925            for (int i=2; i<prevNextList.length; i++)
1926            {
1927                if (prevNextList[i].equals(id))
1928                {
1929                    issuePos = listOffset + i - 1;
1930                    break;
1931                }
1932            }
1933        }
1934
1935        return (issuePos <= 0) ? 1 : issuePos;
1936    }
1937
1938    /**
1939     * Returns next issue id in list.
1940     */

1941    public String JavaDoc getNextIssue()
1942        throws Exception JavaDoc, ScarabException
1943    {
1944        String JavaDoc nextIssueId = null;
1945        String JavaDoc[] prevNextList = data.getParameters().getStrings("issueList");
1946        if (prevNextList != null)
1947        {
1948            String JavaDoc id = getIssue().getUniqueId();
1949            for (int i=2; i<prevNextList.length-1; i++)
1950            {
1951                if (prevNextList[i].equals(id))
1952                {
1953                    nextIssueId = prevNextList[i+1];
1954                    break;
1955                }
1956            }
1957        }
1958        
1959        if (nextIssueId == null)
1960        {
1961            if (cachedNextIssueId == null)
1962            {
1963                int issuePos = getIssuePosInList();
1964                if (issuePos <= getCurrentSearchResultsSize())
1965                {
1966                    resetIssueIdList(issuePos);
1967                    nextIssueId = cachedNextIssueId;
1968                }
1969            }
1970            else
1971            {
1972                nextIssueId = cachedNextIssueId;
1973            }
1974        }
1975        return nextIssueId;
1976    }
1977
1978    /**
1979     * Returns previous issue id in list.
1980     */

1981    public String JavaDoc getPrevIssue()
1982        throws Exception JavaDoc, ScarabException
1983    {
1984        String JavaDoc prevIssueId = null;
1985        String JavaDoc[] prevNextList = data.getParameters().getStrings("issueList");
1986        if (prevNextList != null)
1987        {
1988            String JavaDoc id = getIssue().getUniqueId();
1989            for (int i=3; i<prevNextList.length; i++)
1990            {
1991                if (prevNextList[i].equals(id))
1992                {
1993                    prevIssueId = prevNextList[i-1];
1994                    break;
1995                }
1996            }
1997        }
1998        
1999        if (prevIssueId == null)
2000        {
2001            if (cachedPrevIssueId == null)
2002            {
2003                int issuePos = getIssuePosInList();
2004                if (issuePos > 1)
2005                {
2006                    resetIssueIdList(issuePos);
2007                    prevIssueId = cachedPrevIssueId;
2008                }
2009            }
2010            else
2011            {
2012                prevIssueId = cachedPrevIssueId;
2013            }
2014        }
2015        return prevIssueId;
2016    }
2017
2018    private void resetIssueIdList(int issuePos)
2019    {
2020        IteratorWithSize idList = getCurrentSearchResults();
2021        ParameterParser pp = data.getParameters();
2022        pp.remove("issueList");
2023        int min = issuePos - 5;
2024        int max = issuePos + 10;
2025        pp.add("issueList", min);
2026        pp.add("issueList", idList.size());
2027
2028        int count;
2029        for (count = 0; idList.hasNext() && count < min; count++)
2030        {
2031            idList.next();
2032        }
2033        for (; idList.hasNext() && count < issuePos - 2; count++)
2034        {
2035            pp.add("issueList",
2036                   ((QueryResult) idList.next()).getUniqueId());
2037        }
2038        if (idList.hasNext())
2039        {
2040            cachedPrevIssueId = ((QueryResult)idList.next())
2041                .getUniqueId();
2042            pp.add("issueList", cachedPrevIssueId);
2043        }
2044        if (idList.hasNext())
2045        {
2046            pp.add("issueList",
2047                   ((QueryResult) idList.next()).getUniqueId());
2048        }
2049        if (idList.hasNext())
2050        {
2051            cachedNextIssueId = ((QueryResult)idList.next())
2052                .getUniqueId();
2053            pp.add("issueList", cachedNextIssueId);
2054        }
2055        for (count += 3; idList.hasNext() && count < max; count++)
2056        {
2057            pp.add("issueList",
2058                   ((QueryResult) idList.next()).getUniqueId());
2059        }
2060    }
2061
2062    /**
2063     * Attempts to parse a date passed in the query page.
2064    */

2065    private boolean checkDate(IssueSearch search, String JavaDoc date)
2066        throws Exception JavaDoc
2067    {
2068        boolean success = true;
2069        try
2070        {
2071            search.parseDate(date, false);
2072        }
2073        catch (Exception JavaDoc e)
2074        {
2075            success = false;
2076        }
2077        return success;
2078    }
2079
2080
2081    /**
2082     * Convert paths with slashes to commas.
2083     */

2084    public String JavaDoc convertPath(String JavaDoc path)
2085        throws Exception JavaDoc
2086    {
2087            return path.replace('/',',');
2088    }
2089
2090    /**
2091     * Returns all issue templates that are global,
2092     * Plus those that are personal and created by logged-in user.
2093    */

2094    public List JavaDoc getAllIssueTemplates(IssueType issueType)
2095        throws Exception JavaDoc
2096    {
2097        ParameterParser params = data.getParameters();
2098        String JavaDoc sortColumn = params.getString("sortColumn", "name");
2099        String JavaDoc sortPolarity = params.getString("sortPolarity", "asc");
2100        return IssueTemplateInfoPeer.getTemplates(getCurrentModule(),
2101               issueType, (ScarabUser)data.getUser(),
2102               sortColumn, sortPolarity, IssueTemplateInfoPeer.TYPE_ALL);
2103    }
2104
2105    /**
2106     * Returns templates that are personal and created by logged-in user.
2107    */

2108    public List JavaDoc getPrivateTemplates(IssueType issueType)
2109        throws Exception JavaDoc
2110    {
2111        return IssueTemplateInfoPeer.getTemplates(getCurrentModule(),
2112               issueType, (ScarabUser)data.getUser(),
2113               "name", "asc", IssueTemplateInfoPeer.TYPE_PRIVATE);
2114    }
2115
2116    /**
2117     * Returns templates that are personal and created by logged-in user.
2118    */

2119    public List JavaDoc getGlobalTemplates(IssueType issueType)
2120        throws Exception JavaDoc
2121    {
2122        return IssueTemplateInfoPeer.getTemplates(getCurrentModule(),
2123               issueType, (ScarabUser)data.getUser(),
2124               "name", "asc", IssueTemplateInfoPeer.TYPE_GLOBAL);
2125    }
2126
2127    /**
2128     * Returns all queries that are global,
2129     * Plus those that are personal and created by logged-in user.
2130    */

2131    public List JavaDoc getAllQueries()
2132        throws Exception JavaDoc
2133    {
2134        String JavaDoc sortColumn = data.getParameters().getString("sortColumn");
2135        String JavaDoc sortPolarity = data.getParameters().getString("sortPolarity");
2136        if (sortColumn == null)
2137        {
2138            sortColumn = "avail";
2139        }
2140        if (sortPolarity == null)
2141        {
2142            sortPolarity = "desc";
2143        }
2144        return QueryPeer.getQueries(getCurrentModule(),
2145               null, (ScarabUser)data.getUser(),
2146               sortColumn, sortPolarity, IssueTemplateInfoPeer.TYPE_ALL);
2147    }
2148
2149    /**
2150     * Returns queries that are personal and created by logged-in user.
2151    */

2152    public List JavaDoc getPrivateQueries()
2153        throws Exception JavaDoc
2154    {
2155        return QueryPeer.getQueries(getCurrentModule(),
2156               null, (ScarabUser)data.getUser(),
2157               "name", "asc", QueryPeer.TYPE_PRIVATE);
2158    }
2159
2160    /**
2161     * Returns queries that are personal and created by logged-in user.
2162    */

2163    public List JavaDoc getUserQueries()
2164        throws Exception JavaDoc
2165    {
2166        return QueryPeer.getQueries(getCurrentModule(),
2167               null, (ScarabUser)data.getUser(),
2168               "name", "asc", QueryPeer.TYPE_ALL_USER);
2169    }
2170
2171    /**
2172     * Returns all queries that are global.
2173    */

2174    public List JavaDoc getGlobalQueries()
2175        throws Exception JavaDoc
2176    {
2177        return QueryPeer.getQueries(getCurrentModule(),
2178               null, (ScarabUser)data.getUser(),
2179               "name", "asc", QueryPeer.TYPE_GLOBAL);
2180    }
2181
2182    /**
2183     * Returns all queries that are global.
2184    */

2185    public List JavaDoc getUserAllQueries()
2186        throws Exception JavaDoc
2187    {
2188        return QueryPeer.getQueries(getCurrentModule(),
2189               null, (ScarabUser)data.getUser(),
2190               "name", "asc", QueryPeer.TYPE_ALL_USER);
2191    }
2192
2193    /**
2194     * a report helper class
2195     */

2196    public ReportBridge getReport()
2197        throws Exception JavaDoc
2198    {
2199        if (reportGenerator == null)
2200       {
2201            String JavaDoc key = data.getParameters()
2202                .getString(ScarabConstants.CURRENT_REPORT);
2203            ParameterParser parameters = data.getParameters();
2204            String JavaDoc id = parameters.getString("report_id");
2205            if (id == null || id.length() == 0)
2206            {
2207                ScarabUser user = (ScarabUser)data.getUser();
2208                MITList mitlist = user.getCurrentMITList();
2209                if (key == null)
2210                {
2211                    reportGenerator = getNewReport(mitlist);
2212                }
2213                else
2214                {
2215                    reportGenerator = user.getCurrentReport(key);
2216                    
2217                    // if reportingIssue is still null, the parameter must have
2218
// been stale, just get a new report
2219
if (reportGenerator == null &&
2220                        mitlist != null && !mitlist.isEmpty())
2221                    {
2222                        reportGenerator = getNewReport(mitlist);
2223                    }
2224                }
2225            }
2226            else
2227            {
2228                reportGenerator = new ReportBridge(
2229                    ReportManager.getInstance(new NumberKey(id), false));
2230                key = ((ScarabUser)data.getUser())
2231                    .setCurrentReport(reportGenerator);
2232                data.getParameters()
2233                    .remove(ScarabConstants.CURRENT_REPORT);
2234                data.getParameters()
2235                    .add(ScarabConstants.CURRENT_REPORT, key);
2236            }
2237        }
2238
2239        return reportGenerator;
2240    }
2241
2242    private ReportBridge getNewReport(MITList mitList)
2243        throws Exception JavaDoc
2244    {
2245        if (mitList == null)
2246        {
2247            throw new IllegalArgumentException JavaDoc(
2248                "Cannot create a new report without any issue types."); //EXCEPTION
2249
}
2250        
2251        ScarabUser user = (ScarabUser)data.getUser();
2252        org.tigris.scarab.om.Report om = new org.tigris.scarab.om.Report();
2253        ReportBridge report = new ReportBridge(om);
2254        report.setGeneratedBy(user);
2255        report.setMITList(mitList);
2256        
2257        String JavaDoc key = ((ScarabUser)data.getUser()).setCurrentReport(report);
2258        data.getParameters().add(ScarabConstants.CURRENT_REPORT, key);
2259
2260        return report;
2261    }
2262
2263    public void setReport(ReportBridge report)
2264    {
2265        this.reportGenerator = report;
2266    }
2267    
2268    /**
2269     * Full featured, paginated, sorted method for returning the results
2270     * of user search. Returns all users (no search criteria).
2271     */

2272    public ScarabPaginatedList getUserSearchResults(MITList mitList,
2273                                                    int pageNum,
2274                                                    int resultsPerPage,
2275                                                    String JavaDoc sortColumn,
2276                                                    String JavaDoc sortPolarity,
2277                                                    boolean includeCommitters)
2278        throws Exception JavaDoc
2279    {
2280        return userFilteredSearchResults(mitList, pageNum, resultsPerPage,
2281                                         sortColumn, sortPolarity, "", "",
2282                                         includeCommitters);
2283    }
2284
2285    /**
2286     * Full featured, paginated, sorted version for returning results
2287     * of a user search.
2288     */

2289    public ScarabPaginatedList getUserFilteredSearchResults(MITList mitList,
2290        int pageNum, int resultsPerPage, String JavaDoc sortColumn,
2291        String JavaDoc sortPolarity, boolean includeCommitters)
2292        throws Exception JavaDoc
2293    {
2294        String JavaDoc searchString = data.getParameters()
2295               .getString("searchString");
2296        String JavaDoc searchField = data.getParameters()
2297               .getString("searchField");
2298
2299        if (searchField == null)
2300        {
2301            setInfoMessage(L10NKeySet.SearchFieldPrompt);
2302            return null ;
2303        }
2304        
2305        return userFilteredSearchResults(mitList, pageNum, resultsPerPage,
2306                                         sortColumn, sortPolarity,
2307                                         searchString, searchField, includeCommitters);
2308
2309    }
2310
2311    private ScarabPaginatedList userFilteredSearchResults(MITList mitList,
2312                                                          int pageNum,
2313                                                          int resultsPerPage,
2314                                                          String JavaDoc sortColumn,
2315                                                          String JavaDoc sortPolarity,
2316                                                          String JavaDoc searchString,
2317                                                          String JavaDoc searchField,
2318                                                          boolean includeCommitters)
2319        throws Exception JavaDoc
2320    {
2321        ScarabPaginatedList list = null;
2322        String JavaDoc name = null;
2323        String JavaDoc userName = null;
2324
2325        if ("FullName".equalsIgnoreCase(searchField))
2326        {
2327            name = searchString;
2328        }
2329        else if ("UserName".equalsIgnoreCase(searchField))
2330        {
2331            userName = searchString;
2332        }
2333
2334        try
2335        {
2336            list = getCurrentModule().getUsers(name, userName, mitList,
2337                                               pageNum, resultsPerPage,
2338                                               sortColumn, sortPolarity,
2339                                               includeCommitters);
2340        }
2341        catch (Exception JavaDoc e)
2342        {
2343            Log.get().error("Problem getting user list", e);
2344            list = new ScarabPaginatedList();
2345        }
2346
2347        // These are object members are used by GlobalMacros.vm via
2348
// the bean interface. Leave them here until all users of the
2349
// paginate macro can be updated.
2350
this.nbrPages = list.getNumberOfPages();
2351        this.nextPage = list.getNextPageNumber();
2352        this.prevPage = list.getPrevPageNumber();
2353
2354        return list;
2355    }
2356                                
2357
2358    /**
2359     * Return results of attribute search.
2360     */

2361    public List JavaDoc getAttributeSearchResults() throws Exception JavaDoc
2362    {
2363        String JavaDoc searchString = data.getParameters()
2364               .getString("searchString");
2365        String JavaDoc searchField = data.getParameters()
2366               .getString("searchField");
2367        if (searchField == null)
2368        {
2369            setInfoMessage(L10NKeySet.SearchFieldPrompt);
2370            return null ;
2371        }
2372        
2373        String JavaDoc name = null;
2374        String JavaDoc description = null;
2375        if (searchField.equals("Name") || searchField.equals("Any"))
2376        {
2377            name = searchString;
2378        }
2379        if (searchField.equals("Description") || searchField.equals("Any"))
2380        {
2381            description = searchString;
2382        }
2383
2384        return sortAttributes(AttributePeer
2385            .getFilteredAttributes(name, description, searchField));
2386    }
2387
2388    /**
2389     * Sort users on name or email.
2390     */

2391    public List JavaDoc sortUsers(List JavaDoc userList) throws Exception JavaDoc
2392    {
2393        final String JavaDoc sortColumn = data.getParameters().getString("sortColumn");
2394        final String JavaDoc sortPolarity = data.getParameters().getString("sortPolarity");
2395        final int polarity = ("desc".equals(sortPolarity)) ? -1 : 1;
2396        Comparator JavaDoc c = new Comparator JavaDoc()
2397        {
2398            public int compare(Object JavaDoc o1, Object JavaDoc o2)
2399            {
2400                int i = 0;
2401                if ("username".equals(sortColumn))
2402                {
2403                    i = polarity * ((ScarabUser)o1).getUserName()
2404                         .compareTo(((ScarabUser)o2).getUserName());
2405                }
2406                else
2407                {
2408                    i = polarity * ((ScarabUser)o1).getName()
2409                         .compareTo(((ScarabUser)o2).getName());
2410                }
2411                return i;
2412             }
2413        };
2414        Collections.sort(userList, c);
2415        return userList;
2416    }
2417
2418
2419    /**
2420     * Sort attributes on name or description.
2421     */

2422    public List JavaDoc sortAttributes(List JavaDoc attList) throws Exception JavaDoc
2423    {
2424        final String JavaDoc sortColumn = data.getParameters().getString("sortColumn");
2425        final String JavaDoc sortPolarity = data.getParameters().getString("sortPolarity");
2426        final int polarity = ("desc".equals(sortPolarity)) ? -1 : 1;
2427        Comparator JavaDoc c = new Comparator JavaDoc()
2428        {
2429            public int compare(Object JavaDoc o1, Object JavaDoc o2)
2430            {
2431                int i = 0;
2432                if (sortColumn != null && sortColumn.equals("name"))
2433                {
2434                    i = polarity * ((Attribute)o1).getName()
2435                         .compareTo(((Attribute)o2).getName());
2436                }
2437                else
2438                {
2439                    i = polarity * ((Attribute)o1).getDescription()
2440                         .compareTo(((Attribute)o2).getDescription());
2441                }
2442                return i;
2443             }
2444        };
2445        Collections.sort(attList, c);
2446        return attList;
2447    }
2448
2449    /**
2450     * Return a subset of the passed-in list.
2451     *
2452     * @param nbrItmsPerPage negative value returns full list
2453     */

2454    public List JavaDoc getPaginatedList(List JavaDoc fullList, int pgNbr, int nbrItmsPerPage)
2455    {
2456        List JavaDoc pageResults = null;
2457        try
2458        {
2459            if (nbrItmsPerPage < 0)
2460            {
2461                pageResults = fullList;
2462            }
2463            else
2464            {
2465                this.nbrPages = (int)Math.ceil((float)fullList.size()
2466                                                / nbrItmsPerPage);
2467                this.nextPage = pgNbr + 1;
2468                this.prevPage = pgNbr - 1;
2469                pageResults = fullList.subList ((pgNbr - 1) * nbrItmsPerPage,
2470                    Math.min(pgNbr * nbrItmsPerPage, fullList.size()));
2471            }
2472        }
2473        catch(Exception JavaDoc e)
2474        {
2475            Log.get().error("", e);
2476        }
2477        return pageResults;
2478    }
2479
2480    /**
2481     * Return a subset of the passed-in list.
2482     *
2483     * @param nbrItmsPerPage negative value returns full list
2484     */

2485    public IteratorWithSize getPaginatedIterator(IteratorWithSize fullList,
2486                                                 int pgNbr,
2487                                                 int nbrItmsPerPage)
2488    {
2489        IteratorWithSize pageResults;
2490        try
2491        {
2492            if (nbrItmsPerPage < 0)
2493            {
2494                pageResults = fullList;
2495            }
2496            else
2497            {
2498                this.nbrPages = (int)Math.ceil((float)fullList.size()
2499                                                / nbrItmsPerPage);
2500                this.nextPage = pgNbr + 1;
2501                this.prevPage = pgNbr - 1;
2502                pageResults = new SubsetIteratorWithSize(
2503                    fullList, (pgNbr - 1) * nbrItmsPerPage, nbrItmsPerPage);
2504            }
2505        }
2506        catch(Exception JavaDoc e)
2507        {
2508            Log.get().error("", e);
2509            pageResults = IteratorWithSize.EMPTY;
2510        }
2511        return pageResults;
2512    }
2513
2514
2515
2516    /**
2517     * Set the value of issueList.
2518     * @param v Value to assign to issueList.
2519     */

2520    public void setIssueList(List JavaDoc v)
2521    {
2522        this.issueList = v;
2523    }
2524
2525    /**
2526     * Checks for a query parameter "oldResultsPerPage" and compares it
2527     * to the current "resultsPerPage" parameter. If they are different,
2528     * it returns 1 to avoid returning a value larger than the maximum
2529     * number of pages; otherwise it returns the value of the query parameter
2530     * "pageNum".
2531     * Preferrable optimization would be to adjust the page number to
2532     * keep a set of the old displayed items on the new page.
2533     */

2534    public int getAdjustedPageNum()
2535    {
2536        ParameterParser parameters = data.getParameters();
2537        int resultsPerPage = parameters.getInt("resultsPerPage", 0);
2538        int oldResultsPerPage = parameters.getInt("oldResultsPerPage", 0);
2539        int pageNum = parameters.getInt("pageNum", 1);
2540        // I seem to be too braindead to come up with a formula to return the
2541
// new page that will contain the first item on the last page we
2542
// viewed.
2543
// forget it and start over
2544

2545        // Note that -1 -> All results
2546
if (oldResultsPerPage != 0 && oldResultsPerPage != resultsPerPage)
2547        {
2548            pageNum = 1;
2549        }
2550        return pageNum;
2551    }
2552
2553    
2554    /**
2555     * Return the number of paginated pages.
2556     *
2557     */

2558    public int getNbrPages()
2559    {
2560        return nbrPages;
2561    }
2562
2563    /**
2564     * Return the next page in the paginated list.
2565     *
2566     */

2567    public int getNextPage()
2568    {
2569        if (nextPage <= nbrPages)
2570        {
2571            return nextPage;
2572        }
2573        else
2574        {
2575            return 0;
2576        }
2577    }
2578
2579    /**
2580     * Return the previous page in the paginated list.
2581     *
2582     */

2583    public int getPrevPage()
2584    {
2585        return prevPage;
2586    }
2587
2588    /**
2589     * This is used to get the format for a date in the
2590     * Locale sent by the browser.
2591     */

2592    public DateFormat JavaDoc getDateFormat()
2593    {
2594        Locale JavaDoc locale = Localization.getLocale(data.getRequest());
2595        DateFormat JavaDoc df = DateFormat
2596            .getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, locale);
2597        if (timezone != null)
2598        {
2599            df.setTimeZone(timezone);
2600        }
2601        return df;
2602
2603        // We may want to eventually format the date other than default,
2604
// this is how you would do it.
2605
//SimpleDateFormat sdf = new SimpleDateFormat(
2606
// "yyyy/MM/dd hh:mm:ss a z", locale);
2607
//return (DateFormat) sdf;
2608
}
2609
2610    /**
2611     * This is used to get the format for a date in the
2612     * Locale sent by the browser.
2613     */

2614    public Calendar JavaDoc getCalendar()
2615    {
2616        Locale JavaDoc locale = Localization.getLocale(data.getRequest());
2617        Calendar JavaDoc cal = Calendar
2618            .getInstance(locale);
2619        if (timezone != null)
2620        {
2621            cal.setTimeZone(timezone);
2622        }
2623        return cal;
2624    }
2625
2626    /**
2627     * Determine if the user currently interacting with the scarab
2628     * application has a permission within the user's currently
2629     * selected module.
2630     *
2631     * @param permission a <code>String</code> permission value, which should
2632     * be a constant in this interface.
2633     * @return true if the permission exists for the user within the
2634     * current module, false otherwise
2635     */

2636    public boolean hasPermission(String JavaDoc permission)
2637    {
2638        boolean hasPermission = false;
2639        try
2640        {
2641            Module module = getCurrentModule();
2642            hasPermission = hasPermission(permission, module);
2643        }
2644        catch (Exception JavaDoc e)
2645        {
2646            hasPermission = false;
2647            Log.get().error("Permission check failed on:" + permission, e);
2648        }
2649        return hasPermission;
2650    }
2651
2652    /**
2653     * Determine if the user currently interacting with the scarab
2654     * application has a permission within a module.
2655     *
2656     * @param permission a <code>String</code> permission value, which should
2657     * be a constant in this interface.
2658     * @param module a <code>Module</code> value
2659     * @return true if the permission exists for the user within the
2660     * given module, false otherwise
2661     */

2662    public boolean hasPermission(String JavaDoc permission, Module module)
2663    {
2664        boolean hasPermission = false;
2665        try
2666        {
2667            hasPermission = ((ScarabUser)data.getUser())
2668                .hasPermission(permission, module);
2669        }
2670        catch (Exception JavaDoc e)
2671        {
2672            hasPermission = false;
2673            Log.get().error("Permission check failed on:" + permission, e);
2674        }
2675        return hasPermission;
2676    }
2677
2678    /* The map of associated users used on AssignIssue
2679     * When we first go to the screen, reset the map
2680     * To the currently assigned users for each issue
2681     */

2682    public void resetAssociatedUsers() throws Exception JavaDoc
2683    {
2684        HashMap JavaDoc assoUsers = new HashMap JavaDoc();
2685        List JavaDoc issueList = getIssues();
2686        if (issueList != null)
2687        {
2688            for (int i=0; i<issueList.size(); i++)
2689            {
2690                Issue issue = (Issue)issueList.get(i);
2691                assoUsers.put(issue.getIssueId(), issue.getAssociatedUsers());
2692            }
2693            ((ScarabUser)data.getUser()).setAssociatedUsersMap(assoUsers);
2694        }
2695    }
2696    public void resetSelectedUsers() throws Exception JavaDoc
2697    {
2698        ScarabUser user = (ScarabUser)data.getUser();
2699        user.setSelectedUsersMap(null);
2700    }
2701
2702    public List JavaDoc getAssignIssuesList()
2703        throws Exception JavaDoc
2704    {
2705        List JavaDoc issues = null;
2706        Map JavaDoc userMap = ((ScarabUser)data.getUser()).getAssociatedUsersMap();
2707        if (userMap != null && userMap.size() > 0)
2708        {
2709            issues = new ArrayList JavaDoc();
2710            Iterator JavaDoc iter = userMap.keySet().iterator();
2711            while (iter.hasNext())
2712            {
2713                issues.add(IssueManager.getInstance((Long JavaDoc)iter.next()));
2714            }
2715        }
2716        return issues;
2717    }
2718
2719    /**
2720     * When a user searches for other users (in the ManageUserSearch.vm
2721     * template for example), the result of this search is stored into
2722     * the temporary data for that user. This previous result can be
2723     * retrieved by this method.
2724     *
2725     * FIXME: shouldn't this be stored into the cache instead of the
2726     * temporary data of the user?
2727     *
2728     * @return The list of users of the last user-search.
2729     */

2730    public List JavaDoc getGlobalUserSearch()
2731    {
2732        List JavaDoc users = (List JavaDoc) data.getUser().getTemp("userList");
2733        if (users == null)
2734        {
2735            users = new ArrayList JavaDoc();
2736        }
2737        return users;
2738    }
2739    
2740    public ScarabPaginatedList getPaginatedGlobalUsersList(int pageNum, int resultsPerPage,
2741            String JavaDoc searchField, String JavaDoc searchCriteria, String JavaDoc sortColumn, String JavaDoc sortPolarity)
2742        throws Exception JavaDoc
2743    {
2744        ScarabPaginatedList paginated;
2745        Criteria crit = new Criteria();
2746        Criteria critCount = new Criteria();
2747        crit.setOffset((pageNum-1)*resultsPerPage);
2748        crit.setLimit(resultsPerPage);
2749        crit.add(ScarabUserImplPeer.USER_ID, (Object JavaDoc)(ScarabUserImplPeer.USER_ID+" IS NOT NULL"), Criteria.CUSTOM);
2750
2751        if (searchField.equals("LOGIN_NAME"))
2752            searchField = ScarabUserImplPeer.LOGIN_NAME;
2753        else if (searchField.equals("LAST_NAME"))
2754            searchField = ScarabUserImplPeer.LAST_NAME;
2755        else if (searchField.equals("FIRST_NAME"))
2756            searchField = ScarabUserImplPeer.FIRST_NAME;
2757        else if (searchField.equals("EMAIL"))
2758            searchField = ScarabUserImplPeer.EMAIL;
2759        crit.add(searchField, (Object JavaDoc)("%" + searchCriteria + "%"), Criteria.LIKE);
2760        critCount.add(searchField, (Object JavaDoc)("%" + searchCriteria + "%"), Criteria.LIKE);
2761        
2762        String JavaDoc col = ScarabUserImplPeer.FIRST_NAME;
2763        if (sortColumn.equals("LOGIN_NAME"))
2764            col = ScarabUserImplPeer.LOGIN_NAME;
2765        else if (sortColumn.equals("LAST_NAME"))
2766            col = ScarabUserImplPeer.LAST_NAME;
2767        else if (sortColumn.equals("FIRST_NAME"))
2768            col = ScarabUserImplPeer.FIRST_NAME;
2769        else if (sortColumn.equals("EMAIL"))
2770            col = ScarabUserImplPeer.EMAIL;
2771        if (sortPolarity.equalsIgnoreCase("asc"))
2772        {
2773            crit.addAscendingOrderByColumn(col);
2774        }
2775        else
2776        {
2777            crit.addDescendingOrderByColumn(col);
2778        }
2779        
2780        
2781        critCount.add(ScarabUserImplPeer.USER_ID, (Object JavaDoc)(ScarabUserImplPeer.USER_ID+" IS NOT NULL"), Criteria.CUSTOM);
2782        List JavaDoc result = ScarabUserImplPeer.doSelect(crit);
2783        critCount.addSelectColumn("COUNT(*)");
2784        int totalResultSize = ScarabUserImplPeer.getUsersCount(critCount);
2785        if (totalResultSize > 0 && resultsPerPage > 0)
2786        {
2787
2788            paginated = new ScarabPaginatedList(result, totalResultSize,
2789                                                pageNum,
2790                                                resultsPerPage);
2791        }
2792        else
2793        {
2794            paginated = new ScarabPaginatedList();
2795        }
2796    
2797    return paginated;
2798    }
2799    
2800    /**
2801     * Store the search result of other users for later use. The
2802     * result is stored into the temporary data of the current user.
2803     *
2804     * FIXME: use the cache instead?
2805     *
2806     * @param users The list of users that is a result of a query.
2807     */

2808    public void setGlobalUserSearch(List JavaDoc users)
2809    {
2810        data.getUser().setTemp("userList", users);
2811    }
2812    
2813    /**
2814     * Return the parameter used for the user-search (like in the
2815     * ManageUserSearch.vm template for example) returned by the
2816     * getGlobalUserSearch() method. These parameters are stored
2817     * into the temporary data of the current user.
2818     *
2819     * FIXME: use the cache instead?
2820     *
2821     * @param name The name of the parameter
2822     * @return The value of the parameter used in the search for users.
2823     */

2824    public String JavaDoc getGlobalUserSearchParam(String JavaDoc name)
2825    {
2826        Hashtable JavaDoc params = (Hashtable JavaDoc) data.getUser().getTemp("userListParams");
2827        
2828        if (params == null)
2829        {
2830            return "";
2831        }
2832
2833        return (String JavaDoc) params.get(name);
2834    }
2835    
2836    /**
2837     * Set the parameters used to retrieved the users in the List given
2838     * to the setGlobalUserSearch(List) method. These parameters can be
2839     * retrieved by the getGlobalUserSearchParam(String) for later use.
2840     *
2841     * FIXME: use the cache instead?
2842     *
2843     * @param name The name of the parameter
2844     * @param value The value of the parameter
2845     */

2846    public void setGlobalUserSearchParam(String JavaDoc name, String JavaDoc value)
2847    {
2848        Hashtable JavaDoc params = (Hashtable JavaDoc) data.getUser().getTemp("userListParams");
2849        if (params == null)
2850        {
2851            params = new Hashtable JavaDoc();
2852        }
2853
2854        if ((name != null) && (value != null))
2855        {
2856            params.put(name, value);
2857        }
2858        data.getUser().setTemp("userListParams", params);
2859    }
2860
2861    public boolean hasItemsToApprove()
2862    {
2863        try
2864        {
2865            SecurityAdminTool sat = (SecurityAdminTool)org.apache.turbine.modules.Module.getTemplateContext(data)
2866                .get(ScarabConstants.SECURITY_ADMIN_TOOL);
2867            if (getCurrentModule().getUnapprovedQueries().isEmpty() &&
2868                getCurrentModule().getUnapprovedTemplates().isEmpty() &&
2869                sat.getPendingGroupUserRoles(getCurrentModule()).isEmpty())
2870            {
2871                return false;
2872            }
2873        }
2874        catch (Exception JavaDoc e)
2875        {
2876            Log.get().debug("Error: ", e);
2877        }
2878        return true;
2879    }
2880
2881    public MITList getMITList(List JavaDoc issues)
2882        throws Exception JavaDoc
2883    {
2884        return MITListManager
2885            .getInstanceFromIssueList(issues, (ScarabUser)data.getUser());
2886    }
2887
2888    /**
2889     * Gets a list of Attributes or the user type that are in common
2890     * between the issues in the given list.
2891     *
2892     * @param issues a <code>List</code> value
2893     * @return a <code>List</code> value
2894     * @exception Exception if an error occurs
2895     */

2896    public List JavaDoc getUserAttributes(List JavaDoc issues, boolean activeOnly)
2897        throws Exception JavaDoc
2898    {
2899        List JavaDoc attributes = null;
2900        if (issues == null || issues.isEmpty())
2901        {
2902            attributes = Collections.EMPTY_LIST;
2903            Log.get().warn("ScarabRequestTool.getUserAttributes issue list was"
2904                     + (issues == null ? " null" : " empty")) ;
2905        }
2906        else
2907        {
2908            attributes = getMITList(issues).getCommonUserAttributes(activeOnly);
2909        }
2910        
2911        return attributes;
2912    }
2913
2914
2915    // --------------------
2916
// template timing methods
2917
private long startTime;
2918    private long lapTime;
2919
2920    /**
2921     * Should be called near the beginning of a template or wherever timing
2922     * should start.
2923     */

2924    public void startTimer()
2925    {
2926        startTime = System.currentTimeMillis();
2927        lapTime = startTime;
2928    }
2929
2930    /**
2931     * Useful when performance tuning. Usage is to call
2932     * <pre><code>
2933     * $scarabR.startTimer()
2934     * ...
2935     * $scarabR.reportTimer("foo")
2936     * ...
2937     * $scarabR.reportTimer("bar")
2938     *
2939     * or
2940     *
2941     * $scarabG.log($scarabR.reportTimer("bar"))
2942     * </code></pre>
2943     *
2944     * The labels are useful when output is directed to a log file, it can
2945     * be "", if the output is written as part of the response.
2946     */

2947    public String JavaDoc reportTimer(String JavaDoc mesg)
2948    {
2949        long endTime = System.currentTimeMillis();
2950        String JavaDoc s = mesg + ". Time for " + data.getTarget() + ": Lap/Split= "
2951            + (endTime-lapTime) + "ms; Cumulative= " +
2952            (endTime-startTime) + "ms";
2953        lapTime = endTime;
2954        return s;
2955    }
2956
2957    /**
2958     * Helper method to retrieve the ScarabLocalizationTool from the Context
2959     */

2960    private ScarabLocalizationTool getLocalizationTool()
2961    {
2962        return (ScarabLocalizationTool)org.apache.turbine.modules.Module
2963            .getTemplateContext(data).get(ScarabConstants.LOCALIZATION_TOOL);
2964    }
2965
2966    /**
2967     * Helper method to retrieve the ScarabGlobalTool from the Context
2968     */

2969    private ScarabGlobalTool getGlobalTool()
2970    {
2971        return (ScarabGlobalTool)org.apache.turbine.modules.Module
2972            .getTemplateContext(data).get(ScarabConstants.SCARAB_GLOBAL_TOOL);
2973    }
2974
2975    /**
2976     * Get any confirmation message usually set in the action.
2977     * @return value of confirmMessage.
2978     */

2979    public Object JavaDoc getConfirmMessage()
2980    {
2981        return confirmMessage;
2982    }
2983    
2984    /**
2985     * Set confirmation message.
2986     * @deprecated
2987     * @param v Value to assign to confirmMessage.
2988     */

2989    public void setConfirmMessage(Object JavaDoc v)
2990    {
2991        this.confirmMessage = v;
2992    }
2993
2994    /**
2995     * Set confirm message using Localizable localizable.
2996     * @param v Value to assign to alertMessage.
2997     */

2998    public void setConfirmMessage(Localizable localizable)
2999    {
3000        ScarabLocalizationTool l10n = getLocalizationTool();
3001        this.confirmMessage = new SimpleSkipFiltering(localizable.getMessage(l10n));
3002    }
3003
3004    /**
3005     * Get any informational message usually set in the action.
3006     * @return value of infoMessage.
3007     */

3008    public Object JavaDoc getInfoMessage()
3009    {
3010        return infoMessage;
3011    }
3012    
3013    /**
3014     * Set informational message.
3015     * @deprecated
3016     * @param v Value to assign to infoMessage.
3017     */

3018    public void setInfoMessage(Object JavaDoc v)
3019    {
3020        this.infoMessage = v;
3021    }
3022
3023    /**
3024     * Set alert message using Localizable localizable.
3025     * @param v Value to assign to alertMessage.
3026     */

3027    public void setInfoMessage(Localizable localizable)
3028    {
3029        ScarabLocalizationTool l10n = getLocalizationTool();
3030        this.infoMessage = new SimpleSkipFiltering(localizable.getMessage(l10n));
3031    }
3032
3033    /**
3034     * Get any alert message usually set in the action.
3035     * @return value of alertMessage.
3036     */

3037    public Object JavaDoc getAlertMessage()
3038    {
3039        return alertMessage;
3040    }
3041    
3042    /**
3043     * Set alert message.
3044     * @deprecated
3045     * @param v Value to assign to alertMessage.
3046     */

3047    public void setAlertMessage(Object JavaDoc v)
3048    {
3049        this.alertMessage = v;
3050    }
3051    
3052    /**
3053     * Set alert message using Localizable localizable.
3054     * @param v Value to assign to alertMessage.
3055     */

3056    public void setAlertMessage(Localizable localizable)
3057    {
3058        ScarabLocalizationTool l10n = getLocalizationTool();
3059        this.alertMessage = new SimpleSkipFiltering(localizable.getMessage(l10n));
3060    }
3061
3062    public IssueListIterator getIssueListIterator(IteratorWithSize iterator,
3063                                                  int listOffset, int size)
3064    {
3065        return new IssueListIterator(iterator, listOffset, size);
3066    }
3067
3068    public class IssueListIterator implements Iterator JavaDoc
3069    {
3070        private static final String JavaDoc ISSUE_LIST = "issueList";
3071        private static final int PREV_SIZE = 1;
3072        private static final int NEXT_SIZE = 2;
3073
3074        private WindowIterator i;
3075        private int size;
3076        private int listOffset;
3077        private int count = -1;
3078
3079        private IssueListIterator(IteratorWithSize iterator,
3080                                  int listOffset, int size)
3081        {
3082            this.listOffset = Math.max(listOffset, 0);
3083            this.size = size;
3084            this.i = new WindowIterator(iterator, PREV_SIZE, NEXT_SIZE);
3085        }
3086
3087        public Object JavaDoc next()
3088        {
3089            count++;
3090            return i.next();
3091        }
3092
3093        public boolean hasNext()
3094        {
3095            return i.hasNext();
3096        }
3097
3098        public void remove()
3099        {
3100            i.remove();
3101        }
3102
3103        public void initializeLink(ScarabLink link)
3104        {
3105            link.setPage("ViewIssue.vm")
3106                .addPathInfo("id",
3107                             ((QueryResult)i.get(0)).getUniqueId());
3108            int offset = listOffset + count;
3109            for (int m = -1 * PREV_SIZE; m < 0; m++)
3110            {
3111                if (i.hasValue(m))
3112                {
3113                    offset--;
3114                }
3115            }
3116            link.addPathInfo(ISSUE_LIST, offset);
3117            link.addPathInfo(ISSUE_LIST, size);
3118            for (int m = -1 * PREV_SIZE; m <= NEXT_SIZE; m++)
3119            {
3120                if (i.hasValue(m))
3121                {
3122                    link.addPathInfo(ISSUE_LIST,
3123                                     ((QueryResult)i.get(m)).getUniqueId());
3124                }
3125            }
3126        }
3127    }
3128
3129
3130
3131   /**
3132    * @return an IssueType which may represent a template
3133    */

3134    public Object JavaDoc getLastEnteredIssueTypeOrTemplate()
3135        throws Exception JavaDoc
3136    {
3137        Object JavaDoc result = null;
3138        IssueType issueType = getCurrentIssueType();
3139        ScarabUser user = (ScarabUser)data.getUser();
3140        String JavaDoc templateId = data.getParameters().getString("templateId");
3141        if (templateId != null && templateId.trim().length() > 0)
3142        {
3143            Issue template = getIssueTemplate(templateId);
3144            issueType = template.getIssueType().getIssueTypeForTemplateType();
3145            user.setLastEnteredTemplate(template);
3146            result = template;
3147        }
3148
3149        if (result == null && issueType != null)
3150        {
3151            result = issueType;
3152            user.setLastEnteredIssueType(issueType);
3153        }
3154        
3155        if (result == null)
3156        {
3157            result = user.lastEnteredIssueTypeOrTemplate();
3158            if (result != null)
3159            {
3160                if (result instanceof Issue)
3161                {
3162                    issueType = ((Issue)result).getIssueType()
3163                        .getIssueTypeForTemplateType();
3164                }
3165                else if (result instanceof IssueType)
3166                {
3167                    issueType = (IssueType)result;
3168                }
3169                else
3170                {
3171                    Log.get().warn("An object of unexpected class was saved as"
3172                        + " the last entered issuetype or template: " +
3173                        result.getClass().getName());
3174                    result = null;
3175                }
3176                
3177            }
3178        }
3179        
3180        // finally if we have a value, check that it is active
3181
if (issueType != null)
3182        {
3183            RModuleIssueType rmit =
3184                getCurrentModule().getRModuleIssueType(issueType);
3185            if (rmit == null || !rmit.getActive())
3186            {
3187                result = null;
3188            }
3189        }
3190        
3191        return result;
3192    }
3193    
3194    public List JavaDoc getSortedAttributeOptions()
3195    {
3196        return AttributeOptionPeer.getSortedAttributeOptions();
3197    }
3198
3199    /**
3200     * Returned all attributeoptions allowed for every attribute assigned to this
3201     * RModuleIssueType.
3202     * @param rmit
3203     * @return List with all the attributeoptions of every attribute.
3204     * @throws Exception
3205     */

3206    public List JavaDoc getSortedAttributeOptionsForRMIT(RModuleIssueType rmit) throws Exception JavaDoc
3207    {
3208        List JavaDoc attributes = rmit.getIssueType().getActiveAttributes(rmit.getModule());
3209        List JavaDoc result = new ArrayList JavaDoc();
3210        for (Iterator JavaDoc it = attributes.iterator(); it.hasNext(); )
3211        {
3212            Attribute attr = (Attribute)it.next();
3213            if (attr.getAttributeType().getAttributeClass().getName().equals("select-one"))
3214                result.addAll(attr.getAttributeOptions());
3215        }
3216        return result;
3217    }
3218    /**
3219     * Returns if the system is configurated to allow anonymous login.
3220     *
3221     */

3222    public boolean isAnonymousLoginAllowed()
3223    {
3224        return AnonymousUserUtil.anonymousAccessAllowed();
3225    }
3226
3227    public Transition getTransition(Integer JavaDoc pk)
3228    {
3229        Transition tran = null;
3230        try
3231        {
3232            tran = TransitionPeer.retrieveByPK(pk);
3233        }
3234        catch (Exception JavaDoc e)
3235        {
3236            // Nothing to do. Ignore.
3237
}
3238        return tran;
3239    }
3240    
3241    // ****************** Recyclable implementation ************************
3242
/**
3243     * Recycles the object by removing its disposed flag.
3244     */

3245    public void recycle()
3246    {
3247        disposed = false;
3248    }
3249    /**
3250     * Disposes the object after use. The method is called when the
3251     * object is returned to its pool. The dispose method must call
3252     * its super.
3253     */

3254    public void dispose()
3255    {
3256        disposed = true;
3257        data = null;
3258        refresh();
3259    }
3260    /**
3261     * Checks whether the object is disposed.
3262     *
3263     * @return true, if the object is disposed.
3264     */

3265    public boolean isDisposed()
3266    {
3267        return disposed;
3268    }
3269
3270    /**
3271     * Format a date from internal timestamp value to the user's locale format.
3272     * @param value
3273     * @return
3274     */

3275    public String JavaDoc formatDate(String JavaDoc value)
3276    {
3277        return DateAttribute.dateFormat(value, getLocalizationTool().get(L10NKeySet.ShortDatePattern));
3278    }
3279    
3280    /**
3281     * Stores in the request scope a type. Used in IssueList.vm
3282     * @param key
3283     * @param type
3284     */

3285    public void setAttributeType(int key, String JavaDoc type)
3286    {
3287        attributeTypes.put(Integer.toString(key), type);
3288    }
3289
3290    /**
3291     * Retrieves an attribute type from request scope. USed in IssueList.vm
3292     * @param key
3293     * @return
3294     */

3295    public String JavaDoc getAttributeType(int key)
3296    {
3297        return (String JavaDoc)attributeTypes.get(Integer.toString(key));
3298    }
3299
3300    public RModuleIssueType getRModuleIssueType(Integer JavaDoc moduleId, Integer JavaDoc issueTypeId) throws Exception JavaDoc
3301    {
3302        return RModuleIssueTypePeer.retrieveByPK(moduleId, issueTypeId);
3303    }
3304
3305}
3306
3307
3308
Popular Tags