KickJava   Java API By Example, From Geeks To Geeks.

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


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

48
49 import java.util.ArrayList JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Map JavaDoc;
55
56 import org.apache.commons.lang.StringUtils;
57 import org.apache.fulcrum.intake.Intake;
58 import org.apache.fulcrum.intake.model.Field;
59 import org.apache.fulcrum.intake.model.Group;
60 import org.apache.fulcrum.parser.ParameterParser;
61 import org.apache.fulcrum.parser.StringValueParser;
62 import org.apache.turbine.RunData;
63 import org.apache.turbine.TemplateContext;
64 import org.apache.turbine.Turbine;
65 import org.tigris.scarab.actions.base.RequireLoginFirstAction;
66 import org.tigris.scarab.om.Attribute;
67 import org.tigris.scarab.om.AttributeType;
68 import org.tigris.scarab.om.MITList;
69 import org.tigris.scarab.om.MITListManager;
70 import org.tigris.scarab.om.Module;
71 import org.tigris.scarab.om.ModuleManager;
72 import org.tigris.scarab.om.Query;
73 import org.tigris.scarab.om.QueryPeer;
74 import org.tigris.scarab.om.RModuleUserAttribute;
75 import org.tigris.scarab.om.ScarabUser;
76 import org.tigris.scarab.om.Scope;
77 import org.tigris.scarab.services.security.ScarabSecurity;
78 import org.tigris.scarab.tools.ScarabLocalizationTool;
79 import org.tigris.scarab.tools.ScarabRequestTool;
80 import org.tigris.scarab.tools.localization.L10NKeySet;
81 import org.tigris.scarab.tools.localization.L10NMessage;
82 import org.tigris.scarab.util.IteratorWithSize;
83 import org.tigris.scarab.util.Log;
84 import org.tigris.scarab.util.ScarabConstants;
85 import org.tigris.scarab.util.ScarabUtil;
86 import org.tigris.scarab.util.export.ExportFormat;
87 import org.tigris.scarab.util.word.IssueSearch;
88
89 /**
90  * This class is responsible for searching.
91  *
92  * @author <a HREF="mailto:jmcnally@collab.net">John D. McNally</a>
93  * @author <a HREF="mailto:elicia@collab.net">Elicia David</a>
94  * @author <a HREF="mailto:jon@collab.net">Jon S. Stevens</a>
95  * @version $Id: Search.java 9594 2005-04-10 19:12:24Z jorgeuriarte $
96  */

97 public class Search extends RequireLoginFirstAction
98 {
99     private static final String JavaDoc ADD_USER = "add_user";
100     private static final String JavaDoc ADD_USER_BY_USERNAME = "add_user_by_username";
101     private static final String JavaDoc SELECTED_USER = "select_user";
102     private static final String JavaDoc USER_LIST = "user_list";
103     private static final String JavaDoc ANY = "any";
104     private static final String JavaDoc CREATED_BY = "created_by";
105
106     ScarabLocalizationTool l10n;
107     ScarabRequestTool scarabR;
108     Intake intake;
109     ParameterParser params;
110     ScarabUser user;
111
112     /**
113      *
114      */

115     public void doPerform(RunData data, TemplateContext context)
116         throws Exception JavaDoc
117     {
118         setup(data, context);
119         IteratorWithSize queryResults = scarabR.getCurrentSearchResults();
120         if (queryResults != null && queryResults.hasNext())
121         {
122             context.put("queryResults", queryResults);
123             String JavaDoc next = ScarabUtil.findValue(data, "next");
124             if (StringUtils.isNotEmpty
125                 (ScarabUtil.findValue(data, ExportFormat.KEY_NAME)))
126             {
127                 // Send to the IssueListExport screen (which actually
128
// has no corresponding Velocity template).
129
setTarget(data, "IssueListExport.vm");
130             }
131             else if (StringUtils.isNotEmpty(next))
132             {
133                 // Redirect to View, Assign, or Move/Copy
134
List JavaDoc issueIds = null;
135                 ScarabUser user = (ScarabUser) data.getUser();
136                 if (next.indexOf("All") > -1)
137                 {
138                     // all issues are selected
139
issueIds = getAllIssueIds(data);
140                 }
141                 else
142                 {
143                     // get issues select by user
144
issueIds = getSelected(data);
145                 }
146
147
148                 if (issueIds.size() < 1)
149                 {
150                     scarabR.setAlertMessage(L10NKeySet.SelectIssues);
151                     return;
152                 }
153
154                 List JavaDoc modules = ModuleManager.getInstancesFromIssueList(
155                     scarabR.getIssues(issueIds));
156                 if (next.indexOf("assign") > -1)
157                 {
158                     if (user.hasPermission(ScarabSecurity.ISSUE__ASSIGN, modules))
159                     {
160                         if (issueIds.size() <= ScarabConstants.ISSUE_MAX_ASSIGN)
161                         {
162                             scarabR.resetAssociatedUsers();
163                             setTarget(data, "AssignIssue.vm");
164                         }
165                         else
166                         {
167                             L10NMessage msg = new L10NMessage
168                             (
169                                 L10NKeySet.IssueLimitExceeded,
170                                 String.valueOf(ScarabConstants.ISSUE_MAX_ASSIGN)
171                             );
172                             scarabR.setAlertMessage(msg);
173                             return;
174                         }
175                     }
176                     else
177                     {
178                         scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
179                         return;
180                     }
181                 }
182                 else if (next.indexOf("view") > -1)
183                 {
184                     if (user.hasPermission(ScarabSecurity.ISSUE__VIEW, modules))
185                     {
186                         if (issueIds.size() <= ScarabConstants.ISSUE_MAX_VIEW)
187                         {
188                             setTarget(data, "ViewIssueLong.vm");
189                         }
190                         else
191                         {
192                             L10NMessage msg = new L10NMessage
193                             (
194                                 L10NKeySet.IssueLimitExceeded,
195                                 String.valueOf(ScarabConstants.ISSUE_MAX_VIEW)
196                             );
197                             scarabR.setAlertMessage(msg);
198                             return;
199                         }
200                     }
201                     else
202                     {
203                         scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
204                         return;
205                     }
206                 }
207                 else if (next.indexOf("copy") > -1)
208                 {
209                     if (user.hasPermission(ScarabSecurity.ISSUE__ENTER, modules))
210                     {
211                         if (issueIds.size() <= ScarabConstants.ISSUE_MAX_COPY)
212                         {
213                             data.getParameters().add("mv_0rb", "copy");
214                             setTarget(data, "MoveIssue.vm");
215                         }
216                         else
217                         {
218                             L10NMessage msg = new L10NMessage
219                             (
220                                 L10NKeySet.IssueLimitExceeded,
221                                 String.valueOf(ScarabConstants.ISSUE_MAX_COPY)
222                             );
223                             scarabR.setAlertMessage(msg);
224                             return;
225                         }
226                     }
227                     else
228                     {
229                         scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
230                     }
231                 }
232                 else if (next.indexOf("move") > -1)
233                 {
234                     if (user.hasPermission(ScarabSecurity.ISSUE__MOVE, modules))
235                     {
236                         if (issueIds.size() <= ScarabConstants.ISSUE_MAX_MOVE)
237                         {
238                             data.getParameters().add("mv_0rb", "move");
239                             setTarget(data, "MoveIssue.vm");
240                         }
241                         else
242                         {
243                             L10NMessage msg = new L10NMessage
244                             (
245                                 L10NKeySet.IssueLimitExceeded,
246                                 String.valueOf(ScarabConstants.ISSUE_MAX_MOVE)
247                             );
248                             scarabR.setAlertMessage(msg);
249                             return;
250                         }
251                     }
252                     else
253                     {
254                         scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
255                     }
256                 }
257             }
258             else
259             {
260                 String JavaDoc template = data.getParameters()
261                     .getString(ScarabConstants.NEXT_TEMPLATE,
262                                "IssueList.vm");
263                 setTarget(data, template);
264             }
265         }
266     }
267
268     /**
269      * Saves the query string for the logged-in user, and performs the
270      * default action of {@link #doPerform}.
271      */

272     public void doSearch(RunData data, TemplateContext context)
273         throws Exception JavaDoc
274     {
275         setup(data, context);
276         String JavaDoc queryString = getQueryString(data);
277         user.setMostRecentQuery(queryString);
278
279         doPerform(data, context);
280     }
281
282     /**
283         Redirects to form to save the query. May redirect to Login page.
284     */

285     public void doRedirecttosavequery(RunData data, TemplateContext context)
286          throws Exception JavaDoc
287     {
288         setup(data, context);
289         if (data.getParameters().getString("refine") != null)
290         {
291             user.setMostRecentQuery(getQueryString(data));
292         }
293
294         if (scarabR.hasPermission(ScarabSecurity.USER__EDIT_PREFERENCES))
295         {
296             setTarget(data, "SaveQuery.vm");
297         }
298         else
299         {
300             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
301         }
302     }
303
304     public void doRedirecttocrossmodulelist(RunData data, TemplateContext context)
305          throws Exception JavaDoc
306     {
307         data.getParameters().setString("queryString", getQueryString(data));
308         setTarget(data, "IssueTypeList.vm");
309     }
310
311     /**
312         Saves query.
313     */

314     public void doSavequery(RunData data, TemplateContext context)
315          throws Exception JavaDoc
316     {
317         setup(data, context);
318         
319         if (!scarabR.hasPermission(ScarabSecurity.USER__EDIT_PREFERENCES))
320         {
321             scarabR.setAlertMessage(NO_PERMISSION_MESSAGE);
322             return;
323         }
324
325                
326         Module module = scarabR.getCurrentModule();
327         Query query = scarabR.getQuery();
328         Group queryGroup = intake.get("Query",
329                                       query.getQueryKey());
330
331         Field name = queryGroup.get("Name");
332         name.setRequired(true);
333         data.getParameters().setString("queryString", getQueryString(data));
334
335         if (intake.isAllValid())
336         {
337             queryGroup.setProperties(query);
338             query.setScarabUser(user);
339             MITList currentList = user.getCurrentMITList();
340             if (currentList == null)
341             {
342                 scarabR.setAlertMessage(L10NKeySet.NoIssueTypeList);
343                 return;
344             }
345             else
346             {
347                 //
348
// Get hold of all the attributes that apply to
349
// this list. We will have to copy them manually
350
// to the new list because MITList.copy() won't
351
// do it for us.
352
//
353
List JavaDoc commonAttributes =
354                     currentList.getCommonRModuleUserAttributes();
355                 
356                 // associate the query with a new list, the current
357
// implementation does not allow for multiple queries to
358
// work from the same MITList and this guarantees they
359
// will not accidently be linked.
360
currentList = currentList.copy();
361                 if (currentList.isModifiable())
362                 {
363                     currentList.setName(null);
364                 }
365                 
366                 //
367
// Copy the attributes from the original list
368
// to the new one.
369
//
370
for (Iterator JavaDoc iter = commonAttributes.iterator();
371                               iter.hasNext(); )
372                 {
373                     RModuleUserAttribute attr =
374                             (RModuleUserAttribute) iter.next();
375                     
376                     //
377
// When we copy the attribute, we don't actually
378
// want to keep the list ID because that refers
379
// to the old list rather than the new one. So
380
// we just clear it - when the list is saved the
381
// correct list ID will automatically be set for
382
// the attribute.
383
//
384
RModuleUserAttribute newAttr = attr.copy();
385                     newAttr.setListId(null);
386                     currentList.addRModuleUserAttribute(newAttr);
387                 }
388                 
389                 //
390
// Update the query to use the new MIT list.
391
//
392
query.setMITList(currentList);
393                 if (!currentList.isSingleModule())
394                 {
395                     query.setModule(null);
396                     query.setScopeId(Scope.PERSONAL__PK);
397                 }
398             }
399
400             ScarabUser[] userList =
401                 module.getUsers(ScarabSecurity.ITEM__APPROVE);
402             if (checkForDupes(query, user, module))
403             {
404                 scarabR.setAlertMessage(L10NKeySet.DuplicateQueryName);
405             }
406             else if (Scope.MODULE__PK.equals(query.getScopeId())
407                  && user.hasPermission(ScarabSecurity.ITEM__APPROVE, module)
408                  && (userList == null || userList.length == 0))
409             {
410                 L10NMessage msg = new L10NMessage(L10NKeySet.NoApproverAvailable, module.getName());
411                 scarabR.setAlertMessage(msg);
412             }
413             else
414             {
415                 try
416                 {
417                     query.saveAndSendEmail(user, module, context);
418                 }
419                 catch(Exception JavaDoc e)
420                 {
421                     L10NMessage msg = new L10NMessage(L10NKeySet.ExceptionGeneral,e);
422                     scarabR.setAlertMessage(msg);
423                 }
424                 scarabR.resetSelectedUsers();
425                 if (query.canEdit(user))
426                 {
427                     scarabR.setConfirmMessage(DEFAULT_MSG);
428                 }
429                 else
430                 {
431                     L10NMessage msg = new L10NMessage(L10NKeySet.NotifyPendingApproval,L10NKeySet.Query);
432                     scarabR.setInfoMessage(msg);
433                     //scarabR.setInfoMessage(
434
// l10n.format("NotifyPendingApproval",
435
// l10n.get("Query").toLowerCase()));
436
}
437                 setTarget(data, "QueryList.vm");
438             }
439         }
440         else
441         {
442             scarabR.setAlertMessage(ERROR_MESSAGE);
443         }
444     }
445
446     public boolean doEditqueryinfo(RunData data, TemplateContext context)
447         throws Exception JavaDoc
448     {
449         setup(data, context);
450         boolean success = false;
451
452         Module module = scarabR.getCurrentModule();
453         Query query = scarabR.getQuery();
454         Group queryGroup = intake.get("Query",
455                                       query.getQueryKey());
456         queryGroup.get("Name").setRequired(true);
457         if (intake.isAllValid())
458         {
459             queryGroup.setProperties(query);
460             if (checkForDupes(query, user, module))
461             {
462                 scarabR.setAlertMessage(L10NKeySet.DuplicateQueryName);
463             }
464             else
465             {
466                 query.saveAndSendEmail(user, module, context);
467                 success = true;
468                 if (query.canEdit(user))
469                 {
470                     scarabR.setConfirmMessage(L10NKeySet.QueryModified);
471                 }
472                 else
473                 {
474                     L10NMessage msg = new L10NMessage(L10NKeySet.NotifyPendingApproval,L10NKeySet.Query);
475                     scarabR.setInfoMessage(msg);
476                     //scarabR.setInfoMessage(
477
// l10n.format("NotifyPendingApproval",
478
// l10n.get("Query").toLowerCase()));
479
setTarget(data, data.getParameters().getString(
480                                     ScarabConstants.CANCEL_TEMPLATE));
481                 }
482
483             }
484         }
485         else
486         {
487             scarabR.setAlertMessage(ERROR_MESSAGE);
488         }
489         return success;
490     }
491
492     public void doPreparequery(RunData data, TemplateContext context)
493          throws Exception JavaDoc
494     {
495         setup(data, context);
496         Query query = scarabR.getQuery();
497         user.setCurrentMITList(query.getMITList());
498         /* TODO! It would be better if the query could be viewed or
499            edited without having to pass the query data via request parameters
500            as would be done with the code below, but it caused a few bugs like
501            losing users and maybe the mitlist, so revisit this later.
502         user.setMostRecentQuery(query.getValue());
503         */

504         user.setMostRecentQuery(getQueryString(data));
505         scarabR.resetSelectedUsers();
506     }
507
508     /**
509         Edits the stored query.
510     */

511     public void doEditstoredquery(RunData data, TemplateContext context)
512          throws Exception JavaDoc
513     {
514         setup(data, context);
515
516         Query query = scarabR.getQuery();
517         String JavaDoc newValue = getQueryString(data);
518         query.setValue(newValue);
519         query.saveAndSendEmail((ScarabUser)data.getUser(),
520                  scarabR.getCurrentModule(), context);
521         scarabR.resetSelectedUsers();
522         user.setMostRecentQuery(newValue);
523     }
524
525     /**
526         Runs the stored story.
527     */

528     public void doRunstoredquery(RunData data, TemplateContext context)
529          throws Exception JavaDoc
530     {
531         setup(data, context);
532         // Set current query to the stored query
533
Query query = scarabR.getQuery();
534         MITList mitList = query.getMITList();
535         user.setCurrentMITList(mitList);
536         if (mitList != null)
537         {
538             mitList.setScarabUser(user);
539         }
540         user.setMostRecentQuery(query.getValue());
541         
542         //
543
// Add 'sortColumn', 'sortPolarity' and 'resultsPerPage'
544
// to the RunData parameters. This ensures that when the
545
// user runs a saved query, the resulting issue list is
546
// displayed with that query's settings.
547
//
548
StringValueParser parser = new StringValueParser();
549         parser.parse(query.getValue(), '&', '=', true);
550         
551         if (parser.containsKey("resultsperpage")) {
552             data.getParameters().add("resultsperpage",
553                                      parser.getInt("resultsperpage"));
554         }
555         
556         if (parser.containsKey("searchsai")) {
557             data.getParameters().add("sortColumn",
558                                      parser.getInt("searchsai"));
559         }
560         
561         if (parser.containsKey("searchsp")) {
562             data.getParameters().add("sortPolarity",
563                                      parser.getString("searchsp"));
564         }
565
566         setTarget(data, "IssueList.vm");
567     }
568
569
570     /**
571      * This method handles clicking the Go button in the SearchNav.vm
572      * file. First it checks to see if the select box passed in a number
573      * or a string. If it is a number, then we run the stored query
574      * assuming the number is the query id. Else, we assume it is a
575      * string and that is our template to redirect to.
576      */

577     public void doSelectquery(RunData data, TemplateContext context)
578         throws Exception JavaDoc
579     {
580         setup(data, context);
581         String JavaDoc go = data.getParameters().getString("go");
582         
583
584         if (go != null && go.length() > 0)
585         {
586             // if the string is a number, then execute
587
// doRunstoredquery()
588
if (StringUtils.isNumeric(go))
589             {
590                 data.getParameters().setString("queryId", go);
591                 doRunstoredquery(data, context);
592             }
593             else if (go.startsWith("newQuery"))
594             {
595                 // do this to load last mitlist
596
user.getMostRecentQuery();
597                 if (go.endsWith("IT"))
598                 {
599                     user.setCurrentMITList(null);
600                 }
601                 // reset selected users map
602
scarabR.resetSelectedUsers();
603                 setTarget(data, user.getQueryTarget());
604             }
605             else if (go.equals("mostRecent"))
606             {
607                 setTarget(data, "IssueList.vm");
608             }
609             else if (go.equals("myIssuesThisModule"))
610             {
611                 Module module = user.getCurrentModule();
612                 user.setCurrentMITList(MITListManager
613                     .getSingleModuleAllIssueTypesList(module, user));
614
615                 String JavaDoc userId = user.getQueryKey();
616                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(26 + 2*userId.length());
617                 String JavaDoc query = sb.append("&user_list=").append(userId)
618                     .append("&user_attr_").append(userId).append("=any")
619                     .toString();
620                 user.setMostRecentQuery(query);
621                 setTarget(data, "IssueList.vm");
622             }
623             else if (go.equals("myIssuesAllModules"))
624             {
625                 user.setCurrentMITList(MITListManager.getAllModulesAllIssueTypesList(user));
626
627                 String JavaDoc userId = user.getQueryKey();
628                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(26 + 2*userId.length());
629                 String JavaDoc query = sb.append("&user_list=").append(userId)
630                     .append("&user_attr_").append(userId).append("=any")
631                     .toString();
632                 user.setMostRecentQuery(query);
633                 setTarget(data, "IssueList.vm");
634             }
635             else if (go.equals("quickSearch"))
636             {
637                 String JavaDoc searchString = data.getParameters().getString("searchString");
638                 if(searchString==null || searchString.equals(""))
639                 {
640                     scarabR.setAlertMessage(L10NKeySet.QueryParserError);
641                 }
642                 else
643                 {
644                     Module module = user.getCurrentModule();
645                     MITList mitList = MITListManager.getSingleModuleAllIssueTypesList(module,user);
646                     user.setCurrentMITList(mitList);
647                                
648                     Map JavaDoc attributeMap = new Hashtable JavaDoc();
649                     //List modules = mitList.getModules();
650
//for (int index=0; index < modules.size(); index++)
651
//{
652
// Module module = (Module)modules.get(index);
653
String JavaDoc moduleName = module.getName();
654                     List JavaDoc attributes = module.getAllAttributes();
655                     for( int aindex = 0; aindex < attributes.size(); aindex++)
656                     {
657                         Attribute attribute = (Attribute) attributes.get(aindex);
658                         AttributeType type = attribute.getAttributeType();
659                         String JavaDoc typeName = type.getName();
660                         String JavaDoc attributeName = attribute.getName();
661                         if(typeName.equals("string") || typeName.equals("long-string"))
662                         {
663                             if (attribute.isTextAttribute())
664                             {
665                                 Integer JavaDoc id = attribute.getAttributeId();
666                                 if(attributeMap.get(id) == null)
667                                 {
668                                     attributeMap.put(id,attribute);
669                                 }
670                             }
671                         }
672                     }
673                     //}
674

675                     quickSearch(searchString, attributeMap, user, context);
676                     user.setMostRecentQuery(getQueryString(data));
677                 }
678                 setTarget(data, "IssueList.vm");
679             }
680             else if (go.equals("privateQueries")
681                    ||go.equals("publicQueries"))
682             {
683                 setTarget(data,"QueryList.vm");
684             }
685             else
686             {
687                 setTarget(data, go);
688             }
689             if (go.equals("myIssues") || go.equals("mostRecent"))
690             {
691                 IteratorWithSize searchResults = null;
692                 try
693                 {
694                     searchResults = scarabR.getCurrentSearchResults();
695                 }
696                 catch (java.lang.IllegalArgumentException JavaDoc e)
697                 {
698                     // Swallow this exception.
699
Log.get().debug("", e);
700                 }
701                 if (searchResults != null && searchResults.size() > 0)
702                 {
703                     context.put("issueList", searchResults);
704                 }
705             }
706         }
707         else
708         {
709             // set the next template
710
String JavaDoc nextTemplate = data.getParameters()
711                 .getString(ScarabConstants.NEXT_TEMPLATE,
712                 Turbine.getConfiguration()
713                            .getString("template.homepage", "Index.vm"));
714             setTarget(data, nextTemplate);
715         }
716     }
717
718     /**
719      * @param attributeMap
720      * @return
721      */

722     private void quickSearch(String JavaDoc searchString, Map JavaDoc attributeMap, ScarabUser user, TemplateContext context)
723     {
724         String JavaDoc query;
725
726         String JavaDoc userId = user.getQueryKey();
727
728         String JavaDoc queryStart = "&user_attr_"+userId+"=any"
729                          + "&intake-grp=attv"
730                          + "&intake-grp=search"
731                          + "&searchsp=asc"
732                          + "&searchtype=advanced";
733
734         final String JavaDoc queryEnd = "&searchsctoi=0"
735                               + "&resultsperpage=25"
736                               + "&searchscfoi=0";
737
738         Iterator JavaDoc iter = attributeMap.keySet().iterator();
739         query = queryStart;
740         while(iter.hasNext())
741         {
742             Integer JavaDoc id = (Integer JavaDoc)iter.next();
743             query += "&attv__"+id+"val="+searchString;
744         }
745         
746         query += queryEnd;
747
748         user.setMostRecentQuery(query.toLowerCase());
749         
750         IteratorWithSize searchResults = null;
751         try
752         {
753             searchResults = scarabR.getCurrentSearchResults(true);
754         }
755         catch (java.lang.IllegalArgumentException JavaDoc e)
756         {
757             // Swallow this exception.
758
Log.get().debug("", e);
759         }
760         if (searchResults != null && searchResults.size() > 0)
761         {
762             context.put("issueList", searchResults);
763         }
764     }
765
766     /**
767         redirects to AdvancedQuery.
768     */

769     public void doRefinequery(RunData data, TemplateContext context)
770          throws Exception JavaDoc
771     {
772         context.put("refine", "true");
773         setTarget(data, "AdvancedQuery.vm");
774     }
775
776
777     /**
778         Overrides base class.
779     */

780     public void doDone(RunData data, TemplateContext context)
781         throws Exception JavaDoc
782     {
783         boolean success = doEditqueryinfo(data, context);
784         if (success)
785         {
786             doEditstoredquery(data, context);
787             doCancel(data, context);
788         }
789     }
790
791     /**
792      * @return The search string used to perform the query. (Does
793      * <i>not</i> refer to the CGI context of the term "query
794      * string".)
795      */

796     public static String JavaDoc getQueryString(RunData data) throws Exception JavaDoc
797     {
798         String JavaDoc queryString = data.getParameters().getString("queryString");
799         if (queryString == null)
800         {
801             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
802             Object JavaDoc[] keys = data.getParameters().getKeys();
803             for (int i =0; i<keys.length; i++)
804             {
805                 String JavaDoc key = keys[i].toString();
806                 if (key.startsWith("attv") || key.startsWith("search")
807                     || key.startsWith("intake") || key.startsWith("user_attr")
808                     || key.startsWith("user_list") || key.startsWith("results")
809                     || "format".equalsIgnoreCase(key))
810                 {
811                     String JavaDoc[] values = data.getParameters().getStrings(key);
812                     for (int j=0; j<values.length; j++)
813                     {
814                         String JavaDoc value = values[j];
815                         if (StringUtils.isNotEmpty(value))
816                         {
817                             buf.append('&').append(key);
818                             buf.append('=').append(ScarabUtil.urlEncode(value));
819                         }
820                     }
821                 }
822             }
823
824             queryString = (buf.length() == 0
825                            ? ((ScarabUser)data.getUser()).getMostRecentQuery()
826                            : buf.toString());
827         }
828         return queryString.toLowerCase();
829     }
830         
831     /**
832        Check for duplicate query names.
833        A user cannot create a personal query with the same name as another one
834        of their personal queries.
835        A user cannot create a module-level query with the same name
836        as another module-level query in the same module.
837     */

838     private boolean checkForDupes(Query query, ScarabUser user, Module module)
839         throws Exception JavaDoc
840     {
841         boolean areThereDupes = false;
842         List JavaDoc prevQueries = new ArrayList JavaDoc();
843         if (query.getScopeId().equals(Scope.MODULE__PK))
844         {
845             prevQueries.addAll(QueryPeer.getModuleQueries(module));
846         }
847         else
848         {
849             // Add personal queries only, not all module-level queries created
850
// by this user.
851
for (Iterator JavaDoc i = QueryPeer.getUserQueries(user).iterator(); i.hasNext(); )
852             {
853                 Query q = (Query)i.next();
854                 if (q.getModule() == null)
855                 {
856                     prevQueries.add(q);
857                 }
858             }
859         }
860         if (prevQueries != null && !prevQueries.isEmpty())
861         {
862             Long JavaDoc pk = query.getQueryId();
863             String JavaDoc name = query.getName();
864             for (Iterator JavaDoc i = prevQueries.iterator();
865                  i.hasNext() && !areThereDupes;)
866             {
867                 Query q = (Query)i.next();
868                 areThereDupes = (pk == null || !pk.equals(q.getQueryId())) &&
869                     name.trim().toLowerCase().equals(
870                         q.getName().trim().toLowerCase());
871             }
872         }
873         return areThereDupes;
874     }
875
876     /**
877         Retrieves list of all issue id's and puts in the context.
878     */

879     private List JavaDoc getAllIssueIds(RunData data)
880     {
881         List JavaDoc newIssueIdList = new ArrayList JavaDoc();
882         ParameterParser pp = data.getParameters();
883         String JavaDoc[] allIssueIds = pp.getStrings("all_issue_ids");
884         if (allIssueIds != null)
885         {
886             while(pp.containsKey("issue_ids"))
887             {
888                 pp.remove("issue_ids");
889             }
890             for (int i =0; i< allIssueIds.length; i++)
891             {
892                 pp.add("issue_ids", allIssueIds[i]);
893                 newIssueIdList.add(allIssueIds[i]);
894             }
895         }
896         return newIssueIdList;
897     }
898
899     /**
900         Retrieves list of selected issue id's and puts in the context.
901     */

902     private List JavaDoc getSelected(RunData data)
903     {
904         List JavaDoc newIssueIdList = new ArrayList JavaDoc();
905         ParameterParser pp = data.getParameters();
906         String JavaDoc[] selectedIds = pp.getStrings("issue_ids");
907         if (selectedIds != null)
908         {
909             while(pp.containsKey("issue_ids"))
910             {
911                 pp.remove("issue_ids");
912             }
913             for (int i=0; i<selectedIds.length; i++)
914             {
915                 pp.add("issue_ids", selectedIds[i]);
916                 newIssueIdList.add(selectedIds[i]);
917             }
918         }
919         return newIssueIdList;
920     }
921
922     public void doGotoeditlist(RunData data, TemplateContext context)
923         throws Exception JavaDoc
924     {
925         setup(data, context);
926         Map JavaDoc userMap = user.getSelectedUsersMap();
927         if (userMap == null || userMap.size() == 0)
928         {
929             userMap = new HashMap JavaDoc();
930             loadUsersFromUserList(data, userMap);
931         }
932         data.getParameters().setString(ScarabConstants.CANCEL_TEMPLATE,
933                                        getCurrentTemplate(data));
934         user.setMostRecentQuery(getQueryString(data));
935         IssueSearch search = scarabR.getPopulatedSearch();
936         if (search != null)
937         {
938             setTarget(data, "UserList.vm");
939         }
940     }
941
942     /**
943      * Adds users from temporary working list.
944      */

945     public void doAddusers(RunData data, TemplateContext context)
946         throws Exception JavaDoc
947     {
948         setup(data, context);
949         
950         Map JavaDoc userMap = user.getSelectedUsersMap();
951         if (userMap == null)
952         {
953             userMap = new HashMap JavaDoc();
954         }
955         String JavaDoc[] userIds = params.getStrings(ADD_USER);
956         if (userIds != null && userIds.length > 0)
957         {
958             for (int i =0; i<userIds.length; i++)
959             {
960                 String JavaDoc userId = userIds[i];
961                 String JavaDoc[] attrIds = params.getStrings("user_attr_" + userId);
962                 if (attrIds != null)
963                 {
964                     for (int j=0; j<attrIds.length; j++)
965                     {
966                         addAttributeToMap(userMap, userId, attrIds[j], context);
967                     }
968                 }
969             }
970             user.setSelectedUsersMap(userMap);
971             scarabR.setConfirmMessage(L10NKeySet.SelectedUsersWereAdded);
972         }
973         else
974         {
975             scarabR.setAlertMessage(L10NKeySet.NoUsersSelected);
976         }
977     }
978
979
980     /**
981         Adds user to the search form.
982     */

983     public void doAdduserbyusername(RunData data, TemplateContext context)
984         throws Exception JavaDoc
985     {
986         setup(data, context);
987
988         String JavaDoc userName = params.getString(ADD_USER_BY_USERNAME);
989         String JavaDoc attrId = params.getString("add_user_attr");
990
991         Map JavaDoc userMap = user.getSelectedUsersMap();
992         if (userMap == null || userMap.size() == 0)
993         {
994             userMap = new HashMap JavaDoc();
995             loadUsersFromUserList(data, userMap);
996         }
997
998        ScarabUser newUser = scarabR.getUserByUserName(userName);
999        boolean success = false;
1000       // we are only interested in users that can be assignees
1001
if (newUser != null)
1002       {
1003           MITList mitList = user.getCurrentMITList();
1004           List JavaDoc modules = mitList.getModules();
1005           if (ANY.equals(attrId))
1006           {
1007               success = false;
1008               // check that the user has at least one applicable attribute
1009
for (Iterator JavaDoc i = mitList.getCommonUserAttributes().iterator();
1010                    i.hasNext() && !success;)
1011               {
1012                   success = newUser.hasPermission(
1013                       ((Attribute)i.next()).getPermission(), modules);
1014               }
1015               if (!success)
1016               {
1017                   // check created by
1018
success = newUser.hasPermission(ScarabSecurity.ISSUE__ENTER,
1019                                                   modules);
1020               }
1021           }
1022           else if (CREATED_BY.equals(attrId))
1023           {
1024               success = newUser.hasPermission(ScarabSecurity.ISSUE__ENTER,
1025                                               modules);
1026           }
1027           else
1028           {
1029               try
1030               {
1031                   Attribute attribute =
1032                       scarabR.getAttribute(new Integer JavaDoc(attrId));
1033                   success = newUser.hasPermission(attribute.getPermission(),
1034                                                   modules);
1035               }
1036               catch (Exception JavaDoc e)
1037               {
1038                   // don't allow adding the user
1039
success = false;
1040                   Log.get().error("Error trying to get user ," + userName +
1041                       ", for a query. Attribute id = " + attrId, e);
1042               }
1043           }
1044       }
1045
1046       if (success)
1047       {
1048           String JavaDoc userId = newUser.getUserId().toString();
1049           addAttributeToMap(userMap, userId, attrId, context);
1050           user.setSelectedUsersMap(userMap);
1051           scarabR.setConfirmMessage(L10NKeySet.SelectedUsersWereAdded);
1052       }
1053       else
1054       {
1055           scarabR.setAlertMessage(L10NKeySet.UserNotPossibleAssignee);
1056       }
1057    }
1058
1059    private void addAttributeToMap(Map JavaDoc userMap, String JavaDoc userId, String JavaDoc attrId,
1060                                   TemplateContext context)
1061    {
1062        ScarabRequestTool scarabR = getScarabRequestTool(context);
1063        ScarabLocalizationTool l10n = getLocalizationTool(context);
1064        List JavaDoc attrIds = (List JavaDoc)userMap.get(userId);
1065        if (attrIds == null)
1066        {
1067            attrIds = new ArrayList JavaDoc(3);
1068            userMap.put(userId, attrIds);
1069        }
1070
1071        if (ANY.equals(attrId))
1072        {
1073            if (!attrIds.isEmpty())
1074            {
1075                scarabR.setInfoMessage(L10NKeySet.AnyHasReplacedPreviousChoices);
1076            }
1077            attrIds.clear();
1078        }
1079
1080        boolean isNew = true;
1081        for (Iterator JavaDoc i = attrIds.iterator(); i.hasNext() && isNew;)
1082        {
1083            Object JavaDoc oldAttrId = i.next();
1084            isNew = !ANY.equals(oldAttrId) && !oldAttrId.equals(attrId);
1085        }
1086        
1087        if (isNew)
1088        {
1089            attrIds.add(attrId);
1090        }
1091        else
1092        {
1093            scarabR.setInfoMessage(L10NKeySet.ChoiceAlreadyAccountedAny);
1094        }
1095    }
1096
1097    /**
1098     * Removes users from temporary working list.
1099     */

1100    public void doRemoveusers(RunData data, TemplateContext context)
1101        throws Exception JavaDoc
1102    {
1103        setup(data, context);
1104         
1105        Map JavaDoc userMap = user.getSelectedUsersMap();
1106        if (userMap == null || userMap.size() == 0)
1107        {
1108            userMap = new HashMap JavaDoc();
1109            loadUsersFromUserList(data, userMap);
1110        }
1111        
1112        String JavaDoc[] userAttrIds = params.getStrings(SELECTED_USER);
1113        if (userAttrIds != null && userAttrIds.length > 0)
1114        {
1115            for (int i =0; i<userAttrIds.length; i++)
1116            {
1117                String JavaDoc userAttrId = userAttrIds[i];
1118                int delimPos = userAttrId.indexOf('_');
1119                String JavaDoc userId = userAttrId.substring(0, delimPos);
1120                List JavaDoc currentAttrIds = (List JavaDoc)userMap.get(userId);
1121                if (currentAttrIds.size() == 1)
1122                {
1123                    userMap.remove(userId);
1124                }
1125                else
1126                {
1127                    currentAttrIds.remove(userAttrId.substring(delimPos+1));
1128                }
1129            }
1130            user.setSelectedUsersMap(userMap);
1131            scarabR.setConfirmMessage(L10NKeySet.SelectedUsersWereRemoved);
1132        }
1133        else
1134        {
1135            scarabR.setAlertMessage(L10NKeySet.NoUsersSelected);
1136        }
1137    }
1138
1139    /**
1140     * Changes the user attribute a user is associated with.
1141     */

1142    public void doUpdateusers(RunData data, TemplateContext context)
1143        throws Exception JavaDoc
1144    {
1145        setup(data, context);
1146        
1147        Map JavaDoc userMap = user.getSelectedUsersMap();
1148        
1149        String JavaDoc[] userAttrIds = params.getStrings(SELECTED_USER);
1150        if (userAttrIds != null && userAttrIds.length > 0)
1151        {
1152            for (int i =0; i<userAttrIds.length; i++)
1153            {
1154                String JavaDoc userAttrId = userAttrIds[i];
1155                int delimPos = userAttrId.indexOf('_');
1156                String JavaDoc userId = userAttrId.substring(0, delimPos);
1157                String JavaDoc oldAttrId = userAttrId.substring(delimPos+1);
1158                String JavaDoc newAttrId = params
1159                    .getString("user_attr_" + userAttrId);
1160                if (!oldAttrId.equals(newAttrId))
1161                {
1162                    List JavaDoc currentAttrIds = (List JavaDoc)userMap.get(userId);
1163                    if (ANY.equals(newAttrId))
1164                    {
1165                        currentAttrIds.clear();
1166                        currentAttrIds.add(ANY);
1167                    }
1168                    else
1169                    {
1170                        for (int j=currentAttrIds.size()-1; j>=0; j--)
1171                        {
1172                            if (currentAttrIds.get(j).equals(oldAttrId))
1173                            {
1174                                currentAttrIds.set(j, newAttrId);
1175                                break;
1176                            }
1177                        }
1178                    }
1179                }
1180            }
1181            user.setSelectedUsersMap(userMap);
1182            scarabR.setConfirmMessage(L10NKeySet.SelectedUsersWereModified);
1183        }
1184        else
1185        {
1186            scarabR.setAlertMessage(L10NKeySet.NoUsersSelected);
1187        }
1188    }
1189
1190    /**
1191     * In the case of a saved query, puts the saved query's users
1192     * Into the selected users map
1193     */

1194    public void loadUsersFromUserList(RunData data, Map JavaDoc userMap)
1195        throws Exception JavaDoc
1196    {
1197        ParameterParser params = data.getParameters();
1198        String JavaDoc[] userList = params.getStrings(USER_LIST);
1199        if (userList !=null && userList.length > 0)
1200        {
1201            for (int i =0;i<userList.length;i++)
1202            {
1203                String JavaDoc userId = userList[i];
1204                String JavaDoc[] attrIds = params.getStrings("user_attr_" + userId);
1205                if (attrIds != null)
1206                {
1207                    for (int j=0; j<attrIds.length; j++)
1208                    {
1209                        addAttributeToMap(userMap, userId, attrIds[j],
1210                                          getTemplateContext(data));
1211                    }
1212                }
1213            }
1214            ((ScarabUser)data.getUser()).setSelectedUsersMap(userMap);
1215        }
1216    }
1217
1218    public void doSetquerytarget(RunData data, TemplateContext context)
1219        throws Exception JavaDoc
1220    {
1221        setup(data, context);
1222        
1223        MITList mitlist = user.getCurrentMITList();
1224        if (mitlist != null && mitlist.isSingleModuleIssueType())
1225        {
1226            user.setSingleIssueTypeQueryTarget(
1227                mitlist.getIssueType(), data.getTarget());
1228        }
1229        else
1230        {
1231        
1232            if (mitlist == null)
1233            {
1234                scarabR.setAlertMessage(L10NKeySet.NoIssueTypeList);
1235            }
1236            else
1237            {
1238                scarabR.setAlertMessage(L10NKeySet.IssueTypeListMoreThanOne);
1239            }
1240            
1241
1242            Log.get().warn(
1243                "Issue type list did not contain one and only one element.");
1244        }
1245    }
1246    private void setup(RunData data, TemplateContext context) throws Exception JavaDoc{
1247        l10n = getLocalizationTool(context);
1248        scarabR = getScarabRequestTool(context);
1249        intake = getIntakeTool(context);
1250        params = data.getParameters();
1251        user = (ScarabUser)data.getUser();
1252    }
1253        
1254}
1255
Popular Tags