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.krad.web.controller;
17  
18  import java.util.Collection;
19  import java.util.Properties;
20  import java.util.Set;
21  
22  import javax.servlet.http.HttpServletRequest;
23  import javax.servlet.http.HttpServletResponse;
24  
25  import org.apache.commons.lang.StringUtils;
26  import org.kuali.rice.core.api.exception.RiceRuntimeException;
27  import org.kuali.rice.krad.lookup.CollectionIncomplete;
28  import org.kuali.rice.krad.lookup.Lookupable;
29  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
30  import org.kuali.rice.krad.service.ModuleService;
31  import org.kuali.rice.krad.uif.UifConstants;
32  import org.kuali.rice.krad.uif.UifParameters;
33  import org.kuali.rice.krad.uif.UifPropertyPaths;
34  import org.kuali.rice.krad.util.GlobalVariables;
35  import org.kuali.rice.krad.util.KRADConstants;
36  import org.kuali.rice.krad.util.KRADUtils;
37  import org.kuali.rice.krad.web.form.LookupForm;
38  import org.kuali.rice.krad.web.form.UifFormBase;
39  import org.springframework.stereotype.Controller;
40  import org.springframework.validation.BindingResult;
41  import org.springframework.web.bind.annotation.ModelAttribute;
42  import org.springframework.web.bind.annotation.RequestMapping;
43  import org.springframework.web.bind.annotation.RequestMethod;
44  import org.springframework.web.servlet.ModelAndView;
45  
46  /**
47   * Controller that handles requests coming from a <code>LookupView</code>
48   *
49   * @author Kuali Rice Team (rice.collab@kuali.org)
50   */
51  @Controller
52  @RequestMapping(value = "/lookup")
53  public class LookupController extends UifControllerBase {
54      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(LookupController.class);
55  
56      /**
57       * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
58       */
59      @Override
60      protected LookupForm createInitialForm(HttpServletRequest request) {
61          return new LookupForm();
62      }
63  
64      protected void suppressActionsIfNeeded(LookupForm lookupForm) {
65          //        try {
66          //            // TODO; move to authorizer for lookup view
67          //            Class<?> dataObjectClass = Class.forName(lookupForm.getDataObjectClassName());
68          //            Person user = GlobalVariables.getUserSession().getPerson();
69          //            // check if creating documents is allowed
70          //            String documentTypeName = KRADServiceLocatorWeb.getDocumentDictionaryService()
71          //                    .getMaintenanceDocumentTypeName(dataObjectClass);
72          //            if ((documentTypeName != null) &&
73          //                    !KRADServiceLocatorWeb.getDocumentHelperService().getDocumentAuthorizer(documentTypeName)
74          //                            .canInitiate(documentTypeName, user)) {
75          //                ((LookupView) lookupForm.getView()).setSuppressActions(true);
76          //            }
77          //        } catch (ClassNotFoundException e) {
78          //            LOG.warn("Unable to load Data Object Class: " + lookupForm.getDataObjectClassName(), e);
79          //        }
80      }
81  
82      /**
83       * Invoked to request an lookup view for a data object class
84       *
85       * <p>
86       * Checks if the data object is externalizable and we need to redirect to the appropriate lookup URL, else
87       * continues with the lookup view display
88       * </p>
89       */
90      @RequestMapping(params = "methodToCall=start")
91      @Override
92      public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
93              HttpServletRequest request, HttpServletResponse response) {
94          LookupForm lookupForm = (LookupForm) form;
95  
96          // if request is not a redirect, determine if we need to redirect for an externalizable object lookup
97          if (!lookupForm.isRedirectedLookup()) {
98              Class lookupObjectClass = null;
99              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 }