View Javadoc

1   /*
2    * Copyright 2005-2007 The Kuali Foundation
3    *
4    *
5    * Licensed under the Educational Community License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.opensource.org/licenses/ecl2.php
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.kuali.rice.kew.actionlist.dao.impl;
18  
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.ojb.broker.PersistenceBroker;
21  import org.apache.ojb.broker.accesslayer.LookupException;
22  import org.apache.ojb.broker.query.Criteria;
23  import org.apache.ojb.broker.query.QueryByCriteria;
24  import org.kuali.rice.kew.actionitem.ActionItem;
25  import org.kuali.rice.kew.actionitem.ActionItemActionListExtension;
26  import org.kuali.rice.kew.actionitem.OutboxItemActionListExtension;
27  import org.kuali.rice.kew.actionlist.ActionListFilter;
28  import org.kuali.rice.kew.actionlist.dao.ActionListDAO;
29  import org.kuali.rice.kew.api.WorkflowRuntimeException;
30  import org.kuali.rice.kew.api.action.DelegationType;
31  import org.kuali.rice.kew.doctype.bo.DocumentType;
32  import org.kuali.rice.kew.service.KEWServiceLocator;
33  import org.kuali.rice.kew.util.KEWConstants;
34  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
35  import org.springmodules.orm.ojb.PersistenceBrokerCallback;
36  import org.springmodules.orm.ojb.support.PersistenceBrokerDaoSupport;
37  
38  import java.sql.Connection;
39  import java.sql.PreparedStatement;
40  import java.sql.ResultSet;
41  import java.sql.SQLException;
42  import java.sql.Timestamp;
43  import java.util.Calendar;
44  import java.util.Collection;
45  import java.util.Date;
46  import java.util.HashMap;
47  import java.util.Iterator;
48  import java.util.List;
49  import java.util.Map;
50  
51  /**
52   * OJB implementation of the {@link ActionListDAO}.
53   *
54   * @author Kuali Rice Team (rice.collab@kuali.org)
55   */
56  public class ActionListDAOOjbImpl extends PersistenceBrokerDaoSupport implements ActionListDAO {
57  
58      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ActionListDAOOjbImpl.class);
59  
60      public Collection<ActionItem> getActionList(String principalId, ActionListFilter filter) {
61          return getActionItemsInActionList(ActionItemActionListExtension.class, principalId, filter);
62  //        LOG.debug("getting action list for user " + workflowUser.getWorkflowUserId().getWorkflowId());
63  //        Criteria crit = null;
64  //        if (filter == null) {
65  //            crit = new Criteria();
66  //            crit.addEqualTo("workflowId", workflowUser.getWorkflowUserId().getWorkflowId());
67  //        } else {
68  //            crit = setUpActionListCriteria(workflowUser, filter);
69  //        }
70  //        LOG.debug("running query to get action list for criteria " + crit);
71  //        Collection<ActionItem> collection = this.getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ActionItemActionListExtension.class, crit));
72  //        LOG.debug("found " + collection.size() + " action items for user " + workflowUser.getWorkflowUserId().getWorkflowId());
73  //        return createActionListForUser(collection);
74      }
75  
76      public Collection<ActionItem> getActionListForSingleDocument(String documentId) {
77          LOG.debug("getting action list for document id " + documentId);
78          Criteria crit = new Criteria();
79          crit.addEqualTo("documentId", documentId);
80          Collection<ActionItem> collection = this.getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(ActionItemActionListExtension.class, crit));
81          LOG.debug("found " + collection.size() + " action items for document id " + documentId);
82          return createActionListForRouteHeader(collection);
83      }
84  
85      private Criteria setUpActionListCriteria(String principalId, ActionListFilter filter) {
86          LOG.debug("setting up Action List criteria");
87          Criteria crit = new Criteria();
88          boolean filterOn = false;
89          String filteredByItems = "";
90  
91          if (filter.getActionRequestCd() != null && !"".equals(filter.getActionRequestCd().trim()) && !filter.getActionRequestCd().equals(KEWConstants.ALL_CODE)) {
92              if (filter.isExcludeActionRequestCd()) {
93                  crit.addNotEqualTo("actionRequestCd", filter.getActionRequestCd());
94              } else {
95                  crit.addEqualTo("actionRequestCd", filter.getActionRequestCd());
96              }
97              filteredByItems += filteredByItems.length() > 0 ? ", " : "";
98              filteredByItems += "Action Requested";
99          }
100 
101         if (filter.getCreateDateFrom() != null || filter.getCreateDateTo() != null) {
102             if (filter.isExcludeCreateDate()) {
103                 if (filter.getCreateDateFrom() != null && filter.getCreateDateTo() != null) {
104                     crit.addNotBetween("routeHeader.createDate", new Timestamp(beginningOfDay(filter.getCreateDateFrom()).getTime()), new Timestamp(endOfDay(filter.getCreateDateTo()).getTime()));
105                 } else if (filter.getCreateDateFrom() != null && filter.getCreateDateTo() == null) {
106                     crit.addLessOrEqualThan("routeHeader.createDate", new Timestamp(beginningOfDay(filter.getCreateDateFrom()).getTime()));
107                 } else if (filter.getCreateDateFrom() == null && filter.getCreateDateTo() != null) {
108                     crit.addGreaterOrEqualThan("routeHeader.createDate", new Timestamp(endOfDay(filter.getCreateDateTo()).getTime()));
109                 }
110             } else {
111                 if (filter.getCreateDateFrom() != null && filter.getCreateDateTo() != null) {
112                     crit.addBetween("routeHeader.createDate", new Timestamp(beginningOfDay(filter.getCreateDateFrom()).getTime()), new Timestamp(endOfDay(filter.getCreateDateTo()).getTime()));
113                 } else if (filter.getCreateDateFrom() != null && filter.getCreateDateTo() == null) {
114                     crit.addGreaterOrEqualThan("routeHeader.createDate", new Timestamp(beginningOfDay(filter.getCreateDateFrom()).getTime()));
115                 } else if (filter.getCreateDateFrom() == null && filter.getCreateDateTo() != null) {
116                     crit.addLessOrEqualThan("routeHeader.createDate", new Timestamp(endOfDay(filter.getCreateDateTo()).getTime()));
117                 }
118             }
119             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
120             filteredByItems += "Date Created";
121         }
122 
123         if (filter.getDocRouteStatus() != null && !"".equals(filter.getDocRouteStatus().trim()) && !filter.getDocRouteStatus().equals(KEWConstants.ALL_CODE)) {
124             if (filter.isExcludeRouteStatus()) {
125                 crit.addNotEqualTo("routeHeader.docRouteStatus", filter.getDocRouteStatus());
126             } else {
127                 crit.addEqualTo("routeHeader.docRouteStatus", filter.getDocRouteStatus());
128             }
129             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
130             filteredByItems += "Document Route Status";
131         }
132 
133         if (filter.getDocumentTitle() != null && !"".equals(filter.getDocumentTitle().trim())) {
134             String docTitle = filter.getDocumentTitle();
135             if (docTitle.trim().endsWith("*")) {
136                 docTitle = docTitle.substring(0, docTitle.length() - 1);
137             }
138 
139             if (filter.isExcludeDocumentTitle()) {
140                 crit.addNotLike("docTitle", "%" + docTitle + "%");
141             } else {
142                 crit.addLike("docTitle", "%" + docTitle + "%");
143             }
144             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
145             filteredByItems += "Document Title";
146         }
147 
148         if (filter.getDocumentType() != null && !"".equals(filter.getDocumentType().trim())) {
149             if (filter.isExcludeDocumentType()) {
150                 crit.addNotLike("docName", "%" + filter.getDocumentType() + "%");
151             } else {
152             	String documentTypeName = filter.getDocumentType();
153             	DocumentType documentType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
154             	if (documentType == null) {
155             	    crit.addLike("docName", "%" + filter.getDocumentType() + "%");
156             	} else {
157             	    // search this document type plus it's children
158             	    Criteria docTypeCrit = new Criteria();
159             	    constructDocumentTypeCriteria(docTypeCrit, documentType);
160             	    crit.addAndCriteria(docTypeCrit);
161             	}
162             }
163             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
164             filteredByItems += "Document Type";
165         }
166 
167         if (filter.getLastAssignedDateFrom() != null || filter.getLastAssignedDateTo() != null) {
168             if (filter.isExcludeLastAssignedDate()) {
169                 if (filter.getLastAssignedDateFrom() != null && filter.getLastAssignedDateTo() != null) {
170                     crit.addNotBetween("dateAssigned", new Timestamp(beginningOfDay(filter.getLastAssignedDateFrom()).getTime()), new Timestamp(endOfDay(filter.getLastAssignedDateTo()).getTime()));
171                 } else if (filter.getLastAssignedDateFrom() != null && filter.getLastAssignedDateTo() == null) {
172                     crit.addLessOrEqualThan("dateAssigned", new Timestamp(beginningOfDay(filter.getLastAssignedDateFrom()).getTime()));
173                 } else if (filter.getLastAssignedDateFrom() == null && filter.getLastAssignedDateTo() != null) {
174                     crit.addGreaterOrEqualThan("dateAssigned", new Timestamp(endOfDay(filter.getLastAssignedDateTo()).getTime()));
175                 }
176             } else {
177                 if (filter.getLastAssignedDateFrom() != null && filter.getLastAssignedDateTo() != null) {
178                     crit.addBetween("dateAssigned", new Timestamp(beginningOfDay(filter.getLastAssignedDateFrom()).getTime()), new Timestamp(endOfDay(filter.getLastAssignedDateTo()).getTime()));
179                 } else if (filter.getLastAssignedDateFrom() != null && filter.getLastAssignedDateTo() == null) {
180                     crit.addGreaterOrEqualThan("dateAssigned", new Timestamp(beginningOfDay(filter.getLastAssignedDateFrom()).getTime()));
181                 } else if (filter.getLastAssignedDateFrom() == null && filter.getLastAssignedDateTo() != null) {
182                     crit.addLessOrEqualThan("dateAssigned", new Timestamp(endOfDay(filter.getLastAssignedDateTo()).getTime()));
183                 }
184             }
185             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
186             filteredByItems += "Date Last Assigned";
187         }
188 
189         filter.setGroupId(null);
190         if (filter.getGroupIdString() != null && !"".equals(filter.getGroupIdString().trim()) && !filter.getGroupIdString().trim().equals(KEWConstants.NO_FILTERING)) {
191 
192             filter.setGroupId(filter.getGroupIdString().trim());
193           
194             if (filter.isExcludeGroupId()) {
195                 Criteria critNotEqual = new Criteria();
196                 critNotEqual.addNotEqualTo("groupId", filter.getGroupId());
197                 Criteria critNull = new Criteria();
198                 critNull.addIsNull("groupId");
199                 critNotEqual.addOrCriteria(critNull);
200                 crit.addAndCriteria(critNotEqual);
201             } else {
202                 crit.addEqualTo("groupId", filter.getGroupId());
203             }
204             filteredByItems += filteredByItems.length() > 0 ? ", " : "";
205             filteredByItems += "Action Request Workgroup";
206         }
207 
208         if (filteredByItems.length() > 0) {
209             filterOn = true;
210         }
211 
212         boolean addedDelegationCriteria = false;
213         if (StringUtils.isBlank(filter.getDelegationType()) && StringUtils.isBlank(filter.getPrimaryDelegateId()) && StringUtils.isBlank(filter.getDelegatorId())) {
214             crit.addEqualTo("principalId", principalId);
215             addedDelegationCriteria = true;
216         } else if ((StringUtils.isNotBlank(filter.getDelegationType()) && DelegationType.PRIMARY.getCode().equals(filter.getDelegationType()))
217                 || StringUtils.isNotBlank(filter.getPrimaryDelegateId())) {
218             // using a primary delegation
219             if ((StringUtils.isBlank(filter.getPrimaryDelegateId())) || (filter.getPrimaryDelegateId().trim().equals(KEWConstants.ALL_CODE))) {
220                 // user wishes to see all primary delegations
221                 Criteria userCrit = new Criteria();
222                 Criteria groupCrit = new Criteria();
223                 Criteria orCrit = new Criteria();
224                 userCrit.addEqualTo("delegatorWorkflowId", principalId);
225                 List<String> delegatorGroupIds = KimApiServiceLocator.getGroupService().getGroupIdsForPrincipal(principalId);
226                 if (delegatorGroupIds != null && !delegatorGroupIds.isEmpty()) {
227                 	groupCrit.addIn("delegatorGroupId", delegatorGroupIds);
228                 }
229                 orCrit.addOrCriteria(userCrit);
230                 orCrit.addOrCriteria(groupCrit);
231                 crit.addAndCriteria(orCrit);
232                 crit.addEqualTo("delegationType", DelegationType.PRIMARY.getCode());
233                 filter.setDelegationType(DelegationType.PRIMARY.getCode());
234                 filter.setExcludeDelegationType(false);
235                 addToFilterDescription(filteredByItems, "Primary Delegator Id");
236                 addedDelegationCriteria = true;
237                 filterOn = true;
238             } else if (!filter.getPrimaryDelegateId().trim().equals(KEWConstants.PRIMARY_DELEGATION_DEFAULT)) {
239                 // user wishes to see primary delegation for a single user
240                 crit.addEqualTo("principalId", filter.getPrimaryDelegateId());
241                 Criteria userCrit = new Criteria();
242                 Criteria groupCrit = new Criteria();
243                 Criteria orCrit = new Criteria();
244                 userCrit.addEqualTo("delegatorWorkflowId", principalId);
245                 List<String> delegatorGroupIds = KimApiServiceLocator.getGroupService().getGroupIdsForPrincipal(principalId);
246                 if (delegatorGroupIds != null && !delegatorGroupIds.isEmpty()) {
247                 	groupCrit.addIn("delegatorGroupId", delegatorGroupIds);
248                 }
249                 orCrit.addOrCriteria(userCrit);
250                 orCrit.addOrCriteria(groupCrit);
251                 crit.addAndCriteria(orCrit);
252                 crit.addEqualTo("delegationType", DelegationType.PRIMARY.getCode());
253                 filter.setDelegationType(DelegationType.PRIMARY.getCode());
254                 filter.setExcludeDelegationType(false);
255                 addToFilterDescription(filteredByItems, "Primary Delegator Id");
256                 addedDelegationCriteria = true;
257                 filterOn = true;
258             }
259         }
260         if (!addedDelegationCriteria && ( (StringUtils.isNotBlank(filter.getDelegationType()) && DelegationType.SECONDARY.getCode().equals(filter.getDelegationType()))
261                 || StringUtils.isNotBlank(filter.getDelegatorId()) )) {
262             // using a secondary delegation
263             crit.addEqualTo("principalId", principalId);
264             if (StringUtils.isBlank(filter.getDelegatorId())) {
265                 filter.setDelegationType(DelegationType.SECONDARY.getCode());
266                 // if isExcludeDelegationType() we want to show the default action list which is set up later in this method
267                 if (!filter.isExcludeDelegationType()) {
268                     crit.addEqualTo("delegationType", DelegationType.SECONDARY.getCode());
269                     addToFilterDescription(filteredByItems, "Secondary Delegator Id");
270                     addedDelegationCriteria = true;
271                     filterOn = true;
272                 }
273             } else if (filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
274                 // user wishes to see all secondary delegations
275                 crit.addEqualTo("delegationType", DelegationType.SECONDARY.getCode());
276                 filter.setDelegationType(DelegationType.SECONDARY.getCode());
277                 filter.setExcludeDelegationType(false);
278                 addToFilterDescription(filteredByItems, "Secondary Delegator Id");
279                 addedDelegationCriteria = true;
280                 filterOn = true;
281             } else if (!filter.getDelegatorId().trim().equals(
282                     KEWConstants.DELEGATION_DEFAULT)) {
283                 // user has specified an id to see for secondary delegation
284                 filter.setDelegationType(DelegationType.SECONDARY.getCode());
285                 filter.setExcludeDelegationType(false);
286                 Criteria userCrit = new Criteria();
287                 Criteria groupCrit = new Criteria();
288                 if (filter.isExcludeDelegatorId()) {
289                     Criteria userNull = new Criteria();
290                     userCrit.addNotEqualTo("delegatorWorkflowId", filter.getDelegatorId());
291                     userNull.addIsNull("delegatorWorkflowId");
292                     userCrit.addOrCriteria(userNull);
293                     Criteria groupNull = new Criteria();
294                     groupCrit.addNotEqualTo("delegatorGroupId", filter.getDelegatorId());
295                     groupNull.addIsNull("delegatorGroupId");
296                     groupCrit.addOrCriteria(groupNull);
297                     crit.addAndCriteria(userCrit);
298                     crit.addAndCriteria(groupCrit);
299                 } else {
300                     Criteria orCrit = new Criteria();
301                     userCrit.addEqualTo("delegatorWorkflowId", filter.getDelegatorId());
302                     groupCrit.addEqualTo("delegatorGroupId", filter.getDelegatorId());
303                     orCrit.addOrCriteria(userCrit);
304                     orCrit.addOrCriteria(groupCrit);
305                     crit.addAndCriteria(orCrit);
306                 }
307                 addToFilterDescription(filteredByItems, "Secondary Delegator Id");
308                 addedDelegationCriteria = true;
309                 filterOn = true;
310             }
311 //            } else if ( (StringUtils.isNotBlank(filter.getDelegationType()) && KEWConstants.DELEGATION_DEFAULT.equals(filter.getDelegationType())) ||
312 //                    StringUtils.isNotBlank(filter.getDelegatorId()) ) {
313 //            // not using a primary delegation so we can assume the action item will be assigned to the given user
314 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
315 //            if (filter.getDelegatorId() != null && !"".equals(filter.getDelegatorId().trim()) && !filter.getDelegatorId().trim().equals(KEWConstants.DELEGATION_DEFAULT)
316 //                    && !filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
317 //                filter.setDelegationType(DelegationType.SECONDARY.getCode());
318 //                filter.setExcludeDelegationType(false);
319 //                Criteria userCrit = new Criteria();
320 //                Criteria groupCrit = new Criteria();
321 //                if (filter.isExcludeDelegatorId()) {
322 //                    Criteria userNull = new Criteria();
323 //                    userCrit.addNotEqualTo("delegatorWorkflowId", filter.getDelegatorId());
324 //                    userNull.addIsNull("delegatorWorkflowId");
325 //                    userCrit.addOrCriteria(userNull);
326 //                    Criteria groupNull = new Criteria();
327 //                    groupCrit.addNotEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
328 //                    groupNull.addIsNull("delegatorWorkgroupId");
329 //                    groupCrit.addOrCriteria(groupNull);
330 //                    crit.addAndCriteria(userCrit);
331 //                    crit.addAndCriteria(groupCrit);
332 //                } else {
333 //                    Criteria orCrit = new Criteria();
334 //                    userCrit.addEqualTo("delegatorWorkflowId", filter.getDelegatorId());
335 //                    groupCrit.addEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
336 //                    orCrit.addOrCriteria(userCrit);
337 //                    orCrit.addOrCriteria(groupCrit);
338 //                    crit.addAndCriteria(orCrit);
339 //                }
340 //                addToFilterDescription(filteredByItems, "Secondary Delegator Id");
341 //                addedDelegationCriteria = true;
342 //            } else if (filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
343 //                filter.setDelegationType(DelegationType.SECONDARY.getCode());
344 //                filter.setExcludeDelegationType(false);
345 //                addToFilterDescription(filteredByItems, "Secondary Delegator Id");
346 //                addedDelegationCriteria = true;
347 //            }
348         }
349 
350         // if we haven't added delegation criteria then use the default criteria below
351         if (!addedDelegationCriteria) {
352             crit.addEqualTo("principalId", principalId);
353             filter.setDelegationType(DelegationType.SECONDARY.getCode());
354             filter.setExcludeDelegationType(true);
355             Criteria critNotEqual = new Criteria();
356             Criteria critNull = new Criteria();
357             critNotEqual.addNotEqualTo("delegationType", DelegationType.SECONDARY.getCode());
358             critNull.addIsNull("delegationType");
359             critNotEqual.addOrCriteria(critNull);
360             crit.addAndCriteria(critNotEqual);
361         }
362 
363 
364 //        if (filter.getPrimaryDelegateId().equals(KEWConstants.PRIMARY_DELEGATION_DEFAULT) && filter.getDelegatorId().equals(KEWConstants.DELEGATION_DEFAULT)) {
365 //            // no secondary or primary delegation displayed
366 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
367 //            filter.setDelegationType(DelegationType.SECONDARY.getCode());
368 //            Criteria critNotEqual = new Criteria();
369 //            Criteria critNull = new Criteria();
370 //            critNotEqual.addNotEqualTo("delegationType", DelegationType.SECONDARY.getCode());
371 //            critNull.addIsNull("delegationType");
372 //            critNotEqual.addOrCriteria(critNull);
373 //            crit.addAndCriteria(critNotEqual);
374 //            filter.setExcludeDelegationType(true);
375 //        } else if (filter.getPrimaryDelegateId().trim().equals(KEWConstants.ALL_CODE)) {
376 //            // user wishes to see all primary delegations
377 //            Criteria userCrit = new Criteria();
378 //            Criteria groupCrit = new Criteria();
379 //            Criteria orCrit = new Criteria();
380 //            userCrit.addEqualTo("delegatorWorkflowId", user.getWorkflowUserId().getWorkflowId());
381 //            groupCrit.addEqualTo("delegatorWorkgroupId", filter.getPrimaryDelegateId()); // TODO delyea: add all workgroups here?
382 //            orCrit.addOrCriteria(userCrit);
383 //            orCrit.addOrCriteria(groupCrit);
384 //            crit.addAndCriteria(orCrit);
385 //            crit.addEqualTo("delegationType", DelegationType.PRIMARY.getCode());
386 //            filter.setDelegationType(DelegationType.PRIMARY.getCode());
387 //            filter.setExcludeDelegationType(false);
388 //            filteredByItems += filteredByItems.length() > 0 ? ", " : "";
389 //            filteredByItems += "Primary Delegator Id";
390 //            filterOn = true;
391 //        } else if (filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
392 //            // user wishes to see all secondary delegations
393 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
394 //            crit.addEqualTo("delegationType", DelegationType.SECONDARY.getCode());
395 //            filter.setDelegationType(DelegationType.SECONDARY.getCode());
396 //            filter.setExcludeDelegationType(false);
397 //            filteredByItems += filteredByItems.length() > 0 ? ", " : "";
398 //            filteredByItems += "Secondary Delegator Id";
399 //            filterOn = true;
400 //        } else if (filter.getPrimaryDelegateId() != null && !"".equals(filter.getPrimaryDelegateId().trim())) {
401 //            // user wishes to see primary delegation for a single user
402 //            Criteria userCrit = new Criteria();
403 //            Criteria groupCrit = new Criteria();
404 //            Criteria orCrit = new Criteria();
405 //            userCrit.addEqualTo("delegatorWorkflowId", user.getWorkflowUserId().getWorkflowId());
406 //            groupCrit.addEqualTo("delegatorWorkgroupId", filter.getDelegatorId()); // TODO delyea: add all workgroups here?
407 //            orCrit.addOrCriteria(userCrit);
408 //            orCrit.addOrCriteria(groupCrit);
409 //            crit.addAndCriteria(orCrit);
410 //            crit.addEqualTo("delegationType", DelegationType.PRIMARY.getCode());
411 //            filter.setDelegationType(DelegationType.PRIMARY.getCode());
412 //            filter.setExcludeDelegationType(false);
413 //            filteredByItems += filteredByItems.length() > 0 ? ", " : "";
414 //            filteredByItems += "Primary Delegator Id";
415 //            filterOn = true;
416 //        } else if (filter.getDelegatorId() != null && !"".equals(filter.getDelegatorId().trim())) {
417 //            // user wishes to see secondary delegation for a single user
418 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
419 //            crit.addEqualTo("delegationType", DelegationType.SECONDARY.getCode());
420 //            filter.setDelegationType(DelegationType.SECONDARY.getCode());
421 //            filter.setExcludeDelegationType(false);
422 //            Criteria userCrit = new Criteria();
423 //            Criteria groupCrit = new Criteria();
424 //            if (filter.isExcludeDelegatorId()) {
425 //                Criteria userNull = new Criteria();
426 //                userCrit.addNotEqualTo("delegatorWorkflowId", filter.getDelegatorId());
427 //                userNull.addIsNull("delegatorWorkflowId");
428 //                userCrit.addOrCriteria(userNull);
429 //                Criteria groupNull = new Criteria();
430 //                groupCrit.addNotEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
431 //                groupNull.addIsNull("delegatorWorkgroupId");
432 //                groupCrit.addOrCriteria(groupNull);
433 //                crit.addAndCriteria(userCrit);
434 //                crit.addAndCriteria(groupCrit);
435 //            } else {
436 //                Criteria orCrit = new Criteria();
437 //                userCrit.addEqualTo("delegatorWorkflowId", filter.getDelegatorId());
438 //                groupCrit.addEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
439 //                orCrit.addOrCriteria(userCrit);
440 //                orCrit.addOrCriteria(groupCrit);
441 //                crit.addAndCriteria(orCrit);
442 //            }
443 //            filteredByItems += filteredByItems.length() > 0 ? ", " : "";
444 //            filteredByItems += "SeDelegator Id";
445 //            filterOn = true;
446 //        } else if (StringUtils.isBlank(filter.getPrimaryDelegateId()) && StringUtils.isBlank(filter.getDelegatorId())) {
447 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
448 //            if (filter.getDelegationType() != null && !"".equals(filter.getDelegationType().trim())) {
449 //                if (filter.isExcludeDelegationType()) {
450 //                    Criteria critNotEqual = new Criteria();
451 //                    Criteria critNull = new Criteria();
452 //                    critNotEqual.addNotEqualTo("delegationType", filter.getDelegationType());
453 //                    critNull.addIsNull("delegationType");
454 //                    critNotEqual.addOrCriteria(critNull);
455 //                    crit.addAndCriteria(critNotEqual);
456 //                } else {
457 //                    crit.addEqualTo("delegationType", filter.getDelegationType());
458 //                }
459 //            }
460 //        }
461 
462 
463 //        if (primary delegation) {
464 //            filter.setDelegationType(DelegationType.PRIMARY.getCode());
465 //            crit.addEqualTo("delegatorWorkflowId", user.getWorkflowUserId().getWorkflowId());
466 //
467 //        } else {
468 //            crit.addEqualTo("workflowId", user.getWorkflowUserId().getWorkflowId());
469 //            if (filter.getDelegatorId() != null && !"".equals(filter.getDelegatorId().trim()) && !filter.getDelegatorId().trim().equals(KEWConstants.DELEGATION_DEFAULT)
470 //                    && !filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
471 //                filter.setDelegationType(DelegationType.SECONDARY.getCode());
472 //                filter.setExcludeDelegationType(false);
473 //                Criteria userCrit = new Criteria();
474 //                Criteria groupCrit = new Criteria();
475 //                if (filter.isExcludeDelegatorId()) {
476 //                    Criteria userNull = new Criteria();
477 //                    userCrit.addNotEqualTo("delegatorWorkflowId", filter.getDelegatorId());
478 //                    userNull.addIsNull("delegatorWorkflowId");
479 //                    userCrit.addOrCriteria(userNull);
480 //                    Criteria groupNull = new Criteria();
481 //                    groupCrit.addNotEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
482 //                    groupNull.addIsNull("delegatorWorkgroupId");
483 //                    groupCrit.addOrCriteria(groupNull);
484 //                    crit.addAndCriteria(userCrit);
485 //                    crit.addAndCriteria(groupCrit);
486 //                } else {
487 //                    Criteria orCrit = new Criteria();
488 //                    userCrit.addEqualTo("delegatorWorkflowId", filter.getDelegatorId());
489 //                    groupCrit.addEqualTo("delegatorWorkgroupId", filter.getDelegatorId());
490 //                    orCrit.addOrCriteria(userCrit);
491 //                    orCrit.addOrCriteria(groupCrit);
492 //                    crit.addAndCriteria(orCrit);
493 //                }
494 //                filteredByItems += filteredByItems.length() > 0 ? ", " : "";
495 //                filteredByItems += "Delegator Id";
496 //                filterOn = true;
497 //            } else if (filter.getDelegatorId().trim().equals(KEWConstants.DELEGATION_DEFAULT)) {
498 //                filter.setDelegationType(DelegationType.SECONDARY.getCode());
499 //                filter.setExcludeDelegationType(true);
500 //            } else if (filter.getDelegatorId().trim().equals(KEWConstants.ALL_CODE)) {
501 //                filter.setDelegationType(DelegationType.SECONDARY.getCode());
502 //                filter.setExcludeDelegationType(false);
503 //                filteredByItems += filteredByItems.length() > 0 ? ", " : "";
504 //                filteredByItems += "Delegator Id";
505 //                filterOn = true;
506 //            }
507 //
508 //        }
509 //
510 //
511 //        //must come after delegation id since the delegation choices are all secondary delegations
512 //        if (filter.getDelegationType() != null && !"".equals(filter.getDelegationType().trim())) {
513 //            if (filter.isExcludeDelegationType()) {
514 //                Criteria critNotEqual = new Criteria();
515 //                Criteria critNull = new Criteria();
516 //                critNotEqual.addNotEqualTo("delegationType", filter.getDelegationType());
517 //                critNull.addIsNull("delegationType");
518 //                critNotEqual.addOrCriteria(critNull);
519 //                crit.addAndCriteria(critNotEqual);
520 //            } else {
521 //                crit.addEqualTo("delegationType", filter.getDelegationType());
522 //            }
523 //        }
524 
525         if (! "".equals(filteredByItems)) {
526             filteredByItems = "Filtered by " + filteredByItems;
527         }
528         filter.setFilterLegend(filteredByItems);
529         filter.setFilterOn(filterOn);
530 
531         LOG.debug("returning from Action List criteria");
532         return crit;
533     }
534 
535     private void constructDocumentTypeCriteria(Criteria criteria, DocumentType documentType) {
536     	// search this document type plus it's children
537     	Criteria docTypeBaseCrit = new Criteria();
538     	docTypeBaseCrit.addEqualTo("docName", documentType.getName());
539     	criteria.addOrCriteria(docTypeBaseCrit);
540     	Collection children = documentType.getChildrenDocTypes();
541     	if (children != null) {
542     	    for (Iterator iterator = children.iterator(); iterator.hasNext();) {
543     	    	DocumentType childDocumentType = (DocumentType) iterator.next();
544     	    	constructDocumentTypeCriteria(criteria, childDocumentType);
545     	    }
546     	}
547     }
548     
549     private void addToFilterDescription(String filterDescription, String labelToAdd) {
550         filterDescription += filterDescription.length() > 0 ? ", " : "";
551         filterDescription += labelToAdd;
552     }
553 
554     private static final String ACTION_LIST_COUNT_QUERY = "select count(distinct(ai.doc_hdr_id)) from krew_actn_itm_t ai where ai.PRNCPL_ID = ? and (ai.dlgn_typ is null or ai.dlgn_typ = 'P')";
555 
556     public int getCount(final String workflowId) {
557     	return (Integer)getPersistenceBrokerTemplate().execute(new PersistenceBrokerCallback() {
558             public Object doInPersistenceBroker(PersistenceBroker broker) {
559                 PreparedStatement statement = null;
560                 ResultSet resultSet = null;
561                 try {
562                     Connection connection = broker.serviceConnectionManager().getConnection();
563                     statement = connection.prepareStatement(ACTION_LIST_COUNT_QUERY);
564                     statement.setString(1, workflowId);
565                     resultSet = statement.executeQuery();
566                     if (!resultSet.next()) {
567                         throw new WorkflowRuntimeException("Error determining Action List Count.");
568                     }
569                     return resultSet.getInt(1);
570                 } catch (SQLException e) {
571                     throw new WorkflowRuntimeException("Error determining Action List Count.", e);
572                 } catch (LookupException e) {
573                     throw new WorkflowRuntimeException("Error determining Action List Count.", e);
574                 } finally {
575                     if (statement != null) {
576                         try {
577                             statement.close();
578                         } catch (SQLException e) {}
579                     }
580                     if (resultSet != null) {
581                         try {
582                             resultSet.close();
583                         } catch (SQLException e) {}
584                     }
585                 }
586             }
587         });
588     }
589 
590     /**
591      * Creates an Action List from the given collection of Action Items.  The Action List should
592      * contain only one action item per document.  The action item chosen should be the most "critical"
593      * or "important" one on the document.
594      *
595      * @return the Action List as a Collection of ActionItems
596      */
597     private Collection<ActionItem> createActionListForUser(Collection<ActionItem> actionItems) {
598         Map<String, ActionItem> actionItemMap = new HashMap<String, ActionItem>();
599         ActionListPriorityComparator comparator = new ActionListPriorityComparator();
600         for (ActionItem potentialActionItem: actionItems) {
601             ActionItem existingActionItem = actionItemMap.get(potentialActionItem.getDocumentId());
602             if (existingActionItem == null || comparator.compare(potentialActionItem, existingActionItem) > 0) {
603                 actionItemMap.put(potentialActionItem.getDocumentId(), potentialActionItem);
604             }
605         }
606         return actionItemMap.values();
607     }
608 
609     /**
610      * Creates an Action List from the given collection of Action Items.  The Action List should
611      * contain only one action item per user.  The action item chosen should be the most "critical"
612      * or "important" one on the document.
613      *
614      * @return the Action List as a Collection of ActionItems
615      */
616     private Collection<ActionItem> createActionListForRouteHeader(Collection<ActionItem> actionItems) {
617         Map<String, ActionItem> actionItemMap = new HashMap<String, ActionItem>();
618         ActionListPriorityComparator comparator = new ActionListPriorityComparator();
619         for (ActionItem potentialActionItem: actionItems) {
620             ActionItem existingActionItem = actionItemMap.get(potentialActionItem.getPrincipalId());
621             if (existingActionItem == null || comparator.compare(potentialActionItem, existingActionItem) > 0) {
622                 actionItemMap.put(potentialActionItem.getPrincipalId(), potentialActionItem);
623             }
624         }
625         return actionItemMap.values();
626     }
627 
628     private Collection<ActionItem> getActionItemsInActionList(Class objectsToRetrieve, String principalId, ActionListFilter filter) {
629         LOG.debug("getting action list for user " + principalId);
630         Criteria crit = null;
631         if (filter == null) {
632             crit = new Criteria();
633             crit.addEqualTo("principalId", principalId);
634         } else {
635             crit = setUpActionListCriteria(principalId, filter);
636         }
637         LOG.debug("running query to get action list for criteria " + crit);
638         Collection<ActionItem> collection = this.getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(objectsToRetrieve, crit));
639         LOG.debug("found " + collection.size() + " action items for user " + principalId);
640         return createActionListForUser(collection);
641     }
642 
643     public Collection<ActionItem> getOutbox(String principalId, ActionListFilter filter) {
644         return getActionItemsInActionList(OutboxItemActionListExtension.class, principalId, filter);
645 //        LOG.debug("getting action list for user " + workflowUser.getWorkflowUserId().getWorkflowId());
646 //        Criteria crit = new Criteria();
647 //        crit.addEqualTo("workflowId", workflowUser.getWorkflowUserId().getWorkflowId());
648 //        if (filter != null) {
649 //            setUpActionListCriteria(workflowUser, filter);
650 //        }
651 //        LOG.debug("running query to get action list for criteria " + crit);
652 //        Collection<ActionItem> collection = this.getPersistenceBrokerTemplate().getCollectionByQuery(new QueryByCriteria(OutboxItemActionListExtension.class, crit));
653 //        LOG.debug("found " + collection.size() + " action items for user " + workflowUser.getWorkflowUserId().getWorkflowId());
654 //        return createActionListForUser(collection);
655     }
656 
657     /**
658      *
659      * Deletes all outbox items specified by the list of ids
660      *
661      * @see org.kuali.rice.kew.actionlist.dao.ActionListDAO#removeOutboxItems(java.lang.String, java.util.List)
662      */
663     public void removeOutboxItems(String principalId, List<String> outboxItems) {
664         Criteria crit = new Criteria();
665         crit.addIn("actionItemId", outboxItems);
666         getPersistenceBrokerTemplate().deleteByQuery(new QueryByCriteria(OutboxItemActionListExtension.class, crit));
667     }
668 
669     /**
670      * Saves an outbox item
671      *
672      * @see org.kuali.rice.kew.actionlist.dao.ActionListDAO#saveOutboxItem(org.kuali.rice.kew.actionitem.OutboxItemActionListExtension)
673      */
674     public void saveOutboxItem(OutboxItemActionListExtension outboxItem) {
675         this.getPersistenceBrokerTemplate().store(outboxItem);
676     }
677 
678     /**
679      * Gets the outbox item associated with the document id
680      *
681      * @see org.kuali.rice.kew.actionlist.dao.ActionListDAO#getOutboxByDocumentId(java.lang.String)
682      */
683     public OutboxItemActionListExtension getOutboxByDocumentId(String documentId) {
684         Criteria crit = new Criteria();
685         crit.addEqualTo("documentId", documentId);
686         return (OutboxItemActionListExtension)getPersistenceBrokerTemplate().getObjectByQuery(new QueryByCriteria(OutboxItemActionListExtension.class, crit));
687     }
688 
689     /**
690      * This overridden method ...
691      *
692      * @see org.kuali.rice.kew.actionlist.dao.ActionListDAO#getOutboxByDocumentIdUserId(java.lang.String)
693      */
694     public OutboxItemActionListExtension getOutboxByDocumentIdUserId(String documentId, String userId) {
695         Criteria crit = new Criteria();
696         crit.addEqualTo("documentId", documentId);
697         crit.addEqualTo("principalId", userId);
698         return (OutboxItemActionListExtension)getPersistenceBrokerTemplate().getObjectByQuery(new QueryByCriteria(OutboxItemActionListExtension.class, crit));
699     }
700 
701     private Date beginningOfDay(Date date) {
702         Calendar cal = Calendar.getInstance();
703         cal.setTime(date);
704         cal.set(Calendar.HOUR_OF_DAY, 0);
705         cal.set(Calendar.MINUTE, 0);
706         cal.set(Calendar.SECOND, 0);
707         return cal.getTime();
708     }
709 
710     private Date endOfDay(Date date) {
711         Calendar cal = Calendar.getInstance();
712         cal.setTime(date);
713         cal.set(Calendar.HOUR_OF_DAY, 23);
714         cal.set(Calendar.MINUTE, 59);
715         cal.set(Calendar.SECOND, 59);
716         return cal.getTime();
717     }
718 
719 }