View Javadoc

1   package org.kuali.ole.deliver.request.controller;
2   
3   import org.apache.log4j.Logger;
4   import org.kuali.ole.OLEConstants;
5   import org.kuali.ole.deliver.loan.LoanProcessor;
6   import org.kuali.ole.deliver.request.bo.OleDeliverRequestBo;
7   import org.kuali.ole.deliver.request.service.OleDeliverRequestDocumentHelperServiceImpl;
8   import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.Item;
9   import org.kuali.ole.ingest.pojo.MatchBo;
10  import org.kuali.rice.core.api.exception.RiceRuntimeException;
11  import org.kuali.rice.core.api.util.xml.XmlHelper;
12  import org.kuali.rice.kew.rule.xmlrouting.XPathHelper;
13  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
14  import org.kuali.rice.krad.maintenance.MaintenanceUtils;
15  import org.kuali.rice.krad.service.KRADServiceLocator;
16  import org.kuali.rice.krad.util.GlobalVariables;
17  import org.kuali.rice.krad.web.controller.MaintenanceDocumentController;
18  import org.kuali.rice.krad.web.form.DocumentFormBase;
19  import org.kuali.rice.krad.web.form.MaintenanceForm;
20  import org.kuali.rice.krms.api.KrmsApiServiceLocator;
21  import org.kuali.rice.krms.api.engine.*;
22  import org.kuali.rice.krms.impl.repository.AgendaBo;
23  import org.springframework.stereotype.Controller;
24  import org.springframework.validation.BindingResult;
25  import org.springframework.web.bind.annotation.ModelAttribute;
26  import org.springframework.web.bind.annotation.RequestMapping;
27  import org.springframework.web.servlet.ModelAndView;
28  import org.w3c.dom.Document;
29  
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  import javax.xml.xpath.XPath;
33  import javax.xml.xpath.XPathConstants;
34  import java.io.ByteArrayInputStream;
35  import java.sql.*;
36  import java.util.*;
37  import java.util.Date;
38  
39  /**
40   * Created with IntelliJ IDEA.
41   * User: ?
42   * Date: 10/17/12
43   * Time: 1:59 PM
44   * To change this template use File | Settings | File Templates.
45   */
46  @Controller
47  @RequestMapping(value = "/deliverRequestMaintenance")
48  public class OleDeliverRequestMaintenanceDocumentController extends MaintenanceDocumentController {
49      private static final Logger LOG = Logger.getLogger(OleDeliverRequestMaintenanceDocumentController.class);
50      private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
51      private static final String NAME_SELECTOR = "name";
52      private final static String RULE_EVALUATED = "Rule Evaluated";
53      private final static String ROUTED_EXTERNAL = "Routed External";
54      OleDeliverRequestDocumentHelperServiceImpl service = new OleDeliverRequestDocumentHelperServiceImpl();
55      @RequestMapping(params = "methodToCall=" +"maintenanceCancel")
56      public ModelAndView maintenanceCancel(@ModelAttribute("KualiForm") MaintenanceForm form, BindingResult result,
57                                            HttpServletRequest request, HttpServletResponse response) throws Exception {
58          setupMaintenanceForDelete(form, request,"Cancel");
59          return getUIFModelAndView(form);
60      }
61  
62  
63  
64      /**
65       *  This method invokes deleteAttachment method to delete attachment and set the error accordingly ..
66       * @param form
67       * @param result
68       * @param request
69       * @param response
70       * @return ModelAndView
71       * @throws Exception
72       */
73      @RequestMapping(params = "methodToCall=" +"cancelDocument")
74      public ModelAndView cancelDocument(@ModelAttribute("KualiForm") MaintenanceForm form, BindingResult result,
75                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
76          LOG.info("Inside Cancel document");
77          MaintenanceDocument document = form.getDocument();
78          OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo)document.getOldMaintainableObject().getDataObject();
79          service.cancelDocument(oleDeliverRequestBo);
80  
81          return close(form,result,request,response);
82      }
83  
84      /**
85       * This method populates confirmation to delete the document.
86       * @param form
87       * @param request
88       * @param maintenanceAction
89       */
90      protected void setupMaintenanceForDelete(MaintenanceForm form, HttpServletRequest request, String maintenanceAction) {
91          MaintenanceDocument document = form.getDocument();
92          if (document == null) {
93              document = getMaintenanceDocumentService()
94                      .setupNewMaintenanceDocument(form.getDataObjectClassName(), form.getDocTypeName(),
95                              maintenanceAction);
96  
97              form.setDocument(document);
98              form.setDocTypeName(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
99          }
100 
101         form.setMaintenanceAction(maintenanceAction);
102         getMaintenanceDocumentService().setupMaintenanceObject(document, maintenanceAction, request.getParameterMap());
103         MaintenanceUtils.checkForLockingDocument(document, false);
104     }
105 
106     @Override
107     @RequestMapping(params = "methodToCall=route")
108     public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
109                               HttpServletRequest request, HttpServletResponse response) {
110         LOG.info("Inside route document");
111         MaintenanceForm maintenanceForm = (MaintenanceForm) form;
112         MaintenanceDocument maintenanceDocument = (MaintenanceDocument)form.getDocument();
113         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo)maintenanceDocument.getDocumentDataObject();
114         if(oleDeliverRequestBo.getOperatorModifiedId()==null){
115             if(!service.isItemAvailbleInDocstore(oleDeliverRequestBo)){
116                 GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.ITEM_NOT_AVAILABLE_IN_DOCSTORE);
117             }
118 
119             oleDeliverRequestBo = service.processRequestType(oleDeliverRequestBo);
120             if(service.isItemAvailbleInDocstore(oleDeliverRequestBo) &&!oleDeliverRequestBo.getRequestTypeId().equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_7) && !oleDeliverRequestBo.getRequestTypeId().equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_8)) {
121 
122 
123                 if(service.isPatronRecordExpired(oleDeliverRequestBo)){
124                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID,OLEConstants.OleDeliverRequest.PATRON_RECORD_EXPIRE);
125                 }
126 
127                 if(!service.isValidProxyPatron(oleDeliverRequestBo)){
128                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.PROXY_BORROWER_ID,OLEConstants.OleDeliverRequest.INVALID_PROXY);
129                 }
130                 if(!service.validateDeliveryPrivilege(oleDeliverRequestBo)){
131                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.NO_DELIVERY_PRIVILEGE);
132                 }
133                 if(!service.validatePagingPrivilege(oleDeliverRequestBo)) {
134                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.NO_PAGE_PRIVILEGE);
135                 }
136 
137                 if(service.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo) ){
138                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.ALREADY_RAISED);
139                 }
140 
141                 /* if( service.isItemAvailable(oleDeliverRequestBo)){
142                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.ITEM_AVAILABLE);
143                 }*/
144                 if(!service.canRaiseRequest(oleDeliverRequestBo)){
145                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.NO_RECALL_REQUEST);
146                 }
147                 if(!service.isItemEligible(oleDeliverRequestBo)){
148                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.ITEM_NOT_ELIGIBLE);
149                 }
150 
151                 if(service.isAlreadyLoaned(oleDeliverRequestBo)){
152                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.ITEM_ALREADY_LOANED);
153                 }
154 
155             }
156 
157             if(oleDeliverRequestBo.getRequestTypeId().equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_8)){
158                 if(!oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR)){
159                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.TRANSIT_ERROR);
160                 }  else {
161                     LoanProcessor loanProcessor = new LoanProcessor();
162                     try{
163                         Map  docStoreDetails= loanProcessor.getItemDetails(oleDeliverRequestBo.getItemId());
164                         String itemXml = loanProcessor.getItemXML((String) docStoreDetails.get("itemUuid"));
165                         Item oleItem = loanProcessor.getItemPojo(itemXml);
166                         oleItem.setItemStatusEffectiveDate(new Date(System.currentTimeMillis()).toString());
167                           if(oleDeliverRequestBo.getInTransitCheckInNote()!=null && !oleDeliverRequestBo.getInTransitCheckInNote().isEmpty()){
168                               oleItem.setCheckinNote(oleDeliverRequestBo.getInTransitCheckInNote());
169                           }
170                         loanProcessor.updateItemStatus(oleItem,OLEConstants.OleDeliverRequest.INTRANSIT_STATUS);
171                     }
172                     catch (Exception e){
173                         e.printStackTrace();
174                     }
175                     if(!service.isItemAvailable(oleDeliverRequestBo)){
176                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.ITEM_IN_LOAN);
177                     }
178                     if(service.isRequestRaised(oleDeliverRequestBo)){
179                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.TRANSIT_REQUEST_RAISED);
180                     }
181 
182                 }
183             }
184             if(oleDeliverRequestBo.getRequestTypeId().equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_7)){
185                 if(service.isPatronRecordExpired(oleDeliverRequestBo)){
186                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID,OLEConstants.OleDeliverRequest.PATRON_RECORD_EXPIRE);
187                 }
188                 if(service.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo)){
189                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID,OLEConstants.OleDeliverRequest.ALREADY_RAISED);
190                 }
191             }
192             oleDeliverRequestBo = service.processRequester(oleDeliverRequestBo);
193 
194             boolean valid = false;
195             EngineResults engineResult = executeEngineResults(oleDeliverRequestBo);
196             if(engineResult!=null){
197             List<ResultEvent> allResults = engineResult.getAllResults();
198             if(allResults.size()>0){
199             for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
200                 ResultEvent resultEvent = resultEventIterator.next();
201                 if (resultEvent.getType().equals(RULE_EVALUATED)) {
202                     valid |= resultEvent.getResult();
203                 }
204             }
205           }                        }
206             //  oleDeliverRequestBo = service.reOrderQueuePosition(oleDeliverRequestBo);
207         }
208         return super.route(form,result,request,response);
209     }
210 
211 
212 
213     private EngineResults executeEngineResults(OleDeliverRequestBo oleDeliverRequestBo){
214         List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
215         List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
216         List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
217         List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
218         Engine engine =  KrmsApiServiceLocator.getEngine();
219         EngineResults engineResult =null;
220         HashMap<String, Object> agendaValue = new HashMap<String, Object>();
221         agendaValue.put("nm", "Request Validation");
222         List<AgendaBo> agendaBos = (List<AgendaBo>) KRADServiceLocator.getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
223         if(agendaBos!=null && agendaBos.size()>0){
224             AgendaBo agendaBo = agendaBos.get(0);
225             HashMap<String, String> map = new HashMap<String, String>();
226             map.put("AGENDA_NAME", agendaBo.getName());
227             List<MatchBo> matchBos = (List<MatchBo>) KRADServiceLocator.getBusinessObjectService().findMatching(MatchBo.class, map);
228 
229             SelectionCriteria selectionCriteria =
230                     SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()),
231                             getAgendaContext("Request Validation"));
232 
233             ExecutionOptions executionOptions = new ExecutionOptions();
234             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
235 
236             Facts.Builder factBuilder = Facts.Builder.create();
237 
238 
239 
240             String borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeName();
241 
242             String itemType = oleDeliverRequestBo.getItemTypeName();
243 
244             String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
245 
246             String location = oleDeliverRequestBo.getShelvingLocation();
247              String requestType = oleDeliverRequestBo.getRequestTypeCode();
248             String itemId   = oleDeliverRequestBo.getItemId();
249             String borrowerId = oleDeliverRequestBo.getBorrowerId();
250             Map<String,String> requestMap = new HashMap<String,String>();
251             requestMap.put(OLEConstants.OleDeliverRequest.ITEM_ID,itemId);
252             if(requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_1) || requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_2)){
253                 recallList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
254             } else if(requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_3) || requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_4)){
255                 holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
256             } else if(requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_5) || requestTypeId.equals(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID_6)){
257                 pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
258             }
259 
260             Map<String,String> requestByBorrower = new HashMap<String,String>();
261             requestByBorrower.put("borrowerId",borrowerId);
262             requestsByBorrower = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestByBorrower);
263             HashMap<String,Object> termValues = new HashMap<String, Object>() ;
264             termValues.put("borrowerType",borrowerType);
265             termValues.put("itemType",itemType);
266             termValues.put("location",location);
267             termValues.put("requestType",requestType);
268             termValues.put("maxNumberOfRecallRequest",new Integer(recallList.size())+1);
269             termValues.put("maxNumberOfHoldRequest",new Integer(holdList.size())+1);
270             termValues.put("maxNumberOfPageRequest",new Integer(pageList.size())+1);
271             // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
272             termValues.put("requestTypeId",requestTypeId);
273 
274 
275 
276             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
277                 MatchBo matchBo = matchBoIterator.next();
278                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
279             }
280 
281 
282             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
283             List<String>  errorMessage = (List<String>)engineResult.getAttribute("errorAction");
284             java.sql.Date d = (java.sql.Date) engineResult.getAttribute("requestExpirationDate");
285             oleDeliverRequestBo.setRequestExpiryDate(d);
286             StringBuffer failures = new StringBuffer();
287             if(errorMessage!=null && errorMessage.size()>0){
288                 int i=1;
289                 for(String errMsg : errorMessage){
290                     failures.append(i+++". "+errMsg+"<br/>");
291                 }
292             }
293             if(!failures.toString().isEmpty()){
294                 GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID,OLEConstants.OleDeliverRequest.MAX_REQUEST_REACHED);
295 
296             }
297 
298         }
299         return engineResult;
300     }
301 
302     /**
303      * This method returns ElementValue using docContent and xpathExpression..
304      * @param docContent
305      * @param xpathExpression
306      * @return value
307      */
308     private String getElementValue(String docContent, String xpathExpression) {
309         try {
310             Document document = XmlHelper.trimXml(new ByteArrayInputStream(docContent.getBytes()));
311 
312             XPath xpath = XPathHelper.newXPath();
313             String value = (String)xpath.evaluate(xpathExpression, document, XPathConstants.STRING);
314 
315             return value;
316 
317         } catch (Exception e) {
318             throw new RiceRuntimeException();
319         }
320     }
321 
322     /**
323      *  This method returns SelectionContext using contextName.
324      * @param contextName
325      * @return Map
326      */
327     protected Map<String, String> getSelectionContext(String contextName) {
328         Map<String, String> selector = new HashMap<String, String>();
329         selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
330         selector.put(NAME_SELECTOR, contextName);
331         return selector;
332     }
333 
334     /**
335      *  This method returns AgendaContext using agendaName..
336      * @param agendaName
337      * @return Map
338      */
339     protected Map<String, String> getAgendaContext(String agendaName) {
340         Map<String, String> selector = new HashMap<String, String>();
341         selector.put(NAME_SELECTOR, agendaName);
342         return selector;
343     }
344 }
345 
346