001/**
002 * Copyright 2005-2016 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 */
016package org.kuali.rice.kim.lookup;
017
018import org.apache.commons.lang.StringUtils;
019import org.kuali.rice.core.api.util.ConcreteKeyValue;
020import org.kuali.rice.core.api.util.KeyValue;
021import org.kuali.rice.kew.api.KewApiConstants;
022import org.kuali.rice.kim.api.KimConstants;
023import org.kuali.rice.kim.api.services.KimApiServiceLocator;
024import org.kuali.rice.kim.api.type.KimAttributeField;
025import org.kuali.rice.kim.api.type.KimType;
026import org.kuali.rice.kim.impl.role.RoleBo;
027import org.kuali.rice.kim.impl.role.RoleDao;
028import org.kuali.rice.kim.impl.type.KimTypeBo;
029import org.kuali.rice.kim.impl.type.KimTypeLookupableHelperServiceImpl;
030import org.kuali.rice.kim.util.KimCommonUtilsInternal;
031import org.kuali.rice.kim.web.struts.form.IdentityManagementRoleDocumentForm;
032import org.kuali.rice.kns.document.authorization.BusinessObjectRestrictions;
033import org.kuali.rice.kns.lookup.HtmlData;
034import org.kuali.rice.kns.web.struts.form.KualiForm;
035import org.kuali.rice.kns.web.struts.form.LookupForm;
036import org.kuali.rice.kns.web.ui.Field;
037import org.kuali.rice.kns.web.ui.Row;
038import org.kuali.rice.krad.bo.BusinessObject;
039import org.kuali.rice.krad.datadictionary.BusinessObjectEntry;
040import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
041import org.kuali.rice.krad.service.ModuleService;
042import org.kuali.rice.krad.util.BeanPropertyComparator;
043import org.kuali.rice.krad.util.GlobalVariables;
044import org.kuali.rice.krad.util.KRADConstants;
045import org.kuali.rice.krad.util.UrlFactory;
046
047import java.util.ArrayList;
048import java.util.Collection;
049import java.util.Collections;
050import java.util.Comparator;
051import java.util.HashMap;
052import java.util.List;
053import java.util.Map;
054import java.util.Properties;
055
056/**
057 * This is a description of what this class does - shyu don't forget to fill this in. 
058 * 
059 * @author Kuali Rice Team (rice.collab@kuali.org)
060 *
061 */
062public class RoleLookupableHelperServiceImpl extends KimLookupableHelperServiceImpl {
063
064    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(RoleLookupableHelperServiceImpl.class);
065
066        // need this so kimtypeId value can be retained in 'rows'
067        // 1st pass populate the grprows
068        // 2nd pass for jsp, no populate, so return the existing one. 
069        private List<Row> roleRows = new ArrayList<Row>();
070        private List<Row> attrRows = new ArrayList<Row>();
071        private RoleDao roleDao;
072        private String typeId;
073        private List<KimAttributeField> attrDefinitions;
074        
075    @Override
076    public List<HtmlData> getCustomActionUrls(BusinessObject bo, List pkNames) {
077        RoleBo roleBo = (RoleBo) bo;
078        List<HtmlData> anchorHtmlDataList = new ArrayList<HtmlData>();
079        if(allowsNewOrCopyAction(KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_TYPE_NAME)){
080                anchorHtmlDataList.add(getEditRoleUrl(roleBo));
081        }
082        return anchorHtmlDataList;
083    }
084    
085    protected HtmlData getEditRoleUrl(RoleBo roleBo) {
086        Properties parameters = new Properties();
087        parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.DOC_HANDLER_METHOD);
088        parameters.put(KRADConstants.PARAMETER_COMMAND, KewApiConstants.INITIATE_COMMAND);
089        parameters.put(KRADConstants.DOCUMENT_TYPE_NAME, KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_TYPE_NAME);
090        parameters.put(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, roleBo.getId());
091        if (StringUtils.isNotBlank(getReturnLocation())) {
092                parameters.put(KRADConstants.RETURN_LOCATION_PARAMETER, getReturnLocation());
093                }
094        String href = UrlFactory.parameterizeUrl(KimCommonUtilsInternal.getKimBasePath()+KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_ACTION, parameters);
095        
096        HtmlData.AnchorHtmlData anchorHtmlData = new HtmlData.AnchorHtmlData(href,
097                        KRADConstants.DOC_HANDLER_METHOD, KRADConstants.MAINTENANCE_EDIT_METHOD_TO_CALL);
098        return anchorHtmlData;
099    }
100
101    @Override
102        protected HtmlData getReturnAnchorHtmlData(BusinessObject businessObject, Properties parameters, LookupForm lookupForm, List returnKeys, BusinessObjectRestrictions businessObjectRestrictions){
103        RoleBo roleBo = (RoleBo) businessObject;
104        HtmlData anchorHtmlData = super.getReturnAnchorHtmlData(businessObject, parameters, lookupForm, returnKeys, businessObjectRestrictions);
105        
106        // prevent derived roles from being selectable (except for identityManagementRoleDocuments)     
107        KualiForm myForm = (KualiForm) GlobalVariables.getUserSession().retrieveObject(getDocFormKey());
108        if (myForm == null || !(myForm instanceof IdentityManagementRoleDocumentForm)){
109                if(KimTypeLookupableHelperServiceImpl.hasDerivedRoleTypeService(KimTypeBo.to(roleBo.getKimRoleType()))){
110                        ((HtmlData.AnchorHtmlData)anchorHtmlData).setHref("");
111                }
112        }
113        return anchorHtmlData;
114    }
115    
116    @Override
117    public List<? extends BusinessObject> getSearchResults(java.util.Map<String,String> fieldValues) {
118        //String kimTypeId = "";
119        fieldValues.remove(KRADConstants.BACK_LOCATION);
120        fieldValues.remove(KRADConstants.DOC_FORM_KEY);
121        fieldValues.remove(KRADConstants.DOC_NUM);
122        /*for (Map.Entry<String,String> entry : fieldValues.entrySet()) {
123                if (entry.getKey().equals(KimConstants.PrimaryKeyConstants.KIM_TYPE_ID)) {
124                        kimTypeId = entry.getValue();
125                        break;
126                }
127        }*/
128        List<RoleBo> roles = roleDao.getRoles(fieldValues);
129        //List<RoleBo> baseLookup = (List<RoleBo>)super.getSearchResults(fieldValues);
130
131        return roles;
132    }
133
134        private List<KeyValue> getRoleTypeOptions() {
135                List<KeyValue> options = new ArrayList<KeyValue>();
136                options.add(new ConcreteKeyValue("", ""));
137
138                Collection<KimType> kimGroupTypes = KimApiServiceLocator.getKimTypeInfoService().findAllKimTypes();
139                // get the distinct list of type IDs from all roles in the system
140        for (KimType kimType : kimGroupTypes) {
141            if (KimTypeLookupableHelperServiceImpl.hasRoleTypeService(kimType)) {
142                String value = kimType.getNamespaceCode().trim() + KRADConstants.FIELD_CONVERSION_PAIR_SEPARATOR + kimType.getName().trim();
143                options.add(new ConcreteKeyValue(kimType.getId(), value));
144            }
145        }
146        Collections.sort(options, new Comparator<KeyValue>() {
147           @Override
148                public int compare(KeyValue k1, KeyValue k2) {
149               return k1.getValue().compareTo(k2.getValue());
150           }
151        });
152                return options;
153        }
154        
155        public List<Row> getRoleRows() {
156                return this.roleRows;
157        }
158
159        public void setRoleRows(List<Row> roleRows) {
160                this.roleRows = roleRows;
161        }
162
163        public RoleDao getRoleDao() {
164                return this.roleDao;
165        }
166
167        public void setRoleDao(RoleDao roleDao) {
168                this.roleDao = roleDao;
169        }
170
171        public List<KimAttributeField> getAttrDefinitions() {
172                return this.attrDefinitions;
173        }
174
175        public void setAttrDefinitions(List<KimAttributeField> attrDefinitions) {
176                this.attrDefinitions = attrDefinitions;
177        }
178
179        public List<Row> getAttrRows() {
180                return this.attrRows;
181        }
182
183        public void setAttrRows(List<Row> attrRows) {
184                this.attrRows = attrRows;
185        }
186
187        public String getTypeId() {
188                return this.typeId;
189        }
190
191        public void setTypeId(String typeId) {
192                this.typeId = typeId;
193        }
194
195        @Override
196        public List<Row> getRows() {
197                new ArrayList<Row>();
198                if (getRoleRows().isEmpty()) {
199                        List<Row> rows = super.getRows();
200                        List<Row> returnRows = new ArrayList<Row>();
201                        for (Row row : rows) {
202                                for (int i = row.getFields().size() - 1; i >= 0; i--) {
203                                        Field field = row.getFields().get(i);
204                                        if (field.getPropertyName().equals("kimTypeId")) {
205                                                Field typeField = new Field();
206                                                typeField.setFieldLabel("Type");
207                                                typeField.setPropertyName("kimTypeId");
208                                                typeField.setFieldValidValues(getRoleTypeOptions());
209                                                typeField.setFieldType(Field.DROPDOWN);
210                                                typeField.setMaxLength(100);
211                                                typeField.setSize(40);
212                                                // row.getFields().set(i, new Field("Type", "", Field.DROPDOWN_REFRESH,
213                                                // false, "kimTypeId", "", getGroupTypeOptions(), null));
214                                                row.getFields().set(i, typeField);
215                                        }
216                                }
217                                returnRows.add(row);
218                        }
219                        setRoleRows(returnRows);
220                        //setAttrRows(setupAttributeRows());
221                }
222                if (getAttrRows().isEmpty()) {
223                        //setAttrDefinitions(new AttributeDefinitionMap());
224                        return getRoleRows();
225                } else {
226                        List<Row> fullRows = new ArrayList<Row>();
227                        fullRows.addAll(getRoleRows());
228                        //fullRows.addAll(getAttrRows());
229                        return fullRows;
230                }
231                
232        }
233
234        @Override
235        protected List<? extends BusinessObject> getSearchResultsHelper(
236                        Map<String, String> fieldValues, boolean unbounded) {
237        List searchResults;
238        Map<String,String> nonBlankFieldValues = new HashMap<String, String>();
239        boolean includeAttr = false;
240        for (String fieldName : fieldValues.keySet()) {
241                if (StringUtils.isNotBlank(fieldValues.get(fieldName)) ) {
242                        nonBlankFieldValues.put(fieldName, fieldValues.get(fieldName));
243                        if (fieldName.contains(".")) {
244                                includeAttr = true;
245                        }
246                }
247        }
248
249        if (includeAttr) {
250                ModuleService eboModuleService = KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService( getBusinessObjectClass() );
251                BusinessObjectEntry ddEntry = eboModuleService.getExternalizableBusinessObjectDictionaryEntry(getBusinessObjectClass());
252                Map<String,String> filteredFieldValues = new HashMap<String, String>();
253                for (String fieldName : nonBlankFieldValues.keySet()) {
254                        if (ddEntry.getAttributeNames().contains(fieldName) || fieldName.contains(".")) {
255                                filteredFieldValues.put(fieldName, nonBlankFieldValues.get(fieldName));
256                        }
257                }
258                searchResults = eboModuleService.getExternalizableBusinessObjectsListForLookup(getBusinessObjectClass(), (Map)filteredFieldValues, unbounded);
259
260        } else {
261                searchResults = super.getSearchResultsHelper(fieldValues, unbounded);
262        }
263        List defaultSortColumns = getDefaultSortColumns();
264        if (defaultSortColumns.size() > 0) {
265            Collections.sort(searchResults, new BeanPropertyComparator(defaultSortColumns, true));
266        }
267        return searchResults;
268
269        }
270        
271        private static final String ROLE_ID_URL_KEY = "&"+KimConstants.PrimaryKeyConstants.ROLE_ID+"=";
272
273        public static String getCustomRoleInquiryHref(String href){
274                return getCustomRoleInquiryHref("", href);
275        }
276        
277        static String getCustomRoleInquiryHref(String backLocation, String href){
278        Properties parameters = new Properties();
279        String hrefPart = "";
280        String docTypeAction = "";
281        if(StringUtils.isBlank(backLocation) || backLocation.contains(KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_ACTION)
282                        || !backLocation.contains(KimConstants.KimUIConstants.KIM_GROUP_DOCUMENT_ACTION)){
283                docTypeAction = KimConstants.KimUIConstants.KIM_ROLE_INQUIRY_ACTION;
284        } else{
285                docTypeAction = KimConstants.KimUIConstants.KIM_GROUP_DOCUMENT_ACTION;
286        }
287                if (StringUtils.isNotBlank(href) && href.contains(ROLE_ID_URL_KEY)) {
288                        int idx1 = href.indexOf("&"+ KimConstants.PrimaryKeyConstants.ROLE_ID+"=");
289                    int idx2 = href.indexOf("&", idx1+1);
290                    if (idx2 < 0) {
291                        idx2 = href.length();
292                    }
293                parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.PARAM_MAINTENANCE_VIEW_MODE_INQUIRY);
294                hrefPart = href.substring(idx1, idx2);
295            }
296                return UrlFactory.parameterizeUrl(KimCommonUtilsInternal.getKimBasePath()+docTypeAction, parameters)+hrefPart;
297        }
298
299}