View Javadoc

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