KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > tigris > scarab > om > MITList


1 package org.tigris.scarab.om;
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.Set JavaDoc;
50 import java.util.HashSet JavaDoc;
51 import java.util.List JavaDoc;
52 import java.util.ArrayList JavaDoc;
53 import java.util.Iterator JavaDoc;
54 import java.util.Collections JavaDoc;
55 import java.sql.Connection JavaDoc;
56 import org.apache.torque.om.Persistent;
57 import org.apache.torque.util.Criteria;
58 import org.apache.torque.TorqueException;
59 import org.apache.torque.TorqueRuntimeException;
60 import org.tigris.scarab.services.security.ScarabSecurity;
61 import org.tigris.scarab.util.Log;
62
63 /**
64  * A class representing a list (not List) of MITListItems. MIT stands for
65  * Module and IssueType. This class contains corresponding methods to many
66  * in Module which take a single IssueType. for example
67  * module.getAttributes(issueType) is replaced with
68  * mitList.getCommonAttributes() in cases where several modules and issuetypes
69  * are involved.
70  *
71  * @author <a HREF="mailto:jon@latchkey.com">Jon S. Stevens</a>
72  * @author <a HREF="mailto:jmcnally@collab.net">John McNally</a>
73  * @version $Id: MITList.java 9689 2005-05-14 16:03:15Z jorgeuriarte $
74  */

75 public class MITList
76     extends org.tigris.scarab.om.BaseMITList
77     implements Persistent
78 {
79     /**
80      * A local reference to the user.
81      */

82     private ScarabUser aScarabUser;
83
84     private List JavaDoc itemsScheduledForDeletion;
85
86     /**
87      * Cache the expanded list because it is widely used and unlikely
88      * to change after initialization.
89      */

90     private List JavaDoc expandedList = null;
91
92     /**
93      * Whether this list represents everything the user can query.
94      */

95     private boolean isAllMITs = false;
96
97     public int size()
98     {
99         int size = 0;
100         List JavaDoc items = getExpandedMITListItems();
101         if (items != null)
102         {
103             size = items.size();
104         }
105         return size;
106     }
107
108     /**
109      * tests if the list is empty
110      *
111      * @return true if the list is empty, otherwise false
112      */

113     public boolean isEmpty()
114     {
115         boolean empty = true;
116         List JavaDoc items = getExpandedMITListItems();
117         if (items != null)
118         {
119             empty = items.isEmpty();
120         }
121         return empty;
122     }
123
124     /**
125      * asserts that the list is not empty
126      *
127      * @throws IllegalStateException if the list is empty
128      */

129     private void assertNotEmpty()
130     {
131         if (isEmpty())
132         {
133             throw new IllegalStateException JavaDoc("method should not be called on an empty list."); //EXCEPTION
134
}
135     }
136
137     public Iterator JavaDoc iterator()
138     {
139         Iterator JavaDoc i = null;
140         List JavaDoc items = getExpandedMITListItems();
141         if (items == null)
142         {
143             i = Collections.EMPTY_LIST.iterator();
144         }
145         else
146         {
147             i = new ItemsIterator(items.iterator());
148         }
149         return i;
150     }
151
152     public boolean contains(MITListItem item)
153     {
154         boolean result = false;
155         for (Iterator JavaDoc i = iterator(); i.hasNext() && !result;)
156         {
157             result = i.next().equals(item);
158         }
159         return result;
160     }
161
162     public class ItemsIterator implements Iterator JavaDoc
163     {
164         private Iterator JavaDoc i;
165         private Object JavaDoc currentObject;
166         private ItemsIterator(Iterator JavaDoc i)
167         {
168             this.i = i;
169         }
170
171         public boolean hasNext()
172         {
173             return i.hasNext();
174         }
175
176         public Object JavaDoc next()
177         {
178             currentObject = i.next();
179             return currentObject;
180         }
181
182         public void remove()
183         {
184             List JavaDoc rawList = null;
185             try
186             {
187                 rawList = getMITListItems();
188             }
189             catch (TorqueException e)
190             {
191                 throw new TorqueRuntimeException(e); //EXCEPTION
192
}
193
194             if (rawList.contains(currentObject))
195             {
196                 rawList.remove(currentObject);
197                 i.remove();
198                 expandedList = null;
199             }
200             else
201             {
202                 throw new UnsupportedOperationException JavaDoc(
203                     "Removing items "
204                         + "from a list containing wildcards is not supported."); //EXCEPTION
205
}
206         }
207     }
208
209     /**
210      * Alias for getModifiable()
211      *
212      * @return a <code>boolean</code> value
213      */

214     public boolean isModifiable()
215     {
216         return getModifiable();
217     }
218
219     public boolean isAnonymous()
220     {
221         return !isNew() && getName() == null;
222     }
223
224     /**
225      * Makes a copy of this object.
226      * It creates a new object filling in the simple attributes.
227      * It then fills all the association collections and sets the
228      * related objects to isNew=true.
229      */

230     public MITList copy() throws TorqueException
231     {
232         MITList copyObj = new MITList();
233         copyObj.setName(getName());
234         copyObj.setActive(getActive());
235         copyObj.setModifiable(getModifiable());
236         copyObj.setUserId(getUserId());
237
238         List JavaDoc v = getMITListItems();
239         for (int i = 0; i < v.size(); i++)
240         {
241             MITListItem obj = (MITListItem) v.get(i);
242             copyObj.addMITListItem(obj.copy());
243         }
244
245         return copyObj;
246     }
247
248     /**
249      * Creates a new MITList containing only those items from this list
250      * for which the searcher has the given permission.
251      *
252      * @param permission a <code>String</code> value
253      * @param searcher a <code>ScarabUser</code> value
254      * @return a <code>MITList</code> value
255      */

256     public MITList getPermittedSublist(String JavaDoc permission, ScarabUser user)
257         throws Exception JavaDoc
258     {
259         String JavaDoc[] perms = { permission };
260         return getPermittedSublist(perms, user);
261     }
262
263     /**
264      * Creates a new MITList containing only those items from this list
265      * for which the searcher has at least one of the permission.
266      *
267      * @param permission a <code>String</code> value
268      * @param searcher a <code>ScarabUser</code> value
269      * @return a <code>MITList</code> value
270      */

271     public MITList getPermittedSublist(String JavaDoc[] permissions, ScarabUser user)
272         throws Exception JavaDoc
273     {
274         MITList sublist = new MITList();
275         ScarabUser userB = getScarabUser();
276         if (userB != null)
277         {
278             sublist.setScarabUser(userB);
279         }
280         List JavaDoc items = getExpandedMITListItems();
281         sublist.isAllMITs = this.isAllMITs;
282         Module[] validModules = user.getModules(permissions);
283
284         Set JavaDoc moduleIds = new HashSet JavaDoc();
285         for (int j = 0; j < validModules.length; j++)
286         {
287             moduleIds.add(validModules[j].getModuleId());
288         }
289
290         for (Iterator JavaDoc i = items.iterator(); i.hasNext();)
291         {
292             MITListItem item = (MITListItem) i.next();
293             if (moduleIds.contains(item.getModuleId()))
294             {
295                 // use a copy of the item here to avoid changing the the
296
// list_id of the original
297
sublist.addMITListItem(item.copy());
298             }
299         }
300
301         return sublist;
302     }
303
304     public MITListItem getFirstItem()
305     {
306         MITListItem i = null;
307         List JavaDoc items = getExpandedMITListItems();
308         if (items != null)
309         {
310             i = (MITListItem) items.get(0);
311         }
312         return i;
313     }
314
315     public boolean isSingleModuleIssueType()
316     {
317         return size() == 1 && getFirstItem().isSingleModuleIssueType();
318     }
319
320     public boolean isSingleModule()
321     {
322         List JavaDoc ids = getModuleIds();
323         return ids.size() == 1;
324     }
325
326     public boolean isSingleIssueType()
327     {
328         List JavaDoc ids = getIssueTypeIds();
329         return ids.size() == 1;
330     }
331
332     public Module getModule() throws Exception JavaDoc
333     {
334         if (!isSingleModule())
335         {
336             throw new IllegalStateException JavaDoc(
337                 "method should not be called on"
338                     + " a list including more than one module."); //EXCEPTION
339
}
340         return getModule(getFirstItem());
341     }
342
343     public IssueType getIssueType() throws Exception JavaDoc
344     {
345         if (!isSingleIssueType())
346         {
347             throw new IllegalStateException JavaDoc(
348                 "method should not be called on"
349                     + " a list including more than one issue type."); //EXCEPTION
350
}
351         return getFirstItem().getIssueType();
352     }
353
354     Module getModule(MITListItem item) throws Exception JavaDoc
355     {
356         Module module = null;
357         if (item.getModuleId() == null)
358         {
359             module = getScarabUser().getCurrentModule();
360         }
361         else
362         {
363             module = item.getModule();
364         }
365         return module;
366     }
367
368     /**
369      * Declares an association between this object and a ScarabUser object
370      *
371      * @param v
372      */

373     public void setScarabUser(ScarabUser v) throws TorqueException
374     {
375         if (v == null)
376         {
377             throw new IllegalArgumentException JavaDoc("cannot set user to null."); //EXCEPTION
378
}
379
380         super.setScarabUser(v);
381         aScarabUser = v;
382         expandedList = null;
383     }
384
385     public ScarabUser getScarabUser() throws TorqueException
386     {
387         ScarabUser user = null;
388         if (aScarabUser == null)
389         {
390             user = super.getScarabUser();
391         }
392         else
393         {
394             user = aScarabUser;
395         }
396         return user;
397     }
398
399     public List JavaDoc getCommonAttributes(boolean activeOnly) throws Exception JavaDoc
400     {
401         List JavaDoc matchingAttributes = new ArrayList JavaDoc();
402         MITListItem item = getFirstItem();
403
404         List JavaDoc rmas = getModule(item).getRModuleAttributes(item.getIssueType());
405         for (Iterator JavaDoc i = rmas.iterator(); i.hasNext();)
406         {
407             RModuleAttribute rma = (RModuleAttribute) i.next();
408             Attribute att = rma.getAttribute();
409             if ((!activeOnly || rma.getActive())
410                 && (size() == 1 || isCommon(att, activeOnly)))
411             {
412                 matchingAttributes.add(att);
413             }
414         }
415
416         return matchingAttributes;
417     }
418
419     public List JavaDoc getCommonAttributes() throws Exception JavaDoc
420     {
421         return getCommonAttributes(true);
422     }
423
424     /**
425      * Checks all items to see if they contain the attribute.
426      *
427      * @param attribute an <code>Attribute</code> value
428      * @return a <code>boolean</code> value
429      */

430     public boolean isCommon(Attribute attribute, boolean activeOnly)
431         throws Exception JavaDoc
432     {
433         Criteria crit = new Criteria();
434         addToCriteria(
435             crit,
436             RModuleAttributePeer.MODULE_ID,
437             RModuleAttributePeer.ISSUE_TYPE_ID);
438         crit.add(RModuleAttributePeer.ATTRIBUTE_ID, attribute.getAttributeId());
439         if (activeOnly)
440         {
441             crit.add(RModuleAttributePeer.ACTIVE, true);
442         }
443
444         return size() == RModuleAttributePeer.count(crit);
445
446         /*
447         List rmas = RModuleAttributePeer.doSelect(crit);
448         boolean common = true;
449         for (Iterator items = iterator(); items.hasNext() && common;)
450         {
451             MITListItem compareItem = (MITListItem)items.next();
452             boolean foundRma = false;
453             for (Iterator rmaIter = rmas.iterator();
454                  rmaIter.hasNext() && !foundRma;)
455             {
456                 RModuleAttribute rma = (RModuleAttribute)rmaIter.next();
457                 foundRma = (!activeOnly || rma.getActive()) &&
458                     rma.getModuleId().equals(compareItem.getModuleId()) &&
459                     rma.getIssueTypeId().equals(compareItem.getIssueTypeId());
460             }
461             common = foundRma;
462         }
463         return common;
464         */

465     }
466
467     public boolean isCommon(Attribute attribute) throws Exception JavaDoc
468     {
469         return isCommon(attribute, true);
470     }
471
472     public List JavaDoc getCommonNonUserAttributes() throws Exception JavaDoc
473     {
474         assertNotEmpty();
475
476         List JavaDoc matchingAttributes = new ArrayList JavaDoc();
477         MITListItem item = getFirstItem();
478
479         List JavaDoc rmas = getModule(item).getRModuleAttributes(item.getIssueType());
480         Iterator JavaDoc i = rmas.iterator();
481         while (i.hasNext())
482         {
483             RModuleAttribute rma = (RModuleAttribute) i.next();
484             Attribute att = rma.getAttribute();
485             if (!att.isUserAttribute() && rma.getActive() && isCommon(att))
486             {
487                 matchingAttributes.add(att);
488             }
489         }
490
491         return matchingAttributes;
492     }
493
494     public List JavaDoc getCommonOptionAttributes() throws Exception JavaDoc
495     {
496         assertNotEmpty();
497
498         List JavaDoc matchingAttributes = new ArrayList JavaDoc();
499         MITListItem item = getFirstItem();
500
501         List JavaDoc rmas = getModule(item).getRModuleAttributes(item.getIssueType());
502         Iterator JavaDoc i = rmas.iterator();
503         while (i.hasNext())
504         {
505             RModuleAttribute rma = (RModuleAttribute) i.next();
506             Attribute att = rma.getAttribute();
507             if (att.isOptionAttribute() && rma.getActive() && isCommon(att))
508             {
509                 matchingAttributes.add(att);
510             }
511         }
512
513         return matchingAttributes;
514     }
515
516     /**
517      * gets a list of all of the User Attributes common to all modules in
518      * the list.
519      */

520     public List JavaDoc getCommonUserAttributes(boolean activeOnly) throws Exception JavaDoc
521     {
522         List JavaDoc attributes = null;
523         if (isSingleModuleIssueType())
524         {
525             attributes =
526                 getModule().getUserAttributes(getIssueType(), activeOnly);
527         }
528         else
529         {
530             List JavaDoc matchingAttributes = new ArrayList JavaDoc();
531             MITListItem item = getFirstItem();
532             List JavaDoc rmas =
533                 getModule(item).getRModuleAttributes(
534                     item.getIssueType(),
535                     activeOnly,
536                     Module.USER);
537             Iterator JavaDoc i = rmas.iterator();
538             while (i.hasNext())
539             {
540                 RModuleAttribute rma = (RModuleAttribute) i.next();
541                 Attribute att = rma.getAttribute();
542                 if ((!activeOnly || rma.getActive())
543                     && isCommon(att, activeOnly))
544                 {
545                     matchingAttributes.add(att);
546                 }
547             }
548             attributes = matchingAttributes;
549         }
550         return attributes;
551     }
552
553     public List JavaDoc getCommonUserAttributes() throws Exception JavaDoc
554     {
555         return getCommonUserAttributes(false);
556     }
557
558     /**
559      * potential assignee must have at least one of the permissions
560      * for the user attributes in all the modules.
561      */

562     public List JavaDoc getPotentialAssignees(boolean includeCommitters)
563         throws Exception JavaDoc
564     {
565         List JavaDoc users = new ArrayList JavaDoc();
566         List JavaDoc perms = getUserAttributePermissions();
567         if (includeCommitters && !perms.contains(ScarabSecurity.ISSUE__ENTER))
568         {
569             perms.add(ScarabSecurity.ISSUE__ENTER);
570         }
571         if (isSingleModule())
572         {
573             ScarabUser[] userArray = getModule().getUsers(perms);
574             for (int i = 0; i < userArray.length; i++)
575             {
576                 users.add(userArray[i]);
577             }
578         }
579         else
580         {
581             MITListItem item = getFirstItem();
582             ScarabUser[] userArray = getModule(item).getUsers(perms);
583             List JavaDoc modules = getModules();
584             for (int i = 0; i < userArray.length; i++)
585             {
586                 boolean validUser = false;
587                 ScarabUser user = userArray[i];
588                 for (Iterator JavaDoc j = perms.iterator(); j.hasNext() && !validUser;)
589                 {
590                     validUser = user.hasPermission((String JavaDoc) j.next(), modules);
591                 }
592                 if (validUser)
593                 {
594                     users.add(user);
595                 }
596             }
597         }
598         return users;
599     }
600
601     /**
602      * gets a list of permissions associated with the User Attributes
603      * that are active for this Module.
604      */

605     public List JavaDoc getUserAttributePermissions() throws Exception JavaDoc
606     {
607         List JavaDoc userAttrs = getCommonUserAttributes();
608         List JavaDoc permissions = new ArrayList JavaDoc();
609         for (int i = 0; i < userAttrs.size(); i++)
610         {
611             String JavaDoc permission = ((Attribute) userAttrs.get(i)).getPermission();
612             if (!permissions.contains(permission))
613             {
614                 permissions.add(permission);
615             }
616         }
617         return permissions;
618     }
619
620     public List JavaDoc getCommonRModuleUserAttributes() throws Exception JavaDoc
621     {
622         List JavaDoc matchingRMUAs = new ArrayList JavaDoc();
623         List JavaDoc rmuas = getSavedRMUAs();
624         Iterator JavaDoc i = rmuas.iterator();
625         ScarabUser user = getScarabUser();
626         while (i.hasNext())
627         {
628             RModuleUserAttribute rmua = (RModuleUserAttribute) i.next();
629             Attribute att = rmua.getAttribute();
630             if (isCommon(att, false))
631             {
632                 matchingRMUAs.add(rmua);
633             }
634         }
635
636         // None of the saved RMUAs are common for these pairs
637
// Delete them and seek new ones.
638
if (matchingRMUAs.isEmpty())
639         {
640             i = rmuas.iterator();
641             while (i.hasNext())
642             {
643                 RModuleUserAttribute rmua = (RModuleUserAttribute) i.next();
644                 rmua.delete(user);
645             }
646             int sizeGoal = 3;
647             int moreAttributes = sizeGoal;
648
649             // First try saved RMUAs for first module-issuetype pair
650
MITListItem item = getFirstItem();
651             Module module = getModule(item);
652             IssueType issueType = item.getIssueType();
653             rmuas = user.getRModuleUserAttributes(module, issueType);
654             // Next try default RMUAs for first module-issuetype pair
655
if (rmuas.isEmpty())
656             {
657                 rmuas = module.getDefaultRModuleUserAttributes(issueType);
658             }
659
660             // Loop through these and if find common ones, save the RMUAs
661
i = rmuas.iterator();
662             while (i.hasNext() && moreAttributes > 0)
663             {
664                 RModuleUserAttribute rmua = (RModuleUserAttribute) i.next();
665                 Attribute att = rmua.getAttribute();
666                 if (isCommon(att, false) && !matchingRMUAs.contains(rmua))
667                 {
668                     RModuleUserAttribute newRmua =
669                         getNewRModuleUserAttribute(att);
670                     newRmua.setOrder(1);
671                     newRmua.save();
672                     matchingRMUAs.add(rmua);
673                     moreAttributes--;
674                 }
675             }
676
677             // if nothing better, go with random common attributes
678
moreAttributes = sizeGoal - matchingRMUAs.size();
679             if (moreAttributes > 0)
680             {
681                 Iterator JavaDoc attributes = getCommonAttributes(false).iterator();
682                 int k = 1;
683                 while (attributes.hasNext() && moreAttributes > 0)
684                 {
685                     Attribute att = (Attribute) attributes.next();
686                     boolean isInList = false;
687                     i = matchingRMUAs.iterator();
688                     while (i.hasNext())
689                     {
690                         RModuleUserAttribute rmua =
691                             (RModuleUserAttribute) i.next();
692                         if (rmua.getAttribute().equals(att))
693                         {
694                             isInList = true;
695                             break;
696                         }
697                     }
698                     if (!isInList)
699                     {
700                         RModuleUserAttribute rmua =
701                             getNewRModuleUserAttribute(att);
702                         rmua.setOrder(k++);
703                         rmua.save();
704                         matchingRMUAs.add(rmua);
705                         moreAttributes--;
706                     }
707                 }
708             }
709         }
710
711         return matchingRMUAs;
712     }
713
714     protected RModuleUserAttribute getNewRModuleUserAttribute(Attribute attribute)
715         throws Exception JavaDoc
716     {
717         RModuleUserAttribute result = RModuleUserAttributeManager.getInstance();
718         result.setUserId(getUserId());
719         result.setAttributeId(attribute.getAttributeId());
720
721         if (isSingleModuleIssueType())
722         {
723             result.setModuleId(getModule().getModuleId());
724             result.setIssueTypeId(getIssueType().getIssueTypeId());
725         }
726
727         if (!isNew())
728         {
729             result.setListId(getListId());
730         }
731         return result;
732     }
733
734     /**
735     * get common and active RMOs.
736     *
737     * @param rmos a list of RModuleOptions
738     * @return the sublist of common and active RMOs
739     * @throws TorqueException
740     * @throws Exception
741     *
742     * TODO write a more generic search routine (e.g. for getCommonAttributes,
743     * getCommonNonUserAttributes, getCommonOptionAttributes, ...)
744     */

745     private List JavaDoc getMatchingRMOs(List JavaDoc rmos) throws TorqueException, Exception JavaDoc
746     {
747         List JavaDoc matchingRMOs = new ArrayList JavaDoc();
748         if (rmos != null)
749         {
750             for (Iterator JavaDoc i = rmos.iterator(); i.hasNext();)
751             {
752                 RModuleOption rmo = (RModuleOption) i.next();
753                 AttributeOption option = rmo.getAttributeOption();
754                 if (rmo.getActive() && isCommon(option))
755                 {
756                     matchingRMOs.add(rmo);
757                 }
758             }
759         }
760         return matchingRMOs;
761     }
762
763     protected List JavaDoc getSavedRMUAs() throws Exception JavaDoc
764     {
765         Criteria crit = new Criteria();
766         crit.add(RModuleUserAttributePeer.USER_ID, getUserId());
767         if (!isNew())
768         {
769             crit.add(RModuleUserAttributePeer.LIST_ID, getListId());
770         }
771         else if (isSingleModuleIssueType())
772         {
773             crit.add(RModuleUserAttributePeer.LIST_ID, null);
774             crit.add(
775                 RModuleUserAttributePeer.MODULE_ID,
776                 getModule().getModuleId());
777             crit.add(
778                 RModuleUserAttributePeer.ISSUE_TYPE_ID,
779                 getIssueType().getIssueTypeId());
780         }
781         else
782         {
783             crit.add(RModuleUserAttributePeer.LIST_ID, null);
784             crit.add(RModuleUserAttributePeer.MODULE_ID, null);
785             crit.add(RModuleUserAttributePeer.ISSUE_TYPE_ID, null);
786         }
787         crit.addAscendingOrderByColumn(
788             RModuleUserAttributePeer.PREFERRED_ORDER);
789
790         return RModuleUserAttributePeer.doSelect(crit);
791     }
792
793     public List JavaDoc getCommonLeafRModuleOptions(Attribute attribute)
794         throws Exception JavaDoc
795     {
796         assertNotEmpty();
797         
798         MITListItem item = getFirstItem();
799         List JavaDoc rmos =
800             getModule(item).getLeafRModuleOptions(
801                 attribute,
802                 item.getIssueType());
803         return getMatchingRMOs(rmos);
804     }
805
806     public List JavaDoc getCommonRModuleOptionTree(Attribute attribute)
807         throws Exception JavaDoc
808     {
809         assertNotEmpty();
810         MITListItem item = getFirstItem();
811         List JavaDoc rmos =
812             getModule(item).getOptionTree(attribute, item.getIssueType());
813         return getMatchingRMOs(rmos);
814     }
815
816     public List JavaDoc getAllRModuleOptionTree(Attribute attribute)
817         throws Exception JavaDoc
818     {
819         assertNotEmpty();
820     
821         // Get all isse types from this MITList
822
List JavaDoc listItems = getExpandedMITListItems();
823
824         // Get all attribute options from all issue types for the requested attribute
825
List JavaDoc attributeOptions = new ArrayList JavaDoc();
826         if (listItems!=null) {
827             Iterator JavaDoc listItemIterator = listItems.iterator();
828             while (listItemIterator.hasNext()) {
829                 MITListItem item = (MITListItem)listItemIterator.next();
830                 List JavaDoc rmos = getModule(item).getOptionTree(attribute, item.getIssueType());
831                 mergeRModuleOptionsIgnoreDuplicates(attributeOptions, rmos);
832             }
833         }
834     
835         return attributeOptions;
836     }
837
838     private void mergeRModuleOptionsIgnoreDuplicates(List JavaDoc masterList, List JavaDoc addList)
839         throws TorqueException {
840         // Get a set of all existing option ids
841
Set JavaDoc optionIds = new HashSet JavaDoc();
842         Iterator JavaDoc masterIterator = masterList.iterator();
843         while (masterIterator.hasNext()) {
844             RModuleOption option = (RModuleOption)masterIterator.next();
845             optionIds.add(option.getOptionId());
846         }
847   
848         // add all options not already present in the list, add only active options
849
Iterator JavaDoc addIterator = addList.iterator();
850         while (addIterator.hasNext()) {
851             RModuleOption rmo = (RModuleOption)addIterator.next();
852             if (rmo.getActive() && !optionIds.contains(rmo.getOptionId())) {
853                 masterList.add(rmo);
854             }
855         }
856     }
857
858     public List JavaDoc getDescendantsUnion(AttributeOption option) throws Exception JavaDoc
859     {
860         assertNotEmpty();
861
862         List JavaDoc matchingRMOs = new ArrayList JavaDoc();
863         Iterator JavaDoc items = iterator();
864         while (items.hasNext())
865         {
866             MITListItem item = (MITListItem) items.next();
867             IssueType issueType = item.getIssueType();
868             RModuleOption parent =
869                 getModule(item).getRModuleOption(option, issueType);
870             if (parent != null)
871             {
872                 Iterator JavaDoc i = parent.getDescendants(issueType).iterator();
873                 while (i.hasNext())
874                 {
875                     RModuleOption rmo = (RModuleOption) i.next();
876                     if (!matchingRMOs.contains(rmo))
877                     {
878                         matchingRMOs.add(rmo);
879                     }
880                 }
881             }
882         }
883
884         return matchingRMOs;
885     }
886
887     public boolean isCommon(AttributeOption option) throws Exception JavaDoc
888     {
889         return isCommon(option, true);
890     }
891
892     /**
893      * Checks all items after the first to see if they contain the attribute.
894      * It is assumed the attribute is included in the first item.
895      *
896      * @param option an <code>Attribute</code> value
897      * @return a <code>boolean</code> value
898      */

899     public boolean isCommon(AttributeOption option, boolean activeOnly)
900         throws Exception JavaDoc
901     {
902         Criteria crit = new Criteria();
903         addToCriteria(
904             crit,
905             RModuleOptionPeer.MODULE_ID,
906             RModuleOptionPeer.ISSUE_TYPE_ID);
907         crit.add(RModuleOptionPeer.OPTION_ID, option.getOptionId());
908         if (activeOnly)
909         {
910             crit.add(RModuleOptionPeer.ACTIVE, true);
911         }
912
913         return size() == RModuleOptionPeer.count(crit);
914     }
915
916     public List JavaDoc getModuleIds()
917     {
918         assertNotEmpty();
919
920         List JavaDoc items = getExpandedMITListItems();
921         ArrayList JavaDoc ids = new ArrayList JavaDoc(items.size());
922         Iterator JavaDoc i = items.iterator();
923         while (i.hasNext())
924         {
925             Integer JavaDoc id = ((MITListItem) i.next()).getModuleId();
926             if (!ids.contains(id))
927             {
928                 ids.add(id);
929             }
930         }
931         return ids;
932     }
933
934     public List JavaDoc getModules() throws TorqueException
935     {
936         assertNotEmpty();
937
938         List JavaDoc items = getExpandedMITListItems();
939         ArrayList JavaDoc modules = new ArrayList JavaDoc(items.size());
940         Iterator JavaDoc i = items.iterator();
941         while (i.hasNext())
942         {
943             Module m = ((MITListItem) i.next()).getModule();
944             if (!modules.contains(m))
945             {
946                 modules.add(m);
947             }
948         }
949         return modules;
950     }
951
952     public List JavaDoc getIssueTypeIds()
953     {
954         assertNotEmpty();
955
956         List JavaDoc items = getExpandedMITListItems();
957         ArrayList JavaDoc ids = new ArrayList JavaDoc(items.size());
958         Iterator JavaDoc i = items.iterator();
959         while (i.hasNext())
960         {
961             Integer JavaDoc id = ((MITListItem) i.next()).getIssueTypeId();
962             if (!ids.contains(id))
963             {
964                 ids.add(id);
965             }
966         }
967         return ids;
968     }
969
970     public void addToCriteria(Criteria crit) throws Exception JavaDoc
971     {
972         addToCriteria(crit, IssuePeer.MODULE_ID, IssuePeer.TYPE_ID);
973     }
974
975     private void addToCriteria(
976         Criteria crit,
977         String JavaDoc moduleField,
978         String JavaDoc issueTypeField)
979         throws Exception JavaDoc
980     {
981         if (!isSingleModule() && isSingleIssueType())
982         {
983             crit.addIn(moduleField, getModuleIds());
984             crit.add(issueTypeField, getIssueType().getIssueTypeId());
985         }
986         else if (isSingleModule() && !isSingleIssueType())
987         {
988             crit.add(moduleField, getModule().getModuleId());
989             crit.addIn(issueTypeField, getIssueTypeIds());
990         }
991         else if (isAllMITs)
992         {
993             crit.addIn(moduleField, getModuleIds());
994             // we do this to avoid including templates in results
995
crit.addIn(issueTypeField, getIssueTypeIds());
996         }
997         else if (size() > 0)
998         {
999             List JavaDoc items = getExpandedMITListItems();
1000            Iterator JavaDoc i = items.iterator();
1001            Criteria.Criterion c = null;
1002            while (i.hasNext())
1003            {
1004                MITListItem item = (MITListItem) i.next();
1005                Criteria.Criterion c1 =
1006                    crit.getNewCriterion(
1007                        moduleField,
1008                        item.getModuleId(),
1009                        Criteria.EQUAL);
1010                Criteria.Criterion c2 =
1011                    crit.getNewCriterion(
1012                        issueTypeField,
1013                        item.getIssueTypeId(),
1014                        Criteria.EQUAL);
1015                c1.and(c2);
1016                if (c == null)
1017                {
1018                    c = c1;
1019                }
1020                else
1021                {
1022                    c.or(c1);
1023                }
1024            }
1025            crit.add(c);
1026        }
1027    }
1028
1029    public void addAll(MITList list) throws TorqueException
1030    {
1031        List JavaDoc currentList = getExpandedMITListItems();
1032        for (Iterator JavaDoc i = list.getExpandedMITListItems().iterator();
1033            i.hasNext();
1034            )
1035        {
1036            MITListItem item = (MITListItem) i.next();
1037            if (!currentList.contains(item))
1038            {
1039                addMITListItem(item);
1040            }
1041        }
1042    }
1043
1044    public void addMITListItem(MITListItem item) throws TorqueException
1045    {
1046        super.addMITListItem(item);
1047        expandedList = null;
1048        calculateIsAllMITs(item);
1049    }
1050
1051    private void calculateIsAllMITs(MITListItem item)
1052    {
1053        isAllMITs
1054            |= (MITListItem.MULTIPLE_KEY.equals(item.getModuleId())
1055                && MITListItem.MULTIPLE_KEY.equals(item.getIssueTypeId()));
1056    }
1057
1058    public List JavaDoc getExpandedMITListItems()
1059    {
1060        if (expandedList == null)
1061        {
1062            List JavaDoc items = new ArrayList JavaDoc();
1063            try
1064            {
1065                for (Iterator JavaDoc rawItems = getMITListItems().iterator();
1066                    rawItems.hasNext();
1067                    )
1068                {
1069                    MITListItem item = (MITListItem) rawItems.next();
1070                    calculateIsAllMITs(item);
1071                    if (!item.isSingleModule())
1072                    {
1073                        Module[] modules =
1074                            getScarabUser().getModules(
1075                                ScarabSecurity.ISSUE__SEARCH);
1076                        for (int i = 0; i < modules.length; i++)
1077                        {
1078                            Module module = modules[i];
1079                            if (item.isSingleIssueType())
1080                            {
1081                                IssueType type = item.getIssueType();
1082                                if (module.getRModuleIssueType(type) != null)
1083                                {
1084                                    MITListItem newItem =
1085                                        MITListItemManager.getInstance();
1086                                    newItem.setModule(module);
1087                                    newItem.setIssueType(type);
1088                                    newItem.setListId(getListId());
1089                                    items.add(newItem);
1090                                }
1091                            }
1092                            else
1093                            {
1094                                addIssueTypes(module, items);
1095                            }
1096                        }
1097                    }
1098                    else if (!item.isSingleIssueType())
1099                    {
1100                        addIssueTypes(getModule(item), items);
1101                    }
1102                    else
1103                    {
1104                        items.add(item);
1105                    }
1106                }
1107            }
1108            catch (Exception JavaDoc e)
1109            {
1110                throw new TorqueRuntimeException(e); //EXCEPTION
1111
}
1112            expandedList = items;
1113        }
1114
1115        return expandedList;
1116    }
1117
1118    /**
1119     * Adds all the active issue types in module to the items List
1120     */

1121    private void addIssueTypes(Module module, List JavaDoc items) throws Exception JavaDoc
1122    {
1123        Iterator JavaDoc rmits = module.getRModuleIssueTypes().iterator();
1124        while (rmits.hasNext())
1125        {
1126            MITListItem newItem = MITListItemManager.getInstance();
1127            newItem.setModuleId(module.getModuleId());
1128            newItem.setIssueTypeId(
1129                ((RModuleIssueType) rmits.next()).getIssueTypeId());
1130            newItem.setListId(getListId());
1131            items.add(newItem);
1132        }
1133    }
1134
1135    public void scheduleItemForDeletion(MITListItem item)
1136    {
1137        if (itemsScheduledForDeletion == null)
1138        {
1139            itemsScheduledForDeletion = new ArrayList JavaDoc();
1140        }
1141        itemsScheduledForDeletion.add(item);
1142    }
1143
1144    public void save(Connection JavaDoc con) throws TorqueException
1145    {
1146        super.save(con);
1147        if (itemsScheduledForDeletion != null
1148            && !itemsScheduledForDeletion.isEmpty())
1149        {
1150            List JavaDoc itemIds = new ArrayList JavaDoc(itemsScheduledForDeletion.size());
1151            for (Iterator JavaDoc iter = itemsScheduledForDeletion.iterator();
1152                iter.hasNext();
1153                )
1154            {
1155                MITListItem item = (MITListItem) iter.next();
1156                if (!item.isNew())
1157                {
1158                    itemIds.add(item.getItemId());
1159                }
1160            }
1161            if (!itemIds.isEmpty())
1162            {
1163                Criteria crit = new Criteria();
1164                crit.addIn(MITListItemPeer.ITEM_ID, itemIds);
1165                MITListItemPeer.doDelete(crit);
1166            }
1167        }
1168    }
1169
1170    public String JavaDoc toString()
1171    {
1172        StringBuffer JavaDoc sb = new StringBuffer JavaDoc(100);
1173        sb.append(super.toString()).append(':');
1174        sb.append((getListId() == null) ? "New" : getListId().toString());
1175        if (getName() != null)
1176        {
1177            sb.append(" name=").append(getName());
1178        }
1179        sb.append('[');
1180        boolean addComma = false;
1181        try
1182        {
1183            for (Iterator JavaDoc rawItems = getMITListItems().iterator();
1184                rawItems.hasNext();
1185                )
1186            {
1187                if (addComma)
1188                {
1189                    sb.append(", ");
1190                }
1191                else
1192                {
1193                    addComma = true;
1194                }
1195
1196                MITListItem item = (MITListItem) rawItems.next();
1197                sb
1198                    .append('(')
1199                    .append(item.getModuleId())
1200                    .append(',')
1201                    .append(item.getIssueTypeId())
1202                    .append(',')
1203                    .append(item.getListId())
1204                    .append(')');
1205            }
1206        }
1207        catch (Exception JavaDoc e)
1208        {
1209            sb.append("Error retrieving list items. see logs.");
1210            Log.get().warn("", e);
1211        }
1212
1213        return sb.append(']').toString();
1214    }
1215}
1216
Popular Tags