001    /**
002     * Copyright 2005-2013 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.kew.quicklinks.dao.impl;
017    
018    import org.apache.ojb.broker.PersistenceBroker;
019    import org.kuali.rice.core.api.delegation.DelegationType;
020    import org.kuali.rice.core.api.util.KeyValue;
021    import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
022    import org.kuali.rice.kew.api.WorkflowRuntimeException;
023    import org.kuali.rice.kew.docsearch.service.DocumentSearchService;
024    import org.kuali.rice.kew.doctype.DocumentTypePolicy;
025    import org.kuali.rice.kew.doctype.bo.DocumentType;
026    import org.kuali.rice.kew.doctype.service.DocumentTypeService;
027    import org.kuali.rice.kew.quicklinks.ActionListStats;
028    import org.kuali.rice.kew.quicklinks.InitiatedDocumentType;
029    import org.kuali.rice.kew.quicklinks.WatchedDocument;
030    import org.kuali.rice.kew.quicklinks.dao.QuickLinksDAO;
031    import org.kuali.rice.kew.service.KEWServiceLocator;
032    import org.kuali.rice.kew.api.KewApiConstants;
033    import org.kuali.rice.krad.util.KRADConstants;
034    import org.springmodules.orm.ojb.PersistenceBrokerCallback;
035    import org.springmodules.orm.ojb.support.PersistenceBrokerDaoSupport;
036    
037    import java.sql.Connection;
038    import java.sql.PreparedStatement;
039    import java.sql.ResultSet;
040    import java.sql.SQLException;
041    import java.util.ArrayList;
042    import java.util.Collections;
043    import java.util.List;
044    import java.util.StringTokenizer;
045    
046    
047    public class QuickLinksDAOOjbImpl extends PersistenceBrokerDaoSupport implements QuickLinksDAO {
048    
049        @Override
050            public List<ActionListStats> getActionListStats(final String principalId) {
051            return (List<ActionListStats>) this.getPersistenceBrokerTemplate().execute(new PersistenceBrokerCallback() {
052                @Override
053                            public Object doInPersistenceBroker(PersistenceBroker broker) {
054                    PreparedStatement selectActionItems = null;
055                    PreparedStatement selectDocTypeLabel = null;
056                    ResultSet selectedActionItems = null;
057                    ResultSet selectedDocTypeLabel = null;
058                    List<ActionListStats> docTypes = new ArrayList<ActionListStats>();
059                    try {
060                        Connection connection = broker.serviceConnectionManager().getConnection();
061    
062                        selectActionItems = connection.prepareStatement("select DOC_TYP_NM, COUNT(*) from KREW_ACTN_ITM_T where PRNCPL_ID = ? " +
063                                "and (dlgn_typ is null or dlgn_typ != '" + DelegationType.SECONDARY.getCode() + "') group by DOC_TYP_NM");
064                        selectDocTypeLabel = connection.prepareStatement("select LBL from KREW_DOC_TYP_T WHERE DOC_TYP_NM = ? and CUR_IND = 1");
065                        selectActionItems.setString(1, principalId);
066                        selectedActionItems = selectActionItems.executeQuery();
067                        while (selectedActionItems.next()) {
068                            String docTypeName = selectedActionItems.getString(1);
069                            int count = selectedActionItems.getInt(2);
070                            selectDocTypeLabel.setString(1, docTypeName);
071                            selectedDocTypeLabel = selectDocTypeLabel.executeQuery();
072                            if (selectedDocTypeLabel.next()) {
073                                docTypes.add(new ActionListStats(docTypeName, selectedDocTypeLabel.getString(1), count));
074                            }
075                        }
076                        Collections.sort(docTypes);
077                        return docTypes;
078                    } catch (Exception e) {
079                        throw new WorkflowRuntimeException("Error getting action list stats for user: " + principalId, e);
080                    } finally {
081                        if (selectActionItems != null) {
082                            try {
083                                selectActionItems.close();
084                            } catch (SQLException e) {
085                            }
086                        }
087    
088                        if (selectDocTypeLabel != null) {
089                            try {
090                                selectDocTypeLabel.close();
091                            } catch (SQLException e) {
092                            }
093                        }
094    
095                        if (selectedActionItems != null) {
096                            try {
097                                selectedActionItems.close();
098                            } catch (SQLException e) {
099                            }
100                        }
101    
102                        if (selectedDocTypeLabel != null) {
103                            try {
104                                selectedDocTypeLabel.close();
105                            } catch (SQLException e) {
106                            }
107                        }
108    
109                    }
110                }
111            });
112        }
113    
114        @Override
115            public List<InitiatedDocumentType> getInitiatedDocumentTypesList(final String principalId) {
116            return (List<InitiatedDocumentType>)  this.getPersistenceBrokerTemplate().execute(new PersistenceBrokerCallback() {
117    
118                @Override
119                            public Object doInPersistenceBroker(PersistenceBroker broker) {
120                    PreparedStatement selectDistinctDocumentTypes = null;
121                    ResultSet selectedDistinctDocumentTypes = null;
122                    List<InitiatedDocumentType> documentTypesByName = new ArrayList<InitiatedDocumentType>();
123                    try {
124                        Connection connection = broker.serviceConnectionManager().getConnection();
125    //                  select the doc type only if the SUPPORTS_QUICK_INITIATE policy is NULL or true
126                        String sql = "select distinct B.DOC_TYP_NM, B.LBL from KREW_DOC_HDR_T A, KREW_DOC_TYP_T B "+
127                            "where A.INITR_PRNCPL_ID = ? and A.DOC_TYP_ID = B.DOC_TYP_ID and " +
128                            "B.ACTV_IND = 1 and B.CUR_IND = 1 " +
129                            "order by upper(B.LBL)";
130    
131                        selectDistinctDocumentTypes = connection.prepareStatement(sql);
132                        selectDistinctDocumentTypes.setString(1, principalId);
133                        selectedDistinctDocumentTypes = selectDistinctDocumentTypes.executeQuery();
134    
135                        String documentNames = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.QUICK_LINK_DETAIL_TYPE, KewApiConstants.QUICK_LINKS_RESTRICT_DOCUMENT_TYPES);
136                        if (documentNames != null) {
137                            // TODO Should this happen???
138                            documentNames = documentNames.trim();
139                        }
140                        if (documentNames == null || "none".equals(documentNames)) {
141                            documentNames = "";
142                        }
143    
144                        List docTypesToRestrict = new ArrayList();
145                        StringTokenizer st = new StringTokenizer(documentNames, ",");
146                        while (st.hasMoreTokens()) {
147                            docTypesToRestrict.add(st.nextToken());
148                        }
149                        while (selectedDistinctDocumentTypes.next()) {
150                            String docTypeName = selectedDistinctDocumentTypes.getString(1);
151                            String docTypeTopParent = "";
152                            int firstPeriod = docTypeName.indexOf(".");
153                            if (firstPeriod == -1) {
154                                docTypeTopParent = docTypeName.substring(0);
155                            } else {
156                                docTypeTopParent = docTypeName.substring(0, firstPeriod);
157                            }
158                            if (!docTypesToRestrict.contains(docTypeTopParent)) {
159                                    // the document types should be cached so this should be pretty quick
160                                    DocumentType docType = KEWServiceLocator.getDocumentTypeService().findByName(docTypeName);
161                                    DocumentTypePolicy quickInitiatePolicy = docType.getSupportsQuickInitiatePolicy();
162                                if (quickInitiatePolicy.getPolicyValue().booleanValue()) {
163                                    documentTypesByName.add(new InitiatedDocumentType(docTypeName, selectedDistinctDocumentTypes.getString(2)));
164                                }
165                            }
166                        }
167                        return documentTypesByName;
168                    } catch (Exception e) {
169                        throw new WorkflowRuntimeException("Error getting initiated document types for user: " + principalId, e);
170                    } finally {
171                        if (selectDistinctDocumentTypes != null) {
172                            try {
173                                selectDistinctDocumentTypes.close();
174                            } catch (SQLException e) {
175                            }
176                        }
177                        if (selectedDistinctDocumentTypes != null) {
178                            try {
179                                selectedDistinctDocumentTypes.close();
180                            } catch (SQLException e) {
181                            }
182                        }
183    
184                    }
185    
186                }
187            });
188        }
189    
190        @Override
191            public List<KeyValue> getNamedSearches(String principalId) {
192            return getDocumentSearchService().getNamedSearches(principalId);
193        }
194    
195        @Override
196            public List<KeyValue> getRecentSearches(String principalId) {
197            return getDocumentSearchService().getMostRecentSearches(principalId);
198        }
199    
200        @Override
201            public List<WatchedDocument> getWatchedDocuments(final String principalId) {
202            return (List<WatchedDocument>) this.getPersistenceBrokerTemplate().execute(new PersistenceBrokerCallback() {
203                @Override
204                            public Object doInPersistenceBroker(PersistenceBroker broker) {
205                    List<WatchedDocument> watchedDocuments = new ArrayList<WatchedDocument>();
206                    PreparedStatement selectWatchedDocuments = null;
207                    ResultSet selectedWatchedDocuments = null;
208                    try {
209                        Connection connection = broker.serviceConnectionManager().getConnection();
210                        selectWatchedDocuments = connection.prepareStatement("select DOC_HDR_ID, DOC_HDR_STAT_CD, TTL, CRTE_DT from KREW_DOC_HDR_T where INITR_PRNCPL_ID = ? and DOC_HDR_STAT_CD in ('"+ KewApiConstants.ROUTE_HEADER_ENROUTE_CD +"','"+ KewApiConstants.ROUTE_HEADER_EXCEPTION_CD +"') order by CRTE_DT desc");
211                        selectWatchedDocuments.setString(1, principalId);
212                        selectedWatchedDocuments = selectWatchedDocuments.executeQuery();
213                        while (selectedWatchedDocuments.next()) {
214                            watchedDocuments.add(new WatchedDocument(selectedWatchedDocuments.getString(1), KewApiConstants.DOCUMENT_STATUSES.get(selectedWatchedDocuments.getString(2)), selectedWatchedDocuments.getString(3)));
215                        }
216                        return watchedDocuments;
217                    } catch (Exception e) {
218                        throw new WorkflowRuntimeException("Error getting initiated document types for user: " + principalId, e);
219                    } finally {
220                        if (selectWatchedDocuments != null) {
221                            try {
222                                selectWatchedDocuments.close();
223                            } catch (SQLException e) {
224                            }
225                        }
226                        if (selectedWatchedDocuments != null) {
227                            try {
228                                selectedWatchedDocuments.close();
229                            } catch (SQLException e) {
230                            }
231                        }
232    
233                    }
234                }
235            });
236        }
237    
238        public DocumentTypeService getDocumentTypeService() {
239            return ((DocumentTypeService) KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_TYPE_SERVICE));
240        }
241    
242        public DocumentSearchService getDocumentSearchService() {
243            return ((DocumentSearchService) KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_SEARCH_SERVICE));
244        }
245    
246    }