View Javadoc

1   /*
2    * Copyright 2011 The Kuali Foundation
3    * 
4    * Licensed under the Educational Community License, Version 1.0 (the
5    * "License"); 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/ecl1.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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package org.kuali.student.enrollment.class1.check.controller;
17  
18  import org.apache.commons.lang.BooleanUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.kuali.rice.core.api.criteria.Predicate;
21  import org.kuali.rice.core.api.criteria.QueryByCriteria;
22  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
23  import org.kuali.rice.krad.datadictionary.DataObjectEntry;
24  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
25  import org.kuali.rice.krad.uif.UifConstants;
26  import org.kuali.rice.krad.uif.UifParameters;
27  import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
28  import org.kuali.rice.krad.util.GlobalVariables;
29  import org.kuali.rice.krad.util.KRADConstants;
30  import org.kuali.rice.krad.web.controller.LookupController;
31  import org.kuali.rice.krad.web.controller.UifControllerBase;
32  import org.kuali.rice.krad.web.form.UifFormBase;
33  import org.kuali.student.enrollment.class1.check.form.CheckInfoForm;
34  import org.kuali.student.enrollment.class1.process.form.ProcessInfoForm;
35  import org.kuali.student.common.uif.view.KSLookupView;
36  import org.kuali.student.mock.utilities.TestHelper;
37  import org.kuali.student.r2.common.dto.ContextInfo;
38  import org.kuali.student.r2.common.dto.RichTextInfo;
39  import org.kuali.student.r2.core.constants.ProcessServiceConstants;
40  import org.kuali.student.r2.core.process.dto.CheckInfo;
41  import org.kuali.student.r2.core.process.dto.InstructionInfo;
42  import org.kuali.student.r2.core.process.dto.ProcessInfo;
43  import org.kuali.student.r2.core.process.service.ProcessService;
44  import org.springframework.stereotype.Controller;
45  import org.springframework.validation.BindingResult;
46  import org.springframework.web.bind.annotation.ModelAttribute;
47  import org.springframework.web.bind.annotation.RequestMapping;
48  import org.springframework.web.bind.annotation.RequestMethod;
49  import org.springframework.web.servlet.ModelAndView;
50  import org.kuali.rice.krad.web.form.LookupForm;
51  import javax.servlet.http.HttpServletRequest;
52  import javax.servlet.http.HttpServletResponse;
53  import javax.xml.namespace.QName;
54  import java.util.Collection;
55  import java.util.Map;
56  import java.util.Properties;
57  import java.util.ArrayList;
58  import java.util.List;
59  
60  import static org.kuali.rice.core.api.criteria.PredicateFactory.and;
61  import static org.kuali.rice.core.api.criteria.PredicateFactory.equal;
62  import static org.kuali.rice.core.api.criteria.PredicateFactory.like;
63  
64  /**
65   * This controller handles all the request from Academic calendar UI.
66   *
67   * @author Kuali Student Team
68   */
69  
70  @Controller
71  @RequestMapping(value = "/createCheck")
72  public class CheckInfoController extends UifControllerBase {
73  
74      private transient ProcessService processService;
75      private ContextInfo contextInfo;
76      private Map<String,String> actionParameters;
77  
78      @Override
79      protected UifFormBase createInitialForm(HttpServletRequest request) {
80          return new CheckInfoForm();
81      }
82  
83      /**
84       * This GET method loads an academic calendar based on the parameters passed into the request.
85       *
86       * These are the supported request parameters
87       * 1. id - Academic Calendar Id to load in to UI
88       * 2. readOnlyView - If true, sets the view as read only
89       * 3. selectTab - can be 'info' or 'term'
90       *
91       */
92      @Override
93      @RequestMapping(method = RequestMethod.GET, params = "methodToCall=start")
94      public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
95                                HttpServletRequest request, HttpServletResponse response) {
96          CheckInfoForm checkForm = (CheckInfoForm) form;
97          checkForm.setIsSaveSuccess(false);
98          checkForm.setIsInstructionActive(false);
99          return super.start(form, result, request, response);
100     }
101 
102     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=search")
103     public ModelAndView search(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
104                                HttpServletRequest request, HttpServletResponse response) throws Exception {
105         List<CheckInfo> results = new ArrayList<CheckInfo>();
106         String name = form.getName();
107         String descr = form.getDescr();
108         String type = form.getTypeKey();
109 
110         try {
111             QueryByCriteria.Builder query = buildQueryByCriteria(name, descr, type);
112 
113             processService = getProcessService();
114 
115 
116             List<CheckInfo> checkInfoList = processService.searchForChecks(query.build(), getContextInfo());
117             if (!checkInfoList.isEmpty()){
118                 results.addAll(checkInfoList);
119             }
120         } catch (Exception e) {
121             e.printStackTrace();
122             throw new RuntimeException("Error Performing Search",e); //To change body of catch statement use File | Settings | File Templates.
123         }
124 
125         resetForm(form);
126 
127         form.setCheckInfoList(results);
128 
129         return getUIFModelAndView(form);
130     }
131 
132     @RequestMapping(params = "methodToCall=update")
133     public ModelAndView update(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
134                              HttpServletRequest request, HttpServletResponse response) throws Exception {
135         CheckInfo checkInfo = form.getCheckInfo();
136 
137         checkInfo.setName(form.getName());
138         RichTextInfo richTextInfo = new RichTextInfo();
139         richTextInfo.setPlain(form.getDescr());
140         checkInfo.setDescr(richTextInfo);
141 
142         try {
143             processService = getProcessService();
144             processService.updateCheck(checkInfo.getId(),checkInfo, getContextInfo());
145         } catch (Exception e) {
146             return getUIFModelAndView(form);
147         }
148         if (form.getView() != null){
149             form.getView().setApplyDirtyCheck(false);
150         } else if (form.getPostedView() != null){
151             form.getView().setApplyDirtyCheck(false);
152         }
153         GlobalVariables.getMessageMap().putInfo("Check Info", "info.enroll.save.success");
154 
155         return refresh(form, result, request, response);
156     }
157 
158    @RequestMapping(params = "methodToCall=create")
159     public ModelAndView create(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
160                                HttpServletRequest request, HttpServletResponse response) throws Exception {
161        CheckInfoForm createForm = (CheckInfoForm) form;
162        CheckInfo checkInfo = new CheckInfo();
163        checkInfo.setName(createForm.getName());
164        checkInfo.setTypeKey(createForm.getTypeKey());
165        checkInfo.setStateKey("kuali.process.check.state.active");
166        checkInfo.setChildProcessKey(createForm.getChildProcessKey());
167        checkInfo.setHoldIssueId(createForm.getHoldIssueId());
168        checkInfo.setMilestoneTypeKey(createForm.getMilestoneTypeKey());
169         RichTextInfo richTextInfo = new RichTextInfo();
170         richTextInfo.setPlain(createForm.getDescr());
171        checkInfo.setDescr(richTextInfo);
172 
173 
174         try {
175            processService = getProcessService();
176            processService.createCheck(checkInfo.getTypeKey(), checkInfo, getContextInfo());
177         } catch (Exception e) {
178             return getUIFModelAndView(createForm);
179         }
180 
181        if (form.getView() != null){
182             form.getView().setApplyDirtyCheck(false);
183         } else if (form.getPostedView() != null){
184             form.getView().setApplyDirtyCheck(false);
185         }
186        createForm.setStateKey(checkInfo.getStateKey());
187        createForm.setCheckInfo(checkInfo);
188        return back(createForm, result, request, response);
189     }
190 
191     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=edit")
192     public ModelAndView edit(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
193                              HttpServletRequest request, HttpServletResponse response) throws Exception {
194         CheckInfo checkInfo = getSelectedCheckInfo(form, "edit");
195 
196         if ((checkInfo.getId() != null) && !checkInfo.getId().trim().isEmpty()) {
197             try {
198                 CheckInfo check = getProcessService().getCheck(checkInfo.getId(), getContextInfo());
199                 form.setName(check.getName());
200                 form.setTypeKey(check.getTypeKey());
201                 form.setDescr(check.getDescr().getPlain());
202                 form.setStateKey(check.getStateKey());
203             } catch (Exception ex) {
204                 throw new RuntimeException("unable to get hold issue");
205             }
206         }
207 
208         return getUIFModelAndView(form, "checkInfoSearch-EditPage");
209     }
210 
211     @RequestMapping(params = "methodToCall=openCreateForm")
212     public ModelAndView openCreateForm(@ModelAttribute("KualiForm") CheckInfoForm searchForm, BindingResult result,
213                              HttpServletRequest request, HttpServletResponse response) throws Exception {
214         String controllerPath;
215         Properties urlParameters = new Properties();
216 
217         urlParameters.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, "start");
218         urlParameters.put(UifParameters.VIEW_ID, "checkCreateView");
219 
220         controllerPath = "createCheck";
221 
222         return performRedirect(searchForm, controllerPath, urlParameters);
223     }
224 
225     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=delete")
226     public ModelAndView delete(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
227                                HttpServletRequest request, HttpServletResponse response) throws Exception {
228         form.setIsInstructionActive(false);
229         form.setDialogStateKey("");
230 
231         String dialogId = "deleteConfirmationDialog";
232 
233         if(!hasDialogBeenDisplayed(dialogId, form)) {
234             actionParameters = form.getActionParameters();
235             return showDialog(dialogId, form, request, response);
236         } else if (form.getActionParamaterValue("resetDialog").equals("true")){
237             form.getDialogManager().removeAllDialogs();
238             form.setLightboxScript("closeLightbox('" + dialogId + "');");
239             return getUIFModelAndView(form);
240         }
241 
242         form.setActionParameters(actionParameters);
243 /*        List<InstructionInfo> instructionInfos = new ArrayList<InstructionInfo>();
244         List<InstructionInfo> activeInstructions = new ArrayList<InstructionInfo>();
245         CheckInfo checkInfo = getSelectedCheckInfo(form, "delete");
246 
247         try{
248             instructionInfos = getProcessService().getInstructionsByProcess(processInfo.getKey(), getContextInfo());
249             for(InstructionInfo instruction : instructionInfos){
250                 if(instruction.getStateKey().equals("kuali.process.instruction.state.active")){
251                     isInstructionActive = true;
252                     activeInstructions.add(instruction);
253                 }
254             }
255 
256             if(!isInstructionActive) {
257                 if(!processInfo.getStateKey().equals("inactive") || !processInfo.getStateKey().equals("disabled")) {
258                     processInfo.setStateKey(form.getStateKey());
259                     getProcessService().updateProcess(processInfo.getKey(), processInfo, getContextInfo());
260                     form.setLightboxScript("closeLightbox('" + dialogId + "');");
261                     form.getDialogManager().removeAllDialogs();
262                     return getUIFModelAndView(form);
263                 }
264             } else if(isInstructionActive && form.getStateKey().equals("disabled")){
265                 processInfo.setStateKey(form.getStateKey());
266                 getProcessService().updateProcess(processInfo.getKey(), processInfo, getContextInfo());
267             } else {
268                 form.setInstructionInfoList(activeInstructions);
269                 return showDialog(dialogId, form, request, response);
270             }
271         } catch (Exception ex) {
272             throw new RuntimeException("Unable to get process");
273         }
274 */
275         form.setLightboxScript("closeLightbox('" + dialogId + "');");
276         form.getDialogManager().removeAllDialogs();
277         return getUIFModelAndView(form);
278     }
279 
280     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=clear")
281     public ModelAndView clear(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
282                               HttpServletRequest request, HttpServletResponse response) throws Exception {
283         clearValues(form);
284         return getUIFModelAndView(form);
285     }
286 
287     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=back")
288     public ModelAndView back(@ModelAttribute("KualiForm") CheckInfoForm form, BindingResult result,
289                              HttpServletRequest request, HttpServletResponse response) throws Exception {
290         clearValues(form);
291         return getUIFModelAndView(form, "checkInfoSearch-SearchPage");
292     }
293 
294     private void clearValues(CheckInfoForm form) {
295         form.setName("");
296         form.setTypeKey("");
297         form.setDescr("");
298     }
299 
300     private void resetForm(CheckInfoForm form) {
301         form.setCheckInfoList(new ArrayList<CheckInfo>());
302     }
303 
304     private ContextInfo getContextInfo() {
305         if (null == contextInfo) {
306             //TODO - get real ContextInfo
307             contextInfo = TestHelper.getContext1();
308         }
309         return contextInfo;
310     }
311 
312     protected ProcessService getProcessService(){
313         if(processService == null) {
314             processService = (ProcessService) GlobalResourceLoader.getService(new QName(ProcessServiceConstants.NAMESPACE, ProcessServiceConstants.SERVICE_NAME_LOCAL_PART));
315         }
316         return processService;
317     }
318 
319     private static QueryByCriteria.Builder buildQueryByCriteria(String name, String descr, String type){
320 
321         QueryByCriteria.Builder qBuilder = QueryByCriteria.Builder.create();
322         List<Predicate> pList = new ArrayList<Predicate>();
323         Predicate p;
324 
325         qBuilder.setPredicates();
326         if (StringUtils.isNotBlank(name)){
327             p = like("name", "%" + name + "%");
328             pList.add(p);
329         }
330 
331         if (StringUtils.isNotBlank(type)){
332             p = like("checkType", "%" + type + "%");
333             pList.add(p);
334         }
335 
336         if (StringUtils.isNotBlank(descr)){
337             p = like("descrPlain", "%" + descr + "%");
338             pList.add(p);
339         }
340 
341         if (!pList.isEmpty()){
342             Predicate[] preds = new Predicate[pList.size()];
343             pList.toArray(preds);
344             qBuilder.setPredicates(and(preds));
345         }
346         return qBuilder;
347     }
348 
349     private CheckInfo getSelectedCheckInfo(CheckInfoForm form, String actionLink){
350         String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
351         if (StringUtils.isBlank(selectedCollectionPath)) {
352             throw new RuntimeException("Selected collection was not set for " + actionLink);
353         }
354 
355         int selectedLineIndex = -1;
356         String selectedLine = form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX);
357         if (StringUtils.isNotBlank(selectedLine)) {
358             selectedLineIndex = Integer.parseInt(selectedLine);
359         }
360 
361         if (selectedLineIndex == -1) {
362             throw new RuntimeException("Selected line index was not set");
363         }
364 
365         Collection<CheckInfo> collection = ObjectPropertyUtils.getPropertyValue(form, selectedCollectionPath);
366         CheckInfo checkInfo = ((List<CheckInfo>) collection).get(selectedLineIndex);
367 
368         return checkInfo;
369     }
370 
371 }