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