001    /**
002     * Copyright 2005-2012 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.krad.web.controller;
017    
018    import java.util.Collection;
019    import java.util.Properties;
020    import java.util.Set;
021    
022    import javax.servlet.http.HttpServletRequest;
023    import javax.servlet.http.HttpServletResponse;
024    
025    import org.apache.commons.lang.StringUtils;
026    import org.kuali.rice.core.api.exception.RiceRuntimeException;
027    import org.kuali.rice.krad.lookup.CollectionIncomplete;
028    import org.kuali.rice.krad.lookup.Lookupable;
029    import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
030    import org.kuali.rice.krad.service.ModuleService;
031    import org.kuali.rice.krad.uif.UifConstants;
032    import org.kuali.rice.krad.uif.UifParameters;
033    import org.kuali.rice.krad.uif.UifPropertyPaths;
034    import org.kuali.rice.krad.util.GlobalVariables;
035    import org.kuali.rice.krad.util.KRADConstants;
036    import org.kuali.rice.krad.util.KRADUtils;
037    import org.kuali.rice.krad.web.form.LookupForm;
038    import org.kuali.rice.krad.web.form.UifFormBase;
039    import org.springframework.stereotype.Controller;
040    import org.springframework.validation.BindingResult;
041    import org.springframework.web.bind.annotation.ModelAttribute;
042    import org.springframework.web.bind.annotation.RequestMapping;
043    import org.springframework.web.bind.annotation.RequestMethod;
044    import org.springframework.web.servlet.ModelAndView;
045    
046    /**
047     * Controller that handles requests coming from a <code>LookupView</code>
048     *
049     * @author Kuali Rice Team (rice.collab@kuali.org)
050     */
051    @Controller
052    @RequestMapping(value = "/lookup")
053    public class LookupController extends UifControllerBase {
054        private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(LookupController.class);
055    
056        /**
057         * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
058         */
059        @Override
060        protected LookupForm createInitialForm(HttpServletRequest request) {
061            return new LookupForm();
062        }
063    
064        protected void suppressActionsIfNeeded(LookupForm lookupForm) {
065            //        try {
066            //            // TODO; move to authorizer for lookup view
067            //            Class<?> dataObjectClass = Class.forName(lookupForm.getDataObjectClassName());
068            //            Person user = GlobalVariables.getUserSession().getPerson();
069            //            // check if creating documents is allowed
070            //            String documentTypeName = KRADServiceLocatorWeb.getDocumentDictionaryService()
071            //                    .getMaintenanceDocumentTypeName(dataObjectClass);
072            //            if ((documentTypeName != null) &&
073            //                    !KRADServiceLocatorWeb.getDocumentHelperService().getDocumentAuthorizer(documentTypeName)
074            //                            .canInitiate(documentTypeName, user)) {
075            //                ((LookupView) lookupForm.getView()).setSuppressActions(true);
076            //            }
077            //        } catch (ClassNotFoundException e) {
078            //            LOG.warn("Unable to load Data Object Class: " + lookupForm.getDataObjectClassName(), e);
079            //        }
080        }
081    
082        /**
083         * Invoked to request an lookup view for a data object class
084         *
085         * <p>
086         * Checks if the data object is externalizable and we need to redirect to the appropriate lookup URL, else
087         * continues with the lookup view display
088         * </p>
089         */
090        @RequestMapping(params = "methodToCall=start")
091        @Override
092        public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
093                HttpServletRequest request, HttpServletResponse response) {
094            LookupForm lookupForm = (LookupForm) form;
095    
096            // if request is not a redirect, determine if we need to redirect for an externalizable object lookup
097            if (!lookupForm.isRedirectedLookup()) {
098                Class lookupObjectClass = null;
099                try {
100                    lookupObjectClass = Class.forName(lookupForm.getDataObjectClassName());
101                } catch (ClassNotFoundException e) {
102                    throw new RiceRuntimeException("Unable to get class for name: " + lookupForm.getDataObjectClassName());
103                }
104    
105                ModuleService responsibleModuleService =
106                        KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService(lookupObjectClass);
107                if (responsibleModuleService != null && responsibleModuleService.isExternalizable(lookupObjectClass)) {
108                    String lookupUrl = responsibleModuleService.getExternalizableDataObjectLookupUrl(lookupObjectClass,
109                            KRADUtils.convertRequestMapToProperties(request.getParameterMap()));
110    
111                    Properties redirectUrlProps = new Properties();
112                    redirectUrlProps.put(UifParameters.REDIRECTED_LOOKUP, "true");
113    
114                    // clear current form from session
115                    GlobalVariables.getUifFormManager().removeSessionForm(form);
116    
117                    return performRedirect(form, lookupUrl, redirectUrlProps);
118                }
119            }
120    
121            return super.start(lookupForm, result, request, response);
122        }
123    
124        /**
125         * Just returns as if return with no value was selected
126         */
127        @Override
128        @RequestMapping(method = RequestMethod.POST, params = "methodToCall=cancel")
129        public ModelAndView cancel(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
130                HttpServletRequest request, HttpServletResponse response) {
131            LookupForm lookupForm = (LookupForm) form;
132            suppressActionsIfNeeded(lookupForm);
133    
134            Properties props = new Properties();
135            props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.REFRESH);
136            if (StringUtils.isNotBlank(lookupForm.getReturnFormKey())) {
137                props.put(UifParameters.FORM_KEY, lookupForm.getReturnFormKey());
138            }
139            if (StringUtils.isNotBlank(lookupForm.getDocNum())) {
140                props.put(UifParameters.DOC_NUM, lookupForm.getDocNum());
141            }
142    
143            // clear current form from session
144            GlobalVariables.getUifFormManager().removeSessionForm(form);
145    
146            return performRedirect(lookupForm, lookupForm.getReturnLocation(), props);
147        }
148    
149        /**
150         * clearValues - clears the values of all the fields on the jsp.
151         */
152        @RequestMapping(method = RequestMethod.POST, params = "methodToCall=clearValues")
153        public ModelAndView clearValues(@ModelAttribute("KualiForm") LookupForm lookupForm, BindingResult result,
154                HttpServletRequest request, HttpServletResponse response) {
155            suppressActionsIfNeeded(lookupForm);
156    
157            Lookupable lookupable = (Lookupable) lookupForm.getLookupable();
158            lookupForm.setLookupCriteria(lookupable.performClear(lookupForm, lookupForm.getLookupCriteria()));
159    
160            return getUIFModelAndView(lookupForm);
161        }
162    
163        /**
164         * search - sets the values of the data entered on the form on the jsp into a map and then searches for the
165         * results.
166         */
167        @RequestMapping(params = "methodToCall=search")
168        public ModelAndView search(@ModelAttribute("KualiForm") LookupForm lookupForm, BindingResult result,
169                HttpServletRequest request, HttpServletResponse response) {
170            suppressActionsIfNeeded(lookupForm);
171    
172            Lookupable lookupable = lookupForm.getLookupable();
173            if (lookupable == null) {
174                LOG.error("Lookupable is null.");
175                throw new RuntimeException("Lookupable is null.");
176            }
177    
178            // validate search parameters
179            boolean searchValid = lookupable.validateSearchParameters(lookupForm, lookupForm.getLookupCriteria());
180    
181            if (searchValid) {
182                Collection<?> displayList = lookupable.performSearch(lookupForm, lookupForm.getLookupCriteria(), true);
183    
184                if (displayList instanceof CollectionIncomplete<?>) {
185                    request.setAttribute("reqSearchResultsActualSize",
186                            ((CollectionIncomplete<?>) displayList).getActualSizeIfTruncated());
187                } else {
188                    request.setAttribute("reqSearchResultsActualSize", new Integer(displayList.size()));
189                }
190    
191                lookupForm.setLookupResults(displayList);
192            }
193    
194            return getUIFModelAndView(lookupForm);
195        }
196    
197        /**
198         * Invoked from the UI to return the selected lookup results lines, parameters are collected to build a URL to
199         * the caller and then a redirect is performed
200         *
201         * @param lookupForm - lookup form instance containing the selected results and lookup configuration
202         */
203        @RequestMapping(method = RequestMethod.POST, params = "methodToCall=returnSelected")
204        public ModelAndView returnSelected(@ModelAttribute("KualiForm") LookupForm lookupForm, BindingResult result,
205                HttpServletRequest request, HttpServletResponse response) {
206            Properties parameters = new Properties();
207            parameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.RETURN_METHOD_TO_CALL);
208    
209            if (StringUtils.isNotBlank(lookupForm.getReturnFormKey())) {
210                parameters.put(UifParameters.FORM_KEY, lookupForm.getReturnFormKey());
211            }
212    
213            parameters.put(KRADConstants.REFRESH_CALLER, lookupForm.getView().getId());
214            parameters.put(KRADConstants.REFRESH_CALLER_TYPE, UifConstants.RefreshCallerTypes.MULTI_VALUE_LOOKUP);
215            parameters.put(KRADConstants.REFRESH_DATA_OBJECT_CLASS, lookupForm.getDataObjectClassName());
216    
217            if (StringUtils.isNotBlank(lookupForm.getDocNum())) {
218                parameters.put(UifParameters.DOC_NUM, lookupForm.getDocNum());
219            }
220    
221            if (StringUtils.isNotBlank(lookupForm.getLookupCollectionName())) {
222                parameters.put(UifParameters.LOOKUP_COLLECTION_NAME, lookupForm.getLookupCollectionName());
223            }
224    
225            if (StringUtils.isNotBlank(lookupForm.getReferencesToRefresh())) {
226                parameters.put(KRADConstants.REFERENCES_TO_REFRESH, lookupForm.getReferencesToRefresh());
227            }
228    
229            // build string of select line identifiers
230            String selectedLineValues = "";
231            Set<String> selectedLines = lookupForm.getSelectedCollectionLines().get(UifPropertyPaths.SEARCH_RESULTS);
232            if (selectedLines != null) {
233                for (String selectedLine : selectedLines) {
234                    selectedLineValues += selectedLine + ",";
235                }
236                selectedLineValues = StringUtils.removeEnd(selectedLineValues, ",");
237            }
238    
239            parameters.put(UifParameters.SELECTED_LINE_VALUES, selectedLineValues);
240    
241            // clear current form from session
242            GlobalVariables.getUifFormManager().removeSessionForm(lookupForm);
243    
244            return performRedirect(lookupForm, lookupForm.getReturnLocation(), parameters);
245        }
246    }